text
stringlengths
184
4.48M
#pragma once #include <iostream> #include <cstdlib> #include <opencv2/opencv.hpp> #include <cmath> #include <omp.h> #include "../Common/Macros.hpp" #ifndef _HELPER_TIMER_H_ #define _HELPER_TIMER_H_ #include "../Common/helper_timer.h" #endif #include "ImageUtils.hpp" class OtsuThresholdCPU { private: StopWatchInterface *cpuTimer = nullptr; /// @brief Generate Histogram From Input Image - Single-threaded /// @param inputImage cv::Mat Pointer to input image /// @param imageUtils Instance of ImageUtils Class /// @param pixelCount Total Pixels in image /// @param cpuTime [OUT] CPU Execution Time For Computing Histogram /// @return STL Vector containing histogram values std::vector<double> computeHistogramST(cv::Mat* inputImage, ImageUtils *imageUtils, size_t* pixelCount, double *cpuTime); /// @brief Generate Histogram From Input Image - Multi-threaded /// @param inputImage cv::Mat Pointer to input image /// @param imageUtils Instance of ImageUtils Class /// @param pixelCount Total Pixels in image /// @param cpuTime [OUT] CPU Execution Time For Computing Histogram /// @param threadCount Thread Count calculated automatically as per CPU, if multiThreading = true /// @return STL Vector containing histogram values std::vector<double> computeHistogramMT(cv::Mat* inputImage, ImageUtils *imageUtils, size_t* pixelCount, double *cpuTime, int threadCount); /// @brief Get Threshold From Input Image - Multi-threaded /// @param inputImage cv::Mat Pointer to input image /// @param imageUtils Instance of ImageUtils Class /// @param cpuTime [OUT] CPU Execution Time For Computing Threshold /// @return Integer threshold value for the image int computeThresholdST(cv::Mat* inputImage, ImageUtils *imageUtils, double *cpuTime); /// @brief Get Threshold From Input Image - Single-threaded /// @param inputImage cv::Mat Pointer to input image /// @param imageUtils Instance of ImageUtils Class /// @param cpuTime [OUT] CPU Execution Time For Computing Threshold /// @param threadCount Thread Count calculated automatically as per CPU, if multiThreading = true /// @return Integer threshold value for the image int computeThresholdMT(cv::Mat* inputImage, ImageUtils *imageUtils, double *cpuTime, int threadCount); public: OtsuThresholdCPU(void); ~OtsuThresholdCPU(); /// @brief Get Threshold From Input Image /// @param inputImage cv::Mat Pointer to input image /// @param imageUtils Instance of ImageUtils Class /// @param multiThreading Single Threaded (false) or MultiThreaded (true) /// @param threadCount Thread Count calculated automatically as per CPU, if multiThreading = true /// @param cpuTime [OUT] CPU Execution Time For Computing Threshold /// @return Integer threshold value for the image int getImageThreshold(cv::Mat* inputImage, ImageUtils *imageUtils, bool multiThreading, int threadCount, double *cpuTime); };
// The MIT License (MIT) // // Copyright (c) 2020 Markus Raufer // // All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. namespace Foundation.Collections.Generic; using Foundation; using System; using System.Data; using System.Diagnostics.CodeAnalysis; public static class EnumerableExtensions { /// <summary> /// Aggregates elements like standard LINQ. /// The first element is taken as seed and can be transformed. /// </summary> /// <typeparam name="T">Type of the elements</typeparam> /// <typeparam name="TAccumulate">The transformation format</typeparam> /// <param name="items">Elements</param> /// <param name="seed">A functor transforms the first element in the list.</param> /// <param name="func">The aggregation function.</param> /// <returns></returns> public static Option<TAccumulate> Aggregate<T, TAccumulate>( this IEnumerable<T> items, Func<T, TAccumulate> seed, Func<TAccumulate, T, TAccumulate> func) { seed.ThrowIfNull(); func.ThrowIfNull(); TAccumulate? acc = default; foreach (var item in items.OnFirst(x => acc = seed(x)) .Skip(1)) { acc = func(acc!, item); } return Option.Maybe(acc); } /// <summary> /// checks if all items are equal. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TSelector"></typeparam> /// <param name="items"></param> /// <returns></returns> public static bool AllEqual<T>(this IEnumerable<T> items) { return AllEqual(items, x => x); } /// <summary> /// checks if all values of the predicate are equal. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TSelector"></typeparam> /// <param name="items"></param> /// <param name="selector"></param> /// <returns></returns> public static bool AllEqual<T, TSelector>(this IEnumerable<T> items, Func<T, TSelector> selector) { selector.ThrowIfNull(); var it = items.ThrowIfEnumerableIsNull().GetEnumerator(); if (!it.MoveNext()) return true; var first = selector(it.Current); while (it.MoveNext()) { if (!EqualityComparer<TSelector>.Default.Equals(selector(it.Current), first)) return false; } return true; } /// <summary> /// checks if all elements of items are equal. /// </summary> /// <typeparam name="T">Type of the elements.</typeparam> /// <typeparam name="TSelector">Type of selected value.</typeparam> /// <param name="items">Elements.</param> /// <param name="selector">selection function.</param> /// <param name="equals">Function to check equality.</param> /// <returns></returns> public static bool AllEqual<T, TSelector>(this IEnumerable<T> items, Func<T, TSelector> selector, Func<TSelector, TSelector, bool> equals) { selector.ThrowIfNull(); equals.ThrowIfNull(); var it = items.ThrowIfEnumerableIsNull().GetEnumerator(); if (!it.MoveNext()) return true; var first = selector(it.Current); while (it.MoveNext()) { if (!equals(selector(it.Current), first)) return false; } return true; } /// <summary> /// Checks if the selected values of the items are of the same type. /// </summary> /// <typeparam name="T">Type of the item.</typeparam> /// <typeparam name="TSelector">Type of the selected value of the item.</typeparam> /// <param name="items">List of items.</param> /// <param name="selector"></param> /// <returns></returns> public static bool AllOfSameType<T, TSelector>(this IEnumerable<T> items, Func<T, TSelector> selector) { selector.ThrowIfNull(); Type? first = null; foreach (var item in items.OnFirst(x => first = x?.GetType()) .Skip(1)) { if (!first.EqualsNullable(item?.GetType())) return false; } return true; } /// <summary> /// Returns the median of all values returned by the converter. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="converter"></param> /// <returns></returns> public static decimal AverageMedian<T>(this IEnumerable<T> items, Func<T, decimal>? converter = null) { var (opt1, opt2) = AverageMedianValues(items); if (opt1.IsNone) return 0; var value1 = (null == converter) ? Convert.ToDecimal(opt1.OrThrow()) : converter(opt1.OrThrow()); if (opt2.IsNone) return value1; var value2 = (null == converter) ? Convert.ToDecimal(opt2.OrThrow()) : converter(opt2.OrThrow()); return (value1 + value2) / 2M; } /// <summary> /// Returns the real values instead of a division of the median values. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <returns></returns> public static (Option<T> value1, Option<T> value2) AverageMedianValues<T>(this IEnumerable<T> items) { var sorted = items.OrderBy(x => x); var count = sorted.Count(); int halfIndex = count / 2; return (count % 2 == 0) ? (Option.Some(sorted.ElementAt(halfIndex - 1)), Option.Some(sorted.ElementAt(halfIndex))) : (Option.Some(sorted.ElementAt(halfIndex)), Option.None<T>()); } /// <summary> /// Creates a cartesian product from the lists lhs and rhs. /// </summary> /// <typeparam name="T">Type of the list.</typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns></returns> public static IEnumerable<TResult> CartesianProduct<T, TResult>( this IEnumerable<T> lhs, IEnumerable<T> rhs, Func<T, T, TResult> selector) { return from l in lhs from r in rhs select selector(l, r); } /// <summary> /// Checks if lhs contains at least one element of rhs. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns></returns> public static bool Contains<T>(this IEnumerable<T> lhs, IEnumerable<T> rhs) { var search = new HashSet<T>(rhs); return search.Overlaps(lhs); } /// <summary> /// compares to lists of integers. /// </summary> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns></returns> public static int CompareTo(this IEnumerable<int> lhs, IEnumerable<int> rhs) { var lhsArray = lhs.ToArray(); var rhsArray = rhs.ToArray(); Array.Sort(lhsArray); Array.Sort(rhsArray); var i = 0; var j = 0; for(; i < lhsArray.Length && j < rhsArray.Length; i++, j++) { var cmp = lhsArray[i].CompareTo(rhsArray[j]); if (0 != cmp) return cmp; } return i.CompareTo(j); } /// <summary> /// Correlates to lists by a predicate. /// </summary> /// <typeparam name="T">Type of the items</typeparam> /// <typeparam name="TKey">Type of the predicate value.</typeparam> /// <param name="lhs">Left list.</param> /// <param name="rhs">Right list.</param> /// <param name="selector">Selector funciton.</param> /// <returns>List of correlating items</returns> public static IEnumerable<T> Correlate<T, TKey>(this IEnumerable<T> lhs, IEnumerable<T> rhs, Func<T, TKey> selector) { foreach (var (x, y) in lhs.Join(rhs, selector, selector, (x, y) => (x, y))) { yield return x; yield return y; } } /// <summary> /// Creates an endless list of items. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <returns></returns> public static IEnumerable<T> Cycle<T>(this IEnumerable<T> items) { return new CyclicEnumerable<T>(items); } /// <summary> /// Removes all duplicates from a list. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="comparer">a compare function to compare the items.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public static IEnumerable<T> DistinctBy<T>(this IEnumerable<T> items, Func<T?, T?, bool> comparer) { comparer.ThrowIfNull(); return DistinctBy(items, comparer, null); } #if NETSTANDARD2_0 public static IEnumerable<T> DistinctBy<T, TKey> (this IEnumerable<T> source, Func<T, TKey> keySelector) { return new HashSet<T>(source, new LambdaEqualityComparer<T, TKey>(keySelector)); } #endif /// <summary> /// Removes all duplicates from a list. With an additional hash function you can change the sorting order. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="comparer"></param> /// <param name="hashFunc">The hash function for each single left. Example: you want all null items at the end of the list. Default: null is -1.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public static IEnumerable<T> DistinctBy<T>( this IEnumerable<T> items, Func<T?, T?, bool> comparer, Func<T?, int>? hashFunc = null) { comparer.ThrowIfNull(); var eqComparer = hashFunc is null ? new LambdaEqualityComparer<T>(comparer) : new LambdaEqualityComparer<T>(comparer, hashFunc); return items.Distinct(eqComparer); } /// <summary> /// This DistinctMembers preserves the ordinal position. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <returns></returns> public static IEnumerable<T> DistinctPreserveOrdinalPosition<T>(this IEnumerable<T> items) { return items.Enumerate() .DistinctBy(tuple => tuple.item) .OrderBy(tuple => tuple.counter) .Select(tuple => tuple.item); } /// <summary> /// Returns doublets of a list. If there are e.g. three of an left, 2 will returned. /// </summary> /// <typeparam name="T">type of elements</typeparam> /// <param name="items">list of elements</param> /// <returns>all doublets</returns> /// <exception cref="ArgumentNullException"></exception> public static IEnumerable<T> Duplicates<T>(this IEnumerable<T> items) { if (null == items) throw new ArgumentNullException(nameof(items)); var set = new HashSet<T>(); foreach (var item in items) { if (!set.Add(item)) yield return item; } } /// <summary> /// returns doublets of a list. If there are e.g. three of an left, 2 will returned. /// </summary> /// <typeparam name="T">type of elements</typeparam> /// <typeparam name="TSelector">type of predicate value</typeparam> /// <param name="items">list of elements</param> /// <param name="selector">predicate delegate</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public static IEnumerable<T> Duplicates<T, TSelector>( this IEnumerable<T> items, Func<T, TSelector> selector) { if (null == items) throw new ArgumentNullException(nameof(items)); var set = new HashSet<TSelector>(); foreach (var item in items) { if (!set.Add(selector(item))) yield return item; } } /// <summary> /// returns doublets of a list. If there are e.g. three of an left, 2 will returned. /// </summary> /// <typeparam name="T">Item type</typeparam> /// <param name="items">list of items</param> /// <param name="comparer">comparer used for equality</param> /// <returns>all doublets</returns> /// <exception cref="ArgumentNullException"></exception> public static IEnumerable<T> Duplicates<T>(this IEnumerable<T> items, IEqualityComparer<T> comparer) { var set = new HashSet<T>(comparer.ThrowIfNull()); foreach (var item in items.ThrowIfEnumerableIsNull()) { if (!set.Add(item)) yield return item; } } /// <summary> /// Enumerates items starting from seed. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="seed"></param> /// <param name="increment">If true, the counter is incremented otherwise it is decremented.</param> /// <returns>Returns tuples (left, index).</returns> //public static IEnumerable<(int counter, T item)> Enumerate<T>(this IEnumerable<T> items, int seed = 0, bool increment = true) //{ // var i = seed; // Func<int> nextCounter = increment ? () => i++ : () => i--; // return Enumerate(items, (item) => nextCounter()); //} public static IEnumerable<(int counter, T item)> Enumerate<T>(this IEnumerable<T> items, int seed = 0, int increment = 1) { var i = seed; int nextCounter() => i += increment; var it = items.GetEnumerator(); if (!it.MoveNext()) yield break; yield return (i, it.Current); while (it.MoveNext()) { yield return (nextCounter(), it.Current); } } /// <summary> /// Enumerates items. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TCounter">Type of the counter value.</typeparam> /// <param name="items">List of elements.</param> /// <param name="createValue">This is the function which increments or decrements the counter. If you use increment(++) or decremenet(--) use it as pre instead of post function.</param> /// <returns>A list of tuples (counter, item).</returns> public static IEnumerable<(TCounter counter, T item)> Enumerate<T, TCounter>(this IEnumerable<T> items, Func<T, TCounter> createValue) { createValue.ThrowIfNull(); foreach (var item in items) yield return (createValue(item), item); } /// <summary> /// /// </summary> /// <typeparam name="T">Type of the items.</typeparam> /// <typeparam name="TCounter">Type of the counters value.</typeparam> /// <param name="items">List of items.</param> /// <param name="seed">Start value of the counter.</param> /// <param name="max">Max value of the counter.</param> /// <param name="nextCounterValue">This is the function which increments or decrements the counter. If you use increment(++) or decremenet(--) use it as pre instead of post function.</param> /// <returns>A list of tuples (counter, item).</returns> public static IEnumerable<(TCounter counter, T item)> Enumerate<T, TCounter>( this IEnumerable<T> items, TCounter seed, TCounter max, Func<TCounter, TCounter> nextCounterValue) where TCounter : notnull { nextCounterValue.ThrowIfNull(); var counter = seed; foreach (var item in items) { yield return (counter, item); if (counter.Equals(max)) { counter = seed; } else { counter = nextCounterValue(counter); } } } /// <summary> /// Enumerates items. Starting from min until max. If the index reaches max it starts again from seed. /// This allows also negative values. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="minMax">Allows also negative numbers.</param> /// <returns></returns> public static IEnumerable<(int counter, T item)> EnumerateRange<T>(this IEnumerable<T> items, int min, int max) { var i = min; foreach (var item in items) { if (i > max) i = min; yield return (i, item); i++; } } /// <summary> /// Enumerates items. Starting from Min until Max. If the index reaches Max it starts again from Min. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="minMax"></param> /// <returns></returns> public static IEnumerable<(int counter, T item)> EnumerateRange<T>(this IEnumerable<T> items, System.Range range) { if (range.End.IsFromEnd) throw new ArgumentException($"{range.End}.IsFromEnd is not allowed"); var i = range.Start.IsFromEnd ? 0 : range.Start.Value; foreach (var item in items) { if (!range.End.IsFromEnd && range.End.Value < i) i = range.Start.Value; yield return (i, item); i++; } } /// <summary> /// Enumerates items. Creates tuples with two different counters and the item. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TValue1"></typeparam> /// <typeparam name="TValue2"></typeparam> /// <param name="items"></param> /// <param name="createValue1"></param> /// <param name="createValue2"></param> /// <returns></returns> public static IEnumerable<(TValue1, TValue2, T)> Enumerate<T, TValue1, TValue2>( this IEnumerable<T> items, Func<T, TValue1> createValue1, Func<T, TValue2> createValue2) { foreach (var item in items) yield return (createValue1(item), createValue2(item), item); } /// <summary> /// Returns true, if all elements of lhs appear in rhs and the number of items and their occurrency are same. /// Positions can be different. /// </summary> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <typeparam name="T"></typeparam> public static bool EqualsCollection<T>(this IEnumerable<T> lhs, IEnumerable<T> rhs) { if (null == lhs) return null == rhs; if (null == rhs) return false; return !lhs.SymmetricDifference(rhs, preserveDuplicates: true).Any(); } /// <summary> /// Returns true when both sides lhs and rhs are equal. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <param name="equal">The selector of the comparison.</param> /// <returns></returns> public static bool EqualsCollection<T, TKey>(this IEnumerable<T> lhs, IEnumerable<T> rhs, Func<T, TKey?> selector) { if (null == lhs) return null == rhs; if (null == rhs) return false; return !lhs.SymmetricDifference(rhs, selector, preserveDuplicates: true).Any(); } /// <summary> /// Returns all lhs elements which are not in rhs. The comparison is made between the TKey values. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <param name="keySelector"></param> /// <param name="resultSelector"></param> /// <returns></returns> public static IEnumerable<TResult> ExceptBy<T, TKey, TResult>( this IEnumerable<T> lhs, IEnumerable<T> rhs, Func<T, TKey?> keySelector, Func<T?, TResult> resultSelector) { rhs.ThrowIfEnumerableIsNull(); keySelector.ThrowIfNull(); resultSelector.ThrowIfNull(); return lhs.Except(rhs, new LambdaEqualityComparer<T>((T? a, T? b) => { if (null == a) return null == b; if (null == b) return false; var selectedA = keySelector(a); var selectedB = keySelector(b); if (null == selectedA) return null == selectedB; if (null == selectedB) return false; return selectedA.Equals(selectedB); })).Select(resultSelector); } /// <summary> /// Returns all elements of first which are not in second. /// </summary> /// <typeparam name="T1">Type of elements of first.</typeparam> /// <typeparam name="T2">Type of elements of second.</typeparam> /// <typeparam name="TKey">Type of the compare value.</typeparam> /// <typeparam name="TResult">Value which will be returned of the first list.</typeparam> /// <param name="lhs">First list.</param> /// <param name="rhs">Second list.</param> /// <param name="lhsKeySelector">Compare value of the elements of the first list. Must be of type TKey.</param> /// <param name="rhsKeySelector">Compare value of the elements of the second list. Must be of type TKey.</param> /// <param name="resultSelector">Rückgabe-Wert. Hier kann auch ein neuer Typ erzeugt werden.</param> /// <returns></returns> public static IEnumerable<TResult> ExceptBy<T1, T2, TKey, TResult>( this IEnumerable<T1> lhs, IEnumerable<T2> rhs, Func<T1, TKey?> lhsKeySelector, Func<T2, TKey?> rhsKeySelector, Func<T1, TResult> resultSelector) { rhs.ThrowIfEnumerableIsNull(); lhsKeySelector.ThrowIfNull(); rhsKeySelector.ThrowIfNull(); resultSelector.ThrowIfNull(); var hashedRhs = new HashSet<TKey>(rhs.Select(rhsKeySelector).NotNull()); foreach (var l in lhs) { var lhsSelected = lhsKeySelector(l); if (lhsSelected is null) continue; if (!hashedRhs.Contains(lhsSelected)) yield return resultSelector(l); } } /// <summary> /// Returns all elements from <paramref name="lhs"/> which are not in <paramref name="rhs"/> including duplicates. /// If T implements <see cref="=IComparable<typeparamref name="T"/>"/> use <see cref="=ExceptOrderedWithDuplicates"/>, because it is more efficient. /// The smaller list should be rhs. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns></returns> public static IEnumerable<T> ExceptWithDuplicates<T>(this IEnumerable<T> lhs, IEnumerable<T> rhs) { var right = new Dictionary<NullableKey<T>, (int l, int r)>(); foreach (var r in rhs) { var key = NullableKey.New(r); if (right.TryGetValue(key, out var tuple)) { tuple.r++; right[key] = tuple; continue; } right[key] = (0, 1); } foreach (var left in lhs) { var key = NullableKey.New(left); if (right.TryGetValue(key, out var tuple)) { tuple.l++; right[key] = tuple; if (tuple.l <= tuple.r) continue; } yield return left; } } /// <summary> /// Returns all elements from <paramref name="lhs"/> which are not in <paramref name="rhs"/> including duplicates. /// The smaller list should be rhs. /// </summary> /// <typeparam name="T">The type of the elements.</typeparam> /// <typeparam name="TKey">The type of the predicate value which is used for comparison.</typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <param name="selector"></param> /// <returns></returns> public static IEnumerable<T> ExceptWithDuplicates<T, TKey>( this IEnumerable<T> lhs, IEnumerable<T> rhs, Func<T, TKey?> selector) { TKey? nullableSelector(NullableKey<T> x) => null == x.Value ? default : selector(x.Value); var right = new Dictionary<NullableKey<T>, (int l, int r)>(new LambdaEqualityComparer<NullableKey<T>, TKey>(nullableSelector)); foreach (var r in rhs) { var key = NullableKey.New(r); if (right.TryGetValue(key, out var tuple)) { tuple.r++; right[key] = tuple; continue; } right[key] = (0, 1); } foreach (var left in lhs) { var key = NullableKey.New(left); if (right.TryGetValue(key, out var tuple)) { tuple.l++; right[key] = tuple; if (tuple.l <= tuple.r) continue; } yield return left; } } /// <summary> /// Returns all elements from <paramref name="lhs"/> which are not in <paramref name="rhs"/> including duplicates. /// First lhs and rhs are sorted and then a <see cref="=Array.BinarySearch"/> is made. /// The smaller list should be rhs. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns></returns> public static IEnumerable<T> ExceptWithDuplicatesSorted<T>(this IEnumerable<T> lhs, IEnumerable<T> rhs) where T : IComparable<T> { var lhsArray = lhs.ToArray(); var rhsArray = rhs.ToArray(); Array.Sort(lhsArray); Array.Sort(rhsArray); var rhsMaxIndex = rhsArray.Length - 1; var rhsIndex = 0; for(var i = 0; i < lhsArray.Length; i++) { var left = lhsArray[i]; if(rhsIndex > rhsMaxIndex) { yield return left; continue; } var right = rhsArray[rhsIndex]; var compare = left.CompareTo(right); if(-1 == compare) { yield return left; continue; } if(0 == compare) { rhsIndex++; continue; } do { rhsIndex++; if (rhsIndex > rhsMaxIndex) break; right = rhsArray[rhsIndex]; compare = left.CompareTo(right); if (0 == compare) rhsIndex++; } while (1 > compare); } } /// <summary> /// Filters and transform items. It returns only Option.Some values. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <param name="selector"></param> /// <returns></returns> public static IEnumerable<TResult> FilterMap<T, TResult>( this IEnumerable<T> items, Func<T, Option<TResult>> selector) { selector.ThrowIfNull(); foreach (var item in items) { var optional = selector(item); #if NETSTANDARD2_0 if (optional.TryGet(out TResult? value)) yield return value; #else if (optional.TryGet(out TResult? value)) yield return value; #endif } } /// <summary> /// Filters and transform items. It returns only Option.Some values. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <param name="selector"></param> /// <returns></returns> public static IEnumerable<TResult> FilterMap<T, TResult>( this IEnumerable<T> items, Func<T, bool> predicate, Func<T, TResult> selector) { selector.ThrowIfNull(); foreach (var item in items) { if (predicate(item)) yield return selector(item); } } /// <summary> /// Returns first left as Option. If the list is empty None is returned. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <returns></returns> public static Option<T> FirstAsOption<T>(this IEnumerable<T> items) { var it = items.GetEnumerator(); if (!it.MoveNext()) return Option.None<T>(); return Option.Maybe(it.Current); } /// <summary> /// Returns first element if exists and is of type TResult Some(TResult) is return otherwise None. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <returns></returns> public static Option<TResult> FirstAsOption<T, TResult>(this IEnumerable<T> items, Func<T, TResult> selector) { var it = items.GetEnumerator(); if (!it.MoveNext()) return Option.None<TResult>(); return Option.Maybe(selector(it.Current)); } /// <summary> /// Returns the first element that matches the predicate or None. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static Option<T> FirstAsOption<T>(this IEnumerable<T> items, Func<T, bool> predicate) { return items.FirstAsOption(predicate, x => x); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <param name="onSome"></param> /// <returns></returns> public static Option<TResult> FirstAsOption<T, TResult>( this IEnumerable<T> items, Func<T, bool> predicate, Func<T, TResult> onSome) { if (null == items) return Option.None<TResult>(); predicate.ThrowIfNull(); onSome.ThrowIfNull(); foreach (var item in items.Where(predicate)) return Option.Some(onSome(item)); return Option.None<TResult>(); } /// <summary> /// Returns the first left that matches the predicate or None. /// </summary> /// <typeparam name="TOk"></typeparam> /// <typeparam name="TError"></typeparam> /// <param name="items">a list of results.</param> /// <param name="predicate"></param> /// <returns></returns> public static Option<TOk> FirstOk<TOk, TError>( this IEnumerable<Result<TOk, TError>> items, Func<TOk, bool> predicate) { predicate.ThrowIfNull(); return items.SelectOk().FirstAsOption(predicate); } /// <summary> /// Returns the first occurrence of TResult. If the sequence does not contain the type TResult it throws an exception. /// </summary> /// <typeparam name="T">Type of the elements of the list.</typeparam> /// <typeparam name="TResult">Type of the returned element.</typeparam> /// <param name="items">List of elements.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> [return: NotNull] public static TResult FirstOfType<T, TResult>(this IEnumerable<T> items) { var first = items.ThrowIfNull().OfType<TResult>().First(); return first ?? throw new ArgumentNullException($"sequence does not contain an element of type {typeof(TResult).Name}"); } /// <summary> /// Returns the first occurrence of T. If the sequence does not contain the type T it throws an exception. /// </summary> /// <typeparam name="T">Type of element searched for.</typeparam> /// <param name="items">List of elements.</param> /// <returns></returns> [return: NotNull] public static T FirstOf<T>(this IEnumerable<object> items) => items.FirstOfType<object, T>(); /// <summary> /// Returns the first occurrence of type TResult otherwise null. /// </summary> /// <typeparam name="T">Type of the elements of the list.</typeparam> /// <typeparam name="TResult">Type of the returned element.</typeparam> /// <param name="items">List of elements.</param> /// <returns></returns> public static TResult? FirstOrDefaultOfType<T, TResult>(this IEnumerable<T> items) => items.ThrowIfNull().OfType<TResult>().FirstOrDefault(); /// <summary> /// Returns the first occurrence of type T otherwise null. /// </summary> /// <typeparam name="T">Type of the returned element.</typeparam> /// <param name="items">List of elements.</param> /// <returns></returns> public static T? FirstOrDefaultOfType<T>(this IEnumerable<object> items) => items.ThrowIfNull().OfType<T>().FirstOrDefault(); /// <summary> /// Returns the first element of a specific type if exists. /// </summary> /// <typeparam name="T">Type of element.</typeparam> /// <param name="items">List of elements.</param> /// <returns>Returns an Option. If found the Option.IsSome is true.</returns> public static Option<T> FirstOfTypeAsOption<T>(this IEnumerable<T> items) => items.OfType().FirstAsOption(); /// <summary> /// Executes action for every left. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="action"></param> /// <returns>The number of executed actions.</returns> public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) { action.ThrowIfNull(); foreach (var item in source) { action(item); } } /// <summary> /// Calls <paramref name="action"/> for every left. If the list is empty <paramref name="emptyAction"/> is called. /// </summary> /// <typeparam name="T">Type of the left.</typeparam> /// <param name="source"></param> /// <param name="action">Will be executed for every left.</param> /// <param name="emptyAction">Will be executed if source is empty.</param> /// <returns>The number of executed actions.</returns> public static void ForEach<T>( this IEnumerable<T> source, Action<T> action, Action emptyAction) { action.ThrowIfNull(); emptyAction.ThrowIfNull(); var it = source.GetEnumerator(); if(!it.MoveNext()) { emptyAction(); return; } var item = it.Current; action(item); while(it.MoveNext()) { item = it.Current; action(item); } } public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey?, TKey?, bool> predicate) { return source.GroupBy(keySelector.ThrowIfNull(), new LambdaEqualityComparer<TKey>(predicate.ThrowIfNull())); } /// <summary> /// Returns items if the list has at least numberOfElements. /// </summary> /// <typeparam name="T">Type of list elements.</typeparam> /// <param name="items">List of items.</param> /// <param name="numberOfElements">The number of elements</param> /// <param name="action">action which is called if numberOfElements is reached.</param> /// <returns></returns> public static bool HasAtLeast<T>(this IEnumerable<T> items, int numberOfElements) { if (0 > numberOfElements) return false; int counter = 0; var it = items.ThrowIfEnumerableIsNull().GetEnumerator(); while(it.MoveNext()) { counter++; if (counter >= numberOfElements) break; } return counter >= numberOfElements; } /// <summary> /// Returns a list of indices of found items. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="item"></param> /// <returns></returns> public static IEnumerable<int> IndicesOf<T>(this IEnumerable<T> items, T? item) { bool equals(T? x) { if (item is null) return x is null; if (x is null) return false; return item.Equals(x); } var i = 0; foreach (var itm in items) { if (equals(itm)) yield return i; i++; } } /// <summary> /// Returns a list of indices of found items. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate">If true the index of the left will be returned.</param> /// <returns></returns> public static IEnumerable<int> IndicesOf<T>(this IEnumerable<T> items, Func<T, bool> predicate) { predicate.ThrowIfNull(); var i = 0; foreach (var item in items) { if (predicate(item)) yield return i; i++; } } /// <summary> /// Returns the index of the first found left. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="item"></param> /// <returns></returns> public static int IndexOf<T>(this IEnumerable<T> items, T? item) { bool equals(T? x) { if (item is null) return x is null; if (x is null) return false; return item.Equals(x); } var index = 0; foreach (var itm in items) { if (equals(itm)) return index; index++; } return -1; } /// <summary> /// Returns the index of the first left found with a specific predicate. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static int IndexOf<T>(this IEnumerable<T> items, Func<T, bool> predicate) { predicate.ThrowIfNull(); var i = 0; foreach (var item in items) { if (predicate(item)) return i; i++; } return -1; } /// <summary> /// Returns the index of the first left found after start with a specific predicate. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="start"></param> /// <param name="predicate"></param> /// <returns></returns> public static int IndexOf<T>(this IEnumerable<T> items, int start, Func<T, bool> predicate) { predicate.ThrowIfNull(); var i = start; foreach (var item in items.Skip(start)) { if (predicate(item)) return i; i++; } return -1; } /// <summary> /// returns a list of tuples including the left and its ordinal index. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static IEnumerable<(T item, int index)> IndexTuplesOf<T>( this IEnumerable<T> items, Func<T, bool> predicate) { predicate.ThrowIfNull(); var i = 0; foreach (var elem in items) { if (predicate(elem)) yield return (item: elem, index: i); i++; } } /// <summary> /// The ignored left does not appear in the result. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="ignoredItem">The left which is filtered.</param> /// <returns></returns> public static IEnumerable<T> Ignore<T>(this IEnumerable<T> items, T ignoredItem) { foreach (var item in items.ThrowIfEnumerableIsNull()) { if (item.EqualsNullable(ignoredItem)) continue; yield return item; } } #if NET6_0_OR_GREATER /// <summary> /// Only items withing the range are returned. If the position is greater than the range end it stops. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="range"></param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public static IEnumerable<T> Ignore<T>(this IEnumerable<T> items, System.Range range) { if (range.Start.Value < 0) throw new ArgumentOutOfRangeException(nameof(range)); int i = 0; foreach (var item in items.ThrowIfEnumerableIsNull()) { if(range.Start.Value >= i && range.End.Value <= i) yield return item; if (range.End.Value < i) yield break; i++; } } #endif /// <summary> /// Items for which the predicate applies are not returned. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static IEnumerable<T> Ignore<T>(this IEnumerable<T> items, Func<T, bool> predicate) { predicate.ThrowIfNull(); foreach (var item in items) { if (predicate(item)) continue; yield return item; } } /// <summary> /// Items for which the predicate applies are not returned. /// </summary> /// <typeparam name="T">Type of elements.</typeparam> /// <param name="items"></param> /// <param name="predicate">Element is ignored when predicate returns true.</param> /// <param name="action">Is called when predicate returns true.</param> /// <returns></returns> public static IEnumerable<T> Ignore<T>(this IEnumerable<T> items, Func<T, bool> predicate, Action<T> action) { predicate.ThrowIfNull(); foreach (var item in items) { if (predicate(item)) { action(item); continue; } yield return item; } } /// <summary> /// Items at indicies are not returned. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="indices">Elements at indices are not returned.</param> /// <returns></returns> public static IEnumerable<T> Ignore<T>(this IEnumerable<T> items, params int[] indices) { if (0 == indices.Length) yield break; var i = 0; foreach (var item in items) { if (!indices.Contains(i)) yield return item; i++; } } /// <summary> /// inserts an left before the equal left. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="item"></param> /// <param name="predicate"></param> /// <returns></returns> public static IEnumerable<T> Insert<T>(this IEnumerable<T> items, T item, Func<T, bool> predicate) { predicate.ThrowIfNull(); var inserted = false; foreach (var i in items.ThrowIfEnumerableIsNull()) { if (!inserted && predicate(i)) { yield return item; inserted = true; } yield return i; } if (!inserted) yield return item; } /// <summary> /// inserts an left before the equal left. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="item"></param> /// <param name="comparer"></param> /// <returns></returns> public static IEnumerable<T> Insert<T>( this IEnumerable<T> items, T item, IComparer<T> comparer) { comparer.ThrowIfNull(); var inserted = false; foreach (var i in items.ThrowIfEnumerableIsNull()) { if (!inserted && comparer.Compare(item, i) < 1) { yield return item; inserted = true; } yield return i; } if (!inserted) yield return item; } /// <summary> /// Inserts an element at a specific index. /// If the index is 0 and the list is empty, the item will be inserted. /// If the index is greater than the last elements index the item will not be inserted. /// </summary> /// <typeparam name="T">Type of items.</typeparam> /// <param name="items">List of elements.</param> /// <param name="item">Element to be added.</param> /// <param name="index">Position where to insert the item.</param> /// <returns></returns> public static IEnumerable<T> InsertAt<T>(this IEnumerable<T> items, T item, long index) { var i = 0L; foreach (var elem in items.ThrowIfEnumerableIsNull()) { if (i == index) yield return item; i++; yield return elem; } if (0 == i && 0 == index) yield return item; } /// <summary> /// Intersects a list of collections. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collections"></param> /// <returns>Only items that are in all collections.</returns> public static IEnumerable<T> Intersect<T>(this IEnumerable<IEnumerable<T>> collections) { var itCollections = collections.GetEnumerator(); if (!itCollections.MoveNext()) yield break; var intersected = itCollections.Current; while (itCollections.MoveNext()) { intersected = intersected.Intersect(itCollections.Current); if (!intersected.Any()) break; } foreach (var item in intersected) { yield return item; } } /// <summary> /// Intersects all collections. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collections"></param> /// <param name="compare"></param> /// <returns></returns> public static IEnumerable<T> IntersectBy<T>(this IEnumerable<IEnumerable<T>> collections, Func<T?, T?, bool> compare) { var itCollections = collections.GetEnumerator(); if (!itCollections.MoveNext()) yield break; var intersected = itCollections.Current; while (itCollections.MoveNext()) { intersected = intersected.Intersect(itCollections.Current, new LambdaEqualityComparer<T>(compare)); if (!intersected.Any()) break; } foreach (var item in intersected) { yield return item; } } /// <summary> /// Iterates to all items. Can be used to iterate all items without using memory. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> public static void Iterate<T>(this IEnumerable<T> items) { var enumerator = items.ThrowIfEnumerableIsNull() .GetEnumerator(); while (enumerator.MoveNext()) { } } /// <summary> /// Returns a list of k-combinations. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="length"></param> /// <returns></returns> public static IEnumerable<IEnumerable<T>> KCombinations<T>(this IEnumerable<T> items, int length) where T : IComparable { items.ThrowIfEnumerableIsNull(); if (length == 1) return items.Select(t => new T[] { t }); return KCombinations(items, length - 1) .SelectMany(t => items.Where(o => o.CompareTo(t.Last()) > 0), (t1, t2) => t1.Concat(new T[] { t2 })); } /// <summary> /// Returns a list of k-combinations with repetitions. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="length"></param> /// <returns></returns> public static IEnumerable<IEnumerable<T>> KCombinationsWithRepetition<T>(this IEnumerable<T> items, int length) where T : IComparable { items.ThrowIfEnumerableIsNull(); if (length == 1) return items.Select(t => new T[] { t }); return KCombinationsWithRepetition(items, length - 1) .SelectMany(t => items.Where(o => o.CompareTo(t.Last()) >= 0), (t1, t2) => t1.Concat(new T[] { t2 })); } /// <summary> /// Returns the last left of items if not empty. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <returns></returns> public static Option<T> LastAsOption<T>(this IEnumerable<T> items) { var it = items.ThrowIfEnumerableIsNull().GetEnumerator(); var last = Option.None<T>(); while (it.MoveNext()) { last = Option.Some(it.Current); } return last; } /// <summary> /// Returns all matching items of both lists as a tuple of two lists. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TKey">Key that is used for matching.</typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <param name="keySelector"></param> /// <param name="unique"></param> /// <returns>matching items as a tuple of two lists.</returns> public static (IEnumerable<T> lhs, IEnumerable<T> rhs) Match<T, TKey>( this IEnumerable<T> lhs, IEnumerable<T> rhs, Func<T, TKey> keySelector) where TKey : notnull { lhs.ThrowIfEnumerableIsNull(); rhs.ThrowIfEnumerableIsNull(); keySelector.ThrowIfNull(); var lhsTuples = lhs.Enumerate().ToArray(); var rhsTuples = rhs.Enumerate().ToArray(); var tuples = from left in lhsTuples join right in rhsTuples on keySelector(left.item) equals keySelector(right.item) select (left, right); var lhsMap = new MultiValueMap<TKey, (int, T)>(); var rhsMap = new MultiValueMap<TKey, (int, T)>(); foreach (var (left, right) in tuples) { lhsMap.AddUnique(keySelector(left.item), left); rhsMap.AddUnique(keySelector(right.item), right); } return (lhsMap.Values.Select(t => t.Item2), rhsMap.Values.Select(t => t.Item2)); } /// <summary> /// Returns all matching items between two lists. The items are returned as tuples with their occurrencies. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns>matching items with their occurrencies.</returns> public static IEnumerable<((int counter, T? item) lhs, (int counter, T? item) rhs)> MatchWithOccurrencies<T>( this IEnumerable<T?> lhs, IEnumerable<T?> rhs) { lhs.ThrowIfEnumerableIsNull(); rhs.ThrowIfEnumerableIsNull(); var enumeratedLhs = lhs.Select(l => NullableKey.New(l)) .Enumerate(); var enumeratedRhs = rhs.Select(r => NullableKey.New(r)) .Enumerate(); var tuples = enumeratedLhs .Join(enumeratedRhs, left => left.item, right => right.item, (left, right) => (left, right)).ToArray(); var lhsMap = new MultiValueMap<NullableKey<T>, (int, T?)>(); var rhsMap = new MultiValueMap<NullableKey<T>, (int, T?)>(); foreach (var (left, right) in tuples) { lhsMap.AddUnique(left.item, (left.counter, left.item.Value)); rhsMap.AddUnique(right.item, (right.counter, right.item.Value)); } foreach (var pair in lhsMap) { var lhsTuples = lhsMap.GetValues(new[] { pair.Key }); var rhsTuples = rhsMap.GetValues(new[] { pair.Key }); var leftTuple = (lhsTuples.Count(), pair.Key.Value); var rightTuple = (rhsTuples.Count(), pair.Key.Value); yield return (leftTuple, rightTuple); } } /// <summary> /// Returns matching items of both lists with their occurrencies. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TKey"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <param name="keySelector"></param> /// <returns></returns> public static IEnumerable<((int counter, T item) lhs, (int counter, T item) rhs)> MatchWithOccurrencies<T, TKey>( this IEnumerable<T> lhs, IEnumerable<T> rhs, Func<T, TKey> keySelector) where TKey : notnull { lhs.ThrowIfEnumerableIsNull(); rhs.ThrowIfEnumerableIsNull(); keySelector.ThrowIfNull(); var enumeratedLhs = lhs.Enumerate(); var enumeratedRhs = rhs.Enumerate(); var tuples = from left in enumeratedLhs join right in enumeratedRhs on keySelector(left.item) equals keySelector(right.item) select (left, right); var lhsMap = new MultiValueMap<TKey, (int, T)>(); var rhsMap = new MultiValueMap<TKey, (int, T)>(); foreach (var (left, right) in tuples) { var key = keySelector(left.item); lhsMap.AddUnique(key, left); rhsMap.AddUnique(key, right); } foreach(var pair in lhsMap) { var lhsTuples = lhsMap.GetValues(new[] { pair.Key }); var rhsTuples = rhsMap.GetValues(new[] { pair.Key }); var leftTuple = (lhsTuples.Count(), pair.Value.Item2); var rightTuple = (rhsTuples.Count(), pair.Value.Item2); yield return (leftTuple, rightTuple); } } /// <summary> /// Returns the greatest left selected by the predicate. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="comparer">Returns the value to compare.</param> /// <returns></returns> public static T MaxBy<T>(this IEnumerable<T> items, Func<T, T, int> comparer) { items.ThrowIfEnumerableIsNull(); comparer.ThrowIfNull(); return items.Aggregate((a, b) => comparer(a, b) == 1 ? a : b); } /// <summary> /// Returns the seed left selected by the predicate. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TSelector"></typeparam> /// <param name="items"></param> /// <param name="comparer"></param> /// <returns></returns> public static T? MinBy<T>(this IEnumerable<T> items, Func<T, T, int> comparer) { items.ThrowIfEnumerableIsNull(); comparer.ThrowIfNull(); return items.Aggregate((a, b) => comparer(a, b) == -1 ? a : b); } /// <summary> /// Returns the seed and max value. /// </summary> /// <typeparam name="T">T must implement IComparable<T></typeparam> /// <param name="items"></param> /// <returns></returns> public static Option<(T min, T max)> MinMax<T>(this IEnumerable<T> items) where T : IComparable<T> { items.ThrowIfEnumerableIsNull(); T? min = default; T? max = default; foreach (var item in items .OnFirst(i => { min = i; max = i; }) .Skip(1)) { if (item.CompareToNullable(min).IsOkAndAlso(x => x == -1)) { min = item; continue; } if (item.CompareToNullable(max).IsOkAndAlso(x => x == 1)) max = item; } return (null != min && null != max) ? Option.Some((min, max)) : Option.None<(T, T)>(); } /// <summary> /// Returns the seed and max selected by the predicate. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TSelector"></typeparam> /// <param name="items"></param> /// <param name="selector"></param> /// <returns></returns> public static Option<(T min, T max)> MinMax<T, TSelector>( this IEnumerable<T> items, Func<T, TSelector> selector) where TSelector : IComparable { T? min = default; T? max = default; foreach (var item in items .OnFirst(x => { min = x; max = x; }) .Skip(1)) { var selectorValue = selector(item); if (null == selectorValue) continue; if (-1 == selectorValue.CompareTo(selector(min!))) { min = item; continue; } if (1 == selectorValue.CompareTo(selector(max!))) max = item; } return null != min && null != max ? Option.Some((min, max)) : Option.None<(T, T)>(); } /// <summary> /// Returns the elements that occure most frequently. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TKey"></typeparam> /// <param name="items"></param> /// <param name="keySelector"></param> /// <returns></returns> public static (IEnumerable<T> items, int count) MostFrequent<T, TKey>( this IEnumerable<T> items, Func<T, TKey> keySelector) { var grouped = items.ThrowIfEnumerableIsNull() .GroupBy(keySelector); var mostFrequent = new List<IGrouping<TKey, T>>(); var itemCount = 0; foreach (var grp in grouped.OnFirst(g => { mostFrequent.Add(g); itemCount = mostFrequent.Count; }).Skip(1)) { var count = grp.Count(); if (itemCount > count) continue; if (count > itemCount) mostFrequent.Clear(); mostFrequent.Add(grp); itemCount = count; } if (null == mostFrequent) return (Enumerable.Empty<T>(), 0); return (mostFrequent.Select(g => g.First()), itemCount); } /// <summary> /// Returns the left on a specific index. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="index"></param> /// <returns>An optional.</returns> public static Option<T> Nth<T>(this IEnumerable<T> items, int index) { if (0 > index) return Option.None<T>(); var pos = 0; foreach (var item in items.ThrowIfEnumerableIsNull()) { if (pos > index) break; if (index == pos) return Option.Some(item); pos++; } return Option.None<T>(); } #if NET6_0_OR_GREATER /// <summary> /// Returns all items within the range of indices. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="range">range of indices. Indices from end are not supported</param> /// <returns>all items within the range of indices</returns> public static IEnumerable<T> Nths<T>(this IEnumerable<T> items, System.Range range) { int i = 0; foreach (var item in items.ThrowIfEnumerableIsNull()) { if (range.Includes(i)) yield return item; i++; } } #endif /// <summary> /// gets items on the certain indexes. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="indexes"></param> /// <returns></returns> public static IEnumerable<T> Nths<T>(this IEnumerable<T> items, IEnumerable<int> indexes) { var pos = 0; foreach (var item in items.ThrowIfEnumerableIsNull()) { if (indexes.Contains(pos)) yield return item; pos++; } } /// <summary> /// Returns a list of items. The predicate allows filtering items by index. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static IEnumerable<T> Nths<T>(this IEnumerable<T> items, Func<long, bool> predicate) { predicate.ThrowIfNull(); long i = 0; return items.Where(item => predicate(i++)); } /// <summary> /// Returns all items with their occurrencies. /// </summary> /// <typeparam name="T">Item type</typeparam> /// <param name="items">list of items</param> /// <returns>Returns all items with their occurrencies.</returns> public static IEnumerable<(T value, int quantity)> Occurrencies<T>(this IEnumerable<T> items) { foreach(var group in items.GroupBy(x => x)) { yield return (value: group.Key, quantity: group.Count()); } } #if NET6_0_OR_GREATER /// <summary> /// Returns all items with their occurrencies. /// </summary> /// <typeparam name="T">Item type</typeparam> /// <param name="items">List of items</param> /// <param name="comparer">custom comparer.</param> /// <returns>Returns all items with their occurrencies.</returns> public static IEnumerable<(T? value, int quantity)> Occurrencies<T>( this IEnumerable<T> items, IEqualityComparer<T> comparer) { var set = new CountedHashSet<T>(new HashSet<Countable<T>>(new NullableEqualityComparer<Countable<T>>( (x, y) => comparer.Equals(x.Value, y.Value), x => comparer.GetHashCode(x.Value!)))); foreach (var item in items) { set.Add(item); } foreach (var (item, count) in set.GetCountedElements()) { yield return (value: item, quantity: count); } } #endif /// <summary> /// Returns all items whose type matches with a list of types. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <param name="types"></param> /// <returns></returns> public static IEnumerable<T> OfType<T>(this IEnumerable<T> items, params Type[] types) { foreach (var item in items.ThrowIfEnumerableIsNull()) { if (null == item) continue; var type = item.GetType(); if (types.Any(t => t.Equals(type) || t.IsAssignableFrom(type))) yield return item; } } /// <summary> /// Returns all items of type <paramref name="types"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <param name="selector"></param> /// <param name="types"></param> /// <returns></returns> public static IEnumerable<TResult> OfType<T, TResult>( this IEnumerable<T> items, Func<T, TResult> selector, params Type[] types) { return items.OfType(types).Select(selector); } /// <summary> /// Returns adjacent items as tuples. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <param name="selector">First T is lhs left and second T is the rhs left and so on.</param> /// <returns></returns> public static IEnumerable<(T lhs, T rhs)> Pairs<T>(this IEnumerable<T> items) { var it = items.ThrowIfEnumerableIsNull() .GetEnumerator(); if (!it.MoveNext()) yield break; var lhs = it.Current; while (it.MoveNext()) { yield return (lhs, it.Current); lhs = it.Current; } } /// <summary> /// Calls action on all adjacent elements. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="action">Contains the previous and the current left.</param> /// <returns></returns> public static IEnumerable<(T lhs, T rhs)> Pairs<T>(this IEnumerable<T> items, Action<T, T> action) { action.ThrowIfNull(); foreach (var tuple in items.Pairs()) { action(tuple.lhs, tuple.rhs); yield return tuple; } } /// <summary> /// Calls predicate on all adjacent elements and returns all elements of the tuple. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="selector"></param> /// <returns></returns> public static IEnumerable<T> Pairs<T>(this IEnumerable<T> items, Func<T, T, (T, T)> selector) { selector.ThrowIfNull(); foreach (var (lhs, rhs) in items.Pairs()) { var (l, r) = selector(lhs, rhs); yield return l; yield return r; } } /// <summary> /// Calls predicate on all adjacent elements and transforms each element into TReturn. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="action">Contains the previous and the current left.</param> /// <returns></returns> public static IEnumerable<TReturn> Pairs<T, TReturn>(this IEnumerable<T> items, Func<T, T, TReturn> selector) { selector.ThrowIfNull(); foreach (var (lhs, rhs) in items.Pairs()) yield return selector(lhs, rhs); } /// <summary> /// Partitions items into two lists. If predicate is true the left is added to matching otherwise to notMatching. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate">Discriminator of the two lists.</param> /// <returns></returns> public static (IEnumerable<T> matching, IEnumerable<T> notMatching) Partition<T>( this IEnumerable<T> items, Func<T, bool> predicate) { items.ThrowIfEnumerableIsNull(); predicate.ThrowIfNull(); var groups = items.GroupBy(predicate); return (groups.Where(grp => grp.Key).SelectMany(x => x), groups.Where(grp => !grp.Key).SelectMany(x => x)); } /// <summary> /// Partitions items into two lists. If predicate is true the left is added to matching otherwise notMatching. /// </summary> /// <typeparam name="T">Type of items.</typeparam> /// <typeparam name="TResult">Type of the result.</typeparam> /// <param name="items">List of items.</param> /// <param name="predicate">Predicate to partition.</param> /// <param name="match">projection to TResult.</param> /// <param name="noMatch">projection to TResult.</param> /// <returns></returns> /// public static (TMatch matching, TNoMatch notMatching) Partition<T, TMatch, TNoMatch>( this IEnumerable<T> items, Func<T, bool> predicate, Func<IEnumerable<T>, TMatch> match, Func<IEnumerable<T>, TNoMatch> noMatch) { predicate.ThrowIfNull(); match.ThrowIfNull(); noMatch.ThrowIfNull(); var (matching, notMatching) = Partition(items, predicate); return (match(matching), noMatch(notMatching)); } /// <summary> /// Creates permutations of a list. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items">items must be sorted</param> /// <param name="length">This is the permutation size.</param> /// <param name="repetitions">If true, it contains repetitions.</param> /// <returns></returns> public static IEnumerable<IEnumerable<T>> Permutations<T>( this IEnumerable<T> items, int length, bool repetitions = true) { items.ThrowIfEnumerableIsNull(); if (length == 1) return items.Select(t => new T[] { t }); if (repetitions) { return Permutations(items, length - 1, repetitions) .SelectMany(t => items, (t1, t2) => t1.Concat(new T[] { t2 })); } return Permutations(items, length - 1) .SelectMany(t => items.Where(o => !t.Contains(o)), (t1, t2) => t1.Concat(new T[] { t2 })); } /// <summary> /// Creates permutations of two lists. /// </summary> /// <typeparam name="T1">Type of elements of first list.</typeparam> /// <typeparam name="T2">Type of elements of second list.</typeparam> /// <param name="lhs">first list.</param> /// <param name="rhs">second list.</param> /// <param name="repetitions">if true the permutations can include repetitions otherwise not.</param> /// <returns></returns> public static IEnumerable<(T1, T2)> Permutations<T1, T2>( this IEnumerable<T1> lhs, IEnumerable<T2> rhs, bool repetitions = true) { var tuples = lhs.SelectMany(l => rhs, (l, r) => (l, r)); return repetitions ? tuples : tuples.Distinct(); } /// <summary> /// Creates permutations of multiple lists. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="lists"></param> /// <returns></returns> public static IEnumerable<T[]> Permutations<T>(this IEnumerable<IEnumerable<T>> lists) { if (!lists.Any()) { yield return Array.Empty<T>(); yield break; } var firstList = lists.First(); var remainingLists = lists.Skip(1); var withoutFirstList = Permutations(remainingLists); foreach (var lhs in firstList) { foreach (var rhs in withoutFirstList) { var permutation = new T[1 + rhs.Length]; permutation[0] = lhs; if (rhs.Length > 0) Array.Copy(rhs, 0, permutation, 1, rhs.Length); yield return permutation; } } } /// <summary> /// Inserts an left at the beginning only if the list is not empty. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="item"></param> /// <returns></returns> public static IEnumerable<T> PrependIfNotEmpty<T>(this IEnumerable<T> items, Func<T> factory) { factory.ThrowIfNull(); var it = items.ThrowIfEnumerableIsNull() .GetEnumerator(); if (!it.MoveNext()) yield break; yield return factory(); yield return it.Current; while (it.MoveNext()) yield return it.Current; } /// <summary> /// Returns a random subset of elems. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="elems"></param> /// <param name="numberOfSubSetElements">the size of the subset.</param> /// <param name="random">random number generator. If it is null a number generator is created.</param> /// <returns></returns> public static IEnumerable<T> RandomSubset<T>( this IEnumerable<T> elems, int numberOfSubSetElements, Random? random = null) { elems.ThrowIfEnumerableIsNull(); if (0 >= numberOfSubSetElements) return Enumerable.Empty<T>(); if (null == random) random = new Random(); var itemCount = elems.Count(); if (numberOfSubSetElements > itemCount) numberOfSubSetElements = itemCount; var indexes = Enumerable.Range(0, itemCount).ToList(); var shuffledIndexes = indexes.Shuffle(random); return elems.Nths(shuffledIndexes .Take(numberOfSubSetElements) .ToArray()); } /// <summary> /// Removes the last element. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="item"></param> /// <returns></returns> public static IEnumerable<T> RemoveTail<T>(this IEnumerable<T> items) { var it = items.ThrowIfEnumerableIsNull() .GetEnumerator(); while (true) { if (!it.MoveNext()) yield break; var prev = it.Current; if (!it.MoveNext()) yield break; yield return prev; yield return it.Current; } } /// <summary> /// Replaces left item with item at a specified index. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="index">The position in the list.</param> /// <param name="item">Item that replaces the existing left at a specific index.</param> /// <returns></returns> public static IEnumerable<T> Replace<T>(this IEnumerable<T> items, int index, T item) { items.ThrowIfEnumerableIsNull(); item.ThrowIfNull(); return Replace(items, new[] {(index, item) }, item => item); } /// <summary> /// Replaces the items with replace items. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="replace"></param> /// <returns></returns> public static IEnumerable<T> Replace<T>(this IEnumerable<T> items, IEnumerable<T> replace) { var replaceItems = replace.ToArray(); foreach(var item in items) { var first = replaceItems.FirstAsOption(x => x.EqualsNullable(item)); if (first.TryGet(out var replaceItem)) { yield return replaceItem; continue; } yield return item; } } /// <summary> /// Replaces the items at specified indexes with the specified values of replaceTuples. /// </summary> /// <typeparam name="T">Type of the elements of the list.</typeparam> /// <param name="items">List of items.</param> /// <param name="replaceTuples">The tuples which should repace the items at specific indices.</param> /// <returns></returns> public static IEnumerable<T> Replace<T>(this IEnumerable<T> items, IEnumerable<(int index, T item)> replaceTuples) { items.ThrowIfEnumerableIsNull(); replaceTuples.ThrowIfEnumerableIsNull(); return Replace(items, replaceTuples, item => item); } /// <summary> /// Replaces the items from a list with the returned values from project. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <param name="project">Gets each left with index.</param> /// <returns></returns> public static IEnumerable<TResult> Replace<T, TResult>( this IEnumerable<T> items, Func<int, T, TResult> project) { items.ThrowIfEnumerableIsNull(); project.ThrowIfNull(); foreach (var (index, item) in items.Enumerate()) { yield return project(index, item); } } /// <summary> /// Replaces items matching the predicate with the result from replace method. /// </summary> /// <typeparam name="T">Type of the elements of items.</typeparam> /// <param name="items">List of items.</param> /// <param name="predicate">The predicate for replacements.</param> /// <param name="replace">Is called when predicate is true.</param> /// <returns></returns> public static IEnumerable<T> Replace<T>( this IEnumerable<T> items, Func<int, T, bool> predicate, Func<int, T, T> replace) { items.ThrowIfEnumerableIsNull(); replace.ThrowIfNull(); foreach (var (index, item) in items.Enumerate()) { if(predicate(index, item)) { yield return replace(index, item); continue; } yield return item; } } /// <summary> /// Replaces the items from a list with specified <paramref name="replaceTuples"/> including values with their indices. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <param name="replaceTuples">A list of tuples which include the replacement items and indexes.</param> /// <param name="project">Projects each left to TResult.</param> /// <returns>A list of TResult items.</returns> public static IEnumerable<TResult> Replace<T, TResult>( this IEnumerable<T> items, IEnumerable<(int index, T item)> replaceTuples, Func<T, TResult> project) { items.ThrowIfEnumerableIsNull(); replaceTuples.ThrowIfEnumerableIsNull(); project.ThrowIfNull(); var orderedTuples = replaceTuples.Where(tuple => 0 <= tuple.index) .OrderBy(tuple => tuple.index) .ToList(); var itReplace = orderedTuples.GetEnumerator(); var hasNext = itReplace.MoveNext(); if(!hasNext) { foreach (var item in items) yield return project(item); yield break; } var replaceTuple = itReplace.Current; foreach (var (index, item) in items.Enumerate()) { if(hasNext && replaceTuple.index == index) { yield return project(replaceTuple.item); hasNext = itReplace.MoveNext(); if (hasNext) replaceTuple = itReplace.Current; continue; } yield return project(item); } } /// <summary> /// Enables you to do folds like <see cref="=Aggregate"/>, while collecting the intermediate results. /// This is equivalent to the Scala scanLeft function. /// </summary> /// <typeparam name="T">Type of an left</typeparam> /// <param name="items">List of items.</param> /// <param name="seed">The initial value.</param> /// <param name="func">The scan function</param> /// <returns></returns> public static IEnumerable<T> ScanLeft<T>(this IEnumerable<T> items, T seed, Func<T, T, T> func) { var it = items.GetEnumerator(); var result = seed; while (it.MoveNext()) { result = func(result, it.Current); yield return result; } } /// <summary> /// Enables you to do folds like <see cref="=Aggregate"/>, while collecting the intermediate results. /// This is equivalent to the Scala scanRight function. /// </summary> /// <typeparam name="T">Type of an left</typeparam> /// <param name="items">List of items.</param> /// <param name="seed">The initial value.</param> /// <param name="func">The scan function</param> /// <returns></returns> public static IEnumerable<T> ScanRight<T>(this IEnumerable<T> items, T seed, Func<T, T, T> func) { return fold(items, seed, func).Reverse(); static IEnumerable<T> fold(IEnumerable<T> items, T seed, Func<T, T, T> func) { var it = items.Reverse().GetEnumerator(); var result = seed; yield return result; while (it.MoveNext()) { result = func(it.Current, result); yield return result; } } } /// <summary> /// Returns items only if all items have a valid predicate. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <param name="project"></param> /// <returns>Returns an empty list if not all items have a valid predicate.</returns> public static IEnumerable<TResult> SelectAll<T, TResult>( this IEnumerable<T> items, Func<T, bool> predicate, Func<T, TResult> project) { predicate.ThrowIfNull(); project.ThrowIfNull(); var all = true; foreach (var item in items.ThrowIfEnumerableIsNull()) { if(!predicate(item)) { all = false; break; } } if (!all) yield break; foreach (var item in items) { yield return project(item); } } /// <summary> /// Returns only the Error values. /// </summary> /// <typeparam name="TOk"></typeparam> /// <typeparam name="TError"></typeparam> /// <param name="items"></param> /// <returns></returns> public static IEnumerable<TError> SelectError<TOk, TError>(this IEnumerable<Result<TOk, TError>> items) { return items.ThrowIfEnumerableIsNull() .Where(item => !item.IsOk) .Select(result => result.ToError()); } /// <summary> /// Filters all items that are null. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <returns></returns> public static IEnumerable<T> SelectNotNull<T>(this IEnumerable<T?> items) { foreach (var item in items.ThrowIfEnumerableIsNull()) { if (item is T result) yield return result; } } /// <summary> /// Returns only the Ok values. /// </summary> /// <typeparam name="TOk"></typeparam> /// <typeparam name="TError"></typeparam> /// <param name="items"></param> /// <returns></returns> public static IEnumerable<TOk> SelectOk<TOk, TError>(this IEnumerable<Result<TOk, TError>> items) { return items.ThrowIfEnumerableIsNull() .Where(item => item.IsOk) .Select(result => result.ToOk()); } /// <summary> /// Returns all Some values. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <returns></returns> public static IEnumerable<T> SelectSome<T>(this IEnumerable<Option<T>> items) { foreach(var item in items) { if (item.TryGet(out var value)) yield return value; } } /// <summary> /// Returns true if lhs and rhs has the same size and all values in the same order. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <param name="equals"></param> /// <returns></returns> public static bool SequenceEqual<T>(this IEnumerable<T> lhs, IEnumerable<T> rhs, Func<T, T, bool> equals) { var itLhs = lhs.GetEnumerator(); var itRhs = rhs.GetEnumerator(); while(itLhs.MoveNext()) { var hasNext = itRhs.MoveNext(); if (!hasNext) return false; var l = itLhs.Current; var r = itRhs.Current; if(!equals(l, r)) return false; } return !itRhs.MoveNext(); } /// <summary> /// Returns Some if exactly one left exists. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static Option<T> SingleAsOption<T>(this IEnumerable<T> items) { var it = items.ThrowIfEnumerableIsNull() .GetEnumerator(); if (!it.MoveNext()) return Option.None<T>(); var first = it.Current; if (it.MoveNext()) return Option.None<T>(); return Option.Maybe(first); } /// <summary> /// Returns Some if exactly one left exists with this predicate. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static Option<T> SingleAsOption<T>(this IEnumerable<T> items, Func<T, bool> predicate) { items.ThrowIfEnumerableIsNull(); predicate.ThrowIfNull(); var found = Option.None<T>(); foreach (var item in items) { if (predicate(item)) { if (found.IsSome) return Option.None<T>(); found = Option.Some(item); } } return found; } /// <summary> /// Skips items until all predicates match exactly one time, and then returns the remaining elements. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicates"></param> /// <returns></returns> public static IEnumerable<T> SkipUntilSatisfied<T>(this IEnumerable<T> items, params Func<T, bool>[] predicates) { items.ThrowIfEnumerableIsNull(); var invasivePredicates = new InvasiveVerification<T>(predicates); var isNone = new TriState(); var isTrue = new TriState(true); foreach (var item in items) { var triState = invasivePredicates.Verify(item); if (isNone != triState) continue; yield return item; } } /// <summary> /// Creates a list of enumerables of size length. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="length">this is the chop size.</param> /// <returns></returns> public static IEnumerable<IEnumerable<T>> Slice<T>(this IEnumerable<T> items, int length) { items.ThrowIfEnumerableIsNull(); var sliced = Enumerable.Empty<T>(); var itemCounter = 0; foreach (var item in items) { sliced = sliced.Append(item); itemCounter++; if (itemCounter == length) { itemCounter = 0; yield return sliced; sliced = Enumerable.Empty<T>(); } } if (0 < itemCounter) yield return sliced; } /// <summary> /// Creates a list of enumerables. For each predicate an enumerable. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicates"></param> /// <returns></returns> public static IEnumerable<IEnumerable<T>> Slice<T>( this IEnumerable<T> items, params Func<T, bool>[] predicates) { items.ThrowIfEnumerableIsNull(); if (0 == predicates.Length) return Enumerable.Empty<IEnumerable<T>>(); var splittedItems = new Dictionary<int, IEnumerable<T>>(); for (var i = 0; i < predicates.Length; i++) splittedItems.Add(i, Enumerable.Empty<T>()); foreach (var item in items) { for (var i = 0; i < predicates.Length; i++) if (predicates[i](item)) splittedItems[i] = splittedItems[i].Append(item); } return splittedItems.Select(x => x.Value); } /// <summary> /// Returns the object with the smallest predicate value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="selector">Returns the value to compare.</param> /// <returns></returns> public static T Smallest<T>(this IEnumerable<T> items, Func<T, IComparable> selector) { selector.ThrowIfNull(); return items.Aggregate((a, b) => selector(a).CompareTo(selector(b)) == -1 ? a : b); } /// <summary> /// Returns the object with the smallest predicate value. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TSelector"></typeparam> /// <param name="items"></param> /// <param name="selector">Returns the value to compare.</param> /// <returns></returns> public static T Smallest<T, TSelector>(this IEnumerable<T> items, Func<T, TSelector> selector) where TSelector : IComparable<TSelector> { selector.ThrowIfNull(); return items.Aggregate((a, b) => selector(a).CompareTo(selector(b)) == -1 ? a : b); } /// <summary> /// This method implements the Fisher-Yates Shuffle. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="random"></param> /// <returns></returns> public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> items, Random? random = null) { if (null == random) random = new Random(); return items.ThrowIfEnumerableIsEmpty() .ToArray() .Shuffle(random); } public static IEnumerable<T> Swap<T>(this IEnumerable<T> items, int lhsIndex, int rhsIndex) { lhsIndex.ThrowIfOutOfRange(() => 0 > lhsIndex); rhsIndex.ThrowIfOutOfRange(() => 0 > rhsIndex); var (min, max) = MathExt.MinMax(lhsIndex, rhsIndex); var swappedItems = Enumerable.Empty<T>(); var minItem = Option.None<T>(); var lhs = Enumerable.Empty<T>(); var enumerated = items.Enumerate(); var it = enumerated.GetEnumerator(); bool swapped = false; while(it.MoveNext()) { var (counter, item) = it.Current; if(!swapped) { if (minItem.IsNone) { if (counter == min) { minItem = Option.Some(item); lhs = swappedItems; swappedItems = Enumerable.Empty<T>(); continue; } } else { if (counter == max) { var rhs = swappedItems.Append(minItem.OrThrow()); lhs = lhs.Append(item); swappedItems = lhs.Concat(rhs); swapped = true; continue; } } } swappedItems = swappedItems.Append(item); } foreach(var item in swappedItems) { yield return item; } } /// <summary> /// Returns the symmetric difference of two lists. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <param name="preserveDuplicates">If true then duplicates are taken into account.</param> /// <returns></returns> public static IEnumerable<T> SymmetricDifference<T>( this IEnumerable<T> lhs, IEnumerable<T> rhs, bool preserveDuplicates = false) { if (!preserveDuplicates) { var set = new HashSet<T>(lhs); set.SymmetricExceptWith(rhs); return set; } return lhs.ExceptWithDuplicates(rhs).Concat(rhs.ExceptWithDuplicates(lhs)); } /// <summary> /// Returns the symmetric difference of two lists. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TKey">The type of the predicate value.</typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <param name="selector">Selects the value of each left to compare.</param> /// <param name="preserveDuplicates"></param> /// <returns></returns> public static IEnumerable<T> SymmetricDifference<T, TKey>( this IEnumerable<T> lhs, IEnumerable<T> rhs, Func<T, TKey?> selector, bool preserveDuplicates = false) { if (!preserveDuplicates) { var set = new HashSet<T>(lhs, new LambdaEqualityComparer<T, TKey>(selector)); set.SymmetricExceptWith(rhs); return set; } return lhs.ExceptWithDuplicates(rhs, selector).Concat(rhs.ExceptWithDuplicates(lhs, selector)); } /// <summary> /// Returns the symmetric difference of two lists. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <param name="preserveDuplicates">preserves duplicates</param> /// <returns>A tuple with elements only on lefthand side <paramref name="lhs"/> and elements only on righthand side <paramref name="rhs"/></returns> public static IEnumerable<T> SymmetricDifferenceSorted<T>( this IEnumerable<T> lhs, IEnumerable<T> rhs, bool preserveDuplicates = false) where T : IComparable<T> { if (!preserveDuplicates) { var set = new HashSet<T>(lhs); set.SymmetricExceptWith(rhs); return set; } return lhs.ExceptWithDuplicatesSorted(rhs).Concat(rhs.ExceptWithDuplicatesSorted(lhs)); } /// <summary> /// Returns the symmetric difference of two lists. This is slower than <see cref="SymmetricDifference{T}(IEnumerable{T}, IEnumerable{T}, bool)"/> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <param name="preserveDuplicates"></param> /// <returns></returns> public static (IEnumerable<T> lhs, IEnumerable<T> rhs) SymmetricDifferenceWithSideIndication<T>( this IEnumerable<T> lhs, IEnumerable<T> rhs, bool preserveDuplicates = false) { return preserveDuplicates ? (lhs.ExceptWithDuplicates(rhs), rhs.ExceptWithDuplicates(lhs)) : (lhs.Except(rhs), rhs.Except(lhs)); } /// <summary> /// <summary> /// Returns the symmetric difference of two lists. This is slower than <see cref="SymmetricDifference{T, TKey}(IEnumerable{T}, IEnumerable{T}, Func{T, TKey?}, bool)"/> /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TKey"></typeparam> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <param name="selector"></param> /// <param name="preserveDuplicates"></param> /// <returns></returns> public static (IEnumerable<T> lhs, IEnumerable<T> rhs) SymmetricDifferenceWithSideIndication<T, TKey>( this IEnumerable<T> lhs, IEnumerable<T> rhs, Func<T, TKey?> selector, bool preserveDuplicates = false) { lhs.ThrowIfNull(); rhs.ThrowIfNull(); selector.ThrowIfNull(); return preserveDuplicates ? (lhs.ExceptWithDuplicates(rhs, selector), rhs.ExceptWithDuplicates(lhs, selector)) : (lhs.ExceptBy(rhs, selector, x => x).NotNull(), rhs.ExceptBy(lhs, selector, x => x).NotNull()); } /// <summary> /// Returns a tuple of taken elements and remaining elements. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TTaken"></typeparam> /// <param name="items"></param> /// <param name="numberOfElements"></param> /// <param name="projectTaken">Projection of taken elements.</param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public static (TTaken taken, IEnumerable<T> remaining) Take<T, TTaken>( this IEnumerable<T> items, int numberOfElements, Func<IEnumerable<T>, TTaken> projectTaken) { if (0 > numberOfElements) throw new ArgumentOutOfRangeException(nameof(numberOfElements), "cannot be negative"); var it = items.GetEnumerator(); var itemCounter = 0; var takenElements = Enumerable.Empty<T>(); while(it.MoveNext()) { itemCounter++; if (itemCounter >= numberOfElements) break; takenElements = takenElements.Append(it.Current); } var remaining = Enumerable.Empty<T>(); while (it.MoveNext()) { remaining = remaining.Append(it.Current); } return (projectTaken(takenElements), remaining); } /// <summary> /// Returns a tuple of taken elements and remaining elements. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TTaken"></typeparam> /// <typeparam name="TRemaining"></typeparam> /// <param name="items"></param> /// <param name="numberOfElements"></param> /// <param name="projectTaken">Projection of taken elements.</param> /// <param name="projectRemaining">Projection of remaining elements.</param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public static (TTaken taken, TRemaining remaining) Take<T, TTaken, TRemaining>( this IEnumerable<T> items, int numberOfElements, Func<IEnumerable<T>, TTaken> projectTaken, Func<IEnumerable<T>, TRemaining> projectRemaining) { if (0 > numberOfElements) throw new ArgumentOutOfRangeException(nameof(numberOfElements), "cannot be negative"); var it = items.GetEnumerator(); var itemCounter = 0; var takenElements = Enumerable.Empty<T>(); var remaining = Enumerable.Empty<T>(); while (it.MoveNext()) { if (itemCounter >= numberOfElements) { remaining = remaining.Append(it.Current); break; } takenElements = takenElements.Append(it.Current); itemCounter++; } while (it.MoveNext()) { remaining = remaining.Append(it.Current); } return (projectTaken(takenElements), projectRemaining(remaining)); } /// <summary> /// Returns at least numberOfElements elements. If the number of elements is smaller, an empty enumerable is returned. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items">Elements of the list.</param> /// <param name="numberOfElements"></param> /// <returns></returns> public static IEnumerable<T> TakeAtLeast<T>(this IEnumerable<T> items, int numberOfElements) { if (0 > numberOfElements) throw new ArgumentOutOfRangeException(nameof(numberOfElements), "cannot be negative"); var it = items.GetEnumerator(); var required = new List<T>(); while (it.MoveNext()) { required.Add(it.Current); if (required.Count == numberOfElements) break; } if (required.Count != numberOfElements) yield break; foreach (var item in required) { yield return item; } while (it.MoveNext()) { yield return it.Current; } } /// <summary> /// Returns at least numberOfElements elements. If the number of elements is smaller, an empty enumerable is returned. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="numberOfElements"></param> /// <param name="predicate"></param> /// <returns></returns> public static IEnumerable<T> TakeAtLeast<T>(this IEnumerable<T> items, int numberOfElements, Func<T, bool> predicate) { if (0 > numberOfElements) throw new ArgumentOutOfRangeException(nameof(numberOfElements), "cannot be negative"); predicate.ThrowIfNull(); var it = items.GetEnumerator(); var required = new List<T>(); while (it.MoveNext()) { if (required.Count == numberOfElements) break; if (predicate(it.Current)) required.Add(it.Current); } if (required.Count != numberOfElements) yield break; foreach (var item in required) { yield return item; } while (it.MoveNext()) { yield return it.Current; } } /// <summary> /// Returns <paramref name="numberOfElements"/> if items contains exactly <paramref name="numberOfElements"/>. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="numberOfElements"></param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public static IEnumerable<T> TakeExact<T>(this IEnumerable<T> items, int numberOfElements) { if (0 > numberOfElements) throw new ArgumentOutOfRangeException(nameof(numberOfElements), "cannot be negative"); var required = new List<T>(); var it = items.GetEnumerator(); while (it.MoveNext()) { required.Add(it.Current); if (required.Count == numberOfElements) break; } if (required.Count != numberOfElements) yield break; if (it.MoveNext()) yield break; foreach (var item in required) { yield return item; } } /// <summary> /// Returns elements from a sequence as long as a specified condition is false, and then skips the remaining elements. /// This is the counterpart to TakeWhile. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <param name="inclusive">if true the matching left is included.</param> /// <returns></returns> public static IEnumerable<T> TakeUntil<T>( this IEnumerable<T> items, Func<T, bool> predicate, bool inclusive = false) { foreach (var item in items) { if (predicate(item)) { if (inclusive) yield return item; yield break; } yield return item; } } /// <summary> /// Returns items until all predicates match exactly one time. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicates"></param> /// <returns></returns> public static IEnumerable<T> TakeUntilSatisfied<T>(this IEnumerable<T> items, params Func<T, bool>[] predicates) { items.ThrowIfEnumerableIsNull(); var invasivePredicates = new InvasiveVerification<T>(predicates); var isNone = new TriState(); var isTrue = new TriState(true); foreach (var item in items) { var triState = invasivePredicates.Verify(item); if (isNone == triState) yield break; if (isTrue == triState) yield return item; } } /// <summary> /// Returns true if all predicates are true. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="elems"></param> /// <param name="predicates"></param> /// <returns></returns> public static bool TryWhere<T>(this IEnumerable<T> items, out IEnumerable<T> elems, params Func<T, bool>[] predicates) { items.ThrowIfEnumerableIsNull(); elems = Enumerable.Empty<T>(); var allFulfilled = new bool[predicates.Length]; foreach (var item in items) { var index = 0; var fulfilled = false; foreach (var predicate in predicates) { if (predicate(item)) { allFulfilled[index] = true; fulfilled = true; } index++; } if (fulfilled) elems.Append(item); } return allFulfilled.All(x => x == true); } /// <summary> /// Returns true if all elements fulfilling the predicate. Stops immediately if predicate returns false. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <param name="elems"></param> /// <returns></returns> public static bool TryWhereAll<T>( this IEnumerable<T> items, Func<T, bool> predicate, out IEnumerable<T> elems) { items.ThrowIfEnumerableIsNull(); predicate.ThrowIfNull(); elems = Enumerable.Empty<T>(); foreach (var item in items) { if (!predicate(item)) { return false; } elems.Append(item); } return true; } /// <summary> /// Checks if all items fulfill the predicate. If there is an left not matching the predicate an exception is thrown. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="predicate"></param> /// <returns></returns> public static IEnumerable<T> WhereAll<T>(this IEnumerable<T> items, Func<T, bool> predicate) { predicate.ThrowIfNull(); foreach (var item in items.ThrowIfEnumerableIsNull()) { if (!predicate(item)) throw new ArgumentOutOfRangeException($"{item}"); yield return item; } } /// <summary> /// Returns all optional values that are some. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <returns></returns> public static IEnumerable<T> WhereSome<T>(this IEnumerable<Option<T>> items) { return items.Where(item => item.IsSome).Select(opt => opt.OrThrow()); } }
const express = require('express') const multer = require('multer') const isAuth = require('../middleware/isAuth') const uploadController = require('../controllers/uploadController') const router = express.Router() const fileStorage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'uploads') }, filename: (req, file, cb) => { cb(null, `${Date.now()}-${file.originalname}`) } }) const filter = (req, file, cb) => { const allowedFileTypes = ['image/jpeg', 'image/jpg', 'image/png'] if (allowedFileTypes.includes(file.mimetype)) { cb(null, true) } else { cb(null, false) } } const upload = multer({ storage: fileStorage, fileFilter: filter }) router.post('/upload', isAuth, upload.single('file'), uploadController.uploadFile) router.delete('/delete-file', isAuth, uploadController.deleteFile) router.put('/reject-shared-file', isAuth, uploadController.rejectSharedFile) router.get('/download-file/:fileId', isAuth, uploadController.downloadFile) router.put('/share-file', isAuth, uploadController.shareFile) module.exports = router
<div class="container"> <h1>Manage account</h1> <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put, :class => "form-horizontal" }) do |f| %> <legend>Edit account</legend> <%= devise_error_messages! %> <div class="control-group"> <%= f.label :avatar, :class => "control-label" %> <div class="controls"> <%= f.file_field :avatar %> <%= f.hidden_field :avatar_cache %> </div> </div> <div class="control-group"> <%= f.label :name, :class => "control-label" %> <div class="controls"> <%= f.text_field :name %> </div> </div> <div class="control-group"> <%= f.label :email, :class => "control-label" %> <div class="controls"> <%= f.email_field :email %> </div> </div> <div class="control-group"> <%= f.label :password, :class => "control-label" %> <div class="controls"> <%= f.password_field :password, :autocomplete => "off" %> <span class="help-inline"> leave blank if you don't want to change it </span> </div> </div> <div class="control-group"> <%= f.label :password_confirmation, :class => "control-label" %> <div class="controls"> <%= f.password_field :password_confirmation %> </div> </div> <div class="control-group info"> <%= f.label :current_password , :class => "control-label"%> <div class="controls"> <%= f.password_field :current_password %> <span class="help-block"> we need your current password to confirm your changes </span> </div> </div> <div class="control-group"> <div class="controls"> <%= f.submit "Update", :class => "btn btn-primary" %> </div> </div> <% end %> <h3>Cancel my account</h3> <p> Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), :class => "btn btn-danger btn-small", :data => { :confirm => "Are you sure?" }, :method => :delete %></p> <%= link_to "Back", :back %> </div>
import { contentTypes, log, RequestMethod } from '@withtyped/shared'; import RequestError from '../errors/RequestError.js'; import type { HttpContext, NextFunction } from '../middleware.js'; import type { Json } from '../types.js'; import type { MergeRequestContext, RequestContext } from './with-request.js'; export type WithBodyContext<InputContext extends RequestContext> = MergeRequestContext< InputContext, { body?: Json; bodyRaw?: Buffer } >; const tryParse = (body: string): Json | undefined => { try { // `body` is not `any`, but `JSON.parse()` returns `any`. :shrug: // eslint-disable-next-line @typescript-eslint/no-unsafe-return return JSON.parse(body); } catch (error: unknown) { log.debug('failed to parse JSON string in `withBody()`', error); } }; export default function withBody<InputContext extends RequestContext>() { return async ( context: InputContext, next: NextFunction<WithBodyContext<InputContext>>, { request }: HttpContext ) => { if ( !context.request.method || [RequestMethod.GET, RequestMethod.OPTIONS, RequestMethod.HEAD].includes( context.request.method ) ) { // eslint-disable-next-line no-restricted-syntax return next(context as WithBodyContext<InputContext>); // No need to spread since nothing needs to change } const readBody = async () => new Promise<Buffer>((resolve, reject) => { const body: Uint8Array[] = []; // eslint-disable-next-line @silverhand/fp/no-mutating-methods const pushToBody = (chunk: Uint8Array | Buffer) => body.push(chunk); request .on('data', pushToBody) .once('end', () => { request.removeListener('data', pushToBody); resolve(Buffer.concat(body)); }) .once('error', (error) => { request.removeListener('data', pushToBody); reject(error); }); }); const raw = await readBody(); const rawString = raw.toString(); if (!rawString) { // eslint-disable-next-line no-restricted-syntax return next(context as WithBodyContext<InputContext>); } if ( context.request.headers['content-type'] ?.split(';') .every((value) => value.trim() !== contentTypes.json) ) { throw new RequestError( `Unexpected \`content-type\` header, only accept "${contentTypes.json}"`, 400 ); } return next({ ...context, request: { ...context.request, body: tryParse(rawString), bodyRaw: raw }, }); }; }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 14 19:25:41 2023 @author: mrityunjay """ from PIL import Image import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle import random class Node: def __init__(self, x, y): self.x = x self.y = y self.children = [] self.parent = None class RRTAlgorithm: def __init__(self, start, goal, num_iterations, grid, step_size): self.random_tree = Node(start[0], start[1]) self.goal_node = Node(goal[0], goal[1]) self.nearest_node = None self.iterations = min(num_iterations, 300) self.grid = grid self.rho = step_size self.num_waypoints = 0 self.nearest_dist = 10000 self.path_distance = 0 self.waypoints = [] def unit_vector(self, start_node, end_node): v = np.array([end_node.x - start_node.x, end_node.y - start_node.y]) u_hat = v / np.linalg.norm(v) return u_hat def add_child(self, x, y): if x == self.goal_node.x: self.nearest_node.children.append(self.goal_node) self.goal_node.parent = self.nearest_node else: temp_node = Node(x, y) self.nearest_node.children.append(temp_node) temp_node.parent = self.nearest_node def sample_point(self): x = random.randint(1, grid.shape[1] - 1) y = random.randint(1, grid.shape[0] - 1) point = np.array([x, y]) return point def steer_to_point(self, start_node, end_point): offset = self.rho * self.unit_vector(start_node, end_point) point = np.array([start_node.x + offset[0], start_node.y + offset[1]]) if point[0] >= grid.shape[1]: point[0] = grid.shape[1] - 1 if point[1] >= grid.shape[0]: point[1] = grid.shape[0] - 1 return point def is_in_obstacle(self, start_node, end_point): u_hat = self.unit_vector(start_node, Node(end_point[0], end_point[1])) test_point = np.array([0.0, 0.0]) for i in range(int(self.rho)): test_point[0] = start_node.x + i * u_hat[0] test_point[1] = start_node.y + i * u_hat[1] if (test_point[0] < 0 or test_point[0] >= self.grid.shape[1] or test_point[1] < 0 or test_point[1] >= self.grid.shape[0]): return True if self.grid[int(round(test_point[1])), int(round(test_point[0]))] == 1: return True return False def find_nearest(self, root, point): if not root: return dist = self.distance(root, point) if dist <= self.nearest_dist: self.nearest_node = root self.nearest_dist = dist for child in root.children: self.find_nearest(child, point) def distance(self, node, point): dist = np.sqrt((node.x - point[0]) ** 2 + (node.y - point[1]) ** 2) return dist def goal_found(self, point): if self.distance(self.goal_node, point) <= self.rho: return True def reset_nearest_values(self): self.nearest_node = None self.nearest_dist = 10000 def retrace_rrt_path(self, goal): if goal.x == self.random_tree.x: return self.num_waypoints += 1 current_point = np.array([goal.x, goal.y]) self.waypoints.insert(0, current_point) self.path_distance += self.rho self.retrace_rrt_path(goal.parent) # Define grid and start/goal points grid = np.load('cspace.npy') start = np.array([100.0, 100.0]) goal = np.array([700.0, 250.0]) num_iterations = 300 step_size = 60 # Create a visualization of the grid with start and goal points start_location = plt.Circle((start[0], start[1]), step_size/2, color='c', fill=False) goal_region = plt.Circle((goal[0], goal[1]), step_size, color='b', fill=False) fig = plt.figure('RRT Algorithm') plt.imshow(grid, cmap='binary') plt.plot(start[0], start[1], 'ro') plt.plot(goal[0], goal[1], 'bo') ax = fig.gca() ax.add_patch(start_location) ax.add_patch(goal_region) plt.xlabel('X-axis (m)') plt.ylabel('Y-axis (m)') plt.show() # Initialize the RRT algorithm rrt = RRTAlgorithm(start, goal, num_iterations, grid, step_size) for i in range(rrt.iterations): rrt.reset_nearest_values() print('Iteration:', i) point = rrt.sample_point() rrt.find_nearest(rrt.random_tree, point) new_point = rrt.steer_to_point(rrt.nearest_node, point) is_in_obstacle = rrt.is_in_obstacle(rrt.nearest_node, new_point) if not is_in_obstacle: rrt.add_child(new_point[0], new_point[1]) plt.pause(0.1) plt.plot([rrt.nearest_node.x, new_point[0]], [rrt.nearest_node.y, new_point[1]], 'go', linestyle="--") if rrt.goal_found(new_point): rrt.add_child(goal[0], goal[1]) print('Goal found!') break rrt.retrace_rrt_path(rrt.goal_node) rrt.waypoints.insert(0, start) print("Number of waypoints:", rrt.num_waypoints) print("Path Distance:", rrt.path_distance) print("Waypoints:", rrt.waypoints) for i in range(len(rrt.waypoints) - 1): plt.plot([rrt.waypoints[i][0], rrt.waypoints[i + 1][0]], [rrt.waypoints[i][1], rrt.waypoints[i + 1][1]], 'ro', linestyle='--') plt.pause(0.1)
"use strict"; /**Typescript Classes: * TypeScript adds types and visibility modifiers to JavaScript classes. * The members of a class (properties & methods) are typed using type annotations, similar to variables.Class members also be given special modifiers which affect visibility: - `public` - (default) allows access to the class member from anywhere - `private` - only allows access to the class member from within the class - `protected` - allows access to the class member from itself and any classes that inherit it. */ class Person { constructor(name) { this.name = name; } getName() { return this.name; } } const person = new Person("Maria"); // console.log(person.name);// person.name isn't accessible from outside the class since it's private console.log(person.getName()); // Propriété des paramètres: //TypeScript provides a convenient way to define class members in the constructor, by adding a visibility modifiers to the parameter. class Animal { // name is a private member variable constructor(name) { this.name = name; } getName() { return this.name; } } const animal = new Animal("Lion"); console.log(animal.getName()); // Readonly: //Similar to arrays, the readonly keyword can prevent class members from being changed. class Plant { constructor(name) { // name cannot be changed after this initial definition, which has to be either at it's declaration or in the constructor. this.name = name; } getName() { return this.name; } } const tree1 = new Plant("Palm"); console.log(tree1.getName()); const tree2 = new Plant("Orange"); console.log(tree2.getName()); class Rectangle { constructor(largeur, longueur) { this.largeur = largeur; this.longueur = longueur; } getArea() { return this.largeur * this.longueur; } } const rectangle1 = new Rectangle(5, 4); console.log(`The area of the rectangle is ${rectangle1.getArea()}`); class Recta { constructor(width, height) { this.width = width; this.height = height; } getArea() { return this.width * this.height; } } class Square extends Rectangle { constructor(width) { super(width, width); } } //# sourceMappingURL=ClassTS.js.map
import * as React from 'react' import { RouteComponentProps } from 'react-router-dom' import { Select, Form, Input, Button, message } from 'antd' import { FormComponentProps } from 'antd/lib/form' import Editor, { UnprivilegedEditor } from '../../components/Editor/Editor' import PicturesWall from '../../components/PicturesWall/PicturesWall' // import * as styles from './index.scss' import { createArticle } from '../../api/article' const { Option } = Select const FormItem = Form.Item interface IProps extends FormComponentProps, RouteComponentProps<any> {} // tslint:disable-line class CreateArticle extends React.Component<IProps, {}> { state = { contentText: '', contentHTML: '', screenshot: '', tags: [ { tag: 'html', text: 'HTML' }, { tag: 'css', text: 'CSS' }, { tag: 'javascript', text: 'JavaScript' }, { tag: 'typescript', text: 'TypeScript' }, { tag: 'es6', text: 'ES6' }, { tag: 'react', text: 'React' }, { tag: 'vue', text: 'Vue' }, { tag: 'angular', text: 'Angular' }, { tag: 'webpack', text: 'Webpack' }, { tag: 'node', text: 'Node' }, { tag: 'zhuanzai', text: '转载' }, { tag: 'others', text: '其他' }, { tag: 'test', text: '测试' } ] } handleChange = (content: string, editor: UnprivilegedEditor) => { this.setState({ contentHTML: content, contentText: editor.getText() }) } handleSubmit = (e: React.FormEvent<any>) => { e.preventDefault() this.props.form.validateFields(async (err, values) => { if (!err && this.state.contentText.trim()) { const description = this.state.contentText.substring(0, 100) + '...' // 在这里进行post提交数据进数据库 const data = { categorys: values.categorys, title: values.title, screenshot: this.state.screenshot, content: this.state.contentHTML, description } const res = await createArticle(data) if (res.code === 0 ) { message.success(res.message) this.props.history.push('/article_list') } if (res.code === 1) { message.info(res.message) } } }) } getScreenShot = (url: string) => { this.setState({ screenshot: url }) } render() { const { getFieldDecorator } = this.props.form const { contentText, contentHTML } = this.state const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 17 } } return ( <div> <Form onSubmit={this.handleSubmit}> <FormItem {...formItemLayout} label="文章标签" hasFeedback> {getFieldDecorator('categorys', { rules: [ { required: true, message: '请至少选择一个文章的标签', type: 'array', } ] })( <Select mode="multiple" placeholder="请至少选择一个文章的标签"> {this.state.tags.map(item => ( <Option key={item.tag} value={item.tag}> {item.text} </Option> ))} </Select> )} </FormItem> <FormItem {...formItemLayout} label="文章标题" hasFeedback> {getFieldDecorator('title', { rules: [ { required: true, message: '文章标题不能为空!' } ] })(<Input placeholder="请输入文章标题" />)} </FormItem> <FormItem {...formItemLayout} label="文章封面"> <PicturesWall getScreenShot={this.getScreenShot}/> </FormItem> <FormItem className="has-error" {...formItemLayout} label="文章内容" required help={!contentText.trim() && '文章内容不能为空'} > <Editor value={contentHTML} onChange={this.handleChange} /> </FormItem> <FormItem wrapperCol={{ span: 12, offset: 12 }}> <Button type="primary" htmlType="submit"> 提交 </Button> </FormItem> </Form> </div> ) } } export default Form.create()(CreateArticle)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/relative_layout_detail" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/scrollDetail"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="8dp" android:orientation="vertical" tools:context="com.arturgiro.android.popularmovies.activities.DetailActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:id="@+id/movie_info"> <ImageView android:id="@+id/iv_poster_detail" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:src="@mipmap/ic_launcher" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/tv_detail_user_rate" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="3" android:gravity="center" android:textSize="50sp" tools:text="7" /> <TextView android:id="@+id/tv_detail_release_date" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="bottom" tools:text="2017-05-30" /> </LinearLayout> </LinearLayout> <android.support.v7.widget.CardView android:id="@+id/card_movie_desc" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginBottom="8dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="8dp" android:orientation="vertical"> <TextView android:id="@+id/tv_detail_original_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:textSize="22sp" android:textStyle="bold" /> <TextView android:id="@+id/tv_detail_overview" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </android.support.v7.widget.CardView> <android.support.v7.widget.CardView android:id="@+id/card_movie_videos" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/card_movie_desc" android:layout_centerHorizontal="true" android:layout_marginBottom="8dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="8dp" android:orientation="vertical"> <TextView android:id="@+id/tv_videos_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Videos" android:textSize="22sp" android:textStyle="bold" /> <android.support.v7.widget.RecyclerView android:id="@+id/movie_videos" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> <ProgressBar android:id="@+id/pb_loading_videos" android:layout_height="42dp" android:layout_width="42dp" android:layout_gravity="center" android:visibility="invisible" /> </android.support.v7.widget.CardView> <android.support.v7.widget.CardView android:id="@+id/card_movie_reviews" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/card_movie_videos" android:layout_centerHorizontal="true"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="4dp"> <TextView android:id="@+id/tv_review_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/review_title" android:textSize="22sp" android:textStyle="bold" /> <android.support.v7.widget.RecyclerView android:id="@+id/movie_reviews" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/tv_review_title" android:paddingTop="4dp" /> </RelativeLayout> <ProgressBar android:id="@+id/pb_loading_reviews" android:layout_height="42dp" android:layout_width="42dp" android:layout_gravity="center" android:visibility="invisible" /> </android.support.v7.widget.CardView> </LinearLayout> </ScrollView> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginBottom="-32dp" android:layout_marginRight="20dp" /> <TextView android:id="@+id/tv_empty_message_display" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="16dp" android:text="@string/empty_message" android:textSize="20sp" android:visibility="invisible" /> </RelativeLayout>
using UnityEngine; using TMPro; using System.Collections.Generic; using Characters; using FightDamageCalc; using Mana; using Systems.Managers; namespace Cards { public class Card3D : MonoBehaviour { [SerializeField] Card cardData; //card object where all the data is retrieved from (the view part of MVC) public Card CardData => cardData; [SerializeField] new TextMeshPro name; [SerializeField] TextMeshPro description; [SerializeField] SpriteRenderer artwork; [SerializeField] SpriteRenderer border; [SerializeField] GameObject manaSockets; //parent object to instantiate sockets under [SerializeField] GameObject socketPrefab; //socket prefab to instatiate depending on the cards mana [SerializeField] Mana3D[] manaInSockets; //mana currently in this cards sockets, start as null for every socket [SerializeField] ParticleSystem playableOutline; [SerializeField] ParticleSystem flash; public static float CAMERA_DISTANCE => Camera.main.nearClipPlane + 7; public static Vector3 DEFAULT_SCALE => new Vector3(0.2f, 1f, 0.3f); public void Play(List<Character> targets) => cardData.Play(targets); public Targeting GetTarget() => cardData.target; public Character Owner { get => cardData.owner; set => cardData.owner = value; } //color of card outline ParticleSystem.MinMaxGradient cachedGradient; void OnEnable() { PlayerTurnInputManager.StaticInstance.MouseEnterPlayArea += EnteredPlayArea; PlayerTurnInputManager.StaticInstance.MouseEnterMana3D += MousedOverMana; PlayerTurnInputManager.StaticInstance.MouseExitMana3D += MouseLeftMana; PlayerTurnInputManager.StaticInstance.RegisterCardEvents(this); Fight.FightEvents.OnCharacterTurnAction += PlayPlayableOutlineParticles; Fight.FightEvents.OnCharacterTurnEnded += PausePlayableOutlineParticles; //Cache color of outline for later var playableOutlineColorOverTime = playableOutline.colorOverLifetime; cachedGradient = playableOutlineColorOverTime.color; } void OnDisable() { PlayerTurnInputManager.StaticInstance.MouseEnterPlayArea -= EnteredPlayArea; PlayerTurnInputManager.StaticInstance.MouseEnterMana3D -= MousedOverMana; PlayerTurnInputManager.StaticInstance.MouseExitMana3D -= MouseLeftMana; PlayerTurnInputManager.StaticInstance.UnregisterCardEvents(this); Fight.FightEvents.OnCharacterTurnAction -= PlayPlayableOutlineParticles; Fight.FightEvents.OnCharacterTurnEnded -= PausePlayableOutlineParticles; } public void Populate(Card card) { if (card == null) return; cardData = card; RemoveSockets(); artwork.sprite = card.artwork; border.sprite = CardConfiguration.GetClassBorder(card.playerClass); name.text = card.name; name.font = CardConfiguration.DEFAULT_FONT; name.color = CardConfiguration.DEFAULT_FONT_COLOR; name.fontSize = CardConfiguration.DEFAULT_FONT_NAME_SIZE; description.text = card.descriptionWithReplaceables; description.font = CardConfiguration.DEFAULT_FONT; description.color = CardConfiguration.DEFAULT_FONT_COLOR; description.fontSize = CardConfiguration.DEFAULT_FONT_NAME_SIZE; UpdateDescription(null); Owner = card.owner; manaInSockets = new Mana3D[card.mana.Length]; //If sockets are already instantiated, destroy them if (manaSockets.transform.childCount > 0) { for (int index = 0; index < manaSockets.transform.childCount; index++) { Destroy(manaSockets.transform.GetChild(index)); } } for (int index = 0; index < card.mana.Length; index++) { //instantiate the socket from the prefab GameObject instanitatedSocket = Instantiate(socketPrefab, manaSockets.transform, false); //offset each socket by a little amount (makes a column on the left side of the card) instanitatedSocket.transform.position += new Vector3(0f, -0.45f, 0f) * index; //set the color of the socket to the manas color instanitatedSocket.transform.GetChild(0).GetComponent<Renderer>().sharedMaterial = ManaConfiguration.GetManaColor(cardData.mana[index]); } } public void UpdateDescription(Character target) { ProcessingChain chain = new ProcessingChain(); var numberValues = cardData.numberValues; for (int index = 0; index < numberValues.Count; index++) { Number copy = numberValues[index]; float numberAffectProcessing = chain.Process(copy, cardData.owner, target).Amount; string typeOfNumberAndIndex = copy.GetDamageType().ToString().ToUpper() + (index + 1); if (numberAffectProcessing < copy.Amount) { description.text = cardData.descriptionWithReplaceables.Replace(typeOfNumberAndIndex, "<color=#910505>" + numberAffectProcessing + "</color>"); } else if (numberAffectProcessing > copy.Amount) { description.text = cardData.descriptionWithReplaceables.Replace(typeOfNumberAndIndex, "<color=#00FF00>" + numberAffectProcessing + "</color>"); } else { description.text = cardData.descriptionWithReplaceables.Replace(typeOfNumberAndIndex, "" + numberAffectProcessing); } } } /// <summary> /// Transforms card to next or previous in chain. /// </summary> /// <param name="direction"> /// true is forward transform (typically an upgrade to the card) /// false is backwards transform /// </param> public void Transform(bool direction) { if (cardData.Transform(direction) == null) return; Populate(cardData.Transform(direction)); } public bool BindMana(Mana3D manaBeingBound) { bool readyToTransform = true; bool binded = false; for (int index = 0; index < manaInSockets.Length; index++) { //manaInSockets and cardScriptableObject.mana will always be same length if (manaInSockets[index] == null && manaBeingBound.type == cardData.mana[index]) { Transform socketTransform = manaSockets.transform.GetChild(index); FitManaIntoSocket(manaBeingBound, socketTransform); binded = true; manaInSockets[index] = manaBeingBound; continue; } if (manaInSockets[index] == null) readyToTransform = false; } //input is true because when every mana is fit into the socket, the card is upgraded if (readyToTransform) Transform(true); void FitManaIntoSocket(Mana3D mana, Transform socket) { mana.transform.SetParent(socket, false); mana.transform.localPosition = Vector3.zero; mana.transform.localScale = new Vector3(.05f, .05f, .05f); } return binded; } public List<ManaType> UnBindAndReturnMana() { List<ManaType> manaTypesToBeUnbound = new List<ManaType>(); foreach (Mana3D mana in manaInSockets) { if (mana != null) { manaTypesToBeUnbound.Add(mana.type); } } return manaTypesToBeUnbound; } void RemoveSockets() { for (int index = 0; index < manaSockets.transform.childCount; index++) { Destroy(manaSockets.transform.GetChild(index).gameObject); } } public delegate void MouseOver(Card3D card); public event MouseOver OnMouseOverEvent; //OnMouseEnter is a unity event that is called whenever the mouse first enters a gameobject with a collider //OnMouseEnterEvent is my custom event that now lets me subscribe other functions to the event in response to a mouse entering this card void OnMouseOver() { if (OnMouseOverEvent != null) { OnMouseOverEvent(this); } } public delegate void MouseExit(Card3D card); public event MouseExit OnMouseExitEvent; void OnMouseExit() { if (OnMouseExitEvent != null) { OnMouseExitEvent(this); } } void PlayPlayableOutlineParticles(Character character) { if (character != Owner) return; playableOutline.Play(); } void PausePlayableOutlineParticles(Character character) { if (character != Owner) return; playableOutline.Pause(); } void EnteredPlayArea() { //Hacky way to tell if this card is the selected card //Only the selected card would have a dragger if (this.TryGetComponent<Dragger>(out Dragger dragger)) { PlayFlash(Color.cyan); } } void MousedOverMana(Mana3D mana) { ManaType type = mana.type; foreach (ManaType manaType in this.CardData.mana) { if (manaType == type) { ChangeColorOfPlayableParticleOutline(type); PlayFlash(ColorForManaType(type)); } } } void MouseLeftMana() { var playableOutlineColorOverTime = playableOutline.colorOverLifetime; playableOutlineColorOverTime.color = cachedGradient; } void ChangeColorOfPlayableParticleOutline(ManaType manaType) { var playableOutlineColorOverTime = playableOutline.colorOverLifetime; Gradient newGradient = new Gradient(); Color color = ColorForManaType(manaType); newGradient.SetKeys(new GradientColorKey[]{ new GradientColorKey(color, 0.0f), new GradientColorKey(color, 1.0f) }, new GradientAlphaKey[] { new GradientAlphaKey(1f, 0.0f), // fade out new GradientAlphaKey(0.0f, 1.0f) // }); playableOutlineColorOverTime.color = newGradient; } void PlayFlash(Color color) { var flashMain = flash.main; flashMain.startColor = color; var flashColor = flash.colorOverLifetime; Gradient newGradient = new Gradient(); newGradient.SetKeys(new GradientColorKey[]{ new GradientColorKey(color, 0.0f), new GradientColorKey(color, 1.0f) }, new GradientAlphaKey[] { new GradientAlphaKey(0.5f, 0.0f), // fade out new GradientAlphaKey(0.0f, 1.0f) // }); flashColor.color = newGradient; flash.Play(); } Color ColorForManaType(ManaType manaType) { switch (manaType) { case ManaType.Red: return Color.red; case ManaType.Blue: return Color.blue; case ManaType.Green: return Color.green; case ManaType.White: return Color.white; case ManaType.Gold: return Color.yellow; case ManaType.Black: return Color.black; } return Color.cyan; } } }
import Article from '../Article/Article'; import blogList from '../../data/blogList.json'; import { BlogPageCards } from 'modules/blogPageCards'; import css from './BlogView.module.scss'; import { useEffect, useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { Loader } from 'shared/components'; import { ROUTES } from 'shared/constants'; const getBlogApi = (id) => { return new Promise((resolve, reject) => { setTimeout(() => { blogList[id] ? resolve(blogList[id]) : reject('Blog not found'); }, 500); }); }; const BlogView = () => { const navigate = useNavigate(); const { blogId } = useParams(); const [blog, setBlog] = useState(null); const [isLoading, setIsLoading] = useState(false); useEffect(() => { setIsLoading(true); getBlogApi(blogId - 1) .then((data) => setBlog(data)) .catch(() => navigate(ROUTES.NOT_FOUND)) .finally(() => setIsLoading(false)); // eslint-disable-next-line }, [blogId]); return ( <> <div className={css.wrapper}> <BlogPageCards /> {blog && <Article article={blog} />} </div> {isLoading && <Loader />} </> ); }; export default BlogView;
--- head: - - meta - property: og:title content: Middleware - - meta - name: description content: A list of modern modules and middleware for building backend apps. - - meta - property: og:description content: A list of modern modules and middleware for building backend apps. --- # Middleware As a rule, when you develop web applications, a web framework is not enough. Below is a list of modern modules and middleware for building backend apps. ## Static server - [sirv](https://github.com/lukeed/sirv) - An optimized middleware & CLI application for serving static files ## Template engine - [Eta](https://eta.js.org/) - Embedded JS template engine for Node, Deno, and the browser. Lighweight, fast, and pluggable. Written in TypeScript - [Edge.js](https://github.com/edge-js/edge) - Node.js templating engine with fresh air - [micromustache](https://github.com/userpixel/micromustache) - An extremely fast and small sub-implementation of the {{mustache}} template engine for JavaScript - [Squirelly](https://github.com/squirrellyjs/squirrelly) - Semi-embedded JS template engine that supports helpers, filters, partials, and template inheritance. 4KB minzipped, written in TypeScript - [sprightly](https://github.com/obadakhalili/sprightly) - A very light-weight JS template engine ## Logger - [@tinyhttp/logger](https://github.com/tinyhttp/logger) - Simple HTTP logger for tinyhttp - [Pino HTTP](https://github.com/pinojs/pino-http) - high-speed HTTP logger for Node.js - [chrona](https://github.com/xambassador/chrona) - Simple HTTP request logger middleware for express.js inspired from koa-logger, written in typescript. ## Session - [micro-session](https://github.com/meyer9/micro-session) - Session middleware for micro - [next-session](https://github.com/hoangvvo/next-session) - Simple promise-based session middleware for Next.js, micro, Express, and more - [iron-session](https://github.com/vvo/iron-session) - Next.js stateless session utility using signed and encrypted cookies to store data. Also works with Express, and Node.js HTTP servers. ## CSRF - [malibu](https://github.com/tinyhttp/malibu) - Framework-agnostic CSRF middleware for modern Node.js. ## Body parser - [milliparsec](https://github.com/tinyhttp/milliparsec) - Tiniest body parser in the universe. Built for modern Node.js. ## Cookies - [cookie-parser](https://github.com/tinyhttp/cookie-parser) - Cookie parsing middleware for Node.js. ## Metrics - [ping](https://github.com/tinyhttp/ping) - Response time checker middleware. ## CORS - [cors](https://github.com/tinyhttp/cors) - CORS middleware for modern Node.js. ## Swagger - [swagger](https://github.com/tinyhttp/swagger) - Swagger integration for tinyhttp. ## Misc - [unless](https://github.com/tinyhttp/unless) - Unless middleware for tinyhttp.
package com.manager.appbanhang.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.manager.appbanhang.R; import com.manager.appbanhang.adapter.DienThoaiAdapter; import com.manager.appbanhang.model.GioHang; import com.manager.appbanhang.model.SanPhamMoi; import com.manager.appbanhang.retrofit.ApiBanHang; import com.manager.appbanhang.retrofit.RetrofitClient; import com.manager.appbanhang.utils.Utils; import com.nex3z.notificationbadge.NotificationBadge; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import io.paperdb.Paper; import io.reactivex.rxjava3.disposables.CompositeDisposable; public class ChitietActivity extends AppCompatActivity { TextView tensp, giasp,soluongkho, mota; Button btnthem; ImageView imghinhanh; Spinner spinner; Toolbar toolbar; SanPhamMoi sanPhamMoi; NotificationBadge badge; // DienThoaiAdapter adapterDt; List<SanPhamMoi> sanPhamMoiList; LinearLayoutManager linearLayoutManager; Handler handler = new Handler(); boolean isLoading = false; // RecyclerView recyclerView; ListView listViewManHinhChinh; CompositeDisposable compositeDisposable = new CompositeDisposable(); ApiBanHang apiBanHang; int page = 1; int loai; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chitiet); apiBanHang = RetrofitClient.getInstance(Utils.BASE_URL).create(ApiBanHang.class); loai = getIntent().getIntExtra("loai", 1); initView(); ActionTooBar(); initData(); initControl(); } private void initControl() { btnthem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { themGioHang(); Paper.book().write("giohang", Utils.manggiohang); } }); } private void themGioHang() { if (Utils.manggiohang.size() > 0) { boolean flag = false; int soluong = Integer.parseInt(spinner.getSelectedItem().toString()); for (int i = 0; i < Utils.manggiohang.size(); i++) { if (Utils.manggiohang.get(i).getIdsp() == sanPhamMoi.getId()) { Utils.manggiohang.get(i).setSoluong(soluong + Utils.manggiohang.get(i).getSoluong()); long gia = Long.parseLong(sanPhamMoi.getGiasp()) * Utils.manggiohang.get(i).getSoluong(); Utils.manggiohang.get(i).setGiasp(gia); flag = true; } } if (flag == false) { // int soluong = Integer.parseInt(spinner.getSelectedItem().toString()); long gia = Long.parseLong(sanPhamMoi.getGiasp()) * soluong; GioHang gioHang = new GioHang(); gioHang.setGiasp(gia); gioHang.setSoluong(soluong); gioHang.setIdsp(sanPhamMoi.getId()); gioHang.setTensp(sanPhamMoi.getTensanpham()); gioHang.setHinhsp(sanPhamMoi.getHinhanh()); gioHang.setSoluongkho(sanPhamMoi.getSoluongkho()); Utils.manggiohang.add(gioHang); } } else { int soluong = Integer.parseInt(spinner.getSelectedItem().toString()); long gia = Long.parseLong(sanPhamMoi.getGiasp()) * soluong; GioHang gioHang = new GioHang(); gioHang.setGiasp(gia); gioHang.setSoluong(soluong); gioHang.setIdsp(sanPhamMoi.getId()); gioHang.setTensp(sanPhamMoi.getTensanpham()); gioHang.setHinhsp(sanPhamMoi.getHinhanh()); gioHang.setSoluongkho(sanPhamMoi.getSoluongkho()); Utils.manggiohang.add(gioHang); } int totalItem = 0; for (int i = 0; i < Utils.manggiohang.size(); i++) { totalItem = totalItem + Utils.manggiohang.get(i).getSoluong(); } badge.setText(String.valueOf(totalItem)); } private void initData() { sanPhamMoi = (SanPhamMoi) getIntent().getSerializableExtra("chitiet"); tensp.setText(sanPhamMoi.getTensanpham()); mota.setText(sanPhamMoi.getMota()); soluongkho.setText("Số lượng kho: " +sanPhamMoi.getSoluongkho() +" sản phẩm"); if (sanPhamMoi.getHinhanh().contains("http")) { Glide.with(getApplicationContext()).load(sanPhamMoi.getHinhanh()).into(imghinhanh); } else { Glide.with(getApplicationContext()).load(Utils.BASE_URL + "images/" + sanPhamMoi.getHinhanh()).into(imghinhanh); } DecimalFormat decimalFormat = new DecimalFormat("###,###,###"); giasp.setText("Giá: " + decimalFormat.format(Double.parseDouble(sanPhamMoi.getGiasp())) + "VND"); Integer[] so = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; ArrayAdapter<Integer> adapterspin = new ArrayAdapter<>(this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, so); spinner.setAdapter(adapterspin); } private void initView() { tensp = findViewById(R.id.txttensp); giasp = findViewById(R.id.txtgiasp); soluongkho = findViewById(R.id.txtsoluongkho); mota = findViewById(R.id.txtmotachitiet); btnthem = findViewById(R.id.btnthemvaogiohang); spinner = findViewById(R.id.spinner); imghinhanh = findViewById(R.id.imgchitiet); toolbar = findViewById(R.id.toobar); //recyclerView = findViewById(R.id.recyclerview_dt); //linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false); //linearLayoutManager = new GridLayoutManager(this,2 ); //recyclerView.setLayoutManager(linearLayoutManager); //recyclerView.setHasFixedSize(true); sanPhamMoiList = new ArrayList<>(); badge = findViewById(R.id.menu_sl); FrameLayout frameLayoutgiohang = findViewById(R.id.framegiohang); frameLayoutgiohang.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent giohang = new Intent(getApplicationContext(), GioHangActivity.class); startActivity(giohang); } }); if (Utils.manggiohang != null) { int totalItem = 0; for (int i = 0; i < Utils.manggiohang.size(); i++) { totalItem = totalItem + Utils.manggiohang.get(i).getSoluong(); } badge.setText(String.valueOf(totalItem)); } } private void ActionTooBar() { setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override protected void onResume() { super.onResume(); if (Utils.manggiohang != null) { int totalItem = 0; for (int i = 0; i < Utils.manggiohang.size(); i++) { totalItem = totalItem + Utils.manggiohang.get(i).getSoluong(); } badge.setText(String.valueOf(totalItem)); } } @Override protected void onDestroy() { compositeDisposable.clear(); super.onDestroy(); } }
/****************************************************************************************************************************** * Name: Kevin Donlon * Presentation Date: 03/16/2021 - 03/20/2021 * Course: EET241 Microcontroller II * Assignment: Final Capstone Project * * Program Abstract: * This code will operate a somewhat complex system of sensors, input devices, and output devices. The main focus of the system * is to create a password protected dairy barn milking system that has an automatic gate opening system that is based off of * RFID tags on the cows. Once the password is entered, the system begins. The gate opens and the system waits for cows. Once * a cow is scanned, the program increments a counter that tracks the number of cows entering or leaving the barn. There is * also a counter that tracks the state of the gate, being open or closed. Based on when the gate is open and closed, and the * count of the cows, the gate will open and close accordingly. The system will operate forever until the user hits the reset * button and the system restarts and awaits a new password. * * This code leaves open room to implement an RFID based cow tracking and management system. In the future, a logging system * will be added to track which cows were scanned at certain times, and display information about the cow scanned. */ //*************************************************Library Section************************************************************* #include <Wire.h> //Wire library for communication between I2C devices, in this case, the LCD screen #include <LiquidCrystal_I2C.h> //LCD I2C library for communication with screen #include <Keypad.h> //Keypad library for use with 4x4 matrix keypad #include <MFRC522.h> //RFID library for use with MFRC #include <Stepper.h> //Stepper library for use with bipolar stepper motor //***************************************************************************************************************************** //*************************************************Predefined Constants******************************************************** #define Password_Length 9 //set Password_Length as a constant, this allows the password to be 8 keys, (9 - 1) #define SS_PIN 9 //set SS_PIN as a constant, designating pin 9 for use with SDA pin on RFID reader #define RST_PIN 8 //set RST_PIN as a constant, designating pin 8 for use with RST pin on RFID reader //***************************************************************************************************************************** //*************************************************Variables and Constants***************************************************** int signalPin = 12; //set signalPin equal to 12 for use programming LCD int cowCount = 0; //set cowCount = to 0, intial setting for start of cow counting sequence int gateState = 0; //set gateState equal to 0, this variable will keep track if the gate is open or close char Data[Password_Length]; //establish password length, in this case it is 8, 9 - 1 char Master[Password_Length] = "134679*#"; //set password as "134679*#" byte data_count = 0, master_count = 0; //data_count and master_count will be used for password entry system char customKey; const int opengate = 200; //change this to fit the number of steps per revolution of stepper motor const byte ROWS = 4; //establish ROWS as a constant of 4 for number of rows on keypad const byte COLS = 4; //establish COLS as a constant of 4 for number of columns on keypad //***************************************************************************************************************************** //*************************************************Setup*********************************************************************** //establish a matrix of characters for each designated position on the keypad, the matrix is a character variable char hexaKeys[ROWS][COLS] = { {'1', '2', '3', 'A'}, {'4', '5', '6', 'B'}, {'7', '8', '9', 'C'}, {'*', '0', '#', 'D'} }; byte rowPins[ROWS] = {35, 37, 39, 41}; //pin 35, 37, 39, and 41 will be used for the rows of the 4x4 keypad byte colPins[COLS] = {43, 45, 47, 49}; //pin 43, 45, 47, and 49 will be used for the columns of the 4x4 keypad Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); //setup keypad with variables designated above LiquidCrystal_I2C lcd(0x27, 16, 2); //set the LCD address to 0x27 for a 16 chars and 2 line display MFRC522 mfrc522(SS_PIN, RST_PIN); //create MFRC522 instance Stepper myStepper(opengate, 29, 27, 25, 23); //setup 4 pin bipolar stepper motor for use with pins 29, 27, 25, and 23 //steps per revolution is set with 'opengate' variable void setup(){ //arduino setup sequence pinMode(A6, INPUT); //set pin A6 as an input for use with gate open button digitalWrite(A6, HIGH); //set pin A6 HIGH pinMode(A7, INPUT); //set pin A7 as an input for use with gate close button digitalWrite(A7, HIGH); //set pin A7 HIGH lcd.init(); //initialize I2C LCD display lcd.backlight(); //initialize I2C display backlight pinMode(signalPin, OUTPUT); //set signalPin (pin 12) as an output //rfid setup Serial.begin(9600); //initiate a serial communication SPI.begin(); //initiate SPI bus mfrc522.PCD_Init(); //initiate MFRC522 (RFID reader) //set stepper motor speed in rotations per minute myStepper.setSpeed(60); Serial.println(); //empty space on Serial Monitor lcd.setCursor(0,0); //cursor position on LCD to the top row, left most position lcd.print("Enter Password:"); //display "Enter Password" on LCD } //***************************************************************************************************************************** //*****************************************************Main Loop*************************************************************** void loop(){ customKey = customKeypad.getKey(); //accept user input on 4x4 keypad for password if (customKey){ //compare entered password (customKey) Data[data_count] = customKey; //counts the place in the password that was entered lcd.setCursor(data_count,1); //set cursor on lcd to position 1 lcd.print(Data[data_count]); //print the key character selected by user data_count++; //increment data_count } if(data_count == Password_Length-1){ //when the number of digits in Password_Length matches data_count, continue lcd.clear(); //clear LCD after password entry if(!strcmp(Data, Master)){ //compare password entered to the master password, if the same, continue //only after the password is entered will the system function, otherwise, nothing works lcd.print("Waiting for Cows"); //print "Waiting for Cows" to the LCD if (digitalRead(A6) == LOW){ //if at any time the button to open the gate is pressed, the gate opens myStepper.step(-60); //no matter where in the code the program is at, this always works } if (digitalRead(A7) == LOW){ //if at any time the button to close the gate is pressed, the gate closes myStepper.step(60); //no matter where in the code the program is at, this always works } //look for new cards with RFID reader if ( ! mfrc522.PICC_IsNewCardPresent()) { return; } //select one of the scanned cards if ( ! mfrc522.PICC_ReadCardSerial()) { return; } //the next 10 lines are the sequence required to display the scanned UID tag on the serial monitor //this can later be used to increment a tracking system where every cow is logged. Serial.print("UID tag :"); //display "UID tag :" obtained from rfid tag on the serial monitor String content= ""; byte letter; //for loop to display every value of UID tag for (byte i = 0; i < mfrc522.uid.size; i++) { Serial.print(mfrc522.uid.uidByte[i] < 0x2 ? " 0" : " "); Serial.print(mfrc522.uid.uidByte[i], HEX); content.concat(String(mfrc522.uid.uidByte[i] < 0x2 ? " 0" : " ")); content.concat(String(mfrc522.uid.uidByte[i], HEX)); } Serial.println(); //print empty space on serial monitor content.toUpperCase(); //change everything to uppercase //if the value on the UID tag is not "00 00 00 00", so any tag scanned, the loop begins //since no tracking is being done, any value that is not "00 00 00 00"" is valid if (content.substring(1) != "00 00 00 00" /*|| "7 96 BB 60") */) //change here the UID of the card/cards that you want to give access { ++cowCount; //increment cowCount Serial.println("Cow Scanned\n"); //display "Cow Scanned" on serial monitor lcd.clear(); //clear LCD screen lcd.print("Cow #"); //display "Cow #" on LCD so user knows what number cow is in barn lcd.print(cowCount); //display cowCount on LCD delay(500); //delay half a second //display UID tag under the cowCount variable on LCD screen, helpful for cow identification lcd.setCursor(0,1); //set cursor to bottom row of LCD screen String content= ""; byte letter; //loop to display every character of UID tag for (byte i = 0; i < mfrc522.uid.size; i++) { lcd.print(mfrc522.uid.uidByte[i] < 0x2 ? " 0" : " "); lcd.print(mfrc522.uid.uidByte[i], HEX); content.concat(String(mfrc522.uid.uidByte[i] < 0x2 ? " 0" : " ")); content.concat(String(mfrc522.uid.uidByte[i], HEX)); } Serial.println(); //print empty space on serial monitor content.toUpperCase(); //change everything to uppercase delay(1500); //delay 1.5 seconds Serial.println("Number of Cows Scanned: "); //print "Number of Cows Scanned: " on serial monitor Serial.println(cowCount); //display cowCount on serial monitor Serial.println(); Serial.println("*******************************"); if (cowCount == 12) //if cowCount equals 12, continue { ++gateState; //pre-increment gateState Serial.println("\ngateState: "); //display "gateState: " on serial monitor Serial.println(gateState); //display gateState value on serial monitor } delay(500); //delay half a second Serial.println(); //print empty space on serial monitor } if (cowCount == 12 && gateState == 1) //if cowCount equals 12 and gateState equals 1, continue { delay(10000); //delay 10 second for gate to clear //ideally this will be a relativeley long period of time to make sure there is no gate obstructions //the push buttons are used if there is an obstruction and the gate does not close correctly //the gate opening can be cleared and manually closed Serial.println("Gate Closing!"); //display "Gate Closing!" on serial monitor lcd.clear(); //clear lcd screen lcd.print("Gate Closing!"); //display "Gate Closing!" on LCD screen myStepper.step(-60); //move stepper motor -60 steps to close gate delay(2000); //delay 2 seconds Serial.println("Begin Milking!"); //diaplay "Begin Milking!" on serial monitor Serial.println(); //display empty space on serial monitor Serial.println("*******************************"); cowCount = 0; //set cowCount back to 0 for next round of cows, DO NOT FORGET } else if (cowCount == 12 && gateState == 2) { delay(10000); //delay 10 second for gate to clear //ideally this will be a relativeley long period of time to make sure there is no gate obstructions //the push buttons are used if there is an obstruction and the gate does not close correctly //the gate opening can be cleared and manually closed Serial.println("Gate Opening!"); //display "Gate Opening!" on serial monitor lcd.clear(); //clear lcd screen lcd.print("Gate Opening!"); //display "Gate Opening!" on LCD screen myStepper.step(60); //move stepper motor -60 steps to close gate delay(2000); //delay 2 seconds cowCount = 0; //set cowCount back to 0 for next round of cows, DO NOT FORGET gateState = 0; //set gateState back to 0, this is only done after the gate is opened again //both if statements used cowCount equal 12 so the gateState is used to determine which way the //gate operates in relation to if the cows just left or entered //display "Waiting for Cows!" on Serial monitor Serial.println("Waiting for Cows!"); Serial.println(); Serial.println("*******************************"); }} //final else statement for incorrect password entry, if password entered is incorrect, continue else{ lcd.print("Incorrect"); //print "Incorrect" to the LCD delay(1000); //delay 1 second lcd.clear(); //clear LCD clearData(); //call clearData function lcd.setCursor(0,0); //set cursor position to 1st row, 1st position lcd.print("Enter Password:"); //display "Enter Password" on LCD } } } //function to clear the dataCount so a new password can be attempted void clearData(){ while(data_count !=0){ Data[data_count--] = 0; } return; }
// // WatchlistView.swift // MovieNight // // Created by Cory Popp on 9/29/22. // import CoreData import SwiftUI struct MyMoviesView: View { // @Environment(\.managedObjectContext) var moc // Filter data @State private var media_type = "movies and tv" @State private var searchText = "" @State private var watched = true @State private var watchedSort = false @FetchRequest(sortDescriptors: [], predicate: NSPredicate(format: "watchlist == true")) var watchlistResults: FetchedResults<Media> var body: some View { VStack { if watchlistResults.count > 0 { List { WatchListFilter(media_type: media_type, watchedSort: watchedSort, watched: watched, searchQuery: searchText) } } else { VStack { Image(systemName: "video") .font(.system(size: 45)) .foregroundColor(Color(.systemPink)) .padding(.vertical) Text("Add Movies and TV shows to start building a watchlist") } } } .navigationTitle("My Movies") .searchable(text: $searchText) .toolbar { ToolbarItem(placement: .navigationBarLeading) { Menu() { Menu() { Button { watched = true watchedSort = true } label: { Text("Watched") } Button { watched = false watchedSort = true } label: { Text("Unwatched") } Button { watchedSort = false } label: { Text("All") } } label: { HStack { Text("Watch Status") Image(systemName: "eye") } } Menu() { Button { media_type = "movie" } label: { Text("Show Movies") } Button { media_type = "tv" } label: { Text("Show TV") } Button { media_type = "movies and tv" } label: { Text("Show All") } } label: { HStack { HStack { Text("Media Type") Image(systemName: "tv") } } } } label: { Image(systemName: "line.3.horizontal.decrease.circle") } } } } } struct WatchlistView_Previews: PreviewProvider { static var previews: some View { MyMoviesView() } }
// Day 1 - Start Chrome => Right Click and select inspect Select Console Tab Select undock into seperate window for full window Variable Holds the values // Syntax for creating Variable var variableName = defaultValue; var user = 'Karthik'; var age = 30; var city; // Viewing the values inside variableName 1. Displaying in Alert Box => alert(user) => Displays user value in popup. 2. Print to Console => console.log(user) => prints value to console. alert(city) => displays undefined in popup. ie defaultValue is undefined var a = 10; var b = 20; var c = a + b; alert(c) => displays 30 in popup var d = '40'; var e = c + d; alert(e) => displays 3040 in popup => concatenation occurs as one of the value type is string. var isMale = true; alert(isMale) => displays true in popup Types String Number Bool Undefined Function Functions Block of code Uses => reusability, code reduction // Syntax-1 for Creating function function functionName(arguments) { // block of code // return value if needed } function welcome(){ console.log('Welcome to Demo'); } // Executing the function functionName(params); welcome(); => Executes the block function add(x, y){ var z = x + y; return z; } var result = add(10, 20); alert(result); x and y are called arguments of function 10 and 20 are called parameters to function // Syntax-2 for Creating function var functionName = function(arguments) { // block of code // return value if needed } var sub = function(x, y){ var z = x - y; return z; } var result = sub(10, 2); alert(result) => displays 8 in popup Helper Functions => functions that are already exists/supports in browser typeof => returns type of the value parseInt => converts string to int this removes decimals and round off is not applied parseFloat => convets string to float typeof("karthik") => string typeof(user) => string typeof(age) => number typeof(isMale) => boolean typeof(city) => undefined typeof(add) => function parseInt("100") => 100 parseInt("100.9") => 100 parseFloat("100.9") => 100.9 Opertors Assignment = Comparison == Conditional ? Or || Handles undefined Conditional Opertor var variableName = condition ? value1 : value2; if condition is true value1 is copied to variable else value2 is copied to variable var z = 10 > 5 ? 20 : 30; alert(z); Comparison 1 == 1 returns true 1 == 2 returns false 1 == "1" returns true as == compares only value 1 === "1" returns false as === compares both value and type 1 === parseInt("1") returns true var a; var b = a || 40; alert(b) => displays 40 in popup var l, m, n; var z = l || m || n || 40; alert(z) => displays 40 in popup m = 20; z = l || m || n || 40; alert(z) => displays 20 in popup function mul(x, y) { console.log('x value is ' + x); console.log('y value is ' + y); var z = x * y; return z; } var result = mul(10, 20); mul(10, 20) returns 200 mul(10, 20, 30) returns 200. 10 is copied to x, 20 is copied to y and 30 is ignored. ie additional params are ignored mul(10) returns NaN - Not a Number. 10 is copied to x. y is not passed, so it picks defaultValue of undefined. 1 + undefined => NaN 1 - undefined => NaN 1 * undefined => NaN 1 / undefined => NaN // Handling undefined in function function mul(x, y) { x = x || 1; y = y || 1; console.log('x value is ' + x); console.log('y value is ' + y); var z = x * y; return z; } mul(10) returns 10 // Day 1 - End // Day 2 - Start Object => Key value pair Key can be string - accessing using . or [] number - accessing using [] Value can be string number boolean object(nested) function // syntax var variableName = {}; // accessing the keys object.key object['key'] // Sample for key of string var neha = { name: 'Neha Singh', age: 20 } // Sample for key of number var test = { 1: 'a', 2: 'b' } test['1'] will return a test.2 throws exception as key with type number cant access using . operator For key of string, we can use special character _ var prakash = { first_name: 'Prakash', last_name: 'Kumar' } var neha = { name: 'Neha Singh', age: 20, city: 'Hyderabad' } // accessing key values as shown below console.log('Neha Singh with age 20 is from Hyderabad '); console.log( neha.name + ' with age '+ neha.age+ ' is from ' + neha.city); console.log( neha['name'] + ' with age '+ neha.age+ ' is from ' + neha['city']); // adding key value pair to object neha.college = "KVR"; neha['native'] = 'India'; if key exists, value of that key is updated. if key doesn't exist, key value pair is added. // deleting keys delete neha.college delete neha['native'] // value can be object(nested object) neha.address = { line1: '1/2/3', line2: 'Kukatpally' } to print kukatpally neha.address.line2 neha.address['line2'] neha['address']['line2'] neha['address'].line2 Use Cases: 1. Object as an input parameter to function function welcome(name, age, city) { name = name || ''; age = age || ''; city = city || ''; console.log('Welcome to Demo ' + name + ',' + age + ',' + city); } function welcome2(options) { console.log('Welcome to Demo ' + options.name + ',' + options.age + ',' + options.city); } welcome2({ name: 'Rakesh', age: 20, city: 'Hyd' }) function welcome3(options) { options = options || {}; options.name = options.name || ''; options.age = options.age || ''; options.city = options.city || ''; console.log('Welcome to Demo ' + options.name + ',' + options.age + ',' + options.city); } 2. Grouping of methods var calculator = { add: function(x, y){ return x + y; }, sub: function(x, y){ return x - y; } } calculator.mul = function(x, y) { return x * y; } JSON.stringify => Converts object to string JSON.parse => converts string to object function createPerson(fn, ln, age) { return { name: fn + ' ' + ln, age: age } } var karthik = createPerson('Karthik', 'Reddy', 30) var preethi = createPerson('Preethi', 'Singh', 20) // Day 2 - End // Day 3 - Start // Arrays Collection Its an Object where keys are numeric, starts with 0, increments by 1 Usually we call key as Index var numbers = [ 1, 2, 3, 4, 5 ]; var students = [ 'Prakash', 'Veena', 'Deepak' ] // Iterating Arrays // Approach 1 - For for(var index = 0; index < students.length; index++){ console.log(index); var student = students[index]; console.log(student); } // Approach 2 - For In - Iterating by Index for(var index in students){ console.log(index); var student = students[index]; console.log(student); } // Approach 3 - For Of - Iterating by item for(var student of students){ console.log(student); } var persons = [ { name: 'Akash', age: 20, city: 'Hyderabad' }, { name: 'Deepthi', age: 30, city: 'Hyderabad' }, { name: 'Venkat', age: 25 }, { name: 'Neha', age: 24, city: 'Delhi' }, { name: 'Prakash', age: 20 } ] // Printing Persons for(var person of persons){ console.log('Welcome to Demo, ' + person.name + ', ' + person.age + ', ' + person.city ); } // Printing Persons where age is greater than 24 for(var person of persons){ if(person.age > 24) { console.log('Welcome to Demo, ' + person.name + ', ' + person.age + ', ' + person.city ); } } // Printing Persons where age is greater than 24 and city is Hyderabad for(var person of persons){ if(person.age > 24 && person.city == 'Hyderabad') { console.log('Welcome to Demo, ' + person.name + ', ' + person.age + ', ' + person.city ); } } // Adding item to Array students.push('Kavya') => added at the end // removing item from Array students.pop() => removed last element or recently added element // Creating array of different types var array = [ 'Prakash', 20, true, undefined, { line1: 'Kupatpally' }, function() { console.log('Welcome to Demo'); } ] array[0] Prakash array[1] 20 array[2] true array[3] undefined array[4] { line1: 'Kupatpally' } array[4].line1 Kupatpally array[5] f array[5]() React.createButton('Submit') var React = { createButton: function(text) { } } React.creatElement('button', { text: 'Submit', id: 'Login'}); var React = { creatElement: function(type, options){ } } NIT.UI.Framework.createButton('Login').submit(); var NIT = { UI: { Framework: { createButton: function(text) { return { submit: function(){ }, validate: function(){ } } } } } } var prakash = { name: 'Prakash Kumar', age: 20, addresses: [ { line1: '1/2/3', line2: 'Kukatpally' }, { line1: '2/3/4', 'line2': 'Ameerpet', city: 'HYD' } ], getCreditScore: function(){ } } JSON.parse JSON.stringify var JSON = { parse: function(){ }, stringify: function(){ } } // Self Executing Functions Function that executes itself Adv: Memory allocated for function is cleared automatically once the function is executed (function functionName() {})() (function welcome() { console.log('Welcome to Demo'); })() (function add(x, y) { return x + y; })(10, 20) sum(10, 20) => 30 sum(10)(20) => 30 // Day 3 - End // Day 4 - Start var neha = { name: 'Neha Singh', age: 30, cc: 123456 } var prakash = { name: 'Prakash', age: 30, cc: 123456 } Naming Conventions Camel Case => first letter will be in lower case, for every word joining higher case letter is used var helloWorld, scientificCalculator creating variables/functions Variable Case => first letter will be in upper case, for every word joining higher case letter is used Student, Person creating class Higher Case => all letters will be in higher case STATES, COUNTRIES creating constants or static data LOWER Case => all letters will be in lower case creating variables student, person // Similar Names Field/Property/Member/Attribute function/method/api // Object Oriented Concepts Class Object Inheritance Constructor Data Hiding or Access Specifiers Advantages Data redundancy can be removed Class - Structure Object/Instance - Real Values of class Constructor - passing default values while creating object // Syntax function className() { // private Variables/Functions // Global variables/Functions return { // Public Variables/Functions } } var instance/object = new className(); // name, age, cc are called public members/variables function Person(){ return { name: '', age: '', cc: '' } } var neha = new Person() var prakash = new Person() // Constructors => inputs that are passed at the time of initialization function Person2(user_name, user_age, user_cc){ return { name: user_name, age: user_age, cc: user_cc } } var neha = new Person2('Neha Singh', 30, '123456'); var prakash = new Person2('Prakash', 30, '123456'); function Person3(options){ return { name: options.name, age: options.age, cc: options.cc } } var neha = new Person3({ name: 'Neha Singh', age:30, cc: '123456' }); var prakash = new Person3( { name: 'Prakash', age:30, cc: '123456' }); // Handling undefined function Person4(options){ options = options || {}; options.name = options.name || ''; options.age = options.age || ''; options.cc = options.cc || ''; return { name: options.name, age: options.age, cc: options.cc } } var krish = new Person4(); // setting defaultValues function Person5(options){ options = options || {}; options.name = options.name || ' Guest User'; options.age = options.age || '0'; options.cc = options.cc || 'xxxxxx'; return { name: options.name, age: options.age, cc: options.cc } } var guest = new Person5(); var Student = function(options) { return { getFullName: function(){ return options.fn + ' ' + options.ln; } } } var karthik = new Student({ fn: 'Karthik', ln: 'Reddy'}); var Account = function(options){ var cc = options.cc; return { makePaymant: function(){ console.log(cc); return "Payment is Done"; } } } var a1 = new Account({ cc: 123456 }); Class A - 10 common 10 other methods Class B - 10 common 5 other methods Class AB - 10 common Class A extends AB => 10 methods Class B extends AB => 5 methods // Global variables => can be accessed/updated from anywhere var Test = function(options) { x = 1; return { welcome: function() { } } } // Person is class, age is field, karthik is object if age is public => karthik.age if age is private => karthik.age will be undefined if age is global => age var Calculator = function(options) { // private variable var token = options.token; // private function var log = function(value) { console.log(' Result is ' + value); } // global variable pi = 3.14; // global function getFramework = function() { console.log('Calculator'); } return { // public variable version: 1.0, // public functions add: function(x, y) { var z = x + y; log(z); return z; }, sub: function(x, y) { var z = x - y; log(z); return z; }, isExpired: function() { } } }
from pathlib import Path import sys path_root = Path(__file__).parents[1] sys.path.append(str(path_root)) from requirements import * class Standard_Scaler(): def __init__(self): self.fit_used = False def fit(self, X): X = self.check_X(X=X) X = self.check_for_object_columns(X=X) self.mean = np.mean(X, axis=0) self.std = np.std(X, axis=0) self.fit_used = True def fit_transform(self, X): X = self.check_X(X=X) X = self.check_for_object_columns(X=X) self.mean = np.mean(X, axis=0) self.std = np.std(X, axis=0) self.fit_used = True return (X-self.mean)/self.std def transform(self, X): self.check_fit(fit_used=self.fit_used) X = self.check_X(X=X) X = self.check_for_object_columns(X=X) return (X-self.mean)/self.std def inverse_transform(self, X): self.check_fit(fit_used=self.fit_used) return X*self.std.T+self.mean.T def check_X(self, X): if not isinstance(X, pd.DataFrame) and not isinstance(X, pd.Series) and not isinstance(X, np.ndarray) and not torch.is_tensor(X): raise TypeError('Wrong type of X. It should be pandas DataFrame, pandas Series, numpy array or torch tensor.') X = np.array(X) if(X.ndim == 1): X = X[None, :] return X def check_for_object_columns(self, X): if not isinstance(X, pd.DataFrame): X = pd.DataFrame(X) if X.select_dtypes(include=np.number).shape[1] != X.shape[1]: raise TypeError('Your data contains object or string columns. Numeric data is obligated.') return np.array(X) def check_fit(self, fit_used): if fit_used == False: raise AttributeError('Standard_Scaler has to be fitted first.')
library(MASS) summary(Cars93) str(Cars93) attach(Cars93) newPrice = cut(Price, c(0, 12, 20, max(Price))) levels(newPrice) = c("Cheap", "Okay", "Expensive") newMPG = cut(MPG.highway, c(0, 20, 30, max(MPG.highway))) levels(newMPG) = c("Gas Guzzler", "Okay", "Economic") table(Type) table(newPrice, Type) table(newPrice, Type, newMPG) #Barplot: Price levels per type barplot(table(newPrice, Type), beside = T) #Barplot: Types per price level barplot(table(Type, newPrice), beside = T) #Boxplot: Types per price level boxplot(Price~Type, col = rainbow(6)) summary(Price) #Multiple boxplots pairs(data.frame(Price, Type, MPG.highway))
// @ts-check // // The line above enables type checking for this file. Various IDEs interpret // the @ts-check directive. It will give you helpful autocompletion when // implementing this exercise. /** * Removes duplicate tracks from a playlist. * * @param {string[]} playlist * @returns {string[]} new playlist with unique entries */ export function removeDuplicates(playlist) { return Array.from(new Set(playlist)); // return playlist.filter((song, index) => playlist.indexOf(song) === index); } /** * Checks whether a playlist includes a track. * * @param {string[]} playlist * @param {string} track * @returns {boolean} whether the track is in the playlist */ export function hasTrack(playlist, track) { return playlist.includes(track); } /** * Adds a track to a playlist. * * @param {string[]} playlist * @param {string} track * @returns {string[]} new playlist */ export function addTrack(playlist, track) { const newPlaylist = new Set(playlist); newPlaylist.add(track); return Array.from(newPlaylist); } /** * Deletes a track from a playlist. * * @param {string[]} playlist * @param {string} track * @returns {string[]} new playlist */ export function deleteTrack(playlist, track) { const newPlaylist = new Set(playlist); newPlaylist.delete(track); return Array.from(newPlaylist); } /** * Lists the unique artists in a playlist. * * @param {string[]} playlist * @returns {string[]} list of artists */ export function listArtists(playlist) { // <SONG> - <ARTIST> const artists = playlist.map(song => song.split(" - ")[1]); return Array.from(new Set(artists)); }
import { ErrorEventLike, CloseEventLike, MessageEventLike, ListenersMap, ReadyState, RetransmittingWebSocketEventMap as WebSocketEventMap, WebSocketEventListenerMap, WebSocketLike, EventLike, } from '../retransmitting-websocket/src/RetransmittingWebSocket.ts' import * as messages from "../messages.ts"; import { WebSocketBase } from '../websocketbase.ts' export class PassiveLogicalWebSocket extends WebSocketBase { public readonly channelUUID: string; private readonly orderedSend: messages.BccMsgSender; readonly handleDisorderdBccMsg: messages.BccMsgConsumer; constructor(channelUUID: string, lowLevelSend: messages.BccMsgConsumer) { super(); this.channelUUID = channelUUID; this.handleDisorderdBccMsg = messages.createOrderedReceiver(this.handleBccMsg.bind(this), channelUUID); this.orderedSend = messages.createOrderedSender(lowLevelSend, channelUUID); } close(code = 1000, reason = ''): void { super.close(code, reason); this.orderedSend(messages.BccMsgType.CLOSE_INBOUND, {code, reason}); } send(dataBody: ArrayBufferLike | string): void { this.orderedSend(messages.BccMsgType.DATA_INBOUND, dataBody); } private handleBccMsg(message: messages.BccMsg) { switch(message.type) { case messages.BccMsgType.NEW: { this.orderedSend(messages.BccMsgType.CREATED, undefined); this._readyState = ReadyState.OPEN; const wsEvent: EventLike = { type: 'open', target: this }; this.triggerEvent(wsEvent); break; } case messages.BccMsgType.DATA_OUTBOUND: { const data = messages.getBccMsgData<messages.BccMsgType.DATA_OUTBOUND>(message); const wsEvent: MessageEventLike = { type: 'message', target: this, data, }; this.triggerEvent(wsEvent); break; } case messages.BccMsgType.CLOSE_OUTBOUND: { const closeMsg = messages.getBccMsgData<messages.BccMsgType.CLOSE_OUTBOUND>(message); this.orderedSend(messages.BccMsgType.CLOSED_INBOUND, undefined); this.closeInternal({ type: 'close', code: closeMsg.code, reason: closeMsg.reason, target: this, wasClean: true, }); break; } case messages.BccMsgType.CLOSED_OUTBOUND: { if (this.pendingCloseEvent) this.closeInternal(this.pendingCloseEvent); break; } } } get config(): { closeTimeoutMs: number, } { return { closeTimeoutMs: 1000, }; }; }
import React, { useState, useCallback } from 'react'; export function ListComponent() { const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']); const handleDelete = useCallback(itemToDelete => { setItems(prevItems => prevItems.filter(item => item !== itemToDelete)); }, []); return ( <div> {items.map(item => ( <ListItemComponent key={item} item={item} onDelete={handleDelete} /> ))} </div> ); } function ListItemComponent({ item, onDelete }) { return ( <div> <span>{item}</span> <button onClick={() => onDelete(item)}>Delete</button> </div> ); }
""" URL configuration for backend project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/5.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from application import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.bookView.as_view(),name='bookview'), path('contact',views.contactView.as_view(),name='contactView'), path('subscriber',views.subscribeView.as_view(),name='subscribeView'), path('review',views.reviewView.as_view(),name='reviewView'), path('register',views.registerView.as_view(),name='registerView'), path('login',views.userloginView.as_view(),name='loginView'), path('appointment',views.appointmentView.as_view(),name='appointmentView'), path('deletebook/<ID>',views.deletebook.as_view(),name='deletebook') ]
<x-modal.modal id="product_type_create_modal"> <x-slot name="title">@lang('globals/words.product_type')</x-slot> <x-slot name="body"> <x-form.form id="product_type_create_form"> <div class="row row-cols-1"> <x-form.input name="name" :label="trans('globals/words.name')" :placeholder="trans('globals/words.name')" required/> <x-form.input name="initial_code" :label="trans('globals/words.initial_code')" :placeholder="trans('globals/words.initial_code')" required/> </div> <x-form.button>@lang('globals/words.save')</x-form.button> </x-form.form> </x-slot> </x-modal.modal> @push('customscripts') <script> const ProductTypeCreateTemplate = function () { const create_modal = $("#product_type_create_modal"); const validations = { name: { validators: { notEmpty: { message: "@lang('globals/validation_messages.required', ['field_name' => trans('globals/words.name')])" }, stringLength: { min: 3, message: "@lang('globals/validation_messages.min', ['field_name' => trans('globals/words.name'), 'min' => 3])" } } }, initial_code: { validators: { notEmpty: { message: "@lang('globals/validation_messages.required', ['field_name' => trans('globals/words.initial_code')])" } } } }; const formValidated = (form) => { let data = $(form).serializeArray(); $.ajax({ url: "{{ route('product_type.store') }}", type: "POST", data: data, success: function (data) { create_modal.modal("hide"); ProductTypeIndexTemplate.initData(); toastr.success("@lang('globals/success_messages.success', ['attr' => trans('globals/words.product_type')])"); }, error: function () { toastr.error("@lang('globals/error_messages.save_error', ['attr' => trans('globals/words.product_type')])"); } }); } LugatApp.validateBasicForm("product_type_create_form", validations, formValidated); return {}; }(); </script> @endpush
/********************************************************************* * Project: Electrical Contact Monitoring * Author: Zac Lynn * Date: 4/26/2022 * Description: This code uses the yxml and SD libraries to read and * save data on an SD card. ********************************************************************/ #ifndef MY_LIBRARY_H #define MY_LIBRARY_H #include <Arduino.h> #include <SPI.h> #include <SD.h> #include "yxml.h" #define FLOAT_TO_LONG 10000000 // Scalar used to convert float to uint32_t for the purpose of writing to bin file more efficiently /***************** Configuration Variable *****************/ #define ZONES 10 // Sets the maximum number of voltage zones allowed in a contact config. Example sliding contacts may have one contact with 5 distinct zones /**********************************************************/ class SD_Lib { private: File data_out; // File pointer to output binary file public: byte *buffer; uint32_t write_count; // If MIN_VOLTAGE_CHANGE <= 4.8mv this represents number of rows in an excel file. Used to limit files based on row count uint32_t byte_count; // Counts how many bytes have been written to the current file. Used to limit files based on size uint8_t INCH; // Number of ADC input channels // Contact structure to hold contact configuration and data to save struct contact{ // Variables to write to sd card uint8_t group; // Unique group ID for each contact uint32_t timestamp; uint32_t voltage; uint8_t state; // State is pressed(1) or unpressed(0) based on voltage_range[2] // Config Variables uint32_t voltage_range[ZONES][2]; uint8_t pin; // other uint8_t voltage_zones; // Stores how many voltage zones, and thus states, are used }; /********************************************************************* * Function: SD_Lib * Description: This function initializes the member variables used * for configuration. * * Param: NONE * Return: NONE ********************************************************************/ SD_Lib(); /********************************************************************* * Function: SD_allocate_buffer * Description: This function allocates the main data buffer. Done * seperately from constructor so that more free memory * exists during setup and buffer size can be maximized. * * Param: NONE * Return: NONE ********************************************************************/ void SD_allocate_buffer(); /********************************************************************* * Function: SD_open * Description: This function tries to open a file with the given name * on an SD card. Enters an infinite loop if fails to * open file. * * Param: String (filename) - name of file to open * Return: int true if file opened, false if file could not be opened ********************************************************************/ int SD_open(String filename, int status_pin); /********************************************************************* * Function: SD_close * Description: This closes the open SD file. The file should always * be closed before removing power from the Arduino in * order to prevent data corruption. * * Param: NONE * Return: NONE ********************************************************************/ bool SD_close(uint16_t *flush_count, int last_flush_count); /********************************************************************* * Function: SD_save_bin * Description: This function checks if the main buffer has at least * 512 bytes in it, and writes a 512 byte block to * the SD card if it can. * * Param: contact* (contact_list) - list of contact structs * uint16_t* (flush_count) - current index in main buffer * Return: NONE ********************************************************************/ bool SD_save_bin(contact *contact_list, uint16_t *flush_count); /********************************************************************* * Function: SD_read_config * Description: This function reads the config file and copies the * configurations to the contact_list array. * * Param: int (cs) - Pin to use as chip select for SPI SD card * Param: uint8_t (status_pin) - LED pin number * Param: contact* (contact_list) - Array of contact structs * Return: NONE ********************************************************************/ void SD_read_config(int cs, uint8_t status_pin, contact *contact_list); /********************************************************************* * Function: decode_config * Description: This function parses the xml file using the yxml * library. * * Param: yxml_t* (x) - main yxml struct. See yxml.h for info * Param: yxml_ret_t (r) - yxml return token. See yxml.h for info * Param: contact* (contact_list) - list of contact structs * Return: NONE ********************************************************************/ void decode_config(yxml_t *x, yxml_ret_t r, contact *contact_list); /********************************************************************* * Function: char_to_double * Description: This function converts a string to a double. Used by * decode_config to read in voltage range variables. * * Param: char* (buf) - string to convert to double * Param: int (index) - length of char buffer * Return: double - the double equivelant of the provided str ********************************************************************/ double char_to_double(char *buf, int index); }; #endif
import React from "react"; import { Swiper, SwiperSlide } from "swiper/react"; import SwiperCore, { Navigation } from "swiper"; import "swiper/swiper.scss"; import "swiper/components/navigation/navigation.scss"; import { withTranslation } from "react-i18next"; import Skeleton from "react-loading-skeleton"; import FunandLearnIntro from "./FunandLearnIntro"; import { t } from "i18next"; import { GrFormNext, GrFormPrevious } from "react-icons/gr"; SwiperCore.use([Navigation]); const FunandLearnSlider = (data) => { const swiperOption = { loop: false, speed: 750, spaceBetween: 20, slidesPerView: 6, navigation: true, breakpoints: { 0: { slidesPerView: 1, }, 768: { slidesPerView: 3, }, 992: { slidesPerView: 4, }, 1200: { slidesPerView: 4, }, }, autoplay: false, }; return ( <React.Fragment> <div className="subcat__slider__context"> <div className="container"> <div className="row"> <div className="quizplay-slider"> {data.funandlearningloading ? ( <div className="text-center"> <Skeleton count={5}/> </div> ) : ( <> {data.data ? ( <Swiper {...swiperOption} navigation={{ prevEl: ".swiper-button-prev", nextEl: ".swiper-button-next", }}> {data.data.length > 0 && data.data.map((Fundata, key) => { return ( <SwiperSlide key={key}> <FunandLearnIntro data={Fundata} url={data.url} funandlearn={Fundata.id} active={data.selected && data.selected.id == Fundata.id ? "active-one" : "unactive-one"}/> </SwiperSlide> ); })} </Swiper> ) : ( <div className="text-center mt-4 commonerror"> <img src={process.env.PUBLIC_URL + "/images/error/error.svg"} title="wrteam" className="error_img"/> <p>{t("No Data found")}</p> </div> )} </> )} {/* Previous Button */} <div className="swiper-button-prev"> <GrFormPrevious /> </div> {/* Next Button */} <div className="swiper-button-next"> <GrFormNext /> </div> </div> </div> </div> </div> </React.Fragment> ); }; export default withTranslation()(FunandLearnSlider);
import torch import torch.nn as nn import torch.nn.functional as F class MIL(nn.Module): def __init__(self, in_dim=1, num_classes=2, **kwargs): super(MIL, self).__init__() self.num_classes = num_classes self.feature_extractor_part1 = nn.Sequential( nn.Conv2d(in_dim, 20, kernel_size=5), nn.ReLU(), nn.MaxPool2d(2, stride=2), nn.Conv2d(20, 50, kernel_size=5), nn.ReLU(), nn.MaxPool2d(2, stride=2) ) self.feature_extractor_part2 = nn.Sequential( nn.Linear(50 * 4 * 4, 500), nn.ReLU(), ) self.num_features = 500 self.classifier = nn.Linear(500, self.num_classes) def forward(self, x, only_feat=False): # TODO: check this batch_size = x.shape[0] x = x.squeeze(0) H = self.feature_extractor_part1(x) H = H.view(batch_size, -1) H = self.feature_extractor_part2(H) # NxL if only_feat: return H Y_prob = self.classifier(H) # Y_hat = torch.ge(Y_prob, 0.5).float() # return Y_prob, Y_hat, A return Y_prob class MILAttention(nn.Module): def __init__(self, in_dim=1, num_classes=2, **kwargs): super(MILAttention, self).__init__() self.L = 500 self.D = 128 self.K = 1 self.num_classes = num_classes self.feature_extractor_part1 = nn.Sequential( nn.Conv2d(in_dim, 20, kernel_size=5), nn.ReLU(), nn.MaxPool2d(2, stride=2), nn.Conv2d(20, 50, kernel_size=5), nn.ReLU(), nn.MaxPool2d(2, stride=2) ) self.feature_extractor_part2 = nn.Sequential( nn.Linear(50 * 4 * 4, self.L), nn.ReLU(), ) self.attention = nn.Sequential( nn.Linear(self.L, self.D), nn.Tanh(), nn.Linear(self.D, self.K) ) self.classifier = nn.Linear(self.L*self.K, 2) def forward(self, x): x = x.squeeze(0) H = self.feature_extractor_part1(x) H = H.view(-1, 50 * 4 * 4) H = self.feature_extractor_part2(H) # NxL A = self.attention(H) # NxK A = torch.transpose(A, 1, 0) # KxN A = F.softmax(A, dim=1) # softmax over N M = torch.mm(A, H) # KxL Y_prob = self.classifier(M) return Y_prob class MILGatedAttention(nn.Module): def __init__(self, in_dim=1, num_classes=2, **kwargs): super(MILGatedAttention, self).__init__() self.L = 500 self.D = 128 self.K = 1 self.feature_extractor_part1 = nn.Sequential( nn.Conv2d(in_dim, 20, kernel_size=5), nn.ReLU(), nn.MaxPool2d(2, stride=2), nn.Conv2d(20, 50, kernel_size=5), nn.ReLU(), nn.MaxPool2d(2, stride=2) ) self.feature_extractor_part2 = nn.Sequential( nn.Linear(50 * 4 * 4, self.L), nn.ReLU(), ) self.attention_V = nn.Sequential( nn.Linear(self.L, self.D), nn.Tanh() ) self.attention_U = nn.Sequential( nn.Linear(self.L, self.D), nn.Sigmoid() ) self.attention_weights = nn.Linear(self.D, self.K) self.classifier = nn.Linear(self.L*self.K, 2) def forward(self, x): x = x.squeeze(0) H = self.feature_extractor_part1(x) H = H.view(-1, 50 * 4 * 4) H = self.feature_extractor_part2(H) # NxL A_V = self.attention_V(H) # NxD A_U = self.attention_U(H) # NxD A = self.attention_weights(A_V * A_U) # element wise multiplication # NxK A = torch.transpose(A, 1, 0) # KxN A = F.softmax(A, dim=1) # softmax over N M = torch.mm(A, H) # KxL Y_prob = self.classifier(M) return Y_prob def lenet5(**kwargs): model = MIL(**kwargs) return model def lenet5_c3(**kwargs): model = MIL(in_dim=3, **kwargs) return model def attn_lenet5(**kwargs): model = MILAttention(**kwargs) return model def gated_attn_lenet5(**kwargs): model = MILGatedAttention(**kwargs) return model
import React, { useEffect, useState } from "react" import { useDispatch, useSelector } from "react-redux" import ExpenseDataList from "./ExpenseDataList" import { startUpdateUser } from "../actions/budgetAction" const ExpenseData = (props) => { const { formSubmission , editId } = props console.log(editId) const dispatch = useDispatch() const expense = useSelector((state)=>{ return state.expense.expense }) const expenseFilter = expense.filter((exp)=>{ return exp._id === editId }) const map = expenseFilter.find((ele)=>{ return ele }) console.log(map) const [name , setName] = useState(map.name ? map.name :'') const [amount , setAmount] = useState(map.amount ? map.amount :'') const [categoryId , setCategoryId] = useState(map.categoryId ? map.categoryId : '') const [date , setDate] = useState(map.date ? map.date : '') const [_id , setId] =useState(map._id ? map._id : '') const data = useSelector((state)=>{ return state.category.category }) console.log("data" , data) // if(editId){ // console.log(map) // console.log("ExpenseFilter" , expenseFilter) // //useEffect(()=>{ // setName(map.name) // setAmount(map.amount) // setCategoryId(map.categoryId) // setDate(map.date) // setId(map._id) // //},[map.name , map.amount ,map.categoryId, map.date , map._id]) // } const handleNameChange = (e) => { setName(e.target.value) } const handleAmountChange = (e) => { setAmount(e.target.value) } const handleIdChange = (e) => { setCategoryId(e.target.value) } const handleDateChange = (e) => { setDate(e.target.value) } const handleSubmit = (e) => { e.preventDefault() const formData = { name : name , amount : amount , categoryId : categoryId , date : date } formSubmission(formData , map._id) setName('') setAmount('') setCategoryId('') setDate('') setId('') } return( <div> <form onSubmit={handleSubmit}> <label>Name</label><br /> <input type="text" value={name} onChange={handleNameChange} /><br/> <label>Amount</label><br/> <input type="text" value={amount} onChange={handleAmountChange} /><br/> <label>Select Category</label><br/> <select value={categoryId} onChange={handleIdChange}> <option value=''>Select</option> { data.map((ele)=>{ return <option key={ele._id} value={ele._id}> {ele.name} </option> }) } </select><br/> <label>Expense Date</label><br/> <input type="date" value={date} onChange={handleDateChange} /> <br/><br/> <input type="submit" /> </form> </div> ) } export default ExpenseData
import React from "react"; import { createBrowserRouter,RouterProvider } from "react-router-dom"; import Rootlayoutmain from "./componentsvidhya/Rootlayoutmain"; import Home from "./componentsvidhya/Home" import Login from "./componentsvidhya/Login"; import Logo from "./componentsvidhya/Logo"; import Mentoring from "./componentsvidhya/Mentoring"; import Practice from "./componentsvidhya/Practice"; import Jobs from "./componentsvidhya/Jobs"; import Courses from "./componentsvidhya/Courses"; import App3 from "./App3"; import Community from "./community/Community"; import Competetions from "./components/Competetions"; import Hackathons from "./components/Hackathons"; import Quizzes from "./components/Quizzes"; import Rootlayout from "./components/Rootlayout"; import Webdevelopment from "./courses/Webdevelopment"; import Programming from "./courses/Programming"; import Digitalmarketing from "./courses/Digitalmarketing"; import Communication from "./courses/Communication"; import Rootlayout2 from "./courses/Rootlayout2"; import { BiHome } from "react-icons/bi"; import Signup from "./componentsvidhya/Signup/Signup"; function App() { const router=createBrowserRouter( [ { path:'/', element:<Rootlayoutmain/>, children:[ { path:'/', element:<Home/> }, { path:'/Login', element:<Login/> }, { path:'/signup', element:<Signup/> }, { path:'/Logo', element:<Logo/> }, { path:'/compete', element:<Rootlayout/>, children:[ { path:'/compete', element:<Competetions/> }, { path:'Hackathons', element:<Hackathons/> }, { path:'Quizzes', element:<Quizzes/> } ] }, { path:'/Mentoring', element:<App3/> }, { path:'/Practice', element:<Practice/> }, { path:'/community', element:<Community/> }, { path:'/courses', element:<Rootlayout2/>, children:[ { path:'/courses', element:<Programming/> }, { path:'/courses/webdevelopment', element:<Webdevelopment/> }, { path:'/courses/digitalmarketing', element:<Digitalmarketing/> }, { path:'/courses/communication', element:<Communication/> } ] } ] } ] ) return ( <div className="App"> <RouterProvider router={router}/> </div> ); } export default App;
#ifndef n_ReactiveObject_H #define n_ReactiveObject_H /* * * nucleo/core/ReactiveObject.H -- * * Copyright (C) Nicolas Roussel * * See the file LICENSE for information on usage and redistribution of * this file, and for a DISCLAIMER OF ALL WARRANTIES. * */ #include <set> #include <list> #include <string> #include <utility> namespace nucleo { class ReactiveObject ; // --------------------------------------------------------- class Observable { private: static std::set<Observable*> _instances ; protected: int _pendingNotifications ; std::list<ReactiveObject*> _observers ; void notifyObservers(void) ; friend class ReactiveEngineImplementation ; public: Observable(void) ; static bool isAlive(Observable *o) { return (_instances.find(o)!=_instances.end()) ; } void addObserver(ReactiveObject *observer) ; void removeObserver(ReactiveObject *observer) ; virtual ~Observable() ; } ; // --------------------------------------------------------- class ReactiveObject : public Observable { protected: void selfNotify(void) ; virtual void react(Observable*) {} friend class ReactiveEngineImplementation ; public: void subscribeTo(Observable &o) { o.addObserver(this) ; } void subscribeTo(Observable *o) { if (o && isAlive(o)) o->addObserver(this) ; } void unsubscribeFrom(Observable &o) { o.removeObserver(this) ; } void unsubscribeFrom(Observable *o) { if (o && isAlive(o)) o->removeObserver(this) ; } } ; // --------------------------------------------------------- class WatchDog : public ReactiveObject { protected: Observable *obs ; bool notified ; void react(Observable *o) { if (obs==o) notified = true ; } public: WatchDog(Observable *o) : obs(o), notified(false) { subscribeTo(o) ; } ~WatchDog(void) { if (Observable::isAlive(obs)) unsubscribeFrom(obs) ; } bool sawSomething(void) { bool result = notified ; notified = false ; return result ; } } ; // --------------------------------------------------------- typedef std::pair<ReactiveObject*,Observable*> ReactivePair ; } #endif
import { RxCross2 } from "react-icons/rx"; import TaskForm from "./TaskForm"; import { updateTask } from "../features/boards/boardsSlice"; import { useDispatch, useSelector } from "react-redux"; import { selectTask } from "../features/boards/boardSelector"; import { setModalType } from "../features/modal/modalSlice"; import { motion } from "framer-motion"; const EditTaskModal = () => { const { id, description, title, subtasks, status } = useSelector(selectTask); const dispatch = useDispatch(); return ( <div className="modal-wrapper" > <motion.div initial={{ opacity: 0, scale: 0.5 }} animate={{ opacity: 1, scale: 1 }} className="modal add-task" > <header className="add-task__header"> <h1 className="add-task__title">Edit task</h1> <button className="add-task__close" onClick={() => dispatch(setModalType(""))} > <RxCross2 /> </button> </header> <div className="container"> <TaskForm dispatchAction={updateTask} taskId={id} incomingValues={{ description: description, title: title, columnName: status, subtasks: subtasks, }} /> </div> </motion.div> </div> ); }; export default EditTaskModal;
// https://start.spring.io/#!type=maven-project&language=java&platformVersion=3.2.5&packaging=jar&jvmVersion=17&groupId=me.rahulsingh&artifactId=springboot.rest.project&name=springboot.rest.project&description=RESTful%20APIs%20to%20get%20the%20students%20data&packageName=me.rahulsingh.springboot.rest.project&dependencies=web,data-jpa,mysql package me.rahulsingh.springboot.rest.project.student; import jakarta.persistence.*; import java.time.LocalDate; import java.time.Period; import java.util.Objects; @Entity @Table public class Student { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private Long id; private String name; private String email; private LocalDate dob; @Transient private Integer age; // Transient means the age field here will not be the column in the database. public Student() {} public Student(Long id, String name, String email, LocalDate dob) { this.id = id; this.name = name; this.email = email; this.dob = dob; } public Student(String name, String email, LocalDate dob) { this.name = name; this.email = email; this.dob = dob; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public LocalDate getDob() { return dob; } public void setDob(LocalDate dob) { this.dob = dob; } public Integer getAge() { return Period.between(this.dob, LocalDate.now()).getYears(); } public void setAge(Integer age) { this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Student student)) return false; return Objects.equals(name, student.name) && Objects.equals(email, student.email) && Objects.equals(dob, student.dob) && Objects.equals(age, student.age); } @Override public int hashCode() { return Objects.hash(id, name, email, dob, age); } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", email='" + email + '\'' + ", dob=" + dob + ", age=" + age + '}'; } }
package lah.spectre.interfaces; /** * Interface for objects that produces resources and call the corresponding listener when it is available for * processing. * * @author L.A.H. * * @param <K> * Type of key * @param <R> * Type of resource */ public interface IResourceSupplier<K, R> { /** * Interface for general object that consumes resources produced by {@link IResourceSupplier}. * * @author L.A.H. * * @param <P> * Type of progress report * @param <R> * Type of resource */ public static interface Listener<P, R> { void onComplete(R resource); void onProgress(P progress); } /** * Get the resource with the supplied key * * @param key * Key of the resource */ R getResource(K key) throws Exception; }
"use client"; import React from "react"; import useUser from "@/hooks/use-user"; import { getReferralLink } from "@/lib/utils"; import SignInMainButton from "../twa/sign-in-main-button"; import { useToast } from "../ui/use-toast"; const ReferralMbWrapper = () => { const { user } = useUser(); const { toast } = useToast(); const pageAction = () => { if (!user) { toast({ title: "Unauthenticated", description: "Please Sign In to view your points and link", variant: "destructive", }); return; } const referralLink = getReferralLink(user.id); navigator?.clipboard.writeText(referralLink).then(() => { toast({ title: "Referral link Copied", description: referralLink, }); }); }; return ( <SignInMainButton pageAction={pageAction} pageActionText={!user ? "Sign In" : "Invite Now"} /> ); }; export default ReferralMbWrapper;
import { configureStore, createSlice } from "@reduxjs/toolkit"; const tasksSlice = createSlice({ name: "tasks", initialState: [], reducers: { addTask: (state, action) => { const { id, description, isDone } = action.payload; state.push({ id, description, isDone }); }, toggleTask: (state, action) => { const { id } = action.payload; const task = state.find((task) => task.id === id); if (task) { task.isDone = !task.isDone; } }, editTask: (state, action) => { const { id, description } = action.payload; const task = state.find((task) => task.id === id); if (task) { task.description = description; } }, }, }); export const { addTask, toggleTask, editTask } = tasksSlice.actions; const store = configureStore({ reducer: tasksSlice.reducer, }); export default store;
import produce from "immer"; import { normalize, schema } from "normalizr"; import { AnyAction } from "redux"; import { Cast, CastShow, showCastType } from "../../Models/Cast"; import { NormalizedShow, Show } from "../../Models/showType"; import { CAST_LOADED, QUERY_CHANGE, SHOWS_LOADED, SINGLE_SHOW_LOADED, SINGLE_SHOW_LOADING, } from "../Action"; export type ShowState = { shows: NormalizedShow; query: string; query_shows: { [query: string]: number[] }; loading: boolean; cast: CastShow }; let initialShowState: ShowState = { shows: {}, query: "", query_shows: {}, cast: {}, loading: false, }; export function showReducer( showState = initialShowState, action: AnyAction ): ShowState { switch (action.type) { case QUERY_CHANGE: return produce(showState, (draft) => { draft.query = action.payload; draft.loading = true; }); case SHOWS_LOADED: return produce(showState, (draft) => { let responseData = action.payload as showCastType[]; let show:Show[] = responseData.map((item:showCastType)=>item.show); let castArray = []; for(let i =0 ;i<responseData.length;i++){ let showObj = { [responseData[i].show.id] : responseData[i].cast } castArray.push(showObj); } let ObjData = castArray.reduce((prev , current)=>{ return {...prev , ...current } },{}) let temp = Object.keys(ObjData).map((id)=>{ return { [id]: ObjData[+id].reduce((prev , current)=>{ return {...prev , [current.id] : current } },{}) } }) let finalCastData = temp.reduce((prev:CastShow , current)=>{ return {...prev , ...current}; },{}) draft.cast = finalCastData!; let showEntity = new schema.Entity("shows"); let NormalizedShow = normalize(show, [showEntity]); draft.query_shows[draft.query] = NormalizedShow.result; draft.shows = { ...draft.shows, ...NormalizedShow.entities.shows }; draft.loading = false; }); case SINGLE_SHOW_LOADING: return produce(showState, (draft) => { draft.loading = true; }); case SINGLE_SHOW_LOADED: return produce(showState, (draft) => { let show: Show = action.payload; draft.shows = { ...draft.shows, [show.id]: action.payload }; draft.loading = false; }); case CAST_LOADED: return produce(showState, (draft) => { let data = action.payload._embedded.cast; let personEntity = new schema.Entity("person"); let castEntity = new schema.Entity("cast", { person: personEntity }); let NormalizedCast = normalize(data, [castEntity]); draft.cast = {...draft.cast , [action.payload.id] : NormalizedCast.entities.person! } || {}; draft.loading = false; }); default: return showState; } }
<script setup lang="ts"> import { RouterLink, RouterView } from "vue-router"; import Axios from "../../Axios"; let isLoggedIn = false; // Check if token exists in local storage const token = localStorage.getItem("token"); if (token) { isLoggedIn = true; } // Function to handle logout const logout = async () => { try { localStorage.removeItem("token"); window.location.reload(); await Axios.post("/auth/logout"); isLoggedIn = false; } catch (error) { console.error(error); } }; </script> <template> <nav> <RouterLink to="/">الرئيسية</RouterLink> <RouterLink v-if="isLoggedIn" to="/favorites">المفضلة</RouterLink> <a v-if="isLoggedIn" @click="logout" style="cursor: pointer; color: black" onmouseover="this.style.color='white';" onmouseout="this.style.color='black';" > تسجيل خروج </a> <RouterLink v-else to="/auth">سجل الآن</RouterLink> </nav> <RouterView></RouterView> </template> <style scoped> nav { width: 90%; display: flex; justify-content: center; align-items: center; padding: 10px; background-color: white; flex-direction: row-reverse; } nav a { text-decoration: none; color: black; font-size: 16px; margin: 0 10px; padding: 5px 20px; border-radius: 4px; transition: background-color 0.3s ease; } nav a:hover { background-color: #555; color: white; } </style>
<script> import Layout from '../_components/_Layout.svelte'; import Header from '../_components/_Header.svelte'; import seoMetaTags from '$utils/seo/metaTags'; import Seo from '$components/Seo.svelte'; import { Highlight as HighlightLink, Standard as StandardLink } from '$elements/links'; const metaTags = ((title = 'What is an activity is it the same as a session or a room?') => ({ title, tags: seoMetaTags({ title, description: '', openGraph: { type: 'website', url: `https://that.us/support/join-activity` } }) }))(); </script> <Seo title={metaTags.title} tags={metaTags.tags} /> <Layout> <Header center={true}>What is an Activity?</Header> <section> <div class="prose prose-lg mx-auto text-gray-500"> <p> <strong>Activities</strong> are topic-based scheduled gatherings that anyone can create for any multitude of reasons in which anyone can join. An activity is simple, a video call in the browser with no tools required. Every Activity has a chat window, the ability to share your desktop, and enables your webcam and microphone. You choose the format that best suits the topic and the people in the conversation. </p> <h2>What makes a good Activity?</h2> <blockquote> <p> An activity's success shouldn't be graded on the number of people in attendance but rather the conversation which was had and the knowledge that was shared. </p> </blockquote> <p> Yes, anything can be an Activity. Activities are about the people involved and the conversation that will be had. They're meant to be dynamic and highly interactive. The topic and the user's problems should determine the format to allow everyone to learn together. So what can you do, well anything but here are a few things that have happened to date: </p> <ul> <li>Presentations</li> <li>User group meetings</li> <li>Virtual conferences</li> <li>Office Hours</li> <li>Code Reviews</li> <li>Design Reviews</li> <li>Interactive Workshops</li> <li>Q&A</li> <li>AMA</li> <li>Just Get Together and Chat</li> </ul> <div class="scale-90 transform text-center"> <figure> <img class="lazyload w-full rounded-lg shadow" src="/images/ActivityDetailExample.jpg" alt="" /> <figcaption>Example: product review and sprint planning Activity.</figcaption> </figure> </div> <h2>How long can an Activity be?</h2> <p> The length of an Activity is up to you. An Activity may be a short 30 minutes or last all day. We have seen quick 30-minute issue triage, to an entire weekend hackathon-type activity. It's entirely up to you and what you are trying to achieve. In the example above you will see our bi-weekly sprint review which typically lasts for an hour. </p> <h2>Who can create and who can join an Activity?</h2> <p> Anybody and Anybody! That's correct. Anyone with an active public THAT account is allowed to create an activity. As for joining, anyone with an active THAT account can join. </p> </div> <div class="mx-auto my-12 flex max-w-prose flex-col items-center justify-center lg:max-w-none"> <div class="flex space-x-4 text-base"> <StandardLink href="/support/">Getting Started</StandardLink> <HighlightLink href="/support/joining-an-activity/">Joining an Activity</HighlightLink> </div> </div> </section> </Layout>
// // Collection.swift // Dokusho // // Created by Stef on 21/12/2021. // import Foundation import GRDB public enum MangaCollectionFilter: String, Codable, Equatable, CaseIterable, DatabaseValueConvertible, Hashable { case onlyUnReadChapter = "Only Unread Chapter", all = "All", completed = "Only Completed" public init(rawValue: String) { switch rawValue.lowercased() { case "only unread chapter": self = .onlyUnReadChapter case "all": self = .all case "only completed": self = .completed default: self = .all } } } public struct MangaCollectionOrder: Codable, Equatable, DatabaseValueConvertible, Hashable { public enum Field: String, Codable, CaseIterable, DatabaseValueConvertible, Hashable { case unreadChapters = "By unread chapter", lastUpdate = "By last update", title = "By title", chapterCount = "By chapter count" public init(rawValue: String) { switch rawValue.lowercased() { case "by unread chapter": fallthrough case "unreadchapters": self = .unreadChapters case "by last update": fallthrough case "lastupdate": self = .lastUpdate case "by title": fallthrough case "title": self = .title case "by chapter count": fallthrough case "chaptercount": self = .chapterCount default: self = .lastUpdate } } } public enum Direction: String, Codable, CaseIterable, DatabaseValueConvertible, Hashable { case ASC = "Ascending", DESC = "Descending" public init(rawValue: String) { switch rawValue.lowercased() { case "ascending": fallthrough case "asc": self = .ASC case "descending": fallthrough case "desc": self = .DESC default: self = .ASC } } } public var field: Field = .lastUpdate public var direction: Direction = .DESC } public struct MangaCollection: Codable, Identifiable, Equatable, Hashable { public var id: UUID public var name: String public var position: Int public var filter: MangaCollectionFilter = .all public var order: MangaCollectionOrder = .init() public var useList: Bool? = false public init(id: UUID, name: String, position: Int, filter: MangaCollectionFilter? = nil, order: MangaCollectionOrder? = nil, useList: Bool? = nil) { self.id = id self.name = name self.position = position if let filter = filter { self.filter = filter } if let order = order { self.order = order } if let useList = useList { self.useList = useList } } } extension MangaCollection: FetchableRecord, PersistableRecord {} extension MangaCollection: TableRecord { public static let mangas = hasMany(Manga.self) public enum Columns { public static let id = Column(CodingKeys.id) public static let name = Column(CodingKeys.name) public static let position = Column(CodingKeys.position) public static let filter = Column(CodingKeys.filter) public static let order = Column(CodingKeys.order) public static let useList = Column(CodingKeys.useList) } public static let databaseSelection: [SQLSelectable] = [ Columns.id, Columns.name, Columns.position, Columns.filter, Columns.order, Columns.useList ] } public extension DerivableRequest where RowDecoder == MangaCollection { func orderByPosition() -> Self { order( RowDecoder.Columns.position.ascNullsLast, RowDecoder.Columns.name.collating(.localizedCaseInsensitiveCompare).asc ) } } public extension MangaCollection { static func fetchOrCreateFromBackup(db: Database, backup: Self) throws -> MangaCollection { if let collection = try MangaCollection.fetchOne(db, id: backup.id) { return collection } return try MangaCollection(id: backup.id, name: backup.name, position: backup.position, filter: backup.filter, order: backup.order, useList: backup.useList).saved(db) } }
--- title: "R 関数の基本" --- # R 関数の基本 関数をつくることにより、`r fontawesome::fa(name = "r-project")` での作業がとても楽になります。 コードを繰り返して使うなら関数をつくりましょう。 ## 関数の作り方 **R の関数に 2 つのパーツがあります。** * **Arguments**: 引数 * **Code block**: 関数のコードは `{}` の間に納めます。 ```{r} #| error: true #| hello = function(x) { if(!is.character(x)) { stop("Please provide a character string.") } sprintf("Hello %s!", x) } hello(214) hello("Yukio") ``` ## 関数のスコープ (scope)(1) 関数の中に作ったものは、関数の中にしか存在しない。 ```{r} #| echo: false set.seed (2021) ``` ```{r} #| echo: true sumofsquare = function(x) { ss = (x - mean(x))^2 # 関数の外から見れない ssq = sum(ss) # 関数の外から見れない ssq # 関数の外に返す } data = sample(1:10, 5, replace = TRUE) data value = sumofsquare(data) value ``` ## 関数のスコープ (scope)(2) ところが、関数は外の環境に存在するものは見れます。 このように関数を作ると、バグを起こしやすいので、注意。 ```{r, error = TRUE} #| echo: true sumofsquare = function(x) { ss = (s - mean(s))^2 # s は関数の外にあるが、関数の引数ではない ssq = sum(ss) # 関数の外から見れない ssq # 関数の外に返す } s = sample(100:1000, 5, replace = TRUE) s data = sample(1:10, 5, replace = TRUE) data value = sumofsquare(data) value # これは s の平方和です。 ``` ## 諸略した関数の書き方と無名関数 (anonymous function) 関数は次のようにもかけます。 `\(x){...}` はラムダ式 (lambda expression) とも呼ばれています。 ```{r} add_one = \(x) { x + 1} add_one(5) ``` 無名関数をつくるときに便利な書き方です。 ```{r} # どちれも無名関数ですが、2つ目の関数がはラムダ式です。 z = 1:5 sapply(z, FUN = function(s){s^2}) sapply(z, FUN = \(s){s^2}) ```
/** * * #license-begin# * MIT License * * Copyright (c) 2005 - 2022 admaDIC GbR - http://www.admadic.de/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * #license-end# * * $Id$ */ package de.admadic.calculator.modules.matrx.ui; import java.util.Locale; /** * @author Rainer Schwarze * */ public class FloatingPointFormatter { String formatString; Locale locale; static final FloatingPointFormatter FPF_SIMPLE = createSimpleFormatter(); /** * No direct constructor calls. */ private FloatingPointFormatter() { super(); } /** * No direct constructor calls. * @param fmtStr * @param locale */ private FloatingPointFormatter(String fmtStr, Locale locale) { super(); this.formatString = fmtStr; this.locale = locale; } /** * @return Returns a simple formatter. */ public static FloatingPointFormatter getSimpleFormatter() { return FPF_SIMPLE; } /** * @return Returns a simple formatter. */ public static FloatingPointFormatter createSimpleFormatter() { FloatingPointFormatter mf = new FloatingPointFormatter(); return mf; } /** * @param fmtStr * @param locale * @return Returns the formatter for the given parameters. */ public static FloatingPointFormatter createFormatter(String fmtStr, Locale locale) { FloatingPointFormatter mf = new FloatingPointFormatter(fmtStr, locale); return mf; } /** * @param v * @return Returns the value as String. */ public String format(Double v) { if (v==null) return null; if (formatString==null) return v.toString(); return String.format(locale, formatString, v); } /** * @return Returns the formatString. */ public String getFormatString() { return formatString; } /** * @param formatString The formatString to set. */ public void setFormatString(String formatString) { this.formatString = formatString; } }
// // DataService.swift // SectionModelExample // // Created by Daisaku Ejiri on 2022/11/18. // import Foundation import RxRelay struct Parameter { let name: String let key: String let value: Float? let isOn: Bool? } enum FretboardOrientation: CaseIterable { case horizontal case vertical var name: String { switch self { case .horizontal: return "Horizontal" case .vertical: return "Vertical" } } } class DataService { static let shared = DataService() private init() { } private let settingsItemsRelay = BehaviorRelay<[SettingsViewSectionModel]>(value: []) // public method to get the section model relay public func getSettingsItems() -> BehaviorRelay<[SettingsViewSectionModel]> { let sections: [SettingsViewSectionModel] = [ onOrOffSection(), parameterSection(), ] settingsItemsRelay.accept(sections) return settingsItemsRelay } // get items per sections func parameterSection() -> SettingsViewSectionModel { let items: [SettingsItem] = [ .tempo, .guitarVolume, .metronomeVolume, ] return SettingsViewSectionModel(model: .parameter, items: items) } func onOrOffSection() -> SettingsViewSectionModel { let items: [SettingsItem] = [ .isFretboardVertical, .isMetronomeOn, ] return SettingsViewSectionModel(model: .onOrOff, items: items) } public static let isMetronomeOnKey = "Metronome_On" public static var isMetronomeOn: Parameter { Parameter(name: "Metronome On", key: DataService.isMetronomeOnKey, value: nil, isOn: UserDefaults.standard.bool(forKey: DataService.isMetronomeOnKey)) } public static let isFretboardVerticalKey = "Is_Fretboard_Vertical" public static var isFretboardVertical: Parameter { Parameter(name: "Vertical Fretboard", key: DataService.isFretboardVerticalKey, value: nil, isOn: UserDefaults.standard.bool(forKey: DataService.isFretboardVerticalKey)) } public static let tempoValueKey = "Tempo_Value" public static var tempoValue: Parameter { let value = UserDefaults.standard.integer(forKey: DataService.tempoValueKey) return Parameter(name: "Tempo", key: DataService.tempoValueKey, value: value != 0 ? Float(value) : 60, isOn: nil) } public static let guitarVolumeKey = "Guitar_Volume" public static var guitarVolume: Parameter { let value = UserDefaults.standard.float(forKey: DataService.guitarVolumeKey) return Parameter(name: "Guitar Volume", key: DataService.guitarVolumeKey, value: value != 0 ? value : 1.0, isOn: nil) } public static let metronomeVolumeKey = "Metronome_Volume" public static var metronomeVolume: Parameter { let value = UserDefaults.standard.float(forKey: DataService.metronomeVolumeKey) return Parameter(name: "Metronome Volume", key: DataService.metronomeVolumeKey, value: value != 0 ? value : 1.0, isOn: nil) } }
import { useContext } from "react"; import { useEffect } from "react"; import { NavLink } from "react-router-dom"; import { PostContext } from "../../context/PostContext"; import { Header } from "../../components/header/header"; import { Navbar } from "../../components/navbar/navbar"; import { SideBar } from "../../components/sidebar/sidebar"; import { AuthContext } from "../../context/AuthContext"; import "./bookmark.css"; import { EditPostModal } from "../../components/modals/editPostModal/editPost"; import { useState } from "react"; export const Bookmark = () => { const token = localStorage.getItem("encodedToken"); const { state, getBookmarks, removeBookmark, likePost, disLikePost, deletePost, bookmarkPost, showEditModal, setEditModal, } = useContext(PostContext); const { foundUser, authData } = useContext(AuthContext); const [showEdit, setShowEdit] = useState(false); console.log(state.bookmarkPost); useEffect(() => { getBookmarks(token); }, []); return ( <div className="bookmark-page"> <Header /> <Navbar /> <div className="bookmark-main-content"> <div className="no-bookmark"> {" "} {state.bookmarkPost.length === 0 && ( <h2>You haven't Bookmark any Post yet.</h2> )} </div> <div className="bookmark-list"> {" "} <div className=""> <ul> {state.bookmarkPost.map((item) => { const { content, id, likes, username, _id, content_img } = item; console.log(content_img); const currentUser = foundUser?.username; const islikedbyMe = likes?.likedBy?.find( (item) => item.username === foundUser.username ); const allusersData = authData?.allUsers; const userData = allusersData.filter( (data) => data.username === username )[0]; return ( <div className="white-bg mr-xxl p-xs mt-s"> <div className="flex flex-row nowrap p-xs" key={id}> <img src={userData.profile_pic} className="br-full width-xl height-xl p-xs mr-xs" /> <div> <div className="flex flex-row flex-align-center flex-space-between"> <div className="flex flex-row"> <p className="fw-semibold"> {userData.firstName + " " + userData.lastName} </p> <p className="grey-color pl-xs"> @{username}</p> </div> {currentUser === username && ( <div> {" "} {showEditModal && ( <EditPostModal img={content_img} content={content} profile_pic={userData.profile_pic} postId={_id} authorization={token} /> )} </div> )} {currentUser === username && ( <div className="dropdown"> <div className="drop-btn" onClick={() => setShowEdit((showEdit) => !showEdit) } > <i class="bi bi-three-dots"></i> </div> <div id={showEdit && "dropdown-menu"} className="dropdown-content" > <div className="dropdown-items" onClick={() => { deletePost(_id, token); setShowEdit(false); }} > Delete </div> <div className="dropdown-items" onClick={() => { setEditModal(true); setShowEdit(false); }} > Edit </div> </div> </div> )} </div> {content_img && ( <img src={content_img} alt="content" width="400" height="300" /> )} <p className="bookmark-post-content">{content}</p> <div className="flex flex-row nowrap flex-space-between pb-xs pt-m pr-s flex-align-center"> <div> {" "} <div onClick={() => { if (islikedbyMe) { disLikePost(_id, token); } else { likePost(_id, token); } }} > {islikedbyMe ? ( <i class="bi bi-suit-heart-fill red-clr like-btn"></i> ) : ( <i class="bi bi-heart like-btn"></i> )}{" "} {likes?.likeCount} </div>{" "} </div> <div> {state.bookmarkPost.find( (item) => item._id === _id ) ? ( <i className="bi bi-bookmark-fill bookmark-with-fill" onClick={() => removeBookmark(_id, token)} ></i> ) : ( <i class="bi bi-bookmark bookmark-btn" onClick={() => bookmarkPost(_id, token)} ></i> )} </div> <i className="bi bi-share share-btn"></i> </div> </div> </div> </div> ); })} </ul> </div> {/* {state.bookmarkPost.map((item) => { const { _id, username, content, likes } = item; // return ( // <div className="white-bg mr-xxl p-xs mt-s"> // <div className="flex flex-row nowrap p-xs" key={_id}> // <h3>{username}</h3> // <p>{content}</p> // <button onClick={() => removeBookmark(_id, token)}> // Remove Bookmark // </button> // </div> // </div> // ); })} */} </div> </div> <SideBar /> </div> ); };
/* * Copyright (C) 2014 Civilian Framework. * * Licensed under the Civilian License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.civilian-framework.org/license.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.civilian.asset; import java.io.File; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import org.junit.Test; import org.civilian.CivTest; import org.civilian.content.ContentType; import org.civilian.response.Response; import org.civilian.server.test.TestRequest; import org.civilian.server.test.TestResponse; import org.civilian.util.http.HeaderNames; public class AssetTest extends CivTest { @Test public void testBytesAsset() throws Exception { BytesAsset asset = new BytesAsset("UTF-8", "bytes"); assertTrue(asset.isValid()); assertTrue(asset.toString().startsWith("BytesAsset@")); assertEquals(5, asset.length()); assertSame(asset, asset.cache()); try { new BytesAsset("XYZ", "bytes"); } catch(IllegalStateException e) { assertTrue(e.getCause() instanceof UnsupportedEncodingException); } } @Test public void testUrlAsset() throws Exception { URL url = getClass().getResource("/java/lang/String.class"); UrlAsset asset = new UrlAsset(url); assertTrue(asset.isValid()); assertEquals(url.toString(), asset.toString()); try(InputStream in = asset.getInputStream()) { assertNotNull(in); } } @Test public void testCachedAsset() throws Exception { File file = File.createTempFile("test", ".css"); write(file, "UTF-8", "body"); try { FileAsset fileAsset = new FileAsset(file); Asset asset = fileAsset.cache(); assertTrue(asset instanceof CachedAsset); CachedAsset cached = (CachedAsset)asset; assertArrayEquals("body".getBytes(), cached.getContent()); assertSame(cached, cached.cache()); assertEquals(4, asset.length()); assertEquals(file.lastModified(), asset.getLastModified()); assertTrue(asset.isValid()); write(file, "UTF-8", "body{}"); assertFalse(asset.isValid()); } finally { assertTrue(file.getAbsolutePath(), file.delete()); } } @Test public void testContentEncodedAsset() throws Exception { ContentEncodedAsset asset = new ContentEncodedAsset(new TestAsset("content"), "br"); TestRequest request = new TestRequest(); TestResponse response = new TestResponse(request); asset.write(request, response, false); assertEquals("br", response.getHeaders().get(HeaderNames.CONTENT_ENCODING)); } @Test public void testLastModified() throws Exception { TestAsset asset = new TestAsset("content"); asset.setLastModified(10000L); assertEquals(10000L, asset.getLastModified()); asset.setLastModified(-50L); assertEquals(-1L, asset.getLastModified()); } @Test public void testWrite() throws Exception { TestAsset asset = new TestAsset("content"); asset.setCharEncoding("ISO-8859-1"); asset.setContentType(ContentType.TEXT_CSS); asset.setCacheControl(AssetCacheControl.DEFAULT); TestRequest request = new TestRequest(); TestRequest.Headers headers = request.getHeaders(); TestResponse response = new TestResponse(request); asset.setLastModified(10000); headers.setDate(HeaderNames.IF_MODIFIED_SINCE, 9500); asset.write(request, response, true); assertEquals("Thu, 01 Jan 1970 00:00:10 GMT", response.getHeaders().get(HeaderNames.LAST_MODIFIED)); assertEquals("max-age=2592000", response.getHeaders().get(HeaderNames.CACHE_CONTROL)); assertEquals(Response.Status.SC304_NOT_MODIFIED, response.getStatus()); response.reset(); headers.setDate(HeaderNames.IF_MODIFIED_SINCE, 8000); asset.write(request, response, true); assertEquals("Thu, 01 Jan 1970 00:00:10 GMT", response.getHeaders().get(HeaderNames.LAST_MODIFIED)); assertEquals("max-age=2592000", response.getHeaders().get(HeaderNames.CACHE_CONTROL)); assertEquals(ContentType.TEXT_CSS.getValue(), response.getContentType()); assertEquals("ISO-8859-1", response.getCharEncoding()); assertEquals(Response.Status.SC200_OK, response.getStatus()); assertEquals("content", response.getContentText(true)); } }
import random import pygame from ninety_nine import ninety_nine_state as game from ninety_nine import human_ai_main_game as game_display from ninety_nine.ninety_nine_state import Card from ninety_nine.constants import ( PlayerTypes, Rank, Suit, GameStage, NUM_CARDS_IN_BID, PLAYER_TYPES, NUM_TRICKS, NUM_PLAYERS, ) IMAGES_DIRECTORY_PATH = ( "/Users/Skyler/Coding/PythonPrograms/NinetyNine/ninety_nine/card_images" ) NUM_CARDS = NUM_CARDS_IN_BID + NUM_TRICKS HUMAN_PLAYER_NUM = 0 WINDOW_WIDTH = 1280 WINDOW_HEIGHT = 720 CARD_WIDTH = 131 CARD_HEIGHT = 186 CARD_INNER_BORDER = 5 BID_TOP = WINDOW_HEIGHT // 4 BID_LEFT = WINDOW_WIDTH // 2 HAND_TOP = WINDOW_HEIGHT - CARD_HEIGHT - 25 SPACE_BETWEEN_CARDS = WINDOW_WIDTH // 15 WIDTH_OF_FULL_HAND = (NUM_CARDS - 1) * SPACE_BETWEEN_CARDS + CARD_WIDTH CARD_OUTSIDE_HORIZONTAL_MARGIN = WINDOW_WIDTH - WIDTH_OF_FULL_HAND FULL_HAND_LEFT = CARD_OUTSIDE_HORIZONTAL_MARGIN // 2 BUTTON_WIDTH = 260 BUTTON_HEIGHT = 90 BUTTON_TOP = HAND_TOP - BUTTON_HEIGHT - 20 BUTTON_HORIZONTAL_CENTER = WINDOW_WIDTH // 2 BUTTON_LEFT = BUTTON_HORIZONTAL_CENTER - BUTTON_WIDTH // 2 TEXTVIEW_WIDTH = 360 TEXTVIEW_HEIGHT = 90 TEXTVIEW_TOP = 10 TEXTVIEW_LEFT = WINDOW_WIDTH - TEXTVIEW_WIDTH - 10 BID_MESSAGE_WIDTH = 90 BID_MESSAGE_HEIGHT = 90 BID_MESSAGE_TOP = 110 BID_MESSAGE_LEFT = WINDOW_WIDTH - BID_MESSAGE_WIDTH - 10 TRICKS_TAKEN_MESSAGE_WIDTH = 90 TRICKS_TAKEN_MESSAGE_HEIGHT = 90 TRICKS_TAKEN_MESSAGE_TOP = WINDOW_HEIGHT - TRICKS_TAKEN_MESSAGE_HEIGHT - 10 TRICKS_TAKEN_MESSAGE_LEFT = WINDOW_WIDTH - TRICKS_TAKEN_MESSAGE_WIDTH - 10 PRIMARY_TRICK_TOP = BID_TOP + 20 PRIMARY_TRICK_LEFT = WINDOW_WIDTH // 2 - CARD_WIDTH // 2 TRICK_POSITIONS = [ pygame.Rect(PRIMARY_TRICK_LEFT, PRIMARY_TRICK_TOP, CARD_WIDTH, CARD_HEIGHT), pygame.Rect( PRIMARY_TRICK_LEFT - CARD_WIDTH - 40, PRIMARY_TRICK_TOP - CARD_HEIGHT, CARD_WIDTH, CARD_HEIGHT, ), pygame.Rect( PRIMARY_TRICK_LEFT + CARD_WIDTH + 40, PRIMARY_TRICK_TOP - CARD_HEIGHT, CARD_WIDTH, CARD_HEIGHT, ), ] BLACK = (0, 0, 0) GREEN = (0, 53, 24) BLUE = (102, 178, 255) WHITE = (255, 255, 255) BACKGROUND_COLOR = GREEN BUTTON_COLOR = BLUE BUTTON_TEXT_COLOR = WHITE TEXTVIEW_COLOR = WHITE TEXTVIEW_TEXT_COLOR = BLACK MILLISECONDS_BETWEEN_PLAYS = 900 class TextView: def __init__(self): self.rect = pygame.Rect( TEXTVIEW_LEFT, TEXTVIEW_TOP, TEXTVIEW_WIDTH, TEXTVIEW_HEIGHT ) self.bg_color = (TEXTVIEW_COLOR,) self.text_color = (TEXTVIEW_TEXT_COLOR,) self.message = "Hello World" self.rendered_text = None self.render_message() def render_message(self, message=None): if message is None: message = self.message else: self.message = message self.rendered_text = pygame.font.SysFont("Arial", 35).render( message, True, self.text_color, self.bg_color ) class Button(TextView): def __init__(self): super().__init__() self.rect = pygame.Rect(BUTTON_LEFT, BUTTON_TOP, BUTTON_WIDTH, BUTTON_HEIGHT) self.bg_color = (BUTTON_COLOR,) self.text_color = (BUTTON_TEXT_COLOR,) self.message = "Confirm Bid" self.visible = False class ClickableCard(Card): def __init__(self, rank: Rank, suit: Suit): super().__init__(rank, suit) self.card_image = None self.clickable_area = pygame.Rect(0, HAND_TOP, SPACE_BETWEEN_CARDS, CARD_HEIGHT) self.display_area = pygame.Rect(0, HAND_TOP, CARD_WIDTH, CARD_HEIGHT) def set_left(self, left): self.clickable_area.left = left self.display_area.left = left def set_top(self, top): self.clickable_area.top = top self.display_area.top = top def get_card(self): return Card(self.rank, self.suit) def __repr__(self): return f"""ClickableCard(rank={self.rank}, suit={self.suit}, left={self.clickable_area.left}, top={self.clickable_area.top})""" def __eq__(self, other): if isinstance(other, ClickableCard): return ( super().__eq__(other) and self.clickable_area == other.clickable_area and self.display_area == other.display_area ) return False def main(): pygame.init() screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption("Ninety Nine") clock = pygame.time.Clock() while True: player_types = PLAYER_TYPES # display_welcome_message() images_dict = make_images_dict(game.get_all_cards()) game_state = game.GameState() num_players = NUM_PLAYERS human_player: game.Player = game_state.PLAYERS[HUMAN_PLAYER_NUM] trump_message = TextView() trump_message.rect = pygame.Rect( TEXTVIEW_LEFT, TEXTVIEW_TOP, TEXTVIEW_WIDTH, TEXTVIEW_HEIGHT ) trump_message.bg_color = TEXTVIEW_COLOR trump_message.text_color = TEXTVIEW_TEXT_COLOR trump_message.render_message( f"Trump Suit: {game_state.TRUMP_SUIT.name.capitalize()}" ) bid_message = TextView() bid_message.rect = pygame.Rect( BID_MESSAGE_LEFT, BID_MESSAGE_TOP, BID_MESSAGE_WIDTH, BID_MESSAGE_HEIGHT ) bid_message.bg_color = TEXTVIEW_COLOR bid_message.text_color = TEXTVIEW_TEXT_COLOR bid_message.render_message(f"{0}") tricks_taken_message = TextView() tricks_taken_message.rect = pygame.Rect( TRICKS_TAKEN_MESSAGE_LEFT, TRICKS_TAKEN_MESSAGE_TOP, TRICKS_TAKEN_MESSAGE_WIDTH, TRICKS_TAKEN_MESSAGE_HEIGHT, ) tricks_taken_message.bg_color = TEXTVIEW_COLOR tricks_taken_message.text_color = TEXTVIEW_TEXT_COLOR tricks_taken_message.render_message(f"{0}") sorted_hand = game_display.get_sorted_cards(human_player.hand) clickable_hand = get_clickable_cards(sorted_hand, images_dict) clickable_bid = get_clickable_cards(list(human_player.bid), images_dict) for player_num in range(num_players): if player_types[player_num] == PlayerTypes.RANDOM: game_display.get_random_bid(game_state.PLAYERS[player_num]) game_state, new_hand = do_bidding_loop( game_state, clickable_hand, clickable_bid, images_dict, screen, clock, trump_message, bid_message, ) game_state = do_playing_loop( game_state, new_hand, images_dict, screen, clock, trump_message, bid_message, tricks_taken_message, ) display_final_scores(screen, game_state, clock) def do_bidding_loop( game_state, clickable_hand, clickable_bid, images_dict, screen, clock, trump_message, bid_message, ): continue_button = Button() continue_button.render_message("Confirm Bid") human_player = game_state.PLAYERS[HUMAN_PLAYER_NUM] while game_state.stage == GameStage.BIDDING: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() raise SystemExit if event.type == pygame.MOUSEBUTTONUP: clicked_card = get_card_from_click( event.pos, clickable_hand + clickable_bid ) if clicked_card in clickable_hand: human_player.hand.remove(clicked_card.get_card()) human_player.bid.add(clicked_card.get_card()) if clicked_card in clickable_bid: human_player.bid.remove(clicked_card.get_card()) human_player.hand.add(clicked_card.get_card()) if clicked_card: sorted_hand = game_display.get_sorted_cards(human_player.hand) clickable_hand = get_clickable_cards(sorted_hand, images_dict) clickable_bid = get_clickable_cards( list(human_player.bid), images_dict ) new_bid_amount = game.bid_value(clickable_bid) bid_message.render_message(f"{new_bid_amount}") center_cards(clickable_hand) center_cards(clickable_bid, BID_TOP) if continue_button.visible and continue_button.rect.collidepoint( event.pos ): game_state.stage = GameStage.PLAYING continue_button.visible = False if len(human_player.bid) == 3: continue_button.visible = True else: continue_button.visible = False screen.fill(BACKGROUND_COLOR) draw_clickable_cards(screen, clickable_hand) draw_clickable_cards(screen, clickable_bid) if trump_message: draw_message(screen, trump_message) if bid_message: draw_message(screen, bid_message) if continue_button.visible: draw_button(screen, continue_button) pygame.display.flip() clock.tick(60) return game_state, clickable_hand def do_playing_loop( game_state, clickable_hand, images_dict, screen, clock: pygame.time.Clock, trump_message=None, bid_message=None, tricks_taken_message=None, player_types=PLAYER_TYPES, human_player_num=HUMAN_PLAYER_NUM, ): continue_button = Button() continue_button.render_message("Next trick") continue_button.visible = False center_cards(clickable_hand) time_of_next_play = pygame.time.get_ticks() + MILLISECONDS_BETWEEN_PLAYS while game_state.stage == GameStage.PLAYING: if ( pygame.time.get_ticks() > time_of_next_play and game_state.next_to_play == -1 ): # The player has just finished their turn game_state.next_to_play = 1 # process player inputs for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() raise SystemExit if event.type == pygame.MOUSEBUTTONUP: clicked_card = get_card_from_click(event.pos, clickable_hand) if ( game_state.next_to_play == HUMAN_PLAYER_NUM and clicked_card and clicked_card.get_card() in game.get_legal_card_plays(game_state, HUMAN_PLAYER_NUM) ): game_state = game.make_card_play( game_state, HUMAN_PLAYER_NUM, clicked_card.get_card() ) sorted_hand = game_display.get_sorted_cards( game_state.PLAYERS[human_player_num].hand ) clickable_hand = get_clickable_cards(sorted_hand, images_dict) center_cards(clickable_hand) time_of_next_play = ( pygame.time.get_ticks() + MILLISECONDS_BETWEEN_PLAYS ) if continue_button.visible and continue_button.rect.collidepoint( event.pos ): game_state = game.finish_trick(game_state) continue_button.visible = False # logical updates here if ( player_types[game_state.next_to_play] == PlayerTypes.RANDOM and pygame.time.get_ticks() > time_of_next_play ): card_to_play = random.choice( list(game.get_legal_card_plays(game_state, game_state.next_to_play)) ) game_state = game.make_card_play( game_state, game_state.next_to_play, card_to_play ) time_of_next_play = pygame.time.get_ticks() + MILLISECONDS_BETWEEN_PLAYS continue_button.visible = game.is_full(game_state.current_trick) if ( game.game_is_over(game_state) and pygame.time.get_ticks() > time_of_next_play ): game_state.stage = GameStage.DONE if tricks_taken_message: tricks_taken = game_state.PLAYERS[HUMAN_PLAYER_NUM].tricks_won tricks_taken_message.render_message(f"{tricks_taken}") # render graphics here screen.fill(BACKGROUND_COLOR) draw_clickable_cards(screen, clickable_hand) draw_trick(screen, game_state.current_trick, images_dict) if trump_message: draw_message(screen, trump_message) if bid_message: draw_message(screen, bid_message) if tricks_taken_message: draw_message(screen, tricks_taken_message) if continue_button.visible: draw_button(screen, continue_button) pygame.display.flip() clock.tick(60) return game_state def display_final_scores(screen, final_state, clock): final_scores = game.get_scores(final_state) continue_button = Button() continue_button.render_message("Start new game") continue_button.visible = True continue_button.rect.top += 80 while final_state.stage == GameStage.DONE: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() raise SystemExit if event.type == pygame.MOUSEBUTTONUP: if continue_button.visible and continue_button.rect.collidepoint( event.pos ): final_state.stage = GameStage.BIDDING continue_button.visible = False screen.fill(BACKGROUND_COLOR) score_bg_rect = pygame.Rect(0, 0, 600, 200) score_bg_rect.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 - 30) pygame.draw.rect(screen, TEXTVIEW_COLOR, score_bg_rect) scores_message = TextView() scores_message.rect.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 - 55) scores_message.render_message(f" Your score: {final_scores[0]} ") screen.blit(scores_message.rendered_text, scores_message.rect) scores_message = TextView() scores_message.rect.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 - 10) scores_message.render_message(f" Opponent 1: {final_scores[1]} ") screen.blit(scores_message.rendered_text, scores_message.rect) scores_message = TextView() scores_message.rect.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 35) scores_message.render_message(f" Opponent 2: {final_scores[2]} ") screen.blit(scores_message.rendered_text, scores_message.rect) if continue_button.visible: draw_button(screen, continue_button) pygame.display.flip() clock.tick(60) def draw_trick( screen: pygame.Surface, trick: game.Trick, images_dict, trick_positions=None, ): if trick_positions is None: trick_positions = TRICK_POSITIONS cards: dict = trick.cards for player, card in cards.items(): card_image = images_dict[card.suit.name.lower()][card.rank.name.lower()] screen.blit(card_image, trick_positions[player]) def draw_button(screen: pygame.Surface, button: Button): pygame.draw.rect(screen, button.bg_color, button.rect) text_rect = button.rendered_text.get_rect(center=button.rect.center) screen.blit(button.rendered_text, text_rect) def draw_message(screen: pygame.Surface, message: TextView): pygame.draw.rect(screen, message.bg_color, message.rect) text_rect = message.rendered_text.get_rect(center=message.rect.center) screen.blit(message.rendered_text, text_rect) def get_card_from_click(pos, all_cards: list[ClickableCard]): for card in all_cards: if card.clickable_area.collidepoint(pos): return card return None def make_images_dict(cards): images_dict = {} # make outer dictionary of suits for card in cards: images_dict[card.suit.name.lower()] = {} # fill inner dictionaries of ranks for card in cards: images_dict[card.suit.name.lower()][ card.rank.name.lower() ] = load_bordered_image_of_card(card) return images_dict def get_clickable_cards(cards: list, image_dict: dict): clickable_cards = [] for card_num, card in enumerate(cards): clickable_card = ClickableCard(card.rank, card.suit) clickable_card.card_image = image_dict[card.suit.name.lower()][ card.rank.name.lower() ] clickable_card.set_left(FULL_HAND_LEFT + card_num * SPACE_BETWEEN_CARDS) clickable_cards.append(clickable_card) return clickable_cards def center_cards( cards_to_center: list[ClickableCard], first_card_y: int = HAND_TOP, x_margin: int = SPACE_BETWEEN_CARDS, card_width: int = CARD_WIDTH, card_height: int = CARD_HEIGHT, ): num_cards = len(cards_to_center) spread_width = (num_cards - 1) * x_margin + card_width first_card_x = (WINDOW_WIDTH - spread_width) / 2 for card_num in range(num_cards): card_left = first_card_x + card_num * x_margin card_top = first_card_y cards_to_center[card_num].clickable_area = pygame.Rect( card_left, card_top, x_margin, card_height ) cards_to_center[card_num].display_area = pygame.Rect( card_left, card_top, card_width, card_height ) def draw_clickable_cards( screen: pygame.Surface, hand_cards: list[ClickableCard], ): for card in hand_cards: screen.blit( card.card_image, card.display_area, ) def get_images_from_cards(cards: list, image_dict: dict): images = [] for card in cards: images.append(image_dict[card.suit.name.lower()][card.rank.name.lower()]) return images def load_bordered_image_of_card( card: game.Card, width: int = CARD_WIDTH, height: int = CARD_HEIGHT, border: int = CARD_INNER_BORDER, ): image_filename = get_image_filename_from_card(card) raw_image = pygame.image.load(image_filename) shrunk_image = pygame.transform.scale( raw_image, (width - 2 * border, height - 2 * border) ) border_surface = pygame.Surface((width, height)) border_surface.fill("black") border_surface.blit(shrunk_image, (border, border)) return border_surface def get_image_filename_from_card(card: game.Card): image_rank = str(card.rank.name).lower() match image_rank: case "ten": image_rank = "10" case "nine": image_rank = "9" case "eight": image_rank = "8" case "seven": image_rank = "7" case "six": image_rank = "6" image_suit = str(card.suit.name).lower() return f"{IMAGES_DIRECTORY_PATH}/{image_suit}_{image_rank}.png" if __name__ == "__main__": main()
/* 6. Proyecto de pasatiempos • Descripción ◦ Para el desarrollo de un proyecto sobre pasatiempos, se tienen los siguientes ficheros: ▪ reservaMemoria.c • funciones para la reserva de memoria de diferentes estructuras de datos ▪ liberaMemoria.c • funciones para liberar memoria ▪ memoria.h • prototipos de las funciones de reserva y liberación de memoria ▪ ficheros.c – ficheros.h • funciones relacionadas con la E/S de datos en archivos y sus prototipos ▪ crucigrama.c – crucigrama.h • funciones específicas para la creación de crucigramas y sus prototipos ▪ main.c • programa que llama a las funciones de los crucigramas y ficheros ◦ El resultado final del proyecto será el ejecutable crucigrama.x que permitirá la creación de crucigramas. • Objetivo ◦ Crea un fichero makefile con las siguientes características: ▪ Construirá una biblioteca (libMemoria.a) a partir de los ficheros objeto (.o) de reservaMemoria.c y liberaMemoria.c. ▪ Construirá el ejecutable crucigrama.x a partir de la biblioteca y los ficheros objeto (.o) de main.c, ficheros.c y crucigrama.c ▪ Permitirá eliminar los ficheros objeto generados mediante un destino phony llamado clean. ▪ Incluirá un destino simbólico para generar el ejecutable y eliminar los ficheros objeto generados con una sola llamada a make. ▪ Para probarlo, puedes utilizar los ficheros que se encuentran en Moodle. */ /*! \file main.c \brief Programa principal que permite resolver un crucigrama \note Metodología de la Programación \note Práctica 4 \note Curso académico 2014-2015 */ #include <stdio.h> #include "ficheros.h" #include "memoria.h" #include "crucigrama.h" /*! \fn int main() \brief Programa principal */ int main(){ /* Comprueba si existe el fichero */ existeFichero(); /* Carga el fichero */ cargaFicheroBinario(); /* Reserva memoria para el crucigrama */ reservaCrucigrama(); /* Crea el crucigrama */ creaCrucigrama(); /* Imprime el crucigrama */ imprimeCrucigrama(); /* Se librera la memoria */ liberaCrucigrama(); return 0; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="style.css"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css"> <title>Photography</title> </head> <body> <nav class="navbar sticky-top bg-dark navbar-expand navbar-dark"> <div class="container"> <a href="#" class="navbar-brand"><img class="img-fluid img-responsive" src="images/TMD-01.png"></a> <div class="pe-5 text-align-center"> <ul class="navbar-nav"> <li class="nav-item"> <a href="portfolio.html" class="nav-link">Portfolio</a> </li> <li class="nav-item dropdown"> <a href="#services" class="nav-link " id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Services</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#studio">Studio Photoshoot</a></li> <li><a class="dropdown-item" href="#outdoor">Outdoor Photoshoot</a></li> <li><a class="dropdown-item" href="#event">Event Photoshoot</a></li> </ul> </li> <li class="nav-item"> <a href="enquire.html" class="nav-link">Enquire</a> </li> </ul> </div> </div> </nav> <section class="showcase h-25"> <div id="carouselExampleIndicators" class="carousel slide carousel-fade" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="images/studio.jpg" class= "img-fluid" alt=""> <div class="bg-dark rounded bg-opacity-50 carousel-caption d-none d-md-block "> <h3>Studio Photoshoot</h3> <p>We do studio photoshoot with 6 different backdrops.</p> </div> </div> <div class="carousel-item"> <img src="images/outdoor.jpg" class="d-block w-100" alt=""> <div class="bg-dark rounded bg-opacity-50 carousel-caption d-none d-md-block"> <h3>Outdoor Photoshoot</h3> <p>Pick a location outdoor we are mobile. We can shoot at parks, hotels and corporate buildings.</p> </div> </div> <div class="carousel-item"> <img src="images/wedding.jpg" class="d-block w-100" alt=""> <div class="bg-dark bg-opacity-50 rounded carousel-caption d-none d-md-block"> <h3>Wedding shoot</h3> <p>Pictures and video wedding shoot with an option to add a drone.</p> </div> </div> </div> </div> </section> <!--services--> <section id="studio services" class="p-5"> <div class="container"> <!--align-items-center is to for centering the text vertically--> <div class="row align-items-center justify-content-between"> <div class="col-sm"> <!--img-fluid makes sure the image stays in the container--> <img src="images/studio_001.jpg" class="img-fluid w-75 d-none d-md-block" alt=""> </div> <div class="col-md"> <h2>Studio Photoshoot</h2> <!--lead will make the paragraph text a bit bigger--> <p class="lead"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed do eiusmod tempor incididunt ut labore. </p> <fieldset class="row mb-3"> <div class="col-sm-10"> <div class="form-check"> <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked> <label class="form-check-label" for="gridRadios1"> 30 mins, 15 edited pictures </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="option2"> <label class="form-check-label" for="gridRadios2"> 1 hr, 30 edited pictures </label> </div> <div class="form-check disabled"> <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios3" value="option3"> <label class="form-check-label" for="gridRadios3"> 2 hrs, 50 edited pictures </label> </div> </div> </fieldset> <button type="button" class="btn btn-light mt-3" data-bs-toggle="modal" data-bs-target="#staticBackdrop"><i class="bi bi-chevron-right"></i> Book</button> </div> </div> </div> </section> <section id="outdoor" class="p-5 bg-dark text-light"> <div class="container"> <div class="row align-items-center"> <div class="col-md p-5 text-end"> <h2>Outdoor Photoshoot</h2> <p class="lead"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed do eiusmod tempor incididunt ut labore. </p> <fieldset class="row mb-3"> <div class=""> <div class="form-check"> <label class="form-check-label" for="gridRadios1"> 30 mins, 15 edited pictures </label> <input style = "float: right;" class="form-check-input ms-2" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked> </div> <div class="form-check"> <label class="form-check-label" for="gridRadios2"> 1 hr, 30 edited pictures </label> <input style = "float: right;"class="form-check-input ms-2" type="radio" name="gridRadios" id="gridRadios2" value="option2"> </div> <div class="form-check disabled"> <label class="form-check-label" for="gridRadios3"> 2 hrs, 50 edited pictures </label> <input style = "float: right;"class="form-check-input ms-2" type="radio" name="gridRadios" id="gridRadios3" value="option3"> </div> </div> </fieldset> <button type="button" class="btn btn-light mt-3" data-bs-toggle="modal" data-bs-target="#staticBackdrop"><i class="bi bi-chevron-right"></i> Book</button> </div> <div class="col-md"> <img src="images/outdoor_001.jpg" class="img-fluid w-75 d-none d-md-block" alt=""> </div> </div> </div> </section> <section id="event" class="p-5"> <div class="container"> <!--align-items-center is to for centering the text vertically--> <div class="row align-items-center justify-content-between"> <div class="col-md"> <!--img-fluid makes sure the image stays in the container--> <img src="images/event.jpg" class="img-fluid w-75 d-none d-md-block" alt=""> </div> <div class="col-md"> <h2>Event Photoshoot</h2> <!--lead will make the paragraph text a bit bigger--> <p class="lead"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed do eiusmod tempor incididunt ut labore. </p> <fieldset class="row mb-3"> <div class="col-sm-10"> <div class="form-check"> <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked> <label class="form-check-label" for="gridRadios1"> 3 hrs event, 150 edited pictures </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="option2"> <label class="form-check-label" for="gridRadios2"> Weddings all day event 250 edited pictures </label> </div> </div> </fieldset> <button type="button" class="btn btn-light mt-3" data-bs-toggle="modal" data-bs-target="#staticBackdrop"><i class="bi bi-chevron-right"></i> Book</button> </div> </div> </div> </section> <!--Photographers--> <section id="instructors" class="p-5 bg-dark"> <div class="container"> <h2 class="text-center text-white">Our Photographers</h2> <p class="lead text-center text-white mb-5"> Our photographers have 1+ years shooting experience in the industry </p> <div class="row g-4 justify-content-md-center"> <!--on medium screen the columns will take half of the screen--> <div class="col-md-6 col-lg-3"> <div class="card bd-light"> <div class="card-body text-center"> <!--random pictures--> <img src="https://randomuser.me/api/portraits/men/11.jpg" class="rounded-circle mb-3" alt=""> <h3 class="card-title mb-3">John Doe</h3> <p class="card-text"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> <a href="#"><i class="bi bi-twitter text-dark mx-1"></i></a> <a href="#"><i class="bi bi-facebook text-dark mx-1"></i></a> <a href="#"><i class="bi bi-linkedin text-dark mx-1"></i></a> <a href="#"><i class="bi bi-instagram text-dark mx-1"></i></a> </div> </div> </div> <div class="col-md-6 col-lg-3"> <div class="card bd-light"> <div class="card-body text-center"> <img src="https://randomuser.me/api/portraits/women/11.jpg" class="rounded-circle mb-3" alt=""> <h3 class="card-title mb-3">Jane Doe</h3> <p class="card-text"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> <a href="#"><i class="bi bi-twitter text-dark mx-1"></i></a> <a href="#"><i class="bi bi-facebook text-dark mx-1"></i></a> <a href="#"><i class="bi bi-linkedin text-dark mx-1"></i></a> <a href="#"><i class="bi bi-instagram text-dark mx-1"></i></a> </div> </div> </div> </div> </div> </section> <!--modal--> <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content container"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Book a shoot</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <!--modal form--> <div class="modal-body row g-3"> <div class="col-md-6"> <label class="form-label">Full name</label> <input type="text" name="clientName" placeholder="enter your full name" class="p-1"> </div> <div class="col-md-6"> <label class="form-label">Shoot date</label> <input type="date" name="shootDate" class="p-1"> </div> <div class="col-md-6"> <label class="form-label">Email</label> <input type="text" name="email" placeholder = "example@email.com" class="p-1"> </div> <div class="col-md-6"> <label class="form-label">Number phone</label> <input type="text" name="number" placeholder="+27......." class="p-1"> </div> <div class="col-md-12"> <label class="form-label">Shoot Brief</label> <div class="input-group"> <textarea class="form-control" aria-label="With textarea"></textarea> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Make booking</button> </div> </div> </div> </div> <footer class="p-5 bg-dark text-white text-center position-relative"> <div class="container"> <p class="lead">Copyright &copy; 2022 Frontend Bootcamp </p> </div> <p class="fw-light">Midrand innovation worx</p> <a href="#"><i class="bi bi-twitter text-light mx-1"></i></a> <a href="#"><i class="bi bi-facebook text-light mx-1"></i></a> <a href="#"><i class="bi bi-linkedin text-light mx-1"></i></a> <a href="#"><i class="bi bi-instagram text-light mx-1"></i></a> </footer> </body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </html>
\subsection{Komponenty wizualne} Biblioteka {\bf System.Windows.Forms} udostępnia szereg gotowych komponentów. Wszystkie właściwości obiektów są odpowiednimi składowymi klas opisujących te obiekty. Oprócz typowych składowych, przynależnych wszystkim obiektom dziedziczącym w klasy {\bf Control}, każdy komponent ma szereg własnych, jemu tylko właściwych składowych. Na przykład pole tekstowe ma właściwość {\bf MaxLength}, pozwalającą ustalić maksymalną długość wprowadzanego napisu, czy propercję {\bf AcceptsEnter}, decydującą o tym, czy naciśnięcie klawisza Enter w obrębie pola tekstowego dołączy do wprowadzanego tekstu znak przejścia do nowej linii, czy też spowoduje przejście do kolejnego komponentu w oknie. \subsubsection{ComboBox, ListBox} Oba komponenty, {\bf ComboBox} i {\bf ListBox}, mają bardzo podobne zastosowanie i bardzo podobny interfejs służący do oprogramowywania ich. Udostępniają one kolekcję {\bf Items}, która przechowuje elementy pokazywane na listach tych komponentów. W najprostszym scenariuszu napisalibyśmy po prostu: \begin{scriptsize} \begin{verbatim} ... ComboBox cbItems; ... cbItems.Add( "napis 1" ); cbItems.Add( "napis 2" ); cbItems.Add( "napis 3" ); ... \end{verbatim} \end{scriptsize} Pojawia się jednak pytanie: w jaki sposób aplikacja może być poinformowana o wyborze konkretnego elementu przez użytkownika? Przypomnijmy sobie, że na poziomie Win32API z każdym elementem {\bf ComboBoxa} można skojarzyć 32-bitową wartość, która może służyć do identyfikowania elementów (może na przykład przechowywać identyfikator bazodanowy elementu na liście)\footnote{Wartość tą można ustalić bądź pobrać za pomocą par komunikatów {\bf CB\_SETITEMDATA}, {\bf CB\_GETITEMDATA} oraz {\bf LB\_SETITEMDATA}, {\bf LB\_GETITEMDATA}.}. W bibliotece okienkowej .NET elementami ComboBoxa i ListBoxa mogą być dowolne obiekty, nie tylko napisy. Jeśli do listy zostaje dodany obiekt innego typu niż {\bf string}, na liście pojawia się jego reprezentacja napisowa, zaś na liście zapamiętana jest referencja do obiektu. Aby zasymulować możliwość jaką daje Win32API, czyli umieszczanie na liście napisów i kojarzenie z każdym z nich wartości 32-bitowej, można posłużyć się pomocniczą klasą, która będzie przechowywać pary: napis i wartość 32-bitową. Zauważmy jednak, że programista nie jest ograniczony do jednej wartości skojarzonej z napisem, ponieważ jest to tylko i wyłącznie kwestią zaprojektowania odpowiedniej klasy. \begin{scriptsize} \begin{verbatim} /* Wiktor Zychla, 2003 */ using System; using System.Windows.Forms; namespace Example { public class MyComboBoxItem { string text; int id; public string Text { get { return text; } } public int ID { get { return id; } } public MyComboBoxItem( string text, int id ) { this.text = text; this.id = id; } public override string ToString() { return text; } } public class CMainForm : Form { ComboBox cbItems; public CMainForm() { cbItems = new ComboBox(); cbItems.Items.Add( new MyComboBoxItem( "ala", 17 ) ); cbItems.Items.Add( new MyComboBoxItem( "ma", 24 ) ); cbItems.Items.Add( new MyComboBoxItem( "kota", 19 ) ); cbItems.Items.Add( new MyComboBoxItem( "!", 78 ) ); cbItems.SelectedIndexChanged += new EventHandler( cbItems_SelectedIndexChanged ); this.Controls.Add( cbItems ); } void cbItems_SelectedIndexChanged( object sender, EventArgs e ) { if ( cbItems.SelectedItem != null ) { MyComboBoxItem myItem = cbItems.SelectedItem as MyComboBoxItem; MessageBox.Show( String.Format( "Wybrano element: {0} - {1}", myItem.Text, myItem.ID ) ); } } public static void Main() { Application.Run( new CMainForm() ); } } } \end{verbatim} \end{scriptsize} \subsubsection{ToolTip} Wyświetlaniem podpowiedzi zajmuje się obiekt typu {\bf ToolTip}. Podpowiedzi mogą składać się z kilku linii tekstu. \begin{scriptsize} \begin{verbatim} /* Wiktor Zychla, 2003 */ using System; using System.Drawing; using System.Windows.Forms; namespace Example { public class CMainForm : Form { Button b; public CMainForm() { b = new Button(); b.Text = "Kliknij mnie"; this.Controls.Add( b ); ToolTip tTip = new ToolTip(); tTip.SetToolTip( b, "Podpowiedź\r\nwielolinijkowa" ); } public static void Main() { Application.Run( new CMainForm() ); } } } \end{verbatim} \end{scriptsize} \subsubsection{ListView} Komponent {\bf ListView} jest bardzo przydatny i w związku z tym często wykorzystywany w aplikacjach Windowsowych. Potrafi pokazywać elementy w 4 różnych widokach\footnote{Cztery możliwości prezentowania elementów listy przez {\bf ListView} najszybciej można zobaczyć w Eksplorerze Windows, który do pokazywania elementów systemu plików używa właśnie ListView i pozwala przełączać się pomiędzy wszystkimi dostępnymi widokami.}. Najczęściej korzysta się z widoku szczegółowego, w którym ListView staje się wielokolumnową listą elementów. Inaczej niż w przypadku {\bf ComboBoxa}, elementy ListView są typu {\bf ListViewItem}. Jeżeli programista chce skojarzyć własną informację z elementem listy, powinien skorzystać z propercji {\bf Tag} elementu, która może przechować referencję na dowolny obiekt. Również inaczej niż w przypadku {\bf ComboBoxa}, każdy element ListView może mieć własny kolor tła i tekstu. ListView wyróżnia się spośród innych komponentów tym, że potrafi samodzielnie sortować swoje elementy. Wymaga to zdefiniowania klasy implementującej interfejs {\bf IComparer} i przypisania obiektu tej klasy do propercji {\bf ListViewItemSorter} komponentu ListView. \begin{figure} \begin{center} \includegraphics[width=0.50\textwidth]{./pic/swf03} \caption{ListView potrafi sam sortować elementy umieszczone na liście} \end{center} \end{figure} \begin{scriptsize} \begin{verbatim} /* Wiktor Zychla, 2003 */ using System; using System.Collections; using System.Drawing; using System.Windows.Forms; namespace Example { // klasa do porównywania elementów ListView // wg. wskazanej kolumny public class MyLVItemSorter : IComparer { int kolumna; // kolumna wg. której sortujemy public MyLVItemSorter( int kolumna ) { this.kolumna = kolumna; } public int Compare( object o1, object o2 ) { ListViewItem l1 = o1 as ListViewItem; ListViewItem l2 = o2 as ListViewItem; return string.Compare( l1.SubItems[ kolumna ].Text, l2.SubItems[ kolumna ].Text ); } } public class CMainForm : Form { ListView lstItems; void InitListViewElements() { string[] sHeaders = new string[] { "Imię", "Nazwisko", "Data urodzenia" }; ListViewItem li; // nagłówki lstItems.Columns.Clear(); foreach ( string s in sHeaders ) lstItems.Columns.Add( s, 60, HorizontalAlignment.Left ); // elementy li = lstItems.Items.Add( "Jan" ); li.SubItems.Add( "Kowalski" ); li.SubItems.Add( "1971-05-05" ); li = lstItems.Items.Add( "Adam" ); li.SubItems.Add( "Malinowski" ); li.SubItems.Add( "1975-02-13" ); li = lstItems.Items.Add( "Zbigniew" ); li.SubItems.Add( "Abacki" ); li.SubItems.Add( "1972-05-11" ); // dopasuj szerokości kolumn foreach ( ColumnHeader ch in lstItems.Columns ) ch.Width = -2; } // po kliku w kolumnę ListView ustal sortowanie wg. tej kolumny void LV_ColumnClick( object sender, ColumnClickEventArgs e ) { lstItems.ListViewItemSorter = new MyLVItemSorter( e.Column ); } public CMainForm() { lstItems = new ListView(); lstItems.Dock = DockStyle.Fill; lstItems.FullRowSelect = true; lstItems.GridLines = true; lstItems.View = System.Windows.Forms.View.Details; lstItems.ColumnClick += new ColumnClickEventHandler( LV_ColumnClick ); this.Controls.Add( lstItems ); InitListViewElements(); } public static void Main() { Application.Run( new CMainForm() ); } } } \end{verbatim} \end{scriptsize} \subsubsection{TreeView} Komponent {\bf TreeView} zyskał nowy, obiektowy interfejs, w którym każdy węzeł ma kolekcję {\bf Nodes}, przechowującą jego podwęzły. Z komponentem tym wiąże się klasyczny problem: jak radzić sobie z wypełnianiem struktury TreeView, jeśli powinien on przechowywać bardzo dużo danych? Oczywiście zainicjowanie całego drzewa w konstruktorze okna macierzystego może nie wchodzić w grę, właśnie z powodu dużej ilości danych. Problem ten rozwiązuje się zwykle tak, że inicjuje się tylko {\em jeden} poziom drzewa, poziom główny, dodając przy okazji tym węzłom, które mają przechowywać jakieś podwęzły, tylko {\em jeden}, bardzo specjalny "pusty" podwęzeł, oznaczony w propercji {\bf Tag} w jakiś określony sposób. Następnie należy dodać funkcję obsługi zdarzenia {\bf BeforeExpand}, które pojawia się, gdy użytkownik próbuje "rozwijać" węzeł drzewa przy pomocy symbolu "+" umieszczonego przy węźle. Wewnątrz funkcji obsługi zdarzenia należy sprawdzić, czy rozwijany węzeł ma tylko jeden podwęzeł i to w dodatku ten specjalnie oznakowany. Jeśli tak - należy ten podwęzeł usunąć i dobudować kolejny poziom drzewa, znów dodając specjalne "puste" podwęzły określonym węzłom. W ten sposób drzewo budowane jest zawsze "na życzenie", przy czym dobudowywany jest zawsze tylko ten poziom drzewa, który jest akurat potrzebny. \begin{figure} \begin{center} \includegraphics[width=0.50\textwidth]{./pic/swf04} \caption{TreeView pozwala pokazać zależności między obiektami} \end{center} \end{figure} \begin{scriptsize} \begin{verbatim} /* Wiktor Zychla, 2003 */ using System; using System.Collections; using System.Drawing; using System.Windows.Forms; namespace Example { public class CMainForm : Form { TreeView tvItems; void InitTVElements() { TreeNode treeRoot = new TreeNode( "Opis struktury" ); treeRoot.ForeColor = Color.Blue; TreeNode treeSubNode; for ( int i=0; i<45; i++ ) { treeSubNode = new TreeNode( String.Format( "Podwęzeł {0}", i ) ); treeRoot.Nodes.Add( treeSubNode ); } tvItems.Nodes.Add( treeRoot ); } public CMainForm() { tvItems = new TreeView(); tvItems.Dock = DockStyle.Fill; this.Controls.Add( tvItems ); InitTVElements(); } public static void Main() { Application.Run( new CMainForm() ); } } } \end{verbatim} \end{scriptsize} \subsection{Rozmieszczanie okien potomnych} Dobrze zaprojektowany interfejs użytkownika powinien być czytelny i przejrzysty. Jednak przy odrobinie wprawy i doświadczenia można sobie z tym poradzić. O wiele trudniej jest zaprojektować interfejs tak, aby pozostawał spójny gdy okno zmienia swoje rozmiary, na przykład gdy jest rozciągane przez użytkownika. Istnieją dwa możliwe rozwiązania: można albo zabronić zmian rozmiaru okna (przez ustawienie propercji {\bf FormBorderStyle} na {\bf FormBorderStyle.FixedDialog}) albo reagować na zmianę rozmiaru okna i dopasowywać rozmiary okien potomnych do rozmiaru okna macierzystego. Oczywiście nie zawsze można po prostu zabronić zmian rozmiaru okna. Czy w związku z tym .NET wspomaga jakoś proces rozmieszczania okien potomnych przy zmianie rozmiaru okna macierzystego? Otóż tak. \subsubsection{Kotwice i dokowanie} Najprostszy sposób dopasowywania rozmiarów okna potomnego do rozmiarów okna macierzystego to tzw. {\em kotwicowanie}. Wystarczy nadać oknu potomnemu właściwość {\em bycia zaczepionym} któregoś z boków okna macierzystego, aby okno potomne zachowywało odległość od odpowiedniego boku podczas zmiany rozmiarów okna macierzystego. \begin{scriptsize} \begin{verbatim} /* Wiktor Zychla, 2003 */ using System; using System.Drawing; using System.Windows.Forms; namespace Example { public class CMainForm : Form { Button b; public CMainForm() { b = new Button(); b.Text = "Kliknij mnie"; b.Location = new Point( 40, 40 ); b.Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; this.Controls.Add( b ); } public static void Main() { Application.Run( new CMainForm() ); } } } \end{verbatim} \end{scriptsize} \begin{figure} \begin{center} \includegraphics[width=0.50\textwidth]{./pic/swf02} \caption{Okna potomne zadokowane w obrębie okna macierzystego} \end{center} \end{figure} Okna potomne można również {\em dokować}, czyli przywiązywać na stałe do któregoś z boków lub całego obszaru okna macierzystego. Dokowanie jest szczególnie przydatne w przypadku dwóch okien potomnych, bowiem jedno z nich można zadokować do któregoś z boków, a drugie do całego obszaru okna. Oba okna potomne zajmą wtedy cały obszar okna macierzystego i będą poprawnie dostosowywać się do zmian jego rozmiaru. Należy jedynie pamiętać o tym, aby to okno potomne, które powinno wypełniać obszar okna macierzystego było umieszczone "na wierzchu", czyli nad oknem zadokowanym do któregoś z boków. \begin{scriptsize} \begin{verbatim} /* Wiktor Zychla, 2003 */ using System; using System.Drawing; using System.Windows.Forms; namespace Example { public class CMainForm : Form { Button b; TextBox t; public CMainForm() { b = new Button(); b.Text = "Kliknij mnie"; b.Dock = DockStyle.Left; t = new TextBox(); t.Multiline = true; t.Dock = DockStyle.Fill; this.Controls.Add( t ); this.Controls.Add( b ); } public static void Main() { Application.Run( new CMainForm() ); } } } \end{verbatim} \end{scriptsize} \subsubsection{Panele} Sytuacja, w której okno macierzyste ma tylko dwa okna potomne jest niezwykle rzadka. Zastosowanie pokazanej powyżej metody wydaje się być więc dość ograniczone. Okazuje się jednak, że istnieje specjalny typ komponentu, {\bf Panel}, który z jednej strony zachowuje się jak okno potomne, bowiem jest komponentem umieszczanym wewnątrz jakiegoś okna dialogowego, z drugiej strony zachowuje się jak okno macierzyste, bowiem ma swoją własną kolekcję okien potomnych, które są kotwicowane i dokowane względem obszaru Panela, a nie okna macierzystego. Można więc używać paneli do podziału okna macierzystego na drobniejsze fragmenty, w obrębie których można dokonywać odpowiednich ustaleń rozmieszczenia okien potomnych. Panele można zagnieżdżać. \begin{scriptsize} \begin{verbatim} /* Wiktor Zychla, 2003 */ using System; using System.Drawing; using System.Windows.Forms; namespace Example { public class CMainForm : Form { Panel p; Button b1; Button b2; TextBox t; public CMainForm() { // panel zadokowany do lewej, a w nim dwa przyciski p = new Panel(); p.Dock = DockStyle.Left; b1 = new Button(); b1.Text = "Kliknij mnie"; b1.Dock = DockStyle.Top; b2 = new Button(); b2.Text = "Kliknij mnie"; b2.Dock = DockStyle.Fill; p.Controls.Add( b2 ); p.Controls.Add( b1 ); // pole tekstowe wypełnia obszar okna t = new TextBox(); t.Multiline = true; t.Dock = DockStyle.Fill; this.Controls.Add( t ); this.Controls.Add( p ); } public static void Main() { Application.Run( new CMainForm() ); } } } \end{verbatim} \end{scriptsize} \subsubsection{Splittery} Splittery są elementami graficznymi w postaci poziomych lub pionowych "belek", pozwalających użytkownikowi zmienić rozmiary okien potomnych. Splitterów używa się tam, gdzie używa się dokowania. \begin{scriptsize} \begin{verbatim} /* Wiktor Zychla, 2003 */ using System; using System.Drawing; using System.Windows.Forms; namespace Example { public class CMainForm : Form { Panel p; // zawiera b1 i b2 Button b1; Button b2; TextBox t; Splitter s1; // rozdziela b1 i b2 Splitter s2; // rozdziela p i t public CMainForm() { // panel zadokowany do lewej, a w nim dwa przyciski p = new Panel(); p.Dock = DockStyle.Left; b1 = new Button(); b1.Text = "Kliknij mnie"; b1.Dock = DockStyle.Top; s1 = new Splitter(); s1.Dock = DockStyle.Top; b2 = new Button(); b2.Text = "Kliknij mnie"; b2.Dock = DockStyle.Fill; p.Controls.Add( b2 ); p.Controls.Add( s1 ); // splitter rozdziela b2 i b1 p.Controls.Add( b1 ); // pole tekstowe wypełnia obszar okna s2 = new Splitter(); s2.Dock = DockStyle.Left; t = new TextBox(); t.Multiline = true; t.Dock = DockStyle.Fill; this.Controls.Add( t ); this.Controls.Add( s2 ); // splitter rozdziela t i p this.Controls.Add( p ); } public static void Main() { Application.Run( new CMainForm() ); } } } \end{verbatim} \end{scriptsize}
import { z } from "zod"; import { FastifyReply, FastifyRequest } from "fastify"; import { UserAlreadyExistsError } from "@/use-cases/errors/user-already-exists"; import { makeRegisterUseCase } from "@/use-cases/factories/make-register-use-case"; const _userSchemaBody = z.object({ name: z.string(), email: z.string().email(), password: z.string().min(6), }); export async function registerUser( request: FastifyRequest, reply: FastifyReply ) { const { name, email, password } = _userSchemaBody.parse(request.body); const registerUseCase = makeRegisterUseCase(request.dbClient); try { await registerUseCase.run({ name, email, password, }); } catch (error) { if (error instanceof UserAlreadyExistsError) { return reply.status(409).send({ message: error.message }); } throw error; } return reply.status(201).send(); }
<template> <div class="my-3 w-8/12"> <span v-if="caption" class="text-lg">{{ caption }}</span> <textarea :class=" `border-b-2 border-${color} focus:border-${focusColor} bg-transparent text-white w-full shadow-lg` " :disabled="disabled" v-model.trim="internal" ></textarea> </div> </template> <script lang="ts"> import { Component, Vue, Prop, Watch } from "vue-property-decorator"; @Component export default class DqButton extends Vue { @Prop({ default: "teal-800" }) color!: string; @Prop({ default: "teal-700" }) focusColor!: string; @Prop({ default: false }) disabled!: boolean; @Prop({ default: "" }) caption!: string; @Prop({ default: "" }) value!: string; internal = ""; @Watch("value") onValueChanged() { this.internal = this.value; } @Watch("internal") onInternalChanged() { this.$emit("input", this.internal); } } </script>
import express from "express"; import { createServer } from "http"; import cors from "cors"; import cookieParser from "cookie-parser"; import session from "express-session"; import { dbInstance } from "./db/db.js"; import { DB_NAME } from "./constants.js"; import fs from "fs"; import path from "path"; import {ApiError} from "./utils/ApiError.js"; import {errorHandler} from "./middlewares/error.middleware.js"; import {ApiResponse} from "./utils/ApiResponse.js"; import { configDotenv } from "dotenv"; configDotenv({ path: "/.env" }) const app = express(); const httpServer = createServer(app); app.use( cors({ origin: process.env.CORS_ORIGIN, credentials: true, }) ); app.use(express.json()); app.use(express.urlencoded({extended: true})); app.use(express.static("public")); app.use(cookieParser()); app.use(session({ secret: process.env.EXPRESS_SESSION_SECRET, resave: true, saveUninitialized: true, })); import userRoutes from "./routes/user.routes.js"; import productRoutes from "./routes/product.routes.js"; import categoryRoutes from "./routes/category.routes.js"; import cartRoutes from "./routes/cart.routes.js"; import orderRoutes from "./routes/order.routes.js"; import addressRoutes from "./routes/address.routes.js"; import couponRoutes from "./routes/coupon.routes.js"; import activeofferRoutes from "./routes/activeoffer.routes.js"; import bestforRoutes from "./routes/bestFor.routes.js"; import diapshapeRoutes from "./routes/dialShape.routes.js"; import featuresRoutes from "./routes/Features.routes.js"; import noicecancellationRoutes from "./routes/noicecancellation.routes.js"; import playbackRoutes from "./routes/playback.routes.js"; import colorRoutes from "./routes/colors.routes.js"; app.use("/api/v1/users", userRoutes); app.use("/api/v1/products", productRoutes); app.use("/api/v1/categories", categoryRoutes); app.use("/api/v1/cart", cartRoutes); app.use("/api/v1/order", orderRoutes); app.use("/api/v1/address", addressRoutes); app.use("/api/v1/coupon", couponRoutes); app.use("/api/v1/activeoffer", activeofferRoutes); app.use("/api/v1/bestfor", bestforRoutes); app.use("/api/v1/dialshape", diapshapeRoutes); app.use("/api/v1/features", featuresRoutes); app.use("/api/v1/noicecancellation", noicecancellationRoutes); app.use("/api/v1/playback", playbackRoutes); app.use("/api/v1/color", colorRoutes); app.use("/", (req, res) => { res.send("Server is running successfully"); }); app.delete("/api/v1/reset-db", async(req, res) => { if(dbInstance) { await dbInstance.connection.db.dropDatabase({ dbName: DB_NAME, }); const directory = "./public/images"; fs.readdir(directory, (err, files) => { if(err) { console.log("Error while removing the images: ", err); } else { for(const file of files) { if(file === ".getkeep") continue; fs.unlink(path.join(directory, file), (err) => { if(err) throw err; }) } } }); fs.unlink("./public/temp/seed-credentials.json", (err) => { if(err) console.log("Seed credentials are missing."); }); return res.status(200).json(new ApiResponse(200, null, "Database dropped successfully")); } throw new ApiError(500, "Something went wrong while dropping database"); }) app.use(errorHandler); export {httpServer};
package com.project.expense_tracker.persistence.dao; import com.project.expense_tracker.persistence.entity.Budget; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Date; import java.util.List; @Repository public class BudgetDAO { @Autowired private JdbcTemplate jdbcTemplate; private static class BudgetRowMapper implements RowMapper<Budget> { @Override public Budget mapRow(ResultSet rs, int rowNum) throws SQLException { Budget budget = new Budget(); budget.setBudget_id(rs.getLong("budget_id")); budget.setUser_id(rs.getLong("user_id")); budget.setBudget_amount(rs.getDouble("budget_amount")); budget.setStart_date(rs.getDate("start_date")); // Use Date type budget.setEnd_date(rs.getDate("end_date")); // Use Date type return budget; } } public List<Budget> findAll() { return jdbcTemplate.query("SELECT * FROM Budget", new BudgetRowMapper()); } public Budget findById(Long id) { return jdbcTemplate.queryForObject("SELECT * FROM Budget WHERE budget_id = ?", new Object[]{id}, new BudgetRowMapper()); } public Budget findByUserId(Long userId) { return jdbcTemplate.queryForObject("SELECT * FROM Budget WHERE user_id = ?", new Object[]{userId}, new BudgetRowMapper()); } public int save(Budget budget) { return jdbcTemplate.update("INSERT INTO Budget (user_id, budget_amount, start_date, end_date) VALUES (?, ?, ?, ?)", budget.getUser_id(), budget.getBudget_amount(), budget.getStart_date(), budget.getEnd_date()); } public int update(Budget budget) { return jdbcTemplate.update("UPDATE Budget SET user_id = ?, budget_amount = ?, start_date = ?, end_date = ? WHERE budget_id = ?", budget.getUser_id(), budget.getBudget_amount(), budget.getStart_date(), budget.getEnd_date(), budget.getBudget_id()); } public int deleteById(Long id) { return jdbcTemplate.update("DELETE FROM Budget WHERE budget_id = ?", id); } }
// Map var mapbox_key = "<%= Acres::Application.config.mapbox_map_id %>" var base_url = "https://c.tiles.mapbox.com/v3/" + mapbox_key + "/{z}/{x}/{y}.png"; var map = L.map('map', { scrollWheelZoom: false }); showMap(map); function showMap(map) { L.tileLayer(base_url, { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors under <a href="http://www.openstreetmap.org/copyright">ODbL</a> | Map imagery &copy; <a href="http://mapbox.com">Mapbox</a>', maxZoom: 18 }).addTo(map); if (location.pathname === "/sites") { // homepage map.setView([-37.85, 145.06], 10); // Melbourne $.getJSON('sites.json', function(sites) { $.each(sites, function(i, site) { if (site.latitude && site.longitude) { addMarker(site, map); } }); }) } else { // specific site $.getJSON(location.pathname + '.json', function(site) { if (site.latitude && site.longitude) { map.setView([site.latitude, site.longitude], 14); // more zoomed in addMarker(site, map); } }); } } function addMarker(site, map) { var pin; switch(site.status) { case 'potential': pin = "<%= image_url('pin-orange.png') %>"; break; case 'proposed': pin = "<%= image_url('pin-yellow.png') %>"; break; case 'active': pin = "<%= image_url('pin-green.png') %>"; break; case 'independent': pin = "<%= image_url('pin-grey.png') %>"; break; } var icon = L.icon({ iconUrl: pin, iconSize: [31, 42], iconAnchor: [15, 42], popupAnchor: [0, -20] }) var marker = new L.Marker(new L.LatLng(site.latitude, site.longitude), { icon: L.icon({ iconUrl: pin, iconSize: [31, 42], iconAnchor: [15, 42], popupAnchor: [0, -20] }) }); var link = "<p><a class='site-title' href='/sites/" + site.slug + "'>" if (site.image) { link += "<img width='180' src='" + site.image + "'><div>" + site.display_name + "</div></a></p>" } else { link += site.display_name + "</a></p>" } link += "<p>" + site.address + ", " + site.suburb + "</p>"; if (site.description) { link += "<p class='site-description'>" + site.description.substr(0,110) + "...</p>"; } if (site.size) { link += "<p>Size: " + site.size + "m<sup>2</sup></p>"; } if (site.available_until) { link += "<p>Available until: " + site.available_until + "</p>"; } if (site.watches.length > 0) { var p = (site.watches.length == 1) ? "person" : "people"; link += "<p>" + site.watches.length + " " + p + " watching.</p>"; } marker.bindPopup(link).openPopup(); map.addLayer(marker); }
import { useState } from "react"; import { useAuthContext } from "./useAuthContext"; const baseUrl = import.meta.env.VITE_BASE_URL; const finalUrl = baseUrl + '/api/user/login' export const useLogin = () => { const [error, setError] = useState(null) const [isLoading, setIsLoading] = useState(null) const { dispatch } = useAuthContext() const login = async (email,password) =>{ setIsLoading(true) setError(null) const response = await fetch(finalUrl, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ email, password }) }) const json = await response.json() if (!response.ok) { setIsLoading(false) setError(json.error) } if (response.ok) { localStorage.setItem('user', JSON.stringify(json)) dispatch({type: 'LOGIN', payload: json}) setIsLoading(false) } } return {login,error,isLoading} }
{* classes.pika *} # create A as a subclass of Object class A function init(a) self.a = a # create instance variable a end end # create B as a subclass of A class B : A function init(a, b) super a # call A.init self.b = b # create instance variable b end end a = A.new("hi") b = B.new("bye", 2) print a.a print "" print b.a print b.b print "a is A:" ... a is A print "a is B:" ... a is B print "b is A:" ... b is A print "b is B:" ... b is B
import 'package:flutter/material.dart'; import 'forgetscreen.dart'; import 'login_success.dart'; import 'signup_page.dart'; class LoginPage extends StatefulWidget { const LoginPage({Key? key}); @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { final TextEditingController emailController = TextEditingController(); final TextEditingController passwordController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( body: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.deepPurpleAccent, Colors.orange], begin: Alignment.topCenter, end: Alignment.bottomCenter)), child: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Login Page', style: TextStyle( fontSize: 35.0, fontWeight: FontWeight.bold, color: Colors.orangeAccent, ), ), SizedBox(height: 20.0), TextField( controller: emailController, decoration: InputDecoration( hintText: 'Email', fillColor: Colors.white, filled: true, border: OutlineInputBorder( borderRadius: BorderRadius.circular(20.0), borderSide: BorderSide.none, ), ), ), SizedBox(height: 20.0), TextField( controller: passwordController, obscureText: true, decoration: InputDecoration( hintText: 'Password', fillColor: Colors.white, filled: true, border: OutlineInputBorder( borderRadius: BorderRadius.circular(20.0), borderSide: BorderSide.none, ), ), ), SizedBox(height: 20.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ ElevatedButton( onPressed: () { Navigator.push( // Navigate to ForgetPage context, MaterialPageRoute(builder: (context) => ForgetPage()), ); }, child: Text('Forgot Password'), style: ElevatedButton.styleFrom( primary: Colors.grey[300], onPrimary: Colors.black, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), ), ), ), ElevatedButton( onPressed: () { // Access the text input values using the text controllers String email = emailController.text; String password = passwordController.text; print('Email: $email'); print('Password: $password'); Navigator.push( // Navigate to LoginSuccessfulPage context, MaterialPageRoute( builder: (context) => LoginSuccessfulPage()), ); }, child: Text('Login'), style: ElevatedButton.styleFrom( primary: Colors.blue, onPrimary: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), ), ), ), ], ), SizedBox(height: 10.0), GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (context) => SignupPage()), ); }, child: Text( "Don't have an account? Sign up", style: TextStyle( decoration: TextDecoration.underline, color: Colors.blue, fontWeight: FontWeight.bold, ), ), ), ], ), ), ), ); } }
package com.atguigu.book.service.impl; import com.atguigu.book.dao.BookDao; import com.atguigu.book.dao.OrderDao; import com.atguigu.book.dao.OrderItemDao; import com.atguigu.book.dao.impl.BookDaoImpl; import com.atguigu.book.dao.impl.OrderDaoImpl; import com.atguigu.book.dao.impl.OrderItemDaoImpl; import com.atguigu.book.pojo.*; import com.atguigu.book.service.OrderService; import java.util.Date; import java.util.Map; public class OrderServiceImpl implements OrderService { OrderDao orderDao = new OrderDaoImpl(); OrderItemDao orderItemDao = new OrderItemDaoImpl(); BookDao bookDao = new BookDaoImpl(); @Override public String createOrder(Cart cart, Integer userId) { //1.调用 OrderDao.saveOrder() 将order对象保存到数据库 //1.1 orderId 用时间戳+userId组成,防止重复 String orderId = System.currentTimeMillis() + "" + userId; //1.2 由Cart组成 Order对象 Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId); orderDao.saveOrder(order); int i = 12 / 0; //2.将 购物车Cart中的Items中的CartItem全部取出,构成一个个OrderItem,再保存到数据库 for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) { CartItem cartItem = entry.getValue(); OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getCount(), cartItem.getPrice(), cartItem.getTotalPrice(), orderId); orderItemDao.saveOrderItem(orderItem); //修改 Book 的销量,库存信息 //1.通过 BookDao.queryBookById() 和 cartItem的商品Id 返回数据库中的 Book对象 Book book = bookDao.queryBookById(cartItem.getId()); //2.修改返回的Book对象,将修改后的Book对象作为参数 通过BookDao.updateBook()在数据库中修改对应的Book数据 book.setStock(book.getStock() - cartItem.getCount()); book.setSales(book.getSales() + cartItem.getCount()); bookDao.updateBook(book); } //将购物车清空 cart.clear(); //返回订单号 return orderId; } }
const mongodb = require('mongodb'); const { validationResult } = require('express-validator'); const ModelRole = require('../../model/model.role'); const ModelUser = require("../../model/model.user"); const ServiceUser = require("../../services/service.user"); class ControllerUser { constructor() { } // TRUY XUẤT DANH MỤC USER async getUsers (req, res, next) { try { let { limit, start} = req.params; await ServiceUser.getLimit(limit, start, (information) => { let { status , message, users} = information; if(status) { res.status(200).json({status, message, users}); } else { res.status(406).json({status, message, error}); } }) } catch (error) { // PHƯƠNG THỨC LỖI res.status(500).json({status: false, message: 'Internal server failed'}); } } // TRUY XUẤT TẤT CẢ DANH MỤC USER async getUsersAll (req, res, next) { try { await ServiceUser.getAll((information) => { let { status, message, users } = information; if(status) { res.status(200).json({status, message, users}); } else { res.status(406).json({status, message, error}); } }) } catch (error) { // PHƯƠNG THỨC LỖI res.status(500).json({status: false, message: 'Internal server failed'}); } } // TRUY XUẤT USER THEO ID async getUserById (req, res, next) { try { let { user } = req.params; await ServiceUser.getById(user, (information) => { let { status, message, user, error } = information; if(status) { res.status(200).json({status, message, user}); } else { res.status(406).json({status, message, error}); } }) } catch (error) { // PHƯƠNG THỨC LỖI res.status(500).json({status: false, message: 'Internal server failed'}); } } // TRUY XUẤT SỐ LƯỢNG USER async getAmount (req, res, next) { try { await ServiceUser.getAmount((information) => { let { status , message, amount} = information; if(status) { res.status(200).json({status, message, amount}); } else { res.status(406).json({status, message, error}); } }) } catch (error) { // PHƯƠNG THỨC LỖI res.status(500).json({status: false, message: 'Internal server failed'}); } } // CREATE USER async createUser(req, res, next) { const { errors } = validationResult(req); try { if(errors.length) { res.status(406).json({status: false, message: 'E-mail account exists already'}); } else { let {username, fullname, email, password, role, phonenumber, address} = req.body; // THỰC HIÊNK TÌM KIẾM ROLE CỦA USER let roleInfor = await ModelRole.findById(role); await ServiceUser.create({username, fullname, email, password, phonenumber, address}, roleInfor, (information) => { let { status, message, error} = information; if(status) { res.status(200).json({status, message}); } else { res.status(406).json({status, message, error}); } }) } } catch (error) { res.status(500).json({status: false, message: 'Internal server failed'}); } } // UPDATE USER async modifiUser(req, res, next) { let { errors } = validationResult(req); if(errors.length) { res.status(406).json({status: false, message: errors[0].msg}); } else { try { let { user, username, fullname, email, phonenumber, address, role } = req.body; let userInfor = await ModelUser.findById(user).populate(['role']).exec(); let roleInfor = await ModelRole.findById(role).exec(); await ServiceUser.update({model: userInfor, username, fullname, email, phonenumber, address}, roleInfor, (information) => { let { status, message, error} = information; if(status) { res.status(200).json({status, message}); } else { res.status(406).json({status, message, error}); } }) } catch (error) { // PHUONG THỨC LỖI res.status(500).json({status: false, message: 'Internal server failed'}); } } } // DELETE USER async deleteUser(req, res, next) { let { errors } = validationResult(req); if(errors.length) { res.status(406).json({staus: false, message: errors[0].msg}); } else { try { let { user } = req.body; let userInfor = await ModelUser.findById(user).populate('role').exec(); await ServiceUser.delete({model: userInfor}, (information) => { let { status, message, error } = information; if(status) { res.status(200).json({status, message}); } else { res.status(406).json({status, message, error}); } }) } catch (error) { // PHƯƠNG THỨC LỖI res.status(500).json({status: false, message: 'Internal server failed'}); } } } } module.exports = new ControllerUser();
import re MUNICIPALITIES_W_S = ['Alingsås kommun', 'Bengtsfors kommun', 'Bollnäs kommun', 'Borås stad', 'Degerfors kommun', 'Grums kommun', 'Hagfors kommun', 'Hofors kommun', 'Hällefors kommun', 'Höganäs kommun', 'Kramfors kommun', 'Munkfors kommun', 'Mönsterås kommun', 'Robertsfors kommun', 'Sotenäs kommun', 'Storfors kommun', 'Strängnäs kommun', 'Torsås kommun', 'Tranås kommun', 'Vännäs kommun', 'Västerås stad'] def clean_kommun(kommun): """ Clean the municipality name by removing whitespace and specific keywords. Args: kommun (str): The municipality name to be cleaned. Returns: str: The cleaned municipality name. """ # Remove any whitespace kommun = kommun.strip() # Replace 'Falu kommun' with 'Falun' if kommun == 'Falu kommun': return 'Falun' if kommun == 'Region Gotland (kommun)': return 'Gotland' # Remove 'kommun' or 'stad' from municipalities in the list 'municipalities_w_s' if kommun in MUNICIPALITIES_W_S: kommun = re.sub(r'( kommun| stad)', '', kommun) # Remove 'kommun', 'stad', 's kommun', or 's stad' from all other municipalities kommun = re.sub(r'( kommun| stad|s kommun|s stad)', '', kommun) return kommun
import React from 'react'; import type { Meta, StoryObj } from '@storybook/react'; import { StatusBadge } from '@stick-ui/lib'; StatusBadge.displayName = 'StatusBadge'; const meta: Meta<typeof StatusBadge> = { title: 'STICK UI/Components/Core/Badges/StatusBadge', component: StatusBadge, tags: ['autodocs'], argTypes: { activeText: { table: { defaultValue: { summary: 'Active' }, }, }, inactiveText: { table: { defaultValue: { summary: 'Inactive' }, }, }, }, decorators: [ (Story) => ( <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', }} > <Story /> </div> ), ], }; export default meta; export const Active: StoryObj = { args: { grow: false, isActive: true, activeText: 'Active', inactiveText: 'Inactive', }, }; export const Inactive: StoryObj = { args: { grow: false, isActive: false, activeText: 'Active', inactiveText: 'Inactive', }, };
import { Router } from 'express'; import CreateProductControler from '../controllers/CreateProductControler'; import DeleteByIdController from '../controllers/DeleteByIdController'; import GetAllProductsController from '../controllers/GetAllProductsController'; import GetByIdProductController from '../controllers/GetByIdProductController'; import UpdateProductController from '../controllers/UpdateProductController'; import { Joi, celebrate, Segments } from 'celebrate'; const productRouter: Router = Router(); //MIddlewares de validação das rotas const middlewares = { create: celebrate({ [Segments.BODY]: { name: Joi.string().required(), quantity: Joi.number().required(), status: Joi.string().required().valid('Active', 'Inactive'), category: Joi.string().required(), }, }), update: celebrate({ [Segments.PARAMS]: { id: Joi.string().required(), }, [Segments.BODY]: { name: Joi.string(), quantity: Joi.number(), status: Joi.string().valid('Active', 'Inactive'), category: Joi.string(), }, }), validID: celebrate({ [Segments.PARAMS]: { id: Joi.string().required().uuid(), }, }), }; productRouter.post('/', middlewares.create, CreateProductControler.execute); productRouter.get('/', GetAllProductsController.execute); productRouter.get( '/:id', middlewares.validID, GetByIdProductController.execute, ); productRouter.delete('/:id', middlewares.validID, DeleteByIdController.execute); productRouter.put('/:id', middlewares.update, UpdateProductController.execute); export default productRouter;
--- alias: [] --- # Expected Value ❌✔️✅📗 ## Average of a Sample Consider a sample of $n = 1,000,000$ [[Random Variables]] $X_i, i = 1,2,...n$ obtained from a distribution with [[Probability Function]] $f(x)$, for example the Poisson random variables. In a sample of $n$ values of the random variable $X$, relative frequencies: $$ freq(x) = \frac{\text{\# of times }X = x}{n} $$ In other words if we count how many times $X = 0$, then divide that by $n$, we get an approximation of the probability of $X = 0$. Similar to probabilities, $P(X = x) = f(x)$ is $n$ is large. The average of all the $X$'s is: $$ \frac{0 \cdot (\text{\# of times} X = 0) + 1 \cdot (\text{\# of times} X = 1)...+ x \cdot (\text{\# of times} X = x)}{n} $$ ## Expected Value Since $n$ is large, $freq(x) \approx P(X = x) = f(x)$ ```ad-def If a discrete random variable $X$ has the p.f. $f(x)$, then the number $E(X) = \sum_\text{all x}{x \cdot f(x)}$ is the **expected value** of $X$, denoted $E(X)$ (also referred to as **mean** or **expectation**). ``` That is, $\sum_{\text{all x}}{\text{value of x} \cdot \text{probability of this value}}$ ```ad-note If there are infinitely many values of $X$, we require the series $\sum_\text{all x}{|x| \cdot f(x)}$ to be convergent. Otherwise we say the expected value DNE ``` ```ad-example Supposed $X$ is $Bi(5, 0.5)$ with probability function ![[Pasted image 20211030003454.png]] Then ![[Pasted image 20211030003514.png]] ``` We don't really expect to get 2.5 heads when we toss a coin 5 times. 2.5 heads is the approximate long-run average when we repeat the experiment many times and average the result. ## Significant of Expected Value $E(X) =$ The sum of (Values of $X \times$ Probability of these values) $E(X) =$The 'fair' price to pay to play a game whose payoff is $X$ $E(X) =$The 'ceneter of gravity' of the distribution of $X$ ```ad-example ![[Pasted image 20211030004118.png]] ``` The center of gravity of this triangle would be on 2 Relate: [[]]
import '../styles/ResultPage.scss' import { useState, useEffect } from 'react' import { Link } from 'react-router-dom' import { IoIosArrowDown } from 'react-icons/io' import { FiFilter } from 'react-icons/fi' import { MdKeyboardDoubleArrowRight, MdKeyboardDoubleArrowLeft } from 'react-icons/md' import ProductCard from '../components/Card/ProductCard' import Banner from '../assets/banner.jpeg' import Phone from '../assets/phone.jpeg' import PC from '../assets/pc.jpeg' import TV from '../assets/tivi.webp' import HeadPhone from '../assets/headphone.jpeg' import Other from '../assets/other.jpeg' import { getAllProducts } from '../api/productApi' const ResultPage = () => { const [products, setProducts] = useState() const [totalCount, setTotalCount] = useState() const [skip, setSkip] = useState(0) useEffect(() => { const fetchProducts = async () => { try { await getAllProducts(skip).then((data) => { setProducts(data?.data?.productData) setTotalCount(data?.data?.count) }) } catch (error) { console.log(error) } } fetchProducts() }, [skip]) const handleNext = () => { if (skip + 12 >= totalCount) { return } setSkip((prevSkip) => prevSkip + 12) } const handlePrevious = () => { if (skip === 0) { return } setSkip((prevSkip) => prevSkip - 12) } return ( <div className="result-container"> <div className="body-section"> <div className="banner-section"> <img src={Banner} alt="" draggable="false" /> </div> <div className="category-section"> <span>Category</span> <div className="category-wrapper"> <div className="left-section"> <Link to="/category/phone"> <div className="list-category-container"> <img src={Phone} alt="" /> <span>Điện thoại</span> </div> </Link> <Link to="/category/pc"> <div className="list-category-container"> <img src={PC} alt="" /> <span>Laptop, PC</span> </div> </Link> <Link to="/category/phukien"> <div className="list-category-container"> <img src={HeadPhone} alt="" /> <span>Phụ kiện</span> </div> </Link> </div> <div className="right-section"> <Link to="/category/tivi"> <div className="list-category-container"> <img src={TV} alt="" /> <span>Tivi</span> </div> </Link> <div className="list-category-container"> <img src={Other} alt="" /> <span>Khác</span> </div> </div> </div> </div> <div className="option-section"> <div className="right-section"> <div className="list-item"> <span>Price</span> <div className="icon"> <IoIosArrowDown /> </div> </div> <div className="list-item"> <span>Review</span> <div className="icon"> <IoIosArrowDown /> </div> </div> <div className="list-item"> <span>Location</span> <div className="icon"> <IoIosArrowDown /> </div> </div> <div className="list-item"> <span>Offer</span> <div className="icon"> <IoIosArrowDown /> </div> </div> <div className="list-item"> <span>All Filters</span> <div className="icon"> <FiFilter /> </div> </div> </div> <div className="left-section"> <div className="sort"> <span>Sort by</span> <div className="icon"> <IoIosArrowDown /> </div> </div> </div> </div> <div className="product-section"> <span>Recommended For You!</span> <div className="product-grid"> {products?.map((product) => { return ( <Link to={`/product-detail/${product._id}`} key={product._id}> <ProductCard name={product.name} desc={product.desc} item={product.item} price={product.price} image={product.image[0]} review={product.review} brand={product.brand} /> </Link> ) })} </div> <div className="pagination-btn"> <button className="icon" onClick={handlePrevious}> <MdKeyboardDoubleArrowLeft size={30} /> </button> <button className="icon" onClick={handleNext}> <MdKeyboardDoubleArrowRight size={30} /> </button> </div> </div> </div> </div> ) } export default ResultPage
import { ImageUploadService } from 'src/app/core/services/image-upload/image-upload.service'; import { User } from '@angular/fire/auth'; import { Component, OnInit } from '@angular/core'; import { MatDialog, MatDialogRef } from '@angular/material/dialog'; import { HotToastService } from '@ngneat/hot-toast'; import { Observable } from 'rxjs'; import { DeleteDialogComponent } from 'src/app/auth/components/delete-dialog/delete-dialog.component'; import { Diario } from 'src/app/core/models/diario'; import { DiariosService } from 'src/app/core/services/diarios/diarios.service'; import { DiarioAddComponent } from '../diario-add/diario-add.component'; import { DiarioEditComponent } from '../diario-edit/diario-edit.component'; import { UsersService } from 'src/app/core/services/users/users.service'; import { AuthService } from 'src/app/core/services/auth/auth.service'; import { concatMap } from 'rxjs/operators'; import { DiarioDetailComponent } from '../diario-detail/diario-detail.component'; @Component({ selector: 'app-diario-list', templateUrl: './diario-list.component.html', styleUrls: ['./diario-list.component.scss'], }) export class DiarioListComponent implements OnInit { allDiarios$?: Observable<Diario[]>; meusDiarios$?: Observable<Diario[]>; atualizaFoto$?: Observable<Diario[]>; atualizaNome$?: Observable<Diario[]>; user$ = this.authService.currentUser$; users$ = this.usersService.currentUserProfile$; diario: Diario = {} as Diario; imagem?: File; dialogRef!: MatDialogRef<DeleteDialogComponent>; constructor( private dialog: MatDialog, private diariosService: DiariosService, private toast: HotToastService, private authService: AuthService, private usersService: UsersService, private imageUploadService: ImageUploadService ) {} setImage(ev: any) { this.imagem = ev.target.files[0]; } onClickDetail(diario: Diario) { this.dialog.open(DiarioDetailComponent, { panelClass: 'fullscreen-dialog', maxWidth: '100%', minWidth: '100%', data: { ...diario }, }); } onClickAdd() { const ref = this.dialog.open(DiarioAddComponent, { maxWidth: '512px' }); ref.afterClosed().subscribe({ next: (result) => { if (result) { this.diariosService .addDiario(result.diario, result.links) .pipe( this.toast.observe({ loading: 'Adicionando...', error: 'Ocorreu um erro', success: 'Diário adicionado', }) ) .subscribe(); } }, }); } uploadImage(event: any, user: User) { this.imageUploadService .uploadImage(event.target.files[0], `images/profile/${user.uid}`) .pipe( this.toast.observe({ loading: 'Imagem carregando...', success: 'Imagem Atualizada', error: 'Erro no carregamento', }), concatMap((photoURL) => this.authService.updateProfileData({ photoURL }) ) ) .subscribe(); } onClickEdit(diario: Diario) { const ref = this.dialog.open(DiarioEditComponent, { maxWidth: '512px', data: { ...diario }, }); ref.afterClosed().subscribe({ next: (result) => { if (result) { this.diariosService .editDiario(result.diario, result.links) .pipe( this.toast.observe({ loading: 'Atualizando...', error: 'Ocorreu um erro', success: 'Diário atualizado', }) ) .subscribe(); } }, }); } onClickDelete(diario: Diario) { this.dialogRef = this.dialog.open(DeleteDialogComponent); this.dialogRef.afterClosed().subscribe(result => { if(result) { this.diariosService .deleteDiario(diario) .pipe(this.toast.observe({ success: 'Diário apagado!' })) .subscribe(); } // this.dialogRef = null }); } ngOnInit(): void { this.allDiarios$ = this.diariosService.getTodosDiarios(); this.meusDiarios$ = this.diariosService.getDiariosUsuario(); this.atualizaFoto$ = this.diariosService.atualizaFoto(); this.atualizaNome$ = this.diariosService.atualizaNome(); } }
import React, { useEffect, useMemo } from "react"; import styles from "./ChatBodyStyles.module.scss"; import clsx from "clsx"; import { useFetchDialogue } from "../../../api/useFetchDialogue"; import { useSelector } from "react-redux"; import { RootState } from "../../../store"; import { Message } from "../../../types/messenger"; import { TextMessageType } from "../../../types/textMessage"; import axios, { AxiosError } from "axios"; import Swal from "sweetalert2"; const TextMessage: React.FC<TextMessageType> = ({ createdBy, text }) => { const selfId: string = useSelector((state: RootState) => state.auth.user._id) || ""; const receivedOrSentStyling = createdBy === selfId ? styles.sent : styles.received; return ( <li className={clsx(styles.message, receivedOrSentStyling)}>{text}</li> ); }; const ChatBody: React.FC = (): JSX.Element => { const dialogueId: string | null = useSelector( (state: RootState) => state.messenger.dialogId ); const { data: dialogues, isSuccess, refetch: refetchDialogue, isLoading, error, } = useFetchDialogue(); const messageWrapper = document.getElementById("messageWrapper"); const fetchedMessages: Message[] = dialogues?.messages; useEffect(() => { const fn = async () => await refetchDialogue(); fn(); }, [dialogueId, refetchDialogue]); useEffect(() => { messageWrapper?.scrollTo({ behavior: "auto", top: messageWrapper?.scrollHeight, }); }, [fetchedMessages, messageWrapper]); const fireErrorAlert = (error: AxiosError) => Swal.fire(error.message); if (axios.isAxiosError(error)) fireErrorAlert(error); const Body = useMemo(() => { return ( <> {isLoading && <div>Loading...</div>} {isSuccess && ( <main className={styles.wrapper}> <div className={styles.header}>{dialogueId}</div> <ul className={styles.messagesWrapper} id={"messageWrapper"}> {fetchedMessages.map((item) => { const { text, createdBy } = item; return <TextMessage createdBy={createdBy} text={text} />; })} </ul> </main> )} </> ); }, [fetchedMessages, isLoading, isSuccess, dialogueId]); return Body; }; export default ChatBody;
-- String,Date -- 중성화 여부 파악하기 -- 방법 1. when 사용 -- SELECT ANIMAL_ID, NAME, -- CASE -- WHEN SEX_UPON_INTAKE LIKE '%Neutered%' OR SEX_UPON_INTAKE LIKE '%Spayed%' -- THEN 'O' -- ELSE 'X' -- END AS '중성화' -- FROM ANIMAL_INS -- ORDER BY ANIMAL_ID; -- 방법 2. if 사용 SELECT ANIMAL_ID, NAME, IF ( SEX_UPON_INTAKE LIKE '%Neutered%' OR SEX_UPON_INTAKE LIKE '%Spayed%', 'O', 'X' ) AS '중성화' FROM ANIMAL_INS ORDER BY ANIMAL_ID;
@extends('layout-master') @section('title','| Reset Password') @section('content') <!-- ##### Breadcrumb Area Start ##### --> <section class="breadcrumb-area bg-img bg-overlay" style="background-image: url(/mag/img/bg-img/40.jpg);"> <div class="container h-100"> <div class="row h-100 align-items-center"> <div class="col-12"> <div class="breadcrumb-content"> <h2>Reset Password</h2> </div> </div> </div> </div> </section> <!-- ##### Breadcrumb Area End ##### --> <!-- ##### Login Area Start ##### --> <div class="mag-login-area py-5"> <div class="container"> <div class="row justify-content-center"> <div class="col-12 col-lg-6"> <div class="login-content bg-white p-30 box-shadow"> <!-- Section Title --> <div class="section-heading"> <h5>Reset Password</h5> </div> <form action="{{ route('password.update') }}" method="post"> @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif @csrf <input type="hidden" name="token" value="{{ $token }}"> <div class="form-group"> <input type="email" class="form-control @error('email') is-invalid @enderror" name="email" id="exampleInputEmail1" value="{{ $email ?? old('email') }}" placeholder="Email"> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div class="form-group"> <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="new-password" placeholder="New Password"> @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div class="form-group"> <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password" placeholder="Confirm Password"> </div> <div class="form-group"> <button type="submit" class="btn mag-btn mt-30">{{ __('Reset Password') }}</button> </div> </form> </div> </div> </div> </div> </div> <!-- ##### Login Area End ##### --> @endsection {{-- @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">{{ __('Reset Password') }}</div> <div class="card-body"> <form method="POST" action="{{ route('password.update') }}"> @csrf <input type="hidden" name="token" value="{{ $token }}"> <div class="form-group row"> <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label> <div class="col-md-6"> <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ $email ?? old('email') }}" required autocomplete="email" autofocus> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label> <div class="col-md-6"> <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="new-password"> @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label> <div class="col-md-6"> <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password"> </div> </div> <div class="form-group row mb-0"> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary"> {{ __('Reset Password') }} </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection --}}
import { View, Text, TouchableOpacity, TextInput, TouchableWithoutFeedback, StyleSheet, Pressable } from 'react-native' import React, {useState} from 'react' import DateTimePickerModal from "react-native-modal-datetime-picker"; import { Formik } from 'formik' import * as Yup from 'yup' const GoalWeightModal = ({modalClose}) => { const [startDate, setStartDate] = useState(new Date()) const [endDate, setEndDate] = useState(new Date()) const [isDatePickerVisible, setDatePickerVisibility] = useState(false); const showDatePicker = () => { setDatePickerVisibility(true); }; const hideDatePicker = () => { setDatePickerVisibility(false); }; const handleConfirmStartDate = (e) => { setStartDate(e) hideDatePicker(); }; const [isEndDatePickerVisible, setEndDatePickerVisibility] = useState(false); const showEndDatePicker = () => { setEndDatePickerVisibility(true); }; const hideEndDatePicker = () => { setEndDatePickerVisibility(false); }; const handleConfirmEndDate = (date) => { setEndDate(date) hideEndDatePicker(); }; const goalWeightSchema = Yup.object().shape({ startWeight: Yup.number().required('Required').positive().min(2), goalWeight: Yup.number().required('Required').positive().min(2), startDate: Yup.date().nullable().required('Date is required'), endDate: Yup.date().nullable().required('Date is required'), }) return ( <View style={styles.centeredView}> <View style={styles.modalView}> <Formik initialValues={{ startWeight: '', goalWeight: '', startDate: new Date(), endDate: new Date(), }} onSubmit={(values) => { console.log(values) }} validationSchema={goalWeightSchema} validateOnMount={true} > {({handleChange, handleBlur, handleSubmit, values, isValid, setFieldValue, errors}) => ( <> <View style={{flexDirection:'row',alignItems:'center', justifyContent:'space-between', borderBottomWidth:1, borderColor:'#eee', width:'100%'}}> <Text style={{color:'#fff'}}>Start Date:</Text> <TouchableOpacity style={styles.date} onPress={showDatePicker} > <Text style={styles.dateText}>{startDate.getMonth() +1}/{startDate.getDate()}/{startDate.getFullYear()}</Text> </TouchableOpacity> <DateTimePickerModal isVisible={isDatePickerVisible} onChange={(e) => setFieldValue('startDate', e)} date={startDate} value={values.startDate} onConfirm={handleConfirmStartDate} onCancel={hideDatePicker} minimumDate={new Date()} /> </View> <View style={{flexDirection:'row',alignItems:'center', justifyContent:'space-between', borderBottomWidth:1, borderColor:'#eee', width:'100%'}}> <Text style={{color:'#fff'}}>End Date:</Text> <TouchableOpacity style={styles.date} onPress={showEndDatePicker} > <Text style={styles.dateText}>{endDate.getMonth() +1}/{endDate.getDate()}/{endDate.getFullYear()}</Text> </TouchableOpacity> <DateTimePickerModal isVisible={isEndDatePickerVisible} onChange={(date) => setFieldValue('endDate', date)} date={endDate} value={values.endDate} onConfirm={handleConfirmEndDate} onCancel={hideEndDatePicker} minimumDate={startDate} /> </View> <View style={{flexDirection:'row',alignItems:'center', justifyContent:'space-between', borderBottomWidth:1, borderColor:'#eee', width:'100%', padding:0}}> <Text style={styles.weight}>Start Weight {errors.name}</Text> <View style={[styles.inputField, {borderColor: 1 < values.startWeight.length ? '#ccc' : 'red'} ]}> <TouchableWithoutFeedback onPress={()=> Keyboard.dismiss() }> <TextInput style={styles.weightInput} placeholderTextColor='#c8cacd' placeholder='lbs.' keyboardType='number-pad' autoFocus={true} onChangeText={handleChange('startWeight')} onBlur={handleBlur('startWeight')} value={values.startWeight} /> </TouchableWithoutFeedback> </View> </View> <View style={{flexDirection:'row',alignItems:'center', justifyContent:'space-between', borderBottomWidth:1, borderColor:'#eee', width:'100%', padding:0}}> <Text style={styles.weight}>Goal Weight {errors.name}</Text> <View style={[styles.inputField, {borderColor: 1 < values.goalWeight.length ? '#ccc' : 'red'} ]}> <TouchableWithoutFeedback onPress={()=> Keyboard.dismiss() }> <TextInput style={styles.weightInput} placeholderTextColor='#c8cacd' placeholder='lbs.' keyboardType='number-pad' autoFocus={true} onChangeText={handleChange('goalWeight')} onBlur={handleBlur('goalWeight')} value={values.goalWeight} /> </TouchableWithoutFeedback> </View> </View> <View style={{flexDirection:'row', marginBottom:20}}> <Pressable style={[styles.buttons, styles.buttonCancel]} onPress={modalClose} > <Text style={styles.textStyle}>Cancel</Text> </Pressable> <Pressable style={[styles.buttons, styles.buttonSubmit]} onPress={() => {handleSubmit()}} > <Text style={styles.textStyle}>Submit</Text> </Pressable> </View> </> )} </Formik> </View> </View> ) } const styles = StyleSheet.create({ centeredView: { flex: 1, justifyContent: "center", alignItems: "center", marginTop: 22, }, modalView: { margin: 20, backgroundColor: "#4c4c4d", borderRadius: 20, padding: 35, alignItems: "center", shadowColor: "#000", shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.25, shadowRadius: 4, elevation: 5 }, buttons: { borderRadius: 10, paddingVertical: 15, paddingHorizontal:30, elevation: 2, margin:10 }, buttonCancel: { backgroundColor: "#f71805", }, buttonSubmit: { backgroundColor: "#2196F3", }, textStyle: { color: "white", fontWeight: "bold", textAlign: "center" }, modalText: { marginBottom: 15, textAlign: "center" }, inputField: { borderRadius:4, padding:2, backgroundColor:'#FAFAFA', marginBottom:1, borderWidth:1 }, weightInput: { width: 80, fontSize:20, backgroundColor:'#4b5055', color:'white', alignSelf:'center' }, weight: { paddingVertical:7, fontSize: 15, marginRight:180, color:'#fff' }, date: { padding:10, justifyContent:'center', margin:10, width: 200, borderColor: '#fff', borderWidth: 2, borderRadius:5, alignItems: 'center', backgroundColor:'#000' }, dateText: { color:'white', fontSize:20, fontWeight:'bold' }, button: (isValid) => ({ backgroundColor: isValid ? '#0096F6': '#9ACAF7', alignItems:'center', width:200, justifyContent:'center', minHeight:42, borderRadius:4, marginVertical:20, }), }) export default GoalWeightModal
// Name : Graph 图论 // Copyright : fateud.com #ifndef GRAPH_H_ #define GRAPH_H_ 20150911L #include <vector> namespace csl { template<typename _Tp> struct _graph_node { typedef _Tp value_type; typedef std::size_t size_type; typedef _graph_node<_Tp>* _Link; typedef _graph_node<_Tp> _Self; _graph_node() : prev(), next(), from(), to(), data() { } _graph_node(_Link a,_Link b,size_type c,size_type d,value_type e) : prev(a), next(b), from(c), to(d), data(e) { } _Link prev; _Link next; size_type from; size_type to; value_type data; }; template<typename _Tp> struct graph { // template parameter. typedef _Tp value_type; typedef _Tp* pointer; typedef _Tp& reference; typedef _graph_node<_Tp>* iterator; typedef _graph_node<_Tp> _Node; typedef _graph_node<_Tp>* _Link; typedef graph<_Tp> _Self; typedef std::size_t size_type; // member function. void m_add_edge(size_type from,size_type to,const value_type& data) { _Link node = m_data.data() + m_size++; *node = _Node(0, m_impl[from], from, to, data); if(m_impl[from]) m_impl[from]->prev = node; m_impl[from] = node; } // constructor & destructor. explicit graph(size_type __v = 0,size_type __e = 0) : m_size() { m_impl.reserve(__v); m_data.reserve(__e); } // iterators. // capacity. inline void build(size_type __v,size_type __e) { m_impl.assign(__v, _Link()); m_data.resize(__e); m_size = 0; } inline size_type size() const { return m_size; } // element access. inline _Link getHead(size_type __x) const { return m_impl[__x]; } inline _Link getEdge(size_type __x) { return m_data.data() + __x; } inline size_type getEdgeIndex(_Link __x) const { return __x - m_data.data(); } // modifiers. inline void add_edge(size_type from,size_type to,const value_type& data) { m_add_edge(from, to, data); } inline void add_double_edge(size_type from,size_type to, const value_type& data) { m_add_edge(from, to, data); m_add_edge(to, from, data); } inline void add_couple_edge(size_type from,size_type to, const value_type& data1,const value_type& data2 = value_type()) { m_add_edge(from, to, data1); m_add_edge(to, from, data2); } // operator overloading. // specialized algorithms. // member variable. std::vector<_Link> m_impl; std::vector<_Node> m_data; size_type m_size; }; template<typename _Tp> struct tarjan { public: typedef typename graph<_Tp>::_Link _Link; typedef std::size_t size_type; private: void __scc(size_type u) { dfn[u] = low[u] = ++idx; vis[u] = true; sta.push_back(u); for(_Link i = map->getHead(u); i; i = i->next) { size_type v = i->to; if(!dfn[v]) { __scc(v); if(low[u] > low[v]) low[u] = low[v]; } else { if(vis[v] && low[u] > dfn[v]) low[u] = dfn[v]; } } if(dfn[u] == low[u]) { size_type w; do { w = sta.back(); sta.pop_back(); vis[w] = false; key[w] = cnt; }while(w != u); ++cnt; } } void __dcc(size_type u,size_type p) { dfn[u] = low[u] = ++idx; sta.push_back(u); for(_Link i = map->getHead(u); i; i = i->next) { size_type v = i->to; if(v == p) continue; if(!dfn[v]) { __dcc(v, u); if(low[u] > low[v]) low[u] = low[v]; if(dfn[u] < low[v]) { size_type w; do { w = sta.back(); sta.pop_back(); key[w] = cnt; }while(w != v); cnt++; } } else { if(low[u] > dfn[v]) low[u] = dfn[v]; } } } public: void scc(graph<_Tp>& __map) { map = &__map; size_type __n = map->m_impl.size(); idx = 0; cnt = 0; sta.reserve(__n); dfn.assign(__n, 0); low.resize(__n); key.resize(__n); vis.assign(__n, false); for(size_type i = 0; i < __n; ++i) if(!dfn[i]) __scc(i); } void dcc(graph<_Tp>& __map) { map = &__map; size_type __n = map->m_impl.size(); idx = 0; cnt = 0; sta.reserve(__n); dfn.assign(__n, 0); low.resize(__n); key.resize(__n); for(size_type i = 0; i < __n; ++i) { if(dfn[i]) continue; sta.clear(); __dcc(i, -1); for(size_type j = 0; j < sta.size(); ++j) key[sta[j]] = cnt; cnt++; } } inline size_type operator[](const size_type __x) const { return key[__x]; } inline size_type size() const { return cnt; } private: graph<_Tp>* map; size_type idx; size_type cnt; std::vector<size_type> sta; std::vector<size_type> dfn; std::vector<size_type> low; std::vector<size_type> key; std::vector<bool> vis; }; } // namespace csl #endif /* GRAPH_H_ */
package firsttutorial.com.example.firsttutorial.student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(path = "api/v1/student") public class StudentController { private final StudentService studentService; @Autowired public StudentController(StudentService studentService) { this.studentService = studentService; } // Retrieving records from db @GetMapping public List<Student> getStudents(){ return studentService.getStudents(); } // Registering new students @PostMapping public void registerNewStudent(@RequestBody Student student){ studentService.addNewStudent(student); } }
import { useState, useEffect } from "react"; import styles from "../styles/Signup.module.css"; import axios from "axios"; const Signup = () => { const [firstName, setFirstName] = useState(""); const [lastName, setLastName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [signupSuccess, setSignupSuccess] = useState(false); // State to track signup success const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const handleSubmit = async (e) => { e.preventDefault(); if (password.length < 8) { setError("Password must be at least 8 characters long"); return; } try { setLoading(true); const response = await axios.post( "https://cravings-5jte.onrender.com/user/signup", { firstName, lastName, email, password, } ); // Redirect to /cart upon successful signup if (response.status === 201) { setSignupSuccess(true); console.log(response.data); } else if (response.status === 404) { console.log(response.data); } } catch (error) { console.error("Signup failed:", error.response?.data?.message); } finally { setLoading(false); } }; // Use useEffect to perform the redirect once signupSuccess changes useEffect(() => { if (signupSuccess) { window.location.href = "/login"; // Redirect to /cart } }, [signupSuccess]); return ( <> <div className={styles.center}> {error && <p className={styles.error}>{error.response.data.message}</p>} <form className={styles.signupCard} onSubmit={handleSubmit}> <input type="firstName" name="firstName" id="firstName" className={styles.firstName} placeholder="First Name" value={firstName} onChange={(e) => { setFirstName(e.target.value); }} required /> <input type="lastName" name="lastName" id="lastName" className={styles.lastName} placeholder="Last Name" value={lastName} onChange={(e) => { setLastName(e.target.value); }} required /> <input type="email" name="email" id="email" className={styles.email} placeholder="Email" value={email} onChange={(e) => { setEmail(e.target.value); }} required /> <input type="password" name="password" id="password" className={styles.password} placeholder="Password" value={password} onChange={(e) => { setPassword(e.target.value); }} required /> <p className={styles.hint}> Password should be at least 8 characters, must include one uppercase letter, one lowercase letter, one number and one sppecial character.{" "} </p> <button className={styles.submit} type="submit" disabled={loading}> {loading ? ( <div className={`${styles.spinner} ${styles.loading}`} /> ) : ( "Signup" )} </button> </form> </div> </> ); }; export default Signup;
<!DOCTYPE html> <html class=" negro" lang="es-ES"> <meta charset="utf-8"> <meta name="viewport" content="witdth=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0"> <link href="https://fonts.googleapis.com/css?family=Fira+Code|Press+Start+2P|Source+Code+Pro&display=swap" rel="stylesheet"> <link rel="stylesheet" href="/css/bulma.css" /> <link rel="stylesheet" href="/css/style.css" /> <link rel="stylesheet" href="/css/navbar.css" /> <title>Mysql desde tu shell - Blg0</title> <meta name="generator" content="Hugo 0.83.1" /> <body class="grisOscuro"><nav class="lateral-navbar"> <ul class="lateral-navbar-nav bordeVerde"> <li class="start2p lateral-nav-item "> <a href="/" class="lateral-nav-link textoVerde"> <img src="/img/disk.png" class="nav-img iconsP panel-icon" alt=""> <span class="textoVerde lateral-nav-text">Home</span> </a> </li> <li class="start2p lateral-nav-item "> <a href="/posts/" class="lateral-nav-link textoVerde"> <img src="/img/paper.png" class="nav-img iconsP panel-icon" alt=""> <span class="textoVerde lateral-nav-text">Posts</span> </a> </li> <li class="start2p lateral-nav-item "> <a href="/projects/" class="lateral-nav-link textoVerde"> <img src="/img/flami.png" class="nav-img iconsP panel-icon" alt=""> <span class="textoVerde lateral-nav-text">Projects</span> </a> </li> <li class="start2p lateral-nav-item "> <a href="/about/" class="lateral-nav-link textoVerde"> <img src="/img/gosht.png" class="nav-img iconsP panel-icon" alt=""> <span class="textoVerde lateral-nav-text">About</span> </a> </li> </ul> </nav> <nav class="container-fluid negro "> <div class=" "> <div class=" "> <a class="" href="/"> <figure class="centrar image is-128x128"> <img class="bordeVerde is-rounded" src="https://avatars2.githubusercontent.com/u/13577926?s=460&amp;v=4" width="50" height="50"alt="Brand"> </figure> </a> </div> <div class=" "> <a href="" class=""> <h1 class="textoCentrado textoVerde start2p title is-1 "> Blg0</h1> </a> </div> </div> </nav> <div id="content"> <h1></h1> <div role="main" class="sourceCode section" > <div class="columns"> <div class="column is-2"> </div> <div class="column is-8"> <div class="negro bordeVerde"> <div class="column textoCentrado"> <h3 class="textoVerde start2p title is-4">Post</h3> </div> </div> <div class="column"></div> <div class="column card grisClaro bordeVerde"> <div class="start2p card-header"> <div class="card-header-title is-centered"> Mysql desde tu shell </div> </div> <div class="card-content"></div> <div class="start2p card-header"> <div class="content" style="font-size: 70%; color: #92d192;"> <nav id="TableOfContents"> <ul> <li> <ul> <li><a href="#de-que-va-esto">De que va esto</a></li> <li><a href="#primero-lo-primero">Primero lo primero</a> <ul> <li> <ul> <li> <ul> <li><a href="#instalando"><strong>Instalando</strong></a></li> </ul> </li> </ul> </li> </ul> </li> <li><a href="#pasemos-al-uso">Pasemos al uso</a> <ul> <li><a href="#configuración">Configuración</a></li> </ul> </li> </ul> </li> </ul> </nav> </div> </div> <div class="card-content"> <div class=""> <div class="content formatoTexto"> <h2 id="de-que-va-esto">De que va esto</h2> <p>Levantar un servidor <strong>MySQL</strong> para tus proyectos es tan sencillo como tener cualquier distribución GNU/linux o similares y asegurarte de seguir algunos pasos sencillos.</p> <h2 id="primero-lo-primero">Primero lo primero</h2> <h5 id="instalando"><strong>Instalando</strong></h5> <p>Según tu sistema(y si no lo tienes instalado) tendrás que utilizar:</p> <div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-shell" data-lang="shell"> apt-get -y install mysql-server <span style="color:#75715e">#instalar</span> service mysql start <span style="color:#75715e">#añadir al arranque</span> </code></pre></div><div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-shell" data-lang="shell"> yum install mysql-server <span style="color:#75715e">#instalar</span> /sbin/service mysqld start <span style="color:#75715e">#arrancar</span> chkconfig mysqld on <span style="color:#75715e">#añadir al arranque</span> </code></pre></div><p>O similares para otros sistemas.</p> <h2 id="pasemos-al-uso">Pasemos al uso</h2> <h3 id="configuración">Configuración</h3> <p>Primeramente el root tendrá los permisos y deberás crear las bases y configurar los permisos para otros usuarios usando esta cuenta.</p> <div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-shell" data-lang="shell"> mysql -u root -p <span style="color:#75715e">#acceso con la cuenta root</span> </code></pre></div><p><strong>Ahora pasamos a un poco de mysql</strong></p> <div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-mysql" data-lang="mysql"> <span style="color:#66d9ef">CREATE</span> <span style="color:#66d9ef">DATABASE</span> nombreEjemplo; <span style="color:#f92672">--</span>nueva base <span style="color:#66d9ef">GRANT</span> <span style="color:#66d9ef">USAGE</span> <span style="color:#66d9ef">ON</span> nombreEjemplo.<span style="color:#f92672">*</span> <span style="color:#66d9ef">TO</span> nombreUsuario<span style="color:#f92672">@</span>localhost <span style="color:#66d9ef">IDENTIFIED</span> <span style="color:#66d9ef">BY</span> <span style="color:#e6db74">&#39;password&#39;</span>; <span style="color:#f92672">--</span>credenciales para otro usuario <span style="color:#66d9ef">GRANT</span> <span style="color:#66d9ef">ALL</span> <span style="color:#66d9ef">PRIVILEGES</span> <span style="color:#66d9ef">ON</span> nombreEjemplo.<span style="color:#f92672">*</span> <span style="color:#66d9ef">TO</span> nombreUsuario<span style="color:#f92672">@</span>localhost ; <span style="color:#f92672">--</span>cuidado con los privilegios, esto es un ejemplo <span style="color:#66d9ef">FLUSH</span> <span style="color:#66d9ef">PRIVILEGES</span>; </code></pre></div><p>Ya lo tenemos configurado, ahora podemos acceder con nuestras <em>nuevas credenciales</em> y listo.</p> <div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-shell" data-lang="shell"> mysql -u nombreUsuario -p<span style="color:#e6db74">&#39;password&#39;</span> <span style="color:#e6db74">&#39;nombreEjemplo&#39;</span> </code></pre></div><p>Saludos <a href="https://github.com/DarFig">DarFig</a></p> </div> <br> </div> </div> <div class=" card-footer is-right"> <div class="card-header-title is-centered"> March 13 - 2017 </div> </div> </div> </div> </div> </div> </div> <div class="alpie"></div> </body><footer class="negro pie"> <div class="container"> <div> <br> <p align="center" class="textoVerde LettCab text-muted"> © by darfig <a href="https://github.com/DarFig">https://github.com/DarFig</a> </p> </div> </div> </footer> </html>
function [I] = simpson(f, a, b, n) % Approximates integral_a^b f(x) dx using composite simpsons rule made of n % basic simpson rules. if nargin < 4, error('Please supply all arguments!'), end if n < 1, error('Number of subintervals must be >= 1'), end if n ~= floor(n), error('Number of intervals must be an integer, got %f', n), end if abs(a-b) < eps, I = 0.0; return, end if b < a, I = -simpson(f, b, a, n); return, end % sedaj vemo, da je a < b x = linspace(a, b, 2*n+1); fx = f(x); I = fx(1) + fx(end) + 4*sum(fx(2:2:end-1)) + 2*sum(fx(3:2:end-2)); I = I * (b-a) / 6 / n; end
import { db } from 'database'; import { IProduct } from 'interfaces'; import { MProduct } from 'models'; export const getProductsBySlug = async (slug: string): Promise<IProduct | null> => { await db.connect(); const product = await MProduct.findOne({ slug }).lean(); await db.disconnect(); if (!product) { return null; } return JSON.parse(JSON.stringify(product)); }; interface IProductSlug { slug: string; } export const getAllProductSlugs = async (): Promise<IProductSlug[]> => { await db.connect(); const slugs = await MProduct.find().select('slug -_id').lean(); await db.disconnect(); return slugs; }; export const getProductsBySearch = async (query: string): Promise<IProduct[]> => { const term = query.toString().toLowerCase().trim(); await db.connect(); const products = await MProduct.find({ $text: { $search: term } }) .select('title images price inStock slug -_id') .lean(); await db.disconnect(); return products; }; export const getAllProducts = async (): Promise<IProduct[]> => { await db.connect(); const products = await MProduct.find().lean(); await db.disconnect(); return JSON.parse(JSON.stringify(products)); };
use std::collections::HashMap; use chrono::NaiveDate; use common_macros::hash_map; use serde_json::Value; use crate::edupage::RequestType::POST; use crate::edupage::{Edupage, EdupageError}; use crate::edupage_traits::Substitution; impl Substitution for Edupage { fn get_substitution_html( &self, date: &NaiveDate, subdomain: &String, ) -> Result<String, EdupageError> { let url = format!( "https://{}.edupage.org/substitution/server/viewer.js?__func=getSubstViewerDayDataHtml", subdomain ); let headers = hash_map! { "Content-Type".to_string() => "application/json".to_string() }; // no point in trying to serialize, too complex structure let post_data = format!( "{{\"__args\":[null,{{\"date\":\"{}\",\"mode\":\"classes\"}}],\"__gsh\":\"{}\"}}", date.format("%Y-%m-%d"), self.gsec_hash.as_ref().unwrap() ); let response = match self.request(url, POST, Some(headers), Some(post_data)) { Ok(x) => x, Err(e) => return Err(EdupageError::HTTPError(e)), }; Ok(match response.json::<HashMap<String, Value>>() { Ok(x) => { let r = x.get("r"); if r.is_none() { return Err(EdupageError::SerializationError( "Failed to traverse json".to_string(), )); } r.unwrap().as_str().unwrap().to_string() } Err(e) => return Err(EdupageError::SerializationError(e.to_string())), }) } }
import { Controller, Get, UseGuards } from '@nestjs/common'; import { FindAllUsersUseCase } from '../../../../application/use-cases/user/find-all-users.use-case'; import { AuthGuard } from '../../../../infrastructure/guard/auth.guard'; import { UserPresenter } from '../../presenters/user.presenter'; @Controller('/users/get/all') export class FindAllUsersController { constructor(private findAllUsersUseCase: FindAllUsersUseCase) {} @UseGuards(AuthGuard) @Get() async findAll() { const users = await this.findAllUsersUseCase.execute(); return users.map((user) => UserPresenter.toHttp(user)); } }
import { Button, IconButton, Slide, TextField } from "@mui/material"; import { Box, styled } from "@mui/system"; import { Colors } from "../../styles/theme"; import SearchIcon from "@mui/icons-material/Search"; import CloseIcon from "@mui/icons-material/Close"; import { useUIContext } from "../../context/ui"; import useDialogModal from "../../hooks/useDialogModal"; import {useState} from 'react'; const SearchBoxContainer = styled(Box)(({ theme }) => ({ position: "absolute", top: 0, left: 0, width: "100%", height: "100%", background: Colors.primary, display: "flex", justifyContent: "center", alignItems: "center", zIndex: 99999, opacity: 0.9, })); const SearchField = styled(TextField)(({ theme }) => ({ ".MuiInputLabel-root": { color: Colors.secondary, }, ".MuiInput-root": { fontSize: '1rem', [theme.breakpoints.up('md')]: { fontSize: '2rem', }, color: Colors.secondary, }, ".MuiInput-root::before": { borderBottom: `1px solid ${Colors.secondary}`, }, padding: "0 0 0 40px", })); export default function SearchBox(ProductDetail) { const [query,setQuery] = useState(''); const [foundProduct,setFoundProduct] = useState({}); const [ProductDetailDialog, showProductDetailDialog, closeProductDialog] = useDialogModal(ProductDetail); const handleSearch = (e) => { const search_product = ProductDetail.ProductDetail; search_product.filter((product) => { if (product.name.trim() === query.trim()) { console.log(product.name); setFoundProduct(product); showProductDetailDialog(); } }); } const { showSearchBox, setShowSearchBox } = useUIContext(); return ( <Slide direction="down" in={showSearchBox} timeout={500}> <SearchBoxContainer> <SearchField color="secondary" variant="standard" fullWidth placeholder="search..." onChange={(e) => setQuery(e.target.value)} /> <IconButton onClick={handleSearch}> <SearchIcon sx={{ fontSize: { xs: '2rem', md: "3rem" } }} color="secondary" /> </IconButton> <IconButton onClick={() => setShowSearchBox(false) } sx={{ position: "absolute", top: 10, right: 10, }} > <CloseIcon sx={{ fontSize: "4rem" }} color="secondary" /> {/* <ProductMeta product={foundProduct} /> <ProductDetailDialog product={foundProduct} /> */} </IconButton> </SearchBoxContainer> </Slide> ); }
import 'package:SDB/domain/service/constants/color.dart'; import 'package:SDB/presentation/ui/pages/catalog/riverpod/provider/catalog_provider.dart'; import 'package:SDB/presentation/ui/pages/widgets/loading_animation.dart'; import 'package:auto_route/auto_route.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../routes/routes.dart'; @RoutePage() class CatalogPage extends ConsumerStatefulWidget { const CatalogPage({super.key}); @override ConsumerState<CatalogPage> createState() => _CatalogPageState(); } class _CatalogPageState extends ConsumerState<CatalogPage> with AutomaticKeepAliveClientMixin{ @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { ref.read(catalogProvider.notifier).getCategory(slug: "list"); }); } @override Widget build(BuildContext context) { // final notifier = ref.read(catalogProvider.notifier); final state = ref.watch(catalogProvider); return Container( color: AppColors.white, child: state.isLoading ? Container( color: AppColors.white, child: const Center( child: CustomLoadingAnimation(), )) : state.category?.categories != null ? ListView.builder( itemCount: state.category!.categories!.length, itemBuilder: (BuildContext context, int index) => Container( margin: const EdgeInsets.symmetric(vertical: 8), decoration: BoxDecoration( color: AppColors.blueOpacity, borderRadius: BorderRadius.circular(25), border: Border.all(color: AppColors.primaryOpacity), ), child: ClipRRect( borderRadius: BorderRadius.circular(12), child: Theme( data: ThemeData( dividerColor: AppColors.transparent, shadowColor: AppColors.transparent), child: ExpansionTile( title: InkWell( onTap: () { context.router.push(ProductListVerticalRoute( slug: state .category!.categories![index].slug .toString())); if (kDebugMode) { print(state.category!.categories![index].slug .toString()); } }, child: Text(state .category!.categories![index].nameUz .toString(),style: TextStyle(color: AppColors.primaryColor,fontSize: 18,fontWeight: FontWeight.bold))), children: List.generate( state.category!.categories![index].children!.length, (value) => Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: Theme( data: ThemeData( dividerColor: AppColors.transparent), child: ExpansionTile( title: InkWell( onTap: () { context.router.push(ProductListVerticalRoute( slug: state.category!.categories![index] .children![value].slug .toString())); if (kDebugMode) { print(state.category!.categories![index] .children![value].slug .toString()); } }, child: Text(state.category!.categories![index] .children![value].nameUz .toString(),style: TextStyle(color: AppColors.primaryColor,fontSize: 16,fontWeight: FontWeight.w700),), ), children: List.generate( state.category!.categories![index] .children![value].children!.length, (item) => Padding( padding: const EdgeInsets.symmetric( horizontal: 8.0), child: InkWell( onTap: () { context.router.push(ProductListVerticalRoute( slug: state .category! .categories![index] .children![value] .children![item] .slug .toString(),)); if (kDebugMode) { print(state .category! .categories![index] .children![value] .children![item] .slug .toString(),); } }, child: ListTile( title: Text(state .category! .categories![index] .children![value] .children![item] .nameUz .toString(),style: TextStyle(color: AppColors.primaryColor,fontSize: 14,fontWeight: FontWeight.w600),)), ), ), ), ), ), ), ), ), ), ), ), ) : Container( color: AppColors.white, child: const Center( child: Text("Muammo chiqdi"), ), ), ); // Center(child: Text(state.category?.categories?[0].nameUz ?? "Hello"),); } @override // TODO: implement wantKeepAlive bool get wantKeepAlive => true; }
import { useState } from 'react' import { useNavigate, Link } from 'react-router-dom' import { useForm } from 'react-hook-form' import { AxiosResponse } from 'axios' import { zodResolver } from '@hookform/resolvers/zod' import axios from '../services/axios' import { User } from '../types' import { loginSchema, LoginInput } from '../schema/auth.schema' import useStore from '../store' import logo from '../assets/logo.png' function Login () { const [loginError, setLoginError] = useState<any | null>(null) const [loading, setLoading] = useState<boolean>(false) const { register, formState: { errors }, handleSubmit } = useForm<LoginInput>({ resolver: zodResolver(loginSchema) }) const { setUser } = useStore() const nav = useNavigate() async function onSubmit (values: LoginInput) { try { console.log(loginError) setLoading(true) const { data }: AxiosResponse<User['body']> = await axios.post( '/api/login', values ) setLoading(false) setUser(data) nav('/dashboard', { replace: true }) } catch (e: any) { console.log(e) setLoginError(e.message) setLoading(false) } } console.log({ errors }) return ( <main className='relative min-h-screen w-full bg-slate-800'> <div className='p-6'> <header className='flex w-full justify-end'> <div> <Link to='/register' className='rounded-2xl border-b-2 border-b-lime-300 bg-lime-400 py-3 px-4 font-bold text-white ring-2 ring-lime-300 hover:bg-lime-600 active:translate-y-[0.125rem] active:border-b-lime-200 transition' > REGISTER </Link> </div> </header> <section className='flex flex-col items-center justify-center mx-auto max-w-sm'> <img src={logo} alt='Froz logo' className='my-14' /> <div className='space-y-4'> <h1 className='text-4xl font-bold mb-6 text-center'>Log in</h1> <p className='text-center text-red-500 text-md'> {loginError && 'Wrong email or password'} </p> <form onSubmit={handleSubmit(onSubmit)}> <div> <label htmlFor='email'>Email</label> <div className='w-full my-2 rounded-2xl bg-gray-200 px-4 ring-2 ring-gray-100 focus-within:ring-lime-400 text-gray-900'> <input type='email' id='email' placeholder='example@mail.com' autoComplete='off' required className='my-3 w-full border-none bg-transparent outline-none focus:outline-none' {...register('email')} /> </div> <p>{errors.email?.message}</p> </div> <div> <label htmlFor='password'>Password</label> <div className='w-full my-2 rounded-2xl bg-gray-200 px-4 ring-2 ring-gray-100 focus-within:ring-lime-400 text-gray-900'> <input type='password' id='password' placeholder='******' autoComplete='off' required className='my-3 w-full border-none bg-transparent outline-none focus:outline-none' {...register('password')} /> </div> <p>{errors.password?.message}</p> </div> {loading ? ( <button disabled className='w-full rounded-2xl border-b-4 border-b-lime-600 bg-lime-500 py-3 font-bold text-white my-4' > Loading... </button> ) : ( <button type='submit' className='w-full rounded-2xl border-b-4 border-b-lime-600 bg-lime-500 py-3 font-bold text-white hover:bg-lime-400 active:translate-y-[0.125rem] active:border-b-lime-700 my-4' > LOG IN </button> )} </form> <p className='text-white text-sm'> Go to{' '} <Link to='/register' className='text-lime-500 hover:underline'> Register Page </Link> </p> </div> </section> </div> </main> ) } export default Login
# AI Rules: client The client part is where all the code related to the front-end is stored. It is a Next.js application, which is a React framework. The client is a web application that can be run in a browser. It is the part of the project that the user will interact with. ## 1. Run the client in localhost To run the client in localhost, you need to first open a terminal, go to the client directory and run the following command: <code> npm install </code> This will install all the dependencies of the client. Then you can run the client with the following command: `npm run dev` This should give you the following message in the terminal : <pre> > client@0.1.0 dev > next dev ▲ Next.js 14.0.3 - Local: http://localhost:3000 ✓ Ready in 3s </pre> You can then open a browser and go to the following address: http://localhost:3000 to see the client running. ## 2. Architecture of the repository ### A. app This directory contains the pages of the client. Each page is a React component. (Here there is only one page) ### B. components This directory contains all the React components used in the client. They are divided into two subdirectories: ui and the rest. The ui directory contains the components that are used to build the user interface. The rest of the directory contains the other components. ### C. public This directory contains all the static files (such as pictures) used in the client. ### D. config files These files are essential for the client to work : <code> package-json </code> : contains the dependencies of the client that need to be installed with the command <code> npm install </code> <code> tailwing.config</code> : contains the general style of the client and the animations ## 3. Roadmap The nexts steps will be to : - Keep stored the previous conversations of the user and make them accessible in the sidebar - Add streaming for displaying the messages in real time (rather than a pop-up)
package com.health.application.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.health.constant.MessageConstant; import com.health.pojo.CheckGroup; import com.health.pojo.PageResult; import com.health.pojo.QueryPageBean; import com.health.pojo.Result; import com.health.service.CheckGroupService; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/checkgroup") public class CheckGroupController { @Reference private CheckGroupService checkGroupService; @RequestMapping("/add") public Result add(@RequestBody CheckGroup checkGroup, Integer[] checkitemIds ){ try { checkGroupService.add(checkGroup,checkitemIds); return new Result(true, MessageConstant.ADD_CHECKGROUP_SUCCESS); } catch (Exception e) { e.printStackTrace(); return new Result(false, MessageConstant.ADD_CHECKGROUP_FAIL); } } @RequestMapping("/findPage") public PageResult findPage(@RequestBody QueryPageBean queryPageBean){ PageResult pageResult=checkGroupService.pageQuery( queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString() ); return pageResult; } //根据id查询 @RequestMapping("/findById") public Result findById(Integer id){ CheckGroup checkGroup = checkGroupService.findById(id); if(checkGroup != null){ Result result = new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS); result.setData(checkGroup); return result; } return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL); } //根据检查组合id查询对应的所有检查项id @RequestMapping("/findCheckItemIdsByCheckGroupId") public List<Integer> findCheckItemIdsByCheckGroupId(Integer id){ List<Integer> list = checkGroupService.findCheckItemIdsByCheckGroupId(id); return list; } //编辑 @RequestMapping("/edit") public Result edit(@RequestBody CheckGroup checkGroup,Integer[] checkitemIds){ try { checkGroupService.edit(checkGroup,checkitemIds); }catch (Exception e){ return new Result(false,MessageConstant.EDIT_CHECKGROUP_FAIL); } return new Result(true,MessageConstant.EDIT_CHECKGROUP_SUCCESS); } //查询所有 @RequestMapping("/findAll") public Result findAll(){ List<CheckGroup> checkGroupList = checkGroupService.findAll(); if(checkGroupList != null && checkGroupList.size() > 0){ Result result = new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS); result.setData(checkGroupList); return result; } return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL); } }
package ex06; import java.util.Scanner; public class Example09 { public static int solution(int n, int m, int[] songs) { int answer = 0; int min = 0; int max = 0; for(int song : songs) { max += song; } while(min < max) { int mid = (min+max)/2; int sum = 0, count = 0; for(int song : songs) { int tmp = sum+song; if(tmp <= mid) { sum += song; } else { sum = song; count++; } } if(count >= m) { min = mid + 1; } else { max = mid; } } return min; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); int[] songs = new int[n]; for(int i=0; i<n; i++) { songs[i] = scan.nextInt(); } System.out.println(solution(n, m, songs)); } }
import { StyleSheet, Text, View, Button, ScrollView, } from "react-native"; import { useEffect, useState, useRef } from "react"; import { Camera } from "expo-camera"; import * as MediaLibrary from "expo-media-library"; import { ScreenBase } from "../common/ScreenBase"; import SensoresList from "../../screens/sensores/SensoresList.js"; import { observer, inject } from "mobx-react"; import DbOperations from "../../database/DbOperations"; const minutes = 30; // base em minutos const timeLimit = 60 * minutes; // base em 60 segundos = 1 min const seconds32 = 32 * 1000; // base em milisegundos = 1000 -> 32 segundos const timeLimitTimeout = (60000 * minutes) - seconds32; // (60000 = 1 minuto * minutes) - 32 segundos let thread = null; let timeoutEvent = null; const TimerDisplay = () => { const [timer, setTimer] = useState(30); useEffect(() => { thread = setInterval(() => { setTimer((timer) => { if (timer > 0) return timer - 1; else { return timer; } }); }, 1000); }, []); return ( <View style={styles.timerBackground}> <Text style={styles.timer}>{timer}</Text> </View> ); } function Recording({ navigation, RegisteredSniffersStore }) { const { startLogs, stopLogs, getExecutionInfo, } = RegisteredSniffersStore; const [timeOutComponent, setTimeOutComponent] = useState(null); let cameraRef = useRef(); const [hasCameraPermission, setHasCameraPermission] = useState(); const [hasMicrophonePermission, setHasMicrophonePermission] = useState(); const [hasMediaLibraryPermission, setHasMediaLibraryPermission] = useState(); const [isRecording, setIsRecording] = useState(false); const [video, setVideo] = useState(); useEffect(() => { (async () => { const cameraPermission = await Camera.requestCameraPermissionsAsync(); const microphonePermission = await Camera.requestMicrophonePermissionsAsync(); const mediaLibraryPermission = await MediaLibrary.requestPermissionsAsync(); setHasCameraPermission(cameraPermission.status === "granted"); setHasMicrophonePermission(microphonePermission.status === "granted"); setHasMediaLibraryPermission(mediaLibraryPermission.status === "granted"); await DbOperations.removeAllTempExecutions(); })(); }, []); if ( hasCameraPermission === undefined || hasMicrophonePermission === undefined ) { return <Text>Requestion permissions...</Text>; } else if (!hasCameraPermission) { return <Text>Permission for camera not granted.</Text>; } let recordVideo = () => { startLogs(); setIsRecording(true); let options = { quality: "480p", maxDuration: timeLimit, // 60 segundos * 30 = 30 min, 30 minuto funciona bem mute: false, }; cameraRef.current.recordAsync(options).then((recordedVideo) => { // this is called when stopRecording(), maxDuration o maxFileSize is reached stopLogs(); setVideo(recordedVideo); setIsRecording(false); // navigation.navigate('execution-preview', {video: recordedVideo, execution}); }); timeoutEvent = setTimeout(() => { setTimeOutComponent(<TimerDisplay />); }, timeLimitTimeout); }; if (video) { clearInterval(thread); thread = null; clearTimeout(timeoutEvent); timeoutEvent = null; // setTimeOutComponent(null); const execution = getExecutionInfo(); execution['videoAsset'] = { uri: video.uri }; /* const execution = { executionId: 2, sniffers: [ { wsClientUrl: "ws://192.168.1.199:81", id: 2, portIds: [ { id: 3, portName: "port1" }, { id: 4, portName: "port2" }, ], }, ], videoAsset: { "mediaType": "video", "modificationTime": 1686517909000, "uri": "file:///storage/emulated/0/DCIM/1e37dd68-3a55-462e-9a66-7d2c7dcc77d2.mp4", "filename": "1e37dd68-3a55-462e-9a66-7d2c7dcc77d2.mp4", "width": 1080, "id": "1000010523", "creationTime": 1686517904000, "albumId": "-2075821635", "height": 1920, "duration": 7.783 }, }; */ navigation.navigate('execution-preview', { execution: execution }); } return ( <View style={styles.returnView}> <View style={styles.viewContainer}> <Camera style={styles.cameraContainer} ref={cameraRef} > <Button title={isRecording ? "Stop Recording" : "Record Video"} onPress={isRecording ? () => { cameraRef.current.stopRecording(); } : recordVideo} /> {timeOutComponent} </Camera> </View> <ScrollView> <SensoresList /> </ScrollView> <ScreenBase openRoutesMenu={() => navigation.openDrawer()} /> </View> ); } const styles = StyleSheet.create({ viewContainer: { height: 300, }, cameraContainer: { flex: 1, alignItems: "center", justifyContent: "flex-end", paddingBottom: 5, }, videoContainer: { flex: 1, }, videoButtonsView: { flex: 1, alignItems: "center", justifyContent: "flex-end", paddingBottom: 5, }, video: { flex: 1, }, returnView: { flex: 1, }, timer: { fontSize: 18, color: 'white', }, timerBackground: { width: 40, height: 40, borderRadius: 20, // Half the width and height to create a circle backgroundColor: '#3B3B3B', justifyContent: 'center', alignItems: 'center', position: 'absolute', right: 4, bottom: 4, } }); export default inject("RegisteredSniffersStore")(observer(Recording));
Title: Integrating MySQL with Flask, pandas and pythonanywhere Date: 2020-05-25 21:48 Author: pythonmarketer Category: data, Databases, ODBC, pandas, programming, SQL, web development, web2py Tags: flask, mysql, py4web, pyDAL, python Slug: essential-mysql-terminal-commands-and-connecting-to-mysql-with-flask-pandas-and-pythonanywhere Status: published `<!-- wp:paragraph -->`{=html} Sometimes a spark comes from seemingly nowhere. That's when you reach for your tools and create. After a series of successful experiments, I decided this stack might be my quickest, best shot to get a functional website up and running in Python. I was pleasantly surprised to make rapid progress over the span of a quarantine weekend. Here are the steps to create a [MySQL backed website](https://weedfiend.pythonanywhere.com) with Flask. `<!-- /wp:paragraph -->`{=html} `<!-- wp:paragraph -->`{=html} **Hosting With pythonanywhere** `<!-- /wp:paragraph -->`{=html} `<!-- wp:paragraph -->`{=html} [pythonanywhere](https://www.pythonanywhere.com/user/weedfiend/) is a web hosting service like GoDaddy. If you host your app with them, MySQL is the default database. Postgres integration is available at higher price tiers. `<!-- /wp:paragraph -->`{=html} `<!-- wp:paragraph -->`{=html} **To get your Flask app's database up and running you need to:** `<!-- /wp:paragraph -->`{=html} `<!-- wp:list {"ordered":true} -->`{=html} 1. Create your database (see the "Databases" tab in pythonanywhere) 2. Use the mysql terminal to create your tables 3. Use the mysql.connector API to connect to your table and execute SQL from your Flask app. `<!-- /wp:list -->`{=html} `<!-- wp:heading -->`{=html} ## Essential MySQL Terminal Commands `<!-- /wp:heading -->`{=html} `<!-- wp:paragraph -->`{=html} **Show MySQL Version** `<!-- /wp:paragraph -->`{=html} `<!-- wp:preformatted -->`{=html} ``` wp-block-preformatted SELECT VERSION(); ``` `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} **List tables in a database** `<!-- /wp:paragraph -->`{=html} `<!-- wp:preformatted -->`{=html} ``` wp-block-preformatted SHOW TABLES; ``` `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} **Show All MySQL Variable Values** `<!-- /wp:paragraph -->`{=html} `<!-- wp:preformatted -->`{=html} ``` wp-block-preformatted SHOW VARIABLES; ``` `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} **Creating a Table** `<!-- /wp:paragraph -->`{=html} `<!-- wp:preformatted -->`{=html} ``` wp-block-preformatted CREATE TABLE Marijuana (id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(350), date VARCHAR(350)); ``` `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} **[Create a Table with a JSON column](https://www.sitepoint.com/use-json-data-fields-mysql-databases/)** `<!-- /wp:paragraph -->`{=html} `<!-- wp:preformatted -->`{=html} ``` wp-block-preformatted CREATE TABLE ​Marijuana ( `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, `store` varchar(200) NOT NULL, `details` json DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB; ``` `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} **Add New Column and specify column to insert AFTER** `<!-- /wp:paragraph -->`{=html} `<!-- wp:preformatted -->`{=html} ``` wp-block-preformatted ALTER TABLE Marijuana ADD COLUMN date VARCHAR(100) AFTER other_column; ``` `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} **Alter Datatype of a Column** `<!-- /wp:paragraph -->`{=html} `<!-- wp:preformatted -->`{=html} ``` wp-block-preformatted ALTER TABLE Marijuana MODIFY id INT AUTO_INCREMENT PRIMARY KEY; ``` `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} **Describe a Table** `<!-- /wp:paragraph -->`{=html} `<!-- wp:preformatted -->`{=html} ``` wp-block-preformatted DESCRIBE Marijuana; ``` `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} **View All Records in a Table** `<!-- /wp:paragraph -->`{=html} ``` wp-block-preformatted SELECT * from Marijuana; ``` `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} [**Using LIKE in MySQL**](https://www.mysqltutorial.org/mysql-like/) **Select 10 Newest Records** ``` {.prettyprint .notranslate .prettyprinted} SELECT * from Marijuana ORDER BY id DESC LIMIT 10; ``` **"Explaining" A Query** ``` wp-block-preformatted EXPLAIN SELECT * from Marijuana; ``` `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} **Using "ANALYZE TABLE" to [optimize them](https://dev.mysql.com/doc/refman/8.0/en/statement-optimization.html) is periodically recommended by MySQL:** ANALYZE TABLE Marijuana; `<!-- /wp:paragraph -->`{=html} `<!-- wp:image {"id":3418} -->`{=html} ```{=html} <figure> ``` ```{=html} </figure> ``` ![](https://pythonmarketer.files.wordpress.com/2020/05/mysql_commands-1.png){.wp-image-3418} `<!-- /wp:image -->`{=html} `<!-- wp:heading -->`{=html} ## Installing Libraries in PythonAnywhere You can use [pip](http://pythonmarketer.wordpress.com/2018/01/20/how-to-python-pip-install-new-libraries/) to install python libraries within the PythonAnywhere bash terminal. Go to the consoles tab and start a new bash terminal. Then to install a library, such as pandas: python -m pip3.8 install --user pandas ## Flask app with [mysql.connector API](https://dev.mysql.com/doc/connector-python/en/), SQL and pandas `<!-- /wp:heading -->`{=html} `<!-- wp:paragraph -->`{=html} **A Flask app making a mysql database connection with pandas:** `<!-- /wp:paragraph -->`{=html} `<!-- wp:list {"ordered":true} -->`{=html} 1. Creating an error log with logging. 2. Connecting to a mysql database hosted through [Flask](https://flask.palletsprojects.com/en/1.1.x/quickstart/) and [pythonanywhere](http://pythonanywhere.com) 3. Then reading a table to a pandas [dataframe](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) `<!-- /wp:list -->`{=html} `<!-- wp:preformatted -->`{=html} ``` wp-block-preformatted import mysql.connector from flask import Flask import pandas as pd from datetime import date import logging import sys """ Flask + MySQL + pandas app from Python Marketer: https://atomic-temporary-107329037.wpcomstaging.com/2020/05/25/essential-mysql-terminal-commands-and-connecting-to-mysql-with-flask-pandas-and-pythonanywhere/ """ app = Flask(__name__) logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) @app.route('/') def hello_world(): """Call database and return data from df. Then display homepage.""" try: email_df = get_database_table_as_dataframe() print(email_df.shape) html_page = render_homepage() return html_page except: logging.exception('Failed to connect to database.') def render_homepage(): """ Note: you should use Flask's render_template to render HTML files. But here's a quick f-string HTML page that works: """ html_page = f"""<html><head><link rel='stylesheet' href="/static/styles/some_file.css"><link rel="shortcut icon" type="image/x-icon" href="static/favicon.ico"> <Title>Support BLM</Title></head> <body><h2>Black Lives Matter</h2> <p>No to Systemic Racism!</p><br> <h6><b>Support BLM:</b></h6><br> <div class="form"> <form action="/add_signup_to_db" method="post" style="width:420px;text-align:center;display:block;" > <input type="text" name="Signup Form"> <input type="submit" value="Submit"> </form></div><br><br> <p><b>Current Time:</b> {str(date.today())} </p></body></html>""" return html_page ``` `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} `<!-- /wp:paragraph -->`{=html} `<!-- wp:preformatted -->`{=html} `<!-- /wp:preformatted -->`{=html} `<!-- wp:paragraph -->`{=html} `<!-- /wp:paragraph -->`{=html} `<!-- wp:paragraph -->`{=html} def get_database_table_as_dataframe(): """Connect to a table named 'Emails'. Returns pandas dataframe.""" try: connection = mysql.connector.connect( host='username.mysql.pythonanywhere-services.com', db='username$DatabaseName', user='username', password='password' ) email_df = pd.read_sql(sql="""SELECT * FROM Emails""", con=connection) logging.info(email_df.head()) return email_df except: logging.exception('Failed to fetch dataframe from DB.') return "Oops!" @app.route("/add_signup_to_db", methods=["GET","POST"]) def add_signup_to_db(email, date): """Pass data as SQL parameters with mysql.""" try: connection = mysql.connector.connect( host='username.mysql.pythonanywhere-services.com', db='username$DatabaseName', user='username', password='password' ) cursor = connection.cursor() sql = """INSERT INTO Emails (message, date) VALUES (%s, %s) """ record_tuple = (email, date) cursor.execute(sql,record_tuple) connection.commit() except mysql.connector.Error as error: logging.info("Failed to insert into MySQL table {}".format(error)) except: logging.exception('Error inserting records to DB.') finally: if (connection.is_connected()): cursor.close() connection.close() return("MySQL connection is closed") **Iterative Development** > Below: making [my website](https://weedfiend.pythonanywhere.com/) look less like a "my first HTML" website, experimenting with my app's message\\name and adding a sign-up form connected to the database. ![Screenshot_20200606-132252 (1)](https://pythonmarketer.files.wordpress.com/2020/05/screenshot_20200606-132252-1-1.png){.alignnone .size-full .wp-image-3524 width="344" height="566"} **Note: if you see this error when making a request in pythonanywhere:** `<!-- wp:paragraph -->`{=html} `OSError: Tunnel connection failed: 403 Forbidden ` It's likely because you are "whitelisted" on the free plan. Upgrading to the \$5/month plan will fix it! **Scoping The Full Stack** I'm really enjoying this web development stack. Here are all of the tools and library choices for this website: - [HTML](https://en.wikipedia.org/wiki/HTML) - [CSS](https://www.taniarascia.com/overview-of-css-concepts/) - [web framework](https://en.wikipedia.org/wiki/Web_framework): Flask library - email: [Flask-Mail](https://pythonhosted.org/Flask-Mail/) library ([SMTP](https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol)) - API calls to external websites: [requests](https://requests.readthedocs.io/en/master/) and json libraries - data handling: MySQL database, mysql.connector API, [pandas](https://pythonmarketer.wordpress.com/2018/05/12/pandas-pythons-excel-powerhouse/) library - file system: [logging](https://docs.python.org/3/library/logging.html), os and sys libraries - (may add) payment processing: [Braintree Library](https://github.com/braintree/braintree_python) - web hosting: pythonanywhere **Finding Your Flask Groove** Flask is a little scary at first, but reasonable once you get a grasp of the basic syntax. Using the logging module to establish access, error and server log feeds was a big step to finding my Python traceback fixing groove. It's a work in progress. `<!-- /wp:paragraph -->`{=html} **Recapping My Python Web Development and Database Experiences** I previously created a [website](http://tameimpala.pythonanywhere.com/) with [web2py](https://pythonmarketer.wordpress.com/2016/03/29/getting-started-with-web2py/), another Python web framework like Flask and Django. I think it was a decent choice for me at that point in my Python journey. Back then, I connected a MongoDB back-end to web2py. I randomly picked Mongo out of the DB hat and it worked well enough. > **My Python Web Development and Database Tools** > > **App #1**                    web2py + MongoDB > > **App #2                     **Flask + MySQL  > > **Future App?**      py4web + pyDAL + PostgreSQL > > **Future App?**     tornado + streamlit (or) Flask + Dash (+ SQLite) Of these two diverse Python stacks, I favor MySQL and Flask. But I learned a lot from watching web2py's tutorial videos and it's less intimidating for beginners. And I barely scratched the surface of web2py's "pure Python" [pyDAL (Database Abstraction Layer)](https://github.com/web2py/pydal), which seems pretty dope. web2py's [creator](https://www.youtube.com/watch?v=hcYUgNWvPtw) has a new framework in progress called [py4web](https://github.com/web2py/py4web). It has the same [DAL](http://www.web2py.com/books/default/chapter/29/06/the-database-abstraction-layer) and inherits many other web2py qualities. Definitely looking forward to exploring the DAL on my first py4web website. I'll likely use it to connect to PostgreSQL or SQLite. Maybe I'll [install pyDAL with pip](https://github.com/web2py/pydal) in the meantime. `<!-- /wp:paragraph -->`{=html} `<!-- wp:paragraph -->`{=html} `<!-- /wp:paragraph -->`{=html} `<!-- wp:paragraph -->`{=html} `<!-- /wp:paragraph -->`{=html} `<!-- wp:paragraph -->`{=html} **[Final Thoughts]{style="color:var(--color-text);"}** [Both of my websites are hosted with pythonanywhere, which gives you a text editor and ]{style="color:var(--color-text);"}[bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell))[ terminal to run your scripts in a shell environment. I'm so pleased with all of these tools. They fit together smoothly and made creating my website a fun experience. 👍👍]{style="color:var(--color-text);"} `<!-- /wp:paragraph -->`{=html}
<template> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Leaderboard</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div v-for="(user, key) in leaderboard" :key="user.id" class="my-10 p-4 rounded border border-grey-light flex justify-between" > <span class="text-5xl text-grey-light">{{ key+1 }}. </span> <a :href="userProfileLink(user.username)" class="inline mb-4 text-xl text-blue" >{{ user.username }}</a> <span class="inline px-2 bg-green rounded font-semibold text-white" >{{ user.reputation }} XP</span> </div> </div> </div> </div> </div> </template> <script> export default { name: "Leaderboard", data() { return { leaderboard: {} }; }, created() { this.fetch(); }, methods: { fetch() { window.axios.get("api/leaderboard").then(this.refresh); }, refresh({ data }) { this.leaderboard = data.leaderboard; }, userProfileLink(username) { return `/profiles/${username}`; } } }; </script>
package net.orangejewce.ojs_rpg_origins.item; import net.minecraft.client.gui.screens.Screen; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Style; import net.minecraft.network.chat.TextColor; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.npc.Villager; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.capabilities.ICapabilityProvider; import top.theillusivec4.curios.api.CuriosApi; import top.theillusivec4.curios.api.SlotContext; import top.theillusivec4.curios.api.type.capability.ICurio; import top.theillusivec4.curios.api.type.capability.ICurioItem; import javax.annotation.Nullable; import java.util.List; import java.util.Random; import net.orangejewce.ojs_rpg_origins.config.ThiefGloveConfig; public class ThiefGloveItem extends Item implements ICurioItem { public ThiefGloveItem() { super(new Item.Properties().stacksTo(1).durability(50)); } public void interactWithVillager(ItemStack stack, Player player, Villager villager, InteractionHand hand) { if (!player.level().isClientSide) { if (player.getCooldowns().isOnCooldown(this)) { return; // If on cooldown, do nothing } if (new Random().nextDouble() < ThiefGloveConfig.stealChance.get()) { List<ItemStack> possibleItems = ThiefGloveConfig.getStealableItems(); ItemStack stolenItem = possibleItems.get(new Random().nextInt(possibleItems.size())).copy(); player.getInventory().add(stolenItem); player.level().playSound(null, player.blockPosition(), SoundEvents.PLAYER_ATTACK_SWEEP, SoundSource.PLAYERS, 1.0F, 1.0F); stack.hurtAndBreak(1, player, (p) -> p.broadcastBreakEvent(hand)); // Reduce durability by 1 on success player.getCooldowns().addCooldown(this, ThiefGloveConfig.cooldownTicks.get()); // Add cooldown } else { player.level().playSound(null, player.blockPosition(), SoundEvents.VILLAGER_NO, SoundSource.NEUTRAL, 1.0F, 1.0F); player.getCooldowns().addCooldown(this, ThiefGloveConfig.cooldownTicks.get()); // Add cooldown even if the steal fails } } } @Override public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag unused) { return CuriosApi.createCurioProvider(new ICurio() { @Override public ItemStack getStack() { return stack; } public void curioTick(SlotContext slotContext, ItemStack stack) { // Ticking logic if needed } public boolean canEquipFromUse(SlotContext slotContext, ItemStack stack) { return true; } public boolean canRightClickEquip() { return true; } }); } @Override @OnlyIn(Dist.CLIENT) public void appendHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltipComponents, TooltipFlag flag) { if (Screen.hasShiftDown()) { tooltipComponents.add(Component.translatable("tooltip.thief_glove.details") .setStyle(Style.EMPTY.withColor(TextColor.fromRgb(0x00FF00)).withItalic(true))); } else { tooltipComponents.add(Component.translatable("tooltip.thief_glove") .setStyle(Style.EMPTY.withColor(TextColor.fromRgb(0x00FF00)).withBold(true))); tooltipComponents.add(Component.translatable("tooltip.info_thief_glove") .setStyle(Style.EMPTY.withColor(TextColor.fromRgb(0xFFFFFF)).withItalic(true))); tooltipComponents.add(Component.translatable("tooltip.steal_ability") .setStyle(Style.EMPTY.withColor(TextColor.fromRgb(0xFFD700)))); tooltipComponents.add(Component.translatable("tooltip.steal_shift_right_click") .setStyle(Style.EMPTY.withColor(TextColor.fromRgb(0xFF4500)).withItalic(true))); tooltipComponents.add(Component.translatable("tooltip.shift_info") .setStyle(Style.EMPTY.withColor(TextColor.fromRgb(0xFFFFFF)).withItalic(true))); } super.appendHoverText(stack, level, tooltipComponents, flag); } }
--- title: إضافة صورة Blob إلى العرض التقديمي في شرائح Java linktitle: إضافة صورة Blob إلى العرض التقديمي في شرائح Java second_title: Aspose.Slides واجهة برمجة تطبيقات معالجة Java PowerPoint description: تعرف على كيفية إضافة صور Blob إلى العروض التقديمية لـ Java Slides دون عناء. اتبع دليلنا خطوة بخطوة مع أمثلة التعليمات البرمجية باستخدام Aspose.Slides لـ Java. type: docs weight: 10 url: /ar/java/image-handling/add-blob-image-to-presentation-in-java-slides/ --- ## مقدمة لإضافة صورة Blob إلى العرض التقديمي في شرائح Java في هذا الدليل الشامل، سنستكشف كيفية إضافة صورة Blob إلى عرض تقديمي باستخدام Java Slides. يوفر Aspose.Slides for Java ميزات قوية لمعالجة عروض PowerPoint التقديمية برمجياً. بحلول نهاية هذا البرنامج التعليمي، سيكون لديك فهم واضح لكيفية دمج صور Blob في العروض التقديمية الخاصة بك. دعونا الغوص في! ## المتطلبات الأساسية قبل أن نبدأ، تأكد من توفر المتطلبات الأساسية التالية: - تم تثبيت Java Development Kit (JDK) على نظامك. - Aspose.Slides لمكتبة جافا. يمكنك تنزيله من[هنا](https://releases.aspose.com/slides/java/). - صورة Blob التي تريد إضافتها إلى العرض التقديمي الخاص بك. ## الخطوة 1: استيراد المكتبات الضرورية في كود Java الخاص بك، تحتاج إلى استيراد المكتبات المطلوبة لـ Aspose.Slides. وإليك كيف يمكنك القيام بذلك: ```java import com.aspose.slides.*; import java.io.FileInputStream; ``` ## الخطوة 2: إعداد المسار حدد المسار إلى دليل المستند الخاص بك حيث قمت بتخزين صورة Blob. يستبدل`"Your Document Directory"` مع المسار الفعلي ```java String dataDir = "Your Document Directory"; String pathToBlobImage = dataDir + "blob_image.jpg"; ``` ## الخطوة 3: قم بتحميل صورة Blob بعد ذلك، قم بتحميل صورة Blob من المسار المحدد. ```java FileInputStream fip = new FileInputStream(pathToBlobImage); ``` ## الخطوة 4: إنشاء عرض تقديمي جديد قم بإنشاء عرض تقديمي جديد باستخدام Aspose.Slides. ```java Presentation pres = new Presentation(); ``` ## الخطوة 5: إضافة صورة النقطة الآن، حان الوقت لإضافة صورة Blob إلى العرض التقديمي. نحن نستخدم ال`addImage` طريقة لتحقيق ذلك. ```java IPPImage img = pres.getImages().addImage(fip, LoadingStreamBehavior.KeepLocked); pres.getSlides().get_Item(0).getShapes().addPictureFrame(ShapeType.Rectangle, 0, 0, 300, 200, img); ``` ## الخطوة 6: احفظ العرض التقديمي وأخيرًا، احفظ العرض التقديمي بصورة Blob المضافة. ```java pres.save(dataDir + "presentationWithBlobImage.pptx", SaveFormat.Pptx); ``` ## أكمل كود المصدر لإضافة صورة Blob إلى العرض التقديمي في شرائح Java ```java // المسار إلى دليل المستندات. String dataDir = "Your Document Directory"; String pathToLargeImage = dataDir + "large_image.jpg"; // قم بإنشاء عرض تقديمي جديد يحتوي على هذه الصورة Presentation pres = new Presentation(); try { // من المفترض أن يكون لدينا ملف الصورة الكبير الذي نريد تضمينه في العرض التقديمي FileInputStream fip = new FileInputStream(dataDir + "large_image.jpg"); try { // دعونا نضيف الصورة إلى العرض التقديمي - نختار سلوك KeepLocked، لأننا لا نختار ذلك // لديك نية للوصول إلى ملف "largeImage.png". IPPImage img = pres.getImages().addImage(fip, LoadingStreamBehavior.KeepLocked); pres.getSlides().get_Item(0).getShapes().addPictureFrame(ShapeType.Rectangle, 0, 0, 300, 200, img); // احفظ العرض التقديمي. وعلى الرغم من ذلك فإن عرض الإخراج سيكون // كبيرة، سيكون استهلاك الذاكرة منخفضًا طوال عمر الكائن السابق pres.save(dataDir + "presentationWithLargeImage.pptx", SaveFormat.Pptx); } finally { fip.close(); } } catch (java.io.IOException e) { e.printStackTrace(); } finally { pres.dispose(); } ``` ## خاتمة تهانينا! لقد تعلمت بنجاح كيفية إضافة صورة Blob إلى عرض تقديمي في Java Slides باستخدام Aspose.Slides. يمكن أن تكون هذه المهارة لا تقدر بثمن عندما تحتاج إلى تحسين العروض التقديمية الخاصة بك باستخدام صور مخصصة. قم بتجربة صور وتخطيطات مختلفة لإنشاء شرائح مذهلة بصريًا. ## الأسئلة الشائعة ### كيف أقوم بتثبيت Aspose.Slides لـ Java؟ يمكن تثبيت Aspose.Slides for Java بسهولة عن طريق تنزيل المكتبة من موقع الويب[هنا](https://releases.aspose.com/slides/java/). اتبع تعليمات التثبيت المقدمة لدمجها في مشروع Java الخاص بك. ### هل يمكنني إضافة صور Blob متعددة إلى عرض تقديمي واحد؟ نعم، يمكنك إضافة صور Blob متعددة إلى عرض تقديمي واحد. ما عليك سوى تكرار الخطوات الموضحة في هذا البرنامج التعليمي لكل صورة تريد تضمينها. ### ما هو تنسيق الصورة الموصى به للعروض التقديمية؟ يُنصح باستخدام تنسيقات الصور الشائعة مثل JPEG أو PNG للعروض التقديمية. يدعم Aspose.Slides for Java تنسيقات الصور المختلفة، مما يضمن التوافق مع معظم برامج العروض التقديمية. ### كيف يمكنني تخصيص موضع وحجم صورة Blob المضافة؟ يمكنك ضبط موضع وحجم صورة Blob المضافة عن طريق تعديل المعلمات في ملف`addPictureFrame` طريقة. تحدد القيم الأربع (الإحداثي x، والإحداثي y، والعرض، والارتفاع) موضع إطار الصورة وأبعاده. ### هل Aspose.Slides مناسب لمهام أتمتة PowerPoint المتقدمة؟ قطعاً! يوفر Aspose.Slides إمكانات متقدمة لأتمتة برنامج PowerPoint، بما في ذلك إنشاء الشرائح وتعديلها واستخراج البيانات. إنها أداة قوية لتبسيط المهام المتعلقة ببرنامج PowerPoint.
# Queens College # Discrete Structures (CSCI 220) # Winter 2024 # Assignment 4 - Combinations and Permutations # Raphael Attiaala # Collaberated with Class import texttable from math import factorial, perm, comb def print_table(title, headers, data, alignments): tt = texttable.Texttable(0) tt.set_cols_align(alignments) tt.add_rows([headers] + data, True) print(title) print(tt.draw()) print() def c(n, r): return comb(n, r) def p(n, r): return perm(n, r) def c2(n, r): return 0 if r > n else fact(n) / (fact(r) * fact(n - r)) def p2(n, r): return 0 if r > n else fact(n) / fact(n - r) def fact(n): return 0 if n < 0 else factorial(n) # [1] Create a function print_table(name, func, n) that prints a (n+1) x (n+1) table for the function f(i, j) where both i and j iterate over 0 thru n inclusive. # [2/3/4/5] From your main function, call print_table using "Permutations" and the built-in math.perm , # Permutations" and your own my_perm, # "Combinations" and the built-in math.comb, # using "Combinations" and your own my_comb def functions(f, c, n, t): headers = [f"{c}(n,{r}" for r in range(n + 1)] data = [[f(i, j) for j in range(n + 1)] for i in range(n + 1)] alignments = ["r"] * (n + 1) print_table(t, headers, data, alignments) # [6] In the standard game of poker, one is dealt a "hand" of five cards which is classified into one of several categories. # For example, "Four of a Kind" means four cards of one rank and one card of another rank. # "Full House'' means three cards of one rank, and two cards of another rank. # We want to compute the number of possible ways to get a given hand. # Then, use this function to compare your calculated answer with the known correct answer and then call it for all standard hands. def q6(): hands = [["Royal_flush", 4, c(4, 1)], ["Straight_flush", 36, c(10, 1) * c(4, 1) - c(4, 1)], ["Four of a kind", 624, c(13, 1) * c(4, 4) * c(12, 1) * c(4, 1)], ["Full House", 3744, c(13, 1) * c(4, 3) * c(12, 1)*c(4, 2)], ["Flush", 5108, c(4, 1) * c(13, 5) - c(10, 1) * c(4,1)], ["Straight", 10200, c(4, 1) ** 5 * c(10, 1) * c(4, 1)], ["Three of a kind", 54912, c(13, 1) * c(4, 3)*c(12, 2) * c(4, 1)**2], ["Two Pair", 123552, c(13, 2) * c(4, 2)**2 * c(11, 1)*c(4, 1)], ["One Pair", 1098240, c(13, 1) * c(4, 2) * c(12, 3) * c(4, 1)**3], ["No Pair", 1302540, ((c(13, 5) - c(10, 1)) * (c(4, 1) ** 5 - c(4, 1)))] ] headers = ["Name", "Frequency", "Computed"] alignments = ["l", "r", "r"] print_table("Poker Hands", headers, hands, alignments) def main(): n = 10 functions(p, "P", n, "Permutations using built in perm function") functions(p2, "P", n, "Permutations using our perm function") functions(c, "C", n, "Combinations using built in comb function") functions(c2, "C", n, "Combinations using our comb function") q6() if __name__ == "__main__": main()
const canvas = document.querySelector("canvas"); const c = canvas.getContext("2d"); canvas.width = 1024; canvas.height = 576; const gravity = 0.7; class Sprite { constructor(position, velocity, color = "red", offset = { x: 0, y: 0 }) { this.position = position; this.velocity = velocity; this.width = 50; this.height = 150; this.lastKey = null; this.attackBox = { position: { x: this.position.x, y: this.position.y, }, offset: offset, width: 100, height: 50, }; this.color = color; this.isAttacking = false; } draw() { c.fillStyle = this.color; c.fillRect(this.position.x, this.position.y, this.width, this.height); // Attack box if (this.isAttacking) { c.fillStyle = "green"; c.fillRect( this.attackBox.position.x, this.attackBox.position.y, this.attackBox.width, this.attackBox.height ); } } update() { this.draw(); this.attackBox.position.x = this.position.x - this.attackBox.offset.x; this.attackBox.position.y = this.position.y; this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y >= canvas.height) { this.velocity.y = 0; } else { this.velocity.y += gravity; } } attack() { this.isAttacking = true; setTimeout(() => { this.isAttacking = false; }, 100); } } const player = new Sprite({ x: 0, y: 0 }, { x: 0, y: 10 }); const enemy = new Sprite({ x: 400, y: 100 }, { x: 0, y: 0 }, "blue", { x: -50, y: 0, }); const keys = { a: { pressed: false }, d: { pressed: false }, w: { pressed: false }, ArrowRight: { pressed: false }, ArrowLeft: { pressed: false }, ArrowUp: { pressed: false }, }; function rectangularCollision(rectangle1, rectangle2) { return ( rectangle1.attackBox.position.x + rectangle1.attackBox.width >= rectangle2.position.x && rectangle1.attackBox.position.x <= rectangle2.position.x + rectangle2.width && rectangle1.attackBox.position.y <= rectangle2.position.y + rectangle2.height && rectangle1.attackBox.position.y + rectangle1.attackBox.height >= rectangle2.position.y ); } function animate() { window.requestAnimationFrame(animate); c.fillStyle = "black"; // Clear the canvas c.fillRect(0, 0, canvas.width, canvas.height); // Update and draw the player player.update(); // Update and draw the enemy enemy.update(); player.velocity.x = 0; enemy.velocity.x = 0; // Player movement if (keys.a.pressed && player.lastKey === "a") { player.velocity.x = -5; } else if (keys.d.pressed && player.lastKey === "d") { player.velocity.x = 5; } // Enemy movement if (keys.ArrowLeft.pressed && enemy.lastKey === "ArrowLeft") { enemy.velocity.x = -5; } else if (keys.ArrowRight.pressed && enemy.lastKey === "ArrowRight") { enemy.velocity.x = 5; } // Detect collision if (rectangularCollision(player, enemy) && player.isAttacking) { player.isAttacking = false; console.log("Player attack successful"); } if (rectangularCollision(enemy, player) && enemy.isAttacking) { enemy.isAttacking = false; console.log("Enemy attack successful"); } } animate(); window.addEventListener("keydown", (event) => { console.log(event.key); switch (event.key) { case "d": keys.d.pressed = true; player.lastKey = "d"; break; case "a": keys.a.pressed = true; player.lastKey = "a"; break; case "w": player.velocity.y = -20; break; case " ": player.attack(); break; case "ArrowRight": keys.ArrowRight.pressed = true; enemy.lastKey = "ArrowRight"; break; case "ArrowLeft": keys.ArrowLeft.pressed = true; enemy.lastKey = "ArrowLeft"; break; case "ArrowUp": enemy.velocity.y = -20; break; case "ArrowDown": enemy.isAttacking = true; break; } }); window.addEventListener("keyup", (event) => { switch (event.key) { case "d": keys.d.pressed = false; break; case "a": keys.a.pressed = false; break; case "w": keys.w.pressed = false; break; } // Enemy keys switch (event.key) { case "ArrowRight": keys.ArrowRight.pressed = false; break; case "ArrowLeft": keys.ArrowLeft.pressed = false; break; } console.log(event.key); }); console.log(player); console.log(enemy);
#ifndef _LIGHTING_UTILS #define _LIGHTING_UTILS #include "/assets/shaders/core/include/common_utils.inc" #include "/assets/shaders/core/include/rand.inc" // Light attenuation function using the squared distance between the light and fragment. float Attenuation(in vec3 _lightPos, in vec3 _fragPos, in float _range) { return _range / length2(_lightPos, _fragPos); } // NVIDIA PCSS: // - Fernando, R. and NVIDIA Corporation (2005). Percentage-Closer Soft Shadows. [online] Available at: https://developer.download.nvidia.com/shaderlibrary/docs/shadow_PCSS.pdf [Accessed 15 Dec. 2023]. // - Myers, K., Fernando , R., Bavoil, L. and NVIDIA Corporation (2008). Integrating Realistic Soft Shadows into Your Game Engine. [online] Available at: https://developer.download.nvidia.com/whitepapers/2008/PCSS_Integration.pdf [Accessed 15 Dec. 2023]. // Hard and PCF shadows derived from implementations by Learn OpenGL: // - de Vries, J. (n.d.). LearnOpenGL - Shadow Mapping. [online] learnopengl.com. Available at: https://learnopengl.com/Advanced-Lighting/Shadows/Shadow-Mapping [Accessed 15 Dec. 2023]. // - de Vries, J. (n.d.). LearnOpenGL - Point Shadows. [online] learnopengl.com. Available at: https://learnopengl.com/Advanced-Lighting/Shadows/Point-Shadows [Accessed 15 Dec. 2023]. // Shadows for Parallax Occlusion Mapping. Implementation courtesy of "Rabbid76": // Rabbid76 (2019). Adding Shadows to Parallax Occlusion Map. [online] Stack Overflow. Available at: https://stackoverflow.com/questions/55089830/adding-shadows-to-parallax-occlusion-map [Accessed 15 Dec. 2023]. #pragma optionNV(unroll all) float ParallaxShadowsHard(in sampler2D _displacement, in vec3 _lightDir, in vec2 _uv, in vec4 _st, in float _scale) { float minLayers = 0.0; float maxLayers = 16.0; float numLayers = mix(maxLayers, minLayers, abs(dot(vec3(0.0, 0.0, 1.0), _lightDir))); vec2 currentTexCoords = _uv; float currentDepthMapValue = Sample1(_displacement, currentTexCoords, _st); float currentLayerDepth = currentDepthMapValue; float layerDepth = 1.0 / numLayers; vec2 P = _lightDir.xy / _lightDir.z * (_scale / maxLayers); vec2 deltaTexCoords = P / numLayers; while (currentLayerDepth <= currentDepthMapValue && currentLayerDepth > 0.0) { currentTexCoords += deltaTexCoords; currentDepthMapValue = Sample1(_displacement, currentTexCoords, _st); currentLayerDepth -= layerDepth; } return currentLayerDepth > currentDepthMapValue ? 1.0 : 0.0; } #pragma optionNV(unroll all) float PCSS_GetOccluderDepth3D(in samplerCube _shadowMap, in vec3 _dir, in float _texelSize, in float _bias, in float _seed, in int _samples) { float result = 0.0; int hits = 0; for (int i = 0; i < _samples; ++i) { vec3 offset = normalize(Random3S(_dir + vec3(i + 1), _seed, 0.1)); offset *= Random1S(_dir.xy + vec2(i + 1), _seed, 0.4); float occluderDepth = Sample1(_shadowMap, _dir + offset); if (occluderDepth < length(_dir) - _bias) { result += occluderDepth; hits++; } } if (hits == 0) { result = -1.0; } return result / float(max(hits, 1)); } float PCSS_Radius3D(in samplerCube _shadowMap, in vec3 _dir, in float _texelSize, in float _bias, in float _lightSize, in float _seed, in int _samples) { float result; float occluderDepth = PCSS_GetOccluderDepth3D(_shadowMap, _dir, _texelSize, _bias, _seed, _samples); if (occluderDepth == -1.0) { result = 1.0; } else { float len = length(_dir); float penumbraWidth = abs(occluderDepth / (occluderDepth - len)); result = penumbraWidth * _lightSize; } return result; } float ShadowCalculationHard3D(in samplerCube _shadowMap, in vec3 _dir, in vec3 _offset, in float _bias, in float _lightRange) { // Get depth from light to closest surface. float shadowDepth = Sample1(_shadowMap, _dir + _offset) * _lightRange; // Compare the depth of the light against the distance from the light to the current fragment. return length(_dir) - _bias > shadowDepth ? 1.0 : 0.0; } #pragma optionNV(unroll all) float ShadowCalculationPCF3D(in samplerCube _shadowMap, in vec3 _dir, in float _texelSize, in float _bias, in float _radius, in float _lightRange, in int _samples) { float result = 0.0; float hits = 0.0; float axis = pow(float(_samples), 1.0 / 3.0); for (float x = -_radius; x < _radius; x += _radius / axis) { for (float y = -_radius; y < _radius; y += _radius / axis) { for (float z = -_radius; z < _radius; z += _radius / axis) { vec3 offset = vec3(x, y, z); offset *= _texelSize * 4.0; result += ShadowCalculationHard3D(_shadowMap, _dir, offset, _bias, _lightRange); hits += 1.0; }}} return result / max(hits, 1.0); } #pragma optionNV(unroll all) float ShadowCalculationDisk3D(in samplerCube _shadowMap, in vec3 _dir, in float _texelSize, in float _bias, in float _radius, in float _lightRange, in float _seed, in int _samples) { float result = 0.0; float multiplier = _radius * 2 * 2 * 2; // Compensation for 3D. for (int i = 0; i < _samples; ++i) { vec3 offset = normalize(Random3S(_dir + vec3(i + 1), fract(_seed), 0.1)); offset *= _texelSize * _radius * multiplier; result += ShadowCalculationHard3D(_shadowMap, _dir, offset, _bias, _lightRange); } return result / float(_samples); } float ShadowCalculationPCSS3D(in samplerCube _shadowMap, in vec3 _dir, in float _texelSize, in float _bias, in float _lightRange, in float _lightSize, in float _seed, in int _samples) { float result = 0.0; float multiplier = 64; int BLOCKER_SEARCH_NUM_SAMPLES = _samples; int PCF_NUM_SAMPLES = 24; float radius = PCSS_Radius3D(_shadowMap, _dir, _texelSize, _bias, _lightSize * multiplier * _lightRange, _seed, BLOCKER_SEARCH_NUM_SAMPLES); return ShadowCalculationPCF3D(_shadowMap, _dir, _texelSize, _bias, radius, _lightRange, clamp(int(radius), 1, PCF_NUM_SAMPLES)); } #pragma optionNV(unroll all) float PCSS_GetOccluderDepth2D(in sampler2D _shadowMap, in vec3 _fragPos, in float _texelSize, in float _bias, in float _seed, in int _samples) { float result = 0.0; int hits = 0; for (int i = 0; i < _samples; ++i) { vec2 offset = normalize(Random2S(_fragPos.xy + vec2(i + 1), _seed, 0.1)); offset *= float(i + 1) / (_samples + 1); float occluderDepth = Sample1(_shadowMap, _fragPos.xy + (offset * _texelSize)); if (occluderDepth < _fragPos.z - _bias) { result += occluderDepth; hits++; } } if (hits == 0) { result = -1.0; } return result / float(max(hits, 1)); } float PCSS_Radius2D(in sampler2D _shadowMap, in vec3 _fragPos, in float _texelSize, in float _bias, in float _seed, in int _samples, in float _lightSize, in float _nearClip) { float result; float occluderDepth = PCSS_GetOccluderDepth2D(_shadowMap, _fragPos, _texelSize, _bias, _seed, _samples); if (occluderDepth == -1.0) { result = 1.0; } else { float penumbraWidth = (_fragPos.z - occluderDepth) / occluderDepth; result = penumbraWidth * _lightSize; } return result; } float ShadowCalculationHard2D(in sampler2D _shadowMap, in vec3 _fragPos, in vec2 _offset, in float _bias) { // Get depth from light to closest surface. float shadowDepth = Sample1(_shadowMap, _fragPos.xy + _offset); // Compare the depth of the light against the distance from the light to the current fragment (converted to light space). return (_fragPos.z <= 1.0) && (_fragPos.z - _bias > shadowDepth) ? 1.0 : 0.0; } #pragma optionNV(unroll all) float ShadowCalculationPCF2D(in sampler2D _shadowMap, in vec3 _fragPos, in float _texelSize, in float _bias, in float _radius, in int _samples) { float result = 0.0; float hits = 0.0; float PCF_SAMPLES = _samples; float axis = sqrt(PCF_SAMPLES); for (float x = -_radius; x < _radius; x += _radius / axis) { for (float y = -_radius; y < _radius; y += _radius / axis) { vec2 dir = vec2(x, y) * _texelSize; result += ShadowCalculationHard2D(_shadowMap, _fragPos, dir, _bias); hits += 1.0; }} return result / max(hits, 1.0); } #pragma optionNV(unroll all) float ShadowCalculationDisk2D(in sampler2D _shadowMap, in vec3 _fragPos, in float _texelSize, in float _bias, in float _radius, in float _seed, in int _samples) { float result = 0.0; for (int i = 0; i < _samples; ++i) { vec2 dir = normalize(Random2S(_fragPos.xy + vec2(i + 1), _seed, 0.1)); dir *= _texelSize * _radius; result += ShadowCalculationHard2D(_shadowMap, _fragPos, dir, _bias); } return result / float(_samples); } float ShadowCalculationPCSS2D(in sampler2D _shadowMap, in vec3 _fragPos, in float _texelSize, in float _bias, in float _nearClip, in float _lightAngle, in float _lightSize, in float _seed, in int _samples) { float result = 0.0; float perspective_multiplier = _lightAngle == -1.0 ? 1.0 : 32.0; int BLOCKER_SEARCH_NUM_SAMPLES = _samples; int PCF_NUM_SAMPLES = 24; float radius = PCSS_Radius2D(_shadowMap, _fragPos, _texelSize, _bias, _seed, BLOCKER_SEARCH_NUM_SAMPLES, _lightSize, _nearClip); radius *= perspective_multiplier; radius /= _texelSize; return ShadowCalculationPCF2D(_shadowMap, _fragPos, _texelSize, _bias, radius, clamp(int(radius), 1, PCF_NUM_SAMPLES)); } #endif
import React from 'react' const NewsItem =(props)=> { let {title, discription,imageUrl,newsUrl,author,date,source,content}=props; return ( // position-absolute top-0 translate-middle style={{zIndex:1,left:"90%"}} <div className="container "> <div className="card " > <div className="container" style={{display:'flex',justifyContent:'flex-end',position:'absolute',right: 0 }}> <span className=" badge rounded-pill bg-danger" >{source}</span> </div> <img src={!imageUrl?"https://motor.ru/imgs/2023/09/24/08/6149699/448299eb855a31fb395b5ecda7a4d133d626edce.jpg":imageUrl} className="card-img-top" alt="error" /> <div className="card-body"> <h5 className="card-title">{title}</h5> <p className="card-text">{discription}...</p> <p className="card-text"><small className="text-body-secondary">By {!author?"Unknown":author} on {new Date(date).toUTCString()}</small></p> <a rel='noreferrer' href={newsUrl} target="_blank" className="btn btn-sm btn-primary">Read More</a> </div> </div> </div> ) } export default NewsItem
package baekjoon; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * BOJ_2096_내려가기 * N줄에 0 이상 9 이하의 숫자가 세 개씩 적혀 있다. * 내려가기 게임을 하고 있는데, 이 게임은 첫 줄에서 시작해서 마지막 줄에서 끝나게 되는 놀이이다. * 먼저 처음에 적혀 있는 세 개의 숫자 중에서 하나를 골라서 시작하게 된다. * 그리고 다음 줄로 내려가는데, 다음 줄로 내려갈 때에는 다음과 같은 제약 조건이 있다. * 바로 아래의 수로 넘어가거나, 아니면 바로 아래의 수와 붙어 있는 수로만 이동할 수 있다는 것이다. * * maxDP[idx][0] = Math.max(maxDP[idx-1][0], maxDP[idx-1][1]) + map[idx][0] * maxDP[idx][1] = Math.max(maxDP[idx-1][0], Math.max(maxDP[idx-1][1], maxDP[idx-1][2])) + map[idx][1] * maxDP[idx][2] = Math.max(maxDP[idx-1][1], maxDP[idx-1][2]) + map[idx][2] * minDP[idx][0] = Math.min(minDP[idx-1][0], minDP[idx-1][1]) + map[idx][0] * minDP[idx][1] = Math.min(minDP[idx-1][0], Math.min(minDP[idx-1][1], minDP[idx-1][2])) + map[idx][1] * minDP[idx][2] = Math.min(minDP[idx-1][1], minDP[idx-1][2]) + map[idx][2] * @author semin.kim */ public class BOJ_2096_내려가기_김세민 { static BufferedReader br; static StringTokenizer st; static StringBuilder sb; static int size; static final int ROW_SIZE = 3; static int[][] map, maxDP, minDP; static int maxScore, minScore = Integer.MAX_VALUE; private static void calculate() { for(int idx = 1; idx <= size; idx++) { maxDP[idx][0] = Math.max(maxDP[idx-1][0], maxDP[idx-1][1]) + map[idx][0]; maxDP[idx][1] = Math.max(maxDP[idx-1][0], Math.max(maxDP[idx-1][1], maxDP[idx-1][2])) + map[idx][1]; maxDP[idx][2] = Math.max(maxDP[idx-1][1], maxDP[idx-1][2]) + map[idx][2]; minDP[idx][0] = Math.min(minDP[idx-1][0], minDP[idx-1][1]) + map[idx][0]; minDP[idx][1] = Math.min(minDP[idx-1][0], Math.min(minDP[idx-1][1], minDP[idx-1][2])) + map[idx][1]; minDP[idx][2] = Math.min(minDP[idx-1][1], minDP[idx-1][2]) + map[idx][2]; } maxScore = Math.max(maxDP[size][0], Math.max(maxDP[size][1], maxDP[size][2])); minScore = Math.min(minDP[size][0], Math.min(minDP[size][1], minDP[size][2])); sb.append(maxScore).append(" ").append(minScore); System.out.println(sb); } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); sb = new StringBuilder(); size = Integer.parseInt(br.readLine().trim()); map = new int[size + 1][ROW_SIZE]; maxDP = new int[size + 1][ROW_SIZE]; minDP = new int[size + 1][ROW_SIZE]; for(int col = 1; col <= size; col++) { st = new StringTokenizer(br.readLine().trim()); for(int row = 0; row < ROW_SIZE; row++) { map[col][row] = Integer.parseInt(st.nextToken()); } } calculate(); } }
import 'package:flutter/material.dart'; import 'package:pie_chart/pie_chart.dart'; final dataMap = <String, double>{ "Bitcoin": 25, "Ethereum": 50, "Ripley": 10, "Ruble": 15, }; final colorList = <Color>[ const Color.fromARGB(255, 231, 240, 105), const Color.fromARGB(255, 179, 105, 240), const Color.fromARGB(255, 235, 133, 226), const Color.fromARGB(255, 64, 161, 240), ]; class TopContent extends StatelessWidget { const TopContent({super.key}); @override Widget build(BuildContext context) { return Material( color: const Color.fromARGB(255, 0, 2, 44), child: Container( height: 150, width: double.infinity, margin: const EdgeInsets.symmetric(horizontal: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Padding( padding: const EdgeInsets.all(8.0), child: PieChart( dataMap: dataMap, chartType: ChartType.ring, baseChartColor: Colors.grey[50]!.withOpacity(0.15), colorList: colorList, chartValuesOptions: const ChartValuesOptions( showChartValues: false, ), totalValue: 100, ), ), ], ), )); } }
import { faUserCircle } from '@fortawesome/free-solid-svg-icons'; import styled from 'styled-components'; import { logOut, signInWithGoogle } from '../../firebaseInit'; import Button from '../base/Button'; import Icon from '../base/Icon'; import Image from 'next/image'; import { useSelector } from 'react-redux'; import { FontColor, Palette } from '../../lib/styles/theme'; import { RootState } from '../../lib/store/store'; import { isEmpty } from '../../lib/utils/isEmpty'; const UserProfileBox = styled.div<{ user: any }>` height: ${(props) => props.user === '150px' && '100px'}; display: flex; flex-direction: column; align-items: center; cursor: ${(props) => props.user && 'pointer'}; margin-bottom: 10px; `; const ProfileImg = styled.div` border-radius: 25px; width: 60px; height: 60px; font-size: 45px; text-align: center; overflow: hidden; .image { position: relative; width: 100%; height: 100%; } .temp { width: 100%; height: 100%; background-color: ${Palette.white_1}; } `; const UserBox = styled.div` margin-top: 10px; color: ${FontColor.white}; `; const UserControlBox = styled.div` margin-top: 10px; `; const UserProfile = () => { const user = useSelector((state: RootState) => state.userReducer.user); const isUser = isEmpty(user); return ( <UserProfileBox user={isUser} onClick={isUser ? signInWithGoogle : undefined} > <ProfileImg> {!isUser ? ( <div className={'image'}> <Image src={user?.photoURL} alt={'userImg'} layout="fill" objectFit="contain" /> </div> ) : ( <Icon icon={faUserCircle} /> )} </ProfileImg> <UserBox>{isUser ? '로그인하세요' : user?.displayName}</UserBox> <UserControlBox> {!isUser && ( <Button backColor={Palette.gray_2} onClick={logOut}> 로그아웃 </Button> )} </UserControlBox> </UserProfileBox> ); }; export default UserProfile;
defmodule IbkrApi.ClientPortal.Contract do defmodule Secdef do defstruct [ conid: nil, currency: nil, cross_currency: nil, time: nil, chinese_name: nil, all_exchanges: nil, listing_exchange: nil, name: nil, asset_class: nil, expiry: nil, last_trading_day: nil, group: nil, put_or_call: nil, sector: nil, sector_group: nil, strike: nil, ticker: nil, und_conid: nil, multiplier: nil, type: nil, und_comp: nil, und_sym: nil, has_options: nil, full_name: nil, is_us: nil, increment_rules: %{} ] end defmodule TradingSchedule do defstruct [ id: nil, trade_venue_id: nil, schedules: [] ] end defmodule SecurityFutures do defstruct symbol: [], futures: [] end defmodule SecurityStocks do defstruct symbol: [], stocks: [] end defmodule ContractDetails do defstruct [ r_t_h: nil, con_id: nil, company_name: nil, exchange: nil, local_symbol: nil, instrument_type: nil, currency: nil, companyName: nil, category: nil, industry: nil, rules: %{} ] end alias IbkrApi.HTTP @base_url IbkrApi.Config.base_url() @spec contract_details(String.t()) :: ErrorMessage.t_res() def contract_details(conid) do HTTP.get(Path.join(@base_url, "/iserver/contract/#{conid}/info")) end @spec security_stocks_by_symbol(String.t()) :: ErrorMessage.t_res() def security_stocks_by_symbol(symbols) do HTTP.get(Path.join(@base_url, "/trsrv/stocks"), %{"symbols" => symbols}) end @spec security_futures_by_symbol(String.t()) :: ErrorMessage.t_res() def security_futures_by_symbol(symbols) do HTTP.get(Path.join(@base_url, "/trsrv/futures"), %{"symbols" => symbols}) end @spec get_trading_schedule(String.t(), String.t(), String.t(), String.t()) :: ErrorMessage.t_res() def get_trading_schedule(asset_class, symbol, exchange, exchange_filter) do query_params = %{ "assetClass" => asset_class, "symbol" => symbol, "exchange" => exchange, "exchangeFilter" => exchange_filter } HTTP.get(Path.join(@base_url, "/trsrv/secdef/schedule"), query_params) end @spec secdef_by_conid(list(integer())) :: ErrorMessage.t_res() def secdef_by_conid(conids) do body = %{"conids" => conids} with {:ok, response} <- HTTP.post(Path.join(@base_url, "/trsrv/secdef"), body) do {:ok, Enum.map(response, &struct(Secdef, &1))} end end end
#include "re2nfa.h" NFA concat(NFA a, NFA b) { NFA result; result.set_vertex(a.get_vertex_count() + b.get_vertex_count()); int i; trans new_trans; for (i = 0; i < a.transitions.size(); i++) { new_trans = a.transitions.at(i); result.set_transition(new_trans.vertex_from, new_trans.vertex_to, new_trans.trans_symbol); } result.set_transition(a.get_final_state(), a.get_vertex_count(), '`'); for (i = 0; i < b.transitions.size(); i++) { new_trans = b.transitions.at(i); result.set_transition(new_trans.vertex_from + a.get_vertex_count(), new_trans.vertex_to + a.get_vertex_count(), new_trans.trans_symbol); } result.set_final_state(a.get_vertex_count() + b.get_vertex_count() - 1); return result; } NFA kleene(NFA a) { NFA result; int i; trans new_trans; result.set_vertex(a.get_vertex_count() + 2); result.set_transition(0, 1, '`'); for (i = 0; i < a.transitions.size(); i++) { new_trans = a.transitions.at(i); result.set_transition(new_trans.vertex_from + 1, new_trans.vertex_to + 1, new_trans.trans_symbol); } result.set_transition(a.get_vertex_count(), a.get_vertex_count() + 1, '`'); result.set_transition(a.get_vertex_count(), 1, '`'); result.set_transition(0, a.get_vertex_count() + 1, '`'); result.set_final_state(a.get_vertex_count() + 1); return result; } NFA or_selection(vector<NFA> selections, int no_of_selections) { NFA result; int vertex_count = 2; int i, j; NFA med; trans new_trans; for (i = 0; i < no_of_selections; i++) { vertex_count += selections.at(i).get_vertex_count(); } result.set_vertex(vertex_count); int adder_track = 1; for (i = 0; i < no_of_selections; i++) { result.set_transition(0, adder_track, '`'); med = selections.at(i); for (j = 0; j < med.transitions.size(); j++) { new_trans = med.transitions.at(j); result.set_transition(new_trans.vertex_from + adder_track, new_trans.vertex_to + adder_track, new_trans.trans_symbol); } adder_track += med.get_vertex_count(); result.set_transition(adder_track - 1, vertex_count - 1, '`'); } result.set_final_state(vertex_count - 1); return result; } NFA re_to_nfa(string re) { stack<char> operators; stack<NFA> operands; char op_sym; int op_count; char cur_sym; NFA* new_sym; for (string::iterator it = re.begin(); it != re.end(); ++it) { cur_sym = *it; if (cur_sym != '(' && cur_sym != ')' && cur_sym != '*' && cur_sym != '|' && cur_sym != '.') { new_sym = new NFA(); new_sym->set_vertex(2); new_sym->set_transition(0, 1, cur_sym); new_sym->set_final_state(1); operands.push(*new_sym); delete new_sym; } else { if (cur_sym == '*') { NFA star_sym = operands.top(); operands.pop(); operands.push(kleene(star_sym)); } else if (cur_sym == '.') { operators.push(cur_sym); } else if (cur_sym == '|') { operators.push(cur_sym); } else if (cur_sym == '(') { operators.push(cur_sym); } else { op_count = 0; char c; op_sym = operators.top(); if (op_sym == '(') continue; do { operators.pop(); op_count++; } while (operators.top() != '('); operators.pop(); NFA op1; NFA op2; vector<NFA> selections; if (op_sym == '.') { for (int i = 0; i < op_count; i++) { op2 = operands.top(); operands.pop(); op1 = operands.top(); operands.pop(); operands.push(concat(op1, op2)); } } else if (op_sym == '|') { selections.assign(op_count + 1, NFA()); int tracker = op_count; for (int i = 0; i < op_count + 1; i++) { selections.at(tracker) = operands.top(); tracker--; operands.pop(); } operands.push(or_selection(selections, op_count + 1)); } else { } } } } return operands.top(); } /* int main() { NFA a, b; string re; set<char> symbols; cout << "\n\nEnter the regular expression :- \n\n"; cin >> re; cout << "\n\nThe required NFA has the transitions : \n\n"; NFA required_nfa; required_nfa = re_to_nfa(re); required_nfa.display(); int N = required_nfa.get_vertex_count(); int M = 3; int T = N - 1; ofstream f; f.open("NFA.txt"); f << N << " " << M << endl; f << 1 << " " << required_nfa.get_final_state() << endl; f << T << endl; for (int i = 0; i < required_nfa.get_vertex_count(); i++) { for (int k = 0; k < 26; k++) { int count = 0; for (int j = 0; j < (required_nfa.transitions).size(); j++) { if ((required_nfa.transitions[j]).vertex_from == i && (required_nfa.transitions[j]).trans_symbol == '`' + k) count++; } if (count > 0) { f << i << " " << k << " " << count << " "; for (int j = 0; j < (required_nfa.transitions).size(); j++) { if ((required_nfa.transitions[j]).vertex_from == i && (required_nfa.transitions[j]).trans_symbol == '`' + k) f << (required_nfa.transitions[j]).vertex_to << " "; } } } f << endl; } f.close(); return 0; } */
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * and limitations under the License. */ import { Aws, Arn, ArnFormat, Stack, Fn } from 'aws-cdk-lib'; import { IRole, PolicyStatement, Role, ServicePrincipal } from 'aws-cdk-lib/aws-iam'; import { Construct } from 'constructs'; import { getShortIdOfStack } from '../../common/stack'; export function createRoleForS3SinkConnectorCustomResourceLambda( scope: Construct, props: { logS3BucketName: string; pluginS3BucketName: string; connectorRole: IRole }, ) { const stackShortId = getShortIdOfStack(Stack.of(scope)); const connectorName = Fn.join('-', [stackShortId, 'Connector-*']); const pluginName = Fn.join('-', [stackShortId, 'Plugin-*']); const role = new Role(scope, 'S3SinkConnectorCustomResourceLambdaRole', { assumedBy: new ServicePrincipal('lambda.amazonaws.com'), }); const policyStatements = [ new PolicyStatement({ resources: [ props.connectorRole.roleArn, ], actions: [ 'iam:PassRole', 'iam:AttachRolePolicy', 'iam:PutRolePolicy', 'iam:UpdateRoleDescription', 'iam:DeleteServiceLinkedRole', 'iam:GetServiceLinkedRoleDeletionStatus', ], }), new PolicyStatement({ resources: [ `arn:${Aws.PARTITION}:iam::${Aws.ACCOUNT_ID}:role/aws-service-role/kafkaconnect.amazonaws.com/AWSServiceRoleForKafkaConnect`, ], actions: [ 'iam:CreateServiceLinkedRole', ], }), new PolicyStatement({ resources: [ //`arn:aws:s3:::${props.logS3BucketName}` Arn.format( { resource: `${props.logS3BucketName}`, region: '', account: '', service: 's3', arnFormat: ArnFormat.COLON_RESOURCE_NAME, }, Stack.of(scope), ), ], actions: [ 's3:GetBucketLocation', 's3:DeleteBucketPolicy', 's3:PutBucketPolicy', 's3:GetBucketPolicy', ], }), new PolicyStatement({ resources: [ //`arn:aws:s3:::${props.pluginS3BucketName}`, Arn.format( { resource: `${props.pluginS3BucketName}/*`, region: '', account: '', service: 's3', arnFormat: ArnFormat.COLON_RESOURCE_NAME, }, Stack.of(scope), ), ], actions: [ 's3:GetObject', 's3:PutObject', 's3:DeleteObject', ], }), new PolicyStatement({ resources: [ //`arn:aws:kafkaconnect:*:*:connector/${props.clusterName}-s3-sink-connector/*`, Arn.format( { resource: `connector/${connectorName}/*`, service: 'kafkaconnect', arnFormat: ArnFormat.COLON_RESOURCE_NAME, }, Stack.of(scope), ), // `arn:aws:kafkaconnect:*:*:custom-plugin/${props.clusterName}-connector-s3-plugin/*`, Arn.format( { resource: `custom-plugin/${pluginName}/*`, service: 'kafkaconnect', arnFormat: ArnFormat.COLON_RESOURCE_NAME, }, Stack.of(scope), ), ], actions: [ 'kafkaconnect:DescribeCustomPlugin', 'kafkaconnect:DescribeConnector', ], }), new PolicyStatement({ resources: [ '*', ], actions: [ 'kafkaconnect:ListConnectors', 'kafkaconnect:CreateCustomPlugin', 'kafkaconnect:CreateConnector', 'kafkaconnect:DeleteConnector', 'kafkaconnect:ListCustomPlugins', 'kafkaconnect:DeleteCustomPlugin', 'kafkaconnect:UpdateConnector', ], conditions: { StringEquals: { 'aws:RequestedRegion': Stack.of(scope).region, }, }, }), new PolicyStatement({ resources: [ '*', ], actions: [ 'ec2:DescribeVpcs', 'ec2:DescribeSubnets', 'ec2:DescribeSecurityGroups', 'ec2:CreateNetworkInterface', 'ec2:DescribeNetworkInterfaces', 'ec2:DeleteNetworkInterface', 'ec2:AssignPrivateIpAddresses', 'ec2:UnassignPrivateIpAddresses', ], conditions: { StringEquals: { 'aws:RequestedRegion': Stack.of(scope).region, }, }, }), new PolicyStatement({ resources: [ '*', ], actions: [ 'logs:ListLogDeliveries', 'logs:CreateLogDelivery', 'logs:CreateLogStream', 'logs:CreateLogGroup', 'logs:PutDestinationPolicy', 'logs:PutDestination', 'logs:PutLogEvents', 'logs:DeleteLogDelivery', 'logs:DeleteLogGroup', 'logs:DeleteLogStream', 'logs:DeleteDestination', 'logs:DeleteRetentionPolicy', ], conditions: { StringEquals: { 'aws:RequestedRegion': Stack.of(scope).region, }, }, }), new PolicyStatement({ resources: [Arn.format( { resource: '*', region: '', account: '', service: 'iam', arnFormat: ArnFormat.COLON_RESOURCE_NAME, }, Stack.of(scope), )], actions: [ 'iam:ListRoles', ], conditions: { StringEquals: { 'aws:RequestedRegion': Stack.of(scope).region, }, }, }), ]; policyStatements.forEach((ps) => role.addToPolicy(ps)); return role; } export function createS3SinkConnectorRole( scope: Construct, props: { mskClusterName: string; s3BucketName: string }, ) { const role = new Role(scope, 's3-kafkaconnect-role', { assumedBy: new ServicePrincipal('kafkaconnect.amazonaws.com'), }); const policyStatements = [ new PolicyStatement({ resources: [ //`arn:aws:kafka:*:*:cluster/${props.mskClusterName}/*` Arn.format( { resource: `cluster/${props.mskClusterName}/*`, service: 'kafka', arnFormat: ArnFormat.COLON_RESOURCE_NAME, }, Stack.of(scope), ), ], actions: ['kafka-cluster:Connect', 'kafka-cluster:DescribeCluster'], }), new PolicyStatement({ resources: [ //`arn:aws:kafka:*:*:topic/${props.mskClusterName}/*/*` Arn.format( { resource: `topic/${props.mskClusterName}/*/*`, service: 'kafka', arnFormat: ArnFormat.COLON_RESOURCE_NAME, }, Stack.of(scope), ), ], actions: [ 'kafka-cluster:ReadData', 'kafka-cluster:DescribeTopic', 'kafka-cluster:CreateTopic', 'kafka-cluster:WriteData', ], }), new PolicyStatement({ resources: [ //`arn:aws:kafka:*:*:group/${props.mskClusterName}/*/*` Arn.format( { resource: `group/${props.mskClusterName}/*/*`, service: 'kafka', arnFormat: ArnFormat.COLON_RESOURCE_NAME, }, Stack.of(scope), ), ], actions: ['kafka-cluster:AlterGroup', 'kafka-cluster:DescribeGroup'], }), new PolicyStatement({ resources: ['*'], actions: [ 'logs:ListLogDeliveries', 'logs:CreateLogDelivery', 'logs:CreateLogStream', 'logs:PutLogEvents', 'logs:CreateLogGroup', ], conditions: { StringEquals: { 'aws:RequestedRegion': Stack.of(scope).region, }, }, }), new PolicyStatement({ resources: ['*'], actions: [ 'ec2:DescribeVpcs', 'ec2:DescribeSubnets', 'ec2:DescribeSecurityGroups', 'ec2:CreateNetworkInterface', 'ec2:DescribeNetworkInterfaces', 'ec2:DeleteNetworkInterface', 'ec2:AssignPrivateIpAddresses', 'ec2:UnassignPrivateIpAddresses', ], conditions: { StringEquals: { 'aws:RequestedRegion': Stack.of(scope).region, }, }, }), new PolicyStatement({ resources: [ //`arn:aws:s3:::*` Arn.format( { resource: '*', region: '', account: '', service: 's3', arnFormat: ArnFormat.COLON_RESOURCE_NAME, }, Stack.of(scope), ), ], actions: ['s3:ListAllMyBuckets'], }), new PolicyStatement({ resources: [ //`arn:aws:s3:::${props.s3BucketName}/*` Arn.format( { resource: `${props.s3BucketName}/*`, region: '', account: '', service: 's3', arnFormat: ArnFormat.COLON_RESOURCE_NAME, }, Stack.of(scope), ), ], actions: [ 's3:PutObject', 's3:GetObject', 's3:AbortMultipartUpload', 's3:ListMultipartUploadParts', 's3:ListBucketMultipartUploads', 's3:ListBucket', 's3:GetBucketLocation', ], }), ]; policyStatements.forEach((ps) => role.addToPolicy(ps)); return role; }
package com.sithuheinn.mm.statedatamanagement.design import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.KeyboardArrowDown import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.toSize import com.sithuheinn.mm.statedatamanagement.model.AllergiesItem @OptIn(ExperimentalMaterial3Api::class) @Composable fun AutoCompleteTextField( allergiesItems: List<AllergiesItem>, onSelect: (String) -> Unit ) { var category by remember { mutableStateOf("") } val heightTextFields by remember { mutableStateOf(55.dp) } var textFieldSize by remember { mutableStateOf(Size.Zero) } var expanded by remember { mutableStateOf(false) } val interactionSource = remember { MutableInteractionSource() } // Category Field Column( modifier = Modifier .padding(30.dp) .fillMaxWidth() .clickable( interactionSource = interactionSource, indication = null, onClick = { expanded = false } ) ) { Column(modifier = Modifier.fillMaxWidth()) { Row(modifier = Modifier.fillMaxWidth()) { TextField( modifier = Modifier .fillMaxWidth() .height(heightTextFields) .border( width = 1.dp, color = Color.LightGray, shape = RoundedCornerShape(8.dp) ) .onGloballyPositioned { coordinates -> textFieldSize = coordinates.size.toSize() }, value = category, onValueChange = { category = it expanded = true }, colors = TextFieldDefaults.colors( focusedContainerColor = Color.Transparent, unfocusedContainerColor = Color.Transparent, disabledContainerColor = Color.Transparent, cursorColor = Color.Black, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, ), textStyle = TextStyle( color = Color.Black, fontSize = 16.sp ), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, imeAction = ImeAction.Done ), singleLine = true, trailingIcon = { IconButton(onClick = { expanded = !expanded }) { Icon( modifier = Modifier.size(24.dp), imageVector = Icons.Rounded.KeyboardArrowDown, contentDescription = "arrow", tint = Color.Black ) } } ) } AnimatedVisibility(visible = expanded) { Card( modifier = Modifier .padding(horizontal = 5.dp) .width(textFieldSize.width.dp), elevation = CardDefaults.cardElevation(5.dp), shape = RoundedCornerShape(8.dp) ) { LazyColumn( modifier = Modifier.heightIn(max = 200.dp), ) { if (category.isNotEmpty()) { items( allergiesItems.map { it.name }.filter { it.lowercase() .contains(category.lowercase()) || it.lowercase() .contains("others") } .sorted() ) { CategoryItems(title = it) { title -> onSelect.invoke(title) category = "" expanded = false } } } else { items( allergiesItems.sortedBy { it.name } ) { CategoryItems(title = it.name) { title -> onSelect.invoke(title) category = "" expanded = false } } } } } } } } } @Composable fun CategoryItems( title: String, onSelect: (String) -> Unit ) { Row( modifier = Modifier .fillMaxWidth() .clickable { onSelect(title) } .padding(10.dp) ) { Text(text = title, fontSize = 16.sp) } }
/* CHAT VIEW TOGGLE FUNCTION This JavaScript code defines a function named 'toggleView' responsible for toggling between chat and participants views on a web page. It controls the display of elements associated with each view and updates button styles accordingly. Key components and functionalities: - The 'toggleView' function takes a 'view' parameter (either 'chat' or 'participants') and toggles the visibility of elements associated with that view while updating button styles to indicate the active view. - Elements such as 'chatBoxContainer,' 'participantsContainer,' 'msgBottom,' 'chatBtn,' and 'participantsBtn' are selected and their display properties are adjusted based on the 'view' parameter. - The function initializes with the chat view ('toggleView('chat')') as the active view. Note: To use this code, you should have corresponding HTML elements with matching IDs, CSS styles for button states, and additional code that triggers the 'toggleView' function based on user interactions, such as clicking buttons or tabs to switch between views. */ function toggleView(view) { const chatBoxContainer = document.getElementById('chat-box-container'); const participantsContainer = document.getElementById('participants-container'); const msgBottom = document.getElementsByClassName('msg-bottom')[0]; const chatBtn = document.getElementById('chatBtn'); const participantsBtn = document.getElementById('participantsBtn'); if (view === 'chat') { chatBoxContainer.style.display = 'flex'; // Show chat box container participantsContainer.style.display = 'none'; // Hide participants container msgBottom.style.display = 'flex'; // Show msg-bottom chatBtn.classList.add('active-btn'); participantsBtn.classList.remove('active-btn'); } else if (view === 'participants') { chatBoxContainer.style.display = 'none'; // Hide chat box container participantsContainer.style.display = 'flex'; // Show participants container msgBottom.style.display = 'none'; // Hide msg-bottom chatBtn.classList.remove('active-btn'); participantsBtn.classList.add('active-btn'); } } // Initialize with chat view active toggleView('chat');
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Insert title here</title> <!-- Bootstrap 5를 위한 외부 라이브러리 설정 --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script> <!-- jQuery 외부 라이브러리 설정 --> <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script> <script type="text/javascript"> function changeContent() { $("#div1").html("<img src='/htmlcssjs/resources/image/photos/photo1.jpg' width='150'/>"); } function appendContent() { const el_img = "<img src='/htmlcssjs/resources/image/photos/photo2.jpg' width='150'/>"; $("#div1").append(el_img); } function deleteContent() { //기존 내용을 모두 삭제 //$("#div1").html(""); //$("#div1").empty(); //맨 뒤에 있는 엘리먼트만 삭제 $("#div1").find("img:last-child").remove(); } function changeCss() { $("#img1").css("width", "50px"); $("#img1").css("height", "50px"); $("#img1").css("border-radius", "25px"); $("#img1").css("border-width", "2px"); $("#img1").css("border-color", "red"); $("#img1").css("border-style", "solid"); } function changeAttribute() { $("#img2").attr("src", "/htmlcssjs/resources/image/photos/photo6.jpg"); } </script> </head> <body> <div class="card"> <div class="card-header">exam03_jquery_element_manipulation</div> <div class="card-body"> <div class="card"> <div class="card-header">엘리먼트 변경, 추가, 삭제</div> <div class="card-body"> <button onclick="changeContent()" class="btn btn-warning btn-sm">변경</button> <button onclick="appendContent()" class="btn btn-warning btn-sm">추가</button> <button onclick="deleteContent()" class="btn btn-warning btn-sm">삭제</button> <hr/> <div id="div1"></div> </div> </div> <div class="card"> <div class="card-header">스타일 변경</div> <div class="card-body"> <button onclick="changeCss()" class="btn btn-warning btn-sm">스타일 변경</button> <hr/> <div id="div2"> <img id="img1" src="/htmlcssjs/resources/image/photos/photo3.jpg" width="100"/> <img class="rounded-circle" src="/htmlcssjs/resources/image/photos/photo4.jpg" width="50" height="50"/> </div> </div> </div> <div class="card"> <div class="card-header">속성값 변경</div> <div class="card-body"> <button onclick="changeAttribute()" class="btn btn-warning btn-sm">속성값 변경</button> <hr/> <div id="div3"> <img id="img2" src="/htmlcssjs/resources/image/photos/photo5.jpg" class="rounded-circle" width="100" height="100"/> </div> </div> </div> </div> </div> </body> </html>
import { Component } from '@angular/core'; import { discount, orders } from 'src/admin/admin.component'; import { CartServiceService } from 'src/app/cart-service.service'; import { DiscountServiceService } from 'src/app/discount-service.service'; import { OrderServiceService } from 'src/app/order-service.service'; import { ProductServiceService } from 'src/app/product-service.service'; import { product } from 'src/product/product.component'; import { getCookie } from 'typescript-cookie'; @Component({ selector: 'app-cart', templateUrl: './cart.component.html', styleUrls: ['./cart.component.css'] }) export class CartComponent { uId: number = 0; ordersList: orders[] = [] cartList: cart[] = []; disList: discount[] = []; prodList: product[] = []; cartProdList: cartProduct[] = [new cartProduct()]; totalPrice:number = 0; totalPriceString: string = '0;' constructor(private cartServe:CartServiceService, private orderServe:OrderServiceService, private disServe: DiscountServiceService, private prodServe:ProductServiceService){ this.getCookieInfo(); } //upon loading the page, get the User ID from the userMetaData cookie getCookieInfo(){ let uMD= getCookie('userMetaData') as string; if((uMD)!== "null" && (uMD)!== undefined) { try { let parsedUMD= JSON.parse(uMD); this.uId = parsedUMD.userId this.getDiscountsByUserId(); } catch (e) { console.error('Failed to parse userMetaData' , e); } } } //then, generate a list of all discounts of that user getDiscountsByUserId(){ return this.disServe.findAllByUserId(this.uId).subscribe(data=>{ console.log(data); this.disList=Object.values(data); this.getProducts(); },error=>console.log(error)); } //then, generate a local list of all available products getProducts(){ return this.prodServe.getAllProduct().subscribe(data=>{ console.log(data); this.prodList=Object.values(data); this.getCartByUserId(); }); } //next, generate a list of all carts belonging to that user getCartByUserId(){ return this.cartServe.getAllByUserId(this.uId).subscribe(data=>{ console.log(data); this.cartList=Object.values(data); this.buildCartProdList(); },error=>console.log(error)); } //then, using all the gathered information, generate a list of cartProducts to store all the relavent information in one place buildCartProdList(){ this.cartProdList = []; this.cartList.forEach(cart => { console.log(cart); let cp: cartProduct = new cartProduct; cp.cartId = cart.cartId; cp.quantity = cart.quantity; cp.p_id = cart.productId; let p:product = this.getProduct(cart.productId); console.log(p); cp.p_name = p.p_name; cp.image_id = p.image_id; cp.p_price = p.p_price cp.t_price = Math.round(cp.p_price * cp.quantity * 100)/100; cp.d_id = this.getDiscountId(cart.productId); cp.discount = this.getDiscount(cart.productId); cp.discount_percent = Math.round(cp.discount * 100); cp.d_price = Math.round(cp.t_price * (1 - cp.discount) * 100)/100; this.cartProdList.push(cp); }); console.log(this.cartProdList); this.setTotalPrice(); } //finally, caluclate the total price of all the carts setTotalPrice(){ this.totalPrice = 0; this.cartProdList.forEach(cp => { this.totalPrice = this.totalPrice + cp.d_price; }); this.totalPrice = Math.round(this.totalPrice * 100) / 100 this.totalPriceString = this.totalPrice.toFixed(3); } getProduct(p_id:number):product { let p = new product(); this.prodList.forEach(prod => { if(prod.p_id == p_id){ p = prod; } }); return p; } getDiscountId(p_id:number):number { let d = 0; this.disList.forEach(dis => { if(dis.p_id == p_id){ d = dis.d_id; } }); return d; } getDiscount(p_id:number):number { let d = 0; this.disList.forEach(dis => { if(dis.p_id == p_id){ d = dis.discount; } }); return d; } addQuantity(cartId: number,quantity: number){ return this.cartServe.updateQuantity(cartId, quantity+1).subscribe(data=>{ this.getCartByUserId(); },error=>console.log(error)); } subQuantity(cartId: number,quantity: number){ return this.cartServe.updateQuantity(cartId, quantity-1).subscribe(data=>{ if(quantity-1 == 0){ this.removeCart(cartId); } this.getCartByUserId(); },error=>console.log(error)); } removeCart(cartId: number){ return this.cartServe.deleteCart(cartId).subscribe(data=>{ this.getCartByUserId(); },error=>console.log(error)); } //build a list of orders based on the information presented in the cartProdList buildOrderList(){ console.log('buildOrderList()') this.cartProdList.forEach(cp => { let o:orders = new orders(); o.d_id = cp.d_id; o.date = '2023-01-01'; o.o_price = cp.p_price; o.productId = cp.p_id; o.quantity = cp.quantity; o.userId = this.uId; this.ordersList.push(o); }); console.log(this.ordersList); this.sendOrder(); } //post the list of orders to the database sendOrder(){ console.log('sendOrder()'); return this.orderServe.postOrder(this.ordersList).subscribe(data=>{ console.log(data); alert(data); this.clearCart(); },error=>console.log(error)); } //clear the cart once the order is made. clearCart(){ console.log('clearCart()'); this.cartProdList.forEach(cp => { this.removeCart(cp.cartId); }); this.getCartByUserId(); } } export class cart{ cartId = 0; userId = 0; productId = 0; quantity = 0; } export class cartProduct{ cartId = 0; p_id = 0; p_name = "product name"; image_id = "image"; quantity = 0; p_price = 0; t_price = 0; d_id = 0; discount = 0; discount_percent = 0; d_price = 0; }