text
stringlengths 184
4.48M
|
---|
import { useEffect, useState } from 'react';
import { ContainerStat } from '../../shared/styles/styles';
import { Divider, Stack, Typography, useTheme } from '@mui/material';
import { ButtonTable } from './ui/button-table';
import PhoneIcon from '@mui/icons-material/Phone';
import BookmarkOutlinedIcon from '@mui/icons-material/BookmarkOutlined';
import FunctionsOutlinedIcon from '@mui/icons-material/FunctionsOutlined';
import { CurrencySymbol } from '../../shared/enums/currency-symbol.enum';
import { userStore } from '../../user-store.context';
import { observer } from 'mobx-react-lite';
import { separateThousand } from '../../shared/lib/separate-thousand';
import { UserStat } from '../../entities/user/model/type';
import { useUser } from '../../user-context';
export const StatOurActionColumn = observer(() => {
const theme = useTheme();
const user = useUser();
const isLoadingStat = userStore.loadingStat;
const [userStat, setUserStat] = useState<UserStat>();
useEffect(() => {
const prepareStat = async () => {
await userStore.fetchStat(user.id);
};
prepareStat().then(() => {
setUserStat(userStore.statAction);
});
}, []);
return userStat ? (
<ContainerStat
padding={theme.custom.layout.padding.lg}
alignItems={'center'}
gap={theme.custom.base.module.fourth}
alignSelf={'stretch'}
direction={'row'}
border={'0px'}
>
<Typography variant={'headline5'} color={theme.palette.text.primary}>
Ваша статистика
</Typography>
{!isLoadingStat && (
<Stack
direction={'row'}
divider={
<Divider
orientation='vertical'
flexItem
sx={{
borderColor: theme.custom.divider.divider,
}}
/>
}
spacing={'24px'}
>
<ButtonTable
background={theme.custom.plus.main}
text={separateThousand(userStat.realEstateCallsCount)}
startIcon={<PhoneIcon />}
tooltip={{
text: 'Звонки, совершенные через АТС за последние 30 дней',
width: '230px',
}}
/>
<ButtonTable
background={theme.palette.error.main}
text={separateThousand(userStat.crmRealEstateCount)}
startIcon={<BookmarkOutlinedIcon />}
tooltip={{
text: 'Объекты, сохраненные из парсера в РИЭС',
width: '277px',
}}
/>
<ButtonTable
background={theme.palette.success.main}
text={`${separateThousand(userStat.crmRealEstateCommission)} ${CurrencySymbol.RUB}`}
startIcon={<FunctionsOutlinedIcon />}
tooltip={{
text: 'Ожидаемая комиссия с продажи объектов, сохраненных в РИЭС',
width: '240px',
}}
/>
</Stack>
)}
</ContainerStat>
) : null;
});
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import { BaseIntegrationTest, ModuleKitHelpers, ModuleKitUserOp } from "test/BaseIntegration.t.sol";
import { AutoSavings } from "src/AutoSavings/AutoSavings.sol";
import { MODULE_TYPE_EXECUTOR } from "modulekit/external/ERC7579.sol";
import { MockERC4626, ERC20 } from "solmate/test/utils/mocks/MockERC4626.sol";
import { SENTINEL } from "sentinellist/SentinelList.sol";
import { IERC20 } from "forge-std/interfaces/IERC20.sol";
address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
contract AutoSavingsIntegrationTest is BaseIntegrationTest {
using ModuleKitHelpers for *;
using ModuleKitUserOp for *;
CONTRACTS
AutoSavings internal executor;
MockERC4626 internal vault1;
MockERC4626 internal vault2;
VARIABLES
address[] _tokens;
IERC20 usdc = IERC20(USDC);
IERC20 weth = IERC20(WETH);
uint256 mainnetFork;
SETUP
function setUp() public virtual override {
string memory mainnetUrl = vm.rpcUrl("mainnet");
mainnetFork = vm.createFork(mainnetUrl);
vm.selectFork(mainnetFork);
vm.rollFork(19_274_877);
BaseIntegrationTest.setUp();
executor = new AutoSavings();
vm.label(address(usdc), "USDC");
vm.label(address(weth), "WETH");
deal(address(usdc), instance.account, 1_000_000);
deal(address(weth), instance.account, 1_000_000);
vault1 = new MockERC4626(ERC20(address(usdc)), "vUSDC", "vUSDC");
vault2 = new MockERC4626(ERC20(address(weth)), "vwETH", "vwETH");
_tokens = new address[](2);
_tokens[0] = address(usdc);
_tokens[1] = address(weth);
AutoSavings.Config[] memory _configs = getConfigs();
bytes memory data = abi.encode(_tokens, _configs);
instance.installModule({
moduleTypeId: MODULE_TYPE_EXECUTOR,
module: address(executor),
data: data
});
}
UTILS
function getConfigs() public returns (AutoSavings.Config[] memory _configs) {
_configs = new AutoSavings.Config[](2);
_configs[0] = AutoSavings.Config(100, address(vault1), 10);
_configs[1] = AutoSavings.Config(100, address(vault2), 10);
}
TESTS
function test_OnInstallSetsConfigAndTokens() public {
// it should set the config and tokens of the account
bool isInitialized = executor.isInitialized(address(instance.account));
assertTrue(isInitialized);
AutoSavings.Config[] memory _configs = getConfigs();
for (uint256 i; i < _tokens.length; i++) {
(uint16 _percentage, address _vault, uint128 _sqrtPriceLimitX96) =
executor.config(address(instance.account), _tokens[i]);
assertEq(_percentage, _configs[i].percentage);
assertEq(_vault, _configs[i].vault);
assertEq(_sqrtPriceLimitX96, _configs[i].sqrtPriceLimitX96);
}
address[] memory tokens = executor.getTokens(address(instance.account));
assertEq(tokens.length, _tokens.length);
}
function test_OnUninstallRemovesConfigAndTokens() public {
// it should remove the config and tokens of the account
instance.uninstallModule({
moduleTypeId: MODULE_TYPE_EXECUTOR,
module: address(executor),
data: ""
});
bool isInitialized = executor.isInitialized(address(instance.account));
assertFalse(isInitialized);
for (uint256 i; i < _tokens.length; i++) {
(uint16 _percentage, address _vault, uint128 _sqrtPriceLimitX96) =
executor.config(address(instance.account), _tokens[i]);
assertEq(_percentage, 0);
assertEq(_vault, address(0));
assertEq(_sqrtPriceLimitX96, 0);
}
address[] memory tokens = executor.getTokens(address(instance.account));
assertEq(tokens.length, 0);
}
function test_SetConfig() public {
// it should add a config and token
address token = address(2);
AutoSavings.Config memory config = AutoSavings.Config(10, address(1), 100);
instance.getExecOps({
target: address(executor),
value: 0,
callData: abi.encodeCall(AutoSavings.setConfig, (token, config)),
txValidator: address(instance.defaultValidator)
}).execUserOps();
(uint16 _percentage, address _vault, uint128 _sqrtPriceLimitX96) =
executor.config(address(instance.account), token);
assertEq(_percentage, config.percentage);
assertEq(_vault, config.vault);
assertEq(_sqrtPriceLimitX96, config.sqrtPriceLimitX96);
}
function test_DeleteConfig() public {
// it should delete a config and token
AutoSavings.Config[] memory _configs = getConfigs();
(uint16 _percentage, address _vault, uint128 _sqrtPriceLimitX96) =
executor.config(address(instance.account), _tokens[1]);
assertEq(_percentage, _configs[1].percentage);
assertEq(_vault, _configs[1].vault);
assertEq(_sqrtPriceLimitX96, _configs[1].sqrtPriceLimitX96);
instance.getExecOps({
target: address(executor),
value: 0,
callData: abi.encodeCall(AutoSavings.deleteConfig, (SENTINEL, _tokens[1])),
txValidator: address(instance.defaultValidator)
}).execUserOps();
(_percentage, _vault, _sqrtPriceLimitX96) =
executor.config(address(instance.account), _tokens[1]);
assertEq(_percentage, 0);
assertEq(_vault, address(0));
assertEq(_sqrtPriceLimitX96, 0);
}
function test_AutoSave_WithUnderlyingToken() public {
// it should deposit the underlying token into the vault
uint256 amountReceived = 100;
uint256 prevBalance = usdc.balanceOf(address(vault1));
uint256 assetsBefore = vault1.totalAssets();
instance.getExecOps({
target: address(executor),
value: 0,
callData: abi.encodeCall(AutoSavings.autoSave, (address(usdc), amountReceived)),
txValidator: address(instance.defaultValidator)
}).execUserOps();
assertEq(usdc.balanceOf(address(instance.account)), 999_900);
assertEq(usdc.balanceOf(address(vault1)), prevBalance + amountReceived);
uint256 assetsAfter = vault1.totalAssets();
assertGt(assetsAfter, assetsBefore);
}
function test_AutoSave_WithNonUnderlyingToken() public {
// it should deposit the underlying token into the vault
uint128 limit = 100;
AutoSavings.Config memory config = AutoSavings.Config(10, address(vault2), limit);
instance.getExecOps({
target: address(executor),
value: 0,
callData: abi.encodeCall(AutoSavings.setConfig, (address(usdc), config)),
txValidator: address(instance.defaultValidator)
}).execUserOps();
// note: this is a hack to use limit 0 instead of calculating the correct limit for the pair
bytes32 slot = bytes32(
uint256(
keccak256(
abi.encode(address(usdc), keccak256(abi.encode(address(instance.account), 0)))
)
) + 1
);
bytes32 storedLimit = vm.load(address(executor), slot);
assertEq(uint256(storedLimit), uint256(limit));
vm.store(address(executor), slot, bytes32(0));
uint256 amountReceived = 1000;
uint256 assetsBefore = vault2.totalAssets();
instance.getExecOps({
target: address(executor),
value: 0,
callData: abi.encodeCall(AutoSavings.autoSave, (address(usdc), amountReceived)),
txValidator: address(instance.defaultValidator)
}).execUserOps();
uint256 assetsAfter = vault2.totalAssets();
assertGt(assetsAfter, assetsBefore);
}
}
|
package com.voloshynroman.zirkon.presentation.activity
import androidx.lifecycle.viewModelScope
import com.voloshynroman.zirkon.core.base.BaseViewModel
import com.voloshynroman.zirkon.core.common.Dialog
import com.voloshynroman.zirkon.core.common.Progress
import com.voloshynroman.zirkon.core.common.UiState
import com.voloshynroman.zirkon.domain.repositories.genre.IGenreRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* @author Roman Voloshyn (Created on 27.05.2024)
*/
@HiltViewModel
class MainViewModel @Inject constructor(
private val genreRepository: IGenreRepository
): BaseViewModel<UiState, MainUiEvent, Progress, Dialog>() {
override fun handleUiEvent(uiEvent: MainUiEvent) {
when(uiEvent) {
MainUiEvent.LoadGenres -> loadGenres()
}
}
private fun loadGenres() {
viewModelScope.launch(Dispatchers.Main) {
genreRepository.saveGenresLocallyIfNeed()
}
}
}
|
## Session 1
> September 06 2022
- **Sorted** (Array/Linked List) will be given.
- You will need to calculate some **specific numbers** that **matches** some value.
- The set of elements could be a pair, a triplet or even a subarray.
### 1. Pair with Target Sum
---
If you already know the topic get let you try first.
```ad-important
**Solve On:** [167. Two Sum II](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)
**Given:** Input array is sorted
**Difficulty:** Easy
**Additional Topic:** ?
```
> **Given:** An array of sorted numbers. And a target sum.
>
> **Find:** A pair of indices in the array whose sum is equal to the given target.
```yaml
Input: [2, 4, 7, 8, 12, 14]
Target Sum: 13
Output: [1, 4]
```
| 2 | 4 | 7 | 8 | 9 | 12 | 14 |
| --- | --- | --- | --- | --- | --- | --- |
| 0 | 1 | 2 | 3 | 4 | 5 | 6 |
#### Approach 1: Brute Force
- Here the length of the array is n = **7**.
- Iterating for each elements (pointed by first pointer) we search second element in remaining elements (pointed by second pointer)
- For First number 2: (2 + 4), (2 + 7), (2 + 8), ( 2 + 9), (2 + 12) (2 + 14) possible sum (6 = n - 1).
- For First number 4: (5 = n - 2) possible sum and so on.
- Time Analysis: $$ Total Possible Sum = 6 + 5 + 4 + 3 + 2 + 1 $$
- For n: $$ Total Possible Sum = (n -1) + (n - 2) + (n - 3) + .... + 2 + 1 $$
- Sum of the first n natural no: $$ = \frac{n(n + 1) }{2} $$
- Sum of the first (n - 1) no: $$ = \frac{n(n - 1)}{2} = \frac{n^2}{2} - \frac{n}{2} $$
- So, $$ Time Complexity: O(n^2) $$ and $$ Space Complexity: O(1) $$
**Code:**
```python
# T.C: O(n^2)
def solve(arr,target):
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] + arr[j] == target:
return [i, j]
return [-1, -1]
arr = [2, 4, 8, 7, 9, 12, 14]
target = 13
print(solve(arr, target))
```
#### Approach 2: Optimized Version
```ad-hint
**Ask Yourself:** Why the array is sorted?
```
| 2 | 4 | 7 | 8 | 9 | 12 | 14 |
| --- | --- | --- | --- | --- | --- | --- |
| 0 | 1 | 2 | 3 | 4 | 5 | 6 |
- An efficient way would be to start with one pointer in the beginning and another pointer at the end.
- At every step, we will see if the numbers pointed by the two pointers add up to the target sum. If they do not, we will do one of two things:
- If the sum of the two numbers pointed by the two pointers is greater than the target sum, this means that we need a pair with a smaller sum. We have to add smaller value for that we have to decrement end pointer index.
- If the sum of the two numbers pointed by the two pointers is less than the target sum, this means that we need a pair with a greater sum. We have to add greater value for that we have to increment start pointer.
$$ Time Complexity: O(n) $$
$$ Space Complexity: O(1) $$

**Code:**
```python
# T.C: O(n)
def pairSum(arr,target):
left = 0
right = len(arr)-1
while left < right:
Sum = arr[left] + arr[right]
if Sum == target:
return [left,right]
elif Sum < target:
left += 1
else:
right -= 1
return [-1, -1]
arr = [1, 3, 5, 6, 8, 9]
target = 11
print(pairSum(arr, target))
```
### 2. Squaring a Sorted Arrays
If you already know the topic get let you try first.
```ad-important
**Solve On:** [977. Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/)
**Given:** Input array is sorted
**Difficulty:** Easy
**Additional Topic:** ?
```
> **Given:** You are given a sorted array of whole numbers.
>
> **Find:** calculate their squares and the array should be in sorted.
```yaml
Input: [2, 4, 7, 8, 9, 12, 14]
Output: [4, 16, 49, 64, 81, 144, 196]
```
```yaml
Input: [-5, -4, -2, 0, 1, 3, 4]
Output: [0, 1, 4, 9, 16, 16, 25]
```
#### Approach 1: Brute Force
- Simply calculate squares and store values into the another `answer` array.
- And then sort the array.
$$ Time Complexity: O(n \log_{10}n) For Sorting $$
$$ Space Complexity: O(n) $$
```python
def squareArr(arr):
ans = []
for i in arr:
ans.append(i*i)
return sorted(ans)
arr = [-5, -4, -1, 0, 2, 3, 4]
print(squareArr(arr))
```
#### Approach 2: Optimized
- let us take two pointer at start and end of the array.
$$ Time Complexity: O(n) $$
$$ Space Complexity: O(n) $$
```python
def square(arr):
left,right = 0, len(arr)-1
index = len(arr)-1
ans = [0]*len(arr)
while left<=right:
lsquare = arr[left]**2
rsquare = arr[right]**2
if lsquare > rsquare:
ans[index] = lsquare
left += 1
else:
ans[index] = rsquare
right -= 1
index -= 1
return ans
arr = [-5, -4, -2, 0, 1, 3, 4]
print(square(arr))
```
**OR**
```python
def squareArr(arr):
ans = []
left, right = 0, len(arr)-1
while left<=right:
l = arr[left]*arr[left]
r = arr[right]*arr[right]
if l>r:
ans.insert(0,l)
left += 1
else:
ans.insert(0,r)
right -= 1
return ans
arr = [-5, -4, -1, 0, 2, 3, 4]
print(squareArr(arr))
```
## Session 2
> September 08 2022
### 3. Triplet Sum to Zero (Unique Triplets)
If you already know the topic get let you try first.
```ad-important
1. **Solve On:** [Find triplets with zero sum](https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1)
**Platform:** GFG
**Difficulty:** Easy
**Additional Topic:** `HashMap`
2. **Solve On:** [15. 3Sum](https://leetcode.com/problems/3sum/)
**Platform:** Leetcode
**Difficulty:** Medium
**Additional Topic:** `HashMap`
3. **Solve On:** [3Sum Closest](https://leetcode.com/problems/3Sum-Closest/)
**Platform:** Leetcode
**Difficulty:** Medium
**Additional Topic:** `HashMap`
```
> **Given:** An unsorted array.
> **Find:** Find all unique triplets in the array which gives the sum of zero.
> The solution set must contain unique triplets.
```yaml
Input: [-3, 0, 1, 2, -1, 1, -2]
Output: [[-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1]]
```
|-3|0|1|2|-1|1|-2|
|--|--|--|--|--|--|--|
|0|1|2|3|4|5|6|

```ad-note
For Solution you must think first on pen and paper.
```
#### Approach 1: Brute Force
| Insert Figure to Illustrate the brute force
1.
2.
3.
4.
5.
6.
7.
```python
def tripletZero(arr):
n = len(arr)
ans = set()
for i in range(n-2):
for j in range(i+1,n-1):
for k in range(j+1,n):
if arr[i] + arr[j] + arr[k] == 0:
ans.add((arr[i], arr[j], arr[k]))
return ans
arr = [-3, 0, 1, 2, -1, 1, -2]
print(tripletZero(arr))
```
**Output:** {(0, -1, 1), (-3, 1, 2), (1, 1, -2), (0, 1, -1), (0, 2, -2), (-3, 2, 1)}
```ad-warning
Here, the solution not contains unique sum.
```
**Complexity Analysis:**
$$ Time Complexity : O (n^3) $$ $$ Space Complexity: O (1), approx $$
#### Approach 2: Optimized
1. First sort the array.
2. Treat the third element (negative of original) as a target of remaining two element $(x + y = - z)$.
|-3|0|-2|1|-1|2|1|-3|2|
|--|--|--|--|--|--|--|--|--|
|0|1|2|3|4|5|6|7|8|
```python
def tripletZero(arr):
triplets = []
arr.sort()
for i in range(len(arr)):
target = -arr[i]
if i>0 and arr[i]==arr[i-1]:
continue
find_pair(arr,i+1,target,triplets)
return triplets
def find_pair(arr, left,target, triplets):
right = len(arr)-1
while left<right:
arrsum = arr[left] + arr[right]
if arrsum==target:
triplets.append([-target, arr[left], arr[right]])
left += 1
right -= 1
# To remove duplicate pair
while left<right and arr[left]==arr[left-1]:
left += 1
while left<right and arr[right]==arr[right+1]:
right -= 1
elif arrsum< target:
left += 1
else:
right -= 1
arr = [-3, -3, 0, 1, 2, 2, -1, 1, -2, -2]
print(tripletZero(arr))
```
- ***Time Complexity :*** $O (n^2)$
- ***Space Complexity :*** $O (n)$
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
|
@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 lead text-center">{{ __('Create an account') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
@csrf
<div class="form-group row">
<label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Username') }}:</label>
<div class="col-md-6">
<input id="username" type="text" class="form-control @error('username') is-invalid @enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>
@error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@else
<small id="username-text" class="form-text text-muted">Letters, numbers, dashes & underscores.</small>
@enderror
</div>
</div>
<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="{{ old('email') }}" required autocomplete="email">
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@else
<small id="email-text" class="form-text text-muted">Verfication is required.</small>
@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>
@else
<small id="password-text" class="form-text text-muted">Passwords must be at least 8 characters.</small>
@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">
<small id="password-confirm-text" class="form-text text-muted">Retype your password.</small>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Create Account') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
|
import 'package:get/get.dart';
import 'package:shopy_bay/data/models/review_model.dart';
import '../data/service/network_caller.dart';
import '../data/utilities/urls.dart';
class GetReviewController extends GetxController {
bool _isLoading = false;
bool get isLoading => _isLoading;
String _errorMessage = '';
String get errorMessage => _errorMessage;
ReviewModel _reviewModel = ReviewModel();
ReviewModel get reviewModel => _reviewModel;
Future<bool> getReview(int id) async {
_isLoading = true;
update();
final response = await NetWorkCaller().getRequest(
Urls.listReviewByProduct(id));
_isLoading = false;
if (response.isSuccess) {
_reviewModel = ReviewModel.fromJson(response.responseData);
update();
return true;
} else {
_errorMessage = response.errorMessage;
update();
return false;
}
}
}
|
import { Component, Inject, OnInit, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
import { TuiDialogService, TuiNotification, TuiNotificationsService } from '@taiga-ui/core';
import { firstValueFrom } from 'rxjs';
import { UserDto, UsersService } from '../../../providers/api-client.generated';
import { BaseComponent } from '../../../utils/base/base.component';
import { AuthDataService } from '../../../utils/services/auth-data.service';
import { AuthProvider } from '../../../utils/services/auth-provider';
interface PictureWrapper {
path: string;
selected: boolean;
}
@Component({
selector: 'app-profile',
templateUrl: './profile.page.html',
styleUrls: ['./profile.page.scss'],
encapsulation: ViewEncapsulation.None,
})
export class ProfilePage extends BaseComponent implements OnInit {
activeItemIndex = 0;
userDto = {} as UserDto;
userForm: any;
modifDateString = '';
imagesList = [
{ path: '/assets/img/boy-1.png', selected: false },
{ path: '/assets/img/boy-2.png', selected: false },
{ path: '/assets/img/boy-3.png', selected: false },
{ path: '/assets/img/boy-4.png', selected: false },
{ path: '/assets/img/girl-1.png', selected: false },
{ path: '/assets/img/girl-2.png', selected: false },
{ path: '/assets/img/girl-3.png', selected: false },
{ path: '/assets/img/girl-4.png', selected: false },
] as PictureWrapper[];
constructor(
private userService: UsersService,
@Inject(TuiNotificationsService)
private readonly notifications: TuiNotificationsService,
@Inject(TuiDialogService) private readonly dialogService: TuiDialogService,
private authProvider: AuthProvider,
private router: Router,
) {
super();
}
async ngOnInit() {
if (!AuthDataService.currentUser)
this.router.navigate([this.RoutesList.Login]);
this.loading = true;
const userResponse = await firstValueFrom(this.userService.getUser({ id: AuthDataService.currentUser?.id! }));
this.loading = false;
if (!userResponse.success) {
this.notifications.show(userResponse.message!);
return;
}
this.userDto = userResponse.user;
const tempDate = new Date(this.userDto.modifDate!);
this.modifDateString = tempDate.toLocaleDateString().toString()!;
}
selectProfilePicture(picture: PictureWrapper) {
this.imagesList.forEach((picture) => {
picture.selected = false;
});
picture.selected = !picture.selected;
this.userDto.imgUrl = picture.path;
}
async save() {
this.loading = true;
const saveResponse = await firstValueFrom(this.userService.createOrUpdateUser({ userDto: this.userDto }));
this.loading = false;
if (!saveResponse.success) {
this.notifications.show(saveResponse.message!);
return;
}
AuthDataService.currentUser.imgUrl = this.userDto.imgUrl;
this.notifications.show('Vos informations ont été sauvegardé avec succès. 👍').subscribe();
}
async archiveMyAccount() {
this.loading = true;
const response = await firstValueFrom(this.userService.archiveMyAccount());
this.loading = false;
if (!response.success) {
this.notifications.show(response.message!).subscribe();
return;
}
this.notifications.show('Votre compte a été désactivé avec succès. 👍', { status: TuiNotification.Warning }).subscribe();
await this.authProvider.logout();
this.router.navigate([this.RoutesList.Home]);
}
async deleteMyAccount() {
this.loading = true;
const response = await firstValueFrom(this.userService.deleteAccount());
this.loading = false;
if (!response.success) {
this.notifications.show(response.message!);
return;
}
this.notifications.show('Votre compte a été supprimé avec succès. 👍', { status: TuiNotification.Error }).subscribe();
await this.authProvider.logout();
this.router.navigate([this.RoutesList.Home]);
}
}
|
#-*- coding:UTF-8 -*-
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.pagedown import PageDown
from config import config
bootstrap=Bootstrap()
mail=Mail()
moment=Moment()
db=SQLAlchemy()
pagedown=PageDown()
login_manager=LoginManager()
login_manager.session_protection='strong'
login_manager.login_view='auth.login'
def create_app(config_name):
app=Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
pagedown.init_app(app)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint,url_prefix='/auth')
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)#在工厂函数中注册蓝本
from .api_1_0 import api as api_1_0_blueprint
app.register_blueprint(api_1_0_blueprint,url_prefix='/api/v1.0')
return app
|
import 'dart:async';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:http/http.dart' show Client;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tambah_limit/models/resultModel.dart';
import 'package:tambah_limit/models/userModel.dart';
import 'package:tambah_limit/resources/userAPI.dart';
import 'package:tambah_limit/settings/configuration.dart';
import 'package:tambah_limit/tools/function.dart';
import 'package:tambah_limit/widgets/EditText.dart';
import 'package:tambah_limit/widgets/TextView.dart';
import 'package:tambah_limit/widgets/button.dart';
Future<SharedPreferences> _sharedPreferences = SharedPreferences.getInstance();
class Profile extends StatefulWidget {
final Result result;
const Profile({Key key, this.result}) : super(key: key);
@override
ProfileState createState() => ProfileState();
}
class ProfileState extends State<Profile> {
bool unlockOldPassword = true;
bool unlockNewPassword = true;
bool unlockConfirmPassword = true;
final oldPasswordController = TextEditingController();
final newPasswordController = TextEditingController();
final confirmPasswordController = TextEditingController();
final FocusNode oldPasswordFocus = FocusNode();
final FocusNode newPasswordFocus = FocusNode();
final FocusNode confirmPasswordFocus = FocusNode();
bool oldPasswordValid = false;
bool newPasswordValid = false;
bool confirmPasswordValid = false;
String oldPasswordErrorMessage = "", newPasswordErrorMessage = "", confirmPasswordErrorMessage = "";
bool changePasswordLoading = false;
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Container(
margin: EdgeInsets.symmetric(vertical: 30, horizontal: 15),
child: EditText(
useIcon: true,
key: Key("OldPassword"),
controller: oldPasswordController,
focusNode: oldPasswordFocus,
obscureText: unlockOldPassword,
validate: oldPasswordValid,
keyboardType: TextInputType.text,
textInputAction: TextInputAction.next,
textCapitalization: TextCapitalization.characters,
hintText: "Password Lama",
alertMessage: oldPasswordErrorMessage,
suffixIcon:
InkWell(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 5),
child: Icon(
Icons.remove_red_eye,
color: unlockOldPassword ? config.lightGrayColor : config.grayColor,
size: 18,
),
),
onTap: () {
setState(() {
unlockOldPassword = !unlockOldPassword;
});
},
),
onSubmitted: (value) {
_fieldFocusChange(context, oldPasswordFocus, newPasswordFocus);
},
onChanged: (value) {
},
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 30, horizontal: 15),
child: EditText(
useIcon: true,
key: Key("NewPassword"),
controller: newPasswordController,
focusNode: newPasswordFocus,
validate: newPasswordValid,
obscureText: unlockNewPassword,
keyboardType: TextInputType.text,
textInputAction: TextInputAction.next,
textCapitalization: TextCapitalization.characters,
hintText: "Password Baru",
alertMessage: newPasswordErrorMessage,
suffixIcon:
InkWell(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 5),
child: Icon(
Icons.remove_red_eye,
color: unlockNewPassword ? config.lightGrayColor : config.grayColor,
size: 18,
),
),
onTap: () {
setState(() {
unlockNewPassword = !unlockNewPassword;
});
},
),
onSubmitted: (value) {
_fieldFocusChange(context, newPasswordFocus, confirmPasswordFocus);
},
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 30, horizontal: 15),
child: EditText(
useIcon: true,
key: Key("ConfirmPassword"),
controller: confirmPasswordController,
focusNode: confirmPasswordFocus,
validate: confirmPasswordValid,
keyboardType: TextInputType.text,
obscureText: unlockConfirmPassword,
textInputAction: TextInputAction.done,
textCapitalization: TextCapitalization.characters,
hintText: "Konfirmasi Password Baru",
alertMessage: confirmPasswordErrorMessage,
suffixIcon:
InkWell(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 5),
child: Icon(
Icons.remove_red_eye,
color: unlockConfirmPassword ? config.lightGrayColor : config.grayColor,
size: 18,
),
),
onTap: () {
setState(() {
unlockConfirmPassword = !unlockConfirmPassword;
});
},
),
onSubmitted: (value) {
confirmPasswordFocus.unfocus();
},
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 15, horizontal: 15),
width: MediaQuery.of(context).size.width,
child: Button(
loading: changePasswordLoading,
backgroundColor: config.darkOpacityBlueColor,
child: TextView("UBAH", 3, color: Colors.white),
onTap: () {
submitValidation();
},
),
),
],
),
);
}
void submitValidation() {
setState(() {
if(oldPasswordController.text.isEmpty){
oldPasswordValid = true;
oldPasswordErrorMessage = "tidak boleh kosong";
} else {
oldPasswordValid = false;
}
if(newPasswordController.text.isEmpty){
newPasswordValid = true;
newPasswordErrorMessage = "tidak boleh kosong";
} else {
newPasswordValid = false;
}
if(confirmPasswordController.text.isEmpty){
confirmPasswordValid = true;
confirmPasswordErrorMessage = "tidak boleh kosong";
} else {
confirmPasswordValid = false;
}
if(oldPasswordController.text.isEmpty){
oldPasswordValid = true;
oldPasswordErrorMessage = "tidak boleh kosong";
} else {
oldPasswordValid = false;
}
if (newPasswordController.text != confirmPasswordController.text){
newPasswordValid = true;
confirmPasswordValid = true;
newPasswordErrorMessage = "tidak sama dengan Konfirmasi Password Baru";
confirmPasswordErrorMessage = "tidak sama dengan Password Baru";
}
});
if(!oldPasswordValid && !newPasswordValid && !confirmPasswordValid){
Alert(
context: context,
title: "Konfirmasi,",
content: Text("Apakah Anda yakin ingin mengubah password?"),
cancel: true,
type: "warning",
defaultAction: () async {
doChangePassword();
});
}
}
void doChangePassword() async {
FocusScope.of(context).requestFocus(FocusNode());
setState(() {
changePasswordLoading = true;
});
Alert(context: context, loading: true, disableBackButton: true);
SharedPreferences prefs = await SharedPreferences.getInstance();
final userCodeData = encryptData(prefs.getString('user_code'));
final oldPasswordData = encryptData(oldPasswordController.text);
String getOldPassword = await userAPI.getPassword(context, parameter: 'user_code=$userCodeData&old_pass=$oldPasswordData');
Navigator.of(context).pop();
if(getOldPassword == "OK"){
final userCodeData = encryptData(prefs.getString("user_code"));
String getChangePassword = await userAPI.changePassword(context, parameter: 'json={"new_pass":"${newPasswordController.text}","user_code":"${userCodeData}"}');
if(getChangePassword == "OK"){
Alert(
context: context,
title: "Terima kasih,",
content: Text("Password berhasil diubah, silahkan lakukan login ulang"),
cancel: false,
type: "success",
defaultAction: () async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.remove("limit_dmd");
await prefs.remove("request_limit");
await prefs.remove("user_code_request");
await prefs.remove("user_code");
await prefs.remove("max_limit");
await prefs.remove("fcmToken");
await prefs.remove("get_user_login");
await prefs.remove("nik");
await prefs.remove("module_privilege");
await FirebaseMessaging.instance.deleteToken();
await prefs.clear();
Navigator.pushReplacementNamed(
context,
"login",
);
// if (mounted) {
// SharedPreferences prefs = await SharedPreferences.getInstance();
// await prefs.remove("limit_dmd");
// await prefs.remove("request_limit");
// await prefs.remove("user_code_request");
// await prefs.remove("user_code");
// await prefs.remove("max_limit");
// await prefs.clear();
// Navigator.pushReplacementNamed(
// context,
// "login",
// );
// }
}
);
} else {
Alert(
context: context,
title: "Maaf,",
content: Text(getChangePassword),
cancel: false,
type: "error"
);
}
setState(() {
changePasswordLoading = false;
});
} else {
Alert(
context: context,
title: "Maaf,",
content: Text(getOldPassword),
cancel: false,
type: "error"
);
}
setState(() {
changePasswordLoading = false;
});
}
_fieldFocusChange(BuildContext context, FocusNode currentFocus,FocusNode nextFocus) {
currentFocus.unfocus();
FocusScope.of(context).requestFocus(nextFocus);
}
}
|
/*
* Copyright (c) 2015. Axetta LLC. All Rights Reserved.
*/
package ru.axetta.ecafe.processor.core.report;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import ru.axetta.ecafe.processor.core.RuntimeContext;
import ru.axetta.ecafe.processor.core.persistence.Org;
import ru.axetta.ecafe.processor.core.persistence.User;
import ru.axetta.ecafe.processor.core.persistence.dao.clients.ClientDao;
import ru.axetta.ecafe.processor.core.persistence.dao.enterevents.EnterEventsRepository;
import ru.axetta.ecafe.processor.core.persistence.dao.model.ClientCount;
import ru.axetta.ecafe.processor.core.persistence.dao.model.enterevent.EnterEventCount;
import ru.axetta.ecafe.processor.core.persistence.dao.model.order.OrderItem;
import ru.axetta.ecafe.processor.core.persistence.dao.order.OrdersRepository;
import ru.axetta.ecafe.processor.core.persistence.dao.org.OrgItem;
import ru.axetta.ecafe.processor.core.persistence.dao.org.OrgRepository;
import ru.axetta.ecafe.processor.core.persistence.service.org.OrgService;
import ru.axetta.ecafe.processor.core.report.model.UserOrgsAndContragents;
import ru.axetta.ecafe.processor.core.report.model.totalbeneffeedreport.SubItem;
import ru.axetta.ecafe.processor.core.report.model.totalbeneffeedreport.TotalBenefFeedData;
import ru.axetta.ecafe.processor.core.report.model.totalbeneffeedreport.TotalBenefFeedItem;
import ru.axetta.ecafe.processor.core.utils.CalendarUtils;
import ru.axetta.ecafe.processor.core.utils.HibernateUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Сводный отчет по льготному питанию
* User: Shamil
* Date: 02.02.15
*/
public class TotalBenefFeedReport extends BasicReportForAllOrgJob {
/*
* Параметры отчета для добавления в правила и шаблоны
*
* При создании любого отчета необходимо добавить параметры:
* REPORT_NAME - название отчета на русском
* TEMPLATE_FILE_NAMES - названия всех jasper-файлов, созданных для отчета
* IS_TEMPLATE_REPORT - добавлять ли отчет в шаблоны отчетов
* PARAM_HINTS - параметры отчета (смотри ReportRuleConstants.PARAM_HINTS)
* заполняется, если отчет добавлен в шаблоны (класс AutoReportGenerator)
*
* Затем КАЖДЫЙ класс отчета добавляется в массив ReportRuleConstants.ALL_REPORT_CLASSES
*/
public static final String REPORT_NAME = "Сводный отчет по льготному питанию";
public static final String[] TEMPLATE_FILE_NAMES = {"TotalBenefFeedReport.jasper"};
public static final boolean IS_TEMPLATE_REPORT = true;
public static final int[] PARAM_HINTS = new int[]{};
public static SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
public static SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yy");
public class AutoReportBuildJob extends BasicReportJob.AutoReportBuildJob {
}
public static class Builder extends BasicReportJob.Builder {
private final String templateFilename;
public Builder(String templateFilename) {
this.templateFilename = templateFilename;
}
@Override
public BasicReportJob build(Session session, Date startTime, Date endTime, Calendar calendar) throws Exception {
Date generateTime = new Date();
Map<String, Object> parameterMap = new HashMap<String, Object>();
//if (RuntimeContext.getInstance().isTestMode()) {
// startTime = new Date(1409877287000L);
// endTime = new Date(1409963687000L);
//}
UserOrgsAndContragents userOAC = new UserOrgsAndContragents(session, getUserId());
parameterMap.put("startDate", CalendarUtils.dateShortToString(startTime));
parameterMap.put("endDate", CalendarUtils.dateShortToString(endTime));
endTime = CalendarUtils.endOfDay(endTime);
JasperPrint jasperPrint = JasperFillManager.fillReport(templateFilename, parameterMap,
createDataSource(session, org, startTime, endTime, userOAC));
Date generateEndTime = new Date();
return new TotalBenefFeedReport(generateTime, generateEndTime.getTime() - generateTime.getTime(),
jasperPrint, startTime, endTime);
}
private JRDataSource createDataSource(Session session, OrgShortItem org, Date startTime, Date endTime, UserOrgsAndContragents userOAC) throws Exception {
Map<Long, TotalBenefFeedItem> dataMap = new HashMap<Long, TotalBenefFeedItem>();
Map<Long,Long> mainBuildingMap = new HashMap<Long, Long>();
retrieveAllOrgs(dataMap, mainBuildingMap, userOAC);
retrieveStudentsCount(dataMap, mainBuildingMap);
retrieveBeneficiaryStudentsCount(dataMap, mainBuildingMap);
retrieveEnterEventsCount(dataMap, mainBuildingMap, startTime, endTime);
retrieveMealCount(dataMap, mainBuildingMap, startTime, endTime);
retrieveOrdersWithEnterEventsCount(dataMap);
retrieveOrdersWithNoEnterEventsCount(dataMap);
retrieveOrderedMeals(dataMap, mainBuildingMap, startTime, endTime);
List<TotalBenefFeedData> dataList = new ArrayList<TotalBenefFeedData>();
dataList.add(new TotalBenefFeedData());
dataList.get(0).getItemList().addAll(dataMap.values());
return new JRBeanCollectionDataSource(dataList);
}
private void retrieveOrderedMeals(Map<Long, TotalBenefFeedItem> dataMap, Map<Long, Long> mainBuildingMap, Date startDate,
Date endDate) {
GoodRequestsNewReportService service;
Session persistenceSession = null;
Transaction persistenceTransaction = null;
RuntimeContext runtimeContext = RuntimeContext.getInstance();
if (!runtimeContext.isMainNode()) {
return;
}
List<GoodRequestsNewReportService.Item> items;
try {
persistenceSession = runtimeContext.createReportPersistenceSession();
persistenceTransaction = persistenceSession.beginTransaction();
service = new GoodRequestsNewReportService(persistenceSession,"И", "И", true);
List<Long> idOfOrgList = new ArrayList<Long>(mainBuildingMap.keySet());//orgRepository.findAllActiveIds();
items = service
.buildReportItems(startDate,endDate, "", 1, 1, new Date(), new Date(),
idOfOrgList, new ArrayList<Long>(), true, true, 1, false);
persistenceTransaction.commit();
persistenceTransaction = null;
} finally {
HibernateUtils.rollback(persistenceTransaction, logger);
HibernateUtils.close(persistenceSession, logger);
}
for (GoodRequestsNewReportService.Item item : items) {
if(item.getFeedingPlanTypeNum() != 0){
continue;
}
if(item.getGoodName().contains("1-4")){
continue;
}
TotalBenefFeedItem dataMapItem = null;
for (TotalBenefFeedItem totalBenefFeedItem : dataMap.values()) {
if(totalBenefFeedItem.getOrgNum().equals(item.getOrgNum())){
dataMapItem = totalBenefFeedItem;
break;
}
}
if(dataMapItem == null){
continue;
}
dataMapItem.setOrderedMeals(dataMapItem.getOrderedMeals() + item.getTotalCount().intValue());
}
}
private void retrieveMealCount(Map<Long, TotalBenefFeedItem> dataMap, Map<Long, Long> mainBuildingMap, Date startTime, Date endTime) {
OrdersRepository ordersRepository = RuntimeContext.getAppContext().getBean(OrdersRepository.class);
for (OrderItem orderItem : ordersRepository.findAllBeneficiaryComplexes(startTime, endTime)) {
TotalBenefFeedItem totalBenefFeedItem = dataMap.get(mainBuildingMap.get(orderItem.getIdOfOrg()));
if(totalBenefFeedItem== null){
continue;
//todo wtf
}
if (orderItem.getOrdertype() == 4){
totalBenefFeedItem.setReceiveMealBenefStudents(totalBenefFeedItem.getReceiveMealBenefStudents() + 1);
totalBenefFeedItem.getReceiveMealBenefStudentsList().add(new SubItem(orderItem.getIdOfClient()));
}else if (orderItem.getOrdertype() == 6){
totalBenefFeedItem.setReceiveMealReserveStudents(totalBenefFeedItem.getReceiveMealReserveStudents() + 1);
}
}
}
private void retrieveOrdersWithEnterEventsCount(Map<Long, TotalBenefFeedItem> dataMap) {
for (TotalBenefFeedItem item : dataMap.values()) {
List<Long> tempEnterEvents = new ArrayList<Long>();
for (SubItem subItem : item.getEnteredBenefStudentsList()) {
tempEnterEvents.add(subItem.getIdofclient());
}
for ( SubItem subItem : item.getReceiveMealBenefStudentsList()){
tempEnterEvents.remove(subItem.getIdofclient());
}
item.setNotReceiveMealEnteredBenefStudents(tempEnterEvents.size());
}
}
private void retrieveOrdersWithNoEnterEventsCount(Map<Long, TotalBenefFeedItem> dataMap) {
for (TotalBenefFeedItem item : dataMap.values()) {
List<Long> tempReceiveMeal = new ArrayList<Long>();
for (SubItem subItem : item.getReceiveMealBenefStudentsList()) {
tempReceiveMeal.add(subItem.getIdofclient());
}
for ( SubItem subItem : item.getEnteredBenefStudentsList()){
tempReceiveMeal.remove(subItem.getIdofclient());
}
item.setReceiveMealNotEnteredBenefStudents(tempReceiveMeal.size());
}
}
private void retrieveStudentsCount(Map<Long, TotalBenefFeedItem> dataMap, Map<Long, Long> mainBuildingMap) {
ClientDao clientDao = RuntimeContext.getAppContext().getBean(ClientDao.class);
for (ClientCount clientCount : clientDao.findAllStudentsCount()) {
TotalBenefFeedItem totalBenefFeedItem = dataMap.get(mainBuildingMap.get(clientCount.getIdOfOrg()));
if(totalBenefFeedItem != null){
totalBenefFeedItem.setStudents(totalBenefFeedItem.getStudents() + clientCount.getCount());
}
}
}
private void retrieveBeneficiaryStudentsCount(Map<Long, TotalBenefFeedItem> dataMap,
Map<Long, Long> mainBuildingMap) {
ClientDao clientDao = RuntimeContext.getAppContext().getBean(ClientDao.class);
for (ClientCount clientCount : clientDao.findAllBeneficiaryStudentsCount()) {
TotalBenefFeedItem totalBenefFeedItem = dataMap.get(mainBuildingMap.get(clientCount.getIdOfOrg()));
if(totalBenefFeedItem != null){
totalBenefFeedItem.setBenefStudents(totalBenefFeedItem.getBenefStudents() + clientCount.getCount());
}
}
}
private void retrieveEnterEventsCount(Map<Long, TotalBenefFeedItem> dataMap, Map<Long, Long> mainBuildingMap, Date startTime, Date endTime) {
EnterEventsRepository enterEventsRepository = RuntimeContext.getAppContext().getBean(EnterEventsRepository.class);
for (EnterEventCount enterEventCount : enterEventsRepository.findAllBeneficiaryStudentsEnterEvents(startTime, endTime)) {
TotalBenefFeedItem totalBenefFeedItem = dataMap.get(mainBuildingMap.get(enterEventCount.getIdOfOrg()));
if(totalBenefFeedItem != null){
totalBenefFeedItem.setEnteredBenefStudents(totalBenefFeedItem.getEnteredBenefStudents() + 1);
totalBenefFeedItem.getEnteredBenefStudentsList().add( new SubItem(enterEventCount.getIdOfOrg(),enterEventCount.getIdOfClient()) );
}
}
}
private void retrieveAllOrgs(Map<Long, TotalBenefFeedItem> totalBenefFeedItemsMap, Map<Long,Long> mainBuildingMap, UserOrgsAndContragents userOAC) {
OrgRepository orgRepository = RuntimeContext.getAppContext().getBean(OrgRepository.class);
OrgService orgService = RuntimeContext.getAppContext().getBean(OrgService.class);
List<OrgItem> allNames;
//если роль пользователя = поставщик ( = 2 ), то берем только организации привязанных контрагентов. Для остальных ролей - все организации
if (User.DefaultRole.SUPPLIER.getIdentification().equals(userOAC.getUser().getIdOfRole())) {
allNames = orgRepository.findAllActiveBySupplier(userOAC.getOrgs(), userOAC.getUser().getIdOfUser());
}
else {
allNames = orgRepository.findAllActive();
}
TotalBenefFeedItem totalBenefFeedItem;
for (OrgItem allName : allNames) {
Org mainBulding = orgService.getMainBulding(allName.getIdOfOrg());
mainBuildingMap.put(allName.getIdOfOrg(),mainBulding.getIdOfOrg());
totalBenefFeedItem = new TotalBenefFeedItem(mainBulding);
totalBenefFeedItemsMap.put(mainBulding.getIdOfOrg(), totalBenefFeedItem);
}
}
}
public TotalBenefFeedReport(Date generateTime, long generateDuration, JasperPrint print, Date startTime,
Date endTime) {
super(generateTime, generateDuration, print, startTime, endTime);
}
private static final Logger logger = LoggerFactory.getLogger(TotalBenefFeedReport.class);
public TotalBenefFeedReport() {
}
@Override
public BasicReportForAllOrgJob createInstance() {
return new TotalBenefFeedReport();
}
@Override
public BasicReportJob.Builder createBuilder(String templateFilename) {
return new Builder(templateFilename);
}
@Override
public Logger getLogger() {
return logger;
}
@Override
public int getDefaultReportPeriod() {
return REPORT_PERIOD_PREV_DAY;
}
}
|
package com.codingpixel.undiscoveredarchives.home.search_result
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.core.view.GravityCompat
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.codingpixel.undiscoveredarchives.base.AppController
import com.codingpixel.undiscoveredarchives.base.BaseActivity
import com.codingpixel.undiscoveredarchives.databinding.ActivitySearchResultBinding
import com.codingpixel.undiscoveredarchives.home.add_new_listing.ProductsGradientsData
import com.codingpixel.undiscoveredarchives.home.add_new_listing.ProductsGradientsModel
import com.codingpixel.undiscoveredarchives.home.all_products.AllProductsData
import com.codingpixel.undiscoveredarchives.home.all_products.AllProductsModel
import com.codingpixel.undiscoveredarchives.home.product_detail.ProductDetailActivity
import com.codingpixel.undiscoveredarchives.loader.Loader
import com.codingpixel.undiscoveredarchives.network.Api
import com.codingpixel.undiscoveredarchives.network.ApiStatus
import com.codingpixel.undiscoveredarchives.network.ApiTags
import com.codingpixel.undiscoveredarchives.network.RetrofitClient
import com.codingpixel.undiscoveredarchives.utils.*
import com.codingpixel.undiscoveredarchives.view_models.HomeViewModel
import com.codingpixel.undiscoveredarchives.view_models.ViewModelFactory
import com.google.gson.Gson
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Call
class SearchResultActivity : BaseActivity() {
private lateinit var binding: ActivitySearchResultBinding
private lateinit var mContext: Context
private lateinit var viewModel: HomeViewModel
private lateinit var retrofitClient: Api
private lateinit var apiCall: Call<ResponseBody>
private var headerList: MutableList<String> = ArrayList()
private lateinit var expandableListAdapter: CustomExpandableListAdapter
private var itemList: HashMap<String, MutableList<String>> = HashMap()
private lateinit var searchAdapter: SearchResultAdapter
private lateinit var dropDownAdapter: ArrayAdapter<DropdownModel>
private var orderBy = ""
private var productCondition = ""
private var categoryId = 0
private var designerId = 0
private var colorId = 0
private var sizeId = 0
private var searchWord = ""
private var skip = 0
private var canLoadMore = false
private var favoritePosition = -1
private var productList: MutableList<AllProductsData?> = ArrayList()
private lateinit var productGradients: ProductsGradientsData
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySearchResultBinding.inflate(layoutInflater)
setContentView(binding.root)
mContext = this
retrofitClient = RetrofitClient.getClient(this@SearchResultActivity).create(Api::class.java)
blackStatusBarIcons()
initViews()
initVM()
initListeners()
initAdapter()
expandableList()
observeApiResponse()
getProductsGradients()
}
private fun expandableList() {
headerList.add("Categories")
headerList.add("Designers")
headerList.add("Size")
headerList.add("Condition")
val categoriesList: MutableList<String> = ArrayList()
categoriesList.add("Tops")
categoriesList.add("Bottoms")
categoriesList.add("Outwear")
categoriesList.add("Footwear")
val designersList: MutableList<String> = ArrayList()
designersList.add("Gucci")
designersList.add("Gucci")
designersList.add("Nike")
designersList.add("Parada")
val sizeList: MutableList<String> = ArrayList()
sizeList.add("XS")
sizeList.add("S")
sizeList.add("M")
sizeList.add("L")
val conditionList: MutableList<String> = ArrayList()
conditionList.add("New")
conditionList.add("Used")
conditionList.add("Mostly Worn")
conditionList.add("Not Specified")
itemList[headerList[0]] = categoriesList
itemList[headerList[1]] = designersList
itemList[headerList[2]] = sizeList
itemList[headerList[3]] = conditionList
expandableListAdapter = CustomExpandableListAdapter(this, headerList, itemList)
binding.navigationView.expandableListView.setAdapter(expandableListAdapter)
}
private fun initVM() {
viewModel = ViewModelProviders.of(this, ViewModelFactory()).get(HomeViewModel::class.java)
binding.viewModel = viewModel
binding.executePendingBindings()
binding.lifecycleOwner = this
}
private fun toggleDrawer() {
if (binding.drawerLayout.isDrawerOpen(binding.navView)) {
binding.drawerLayout.closeDrawer(GravityCompat.START)
} else {
binding.drawerLayout.openDrawer(GravityCompat.END)
}
}
@SuppressLint("SetTextI18n")
private fun initViews() {
binding.topBar.tvScreenTitle.text = "Search Results"
binding.topBar.ivBack.viewVisible()
/*Filter*/
dropDownAdapter = CustomDropDownAdapter(mContext, AppController.filterDropDownList)
binding.filter.adapter = dropDownAdapter
binding.etSearch.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
searchWord = s.toString()
if (s.toString().isBlank())
binding.ivSearchCross.viewGone()
else
binding.ivSearchCross.viewVisible()
}
})
binding.etSearch.setOnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//s Your action on done
getAllProducts()
true
} else false
}
}
private fun initListeners() {
/*Filter*/
binding.filter.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val orderBy = AppController.filterDropDownList[position].value
AppController.filterDropDownList.filter { it.isSelected }.forEach { it.isSelected = false }
AppController.filterDropDownList[position].isSelected = true
binding.tvFilter.text = orderBy
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
binding.ivFilter.setOnClickListener {
toggleDrawer()
}
binding.topBar.ivBack.setOnClickListener { finish() }
binding.ivSearchCross.setOnClickListener {
binding.etSearch.setText("")
searchWord = ""
getAllProducts()
}
}
@SuppressLint("NotifyDataSetChanged")
private fun observeApiResponse() {
viewModel.getApiResponse().observe(this, {
when (it.status) {
ApiStatus.LOADING -> {
Loader.showLoader(this) {
if (this@SearchResultActivity::apiCall.isInitialized)
apiCall.cancel()
}
}
ApiStatus.ERROR -> {
Loader.hideLoader()
AppUtils.showToast(this, it.message!!, false)
}
ApiStatus.SUCCESS -> {
Loader.hideLoader()
when (it.tag) {
ApiTags.GET_ALL_PRODUCTS -> {
val model = Gson().fromJson(it.data.toString(), AllProductsModel::class.java)
handleProductsResponse(model.data)
}
ApiTags.GET_PRODUCT_GRADIENTS -> {
val model = Gson().fromJson(
it.data.toString(),
ProductsGradientsModel::class.java
)
productGradients = model.data
initializeDrawer()
getAllProducts()
}
ApiTags.ADD_PRODUCT_TO_FAVORITES -> {
val jsonObject = JSONObject(it.data.toString())
val data = jsonObject.getJSONObject("data")
AppUtils.showToast(this, jsonObject.getString("message"), true)
if (data.has("is_favourite"))
productList[favoritePosition]?.is_favourite = data.getInt("is_favourite")
searchAdapter.notifyDataSetChanged()
favoritePosition = -1
}
}
}
}
})
}
private fun initializeDrawer() {
}
@SuppressLint("NotifyDataSetChanged")
private fun handleProductsResponse(data: List<AllProductsData>) {
// if (binding.pullToRefresh.isRefreshing)
// binding.pullToRefresh.isRefreshing = false
if (productList.size > 0)
productList.removeAt(productList.size - 1)
productList.addAll(data)
if (data.size >= AppController.PAGINATION_COUNT) {
skip += AppController.PAGINATION_COUNT
productList.add(null)
canLoadMore = true
}
if (productList.isEmpty()) {
binding.searchRecycler.viewGone()
binding.llNoData.viewVisible()
} else {
binding.llNoData.viewGone()
binding.searchRecycler.viewVisible()
}
searchAdapter.notifyDataSetChanged()
}
private fun initAdapter() {
searchAdapter = SearchResultAdapter(productList, object : SearchResultAdapter.SearchResultInterface {
override fun onItemClicked(position: Int) {
val intent = Intent(mContext, ProductDetailActivity::class.java)
intent.putExtra("productId", productList[position]?.id)
startActivity(intent)
}
override fun onFavoriteClicked(position: Int) {
favoritePosition = position
addProductsToFavorites(productList[position]?.id ?: -1)
}
})
binding.searchRecycler.adapter = searchAdapter
binding.searchRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val lm = recyclerView.layoutManager as LinearLayoutManager
if (lm.findLastCompletelyVisibleItemPosition() == productList.size - 1)
if (canLoadMore) {
canLoadMore = false
getAllProducts()
}
}
})
}
private fun getProductsGradients() {
apiCall = retrofitClient.getProductGradients()
viewModel.getProductGradients(apiCall)
}
private fun getAllProducts() {
apiCall = retrofitClient.getAllProducts(
orderBy, productCondition, categoryId, designerId, colorId, sizeId, searchWord, skip
)
viewModel.getAllProducts(apiCall)
}
private fun addProductsToFavorites(id: Int) {
apiCall = retrofitClient.addProductToFavorite(id)
viewModel.addProductToFavorite(apiCall)
}
}
|
import { financing } from '../pages';
import { actions } from '../pages';
import { utils } from '../pages';
const randomNumber = utils.randomNumber();
const hiw_h1 = 'Get pre-qualified with no impact to your credit score';
const hiw_p1 = 'Apply in a few minutes to see your estimated terms.';
const hiw_h2 = 'Shop with your terms';
const hiw_p2 = 'See what your monthly payment and terms would be for each car.';
const hiw_h3 = 'Finance your favorite one';
const hiw_p3 =
'Apply for an official loan from our network of trusted lenders either online or on your test drive.';
describe('Pre-qualified flow', () => {
it('Launch Pre-qualify finance page', () => {
cy.visit(
'https://shift.com/prequalify-for-financing?&financing.prequalificationClearerCommunicationVariation=PrequalificationClearerCommunicationVariationControl'
);
cy.waitForReact();
});
it('Check - How it works text', () => {
cy.get('h4', { timeout: 50000 })
.contains('How it works')
.should('be.visible');
});
it('Validate How it works text - Step 1 text', () => {
cy.get('h6').eq(0).invoke('text').should('eq', hiw_h1);
cy.get('p').eq(0).invoke('text').should('eq', hiw_p1);
});
it('Validate How it works text - Step 2 text', () => {
cy.get('h6').eq(1).invoke('text').should('eq', hiw_h2);
cy.get('p').eq(1).invoke('text').should('eq', hiw_p2);
});
it('Validate How it works text - Step 3 text', () => {
cy.get('h6').eq(2).invoke('text').should('eq', hiw_h3);
cy.get('p').eq(2).invoke('text').should('eq', hiw_p3);
});
it('Click on Get Started button', () => {
financing.clickOnGetStartedButton();
});
it('Enter email', () => {
financing.enterEmail('test-buyer+' + randomNumber + '@shift.com');
});
it('Enter password', () => {
financing.enterPassword('Test123#');
});
it('Check Terms of Service', () => {
financing.checkTermsCheckBox();
});
it('Click on Continue', () => {
actions.clickOnContinue();
});
it('Enter Rent or Mortgage', () => {
financing.enterRentOrMortgage(1000);
});
it('Click on Continue', () => {
actions.clickOnContinue();
});
it('Enter Total income', () => {
financing.enterIncome(100000);
});
it('Select Year', () => {
financing.selectYear();
});
it('Click on Continue', () => {
actions.clickOnContinue();
});
it('Enter Credit Score', () => {
financing.enterCreditScore(800);
});
it('Click on Continue', () => {
actions.clickOnContinue();
});
it('Check I Agree Checkbox', () => {
financing.checkAgreeTermsCheckBox();
});
it('Click on Continue', () => {
cy.get('span').contains('Continue').click({ force: true });
});
it('Validate Dollar Value', () => {
cy.get('div[class=DecisionDisplaySection__value]', { timeout: 100000 })
.eq(0)
.invoke('text')
.then((dollar) => {
cy.wrap(utils.splitDollar(dollar)).then((value) => {
if (value! > 0) {
cy.log('Invalid borrow amount displayed');
} else {
cy.log('borrow amount is greater than zero: ' + value);
}
});
});
});
});
|
// Copyright 2021-2023 FLECS Technologies GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <zenoh.h>
#include <map>
#include <set>
#include <string>
#include <tuple>
#include <variant>
#include "flunder/client.h"
namespace flunder {
namespace impl {
struct mem_storage_t
{
std::string name;
std::string zid;
};
inline auto operator<=>(const mem_storage_t& lhs, const mem_storage_t& rhs)
{
return lhs.name <=> rhs.name;
}
class client_t
{
public:
client_t();
~client_t();
FLECS_EXPORT auto connect(std::string_view host, int port) //
-> int;
FLECS_EXPORT auto reconnect() //
-> int;
FLECS_EXPORT auto is_connected() const noexcept //
-> bool;
FLECS_EXPORT auto disconnect() //
-> int;
FLECS_EXPORT auto publish_bool(
std::string_view topic,
const std::string& value) const //
-> int;
FLECS_EXPORT auto publish_int(
std::string_view topic,
size_t size,
bool is_signed,
const std::string& value) const //
-> int;
FLECS_EXPORT auto publish_float(
std::string_view topic,
size_t size,
const std::string& value) const //
-> int;
FLECS_EXPORT auto publish_string(
std::string_view topic,
const std::string& value) const //
-> int;
FLECS_EXPORT auto publish_raw(
std::string_view topic,
const void* payload,
size_t payloadlen) const //
-> int;
FLECS_EXPORT auto publish_custom(
std::string_view topic,
const void* payload,
size_t payloadlen,
std::string_view encoding) const //
-> int;
using subscribe_cbk_t = flunder::client_t::subscribe_cbk_t;
using subscribe_cbk_userp_t = flunder::client_t::subscribe_cbk_userp_t;
FLECS_EXPORT auto subscribe(
flunder::client_t* client, std::string_view topic, subscribe_cbk_t cbk) //
-> int;
FLECS_EXPORT auto subscribe(
flunder::client_t* client,
std::string_view topic,
subscribe_cbk_userp_t cbk,
const void* userp) //
-> int;
FLECS_EXPORT auto unsubscribe(std::string_view topic) //
-> int;
FLECS_EXPORT auto add_mem_storage(std::string topic, std::string_view name) //
-> int;
FLECS_EXPORT auto remove_mem_storage(std::string name) //
-> int;
FLECS_EXPORT auto get(std::string_view topic) const //
-> std::tuple<int, std::vector<variable_t>>;
FLECS_EXPORT auto erase(std::string_view topic) //
-> int;
/*! Function pointer to receive callback */
using subscribe_cbk_var_t = std::variant<subscribe_cbk_t, subscribe_cbk_userp_t>;
struct subscribe_ctx_t
{
flunder::client_t* _client;
z_owned_subscriber_t _sub;
subscribe_cbk_var_t _cbk;
const void* _userp;
bool _once;
};
private:
FLECS_EXPORT auto publish(
std::string_view topic,
z_encoding_t encoding,
const std::string& value) const //
-> int;
FLECS_EXPORT auto subscribe(
flunder::client_t* client,
std::string_view topic,
subscribe_cbk_var_t cbk,
const void* userp) //
-> int;
FLECS_EXPORT auto determine_connected_router_count() const //
-> int;
std::set<mem_storage_t> _mem_storages;
std::string _host;
std::uint16_t _port;
z_owned_session_t _z_session;
std::map<std::string, subscribe_ctx_t> _subscriptions;
};
auto to_string(z_encoding_prefix_t prefix, std::string_view suffix) //
-> std::string;
auto ntp64_to_unix_time(std::uint64_t ntp_time) //
-> uint64_t;
} // namespace impl
} // namespace flunder
|
@extends('layouts.app') @section('content')
<!-- Main Content -->
<div class="main-content">
<section class="section">
<div class="section-header">
<div class="section-header-back">
<a href="/users" class="btn btn-icon">
<i class="fas fa-arrow-left"></i>
</a>
</div>
<h1>Edit User</h1>
<div class="section-header-breadcrumb"> @foreach($breadcrumbs as $breadcrumb) <div class="breadcrumb-item">
<a href="{{ $breadcrumb['url'] }}">{{ $breadcrumb['label'] }}</a>
</div> @endforeach </div>
</div>
<div class="section-body">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h4>Edit Existing User</h4>
</div>
<div class="card-body">
<form action="{{ route('users.update', $user->id) }}" method="post"> @csrf @method('PUT') <div class="form-group row mb-4">
<label class="col-form-label text-md-right col-12 col-md-3 col-lg-3" for="name">Name</label>
<div class="col-sm-12 col-md-7">
<input type="text" class="form-control" id="name" name="name" value="{{ $user->name }}">
</div>
</div>
<div class="form-group row mb-4">
<label class="col-form-label text-md-right col-12 col-md-3 col-lg-3" for="email">Email</label>
<div class="col-sm-12 col-md-7">
<input type="text" class="form-control" id="email" name="email" value="{{ $user->email }}">
</div>
</div>
<div class="form-group row mb-4">
<label class="col-form-label text-md-right col-12 col-md-3 col-lg-3" for="role_id">Role</label>
<div class="col-sm-12 col-md-7">
<select name="role_id" id="role_id" class="form-control select2" required> @foreach($roles as $role) <option value="{{ $role->id }}" {{ $user->roles->contains('id', $role->id) ? 'selected' : '' }}>{{ $role->name }}</option> @endforeach </select>
</div>
</div>
<div class="form-group row mb-4">
<label class="col-form-label text-md-right col-12 col-md-3 col-lg-3" for="password">Password</label>
<div class="col-sm-12 col-md-7">
<input type="password" class="form-control" id="password" name="password">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</div> @endsection
|
import React, { useEffect, useState } from "react";
import get from "lodash/get";
import { WEATHER_KEY, CITY_ID } from "../utils/key";
import { makeStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import Loading from "../components/Loading";
import CardWheather from "../components/Card";
import axios from "../utils/weather";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
container: {
position: 'absolute',
width: "100%",
height: "70%",
display: "flex",
flexFlow: "column",
alignItems: "center",
justifyContent: "center",
},
}));
const Daily = ({ match }) => {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
const classes = useStyles();
useEffect(() => {
const getData = async () => {
const result = await axios.get(
`forecast?id=${CITY_ID}&APPID=${WEATHER_KEY}&units=metric&lang=es`
);
setItems(get(result, "data.list", []));
setLoading(false);
};
getData();
}, []);
const daily = items.find((e) => (e.dt_txt = match.params.id)) || [];
if (loading) {
return <Loading />;
}
return (
<Grid container className={classes.root} spacing={2}>
<div className={classes.container}>
<CardWheather
time={daily.dt_txt}
button={false}
description={daily.weather[0].description}
humidity={daily.main.humidity}
temperatureMin={Math.round(daily.main.temp_min)}
temperatureMax={Math.round(daily.main.temp_max)}
image={daily.weather.map((i) => {
return i.icon;
})}
/>
</div>
</Grid>
);
};
export default Daily;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->
<link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Frontend Mentor | Four card feature section</title>
</style>
</head>
<body>
<div class="main-cont">
<div class="text-cont">
<h1 class="first-h1">Reliable, efficient delivery</h1>
<h1 class="second-h1">Powered by Technology</h1>
<p>Our Artificial Intelligence powered tools use millions of project data points to ensure that your project is successful</p>
</div>
<div class="cards-cont">
<div class="card first alone">
<h3>Supervisor</h3>
<p>Monitors activity to identify project roadblocks</p>
<img class="icon" src="images/icon-supervisor.svg">
</div>
<div class="cnt-cards">
<div class="card second">
<h3>Team Builder</h3>
<p>Scans our talent network to create the optimal team for your project</p>
<img class="icon" src="images/icon-team-builder.svg">
</div>
<div class="card third">
<h3>Karma</h3>
<p>Regularly evaluates our talent to ensure quality</p>
<img class="icon" src="images/icon-karma.svg">
</div>
</div>
<div class="card forth alone">
<h3>Calculator</h3>
<p>Uses data from past projects to provide better delivery estimates</p>
<img class="icon" src="images/icon-calculator.svg">
</div>
</div>
</div>
<footer>
<p class="attribution">
Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>.
Coded by <a href="#">eleswastaken</a>.
</p>
</footer>
</body>
</html>
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Apache License 2.0.
* See the file "LICENSE" for details.
*/
package libpf
import (
"fmt"
"testing"
assert "github.com/stretchr/testify/require"
)
func TestFileIDSprintf(t *testing.T) {
var origID FileID
var err error
if origID, err = FileIDFromString("600DCAFE4A110000F2BF38C493F5FB92"); err != nil {
t.Fatalf("Failed to build FileID from string: %v", err)
}
marshaled := fmt.Sprintf("%d", origID)
// nolint:goconst
expected := "{6921411395851452416 17491761894677412754}"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%s", origID)
expected = "{%!s(uint64=6921411395851452416) %!s(uint64=17491761894677412754)}"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%v", origID)
expected = "{6921411395851452416 17491761894677412754}"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%#v", origID)
expected = "0x600dcafe4a110000f2bf38c493f5fb92"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
fileID := NewFileID(5705163814651576546, 12305932466601883523)
marshaled = fmt.Sprintf("%x", fileID)
expected = "4f2cd0431db840e2aac77460f5c07783"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%X", fileID)
expected = "4F2CD0431DB840E2AAC77460F5C07783"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%#x", fileID)
expected = "0x4f2cd0431db840e2aac77460f5c07783"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%#X", fileID)
expected = "0x4F2CD0431DB840E2AAC77460F5C07783"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
}
func TestFileIDMarshal(t *testing.T) {
var origID FileID
var err error
if origID, err = FileIDFromString("600DCAFE4A110000F2BF38C493F5FB92"); err != nil {
t.Fatalf("Failed to build FileID from string: %v", err)
}
// Test (Un)MarshalJSON
var data []byte
if data, err = origID.MarshalJSON(); err != nil {
t.Fatalf("Failed to marshal FileID: %v", err)
}
marshaled := string(data)
expected := "\"600dcafe4a110000f2bf38c493f5fb92\""
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
var jsonID FileID
if err = jsonID.UnmarshalJSON(data); err != nil {
t.Fatalf("Failed to unmarshal FileID: %v", err)
}
if jsonID != origID {
t.Fatalf("new FileID is different to original one. Expected %d, got %d", origID, jsonID)
}
// Test (Un)MarshalText
if data, err = origID.MarshalText(); err != nil {
t.Fatalf("Failed to marshal FileID: %v", err)
}
marshaled = string(data)
expected = "600dcafe4a110000f2bf38c493f5fb92"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
var textID FileID
if err = textID.UnmarshalText(data); err != nil {
t.Fatalf("Failed to unmarshal FileID: %v", err)
}
if textID != origID {
t.Fatalf("new FileID is different to original one. Expected %d, got %d", origID, textID)
}
}
func TestInvalidFileIDs(t *testing.T) {
// 15 characters
if _, err := FileIDFromString("600DCAFE4A11000"); err == nil {
t.Fatalf("Expected an error")
}
// Non-hex characters
if _, err := FileIDFromString("600DCAFE4A11000G"); err == nil {
t.Fatalf("Expected an error")
}
}
func TestFileIDFromBase64(t *testing.T) {
expected := NewFileID(0x12345678124397ff, 0x87654321877484a8)
fileIDURLEncoded := "EjRWeBJDl_-HZUMhh3SEqA"
fileIDStdEncoded := "EjRWeBJDl/+HZUMhh3SEqA"
actual, err := FileIDFromBase64(fileIDURLEncoded)
assert.Nil(t, err)
assert.Equal(t, expected, actual)
actual, err = FileIDFromBase64(fileIDStdEncoded)
assert.Nil(t, err)
assert.Equal(t, expected, actual)
}
func TestFileIDBase64(t *testing.T) {
expected := "EjRWeBJDl_WHZUMhh3SEng"
fileID := NewFileID(0x12345678124397f5, 0x876543218774849e)
assert.Equal(t, fileID.Base64(), expected)
}
func TestTraceHashSprintf(t *testing.T) {
origHash := NewTraceHash(0x0001C03F8D6B8520, 0xEDEAEEA9460BEEBB)
marshaled := fmt.Sprintf("%d", origHash)
// nolint:goconst
expected := "{492854164817184 17143777342331285179}"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%s", origHash)
expected = "{%!s(uint64=492854164817184) %!s(uint64=17143777342331285179)}"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%v", origHash)
// nolint:goconst
expected = "{492854164817184 17143777342331285179}"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%#v", origHash)
expected = "0x1c03f8d6b8520edeaeea9460beebb"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
// Values were chosen to test non-zero-padded output
traceHash := NewTraceHash(42, 100)
marshaled = fmt.Sprintf("%x", traceHash)
expected = "2a0000000000000064"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%X", traceHash)
expected = "2A0000000000000064"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%#x", traceHash)
expected = "0x2a0000000000000064"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
marshaled = fmt.Sprintf("%#X", traceHash)
expected = "0x2A0000000000000064"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
}
func TestTraceHashMarshal(t *testing.T) {
origHash := NewTraceHash(0x600DF00D, 0xF00D600D)
var err error
// Test (Un)MarshalJSON
var data []byte
if data, err = origHash.MarshalJSON(); err != nil {
t.Fatalf("Failed to marshal TraceHash: %v", err)
}
marshaled := string(data)
expected := "\"00000000600df00d00000000f00d600d\""
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
var jsonHash TraceHash
if err = jsonHash.UnmarshalJSON(data); err != nil {
t.Fatalf("Failed to unmarshal TraceHash: %v", err)
}
if origHash != jsonHash {
t.Fatalf("new TraceHash is different to original one")
}
// Test (Un)MarshalText
if data, err = origHash.MarshalText(); err != nil {
t.Fatalf("Failed to marshal TraceHash: %v", err)
}
marshaled = string(data)
expected = "00000000600df00d00000000f00d600d"
if marshaled != expected {
t.Fatalf("Expected marshaled value %s, got %s", expected, marshaled)
}
var textHash TraceHash
if err = textHash.UnmarshalText(data); err != nil {
t.Fatalf("Failed to unmarshal TraceHash: %v", err)
}
if origHash != textHash {
t.Fatalf("new TraceHash is different to original one. Expected %s, got %s",
origHash, textHash)
}
}
func TestCRC32(t *testing.T) {
crc32, err := ComputeFileCRC32("testdata/crc32_test_data")
if err != nil {
t.Fatal(err)
}
expectedValue := uint32(0x526B888)
if uint32(crc32) != expectedValue {
t.Fatalf("expected CRC32 value 0x%x, got 0x%x", expectedValue, crc32)
}
}
func TestTraceType(t *testing.T) {
tests := []struct {
ty FrameType
isErr bool
interp InterpType
str string
}{
{
ty: AbortFrame,
isErr: true,
interp: UnknownInterp,
str: "abort-marker",
},
{
ty: PythonFrame,
isErr: false,
interp: Python,
str: "python",
},
{
ty: NativeFrame.Error(),
isErr: true,
interp: Native,
str: "native-error",
},
}
for _, test := range tests {
assert.Equal(t, test.isErr, test.ty.IsError())
assert.Equal(t, test.interp, test.ty.Interpreter())
assert.Equal(t, test.str, test.ty.String())
}
}
|
/*
* @lc app=leetcode id=17 lang=cpp
*
* [17] Letter Combinations of a Phone Number
*
* https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
*
* algorithms
* Medium (44.91%)
* Likes: 3206
* Dislikes: 368
* Total Accepted: 531.2K
* Total Submissions: 1.2M
* Testcase Example: '"23"'
*
* Given a string containing digits from 2-9 inclusive, return all possible
* letter combinations that the number could represent.
*
* A mapping of digit to letters (just like on the telephone buttons) is given
* below. Note that 1 does not map to any letters.
*
*
*
* Example:
*
*
* Input: "23"
* Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
*
*
* Note:
*
* Although the above answer is in lexicographical order, your answer could be
* in any order you want.
*
*/
// @lc code=start
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> list = {"", "", "abc", "def",
"ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz"};
vector<string> result;
if (0 == digits.size()) return result;
result = {""};
for (int i = 0; i < digits.size(); i++) {
string letters = list[digits[i] - '0'];
vector<string> tmp;
for (int j = 0; j < letters.size();j++) {
for (int k = 0; k < result.size(); k++) {
tmp.push_back(result[k] + letters[j]);
}
}
result = tmp;
}
return result;
}
};
// @lc code=end
|
/*
** Copyright 2017-2021 Double Precision, Inc.
** See COPYING for distribution information.
*/
#ifndef x_w_canvasfwd_h
#define x_w_canvasfwd_h
#include <x/w/namespace.H>
#include <x/ptrfwd.H>
LIBCXXW_NAMESPACE_START
class LIBCXX_PUBLIC canvasObj;
struct canvas_config;
//! A mostly empty widget.
//! \code
//! canvas_config config;
//!
//! config.width={0, 50, 100};
//! config.height={0, 50, 100};
//!
//! factory->create_canvas(config);
//! \endcode
//!
//! The canvas object gets constructed, with specified
//! horizontal and vertical metrics.
//!
//! \code
//! c->update(h_metrics, v_metrics);
//! \endcode
//!
//! Update the canvas object's horizontal and vertical metrics.
//!
//! \see canvas_config
typedef ref<canvasObj> canvas;
//! A nullable pointer reference to an canvas.
//! \see canvas
typedef ptr<canvasObj> canvasptr;
//! A reference to a constant canvas object.
//! \see canvas
typedef const_ref<canvasObj> const_canvas;
//! A nullable pointer reference to a constant canvas object.
//! \see canvas
typedef const_ptr<canvasObj> const_canvasptr;
LIBCXXW_NAMESPACE_END
#endif
|
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { BusinessPlace } from '../../../_models/businessPlace';
import { Routine, RoutineList } from '../../../_models/employee';
import { AlertifyService } from '../../../_services/alertify.service';
import { HumanResourceService } from '../../../_services/humanResource.service';
import { MasterService } from '../../../_services/master.service';
import { UtilityService } from '../../../_services/utility.service';
@Component({
// tslint:disable-next-line: component-selector
selector: 'app-Routine',
templateUrl: './Routine.component.html',
styleUrls: ['./Routine.component.scss']
})
export class RoutineComponent implements OnInit {
date: any = '';
routines: Routine[] = [];
businessPlaces: BusinessPlace[] = [];
routineForm: FormGroup;
routinesToUpdate: RoutineList;
get gettableRowArray(): FormArray {
return this.routineForm.get('routines') as FormArray;
}
constructor(private utiService: UtilityService,
private fb: FormBuilder,
private alertify: AlertifyService,
private hrService: HumanResourceService,
private masterService: MasterService) { }
ngOnInit() {
this.date = this.utiService.currentDate();
console.log(this.date);
this.masterService.getBusinessPlaces().subscribe((result) => {
this.businessPlaces = result;
});
this.createForm();
this.getRoutines(this.date);
}
getRoutines(date: Date) {
this.hrService.getRoutines(date).subscribe((result: Routine[]) => {
this.routines = result;
this.createEditForm(result);
});
}
autoAssign() {
this.hrService.createAutoRoutine(this.date).subscribe(() => {
this.getRoutines(this.date);
}, (res) => {
if (res.error.status === 400) {
this.alertify.error(res.error.message + ': error code ' + res.error.code);
} else {
this.alertify.error('Some error occured,Try again');
}
});
}
createForm() {
this.routineForm = this.fb.group({
routines: this.fb.array([this.initiateRowValues()])
});
}
createEditForm(routines: Routine[]) {
this.ClearRows();
this.onDeleteRow(0);
routines.forEach((routineRow) => {
this.gettableRowArray.push(this.initiateEditRowValues(routineRow));
// this.totalValue = this.totalValue + podRow.lineTotal;
});
}
initiateEditRowValues(routineRow: Routine): FormGroup {
const role = routineRow.roleId;
const formRow = this.fb.group({
employeeId: new FormControl(<any>routineRow.employeeId, {
validators: [Validators.required]
}),
businessPlaceId: new FormControl(<any>routineRow.businessPlaceId, {
validators: [Validators.required]
}),
date: new FormControl(routineRow.date, {
validators: [Validators.required]
}),
startTime: new FormControl(routineRow.startTime, {
validators: [Validators.required]
}),
endTime: new FormControl(routineRow.endTime, {
validators: [Validators.required]
})
}, { validators: this.timeUnitValidator }
);
return formRow;
}
initiateRowValues(): FormGroup {
const formRow = this.fb.group({
employeeId: new FormControl(0, {
validators: [Validators.required]
}),
businessPlaceId: new FormControl(0, {
validators: [Validators.required]
}),
roleName: new FormControl('', {
validators: []
}),
date: new FormControl('', {
validators: [Validators.required]
}),
startTime: new FormControl('', {
validators: [Validators.required]
}),
endTime: new FormControl('', {
validators: [Validators.required]
}),
employeeName: new FormControl('', {
validators: []
}),
employeeNo: new FormControl('', {
validators: []
})
}, { validators: this.timeUnitValidator }
);
return formRow;
}
timeUnitValidator(g: FormGroup) {
if (g.get('startTime').touched || g.get('endTime').touched) {
// console.log(g.get('startTime').value);
const hms1: string = g.get('startTime').value;
const a1 = hms1.split(':');
const seconds1 = (+a1[0]) * 60 * 60 + (+a1[1]) * 60 + (+a1[2]);
// console.log(seconds1);
// console.log(g.get('endTime').value);
const hms2: string = g.get('endTime').value;
const a2 = hms2.split(':');
const seconds2 = (+a2[0]) * 60 * 60 + (+a2[1]) * 60 + (+a2[2]);
// console.log(seconds2);
return seconds1 >= seconds2 ? { startTimeGreater: true } : null;
}
return null;
// console.log(g.get('endTime').value);
// return g.get('startTimee').value === g.get('endTime').value ? null : { mismatch: true };
}
updateRoutine() {
this.routinesToUpdate = Object.assign({}, this.routineForm.getRawValue());
console.log(this.routinesToUpdate);
this.hrService.updateRoutines(this.date, this.routinesToUpdate).subscribe((res) => {
this.getRoutines(this.date);
this.alertify.success('Updated successfully');
}, (res) => {
if (res.error.status === 400) {
this.alertify.error(res.error.message + ': error code ' + res.error.code);
} else {
this.alertify.error('Some error occured,Try again');
}
});
console.log(this.routinesToUpdate);
}
dateChange() {
// this.alertify.success(this.date);
this.getRoutines(this.date);
}
ClearRows() {
this.gettableRowArray.clear();
}
onDeleteRow(rowIndex: number): void {
this.gettableRowArray.removeAt(rowIndex);
}
}
|
import {
View,
Text,
TouchableOpacity,
ActivityIndicator,
FlatList,
} from 'react-native';
import PopularJobCard from './PopularJobCard';
import React, {useState} from 'react';
import useFetch from '../../hooks/useFetch';
export default function PopularJobs() {
const data = useFetch('popular');
const isLoading = false;
const error = '';
const [activeId, setActiveId] = useState('0');
const handleCardPress = (id: any) => {
setActiveId(id);
};
return (
<View className="mt-5">
<View className="flex-row items-center justify-between">
<Text className="text-lg text-black font-rubikSemiBold">
Popular jobs
</Text>
<TouchableOpacity>
<Text className="font-rubikLight">Show All</Text>
</TouchableOpacity>
</View>
<View>
{isLoading ? (
<ActivityIndicator className="mt-6" size="large" color="#F77658" />
) : error ? (
<Text className="mt-6 ml-5 text-primary font-rubikLight">
Something went wrong!
</Text>
) : (
<FlatList
data={data}
renderItem={({item}) => (
<PopularJobCard
handleCardPress={handleCardPress}
isActive={activeId === item.job_id}
{...item}
/>
)}
keyExtractor={item => item?.job_id}
contentContainerStyle={{columnGap: 10}}
horizontal
/>
)}
</View>
</View>
);
}
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:tv_series/presentation/bloc/top_rated/tv_series_top_rated_bloc.dart';
import 'package:tv_series/presentation/bloc/top_rated/tv_series_top_rated_event.dart';
import 'package:tv_series/presentation/bloc/top_rated/tv_series_top_rated_state.dart';
import 'package:tv_series/presentation/widgets/tv_series_card_list.dart';
class TopRatedTvSeriesPage extends StatefulWidget {
static const routeName = '/top-rated-tv';
const TopRatedTvSeriesPage({super.key});
@override
TopRatedTvSeriesPageState createState() => TopRatedTvSeriesPageState();
}
class TopRatedTvSeriesPageState extends State<TopRatedTvSeriesPage> {
@override
void initState() {
super.initState();
Future.microtask(() {
context.read<TvSeriesTopRatedBloc>().add(TvSeriesTopRatedEvent());
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Top Rated TV Series'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: BlocBuilder<TvSeriesTopRatedBloc, TvSeriesTopRatedState>(
builder: (context, state) {
if (state is TvSeriesTopRatedLoading) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (state is TvSeriesTopRatedHasData) {
return ListView.builder(
itemBuilder: (context, index) {
final tv = state.tvSeries[index];
return TvSeriesCard(tv, index: index);
},
itemCount: state.tvSeries.length,
);
} else if (state is TvSeriesTopRatedError) {
return Center(
child: Text(key: const Key('error-message'), state.message),
);
} else {
return Container();
}
},
),
),
);
}
}
|
import request from "supertest";
import { app } from "../../../../app";
import { Voucher } from "../../models/voucher";
import mongoose from "mongoose";
import { natsWrapper } from "../../../../nats-wrapper";
it("has a route handler listing t` /api/vouchers`for /${id}post requests", async () => {
const id = new mongoose.Types.ObjectId().toHexString();
const response = await request(app).put(`/api/vouchers/${id}`).send({});
expect(response.status).not.toEqual(404);
});
it("can only be accessed if the user is signed in", async () => {
const id = new mongoose.Types.ObjectId().toHexString();
await request(app).put(`/api/vouchers/${id}`).send({}).expect(401);
});
it("returns a status other than 401 if the user is signed in", async () => {
const id = new mongoose.Types.ObjectId().toHexString();
const response = await request(app)
.put(`/api/vouchers/${id}`)
.set("Cookie", global.signin())
.send({});
expect(response.status).not.toEqual(401);
});
it("returns an error if an invalid amount is provided", async () => {
const id = new mongoose.Types.ObjectId().toHexString();
await request(app)
.put(`/api/vouchers/${id}`)
.set("Cookie", global.signin())
.send({
expire_at: "2022-11-07",
})
.expect(400);
await request(app)
.put(`/api/vouchers/${id}`)
.set("Cookie", global.signin())
.send({
amount: 0,
expire_at: "2022-11-07",
})
.expect(400);
});
it("update a voucher with valid inputs", async () => {
const cookie = global.signin();
const voucherPoolResponse = await request(app)
.post("/api/voucher_pool")
.set("Cookie", cookie)
.send({ title: "new voucher" })
.expect(201);
const response = await request(app)
.post("/api/vouchers")
.set("Cookie", cookie)
.send({
amount: 12,
expire_at: "2022-11-07",
voucher_pool_id: voucherPoolResponse.body.id,
});
const amount = 10;
await request(app)
.put(`/api/vouchers/${response.body.id}`)
.set("Cookie", cookie)
.send({ amount, expire_at: "2022-11-07" })
.expect(201);
const pool = await Voucher.findById(response.body.id);
expect(pool!.amount).toEqual(amount);
});
it("publishes an event", async () => {
const cookie = global.signin();
const voucherPoolResponse = await request(app)
.post("/api/voucher_pool")
.set("Cookie", cookie)
.send({ title: "new voucher" })
.expect(201);
const response = await request(app)
.post("/api/vouchers")
.set("Cookie", cookie)
.send({
amount: 12,
expire_at: "2022-11-07",
voucher_pool_id: voucherPoolResponse.body.id,
});
const amount = 10;
await request(app)
.put(`/api/vouchers/${response.body.id}`)
.set("Cookie", cookie)
.send({ amount, expire_at: "2022-11-07" })
.expect(201);
expect(natsWrapper.client.publish).toHaveBeenCalledTimes(2);
});
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../node_modules/angular/angular.min.js"></script>
</head>
<body>
<!-- demo1 start-->
<!-- <div ng-app="">
<p>名字 : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
</div> -->
<!-- demo2 ng-init ng-bind -->
<!-- <div ng-app="" ng-init="firstName='John'">
<p>姓名为 <span ng-bind="firstName"></span></p>
</div> -->
<!-- demo3 data-ng-init for html5 -->
<!-- <div data-ng-app="" data-ng-init="firstName='John'">
<p>姓名为 <span data-ng-bind="firstName"></span></p>
</div> -->
<!-- demo4 expression -->
<!-- <div ng-app="">
<p>我的第一个表达式: {{ 5 + 5 }}</p>
</div> -->
<!-- demo5 expression and ng-bind -->
<!-- <div ng-app="" ng-init="quantity=1;cost=5">
<p>总价:{{quantity * cost}}</p>
</div> -->
<!-- <div ng-app="" ng-init="quantity=12;cost=5">
<p>总价:<span ng-bind="quantity*cost"></span></p>
</div>
-->
<!-- demo6 ng-repeat -->
<div ng-app="" ng-init="names=['JAne','linda','peter']">
<p>使用ng-repeat来循环数组</p>
<ul>
<li ng-repeat = "x in names">
{{x}}
</li>
</ul>
</div>
</body>
</html>
|
// REF https://github.com/ramda/ramda/blob/v0.29.0/source/internal/_curry2.js
import { Function } from "ts-toolbelt"
import _curry1 from "./_curry1"
export default function _curry2<F extends (...args: readonly any[]) => any>(fn: F): Function.Curry<F> {
// NOTE type ParamTypes = Parameters<F> conflicts with List type from ts-toolbelt
type ParamTypes = readonly any[]
return function f2(this: unknown, ...args: ParamTypes) {
switch (args.length) {
case 0:
return f2
case 1:
return _curry1(function (_b: ParamTypes[1]) {
return fn(args[0], _b)
})
default:
return fn(...args)
}
}
}
|
document.addEventListener('DOMContentLoaded', () => {
loadTrendingMusic();
loadCategories();
});
function loadTrendingMusic() {
const apiKey = 'AIzaSyAh0JDHZA3L_xgnMS4UKC5Iq7MLXPHwK0o';
const maxResults = 50; // Vous pouvez ajuster ce nombre, la limite maximale est généralement de 50
const requestURL = `https://www.googleapis.com/youtube/v3/videos?part=snippet&chart=mostPopular®ionCode=FR&videoCategoryId=10&maxResults=${maxResults}&key=${apiKey}`;
fetch(requestURL)
.then(response => response.json())
.then(data => {
displayTrendingMusic(data.items);
})
.catch(error => console.error('Erreur lors du chargement des musiques en tendance:', error));
}
function displayTrendingMusic(videos) {
const tendancesContainer = document.getElementById('tendances');
tendancesContainer.innerHTML = ''; // Effacer les contenus précédents
videos.forEach(video => {
const artistName = extractArtistName(video.snippet.title);
const videoElement = document.createElement('div');
videoElement.className = 'video';
videoElement.innerHTML = `
<img class="thumbnailimg" src="${video.snippet.thumbnails.high.url}" alt="Miniature">
<h3 class="titleh3">${artistName}</h3>
`;
tendancesContainer.appendChild(videoElement);
});
}
function extractArtistName(videoTitle) {
let artistName = videoTitle.split('-')[0].trim();
return artistName;
}
function loadCategories() {
const categories = ['Pop', 'Hip-Hop', 'Rap', 'Drill'];
const categoriesContainer = document.getElementById('accueil');
categories.forEach(category => {
const categoryElement = document.createElement('div');
categoryElement.className = 'category';
categoryElement.innerHTML = `
<h3>${category}</h3>
<div id="category-${category}" class="videos-container"></div>
`;
categoriesContainer.appendChild(categoryElement);
loadVideosForCategory(category);
});
}
function loadVideosForCategory(category) {
const apiKey = 'AIzaSyAh0JDHZA3L_xgnMS4UKC5Iq7MLXPHwK0o';
const maxResults = 10; // Limite pour chaque catégorie
const requestURL = `https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=${category}&maxResults=${maxResults}&key=${apiKey}`;
fetch(requestURL)
.then(response => response.json())
.then(data => {
displayVideosForCategory(data.items, category);
})
.catch(error => console.error(`Erreur lors du chargement des vidéos pour la catégorie ${category}:`, error));
}
function displayVideosForCategory(videos, category) {
const categoryVideosContainer = document.getElementById(`category-${category}`);
categoryVideosContainer.innerHTML = '';
videos.forEach(video => {
const videoElement = document.createElement('div');
videoElement.className = 'video';
videoElement.innerHTML = `
<img class="thumbnailimg" src="${video.snippet.thumbnails.high.url}" alt="Miniature">
`;
categoryVideosContainer.appendChild(videoElement);
});
}
|
package it.tndigitale.a4g.fascicolo.mediator.business.service.event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.event.TransactionalEventListener;
import it.tndigitale.a4g.fascicolo.mediator.business.service.client.AnagraficaPrivateClient;
import it.tndigitale.a4g.fascicolo.mediator.business.service.fascicolo.DotazioneTecnicaService;
import it.tndigitale.a4g.fascicolo.mediator.business.service.fascicolo.FascicoloValidazioneService;
import it.tndigitale.a4g.fascicolo.mediator.business.service.fascicolo.SincronizzazioneFascicoloService;
import it.tndigitale.a4g.fascicolo.mediator.business.service.fascicolo.ZootecniaService;
import it.tndigitale.a4g.fascicolo.mediator.dto.SchedaValidazioneFascicoloDto;
import it.tndigitale.a4g.fascicolo.mediator.dto.TipoDetenzioneEnum;
import it.tndigitale.a4g.framework.extension.DefaultNameExtension;
@Service
public class ValidazioneFascicoloListener {
private static final Logger log = LoggerFactory.getLogger(ValidazioneFascicoloListener.class);
@Autowired private FascicoloValidazioneService validazioneFascicoloService;
@Autowired private SincronizzazioneFascicoloService sincronizzazioneFascicoloService;
@Autowired private ZootecniaService zootecniaService;
@Autowired private DotazioneTecnicaService dotazioneTecnicaService;
@Autowired private AnagraficaPrivateClient anagraficaPrivateClient;
@Async(DefaultNameExtension.DEFAULT_SECURITY_THREAD_ASYNC)
@TransactionalEventListener
public void handleEvent(StartValidazioneFascicoloEvent event) {
SchedaValidazioneFascicoloDto eventData = event.getData();
String cuaa = eventData.getCodiceFiscale();
Integer idValidazione = eventData.getNextIdValidazione();
Integer result = 0;
if (eventData.getTipoDetenzione() == TipoDetenzioneEnum.DETENZIONE_IN_PROPRIO) {
result = validazioneFascicoloService.startValidazioneFascicoloAutonomoAsincrona(event, cuaa, idValidazione);
} else {
// MANDATO e' il tipo di detenzione di default
try {
anagraficaPrivateClient.notificaMailCaaSchedaValidazioneAccettataUsingPOST(cuaa);
} catch (Exception e) {
log.warn("Errore: {} - {}", e.getMessage(), e.getCause());
}
result = validazioneFascicoloService.startValidazioneFascicoloAsincrona(event, cuaa, idValidazione);
}
try {
if (result == 0) {
// invio evento fine validazione per avvio sincronizzazione AGS.
sincronizzazioneFascicoloService.invioEventoFineValidazione(eventData);
if (eventData.getTipoDetenzione() == TipoDetenzioneEnum.MANDATO) {
// chiamata a zootecniaClient per sincronizzazione AGS
zootecniaService.invioEventoFineValidazione(cuaa, idValidazione);
// chiamata a dotazioneTecnicaClient per validazione
dotazioneTecnicaService.invioEventoFineValidazione(cuaa, idValidazione);
// invio mail al CAA detentore del mandato: se errore non deve far fallire la transazione
anagraficaPrivateClient.notificaMailCaaRichiestaValidazioneAccettataUsingPOST(cuaa);
}
}
} catch (Exception e) {
log.warn("Errore: {} - {}", e.getMessage(), e.getCause());
}
}
}
|
import React from 'react';
import { Button as ChakraButton, forwardRef } from '@chakra-ui/react';
export interface ButtonProps {
children?: React.ReactNode;
dataCy?: string;
icon?: React.ReactElement;
key?: string;
shouldRender?: boolean;
isLoading?: boolean;
}
const Button = forwardRef(
({ children, dataCy, icon, ...props }: ButtonProps, ref) => {
return (
<ChakraButton data-cy={dataCy} leftIcon={icon} ref={ref} {...props}>
{/*
As long as we use React 17 and its types we need a fragment to wrap children,
otherwise we get this error:
children Type '{}' is not assignable to type 'ReactNode'. ts(2322)
Source: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18051
*/}
<> {children} </>
</ChakraButton>
);
}
);
export default Button;
|
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_svg_provider/flutter_svg_provider.dart';
class ScreenLayout extends StatelessWidget {
final Widget bodyContent;
final Widget? leftTopContent;
final Widget? rightTopContent;
final Widget? leftBottomContent;
final Widget? rightBottomContent;
final Widget? topCenterContant;
final AssetImage? background;
const ScreenLayout({
super.key,
required this.bodyContent,
this.leftTopContent,
this.rightTopContent,
this.leftBottomContent,
this.rightBottomContent,
this.topCenterContant,
this.background,
});
@override
Widget build(BuildContext context) {
return Stack(
fit: StackFit.passthrough,
children: [
Container(
height: double.infinity,
width: double.infinity,
decoration: const BoxDecoration(
// color: Color.fromARGB(0, 0, 0, 0)
// backgroundBlendMode: BlendMode.plus,
color: Colors.white
// image: DecorationImage(
// image: Svg('assets/images/background.svg'),
// repeat: ImageRepeat.repeat,
// fit: BoxFit.none)
// image: DecorationImage(
// image: AssetImage('assets/images/test-background.png'),
// repeat: ImageRepeat.noRepeat,
// fit: BoxFit.fitWidth)),
)),
Positioned(
top: 20,
left: 20,
child: leftTopContent != null ? leftTopContent! : Container()
// Icon(Icons.menu, color: Colors.white), // Пример элемента в углу
),
Positioned(
top: 20,
right: 20,
child: rightTopContent != null ? rightTopContent! : Container()),
Positioned(
bottom: 20,
left: 20,
child: leftBottomContent != null ? leftBottomContent! : Container(),
),
Positioned(
bottom: 20,
right: 20,
child: rightBottomContent != null ? rightBottomContent! : Container(),
),
Padding(
padding: const EdgeInsets.all(40.0),
child: bodyContent,
),
],
);
}
}
|
import React, { useEffect } from "react"
import jwt_decode from "jwt-decode"
import { useDispatch } from "react-redux"
import usuariosActions from "../../redux/actions/usuariosActions"
import toast from 'react-hot-toast';
import { useNavigate } from 'react-router-dom'
export default function GoogleSignUp() {
const dispatch = useDispatch();
const navigate = useNavigate()
async function handleCallBackResponse(response) {
let userObject = jwt_decode(response.credential);
const res = await dispatch(usuariosActions.registrarse({
nombre: userObject.given_name,
apellido: userObject.family_name,
email: userObject.email,
contraseña: userObject.sub,
imagen: userObject.picture,
from: "GOOGLE"
}))
if (res.data.success) {
toast.success(res.data.message)
navigate('/signin')
} else {
toast.error(res.data.message)
}
}
useEffect(() => {
/*global google*/
google.accounts.id.initialize({
client_id: '653969002854-i6ioa1k7vk4sj30bbcil1qjq2mg67l4u.apps.googleusercontent.com',
callback: handleCallBackResponse
});
google.accounts.id.renderButton(
document.getElementById("buttonDiv"),
{ type: "icon", size: "medium", shape: "square" }
)
});
return (
<div>
<div id="buttonDiv"></div>
</div>
)
}
|
package com.example.hcart;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.airbnb.lottie.LottieAnimationView;
import com.example.hcart.Personal_Note.AddNewTask;
import com.example.hcart.Personal_Note.DialogCloseListener;
import com.example.hcart.Personal_Note.RecyclerItemTouchHelper;
import com.example.hcart.Personal_Note.ToDoAdapter;
import com.example.hcart.Personal_Note.ToDoModel;
import com.example.hcart.Personal_Note.Utils.DataBaseHandler;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class PersonalTask extends AppCompatActivity implements DialogCloseListener {
TextView date, heading;
/*private boolean isFABOpen = false;
private boolean isfab3Open = false;*/
String message;
private DataBaseHandler db;
private List<ToDoModel> taskList;
private ToDoAdapter tasksAdapter;
EditText editText_create;
LottieAnimationView lottieAnimationView, plus, lottieAnimationView_empty;
Dialog dialog;
ImageView delete, eye, eye_cut;
String today;
ImageView back;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_task);
//getting task data
db = new DataBaseHandler(this);
db.openDatabase();
Window window = PersonalTask.this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(PersonalTask.this, R.color.white));
back = findViewById(R.id.back);
lottieAnimationView_empty = findViewById(R.id.animation_empty);
textView = findViewById(R.id.text_lottie);
RecyclerView tasksRecyclerView = findViewById(R.id.tasksRecyclerView);
tasksRecyclerView.setLayoutManager(new LinearLayoutManager(this));
tasksAdapter = new ToDoAdapter(taskList, db, PersonalTask.this);
tasksRecyclerView.setAdapter(tasksAdapter);
ItemTouchHelper itemTouchHelper = new
ItemTouchHelper(new RecyclerItemTouchHelper(tasksAdapter));
itemTouchHelper.attachToRecyclerView(tasksRecyclerView);
taskList = db.getAllTasks();
Collections.reverse(taskList);
tasksAdapter.setTasks(taskList);
if (taskList.size() != 0) {
lottieAnimationView_empty.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
}
back.setOnClickListener(v->{
finish();
});
//delete = findViewById(R.id.delete_task);
heading = findViewById(R.id.textView5);
EditText inputSearch = findViewById(R.id.inputSearch_my_task);
date = findViewById(R.id.current_date);
Date date_main = Calendar.getInstance().getTime();
@SuppressLint("SimpleDateFormat") DateFormat formatter = new SimpleDateFormat(" EEEE , dd MMMM yyyy , hh:mm aa");
today = formatter.format(date_main);
date.setText(today);
plus = findViewById(R.id.animation_plus_task);
plus.setOnClickListener(v -> {
AddNewTask.newInstance().show(getSupportFragmentManager(), AddNewTask.TAG);
lottieAnimationView_empty.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
});
//search
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
tasksAdapter.cancelTimer();
}
@Override
public void afterTextChanged(Editable s) {
if (inputSearch.getText().toString().equals("")) {
tasksAdapter.setTasks(taskList);
} else if (taskList.size() != 0) {
tasksAdapter.searchNotes(s.toString());
}
}
});
}
@SuppressLint("NotifyDataSetChanged")
@Override
public void handleDialogClose(DialogInterface dialog) {
taskList = db.getAllTasks();
Collections.reverse(taskList);
tasksAdapter.setTasks(taskList);
tasksAdapter.notifyDataSetChanged();
}
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import jsonschema
# JSON схема
schema = {
"type": "object",
"properties": {
"full_name": {"type": "string"},
"group_number": {"type": "string"},
"grades": {"type": "array", "items": {"type": "number"}},
},
"required": ["full_name", "group_number", "grades"],
}
def add_student(students):
full_name = input("Фамилия и инициалы? ")
group_number = input("Номер группы? ")
grades_str = input("Успеваемость (через пробел)? ")
grades = [float(grade) for grade in grades_str.split()]
student = {
"full_name": full_name,
"group_number": group_number,
"grades": grades,
}
students.append(student)
students.sort(key=lambda item: item.get("group_number", ""))
def list_students(students):
line = "+-{}-+-{}-+-{}-+".format("-" * 30, "-" * 15, "-" * 20)
print(line)
print(
"| {:^30} | {:^15} | {:^20} |".format("Ф.И.О.", "Номер группы", "Успеваемость")
)
print(line)
for student in students:
average_grade = sum(student.get("grades", 0)) / len(student.get("grades", 1))
if average_grade > 4.0:
print(
"| {:<30} | {:<15} | {:<20} |".format(
student.get("full_name", ""),
student.get("group_number", ""),
", ".join(map(str, student.get("grades", []))),
)
)
print(line)
def help_command():
print("Список команд:\n")
print("add - добавить студента;")
print("list - вывести список студентов;")
print("save - сохранить данные в файл JSON;")
print("load - загрузить данные из файла JSON;")
print("help - отобразить справку;")
print("exit - завершить работу с программой.")
def save_to_json(filepath, data):
with open(filepath, "w") as file:
json.dump(data, file, ensure_ascii=False, indent=4)
def load_from_json(filename):
with open(filename, "r") as file:
data = json.load(file)
return data
def validate_data(data):
try:
jsonschema.validate(instance=data, schema=schema)
return True
except jsonschema.exceptions.ValidationError as e:
print(f"Ошибка валидации: {e}")
return False
def save_command(students):
filename = input("Введите имя файла для сохранения данных: ")
save_to_json(filename, students)
print(f"Данные успешно сохранены в файл {filename}")
def load_command(students):
filename = input("Введите имя файла для загрузки данных: ")
loaded_data = load_from_json(filename)
if validate_data(loaded_data):
students.clear()
students.extend(loaded_data)
print(f"Данные успешно загружены из файла {filename}")
else:
print("Загруженные данные не прошли валидацию")
def main():
students = []
while True:
command = input(">>> ").lower()
if command == "exit":
break
elif command == "add":
add_student(students)
elif command == "list":
list_students(students)
elif command == "save":
save_command(students)
elif command == "load":
load_command(students)
elif command == "help":
help_command()
else:
print(f"Неизвестная команда {command}")
if __name__ == "__main__":
main()
|
import { resolve } from 'pathe';
import { useLogger, defineNuxtModule, isNuxt2, resolvePath } from '@nuxt/kit';
import { isValidURL, parse, constructURL, merge, download } from 'google-fonts-helper';
const name = "@nuxtjs/google-fonts";
const version = "3.0.0-0";
const logger = useLogger("nuxt:google-fonts");
const module = defineNuxtModule({
meta: {
name,
version,
configKey: "googleFonts"
},
defaults: {
families: {},
display: void 0,
subsets: [],
text: void 0,
prefetch: true,
preconnect: true,
preload: false,
useStylesheet: false,
download: true,
base64: false,
inject: true,
overwriting: false,
outputDir: "node_modules/.cache/nuxt-google-fonts",
stylePath: "css/nuxt-google-fonts.css",
fontsDir: "fonts",
fontsPath: "../fonts"
},
async setup(options, nuxt) {
if (options.display === void 0 && !options.preload) {
options.display = "swap";
}
const fontsParsed = [];
if (isNuxt2()) {
nuxt.options.head = nuxt.options.head || {};
nuxt.options.head.link = nuxt.options.head.link || [];
fontsParsed.push(...nuxt.options.head.link.filter((link) => isValidURL(link.href)).map((link) => parse(link.href)));
} else {
nuxt.options.app.head.link = nuxt.options.app.head.link || [];
fontsParsed.push(...nuxt.options.app.head.link.filter((link) => isValidURL(link.href)).map((link) => parse(link.href)));
}
const url = constructURL(merge(options, ...fontsParsed));
if (!url) {
logger.warn("No provided fonts.");
return;
}
if (isNuxt2()) {
nuxt.options.head = nuxt.options.head || {};
nuxt.options.head.link = nuxt.options.head.link || [];
nuxt.options.head.link = nuxt.options.head.link.filter((link) => !isValidURL(link.href));
} else {
nuxt.options.app.head.link = nuxt.options.app.head.link || [];
nuxt.options.app.head.link = nuxt.options.app.head.link.filter((link) => !isValidURL(link.href));
}
if (options.download) {
const outputDir = await resolvePath(options.outputDir);
try {
const downloader = download(url, {
base64: options.base64,
overwriting: options.overwriting,
outputDir,
stylePath: options.stylePath,
fontsDir: options.fontsDir,
fontsPath: options.fontsPath
});
await downloader.execute();
if (options.inject) {
nuxt.options.css.push(resolve(outputDir, options.stylePath));
}
nuxt.options.nitro = nuxt.options.nitro || {};
nuxt.options.nitro.publicAssets = nuxt.options.nitro.publicAssets || [];
nuxt.options.nitro.publicAssets.push({ dir: outputDir });
} catch (e) {
logger.error(e);
}
return;
}
if (isNuxt2()) {
nuxt.options.head = nuxt.options.head || {};
nuxt.options.head.link = nuxt.options.head.link || [];
nuxt.options.head.script = nuxt.options.head.script || [];
nuxt.options.head.noscript = nuxt.options.head.noscript || [];
nuxt.options.head.__dangerouslyDisableSanitizersByTagID = nuxt.options.head.__dangerouslyDisableSanitizersByTagID || {};
if (options.prefetch) {
nuxt.options.head.link.push({
hid: "gf-prefetch",
rel: "dns-prefetch",
href: "https://fonts.gstatic.com/"
});
}
if (options.preconnect) {
nuxt.options.head.link.push({
hid: "gf-preconnect",
rel: "preconnect",
href: "https://fonts.gstatic.com/",
crossorigin: "anonymous"
}, {
hid: "gf-origin-preconnect",
rel: "preconnect",
href: "https://fonts.googleapis.com/"
});
}
if (options.preload) {
nuxt.options.head.link.push({
hid: "gf-preload",
rel: "preload",
as: "style",
href: url
});
}
if (options.useStylesheet) {
nuxt.options.head.link.push({
hid: "gf-style",
rel: "stylesheet",
href: url
});
return;
}
nuxt.options.head.script.push({
hid: "gf-script",
innerHTML: `(function(){var l=document.createElement('link');l.rel="stylesheet";l.href="${url}";document.querySelector("head").appendChild(l);})();`
});
nuxt.options.head.noscript.push({
hid: "gf-noscript",
innerHTML: `<link rel="stylesheet" href="${url}">`
});
nuxt.options.head.__dangerouslyDisableSanitizersByTagID["gf-script"] = ["innerHTML"];
nuxt.options.head.__dangerouslyDisableSanitizersByTagID["gf-noscript"] = ["innerHTML"];
return;
}
nuxt.options.app.head.link = nuxt.options.app.head.link || [];
nuxt.options.app.head.script = nuxt.options.app.head.script || [];
if (options.prefetch) {
nuxt.options.app.head.link.push({
rel: "dns-prefetch",
href: "https://fonts.gstatic.com/"
});
}
if (options.preconnect) {
nuxt.options.app.head.link.push({
rel: "preconnect",
href: "https://fonts.gstatic.com/",
crossorigin: "anonymous"
}, {
rel: "preconnect",
href: "https://fonts.googleapis.com/"
});
}
if (options.preload) {
nuxt.options.app.head.link.push({
rel: "preload",
as: "style",
href: url
});
}
if (options.useStylesheet) {
nuxt.options.app.head.link.push({
rel: "stylesheet",
href: url
});
return;
}
nuxt.options.app.head.script.unshift({
"data-hid": "gf-script",
children: `(function(){
var h=document.querySelector("head");
var m=h.querySelector('meta[name="head:count"]');
if(m){m.setAttribute('content',Number(m.getAttribute('content'))+1);}
else{m=document.createElement('meta');m.setAttribute('name','head:count');m.setAttribute('content','1');h.append(m);}
var l=document.createElement('link');l.rel='stylesheet';l.href='${url}';h.appendChild(l);
})();`
});
}
});
export { module as default };
|
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <stdlib.h>
#include <string.h>
using namespace std;
class DisjointSet
{
vector<int> rank, parent,size;
public:
DisjointSet(int n)
{
rank.resize(n + 1, 0);
size.resize(n + 1, 0);
parent.resize(n + 1);
for (int i = 0; i <= n; i++)
{
parent[i] = i;
}
}
int findUPar(int node)
{
if (node == parent[node])
return node;
return parent[node] = findUPar(parent[node]);
}
void unionByRank(int u, int v)
{
int ulp_u = findUPar(u);
int ulp_v = findUPar(v);
if (ulp_u == ulp_v)
return;
if (rank[ulp_u] < rank[ulp_v])
{
parent[ulp_u] = ulp_v;
}
else if (rank[ulp_v] < rank[ulp_u])
{
parent[ulp_v] = ulp_u;
}
else
{
parent[ulp_v] = ulp_u;
rank[ulp_u]++;
}
}
void unionBySize(int u, int v) {
int ulp_u = findUPar(u);
int ulp_v = findUPar(v);
if (ulp_u == ulp_v) return;
if (size[ulp_u] < size[ulp_v]) {
parent[ulp_u] = ulp_v;
size[ulp_v] += size[ulp_u];
}
else {
parent[ulp_v] = ulp_u;
size[ulp_u] += size[ulp_v];
}
}
};
int main()
{
DisjointSet ds(7);
ds.unionByRank(1, 2);
ds.unionByRank(2, 3);
ds.unionByRank(4, 5);
ds.unionByRank(6, 7);
ds.unionByRank(5, 6);
// if 3 and 7 same or not
if (ds.findUPar(3) == ds.findUPar(7))
{
cout << "Same\n";
}
else
cout << "Not same\n";
ds.unionByRank(3, 7);
if (ds.findUPar(3) == ds.findUPar(7))
{
cout << "Same\n";
}
else
cout << "Not same\n";
return 0;
}
|
package dev.sourav.currencyconverter.ui
import com.google.common.truth.Truth.assertThat
import dev.sourav.currencyconverter.entity.ConversionRate
import dev.sourav.currencyconverter.entity.Currency
import dev.sourav.currencyconverter.models.ConvertedValue
import dev.sourav.currencyconverter.repo.CurrencyConvertRepo
import dev.sourav.currencyconverter.repo.MockRepo
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
/**
* Created by Sourav
* On 3/26/2023 8:47 PM
* For Currency Converter
*/
class MainActivityVMTest {
private lateinit var viewModel:MainActivityVM
private lateinit var repo : CurrencyConvertRepo
private val exchangeRateList = listOf(
ConversionRate("BDT", 0.8),
ConversionRate("AUD", 0.7),
ConversionRate("CNY", 11.0)
)
private val currencyList = listOf(
Currency("BDT", "Bangladeshi TAKA"),
Currency("AUD", "Australian Dollar"),
Currency("CNY", "Chinese Yun")
)
@Before
fun setup(){
repo = MockRepo()
viewModel = MainActivityVM(repo)
}
@Test
fun `when conversion rate is empty, should return empty list`() = runBlocking {
repo.insertAllExchangeRate(listOf())
val expectedList = listOf<ConvertedValue>()
val actualList = viewModel.getConvertedList(100.0, "USD")
assertThat(expectedList).isEqualTo(actualList)
}
@Test
fun `when conversion rate is not empty, should return converted list sorted by currency code`() = runBlocking {
repo.insertAllExchangeRate(exchangeRateList)
repo.insertAllCurrencies(currencyList)
val res = viewModel.getConvertedList(100.0, "BDT")
val expectedList = listOf(
ConvertedValue((0.7* (100.0/0.8)), "AUD", "Australian Dollar"),
ConvertedValue((11.0* (100.0/0.8)), "CNY", "Chinese Yun"),
ConvertedValue((100.0/0.8), "USD", "United State Dollar")
)
assertThat(res).isEqualTo(expectedList.sortedBy { it.currencyCode })
}
@Test
fun `when input amount is zero, should return empty list`() = runBlocking {
repo.insertAllExchangeRate(exchangeRateList)
repo.insertAllCurrencies(currencyList)
val res = viewModel.getConvertedList(0.0, "BDT")
assertThat(res).isEmpty()
}
@Test
fun `when input amount is not zero but currency code is empty, should return empty list`() = runBlocking {
repo.insertAllExchangeRate(exchangeRateList)
repo.insertAllCurrencies(currencyList)
val res = viewModel.getConvertedList(0.0, "")
assertThat(res).isEmpty()
}
@Test
fun `when currency list is empty, should return empty list`() = runBlocking {
repo.insertAllExchangeRate(exchangeRateList)
val res = viewModel.getConvertedList(0.0, "BDT")
assertThat(res).isEmpty()
}
@Test
fun `when getConversionRate is called, should return a list` () = runBlocking {
viewModel.executeConversionRateFetch()
val result = repo.getConversionRate("EUR")
assertThat(result).isNotNull()
}
@Test
fun `when lastupdated is less than 30 mins ago, should return a false` () = runBlocking {
val res = viewModel.shouldFetchFromAPI(System.currentTimeMillis() - 21 * 60000)
assertThat(res).isFalse()
}
@Test
fun `when lastupdated is more than 30 mins ago, should return a true` () = runBlocking {
val res = viewModel.shouldFetchFromAPI(System.currentTimeMillis() - 33 * 60000)
assertThat(res).isTrue()
}
}
|
import 'dart:async';
import 'dart:developer' as developer;
import 'package:connectivity_plus/connectivity_plus.dart';
import 'connection_service.dart';
class ConnectionPlusService implements ConnectionService {
late StreamSubscription<List<ConnectivityResult>> _connectivitySubscription;
final Connectivity _connectivity = Connectivity();
bool _connected = true;
@override
void listenConectivity({
required Function({required bool connected}) callback,
}) {
final _connectivity = Connectivity();
_connectivitySubscription =
_connectivity.onConnectivityChanged.listen((event) {
final auxConnected = _isConnected(connectivityResult: event);
if (_connected != auxConnected) {
_connected = auxConnected;
developer.log('CONNECTION STATUS HAS CHANGED $_connected');
callback(connected: _connected);
}
});
}
bool _isConnected({required List<ConnectivityResult> connectivityResult}) {
return connectivityResult.contains(ConnectivityResult.wifi) ||
connectivityResult.contains(ConnectivityResult.mobile);
}
@override
void dispose() {
_connectivitySubscription.cancel();
}
@override
Future<bool> returnCurrentStatus() async {
return _connected = _isConnected(
connectivityResult: await _connectivity.checkConnectivity(),
);
}
}
|
<!-- The $emit function allows this input to be compatible with v-model -->
<template>
<textarea :name="getName"
:id="getID"
v-model="value"
@input="$emit('input', $event.target.value)">
</textarea>
</template>
<script>
export default {
name: 'text-area',
inject: {
attr: {},
patchMode: { default: "" },
editMode: { default: "" },
form: { default: "" },
nested: { default: ""} //setting it as "" as default because it may not be present in non-nested environment
},
props: {
for: {
type: String
},
value: {
type: String,
default: ""
}
},
data: function(){
return {
index: ""
}
},
created: function(){
var array = []
this.$parent.$children.filter(function(x){
// do not accept label-tag so as to compute index correctly
if(x._uid != undefined && (x.$vnode.componentOptions.tag != "label-tag")){
array.push(x._uid)
}
})
this.index = array.indexOf(this._uid)
},
computed: {
getValue: function(){
if (this.patchMode.isPatch == true || this.editMode.isEdit == true) {
return this.form.withData[this.for]
} else {
return this.value
}
},
// If this component is nested in fields-for, it will display a different ID e.g. show[seasons_attributes][0][name]
// If it is not nested, the ID will be attribute[name] e.g. show[name]
getName: function() {
if (this.nested != "") {
return this.attr + "[" + this.nested + "_attributes]" + "[" + this.index + "][" + this.for + "]"
} else {
return this.attr + "[" + this.for + "]"
}
},
// If this component is nested in fields-for, it will display a different ID e.g. show_seasons_attributes_0_name
// If it is not nested, the ID will be attribute_name e.g. show_name
getID: function() {
if (this.nested != "") {
return this.attr + "_" + this.nested + "_attributes" + "_" + this.index + "_" + this.for
} else {
return this.attr + "_" + this.for;
}
}
}
}
</script>
|
import numpy as np
class SimplifiedBaggingRegressor:
def __init__(self, num_bags, oob=False):
self.num_bags = num_bags
self.oob = oob
def _generate_splits(self, data: np.ndarray):
'''
Generate indices for every bag and store in self.indices_list list
'''
self.indices_list = []
data_length = len(data)
for bag in range(self.num_bags):
# Your Code Here
self.indices_list.append(np.random.randint(0, data_length, data_length))
def fit(self, model_constructor, data, target):
'''
Fit model on every bag.
Model constructor with no parameters (and with no ()) is passed to this function.
example:
bagging_regressor = SimplifiedBaggingRegressor(num_bags=10, oob=True)
bagging_regressor.fit(LinearRegression, X, y)
'''
self.data = None
self.target = None
self._generate_splits(data)
assert len(set(list(map(len, self.indices_list)))) == 1, 'All bags should be of the same length!'
assert list(map(len, self.indices_list))[0] == len(data), 'All bags should contain `len(data)` number of elements!'
self.models_list = []
for bag in range(self.num_bags):
model = model_constructor()
data_bag, target_bag = data[self.indices_list[bag]], target[self.indices_list[bag]] # Your Code Here
self.models_list.append(model.fit(data_bag, target_bag)) # store fitted models here
if self.oob:
self.data = data
self.target = target
def predict(self, data):
'''
Get average prediction for every object from passed dataset
'''
# Your code here
preds = []
for model in self.models_list:
preds.append(model.predict(data))
preds = np.array(preds)
return preds.mean(axis=0)
def _get_oob_predictions_from_every_model(self):
'''
Generates list of lists, where list i contains predictions for self.data[i] object
from all models, which have not seen this object during training phase
'''
list_of_predictions_lists = [[] for _ in range(len(self.data))]
# Your Code Here
for i in range(len(self.data)):
i_preds = []
for j, bag in enumerate(self.indices_list):
if i not in bag:
i_preds.append(self.models_list[j].predict(self.data[i].reshape(1, -1)))
list_of_predictions_lists[i] = i_preds
self.list_of_predictions_lists = np.array(list_of_predictions_lists, dtype=object)
def _get_averaged_oob_predictions(self):
'''
Compute average prediction for every object from training set.
If object has been used in all bags on training phase, return None instead of prediction
'''
self._get_oob_predictions_from_every_model()
oob_predictions = []
self.valid_indexes = []
for i, preds in enumerate(self.list_of_predictions_lists):
if len(preds) == self.num_bags or len(preds) == 0:
oob_predictions.append(np.nan)
else:
oob_predictions.append(np.mean(preds))
self.valid_indexes.append(i)
self.oob_predictions = np.array(oob_predictions, dtype=object) # Your Code Here
#self.oob_predictions = oob_predictions # Your Code Here
def OOB_score(self):
'''
Compute mean square error for all objects, which have at least one prediction
'''
self._get_averaged_oob_predictions()
oobs = self.oob_predictions[self.valid_indexes]
targets = self.target[self.valid_indexes]
scores = (oobs - targets) ** 2
return np.mean(scores) # Your Code Here
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const DoublyLinkedList_1 = __importDefault(require("../LinkedLists/DoublyLinkedList"));
class Stack {
constructor(maxSize = Infinity) {
this.stack = new DoublyLinkedList_1.default();
this.maxSize = maxSize;
this.size = 0;
}
pop() {
if (!this.isEmpty()) {
const value = this.stack.removeHead();
this.size--;
return value;
}
else {
console.log('Stack is empty');
}
}
push(data) {
if (this.hasRoom()) {
this.size++;
this.stack.addToHead(data);
}
else {
throw new Error('Stack is full');
}
}
peek() {
var _a;
if (!this.isEmpty()) {
return (_a = this.stack.head) === null || _a === void 0 ? void 0 : _a.data;
}
else {
return null;
}
}
isEmpty() {
if (this.size === 0) {
return true;
}
return false;
}
hasRoom() {
if (this.size < this.maxSize) {
return true;
}
return false;
}
printStack() {
throw new Error("Method not implemented.");
}
}
exports.default = Stack;
|
/**
* Filename: NotFoundExceptionHandler.java
*
* Description: Implementation of the NotFoundExceptionHandler class.
*
* Revision: 22 de abr. de 2024
*
* Author: Erik Freire Vergani
* EMail: [email protected]
*
*/
package com.univates.api.handlers;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.univates.api.exception.NotFoundException;
import com.univates.api.records.response.ErrorResponseRecord;
/**
* @author ev
*/
@ControllerAdvice
public class NotFoundExceptionHandler
{
@ExceptionHandler( NotFoundException.class )
@ResponseBody
@ResponseStatus( HttpStatus.NOT_FOUND )
public ErrorResponseRecord handler( NotFoundException ex )
{
return new ErrorResponseRecord( ex.getMessage() );
}
}
|
import { Button, Flex, Link, Tag, Text } from "@chakra-ui/react";
import NextLink from "next/link";
import Image from "next/image";
import { db } from "../../api/firebaseconfig";
import { arrayRemove, arrayUnion } from "firebase/firestore";
import { useRouter } from "next/router";
const ProdRevComponent = (
id,
idts,
website,
img,
title,
phrase,
desphrase,
tags,
comments,
likes,
liked,
mine
) => {
const deleteIt = () => {
if (
window.confirm(
"Do you really want to delete " + title + " update review?"
)
) {
db.collection("startups")
.doc(idts)
.update({ updateReviewId: arrayRemove(id) });
db.collection("users")
.doc(localStorage.getItem("id"))
.update({ updateReviewStartupId: arrayRemove(id) });
db.collection("updateReview").doc(id).delete();
setTimeout(() => {
window.location.reload();
}, 400);
}
};
const addLikes = () => {
if (likes.includes(localStorage.getItem("id"))) {
db.collection("updateReview")
.doc(id)
.update({ likes: arrayRemove(localStorage.getItem("id")) });
} else {
db.collection("updateReview")
.doc(id)
.update({ likes: arrayUnion(localStorage.getItem("id")) });
}
};
if (website) {
return (
<Flex
direction={"row"}
width={"90%"}
alignItems={"center"}
//backgroundColor={mine ? "#dcdcdc" : "#fff"}
backgroundColor={"#fff"}
boxShadow={"0 2px 5px rgba(0, 0, 0, 0.5)"}
_hover={{
//boxShadow: "0 5px 5px rgba(100,100,100,0.9)",
opacity: 0.8,
}}
justifyContent={"space-between"}
padding={2}
//borderRadius={5}
>
<Flex
direction={"row"}
alignItems={"center"}
justifyContent={"center"}
gap={3}
>
<img src={img} alt={title} width={70} height={70} />
<Flex
direction={"column"}
alignItems={"left"}
justifyContent={"center"}
gap={0.75}
>
<Flex alignItems={"center"} direction={"row"}>
<Link
color={"black"}
fontWeight={700}
fontSize={{ base: "11pt", md: "13pt", lg: "15pt" }}
>
<NextLink href={website} passHref target={"_blank"}>
{title}
</NextLink>
</Link>
{mine ? (
<Button onClick={deleteIt} colorScheme={"transparent"}>
<Image
src={"/assets/trash.png"}
alt="Delete"
width={25}
height={25}
/>
</Button>
) : null}
</Flex>
<Text
color={"black"}
fontSize={{ base: "9pt", md: "11pt", lg: "13pt" }}
fontWeight={700}
>
{phrase}
</Text>
<Text
maxWidth={"40vw"}
color={"#808080"}
fontSize={{ base: "6pt", md: "8pt", lg: "10pt" }}
>
{desphrase}
</Text>
<Flex direction={"row"} alignItems={"center"} gap={4}>
<Link
colorScheme={"transparent"}
alignItems={"left"}
gap={1}
display={"flex"}
flexDirection={"row"}
color={"black"}
>
<img
style={{ filter: "brightness(0)" }}
src={"/assets/message.png"}
alt="Message"
width={25}
height={25}
/>
<Text color={"black"} fontWeight={900}>
{Object.keys(comments).length === 0 ? 0 : comments.length}
</Text>
</Link>
<Flex
direction={"row"}
alignItems={"center"}
justifyContent={"center"}
gap={2}
>
{tags.map(function (tag, index) {
console.log("Tag " + tag);
return (
<Tag
key={index}
colorScheme={"green"}
fontSize={{
base: "4pt",
md: "7pt",
lg: "10pt",
}}
size={"lg"}
>
{String(tag)}
</Tag>
);
})}
</Flex>
</Flex>
</Flex>
</Flex>
<Button
display={"flex"}
flexDirection={"column"}
alignItems={"center"}
justifyContent={"center"}
border={liked ? "1px solid #1F90FF" : "1px solid black"}
borderRadius={2}
colorScheme={"transparent"}
height={"100%"}
backgroundColor={"transparent"}
onClick={addLikes}
paddingBottom={3}
paddingTop={3}
>
<img
src={liked ? "/assets/blueup.png" : "/assets/up.png"}
alt="Gloppa up"
width={40}
height={40}
/>
<Text color={"#000"} fontSize={"17pt"}>
{Object.keys(likes).length === 0 ? 0 : likes.length}
</Text>
</Button>
</Flex>
);
}
};
export default ProdRevComponent;
|
class LocalProduct {
final int id;
final String title;
final double price;
final String image;
final double rating;
final List<String> categories;
LocalProduct({
required this.id,
required this.title,
required this.price,
required this.image,
required this.rating,
required this.categories,
});
factory LocalProduct.fromJson(Map<String, dynamic> json) => LocalProduct(
id: json["id"],
title: json["title"],
price: json["price"],
image: json["image"],
rating: json["rating"]?.toDouble(),
categories: List<String>.from(json["categories"].map((x) => x)),
);
}
|
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AlertController, ToastController, LoadingController } from '@ionic/angular';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage {
constructor(
private authService: AuthService,
private alertCtrl: AlertController,
private loadingCtrl: LoadingController,
private router: Router
) { }
loginForm = new FormGroup({
email: new FormControl('', [
Validators.required,
Validators.email,
]),
password: new FormControl('', [
Validators.required,
Validators.minLength(5),
]),
});
async login(){
const loading = await this.loadingCtrl.create({ message: 'Logging in ...' });
await loading.present();
this.authService.login(this.loginForm.value).subscribe(
async token => {
localStorage.setItem('token', token);
loading.dismiss();
this.router.navigateByUrl('/home');
},
async () => {
const alert = await this.alertCtrl.create({ message: 'Login Failed', buttons: ['OK'] });
await alert.present();
loading.dismiss();
}
);
}
}
|
# Tokenized_Education
For a better reading experiance, please visit:
https://docs.google.com/document/d/1weRbGk8cDWu8TAzEWvrG0bCn-D3_0hdlVziJ4s3A9qY/edit?usp=sharing
Decentralized Learning
A White Paper on Tokenizing Education & DAO Governance:
Decentralized Learning is a meritocratic, incentive driven education market, enabled by the Ethereum Virtual Machine (EVM) to facilitate a vibrant education ecosystem where knowledge is rewarded, community governs, and education is democratized.
1. The Problem: Traditional education systems face numerous challenges:
Centralized Control:
One-size-fits-all curriculum: Traditional education systems often adopt a standardized curriculum regardless of individual learning styles, interests, and aptitudes. This can lead to boredom, disengagement, and a failure to cater to diverse learners.
Limited flexibility: Rigid schedules, fixed learning paths, and inflexible course structures leave little room for personalized learning journeys or adapting to individual needs and goals.
Hierarchical structures: Learners have limited agency and participation in shaping their educational experience.Decisions and curriculum development often lie solely with institutions and educators, leaving learners feeling disconnected and lacking ownership.
Inefficient Rewards:
Extrinsic motivation: Traditional systems often rely on grades, tests, and external validation as primary motivators. This can create unhealthy pressure, short-term thinking, and a focus on rote memorization instead of genuine curiosity and lifelong learning.
Financial hurdles: Tuition fees, textbook costs, and other financial barriers restrict access to quality education,disproportionately impacting marginalized communities and individuals from lower socioeconomic backgrounds.
Misaligned incentives: The current system's reward structure (grades, DEI, degrees) may not directly translate into skills and knowledge relevant to actual career paths or personal goals.
Additional Points to Consider:
Focus on rote learning and standardized testing: Traditional education often prioritizes memorization and test-taking skills over critical thinking, creativity, and problem-solving abilities. This can stifle innovation and limit the development of essential skills for the 21st century.
Limited access: Costly tuition and geographical barriers restrict educational opportunities.
Lack of innovation and adaptability: Traditional educational institutions can be slow to adapt to changing technologies, industry demands, and evolving needs of the workforce. This can leave graduates unprepared for the real world and limit their future opportunities.
Environmental impact: The resource-intensive nature of traditional education, including physical buildings,transportation, and paper-based materials, contributes to environmental concerns. A decentralized learning platform could potentially offer a more sustainable model.
Students: Struggling to stay motivated or find relevant learning materials within the rigid confines of traditional education?
Educators: Feeling limited by standardized curriculum and a lack of student engagement in your traditional classroom setting?
District: Frustrated with the cost and inefficiency of traditional employee training programs?
2. Our Solution: Decentralized Learning
Tokenized Incentives: Learners earn tokens for completing modules, engaging in discussions, creating content, and contributing to governance.
Closed-Loop Economy: tokens unlock platform features, purchase learning materials, and participate in governance decisions.
DAO Governance: A Decentralized Autonomous Organization (DAO) empowers token holders to shape the platform's future through proposals and voting.
EVM Smart Contracts: Securely manage token issuance, rewards distribution, and governance processes on the Ethereum (Or Layer 2) blockchain.
Decentralized Learning isn't just about shiny tokens and fancy tech; it's about harnessing the power of token-based game theory to create a self-organizing, community-driven, and intrinsically motivated learning revolution.
It's the future of education, where knowledge is currency, collaboration is king, and the game you play is the game of lifelong learning. Envision a self-organizing system where immutable knowledge acquisition is intrinsically woven with the thrill of discovery and greed.
Here's how Decentralized Learning harnesses the power of token based game theory to supercharge learning:
1. Tokens and Competition: Complete a module? Token boost! Spark vibrant discussions? Token shower! Create top-notch content? Token jackpot! This isn't just gamification; it's the gamification of knowledge, where every action fuels your curiosity and rewards your progress.
2. Network Effects on Steroids: Forget zero-sum competition. Decentralized Learning thrives on positive-sum network effects. Your learning success isn't just yours; it strengthens the entire community. Contributing content, sparking discussions, and mentoring others earn you tokens, but they also amplify everyone's learning potential. Collaboration to build a vast, curated library of knowledge, fueled by shared rewards and collective progress.
3. Collaboration, Amplified: Token based game theory isn't just about individual gains; it's about building a thriving community. Decentralized Learning empowers token holders through a DAO (Decentralized Autonomous Organization), giving them the voice to shape the platform's future. Propose new features, vote on curriculum development, and direct the ecosystem's growth. This collaborative governance fosters a sense of ownership and responsibility, transforming learners from passive consumers to active architects of their own education.
4. Dynamic Equilibrium of Knowledge: Picture a perfectly balanced ecosystem where knowledge flourishes. Decentralized Learning uses game theory to reward valuable contributions. Token rewards are weighted towards high-quality content, ensuring the platform becomes a curated library, not a dumping ground. This self-regulating system continuously evolves, rewarding the best and weeding out the noise, resulting in a constantly growing reservoir of reliable and relevant learning resources.
5. Owning tokens in the platform isn't just about rewards: it's about having a vested interest in its success. Token holders are more than learners; they're investors in their own education. This effect incentivizes responsible participation, thoughtful governance decisions, and a collective commitment to building a valuable and sustainable learning ecosystem for all.
Students: Earn tokens for learning, unlock exclusive content, and shape the platform's future through DAO governance.
Educators: Create and share interactive learning materials, engage with students globally, and earn rewards for your contributions.
District: Design customized training programs, track employee progress, and incentivize skill development in a cost-effective way.
3. Platform Architecture:
Smart Contracts: Manage token minting, distribution, vesting, and burning. Facilitate reward mechanisms and DAO voting.
DApp: Interactive front-end providing personalized learning paths, gamified experiences, and social features.
Backend Services: Manage user accounts, content delivery, and integration with blockchain smart contracts.
Database: Securely store user data, learning materials, and platform activity logs.
Smart Contracts:
Token Management: This is the brain of the operation, controlling minting, distribution, vesting, and burning of tokens. Imagine it as a secure vault, ensuring fair and transparent token issuance and preventing manipulation.
Dynamic Reward Engine: This is where the magic happens! The engine monitors user activity, tracks contributions (module completion, discussions, content creation, governance participation), and automatically distributes earned DL tokens. Every step, big or small, gets rewarded, fueling motivation and engagement.
DAO Governance: Smart contracts facilitate the DAO voting process. Proposals for platform development, feature implementation, and resource allocation are submitted, debated, and voted on by token holders. This empowers the community to actively shape the platform's future.
Chainlink Data Feeds: Integrate Chainlink Data Feeds to bring real-world data and events directly into the learning experience. Imagine courses adapting to current market trends, skill assessments based on job market demands, and dynamic career pathways informed by real-time industry data. This ensures your educational content is constantly relevant and future-proof.
Decentralized Randomness: Utilize Chainlink VRF (Verifiable Random Function) to introduce an element of fairness and unpredictability into your gamified experiences. Imagine randomly generated quests, surprise rewards, and dynamic challenges that keep users engaged and coming back for more.
Dapp:
Personalized Learning Pathways: Forget one-size-fits-all! The DApp utilizes sophisticated algorithms to analyze user interests, skills, and goals, crafting personalized learning journeys. Imagine navigating a dynamic map, uncovering knowledge paths tailored just for you.
Gamified Experiences: Learning shouldn't feel like a chore. The DApp integrates gamification elements like badges, leaderboards, and challenges, transforming knowledge acquisition into an exciting adventure. Earn XP, climb the ranks, and unlock exclusive rewards as you master new skills.
Social Hub: This isn't just a learning platform; it's a thriving community! The DApp boasts interactive forums, discussion boards, and collaboration tools, fostering knowledge sharing, peer-to-peer learning, and a sense of belonging.
Backend Services:
User Management: This handles user accounts, onboarding, authentication, and profile management. Think of it as a secure concierge, ensuring a smooth and seamless user experience.
Content Delivery Network (CDN): Access to learning materials should be effortless and global. The CDN ensures fast and reliable delivery of courses, videos, and other resources, regardless of location.
CCIP (Decentralized Oracle Network): This vital component seamlessly connects the DApp on the Ethereum blockchain, and allows it to become interoperable with other blockchains, and allows liquidity from any Traditional Finance Institution on the SWIFT network. This facilitates secure communication and data exchange between smart contracts and the front-end interface.
Decentralized Storage: Consider integrating decentralized storage solutions like IPFS (InterPlanetary File System) for storing learning materials. This ensures content remains accessible even if individual nodes go offline,increasing platform resilience and censorship resistance.
On-chain Reputation System: Utilize Chainlink Automation to build a decentralized reputation system for users and content creators. Imagine verified profiles, gamified trust scores, and community-driven feedback mechanisms that promote transparency and incentivize high-quality contributions.
Database:
Secure Vault: The heart of Decentralized Learning stores user data, learning materials, platform activity logs, and all things essential for maintaining transparency and functionality. Imagine a fortress of information, protected by cutting-edge cryptography and security protocols.
Audit Trail: Every action on the platform is meticulously recorded, creating an immutable audit trail for governance decisions, reward distribution, and ensuring fairness and accountability.
For students: Personalized learning pathways, gamified experiences, and a thriving social hub to connect with fellow learners.
For educators: Powerful content creation tools, access to real-world data feeds, and decentralized storage for their valuable resources.
For District: Scalable architecture to accommodate large training groups, secure user management, and integration with existing systems.
4. Tokenomics:
Total Supply: Fixed (possibly deflationary TBD) supply to maintain token value and incentivize long-term participation.
Token Distribution: Fair distribution through initial token offering (ITO), earned rewards, and community contributions.
Token Utility: Access premium content, purchase learning materials, participate in governance, and unlock exclusive features.
(Source)
Students: Fair access to tokens through learning and community contributions, unlocking premium content and exclusive features.
Educators: Rewarding system for content creation and community engagement, increasing your influence and earning potential.
District: Flexibility to design token incentives for employee training programs, aligning individual learning goals with organizational objectives.
5. DAO Governance:
While direct democracy empowers every token holder with a vote, it's not the only path to effective DAO governance in Decentralized Learning. Let's explore additional options for a healthy and engaged community:
1. Delegated Democracy:
Imagine a system where token holders elect Delegates: experienced and respected members who vote on their behalf. This model addresses challenges like information overload and voter fatigue, while ensuring efficient decision-making and representation of diverse viewpoints.
2. Hybrid Model:
Why not combine the best of both worlds? A hybrid model allows for direct voting on critical issues like platform development and resource allocation, while delegating day-to-day operations and minor decisions to elected representatives. This fosters both individual agency and collective efficiency.
3. Quadratic Voting:
This innovative approach gives more weight to informed and passionate votes. Users commit tokens to proposals, with the value of their vote increasing exponentially with the amount committed. This incentivizes deeper engagement and rewards conviction, ensuring well-considered decisions.
4. Reputation-Based Voting:
Imagine a system where your contributions to the platform (content creation, mentoring, active participation) earn you reputation points that influence your voting power. This rewards valuable contributions and ensures the community's most engaged members have a stronger voice in shaping the platform's future.
5. Time-Locked Voting:
This model encourages long-term thinking and discourages short-term manipulation. Users can lock their tokens for a specified period when voting on proposals, ensuring decisions are made with the platform's sustainable future in mind.
The optimal governance model will depend on your specific community goals and platform vision. Experiment, adapt, and continuously refine your approach to ensure a thriving and engaged learning ecosystem.
DAO governance goes beyond just casting votes.
Consider additional mechanisms for community engagement:
Proposal Forums: Dedicate a space for discussion, refinement, and debate around proposals before voting. This fosters informed decision-making and builds consensus.
Decentralized Feedback Mechanisms: Utilize on-chain mechanisms like Snapshot or Coordinate to gather community feedback on platform features, content, and development priorities.
Community Treasury Management: Empower token holders to allocate resources from the platform's treasury towards specific initiatives, rewarding valuable contributions and promoting community-driven growth.
By embracing flexible and innovative governance models, Decentralized Learning can create a truly community-owned and driven learning platform where every voice is heard, every contribution matters, and the future of education is shaped by those who learn and grow within it.
Students: Direct voice in shaping the platform's future through voting on proposals and contributing to community discussions.
Educators: Active participation in curriculum development and resource allocation, ensuring the platform meets the needs of learners.
District: Collaboration with other organizations to build a shared knowledge base and improve the overall learning experience.
6. Benefits:
Increased Motivation and Engagement: Tokenized incentives and gamification elements drive active participation and knowledge acquisition.
Improved Learning Outcomes: Personalized learning paths, community support, and reward systems enhance knowledge retention and skill development.
Democratized Access to Education: Affordable micro-learning opportunities, decentralized governance, and global reach break down barriers to education.
Community Ownership and Governance: Token holders directly influence the platform's direction, fostering a sense of ownership and shared responsibility.
7. Challenges and Future Directions:
Technical Complexity: Building a secure and scalable EVM-based platform requires specialized expertise.
Security Concerns: Smart contracts and token systems are vulnerable to hacks and exploits. Robust security measures are crucial.
User Adoption: Educating potential users about blockchain technology and tokenized learning concepts is vital for mainstream adoption.
Integration with Existing Education Systems: Exploring partnerships with traditional institutions to bridge the gap and leverage the benefits of both worlds.
8. Conclusion: Decentralized Learning offers a transformative vision for education. By leveraging blockchain technology, tokenized incentives, and DAO governance, we can create a vibrant learning ecosystem that empowers individuals, democratizes knowledge, and rewards lifelong learning. With continued development, community engagement, and a focus on addressing challenges, Decentralized Learning can revolutionize the way we learn and shape a future where knowledge is truly owned and shared by all.
Disclaimer: This white paper is for informational purposes only and should not be considered financial advice. Please conduct your own research before making any investment decisions.
|
"use client";
import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Star } from "react-feather";
import { toast } from "react-toastify";
import { StarRating } from "@/app/movies/[id]/starRating";
import { Section } from "@/components/section";
import { createReview } from "@/services/reviewService";
import { getMovieById } from "@/services/movieService";
import { reviewMaxLength, reviewMinLength } from "@/schemas/reviewSchema";
interface Props {
movie: Movie;
}
type Movie = NonNullable<Awaited<ReturnType<typeof getMovieById>>>;
export default function ReviewForm({ movie }: Props) {
const router = useRouter();
const [contentInput, setContentInput] = useState("");
const [rating, setRating] = useState<number | null>(null);
const reviewHeader = (
<div className="header-default-style">
<h2 className="yellow-name-header">
<Link href={`/movies/${movie.id}`}>{movie.title}</Link> review
</h2>
</div>
);
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
await createReview(Number(movie?.id), contentInput.trim(), rating);
setContentInput("");
setRating(null);
toast(<p>Your review was submitted</p>, {
icon: <Star className="yellow-icon-filled" />,
className: "yellow-toast",
});
router.push("/movies/" + movie?.id);
};
const setUserRating = async (stars: number | null) => {
const newRating = stars === rating ? null : stars;
setRating(newRating);
};
return (
<main className="form-main">
<div className="section-wrapper">
<Section header={reviewHeader}>
<div style={{ display: "grid", gap: "10px" }}>
<StarRating
rating={rating}
setRating={setUserRating}
size={40}
/>
<form
onSubmit={e => onSubmit(e)}
id="review-form"
className="form"
style={{ padding: "0" }}
>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<label
htmlFor="content"
className="h6"
>
Write your review here
</label>
<p
style={{ marginBottom: "0" }}
className={
contentInput.length <= reviewMaxLength && contentInput.length >= reviewMinLength
? "description grey"
: "description pink"
}
>
{contentInput.length}/{reviewMaxLength}
</p>
</div>
<textarea
id="content"
name="content"
required
rows={10}
minLength={reviewMinLength}
maxLength={reviewMaxLength}
placeholder="Share your thoughts! Was the storyline captivating? How was the acting? Did the special effects blow you away? Would you recommend it to a friend?"
onChange={e => setContentInput(e.target.value)}
/>
<button
type="submit"
form="review-form"
className="form-submit"
>
Send review
</button>
</form>
</div>
</Section>
</div>
</main>
);
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\SinhVien;
use App\Models\Khoa;
use App\Models\ChuyenNganh;
use App\Imports\SinhViensImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\LopHoc;
use DataTables;
use File;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\DB;
class SinhVienController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if ($request->ajax()) {
$data = SinhVien::leftJoin('lop_hocs', 'sinh_viens.id_lop_hoc', '=', 'lop_hocs.id')
->select('sinh_viens.*', 'lop_hocs.ten_lop_hoc')
->where('sinh_viens.trang_thai', 1)
->latest()
->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = '<a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->ma_sv . '" data-original-title="Edit" class="edit btn btn-primary btn-sm editBtn"><i class="fas fa-pencil-alt"></i></a>';
$btn = $btn . ' <a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->ma_sv . '" data-original-title="Delete" class="btn btn-danger btn-sm deleteBtn"><i class="fas fa-trash"></i></a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
$khoas = Khoa::all();
$chuyennganhs = ChuyenNganh::all();
$lophocs = LopHoc::all();
return view('admin.sinhviens.index', compact('khoas','chuyennganhs','lophocs'));
}
public function getInactiveData()
{
$data = SinhVien::leftJoin('lop_hocs', 'sinh_viens.id_lop_hoc', '=', 'lop_hocs.id')
->select('sinh_viens.*', 'lop_hocs.ten_lop_hoc')
->where('sinh_viens.trang_thai', 0)
->latest()
->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = '<a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->ma_sv . '" data-original-title="Edit" class="edit btn btn-primary btn-sm editBtn"><i class="fa-sharp fa-solid fa-pen-to-square"></i></a>';
$btn .= ' <a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->ma_sv.'" data-original-title="Restore" class="restore btn btn-success btn-sm restoreBtn"><i class="fa-solid fa-trash-can-arrow-up"></i></a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
public function import()
{
$idLopHocExcel = request('id_lop_hoc_excel');
Excel::import(new SinhViensImport($idLopHocExcel), request()->file('fileExcel'));
// Excel::import(new SinhViensImport,request()->file('fileExcel'));
return back();
}
public function getChuyenNganhByKhoa($id_khoa)
{
$chuyenNganhs = ChuyenNganh::where('id_khoa', $id_khoa)
->where('trang_thai', 1)
->get();
return response()->json($chuyenNganhs);
}
public function getLopByChuyenNganh($id_chuyen_nganh)
{
$lops = LopHoc::where('id_chuyen_nganh', $id_chuyen_nganh)
->where('trang_thai', 1)
->get();
return response()->json($lops);
}
public function getLopByKhoa($id_khoa)
{
$lops = LopHoc::join('chuyen_nganhs', 'lop_hocs.id_chuyen_nganh', '=', 'chuyen_nganhs.id')
->where('chuyen_nganhs.id_khoa', $id_khoa)
->where('lop_hocs.trang_thai', 1)
->select('lop_hocs.*')
->get();
return response()->json($lops);
}
public function getSinhVienByIdKhoa($id_khoa)
{
$data = SinhVien::leftJoin('lop_hocs', 'sinh_viens.id_lop_hoc', '=', 'lop_hocs.id')
->leftJoin('chuyen_nganhs', 'lop_hocs.id_chuyen_nganh', '=', 'chuyen_nganhs.id')
->select('sinh_viens.*', 'lop_hocs.ten_lop_hoc')
->where('chuyen_nganhs.id_khoa', $id_khoa)
->where('sinh_viens.trang_thai', 1)
->latest()
->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = '<a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->ma_sv . '" data-original-title="Edit" class="edit btn btn-primary btn-sm editBtn"><i class="fas fa-pencil-alt"></i></a>';
$btn = $btn . ' <a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->ma_sv . '" data-original-title="Delete" class="btn btn-danger btn-sm deleteBtn"><i class="fas fa-trash"></i></a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
public function getSinhVienByIdChuyenNganh($id_chuyen_nganh)
{
$data = SinhVien::leftJoin('lop_hocs', 'sinh_viens.id_lop_hoc', '=', 'lop_hocs.id')
->select('sinh_viens.*', 'lop_hocs.ten_lop_hoc')
->where('lop_hocs.id_chuyen_nganh', $id_chuyen_nganh)
->where('sinh_viens.trang_thai', 1)
->latest()
->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = '<a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->ma_sv . '" data-original-title="Edit" class="edit btn btn-primary btn-sm editBtn"><i class="fas fa-pencil-alt"></i></a>';
$btn = $btn . ' <a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->ma_sv . '" data-original-title="Delete" class="btn btn-danger btn-sm deleteBtn"><i class="fas fa-trash"></i></a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
public function getSinhVienByIdLop($id_lop)
{
$data = SinhVien::leftJoin('lop_hocs', 'sinh_viens.id_lop_hoc', '=', 'lop_hocs.id')
->select('sinh_viens.*', 'lop_hocs.ten_lop_hoc')
->where('id_lop_hoc', $id_lop)
->where('sinh_viens.trang_thai', 1)
->latest()
->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = '<a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->ma_sv . '" data-original-title="Edit" class="edit btn btn-primary btn-sm editBtn"><i class="fas fa-pencil-alt"></i></a>';
$btn = $btn . ' <a href="javascript:void(0)" data-toggle="tooltip" data-id="' . $row->ma_sv . '" data-original-title="Delete" class="btn btn-danger btn-sm deleteBtn"><i class="fas fa-trash"></i></a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
public function taoBangTen($hoten, $lop)
{
$maxWidth = 1035 - (2 * 12);
$fontPath = public_path('sinhvien_bangten/calibri.ttf');
$fontSize = 165;
$image = Image::canvas(1000, 350, '#ffffff')->rectangle(6, 6, 995, 343, function ($draw) {
$draw->border(12, '#0000FF');
});
$textLength = imagettfbbox($fontSize, 0, $fontPath, $hoten)[2];
if ($textLength > $maxWidth) {
$fontSize = $fontSize * $maxWidth / $textLength;
$fontSize = $fontSize + 4;
}
$image->text(mb_strtoupper($hoten), 500, 110, function($font) use ($fontPath, $fontSize) {
$font->file($fontPath);
$font->size($fontSize);
$font->color('#0000FF');
$font->align('center');
$font->valign('middle');
});
$image->text(mb_strtoupper($lop), 500, 270, function($font) use ($fontPath, $fontSize) {
$font->file($fontPath);
$font->size(116);
$font->color('#0000FF');
$font->align('center');
$font->valign('middle');
});
$newImagePath = public_path('sinhvien_bangten/image.jpg');
$image->save($newImagePath);
return response()->json(asset('sinhvien_bangten/image.jpg'));
}
public function taoTheSinhVien($mssv)
{
$sv = SinhVien::where('ma_sv', $mssv)->first();
$lop = LopHoc::where('id', $sv->id_lop_hoc)->first();
// dd($sv->ten_sinh_vien);
$image = Image::canvas(770, 400, '#ffffff');
// $hinhsv = Image::make(public_path('sinhvien_img/'.$sv->hinh_anh_dai_dien))->resize(132, 175);
$filePath = null;
if ($sv->hinh_anh_dai_dien) {
$filePath = public_path('sinhvien_img/'.$sv->hinh_anh_dai_dien);
}
if ($filePath && file_exists($filePath)) {
$hinhsv = Image::make($filePath)->resize(132, 175);
} else {
return "Không tìm thấy hình ảnh";
}
$image->insert($hinhsv, 'top-left', 37, 165);
$logocaothang = Image::make(public_path('sinhvien_thesinhvien/logo_caothang.jpg'))->resize(80, 120);
$image->insert($logocaothang, 'top-left', 59, 10);
$image->text('TRƯỜNG CAO ĐẲNG KỸ THUẬT CAO THẮNG', 170, 24, function($font) {
$font->file(public_path('sinhvien_thesinhvien/calibri.ttf'));
$font->size(32);
$font->color('#0000FF');
$font->valign('middle');
});
$image->text('THẺ SINH VIÊN', 360, 65, function($font) {
$font->file(public_path('sinhvien_thesinhvien/calibri.ttf'));
$font->size(42);
$font->color('#FF0000');
$font->align('left');
$font->valign('middle');
});
$image->text(mb_strtoupper($sv->ten_sinh_vien), 250, 120, function($font) {
$font->file(public_path('sinhvien_bangten/calibri.ttf'));
$font->size(40);
$font->color('#0000FF');
$font->align('left');
$font->valign('middle');
});
$image->text('Ngày sinh: ' . date('d/m/Y', strtotime($sv->ngay_sinh)), 250, 180, function($font) {
$font->file(public_path('sinhvien_thesinhvien/calibri.ttf'));
$font->size(35);
$font->color('#0000FF');
$font->align('left');
$font->valign('middle');
});
$image->text('Khóa: '.$sv->khoa_hoc.' - '.($sv->khoa_hoc+3), 250, 250, function($font) {
$font->file(public_path('sinhvien_thesinhvien/calibri.ttf'));
$font->size(35);
$font->color('#0000FF');
$font->align('left');
$font->valign('middle');
});
$image->text('Lớp: '.$lop->ten_lop_hoc, 250, 325, function($font) {
$font->file(public_path('sinhvien_thesinhvien/calibri.ttf'));
$font->size(35);
$font->color('#0000FF');
$font->align('left');
$font->valign('middle');
});
$image->text('MS: '.$sv->ma_sv, 19, 370, function($font) {
$font->file(public_path('sinhvien_thesinhvien/calibri.ttf'));
$font->size(25);
$font->color('#0000FF');
$font->align('left');
$font->valign('middle');
});
$newImagePath = public_path('sinhvien_thesinhvien/image.jpg');
$image->save($newImagePath);
return response()->json(asset('sinhvien_thesinhvien/image.jpg'));
}
public function getDiemTrungBinhHocKy()
{
$result = SinhVien::leftJoin('ct_lop_hoc_phans', 'sinh_viens.ma_sv', '=', 'ct_lop_hoc_phans.ma_sv')
->leftJoin('lop_hoc_phans', 'ct_lop_hoc_phans.id_lop_hoc_phan', '=', 'lop_hoc_phans.id')
->leftJoin('ct_chuong_trinh_dao_taos', 'lop_hoc_phans.id_ct_chuong_trinh_dao_tao', '=', 'ct_chuong_trinh_dao_taos.id')
->select(
'sinh_viens.ten_sinh_vien',
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 1 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk1'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 2 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk2'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 3 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk3'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 4 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk4'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 5 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk5'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 6 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk6')
)
->groupBy('sinh_viens.ten_sinh_vien')
->get();
return response()->json($result);
}
public function getDiemTrungBinhHocKyByLop($id_lop_hoc)
{
$result = SinhVien::leftJoin('ct_lop_hoc_phans', 'sinh_viens.ma_sv', '=', 'ct_lop_hoc_phans.ma_sv')
->leftJoin('lop_hoc_phans', 'ct_lop_hoc_phans.id_lop_hoc_phan', '=', 'lop_hoc_phans.id')
->leftJoin('ct_chuong_trinh_dao_taos', 'lop_hoc_phans.id_ct_chuong_trinh_dao_tao', '=', 'ct_chuong_trinh_dao_taos.id')
->select(
'sinh_viens.ten_sinh_vien',
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 1 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk1'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 2 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk2'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 3 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk3'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 4 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk4'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 5 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk5'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 6 THEN GREATEST(ct_lop_hoc_phans.tong_ket_1, COALESCE(ct_lop_hoc_phans.tong_ket_2, ct_lop_hoc_phans.tong_ket_1)) ELSE NULL END) AS trung_binh_hk6')
)
->where('sinh_viens.id_lop_hoc', $id_lop_hoc)
->groupBy('sinh_viens.ten_sinh_vien')
->get();
return response()->json($result);
}
public function getDiemTrungBinhHocKyByLop_xettotnghiep($id_lop_hoc)
{
$result = SinhVien::leftJoin('ct_lop_hoc_phans', 'sinh_viens.ma_sv', '=', 'ct_lop_hoc_phans.ma_sv')
->leftJoin('lop_hoc_phans', 'ct_lop_hoc_phans.id_lop_hoc_phan', '=', 'lop_hoc_phans.id')
->leftJoin('ct_chuong_trinh_dao_taos', 'lop_hoc_phans.id_ct_chuong_trinh_dao_tao', '=', 'ct_chuong_trinh_dao_taos.id')
->select(
'sinh_viens.ten_sinh_vien',
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 1 THEN GREATEST(COALESCE(ct_lop_hoc_phans.tong_ket_1, 0), COALESCE(ct_lop_hoc_phans.tong_ket_2, 0)) END) AS trung_binh_hk1'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 2 THEN GREATEST(COALESCE(ct_lop_hoc_phans.tong_ket_1, 0), COALESCE(ct_lop_hoc_phans.tong_ket_2, 0)) END) AS trung_binh_hk2'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 3 THEN GREATEST(COALESCE(ct_lop_hoc_phans.tong_ket_1, 0), COALESCE(ct_lop_hoc_phans.tong_ket_2, 0)) END) AS trung_binh_hk3'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 4 THEN GREATEST(COALESCE(ct_lop_hoc_phans.tong_ket_1, 0), COALESCE(ct_lop_hoc_phans.tong_ket_2, 0)) END) AS trung_binh_hk4'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 5 THEN GREATEST(COALESCE(ct_lop_hoc_phans.tong_ket_1, 0), COALESCE(ct_lop_hoc_phans.tong_ket_2, 0)) END) AS trung_binh_hk5'),
DB::raw('AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky = 6 THEN GREATEST(COALESCE(ct_lop_hoc_phans.tong_ket_1, 0), COALESCE(ct_lop_hoc_phans.tong_ket_2, 0)) END) AS trung_binh_hk6'),
DB::raw('CASE
WHEN AVG(CASE WHEN ct_chuong_trinh_dao_taos.hoc_ky <= 6 AND (ct_lop_hoc_phans.tong_ket_1 >= 5 OR ct_lop_hoc_phans.tong_ket_2 >= 5) THEN GREATEST(COALESCE(ct_lop_hoc_phans.tong_ket_1, 0), COALESCE(ct_lop_hoc_phans.tong_ket_2, 0)) END) < 5 THEN "Không đạt"
WHEN COUNT(CASE WHEN (ct_lop_hoc_phans.tong_ket_1 < 5 OR ct_lop_hoc_phans.tong_ket_2 < 5) AND (ct_lop_hoc_phans.tong_ket_1 IS NOT NULL OR ct_lop_hoc_phans.tong_ket_2 IS NOT NULL) THEN 1 END) > 0 THEN "Không đạt"
ELSE "Đạt"
END AS tot_nghiep')
)
->where('lop_hoc_phans.id_lop_hoc', $id_lop_hoc)
->groupBy('sinh_viens.ten_sinh_vien')
->get();
return response()->json($result);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$profileImage = $request->input('hinh_anh_dai_dien_hidden'); // Giá trị hiện tại của hinh_anh_dai_dien
if ($request->hasFile('hinh_anh_dai_dien')) {
$oldImage = SinhVien::where('ma_sv', $request->ma_sv)->value('hinh_anh_dai_dien');
if ($oldImage && FILE::exists('sinhvien_img/' . $oldImage)) {
// Xóa ảnh cũ
FILE::delete('sinhvien_img/' . $oldImage);
}
$files = $request->file('hinh_anh_dai_dien');
$destinationPath = 'sinhvien_img/'; // Đường dẫn lưu trữ ảnh
// $profileImage = $request->ma_sv . "." . $files->getClientOriginalExtension();
$profileImage = $request->ma_sv . "_" . time() . ".jpg";
$files->move($destinationPath, $profileImage);
}
$request->validate([
'ten_sinh_vien' => ['required', 'regex:/^[\p{L}\s]+$/u'],
'email' => ['required', 'email'],
'so_dien_thoai' => ['required', 'regex:/^(0|\+84)?([3-9]\d{8})$/'],
'so_cmt' => ['required', 'regex:/\d{9}|\d{12}/'],
'gioi_tinh' => ['required'],
'ngay_sinh' => ['required'],
'noi_sinh' => ['required'],
'dan_toc' => ['required', 'regex:/^[\p{L}\s]+$/u'],
'ton_giao' => ['required', 'regex:/^[\p{L}\s]+$/u'],
'dia_chi_thuong_tru' => ['required'],
'dia_chi_tam_tru' => ['required'],
'tai_khoan' => ['required'],
'khoa_hoc' => ['required', 'regex:/^\d{4}$/'],
'bac_dao_tao' => ['required'],
'he_dao_tao' => ['required'],
'id_lop_hoc' => ['required'],
'tinh_trang_hoc' => ['required'],
]);
$sinhVienData = [
'ten_sinh_vien' => $request->ten_sinh_vien,
'email' => $request->email,
'so_dien_thoai' => $request->so_dien_thoai,
'so_cmt' => $request->so_cmt,
'gioi_tinh' => $request->gioi_tinh,
'ngay_sinh' => $request->ngay_sinh,
'noi_sinh' => $request->noi_sinh,
'dan_toc' => $request->dan_toc,
'ton_giao' => $request->ton_giao,
'dia_chi_thuong_tru' => $request->dia_chi_thuong_tru,
'dia_chi_tam_tru' => $request->dia_chi_tam_tru,
'hinh_anh_dai_dien' => $profileImage,
'tai_khoan' => $request->tai_khoan,
'khoa_hoc' => $request->khoa_hoc,
'bac_dao_tao' => $request->bac_dao_tao,
'he_dao_tao' => $request->he_dao_tao,
'id_lop_hoc' => $request->id_lop_hoc,
'tinh_trang_hoc' => $request->tinh_trang_hoc,
];
if (!empty($request->mat_khau)) {
$sinhVienData['mat_khau'] = bcrypt($request->mat_khau);
}
SinhVien::updateOrCreate(['ma_sv' => $request->ma_sv], $sinhVienData);
return response()->json(['success'=>'Lưu Thành Công.']);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$sinhvien = SinhVien::find($id);
return response()->json($sinhvien);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
SinhVien::where('ma_sv', $id)->update(['trang_thai' => 0]);
return response()->json(['success' => 'Xóa Chuyên Ngành Thành Công.']);
}
public function restore($id)
{
SinhVien::where('ma_sv', $id)->update(['trang_thai' => 1]);
return response()->json(['success' => 'Xóa Chuyên Ngành Thành Công.']);
}
public function laySinhVienTheoLopHoc($id_lop_hoc)
{
$sinhviens = SinhVien::where('id_lop_hoc', $id_lop_hoc)->get();
return response()->json($sinhviens);
}
public function layTongSinhVien()
{
$tongSinhViens = SinhVien::where('trang_thai', 1)->count();
return response()->json(['tongSinhViens' => $tongSinhViens]);
}
}
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomePageComponent } from './pages/home-page/home-page.component';
import { ProductsPageComponent } from './pages/products-page/products-page.component';
import { NotFoundComponent } from './commons/not-found/not-found.component';
import { ProductPageComponent } from './pages/product-page/product-page.component';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomePageComponent },
{ path: 'products', component: ProductsPageComponent },
// On va juste ajouter une route vers les types
{ path: 'products/:type', component: ProductPageComponent },
// Puis une route vers le type ET l'ID :
{ path: 'products/:type/:id', component: ProductPageComponent },
{ path: '**', component: NotFoundComponent }
];
// Le reste on touche pas :D.
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
<?php
/*
* This file is part of Totara LMS
*
* Copyright (C) 2022 onwards Totara Learning Solutions LTD
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @author Riana Rossouw <[email protected]>
* @package mod_facetoface
*/
use core\performance_statistics\collector;
use mod_facetoface\seminar_event;
use mod_facetoface\signup;
use mod_facetoface\signup\condition\user_has_no_conflicts;
use mod_facetoface\signup\state\booked;
use mod_facetoface\signup_status;
defined('MOODLE_INTERNAL') || die();
/**
* A unit test for the user_has_no_conflicts condition.
*
* Class mod_facetoface_user_has_no_conflicts_testcase
*/
class mod_facetoface_user_has_no_conflicts_testcase extends advanced_testcase {
protected function setUp(): void {
$this->setAdminUser();
set_config('perfdebug', 15);
}
public function test_pass_caching(): void {
$gen = self::getDataGenerator();
/** @var mod_facetoface_generator $f2fgen */
$f2fgen = $gen->get_plugin_generator('mod_facetoface');
$user = $gen->create_user();
$course = $gen->create_course();
$gen->enrol_user($user->id, $course->id);
$now = time();
$start_time = $now + DAYSECS;
// One course, 2 conflicting sessions
$f2f_1 = $f2fgen->create_instance(['course' => $course->id]);
$eventid = $f2fgen->add_session(
[
'facetoface' => $f2f_1->id,
'capacity' => 5,
'sessiondates' => [
(object)[
'sessiontimezone' => '99',
'timestart' => $start_time,
'timefinish' => $start_time + (2 * HOURSECS),
'roomids' => [],
'assetids' => [],
'facilitatorids' => [],
],
],
]
);
$seminar_event_1 = new seminar_event($eventid);
$f2f_2 = $f2fgen->create_instance(['course' => $course->id]);
$eventid = $f2fgen->add_session(
[
'facetoface' => $f2f_2->id,
'capacity' => 5,
'sessiondates' => [
(object)[
'sessiontimezone' => '99',
'timestart' => $start_time + HOURSECS,
'timefinish' => $start_time + (2 * HOURSECS),
'roomids' => [],
'assetids' => [],
'facilitatorids' => [],
],
],
]
);
$seminar_event_2 = new seminar_event($eventid);
// First verify caching when there are no conflicts
$signup_1 = signup::create($user->id, $seminar_event_1)->save();
$n_db_reads_1 = self::get_num_db_reads();
$cond1 = new user_has_no_conflicts($signup_1);
self::assertTrue($cond1->pass());
$n_db_reads_2 = self::get_num_db_reads();
self::assertGreaterThan($n_db_reads_1, $n_db_reads_2);
self::assertTrue($cond1->pass());
$n_db_reads_3 = self::get_num_db_reads();
self::assertSame($n_db_reads_3, $n_db_reads_2);
// Now clear the user_has_no_conflicts cache
$cache = $cond1->get_cache();
$cache->purge();
self::assertTrue($cond1->pass());
$n_db_reads_4 = self::get_num_db_reads();
self::assertGreaterThan($n_db_reads_3, $n_db_reads_4);
// User books for first session and then we check with the conflicting session
signup_status::create($signup_1, new booked($signup_1))->save();
$signup_2 = signup::create($user->id, $seminar_event_2)->save();
$cond2 = new user_has_no_conflicts($signup_2);
$n_db_reads_20 = self::get_num_db_reads();
self::assertFalse($cond2->pass());
$n_db_reads_21 = self::get_num_db_reads();
self::assertGreaterThan($n_db_reads_20, $n_db_reads_21);
self::assertFalse($cond2->pass());
$n_db_reads_22 = self::get_num_db_reads();
self::assertSame($n_db_reads_21, $n_db_reads_22);
// Now clear the user_has_no_conflicts cache
$cache = $cond2->get_cache();
$cache->purge();
self::assertFalse($cond2->pass());
$n_db_reads_23 = self::get_num_db_reads();
self::assertGreaterThan($n_db_reads_22, $n_db_reads_23);
}
private static function get_num_db_reads(): int {
$collector = new collector();
$data = $collector->all();
if (empty($data) || empty($data->core) || empty($data->core->db)) {
return 0;
}
return $data->core->db->reads;
}
}
|
package com.example.jetpackcomposecheckbox
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.leanback.widget.Row
import com.example.jetpackcomposecheckbox.ui.theme.JetpackComposeTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
JetpackComposeTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Calculator()
}
}
}
}
}
@SuppressLint("UnrememberedMutableState")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Calculator() {
var num1 by remember { mutableStateOf("") }
var num2 by remember { mutableStateOf("") }
var result by remember { mutableStateOf("") }
Column {
TextField(
value = num1,
onValueChange = { num1 = it },
label = { Text("Número 1") },
modifier = Modifier.fillMaxWidth(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
)
Spacer(modifier = Modifier.height(5.dp))
TextField(
value = num2,
onValueChange = { num2 = it },
label = { Text("Número 2") },
modifier = Modifier.fillMaxWidth(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
)
val items = listOf("Suma", "Resta", "Multiplicación")
val checkboxStates = remember {mutableStateMapOf<String,Boolean>().withDefault{false}}
Column {
items.forEach { item ->
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = androidx.compose.ui.Alignment.CenterVertically
) {
Checkbox(
checked = checkboxStates.getValue(item),
onCheckedChange = {
checkboxStates[item]=it
}
)
Text(
text = item,
// style = MaterialTheme.typography.body1.merge(),
modifier = Modifier.padding(start = 16.dp)
)
}
}
}
Button(
onClick = {
val n1: Float? = num1.toFloatOrNull()
val n2: Float? = num2.toFloatOrNull()
if (n1 != null && n2 != null) {
var res: String? = ""
if(checkboxStates["Suma"]==true)
res += "$n1 + $n2 = ${n1 + n2}\n"
if(checkboxStates["Resta"]==true)
res += "$n1 - $n2 = ${n1 - n2}\n"
if(checkboxStates["Multiplicación"]==true)
res += "$n1 * $n2 = ${n1 * n2}"
result = if (res != null) "Resultado:\n $res" else "Por favor, seleccione al menos una operación."
} else {
result = "Por favor, ingrese números válidos."
}
},
modifier = Modifier.padding(top = 16.dp)
) {
Text(text = "Calcular")
}
if (result.isNotEmpty()) {
Text(text = result)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TaskList() {
var task by remember { mutableStateOf("") }
val tasks = remember { mutableStateListOf<String>() }
Column {
TextField(
value = task,
onValueChange = { task = it },
label = { Text("Tarea") },
modifier = Modifier.fillMaxWidth()
)
Button(
onClick = {
if (task.isNotEmpty()) {
tasks.add(task)
task = ""
}
},
modifier = Modifier.padding(top = 16.dp)
) {
Text(text = "Agregar")
}
LazyColumn {
items(tasks) { task ->
Card(modifier = Modifier.padding(5.dp)){
Column(modifier = Modifier.padding(5.dp)) {
Row(modifier= Modifier.height(50.dp)
.fillMaxWidth()
) {
Text(text = task)
}
}
}
}
}
}
}
|
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {createBrowserRouter, RouterProvider} from "react-router-dom"
const router = createBrowserRouter([
{
path: "/",
element: <div>Hello world!</div>,
},
{
path: "/login",
element: <div>Login</div>,
},
{
path: "/register",
element: <div>Register</div>,
},
{
path: "/check-email",
element: <div>Check email</div>
},
{
path: "/set-new-password",
element: <div>Set new password</div>
},
{
path: "/forgot-password",
element: <div>Set new password</div>
},
{
path: "/profile",
element: <div>Set new password</div>
},
{
path: "/packs",
element: <div>Set new password</div>
},
{
path: "/cards",
element: <div>Set new password</div>
},
{
path: "/learn",
element: <div>Set new password</div>
}
]);
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
{/*<App />*/}
<RouterProvider router={router} />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TinDog</title>
<!-- bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<!-- css style sheet -->
<link rel="stylesheet" href="css/styles.css">
<!-- bootstrap icon -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<!-- google fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Montserrat+Alternates&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@900&family=Ubuntu:wght@300&display=swap" rel="stylesheet">
</head>
<body>
<section id="title">
<div class="container-fluid">
<!-- Nav Bar -->
<nav class="navbar navbar-expand-lg navbar-dark">
<a class="navbar-brand">tindog</a>
<button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbar01" aria-controls="offcanvasNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="offcanvasNavbar01">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link" href="#footer">Contact</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#pricing">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#cta">Download</a>
</li>
</ul>
</div>
</nav>
<!-- Title -->
<div class="row">
<div class="col-lg-6">
<h1 class="big-heading">Meet new and interesting dogs nearby.</h1>
<button type="button" class="btn btn-dark btn-lg down-button"><i class="bi bi-apple"></i> Download</button>
<button type="button" class="btn btn-outline-light btn-lg down-button"><i class="bi bi-google-play"></i> Download</button>
</div>
<div class="col-lg-6">
<img class="title-image" src="images/iphone6.png" alt="iphone-mockup">
</div>
</div>
</div>
</section>
<!-- Features -->
<section id="features">
<div class="row">
<div class="feature-box col-lg-4">
<h1 class="icon bi bi-check-circle-fill"></h1>
<h3>Easy to use</h3>
<p>So easy to use, even your dog could do it.</p>
</div>
<div class="feature-box col-lg-4">
<h1 class="icon bi bi-bullseye"></h1>
<h3>Elite Clientele</h3>
<p>We have all the dogs, the greatest dogs.</p>
</div>
<div class="feature-box col-lg-4">
<h1 class="icon bi bi-suit-heart-fill"></h1>
<h3>Guaranteed</h3>
<p>Find the love of your dog's life or your money back.</p>
</div>
</div>
</section>
<!-- Testimonials -->
<section id="testimonials">
<div id="carouselExample" class="carousel slide">
<div class="carousel-inner">
<div class="carousel-item active">
<h2>I no longer have to sniff other dogs for love. I've found the hottest Corgi on TinDog. Woof.</h2>
<img class="testimonial-image" src="images/dog-img.jpg" alt="dog-profile">
<em>Pebbles, New York</em>
</div>
<div class="carousel-item">
<h2 class="testimonial-text">My dog used to be so lonely, but with TinDog's help, they've found the love of their life. I think.</h2>
<img class="testimonial-image" src="images/lady-img.jpg" alt="lady-profile">
<em>Beverly, Illinois</em>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExample" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExample" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</section>
<!-- Press -->
<section id="press">
<img class="press-logo" src="images/techcrunch.png" alt="tc-logo">
<img class="press-logo" src="images/tnw.png" alt="tnw-logo">
<img class="press-logo" src="images/bizinsider.png" alt="biz-insider-logo">
<img class="press-logo" src="images/mashable.png" alt="mashable-logo">
</section>
<!-- Pricing -->
<section id="pricing">
<h2>A Plan for Every Dog's Needs</h2>
<p>Simple and affordable price plans for your and your dog.</p>
<div class="row row-cols-1 row-cols-md-3 mb-3 text-center">
<div class="pricing-column col">
<div class="card mb-4 rounded-3 shadow-sm">
<div class="card-header">
<h3>Chihuahua</h3>
</div>
<div class="card-body">
<h2>Free</h2>
<p>5 Matches Per Day</p>
<p>10 Messages Per Day</p>
<p>Unlimited App Usage</p>
<button class="btn btn-lg btn-block btn-outline-dark" type="button">Sign Up</button>
</div>
</div>
</div>
<div class="pricing-column col">
<div class="card mb-4 rounded-3 shadow-sm">
<div class="card-header">
<h3>Labrador</h3>
</div>
<div class="card-body">
<h2>$49 / mo</h2>
<p>Unlimited Matches</p>
<p>Unlimited Messages</p>
<p>Unlimited App Usage</p>
<button class="btn btn-lg btn-block btn-outline-dark" type="button">Sign Up</button>
</div>
</div>
</div>
<div class="pricing-column col">
<div class="card mb-4 rounded-3 shadow-sm">
<div class="card-header">
<h3>Mastiff</h3>
</div>
<div class="card-body">
<h2>$99 / mo</h2>
<p>Pirority Listing</p>
<p>Unlimited Messages</p>
<p>Unlimited App Usage</p>
<button class="btn btn-lg btn-block btn-outline-dark" type="button">Sign Up</button>
</div>
</div>
</div>
</div>
</section>
<!-- Call to Action -->
<section id="cta">
<h3 class="cta-heading">Find the True Love of Your Dog's Life Today.</h3>
<button type="button" class="btn btn-dark btn-lg down-button"><i class="bi bi-apple"></i> Download</button>
<button type="button" class="btn btn-outline-light btn-lg down-button"><i class="bi bi-google-play"></i> Download</button>
</section>
<!-- Footer -->
<footer id="footer">
<i class="social-icon bi bi-facebook"></i>
<i class="social-icon bi bi-instagram"></i>
<i class="social-icon bi bi-envelope-fill"></i>
<i class="social-icon bi bi-snapchat"></i>
<p>© Copyright TinDog</p>
</footer>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
|
package com.example.crud
import android.content.DialogInterface
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import com.example.crud.databinding.ActivityMenuBinding
import com.example.crud.factory.AccountModelFactory
import com.example.crud.helper.AccountPreferences
import com.example.crud.helper.dataStoreAccount
import com.example.crud.model.AccountViewModel
import com.google.firebase.auth.FirebaseAuth
class MenuActivity : AppCompatActivity() {
lateinit var auth: FirebaseAuth
lateinit var binding: ActivityMenuBinding
private lateinit var accountViewModel: AccountViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_menu)
binding = ActivityMenuBinding.inflate(layoutInflater)
setContentView(binding.root)
supportActionBar?.hide()
val pref = AccountPreferences.getInstance(application.dataStoreAccount)
accountViewModel = ViewModelProvider(this, AccountModelFactory(pref)).get(AccountViewModel::class.java)
binding.MImg1.setOnClickListener {
finish()
}
binding.btnInput.setOnClickListener {
startActivity(Intent(this, InputActivity::class.java))
}
binding.btnLihat.setOnClickListener {
startActivity(Intent(this, LihatActivity::class.java))
}
binding.btnInsentif.setOnClickListener {
startActivity(Intent(this, InsentifActivity::class.java))
}
binding.btnInfo.setOnClickListener {
startActivity(Intent(this, InfoActivity::class.java))
}
binding.btnLogout.setOnClickListener {
// startActivity(Intent(this, LogoutActivity::class.java))
try {
showAlertLogout()
} catch (e: Exception) {
Toast.makeText(this, e.message.toString(), Toast.LENGTH_SHORT).show()
Log.e("logout", e.message.toString())
}
}
}
private fun showAlertLogout(){
val builder = AlertDialog.Builder(this)
builder.setTitle("Are you sure wanna logout?")
.setPositiveButton("Yes"){ dialog: DialogInterface, _:Int ->
FirebaseAuth.getInstance().signOut()
accountViewModel.deleteAccount()
// finishAffinity()
val intent = Intent(this@MenuActivity, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
dialog.dismiss()
}
.setNegativeButton("No"){dialog: DialogInterface, _:Int ->
dialog.dismiss()
}
.setCancelable(false)
.show()
}
}
|
package com.malliaridis.tui.domain.configuration
import com.malliaridis.tui.model.AppPreference
import kotlinx.coroutines.flow.StateFlow
/**
* The preferences component manages the user's preferences.
*/
interface PreferencesComponent {
val models: StateFlow<Model>
/**
* Function for handling preference selections.
*/
fun onSelectPreference(preference: AppPreference<*>?)
/**
* Function for handling preference update requests.
*
* This does not clear / resets the preference if [AppPreference.value] is set to [AppPreference.defaultValue]. See for that
* [onResetPreferenceById].
*
* @param preferenceId ID of the preference to update.
* @param value The new value of the preference.
*/
fun onUpdatePreference(preferenceId: String, value: Any?)
/**
* Function that resets the value of a preference with the given ID.
*
* @param preferenceId The ID of the preference to reset.
*/
fun onResetPreferenceById(preferenceId: String)
/**
* Returns the value of the preference with the given ID.
*
* @param preferenceId The ID from which the value should be fetched.
* @return The currently loaded value.
*/
fun <V> get(preferenceId: String): V
/**
* Data class that represents the state of [PreferencesComponent].
*
* @property values A list of the currently active preferences as key-value pairs.
* @property isLoading Whether the preferences are being loaded.
* @property focused The focused preference, if any.
*/
data class Model(
val values: List<AppPreference<*>> = emptyList(),
val isLoading: Boolean = false,
val focused: AppPreference<*>? = null,
)
}
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:responsive_sizer/responsive_sizer.dart';
import '../../../../common/common_methods.dart';
import '../../../../common/common_widgets.dart';
import '../../../data/constants/string_constants.dart';
import '../controllers/withdraw_controller.dart';
class WithdrawView extends GetView<WithdrawController> {
const WithdrawView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: CommonWidgets.appBar(title: StringConstants.withdraw),
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 16.px),
child: ListView(
children: [
SizedBox(height: 20.px),
Text(
StringConstants.howMuchMoney,
textAlign: TextAlign.start,
style: Theme.of(context)
.textTheme
.displayMedium
?.copyWith(fontSize: 18.px),
),
SizedBox(height: 20.px),
Card(
elevation: .4.px,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14.px)),
child: Padding(
padding: EdgeInsets.all(20.px),
child: Column(
children: [
Text.rich(
TextSpan(children: [
TextSpan(
text: CommonMethods.cur,
style: Theme.of(context)
.textTheme
.displayMedium
?.copyWith(
fontSize: 14.px,
color: Theme.of(context).primaryColor,
),
),
TextSpan(
text: '6',
style: Theme.of(context)
.textTheme
.displayMedium
?.copyWith(
fontSize: 60.px,
color: Theme.of(context).primaryColor,
),
),
]),
),
SizedBox(height: 24.px),
Text(
'Maximum \$ 5.00 Minimum \$ 0.50',
textAlign: TextAlign.start,
style:
Theme.of(context).textTheme.displayMedium?.copyWith(
fontSize: 14.px,
color: Theme.of(context).primaryColor,
),
),
SizedBox(height: 10.px),
CommonWidgets.commonElevatedButton(
onPressed: () => controller.clickOnTransferToBank(),
childText: Text(
StringConstants.transferToBank,
style: Theme.of(context)
.textTheme
.headlineSmall
?.copyWith(fontWeight: FontWeight.w700),
),
),
],
),
),
),
SizedBox(height: 20.px),
],
),
),
);
}
}
|
package com.meu.soccernews.ui.news.adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.meu.soccernews.R;
import com.meu.soccernews.databinding.ItemNewsBinding;
import com.meu.soccernews.domain.News;
import com.squareup.picasso.Picasso;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<News> news;
private FavoriteListener favoriteListener;
public NewsAdapter(List<News> news, FavoriteListener favoriteListener){
this.news = news;
this.favoriteListener = favoriteListener;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
ItemNewsBinding binding = ItemNewsBinding.inflate(layoutInflater, parent, false);
return new ViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final Context context = holder.itemView.getContext();
News news = this.news.get(position);
holder.binding.tvTitle.setText(news.title);
holder.binding.tvDescription.setText(news.description);
Picasso.get().load(news.image).into(holder.binding.ivThumbnail);
//Funcionalidade de abrir link
holder.binding.btnOpenLink.setOnClickListener(view -> {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(news.link));
context.startActivity(i);
});
//Funcionalidade de compartilhar link
holder.binding.ivShare.setOnClickListener(view -> {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, news.link);
context.startActivity(Intent.createChooser(i, "share"));
});
//Funcionalidade de favoritar
holder.binding.ivFavorite.setOnClickListener(view -> {
news.favorite = !news.favorite;
this.favoriteListener.onFavorite(news);
notifyItemChanged(position);
});
//
int favoriteColor = news.favorite ? R.color.favorite_active : R.color.favorite_inactive;
holder.binding.ivFavorite.setColorFilter(context.getResources().getColor(favoriteColor));
}
@Override
public int getItemCount() {
return this.news.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final ItemNewsBinding binding;
public ViewHolder(ItemNewsBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
public interface FavoriteListener {
void onFavorite(News news);
}
}
|
const express = require("express");
const { Clearance } = require("../models/clearance");
const { User } = require ("../models/user");
const router = express.Router();
const mongoose = require("mongoose");
const multer = require("multer");
const cloudinary = require("cloudinary");
const FILE_TYPE_MAP = {
"image/png": "png",
"image/jpeg": "jpeg",
"image/jpg": "jpg",
};
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const isValid = FILE_TYPE_MAP[file.mimetype];
let uploadError = new Error("invalid image type");
if (isValid) {
uploadError = null;
}
cb(uploadError, "public/uploads");
},
filename: function (req, file, cb) {
const fileName = file.originalname.split(" ").join("-");
const extension = FILE_TYPE_MAP[file.mimetype];
cb(null, `${fileName}-${Date.now()}.${extension}`);
},
});
const uploadOptions = multer({ storage: storage });
// router.post("/", uploadOptions.any(), async (req, res) => {
// console.log("req body", req.body);
// try {
// const file = req.files;
// console.log("file", file);
// if (!file) return res.status(400).send("no image in the clearance");
// const clearanceImages = req.files.filter(
// (file) => file.fieldname === "clearanceImages" // Updated fieldname to match frontend
// );
// // Upload image to Cloudinary
// const cloudinaryFolderOption = {
// folder: "Clearance of Students",
// crop: "scale",
// };
// let imageClearance = [];
// if (clearanceImages.length > 0) {
// const clearanceResult = await cloudinary.v2.uploader.upload(
// clearanceImages[0].path, // Corrected variable name
// cloudinaryFolderOption
// );
// imageClearance = {
// public_id: clearanceResult.public_id,
// url: clearanceResult.secure_url,
// };
// }
// const user = req.body.user;
// const uploadedAt = req.body.uploadedAt;
// const clearance = new Clearance({
// uploadedAt: uploadedAt,
// user: user,
// clearanceImages: imageClearance,
// });
// console.log("SCREENSHOT", clearance)
// const savedClearance = await clearance.save();
// res.send(savedClearance);
// } catch (error) {
// console.error("Error creating clearance:", error);
// res.status(500).send("Error creating clearance!");
// }
// });
router.post(`/`, uploadOptions.single("image"), async (req, res) => {
try {
const file = req.file;
if (!file) return res.status(400).send("No image in the request");
// File upload successful, now upload to Cloudinary
const cloudinaryFolderOption = {
folder: "Clearance of Students",
crop: "scale",
};
const result = await cloudinary.v2.uploader.upload(
req.file.path,
cloudinaryFolderOption
);
// Create a new clearance instance with the uploaded file information
const clearance = new Clearance({
user: req.body.user,
uploadedAt: req.body.uploadedAt,
clearanceImages: {
public_id: result.public_id,
url: result.secure_url,
},
});
// Save the clearance to the database
const savedClearance = await clearance.save();
if (!savedClearance) {
return res.status(500).send("The clearance cannot be created");
}
res.send(savedClearance);
} catch (error) {
console.error("Error:", error);
res.status(500).send("An error occurred during clearance creation");
}
});
router.get("/studentClearance", async (req, res) => {
try {
const clearanceList = await Clearance.find().populate({
path: "user",
select: "firstname lastname email grade",
});
console.log("CLEARANCE LIST", clearanceList)
res.status(200).json(clearanceList);
} catch (error) {
console.error("Error fetching clearance items:", error);
res.status(500).json({ message: "Internal server error" });
}
});
router.get("/", async (req, res) => {
try {
const clearanceList = await Clearance.find();
if (!clearanceList || clearanceList.length === 0) {
return res.status(404).json({ message: "No clearance items found" });
}
res.status(200).json(clearanceList);
} catch (err) {
console.error("Error fetching clearance items:", err);
res.status(500).json({ error: err.message });
}
});
router.get("/:id", async (req, res) => {
if (!mongoose.isValidObjectId(req.params.id)) {
return res.status(400).send("Invalid Clearance Id");
}
try {
const clearance = await Clearance.findById(req.params.id).populate("user");
if (!clearance) {
return res.status(404).json({ message: "Clearance not found" });
}
res.status(200).json(clearance);
} catch (err) {
console.error("Error fetching clearance item:", err);
res.status(500).json({ error: err.message });
}
});
// router.get("/userClearance/:id", async (req, res) => {
// try {
// const userId = req.params.id;
// const user = await User.findById(userId);
// if (!user) {
// return res.status(404).json({ message: "User not found" });
// }
// const userClearance = await Clearance.find({ user: userId })
// .populate({
// path: "user",
// })
// console.log(userClearance,"fransssssss")
// res.status(200).json(userClearance);
// } catch (error) {
// console.error("Error fetching user Clearance:", error);
// res.status(500).json({ message: "Internal server error" });
// }
// });
// router.get(`/get/userClearance/:userid`, async (req, res) => {
// const userClearanceList = await Clearance.find({
// user: req.params.userid,
// })
// .populate({
// path: "userClearance",
// populate: {
// path: "clearance",
// },
// })
// .sort({ DateTime: -1 });
// if (!userClearanceList) {
// res.status(500).json({ success: false });
// }
// res.send(userClearanceList);
// });
router.delete("/:id", (req, res) => {
Clearance.findByIdAndRemove(req.params.id)
.then((clearance) => {
if (clearance) {
return res
.status(200)
.json({ success: true, message: "the user is deleted!" });
} else {
return res
.status(404)
.json({ success: false, message: "user not found!" });
}
})
.catch((err) => {
return res.status(500).json({ success: false, error: err });
});
});
router.put("/:id", async (req, res) => {
try {
if (!mongoose.isValidObjectId(req.params.id)) {
return res.status(400).send("Invalid Clearance Id");
}
const clearance = await Clearance.findById(req.params.id);
if (!clearance) {
return res.status(404).send("Clearance not found");
}
clearance.uploadedAt = req.body.uploadedAt;
await clearance.save();
res.json(clearance);
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
// router.get("/userClearance/:id", async (req, res) => {
// try {
// const userId = req.params.id;
// console.log(userId);
// const user = await User.findById(userId);
// console.log(user, "user");
// if (!user) {
// return res.status(404).json({ message: "User not found" });
// }
// const userClearance = await Clearance.find({ user: userId })
// .populate({
// path: "user",
// })
// .populate({
// path: "userClearance",
// populate: { path: "clearance", model: "Clearance" },
// });
// res.status(200).json(userClearance);
// } catch (error) {
// console.error("Error fetching user clearance:", error);
// res.status(500).json({ message: "Internal server error" });
// }
// });
module.exports = router;
|
import React, { useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import LoadingSpinner from "../components/LoadingSpinner";
import { getCollectionByIdUrl } from "../constants/apiUrls";
import axios from "axios";
import { Box } from "@mui/system";
import {
Avatar,
Chip,
Grid,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableRow,
Typography,
} from "@mui/material";
import MDEditor from "@uiw/react-md-editor";
import {
getCollectionManagerRoute,
getItemPageRoute,
getTagSearchRoute,
} from "../constants/appRoutes";
import translate from "../utils/translate";
import Image from "material-ui-image";
const CollectionPage = () => {
const { collectionId } = useParams();
const [collection, setCollection] = useState(null);
const [tableRows, setTableRows] = useState([]);
const navigate = useNavigate();
useEffect(() => {
const fetchCollection = async () => {
const { data } = await axios.get(getCollectionByIdUrl(collectionId));
setTableRows([
{ name: translate("author"), value: data.authorId.email },
{ name: translate("name"), value: data.name },
{ name: translate("topic"), value: data.topic },
]);
setCollection(data);
};
fetchCollection();
}, []);
if (collection === null) {
return <LoadingSpinner />;
}
return (
<Box
sx={{
m: 3,
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 5,
}}
>
<img src={collection.imageUrl} />
<TableContainer component={Paper} sx={{ p: 3 }}>
<Table>
<TableBody>
<TableRow>
<TableCell>
<Typography>{tableRows[0].name}</Typography>
</TableCell>
<TableCell
onClick={() =>
navigate(getCollectionManagerRoute(tableRows[0].value))
}
>
<Typography textAlign="end">{tableRows[0].value}</Typography>
</TableCell>
</TableRow>
{tableRows.slice(1).map(({ name, value }, index) => (
<TableRow key={index}>
<TableCell>
<Typography>{name}</Typography>
</TableCell>
<TableCell>
<Typography textAlign="end">{value}</Typography>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
<Box width={"100%"} display="flex" flexDirection="column" gap={3}>
<Typography variant="h5">{translate("description")}</Typography>
<Paper sx={{ p: 3 }}>
<Typography noWrap>
<MDEditor.Markdown
style={{ background: "inherit" }}
source={collection.description}
/>
</Typography>
</Paper>
</Box>
<Box width={"100%"} display="flex" flexDirection="column" gap={3}>
<Typography variant="h5">{translate("collectionItems")}</Typography>
{collection.items.map(({ name, tags, _id }) => (
<Paper elevation={7} sx={{ padding: 3, width: "100%" }}>
<Grid
container
justifyContent="space-between"
alignItems="center"
gap={3}
flexWrap="wrap"
>
<Grid item>
<Link
to={getItemPageRoute(_id)}
style={{ textDecoration: "none", color: "inherit" }}
>
<Typography>{name}</Typography>
</Link>
</Grid>
<Grid item sm={6}>
<Box
display="flex"
alignItems="end"
justifyContent="end"
gap={1}
flexWrap="wrap"
>
{tags.map((tag, index) => (
<Chip
key={index}
label={tag}
variant="outlined"
onClick={() => {
navigate(getTagSearchRoute(tag));
}}
/>
))}
</Box>
</Grid>
</Grid>
</Paper>
))}
</Box>
</Box>
);
};
export default CollectionPage;
|
import type { Keystore } from "../src";
import { NotFoundError } from "../src";
import { nanoid } from "nanoid";
type KeystoreFactory = <T>() => Promise<{
keystore: Keystore<T>;
dispose: () => Promise<void>;
}>;
export function launchConformanceSuite(factory: KeystoreFactory) {
describe("Keystore api", () => {
interface Stored {
foo: string;
}
let keystore: Keystore<Stored>;
let dispose: () => Promise<void>;
beforeEach(async () => {
({ keystore, dispose } = await factory<Stored>());
});
afterEach(async () => {
await dispose();
});
describe("Saving and retrieving values", () => {
describe("Keystore.get()", () => {
test("throws if item absent", async () => {
const key = nanoid();
try {
await keystore.get(key);
} catch (err) {
expect(err instanceof NotFoundError);
expect((err as NotFoundError).message).toBe(`No such key ${key}`);
}
});
});
});
});
}
|
import { Logger, Module } from '@nestjs/common';
import { MailerService } from './mailer.service';
import { MailerModule as _MailerModule } from '@nestjs-modules/mailer';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { envEnum } from '@common/enum/env.enum';
import { join } from 'path';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';
@Module({
imports: [
_MailerModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (config:ConfigService) => {
const logger = new Logger( MailerModule.name )
let errors:Array<string> = []
if( !config.get<string>( envEnum.MAIL_HOST ) ){
errors.push( envEnum.MAIL_HOST + " required" )
}
if( !config.get<number>( envEnum.MAIL_PORT ) || !Number(config.get<number>(envEnum.MAIL_PORT)) ){
errors.push( envEnum.MAIL_PORT + " required and only number" )
}
if( !config.get<string>( envEnum.MAIL_USER ) ){
errors.push( envEnum.MAIL_USER + " required" )
}
if( !config.get<string>( envEnum.MAIL_PASS ) ){
errors.push( envEnum.MAIL_PASS + " required" )
}
if( !config.get<string>( envEnum.MAIL_DEFAULT ) ){
errors.push( envEnum.MAIL_DEFAULT + " required" )
}
if( errors.length > 0 ){
errors.forEach( e => logger.error( e ) )
throw new Error()
}
return {
transport: {
host: config.get<string>( envEnum.MAIL_HOST ),
port: config.get<number>(envEnum.MAIL_PORT),
auth:{
user: config.get<string>(envEnum.MAIL_USER),
pass: config.get<string>(envEnum.MAIL_PASS)
}
},
defaults: {
from: config.get<string>(envEnum.MAIL_DEFAULT)
},
template: {
dir: join("common", "templates"),
adapter: new HandlebarsAdapter(),
options: {
strict: true
}
}
}
}
})
],
providers: [MailerService],
exports: [
MailerModule,
MailerService
]
})
export class MailerModule {}
|
/**
* @interface IServerResponseOptions
*/
interface IServerResponseOption {
/**
* @description Result of the query
*/
results?: any[];
/**
* @description Extra parameters apart from results
*/
extra?: any[];
/**
* @description Current page number for the response in case of large data
*/
perPage?: number;
/**
* @description Current page number for the response in case of large data
*/
page?: number;
/**
* @description Total count of requested result
*/
total?: number;
}
/**
* @class ServerResponse
*/
class ServerResponse {
/**
* @description True or False depending on success or failure response
*/
public status!: boolean;
/**
* @description Message to respond the user with
* @example Internal Server Error
* @example Created new post
*/
public message!: string;
/**
* @description Result of the query
*/
public results!: any[];
/**
* @description Extra parameters apart from results
*/
public extra!: any[];
/**
* @description Result per page in case of large data
*/
public perPage!: number;
/**
* @description Current page number for the response in case of large data
*/
public page!: number;
/**
* @description Total count of requested result
*/
public total!: number;
/**
* @constructs ServerResponse
* @param {boolean} _status TRUE for success response else FALSE
* @param {string} _message MESSAGE
* @param {IServerResponseOption} options The result of the response
*/
constructor(
_status?: boolean,
_message?: string,
options?: IServerResponseOption
) {
if (_status) this.status = _status;
if (_message) this.message = _message;
if (options?.results) this.results = options.results;
if (options?.extra) this.extra = options.extra;
if (options?.perPage) this.perPage = options.perPage;
if (options?.page) this.page = options.page;
if (options?.total) this.total = options.total;
}
}
export { IServerResponseOption };
export default ServerResponse;
|
#ifndef OBJ_LOADER_H_INCLUDED
#define OBJ_LOADER_H_INCLUDED
#include <glm/glm.hpp>
#include <vector>
#include <string>
struct OBJIndex
{
// -Fields
unsigned int vertexIndex;
unsigned int uvIndex;
unsigned int normalIndex;
// -Methods
bool operator<(const OBJIndex& r) const { return vertexIndex < r.vertexIndex; }
};
class IndexedModel
{
public:
// -Fields
std::vector<glm::vec3> positions;
std::vector<glm::vec2> texCoords;
std::vector<glm::vec3> normals;
std::vector<unsigned int> indices;
// -Methods
/// <summary>
/// Calculate normals.
/// </summary>
void CalcNormals();
};
class OBJModel
{
public:
// -Fields
std::vector<OBJIndex> OBJIndices;
std::vector<glm::vec3> vertices;
std::vector<glm::vec2> uvs;
std::vector<glm::vec3> normals;
bool hasUVs;
bool hasNormals;
OBJModel(const std::string& fileName);
// -Methods
/// <returns>Indexed model.</returns>
IndexedModel ToIndexedModel();
private:
// -Methods
/// <returns>Last vertex index.</returns>
unsigned int FindLastVertexIndex(const std::vector<OBJIndex*>& indexLookup, const OBJIndex* currentIndex, const IndexedModel& result);
/// <summary>
/// Creates obj face.
/// </summary>
void CreateOBJFace(const std::string& line);
glm::vec2 ParseOBJVec2(const std::string& line);
glm::vec3 ParseOBJVec3(const std::string& line);
OBJIndex ParseOBJIndex(const std::string& token, bool* hasUVs, bool* hasNormals);
};
#endif // OBJ_LOADER_H_INCLUDED
|
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { UsersGridComponent } from './users/users-list.component';
import { UserRowComponent } from './users/user-row.component';
import { UserService } from './services/user.service';
import { UserDetailsComponent } from './users/user-details.component';
import { UserDetailsGuard } from './users/user-details.guard';
import { StartPageComponent } from './start/start-page.component';
@NgModule({
declarations: [
AppComponent,
UsersGridComponent,
UserRowComponent,
UserDetailsComponent,
StartPageComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
RouterModule.forRoot([
{ path: 'users', component: UsersGridComponent },
{
path: 'users/:id',
canActivate: [UserDetailsGuard],
component: UserDetailsComponent
},
{ path: 'start', component: StartPageComponent },
{ path: '', component: StartPageComponent, pathMatch: 'full' },
{ path: '**', component: StartPageComponent, pathMatch: 'full' }
])
],
bootstrap: [AppComponent],
providers: [UserService]
})
export class AppModule {}
|
# because all the randomness does not help to concentrate on the shapes I modified Main_shapesExample to this one
# and accept that I need simple shapes that do not choose colors and size themselves,
# and also accept that I have to init those shapes with parameters when creating them.
import pygame
import sys
import random
from pygame.locals import *
from Circle import * # already ailable but the implementation left to you
from Triangle import *
from Square import * # tip: make this a child of rectangle
import pygwidgets
# Set up the constants
WHITE = (255, 255, 255)
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
FRAMES_PER_SECOND = 30
# Set up the window
pygame.init()
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32)
clock = pygame.time.Clock()
circle = Circle(window, "Circle", maxWidth, maxHeight)
square = Square(window, "Square", maxWidth, maxHeight)
triangle = Triangle(window, "Triangle", maxWidth, maxHeight)
shapesList = [circle, square, triangle] # I keep a shapesList but the init of the objects changes, in fact only 3 shapes to start with
# Named calling is using the exact name like Color=Green
# the parameter list for simpleshapes is (window, Width, Height, Color, X, Y) to be filled in here
oStatusLine = pygwidgets.DisplayText(window, (4,4),'Click on shapes', fontSize=28)
# Main loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
# Reverse order to check last drawn shape first
for oShape in shapesList:
if oShape.clickedInside(event.pos):
area = oShape.getArea()
area = str(area)
theType = oShape.getType()
newText = 'Clicked on a ' + theType + ' whose area is ' + area
oStatusLine.setValue(newText)
break # only deal with topmost shape
# Tell each shape to draw itself
window.fill(WHITE)
for oShape in shapesList:
oShape.draw()
oStatusLine.draw()
pygame.display.update()
clock.tick(FRAMES_PER_SECOND)
|
class Solution(object):
def nextPermutation(self, nums):
index=-1 #break point
n=len(nums)
# Step 1: Find the break point:
for i in range(n-2,-1,-1): #iterates from second last to first element
if nums[i]<nums[i+1]:
index=i #i is the break point
break
#if break point does not exist
if index==-1:
nums.reverse()
return nums #we get the first combination
for i in range(n-1,index,-1):
if nums[i]>nums[index]:
nums[i],nums[index]=nums[index],nums[i] #swap with element at break point
break
#reverse right hand side
nums[index+1:]=reversed(nums[index+1:])
return nums
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
|
import { afterAll, beforeAll, describe, expect, test } from "vitest";
import { appRouter } from "../../../../src/server/api/root";
import { prisma } from "../../../../src/server/db";
import {
clearDbsTest,
createInnerTRPCContextWithSessionForTest,
createTestGameObjects,
createTestGames,
createTestTags,
getAllTags,
} from "./helpers";
beforeAll(async () => {
await clearDbsTest(prisma);
await createTestGames(3);
await createTestTags(3);
const testTags = await getAllTags();
await createTestGameObjects({
count: 5,
tags: [testTags[0]!.id],
startIndex: 0,
});
await createTestGameObjects({
count: 5,
tags: [testTags[1]!.id],
startIndex: 5,
});
await createTestGameObjects({
count: 5,
tags: [testTags[2]!.id],
startIndex: 10,
});
await createTestGameObjects({
count: 1,
tags: [testTags[0]!.id, testTags[1]!.id],
startIndex: 15,
});
await createTestGameObjects({
count: 4,
startIndex: 16,
});
});
afterAll(async () => {
await clearDbsTest(prisma);
});
describe("exportData router", () => {
test("export all", async () => {
const ctx = await createInnerTRPCContextWithSessionForTest();
const caller = appRouter.createCaller(ctx);
const { count, gameObjects, games, tags } =
await caller.exportData.exportData({});
expect(count).toBeDefined();
expect(gameObjects).toBeDefined();
expect(games).toBeDefined();
expect(tags).toBeDefined();
});
test("get only games", async () => {
const ctx = await createInnerTRPCContextWithSessionForTest();
const caller = appRouter.createCaller(ctx);
const results = await caller.exportData.exportData({
includeGames: true,
includeGameObjects: false,
includeTags: false,
});
expect(results.count).toBeDefined();
expect(results.gameObjects).toBeUndefined();
expect(results.games).toBeDefined();
expect(results.tags).toBeUndefined();
});
test("get only game-objects", async () => {
const ctx = await createInnerTRPCContextWithSessionForTest();
const caller = appRouter.createCaller(ctx);
const results = await caller.exportData.exportData({
includeGames: false,
includeGameObjects: true,
includeTags: false,
});
expect(results.count).toBeDefined();
expect(results.gameObjects).toBeDefined();
expect(results.games).toBeUndefined();
expect(results.tags).toBeUndefined();
});
test("get only tags", async () => {
const ctx = await createInnerTRPCContextWithSessionForTest();
const caller = appRouter.createCaller(ctx);
const results = await caller.exportData.exportData({
includeGames: false,
includeGameObjects: false,
includeTags: true,
});
expect(results.count).toBeDefined();
expect(results.gameObjects).toBeUndefined();
expect(results.games).toBeUndefined();
expect(results.tags).toBeDefined();
});
test("no tag field for games and game-objects if includeTags=false", async () => {
const ctx = await createInnerTRPCContextWithSessionForTest();
const caller = appRouter.createCaller(ctx);
const results = await caller.exportData.exportData({
includeGames: true,
includeGameObjects: true,
includeTags: false,
});
expect(results.count).toBeDefined();
expect(results.gameObjects).toBeDefined();
expect(results.games).toBeDefined();
expect(results.tags).toBeUndefined();
for (const game of results.games!) {
expect(game.inputTagIds).toBeUndefined();
}
for (const gameObject of results.gameObjects!) {
expect(gameObject.tagIds).toBeUndefined();
}
});
test("tags associated with games and game-objects must be in tag filter list", async () => {
const ctx = await createInnerTRPCContextWithSessionForTest();
const caller = appRouter.createCaller(ctx);
const results = await caller.exportData.exportData({
includeGames: true,
includeGameObjects: true,
includeTags: true,
filterTagIds: "test-tag-id-0,test-tag-id-1",
});
expect(results.count).toBeDefined();
expect(results.gameObjects).toBeDefined();
expect(results.games).toBeDefined();
expect(results.tags).toBeDefined();
for (const game of results.games!) {
expect(game.inputTagIds).not.toContain("test-tag-id-2");
}
for (const gameObject of results.gameObjects!) {
expect(gameObject.tagIds).not.toContain("test-tag-id-2");
}
});
test("can get all game-objects", async () => {
const ctx = await createInnerTRPCContextWithSessionForTest();
const caller = appRouter.createCaller(ctx);
const totalGameObjects = await prisma.gameObject.count();
const results = await caller.exportData.exportData({});
expect(results.count?.gameObjects).toBe(totalGameObjects);
});
test("can exclude untagged game-objects", async () => {
const ctx = await createInnerTRPCContextWithSessionForTest();
const caller = appRouter.createCaller(ctx);
const totalTaggedGameObjects = await prisma.gameObject.count({
where: {
tags: {
some: {},
},
},
});
const results = await caller.exportData.exportData({
filterAllowUntaggedGameObjects: false,
});
expect(results.count?.gameObjects).toBe(totalTaggedGameObjects);
});
test("can get untagged game-objects only", async () => {
const ctx = await createInnerTRPCContextWithSessionForTest();
const caller = appRouter.createCaller(ctx);
const totalUntaggedGameObjects = await prisma.gameObject.count({
where: {
tags: {
none: {},
},
},
});
const results = await caller.exportData.exportData({
filterAllowUntaggedGameObjects: true,
filterTagIds: "",
});
expect(results.count?.gameObjects).toBe(totalUntaggedGameObjects);
});
test("can get games with only tags they use", async () => {
const ctx = await createInnerTRPCContextWithSessionForTest();
const caller = appRouter.createCaller(ctx);
// Update the first `beforeAll` created game to use the first existing tag
const game = await prisma.game.findFirst({});
const tag = await prisma.tag.findFirst({});
await prisma.game.update({
where: {
id: game!.id,
},
data: {
inputTags: {
connect: {
id: tag!.id,
},
},
},
});
// Ensure there are multiple games and tags from the `beforeAll`
const allGames = await prisma.game.findMany({});
const allTags = await prisma.tag.findMany({});
expect(allGames.length).toBeGreaterThan(1);
expect(allTags.length).toBeGreaterThan(1);
// Should only get the first game and first tag, because filterGameIds is set to only the first game's ID
// Since filterTagsMustBeInGames is true, only the associated tag should be returned in the results
let results = await caller.exportData.exportData({
filterTagsMustBeInGames: true,
filterGameIds: game!.id,
});
expect(results.count!.games).toBe(1);
expect(results.count!.tags).toBe(1);
// Ensure the game objects are filtered by the tag when filterTagsMustBeInGames is true
// These game objects are the ones that the game ends up using based on the input tag
const gameObjectsWithFirstTag = await prisma.gameObject.findMany({
where: {
tags: {
some: {
id: tag!.id,
},
},
},
});
expect(results.count!.gameObjects).toBe(gameObjectsWithFirstTag.length);
// If filterTagsMustBeInGames is false, then all tags should be returned regardless of whether they are associated with the filtered game
results = await caller.exportData.exportData({
filterTagsMustBeInGames: false,
filterGameIds: game!.id,
});
expect(results.count!.games).toBe(1);
expect(results.count!.tags).toBe(allTags.length);
});
test("can get game-objects with only tags they use", async () => {
const ctx = await createInnerTRPCContextWithSessionForTest();
const caller = appRouter.createCaller(ctx);
const firstTag = await prisma.tag.findFirst({});
const gameObjectWithOneTag = await prisma.gameObject.create({
data: {
name: "test-game-object",
tags: {
connect: {
id: firstTag!.id,
},
},
},
});
// Ensure there are multiple game-objects and tags from the `beforeAll`
const allGameObjects = await prisma.gameObject.findMany({});
const allTags = await prisma.tag.findMany({});
expect(allGameObjects.length).toBeGreaterThan(1);
expect(allTags.length).toBeGreaterThan(1);
// Should only get the first game-object and first tag, because filterGameObjectIds is set to only the first game-object's ID
// Since filterTagsMustBeInGameObjects is true, only the associated tag should be returned in the results
let results = await caller.exportData.exportData({
filterTagsMustBeInGameObjects: true,
filterGameObjectIds: gameObjectWithOneTag!.id,
includeGames: false,
});
expect(results.count!.gameObjects).toBe(1);
expect(results.count!.tags).toBe(1);
expect(results.tags![0]!.id).toBe(firstTag!.id);
// If filterTagsMustBeInGameObjects is false, then all tags should be returned regardless of whether they are associated with the filtered game-object
results = await caller.exportData.exportData({
filterTagsMustBeInGameObjects: false,
includeGames: false,
});
expect(results.count!.gameObjects).toBe(allGameObjects.length);
expect(results.count!.tags).toBe(allTags.length);
});
});
|
package bun;
import haxe.extern.EitherType;
import js.lib.Promise;
/**
* This Streams API interface provides a standard abstraction for writing
* streaming data to a destination, known as a sink. This object comes with
* built-in back pressure and queuing.
*/
extern class WritableStream<T> {
public var locked(default, never):Bool;
public function abort(?reason:Any):js.lib.Promise<Void>;
public function close():js.lib.Promise<Void>;
public function getWriter(?encoding:String, ?mode:String):Dynamic<T>;
public function new(?underlyingSink:UnderlyingSink<T>, ?strategy:QueuingStrategy<T>);
}
typedef UnderlyingSink<T = Any> = {
abort:(?reason:Any) -> EitherType<Void, Promise<Void>>,
close:() -> EitherType<Void, Promise<Void>>,
start:(controller:WritableStreamDefaultController) -> Any,
write:(chunk:T, controller:WritableStreamDefaultController) -> EitherType<Void, Promise<Void>>
};
typedef WritableStreamDefaultController = {
?error:(?error:Any) -> Void
};
|
/*******************************************************************************
* Sketch name: TVOC and CO2 measurement and Blynk MQTT broker with email
* Description: Extend Listing 9-1 to include MQTT broker and email
* Created on: September 2023
* Author: Neil Cameron
* Book: ESP32 Communication
* Chapter : 9 - MQTT
******************************************************************************/
#define BLYNK_TEMPLATE_ID "xxxx" // change xxxx to Template details
#define BLYNK_TEMPLATE_NAME "Listing 92 template"
#define BLYNK_AUTH_TOKEN "xxxx" // change xxxx to Authentication token
#define BLYNK_PRINT Serial
#include <Wire.h> // include Wire and
#include <ccs811.h>; // CCS811 libraries
#include <BlynkSimpleEsp32.h> // Blynk MQTT library
#include <ssid_password.h> // file with logon details
CCS811 ccs811(19); // CCS811 nWAKE on GPIO 19
uint16_t CO2, TVOC, errstat, rawdata;
int LEDpin = 2; // LED as activity indicator
int LEDMQTTpin = 4; // LED controlled with MQTT
int count = 0, countDown = 200;
unsigned long LEDtime = 0, countTime;
unsigned long lag;
int flag = 0;
BlynkTimer timer;
void timerEvent()
{
ccs811.read(&CO2, &TVOC, &errstat, &rawdata); // read CCS811 sensor data
if(errstat == CCS811_ERRSTAT_OK) // given valid readings
{
count++; //increment reading counter
countDown = 60;
countTime = millis(); // set countdown time
Blynk.virtualWrite(V3, CO2); // send data to MQTT
Blynk.virtualWrite(V4, TVOC);
Blynk.virtualWrite(V6, count);
Blynk.virtualWrite(V7, countDown);
Serial.printf("count %d CO2 ", count);
Serial.println(CO2);
LEDtime = millis();
digitalWrite(LEDpin, HIGH); // turn on indicator LED
} // turn off LED after 100ms
if(millis() - LEDtime > 100) digitalWrite(LEDpin, LOW);
if(millis() - countTime > 5000) // countdown interval 5s
{
countTime = millis(); // update countdown time
countDown = countDown - 5; // update countdown
Blynk.virtualWrite(V7, countDown); // send to MQTT
}
}
BLYNK_WRITE(V0) // Blynk virtual pin 0
{
digitalWrite(LEDMQTTpin, param.asInt()); // turn on or off LED
}
BLYNK_CONNECTED() // function called when ESP32 connected
{
Serial.println("ESP32 connected to Blynk");
}
void setup()
{
Serial.begin(115200); // initiate Blynk MQTT
Blynk.begin(BLYNK_AUTH_TOKEN, ssidEXT, password, "blynk.cloud", 80);
timer.setInterval(1000, timerEvent); // timer event called every 1s
pinMode(LEDpin, OUTPUT); // define LED pins as output
digitalWrite(LEDpin, LOW); // turn off LEDs
pinMode(LEDMQTTpin, OUTPUT);
digitalWrite(LEDMQTTpin, LOW);
Wire.begin(); // initialise I2C
ccs811.begin(); // initialise CCS811
ccs811.start(CCS811_MODE_60SEC); // set reading interval at 60s
}
void loop()
{
Blynk.run(); // maintains connection to Blynk
timer.run(); // Blynk timer
if(millis() - lag > 1000) // at one second intervals
{
if(CO2 > 1500 && flag == 0) // when CO2 level > threshold
{ // and email not sent already
digitalWrite(LEDMQTTpin, HIGH); // turn on LED and virtual LED
Blynk.virtualWrite(V0, 1); // call Blynk event called alert
Blynk.logEvent("alert", "CO2 above 1500: " + String(CO2));
flag = 1; // flag indicates event triggered
}
else if(CO2 < 1500 && flag == 1) // when CO2 < threshold
{ // after sending email
flag = 0; // reset event flag
}
lag = millis(); // update time counter
}
}
|
#include "Input.h"
#include <cassert>
Input* Input::m_pInstance = nullptr;
Input::Input()
{
}
void Input::Init()
{
assert(m_pInstance == nullptr);
m_pInstance = new Input();
}
Input* Input::Instance()
{
return m_pInstance;
}
void Input::Close()
{
if (m_pInstance)
{
delete m_pInstance;
m_pInstance = nullptr;
}
}
void Input::ProcessEvents()
{
m_KeysDown.reset();
m_KeysUp.reset();
memset(m_aMouseButtonsDown.data(), false, m_aMouseButtonsDown.size());
memset(m_aMouseButtonsUp.data(), false, m_aMouseButtonsUp.size());
static SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
switch (e.type)
{
case SDL_KEYDOWN: OnKeyDown(e);
break;
case SDL_KEYUP: OnKeyUp(e);
break;
case SDL_MOUSEMOTION: OnMouseMove(e);
break;
case SDL_MOUSEBUTTONDOWN: OnMouseButtonDown(e);
break;
case SDL_MOUSEBUTTONUP: OnMouseButtonUp(e);
break;
case SDL_QUIT: m_bWishQuit = true;
break;
}
}
}
/*
* Getters
*/
#pragma region Getters
bool Input::GetMouseButton(uint8_t nMouseButton)
{
return m_aMouseButtonsState[nMouseButton];
}
bool Input::GetMouseButtonDown(uint8_t nMouseButton)
{
return m_aMouseButtonsDown[nMouseButton];
}
bool Input::GetMouseButtonUp(uint8_t nMouseButton)
{
return m_aMouseButtonsUp[nMouseButton];
}
float Input::GetMouseWheelDelta()
{
return m_nScrollDelta;
}
SDL_Point Input::GetMousePos()
{
return { m_nMouseX, m_nMouseY };
}
int Input::GetMouseX()
{
return m_nMouseX;
}
int Input::GetMouseY()
{
return m_nMouseY;
}
bool Input::GetKey(E_Keys nMouseButton)
{
return m_KeysState[static_cast<int>(nMouseButton)];
}
bool Input::GetKeyDown(E_Keys nMouseButton)
{
return m_KeysDown[static_cast<int>(nMouseButton)];
}
bool Input::GetKeyUp(E_Keys nMouseButton)
{
return m_KeysUp[static_cast<int>(nMouseButton)];
}
bool Input::GetShift()
{
return m_KeysState[static_cast<int>(E_Keys::ShiftL)] || m_KeysState[static_cast<int>(E_Keys::ShiftR)];
}
bool Input::GetCtrl()
{
return m_KeysState[static_cast<int>(E_Keys::CtrlL)] || m_KeysState[static_cast<int>(E_Keys::CtrlR)];
}
bool Input::GetAlt()
{
return m_KeysState[static_cast<int>(E_Keys::AltL)] || m_KeysState[static_cast<int>(E_Keys::AltR)];
}
bool Input::WishQuit()
{
return m_bWishQuit;
}
void Input::ForceQuit()
{
m_bWishQuit = true;
}
#pragma endregion
/*
* Handlers
*/
#pragma region Handlers
void Input::OnKeyDown(const SDL_Event& e)
{
m_KeysState[e.key.keysym.scancode] = 1;
m_KeysDown[e.key.keysym.scancode] = 1;
}
void Input::OnKeyUp(const SDL_Event& e)
{
m_KeysState[e.key.keysym.scancode] = 0;
m_KeysUp[e.key.keysym.scancode] = 1;
}
void Input::OnMouseMove(const SDL_Event& e)
{
SDL_GetMouseState(&m_nMouseX, &m_nMouseY);
}
void Input::OnMouseButtonDown(const SDL_Event& e)
{
m_aMouseButtonsState[e.button.button-1] = true;
m_aMouseButtonsDown[e.button.button-1] = true;
}
void Input::OnMouseButtonUp(const SDL_Event& e)
{
m_aMouseButtonsState[e.button.button-1] = false;
m_aMouseButtonsUp[e.button.button-1] = true;
}
void Input::OnMouseScroll(const SDL_Event& e)
{
m_nScrollDelta = e.wheel.preciseY;
}
#pragma endregion
|
package Day9_JSEScroll_Cookies_Files;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.Cookie;
import utilities.BaseTest;
import java.util.Set;
public class C04_Cookies extends BaseTest {
@Test
public void cookies() {
/*
1-Go to URL: https://kitchen.applitools.com/ingredients/cookie
2-Get cookie.
3-Find the total number of cookies.
4-Print all the cookies.
5-Add cookies.
6-Edit cookies.
7-Delete Cookies
8-Delete All Cookies.
*/
driver.get("https://kitchen.applitools.com/ingredients/cookie");
System.out.println("test get cookie");
Cookie cookie=driver.manage().getCookieNamed("protein");// cookie'yi isimle çağırmış olduk
Assert.assertEquals("chicken", cookie.getValue());
//Find the total number of cookies.
Set<Cookie> allCookies=driver.manage().getCookies();
int numofcookies=allCookies.size();
System.out.println("numofcookies = "+numofcookies);
//Print all the cookies.
for (Cookie each:allCookies){
System.out.println("each cookie :"+ each);
System.out.println("each cookie name:"+each.getName());
System.out.println("each cookie value:"+each.getValue());
}
//Add cookie.
System.out.println("add cookie");
Cookie cookie1=new Cookie("fruit","apple"); // cookie oluşturduk.
driver.manage().addCookie(cookie1);
Assert.assertEquals("eşleşme olmadı.",cookie1.getValue(),driver.manage().getCookieNamed(cookie1.getName()).getValue());
allCookies=driver.manage().getCookies(); // sayfada varolan cookie'leri döndürür.
System.out.println("son toplam cookies sayısı:"+allCookies.size()); // cookieler eklendikten sonraki sayısı.
Cookie editedCookie=new Cookie(cookie1.getName(),"mango");
driver.manage().addCookie(editedCookie);
Assert.assertEquals(editedCookie.getValue(),driver.manage().getCookieNamed(cookie1.getName()).getValue());
System.out.println(driver.manage().getCookieNamed(cookie1.getName()).getValue()); //mango
}
@Test
public void deleteCookies() {
driver.get("https://kitchen.applitools.com/ingredients/cookie");
Set<Cookie> allCookies=driver.manage().getCookies();
int numofcookies=allCookies.size();
System.out.println("numofcookies = "+numofcookies);//num of cookies=2
Cookie addedCookies=new Cookie("drinks","ayran"); //cookie oluşturduk.
driver.manage().addCookie(addedCookies); //cookie ekledik
allCookies =driver.manage().getCookies(); //sayfada var olan cookieleri döndürür.
System.out.println("allcookies:"+allCookies.size());//all cookies=3
System.out.println("delete cookies");
driver.manage().deleteCookie(addedCookies); // cookie sildik.
Assert.assertNull("cookie halen var",driver.manage().getCookieNamed(addedCookies.getName()));
allCookies =driver.manage().getCookies(); //sayfada var olan cookieleri döndürür.
System.out.println("allcookies:"+allCookies.size());//2
driver.manage().deleteAllCookies(); // browser'dan hepsi silinecek.
allCookies =driver.manage().getCookies(); //sayfada var olan cookieleri döndürür.
System.out.println("allcookies:"+allCookies.size()); //all cookies= 0
}
}
|
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
# Generate log-normally distributed data
np.random.seed(0)
data = np.random.lognormal(mean=0, sigma=1, size=1000) # mean=0, std=1
# Fit log-normal distribution using statsmodels
kde = sm.nonparametric.KDEUnivariate(np.log(data))
kde.fit()
# Plotting
plt.figure(figsize=(10, 6))
plt.hist(data, bins=30, density=True, alpha=0.5, label='Data')
plt.plot(np.exp(kde.support), kde.density / np.exp(kde.support), lw=2, label='PDF')
plt.title('Log-Normal Distribution')
plt.xlabel('X')
plt.ylabel('Density')
plt.legend()
plt.show()
|
import json
from data.config import REQUEST_HEADERS, MAX_INLINE_KEYBOARD_LENGTH
from data.urls import STUDENT_SCHEDULE_URL
import httpx
async def get_students_data(user_id: int, students_url: str) -> tuple:
"""
:param user_id: Telegram user id.
:param students_url: Url to search for the alleged students.
Example: https://www.asu.ru/timetable/search/students/?query=404.
:return:
Tuple:
Bool: True - if count of alleged students over MAX_INLINE_KEYBOARD_LENGTH.
Dict: The key - group number, the value is a list of the group name and a link to it.
If an error occurs, then an empty dictionary.
"""
over_max_length, students_data = False, {}
try:
async with httpx.AsyncClient() as client:
response = await client.get(url=students_url, headers=REQUEST_HEADERS, params={'chat_id': user_id})
except (httpx.HTTPError, httpx.RequestError, httpx.TimeoutException):
return over_max_length, students_data
try:
data = response.json()
groups = data.get('groups')
rows = groups.get('rows')
# Checking for the number of matches found with the name of the alleged student.
if not rows:
return over_max_length, students_data
# Checking for an acceptable threshold for the number of possible alleged students.
if rows > MAX_INLINE_KEYBOARD_LENGTH:
return True, students_data
records = groups.get('records')
for i, record in enumerate(records):
students_data[i] = {
'name': record.get('groupCode'),
'url': STUDENT_SCHEDULE_URL.format(record.get('path'))
}
return over_max_length, students_data
except (json.JSONDecodeError, KeyError, AttributeError, TypeError, FileNotFoundError, IOError):
return over_max_length, students_data
|
@extends('layouts.admin.master')
@section('content')
@php
$titles=[
'title' => "Truck",
'sub-title' => "Edit",
'btn' => "Trucks List",
'url' => route('admin.truck')
];
@endphp
@include('admin.components.top-bar', $titles)
<div class="post d-flex flex-column-fluid" id="kt_post">
<div id="kt_content_container" class="container-xxl">
<!--begin::Alert-->
@include('admin.components.alerts')
<!--end::Alert-->
<div class="d-flex flex-column flex-lg-row">
<div class="flex-lg-row-fluid mb-10 mb-lg-0 me-lg-7 me-xl-10">
<div class="card">
<div class="card-body p-12">
<form action="{{ route('admin.truck.update') }}" method="POST">
@csrf
<input type="hidden" name="id" value="{{ $truck->id }}">
<div class="d-flex flex-column align-items-start flex-xxl-row">
<div class="d-flex flex-center flex-equal fw-row text-nowrap order-1 order-xxl-2 me-4">
<span class="fs-2x fw-bolder text-gray-800">Edit Truck</span>
</div>
</div>
<div class="separator separator-dashed my-10"></div>
<div class="form-body">
<h4 class="form-section mb-8 fs-2">Truck Details</h4>
<div class="row">
<div class="form-group col-md-6 mb-7">
<label>Truck Number <sup class="text-danger">*</sup></label>
<input type="text" name="truck_number" value="{{ $truck->truck_number }}" class="form-control form-control-solid @error('truck_number') is-invalid border-danger @enderror" placeholder="Truck Number..." required>
</div>
<div class="form-group col-md-6 mb-7">
<label>Truck Type <sup class="text-danger">*</sup></label>
<select name="truck_type" class="form-control form-select form-select-solid @error('truck_type') is-invalid border-danger @enderror" data-control="select2" data-placeholder="Select Truck Type" required>
<option value="">Select Truck Type</option>
<option value="1" @if($truck->type_id == 1) selected @endif>Truck</option>
<option value="2" @if($truck->type_id == 2) selected @endif>Trailer</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-6 mb-7">
<label>Current Location <sup class="text-danger">*</sup></label>
<input type="text" id="truckLocation" value="{{ $truck->city->name.', '.$truck->city->state->name }}" data-selected="{{ $truck->city->id }}" class="form-control form-control-solid" placeholder="Search City..." autocomplete="off" required>
</div>
<div class="form-group col-md-6 mb-7">
<label>Last Inspection Date</label>
<input type="date" name="last_inspection" value="{{ $truck->last_inspection }}" class="form-control form-control-solid @error('last_inspection') is-invalid border-danger @enderror">
</div>
</div>
<div class="row">
<div class="form-group col-md-6 mb-7">
<label>VIN</label>
<input type="text" name="vin_number" value="{{ $truck->vin_number }}" class="form-control form-control-solid @error('vin_number') is-invalid border-danger @enderror" placeholder="Vehicle Identity Number...">
</div>
<div class="form-group col-md-6 mb-7">
<label>Plate Number</label>
<input type="text" name="plate_number" value="{{ $truck->plate_number }}" class="form-control form-control-solid @error('plate_number') is-invalid border-danger @enderror" placeholder="Plate Number...">
</div>
</div>
<div class="row">
<div class="form-group col-md-6 mb-7">
<label>Ownership Type</label>
<select name="ownership" class="form-control form-select form-select-solid @error('ownership') is-invalid border-danger @enderror" data-control="select2" data-placeholder="Select Ownership Type">
<option value="">Select Ownership Type</option>
<option value="Company Owned" @if($truck->ownership == 'Company Owned') selected @endif>Company Owned</option>
<option value="Owner Operated" @if($truck->ownership == 'Owner Operated') selected @endif>Owner Operated</option>
</select>
</div>
<div class="form-group col-md-6 mb-7">
<label>Status <sup class="text-danger">*</sup></label>
<select name="status" class="form-control form-select form-select-solid @error('status') is-invalid border-danger @enderror" data-control="select2" data-placeholder="Select Status" required>
<option value="">Select Status</option>
<option value="1" @if($truck->status == 1) selected @endif>Active</option>
<option value="0" @if($truck->status == 0) selected @endif>Inactive</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 mb-7">
<label>Note</label>
<textarea name="note" class="form-control form-control-solid @error('note') is-invalid border-danger @enderror" rows="5" placeholder="Any details here..." maxlength="255">{!! $truck->note !!}</textarea>
</div>
</div>
<div class="row">
<div class="form-group mx-auto form-group col-12 mt-3 mb-2">
<button type="submit" class="btn btn-info" id="kt_invoice_submit_button">
Update
<span class="svg-icon svg-icon-3">{!! getSvg('art005') !!}</span>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
@section('scripts')
<!-- Toaster Alerts -->
@include('admin.components.toaster')
<script>
let pluginOptions = {
name: 'city_id',
url: "{{ route('resource.search-city') }}"
};
$(function(){
$('#truckLocation').liveSearch(pluginOptions, response => {
return `${ response.city }, ${ response.state }`;
});
});
</script>
@endsection
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strmapi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kmohamma <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/07 15:01:59 by kmohamma #+# #+# */
/* Updated: 2019/06/10 13:39:35 by kmohamma ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strmapi(char const *s, char (*f) (unsigned int, char))
{
char *new;
unsigned int i;
if (!s)
return (NULL);
i = 0;
if (!(new = (char*)malloc(ft_strlen(s) + 1)))
return (NULL);
while (s[i])
{
new[i] = (*f)(i, s[i]);
i++;
}
new[i] = '\0';
return (new);
}
|
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:why_park/application/account/model/user_account_model.dart';
import 'package:why_park/application/account/user_registry_application_service.dart';
import 'package:why_park/edge/resources/user_resource.dart';
import 'package:why_park/edge/session_storage/session_storage.dart';
import '../http/custom_http_client.dart';
class UserAuthApplicationServiceRemoteAdapter
implements UserAuthApplicationService {
UserAuthApplicationServiceRemoteAdapter(
this._sessionStorage, this._httpClient);
final SessionStorage _sessionStorage;
final CustomHttpClient _httpClient;
@override
Future<void> loginWithEmailAndPassword(final UserAccountModel model) async {
try {
final userCredential = await FirebaseAuth.instance
.signInWithEmailAndPassword(
email: model.email, password: model.password);
User? user = userCredential.user;
user != null
? await _sessionStorage.saveSession(user.uid)
: throw Exception();
user.email != null
? await _sessionStorage.saveEmail(user.email!)
: throw Exception();
} catch (e) {
throw Exception('loginWithEmailAndPassword.error: $e');
}
}
@override
Future<void> signUpWithEmailAndPassword(final UserAccountModel model) async {
try {
UserCredential userCredential =
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: model.email,
password: model.password,
);
User? user = userCredential.user;
user?.email != null
? await _sessionStorage.saveEmail(user!.email!)
: throw Exception();
await _sessionStorage.saveUserName(user.email!, model.name);
final UserResource userResource =
UserResource(model.name, user.email!, '12345678910', user.uid);
final response = await _httpClient.post(
'/api_producer/cliente', userResource.toJson());
await _sessionStorage.saveClientId(response.body['id'].toString());
} catch (e) {
throw Exception('signUpWithEmailAndPassword.error: $e');
}
}
@override
Future<void> loginWithGoogle() async {
const List<String> scopes = <String>[
'email',
'https://www.googleapis.com/auth/contacts.readonly',
];
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: scopes,
);
final googleData = await _googleSignIn.signIn();
}
}
|
import "dotenv/config";
import { ChatMessageHistory } from "@langchain/community/stores/message/in_memory";
import { Chroma } from "@langchain/community/vectorstores/chroma";
import { StringOutputParser } from "@langchain/core/output_parsers";
import {
RunnablePassthrough,
RunnableSequence,
RunnableWithMessageHistory,
} from "@langchain/core/runnables";
import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { pull } from "langchain/hub";
// get the env var COLLECTION_NAME from the .env file
const COLLECTION_NAME = process.env.COLLECTION_NAME;
/**
* Represents the vector store containing recipes.
* There are many options for implementing a retriever, including using a database or a vector store.
* For this example, I'm using ChromaDB as the vector store.
* See more: https://js.langchain.com/docs/modules/data_connection/retrievers/
*/
const vectorStore = await Chroma.fromExistingCollection(
new OpenAIEmbeddings(),
{ collectionName: COLLECTION_NAME }
);
const retriever = vectorStore.asRetriever();
// const ANSWER_CHAIN_SYSTEM_TEMPLATE = `
// You are a world-class recipe bot equipped to handle queries related to recipes, ingredients, cooking methods, and dietary restrictions. If the provided context does not contain sufficient data to answer a question directly, guide the user towards what you can assist with or suggest how they might provide additional relevant information.
// <context>
// {context}
// </context>`;
// const answerGenerationChainPrompt = ChatPromptTemplate.fromMessages([
// // give the system a prompt to generate an answer
// ["system", ANSWER_CHAIN_SYSTEM_TEMPLATE],
// // provide chat history, so the system can generate an answer based on the context
// new MessagesPlaceholder("chat_history"),
// // direct it to answer the user's question given the users input
// [
// "human",
// "Using the given context and chat history, please address the following inquiry:\n{input}",
// ],
// ]);
// const REPHRASE_QUESTION_SYSTEM_TEMPLATE = `
// Your task is to formulate a concise and effective query for a vector database search to find documents relevant to the user's recipe-related inquiry. Use the conversation details to align the query with the user's needs.
// Follow these steps:
// 1. Examine the provided 'chat_history', focusing on exchanges related to the user's recipe interest. Note any specific dish names, ingredients, or cooking methods mentioned.
// 2. Identify the main recipe or food type the user is inquiring about from the chat history.
// 3. Refine the user's follow-up question to improve clarity and search precision. Preserve the original intent but enhance the wording to align better with typical search terminologies.
// 4. Generate and output only the query that will be used for the search, detailing any assumptions made due to ambiguous or incomplete information in the chat.
// Here are a few examples to guide you:
// Example 1:
// Human: "I'm looking for a simple vegetarian pasta dish."
// Human: "Something quick for dinner?"
// AI: "Quick vegetarian pasta dinner recipes"
// Example 2:
// Human: "I want to bake a chocolate cake for my friend's birthday."
// Human: "How to make it more moist?"
// AI: "Moist chocolate cake recipe tips"
// Example 3:
// Human: "I'm trying to find a low-carb breakfast option."
// Human: "Preferably something with eggs?"
// AI: "Low-carb egg breakfast recipes"
// chat_history:
// `;
// const rephraseQuestionChainPrompt = ChatPromptTemplate.fromMessages([
// ["system", REPHRASE_QUESTION_SYSTEM_TEMPLATE],
// new MessagesPlaceholder("chat_history"),
// ["human", "Follow-Up Question: {input}"],
// ]);
// Pull the prompts from the hub
const answerGenerationChainPrompt = await pull(
"kenzic/recipe-answer-generation-prompt"
);
// Pull the prompts from the hub
const rephraseQuestionChainPrompt = await pull(
"kenzic/recipe-rephrase-user-prompt"
);
const rephraseQuestionChain = RunnableSequence.from([
rephraseQuestionChainPrompt,
new ChatOpenAI({ temperature: 0.1, modelName: "gpt-3.5-turbo" }),
new StringOutputParser(),
]);
/**
* Converts an array of documents to a string representation.
* Note: I wrap the page content in a <doc> tag to make it easier for the LLM to understand the boundaries of each document.
*
* @param {Array} documents - The array of documents to convert.
* @returns {string} The string representation of the documents.
*/
const convertDocsToString = (documents) => {
return documents
.map((document) => {
return `<doc>\n${document.pageContent}\n</doc>`;
})
.join("\n");
};
/**
* Represents a chain of functions used for document retrieval.
*
* @description The `documentRetrievalChain` variable is an instance of the `RunnableSequence` class.
* It represents a chain of functions that are executed sequentially to retrieve documents.
* Each function in the chain performs a specific task related to document retrieval.
* In this case, the chain consists of three functions:
* 1. A function that extracts the input from the previous step.
* 2. A function that retrieves documents from a database based on the input.
* 3. A function that converts the retrieved documents into a string format.
*
* For more on `RunnableSequence`, see https://js.langchain.com/docs/expression_language/how_to/routing
*
*/
const documentRetrievalChain = RunnableSequence.from([
(input) => input.question,
retriever,
convertDocsToString,
]);
/**
* Represents a chain of operations for conversational retrieval.
* This chain is responsible for:
* 1. Rephrasing the user's question
* 2. Retrieving relevant documents (ChromaDB in this instance)
* 3. Generating an answer to the user's question
* 4. Parsing the answer to string
*/
const conversationalRetrievalChain = RunnableSequence.from([
RunnablePassthrough.assign({
question: rephraseQuestionChain,
}),
RunnablePassthrough.assign({
context: documentRetrievalChain,
}),
answerGenerationChainPrompt,
new ChatOpenAI({ modelName: "gpt-3.5-turbo" }),
new StringOutputParser(),
]);
// This is where you will store your chat history.
// For a production app you probably want to use a database.
// https://js.langchain.com/docs/integrations/chat_memory
const messageHistory = new ChatMessageHistory();
// Create your `RunnableWithMessageHistory` object, passing in the
// runnable created above.
export const withHistory = new RunnableWithMessageHistory({
runnable: conversationalRetrievalChain,
getMessageHistory: (_sessionId) => messageHistory,
inputMessagesKey: "input",
// This shows the runnable where to insert the history.
// We set to "chat_history" here because of our MessagesPlaceholder.
historyMessagesKey: "chat_history",
});
|
<?php
namespace App\Notifications\Customer;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Models\Order;
use App\Notifications\CustomChannels\TwilioChannel;
class OrderRescheduled extends Notification implements ShouldQueue
{
use Queueable;
protected $order;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct(Order $order)
{
$this->order = $order;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
$channels = ['database'];
if ( method_exists($notifiable, 'subscribedNotificationChannels') ){
$channels = array_merge( $channels, $notifiable->subscribedNotificationChannels() );
}
$finalChannels = array_unique( $channels );
return $finalChannels;
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)->subject('CanaryClean Appointment Reschedule')
->markdown('email.customer.order-rescheduled', [ 'order' => $this->order]);
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
'order_id' => $this->order->id,
];
}
/*
* should return array with keys ( phone, body )
*/
public function toTwilio($notifiable)
{
$url = route('customer.appointment.index', ['selectedDate' => $this->order->cleaning_datetime->toDateString() ]);
$phone = config('app.country_prefix_for_phone_number').(string)$notifiable->contact_number;
$message = "CanaryClean Appointment Reschedule\n\n";
$message .= "Hello ".ucwords($this->order->user->name).", Your booking has been rescheduled. Please see your Appointment schedule below.";
$message .= "\n\nBooking Time: ".$this->order->cleaning_datetime->format('F, l d,Y | h:i A');
$message .= "\n\nView appointment: $url\n\nRegards\n".config('app.name');
return [
'phone' => $phone,
'body' => $message,
];
}
}
|
import numpy as np
import yaml
import pathlib
import os
def save_intrinsics_to_yaml(out_file, cam_id, model, frame_size, matrix, distortion):
'''
Save camera instrinsics to a yaml file.
'''
# Find the number of distortion coefficients, this is the number of elements after which all remaining elements are zero.
if np.max(distortion) == 0:
nr_dist_coeffs = 0
else:
nr_dist_coeffs = np.max(np.where(distortion!=0)[1]) + 1
assert matrix.shape == (3, 3)
data = {
'image_width': frame_size[0],
'image_height': frame_size[1],
'camera_name': cam_id,
'camera_matrix': {
'rows': 3,
'cols': 3,
'data': matrix.flatten().tolist()
},
'distortion_model': model,
'distortion_coefficients': {
'rows': 1,
'cols': int(nr_dist_coeffs),
'data': distortion.flatten()[:nr_dist_coeffs].tolist()
}
}
yaml.dump(data, open(out_file, 'w'), sort_keys=False)
return
def load_intrinsics_from_yaml(in_file):
'''
Load camera instrinsics from a yaml file.
'''
with open(in_file, 'r') as f:
calib = yaml.safe_load(f)
cam_id = calib['camera_name']
cam_model = calib['distortion_model']
matrix = np.asarray(calib['camera_matrix']['data']).reshape([3,3])
distortion = np.asarray(calib['distortion_coefficients']['data'])
frame_size = (calib['image_width'], calib['image_height'])
return cam_id, frame_size, matrix, distortion, cam_model
def save_transform_to_yaml(out_file, data):
'''
Save a 4x4 homogeneous transformation matrix to a yaml file.
'''
assert data.shape == (4, 4)
yaml.dump(data.tolist(), open(out_file, 'w'), sort_keys=False)
return
def load_transform_from_yaml(in_file):
'''
Load a 4x4 homogeneous transformation matrix from a yaml file.
'''
with open(in_file, 'r') as f:
data = yaml.safe_load(f)
return np.asarray(data)
def fetch_recent_intrinsics_path(cam_id='mounted_camera'):
'''
Fetch the path of the most recent camera intrinsics from the config directory.
If not available, return None.
'''
config_dir = str(pathlib.Path(__file__).parent.parent.parent.resolve()) + '/config' # this is the default location where camera intrinsics are saved
matching_files = sorted([entry for entry in os.listdir(config_dir) if 'camera_info' in entry and cam_id in entry]) # find all calibration data for the specified camera ID
if len(matching_files) > 0:
most_recent_calib = matching_files[-1] # if there is one or more, select the most recent
cam_calib_file = os.path.join(config_dir, most_recent_calib) # get the full file path for the most recent calibration file
if os.path.exists(cam_calib_file):
# double check if file is available
return cam_calib_file
# if no file is available, return None
return None
def fetch_recent_base_transform_path():
'''
Fetch the path of the most recent calibrated transform between the pattern origin (world) and the robot base.
If not available, return None.
'''
config_dir = str(pathlib.Path(__file__).parent.parent.parent.resolve()) + '/config' # this is the default location where calibrated transfroms are saved
matching_files = sorted([entry for entry in os.listdir(config_dir) if 'pattern2base' in entry]) # find all calibration data for the specified camera ID
if len(matching_files) > 0:
most_recent_calib = matching_files[-1] # if there is one or more, select the most recent
t_file = os.path.join(config_dir, most_recent_calib) # get the full file path for the most recent calibration file
if os.path.exists(t_file):
# double check if file is available
return t_file
# if no file is available, return None
return None
|
import React, {FC} from "react";
import {
Button,
Card,
CardBody,
CardFooter,
CardHeader,
Heading,
Menu,
MenuButton, MenuItem, MenuList,
Stack,
Text, Tooltip
} from "@chakra-ui/react";
import styles from "./MyCard.module.css";
import {ModalBooking} from "@/shared/ui/ModalBooking/ModalBooking";
import MyBadge from "@/shared/ui/MyBadge/MyBage";
import {useLocation} from "react-router-dom";
import {statusesBookings} from "@/app/constants";
import {usePutBooking} from "@/app/api/queries/booking/usePutBooking";
import {useTranslation} from "react-i18next";
import {useLocalization} from "@/feature/MyLocalization/hooks/useLocalization";
import {currentPrice} from "@/app/helpers";
interface Props {
name: string;
description?: string;
rate?: number;
mb?: string;
isAdmin?: boolean
}
export const MyCard: FC<Props> = ({name, description, rate, isAdmin= false}) => {
const {t} = useTranslation();
return (
<Card marginLeft={0} className={styles.MyCard}>
<CardHeader>
<Heading as='h4' size="md">{name}</Heading>
</CardHeader>
<CardBody>
{description &&
<Text>
{description}
</Text>
}
{
isAdmin &&
<Heading marginTop={2} as={'h4'} size={'md'}>
Admin
</Heading>
}
</CardBody>
{ rate && <CardFooter>
<Heading as="h6" size="xs">{t('rate') + ':' + rate}</Heading>
</CardFooter>
}
</Card>
)
}
interface PropsTour extends Props {
id?: string,
price: number,
address: string,
city: string,
places: number,
name: string,
description: string,
rate: number,
time: string,
remainingPlaces: number
}
export const MyTourCard: FC<PropsTour> = (
{
id,
description,
rate,
places,
address,
city,
name,
price,
time,
remainingPlaces,
mb
}) => {
const {pathname} = useLocation()
const { t } = useTranslation()
const {locale} = useLocalization()
return (
<Card marginLeft={0} className={styles.MyCard} mb={mb}>
<CardHeader>
<Heading as='h4' size="md">{name}</Heading>
</CardHeader>
<CardBody>
{description &&
<Text>
{description}
</Text>
}
<Text>
{t('numberOfSeats') + ':' + places}
</Text>
<Text>
{t('placesLeft') + ':' + remainingPlaces}
</Text>
<Text>
{t('address') + ':' + address}
</Text>
<Text>
{t('city') + ':' + city}
</Text>
<Text>
{t('time') + ':' + time}
</Text>
</CardBody>
<CardFooter>
<Stack style={{width: '100%'}} direction={'column'}>
{rate && <Heading as="h6" size="xs">
{t('rate') + ':' + rate}
</Heading>}
<Text>
{ t('price') + ':' + currentPrice(price, locale) }
</Text>
{!pathname.includes('admin') &&
<ModalBooking tour={{
id,
description,
rate,
places,
address,
remainingPlaces,
city,
name,
price,
time,
}}
/>
}
</Stack>
</CardFooter>
</Card>
)
}
interface IBookingProps {
booking: any
mb?: string
}
export const MyBookingCard: FC<IBookingProps> = ({booking, mb}) => {
const {t} = useTranslation();
const {put} = usePutBooking()
const {pathname} = useLocation()
const {locale} = useLocalization()
function onClick(data: any) {
put(data)
}
return (
<Card marginLeft={0} className={styles.MyCard} mb={mb}>
<Text>
{t('tour') + ':' + booking?.tour?.name[locale]}
</Text>
<Text>
{t('customer') + ':' + booking?.user?.username}
</Text>
<Text>
{t('numberOfPersons') + ':' + booking?.countPeople}
</Text>
<Text>
{ t('price') + ':' + currentPrice(booking.price, locale) }
</Text>
<MyBadge status={booking.status}/>
{pathname.includes('admin') &&
<Menu>
<MenuButton
as={Button}
>
{t('changeStatus')}
</MenuButton>
<MenuList>
{statusesBookings.map(item => {
if (item.value != booking.status) {
return (
<MenuItem key={item.value}
onClick={() => onClick({...booking, status: item.value})}>
{item[locale].text}
</MenuItem>
)
}
})}
</MenuList>
</Menu>
}
</Card>
)
}
|
package com.pluralsight;
import java.util.ArrayList;
import java.util.Collections;
public class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<>();
String[] suits = {"Hearts", "Spades", "Diamonds", "Clubs"};
String[] values = {"J", "Q", "K", "A"};
for (String suit : suits) {
for (String value : values) {
Card card = new Card(suit, value);
cards.add(card);
}
}
}
public void shuffle(){
Collections.shuffle(cards);
}
public Card deal() {
if (cards.size() > 0) {
Card card = cards.remove(0);
return card;
} else {
return null;
}
}
public int getSize(){
return cards.size();
}
}
|
import { Icons } from "@/components/icons";
export type NavItem = {
title: string;
href: string;
disabled?: boolean;
icon?: keyof typeof Icons;
};
// main nav
export type NavbarConfig = {
mainNav: NavItem[];
dashboardNav: NavItem[];
};
type NavItemContent = {
title: string;
items: NavItem[];
};
// sidebar nav
export type SideBarConfig = {
general: NavItemContent[];
admin: NavItemContent[];
};
export type SiteConfig = {
name: string,
gitHub: string,
};
export type FeatureItem = {
title: string,
description: string,
icon: keyof typeof Icons
};
export type FeatureCards = FeatureItem[];
export type SidebarNavItem = {
title: string
disabled?: boolean
icon?: keyof typeof Icons
} & (
| {
href: string
items?: never
}
)
export type DashboardConfig = {
sidebarNav: SidebarNavItem[]
}
export type Transport = {
id: number;
name: string;
takeBy: string;
colorId: number;
categoryId: number;
plate: string;
image: string;
createdAt: Date;
updatedAt: Date;
color: Color;
category: Category;
};
export type FilterItem = {
id: number;
name: string;
}
export type FilterType = "color" | "category";
|
import { EntityNotFoundException } from '@domain/exceptions/entity-not-found.exception';
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';
@Catch(EntityNotFoundException)
export class EntityNotFoundExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = HttpStatus.NOT_FOUND;
response.status(status).json({
statusCode: status,
message: exception.message,
});
}
}
|
using MassTransit;
using MessageQueueBasic.Domain.Models;
using MessageQueueBasic.MessageBroker.Messages;
using Microsoft.AspNetCore.Mvc;
namespace MessageQueueBasic.Web.Controllers;
[ApiController]
[Route("[controller]")]
public class MessageQueueController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<MessageQueueController> _logger;
private readonly IPublishEndpoint _publishEndpoint;
public MessageQueueController(ILogger<MessageQueueController> logger, IPublishEndpoint publishEndpoint)
{
_logger = logger;
_publishEndpoint = publishEndpoint;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
/// <summary>
/// Publica uma mensagem na fila
/// </summary>
/// <returns></returns>
[HttpPost("send-message")]
public IActionResult SendMessage()
{
_publishEndpoint.Publish<ITested>(new
{
Id = 1,
Name = "Inocencio Cardoso"
});
return Ok();
}
}
|
import { useMemo } from 'react'
import { Token, TokenAmount } from 'vexchange-sdk'
import useSWR from 'swr'
import { find } from 'lodash'
import { SWRKeys, useKeepSWRDataLiveAsBlocksArrive } from '.'
import ERC20_ABI from '../constants/abis/erc20.json'
import { useWeb3React } from '../hooks'
// returns null on errors
export function useTokenContract(tokenAddress: string) {
const { library } = useWeb3React()
const abi = find(ERC20_ABI, { name: 'allowance' })
return useMemo(() => {
try {
return library.thor.account(tokenAddress).method(abi)
} catch {
return null
}
}, [tokenAddress, abi, library.thor])
}
function getTokenAllowance(method, token): (owner: string, spender: string) => Promise<TokenAmount> {
return async (owner: string, spender: string): Promise<TokenAmount> =>
method.call(owner, spender).then(data => {
return new TokenAmount(token, data.decoded[0].toString())
})
}
export function useTokenAllowance(token?: Token, owner?: string, spender?: string): TokenAmount {
const method = useTokenContract(token?.address)
const shouldFetch = !!method && typeof owner === 'string' && typeof spender === 'string'
const { data, mutate } = useSWR(
shouldFetch ? [owner, spender, token.address, token.chainId, SWRKeys.Allowances] : null,
getTokenAllowance(method, token)
)
useKeepSWRDataLiveAsBlocksArrive(mutate)
return data
}
|
import { Request, Response } from "express";
import fs from "fs";
import { StatusCodes } from "http-status-codes";
import { NotFoundError, EmptyValueError } from "../errors";
import { IData } from "../types/createDataTypes";
const dataPath = "./callapp-data.json";
let dataObject: any;
fs.readFile(dataPath, (err, data) => {
if (err) {
console.log(`Error reading file: ${dataPath}`, err);
return;
}
dataObject = JSON.parse(data.toString());
console.log(`Data loaded from ${dataPath}:`);
});
const createData = async (req: Request, res: Response) => {
const newData: IData = req.body;
if (
!newData ||
!("name" in newData) ||
!("email" in newData) ||
!("gender" in newData) ||
!("address" in newData) ||
!("phone" in newData)
) {
throw new Error("Invalid data format, Please provide correct values");
}
for (const key in newData) {
if (key === "address") {
if (!(newData[key] instanceof Object)) {
throw new TypeError(
"Address field should be an object with 'street' and 'city' properties"
);
}
if (!newData[key].street || !newData[key].city) {
throw new EmptyValueError(
`Value for 'street' and 'city' in address cannot be empty`
);
}
} else {
if (newData[key] === "") {
throw new EmptyValueError(`Value for '${key}' cannot be empty`);
}
}
}
const lastItemId = dataObject[dataObject.length - 1].id;
const newId = lastItemId + 1;
const newObject: IData = {
id: newId,
name: newData.name,
email: newData.email,
gender: newData.gender,
address: {
street: newData.address.street,
city: newData.address.city,
},
phone: newData.phone,
};
dataObject.push(newObject);
await fs.promises.writeFile(dataPath, JSON.stringify(dataObject, null, 2));
res.status(StatusCodes.CREATED).json(newObject);
};
const getAllData = async (req: Request, res: Response) => {
if (!dataObject || dataObject.length <= 0) {
throw new NotFoundError("Data doesn't exist");
}
res.status(StatusCodes.OK).json({ msg: "all data", dataObject });
};
const updateData = async (req: Request, res: Response) => {
const id = parseInt(req.params.id, 10);
const updatedFields = req.body;
const index = dataObject.findIndex((item: any) => item.id === id);
if (index === -1) {
throw new NotFoundError(`Data with ID ${id} not found`);
}
for (const key in updatedFields) {
if (key === "address" && !(updatedFields[key] instanceof Object)) {
throw new TypeError(
"Address field should be an object with 'street' and 'city' properties"
);
}
if (!(key in dataObject[index])) {
throw new NotFoundError(`Field '${key}' does not exist in the object`);
}
if (updatedFields[key] === "") {
throw new EmptyValueError(`Value for '${key}' cannot be empty`);
}
}
const updatedObject = {
...dataObject[index],
...updatedFields,
};
if (updatedFields.address) {
updatedObject.address = {
...dataObject[index].address,
...updatedFields.address,
};
}
dataObject[index] = updatedObject;
await fs.promises.writeFile(dataPath, JSON.stringify(dataObject, null, 2));
res.status(StatusCodes.OK).json(dataObject[index]);
};
const deleteData = async (req: Request, res: Response) => {
const id = parseInt(req.params.id, 10);
const index = dataObject.findIndex((item: any) => item.id === id);
if (index === -1) {
throw new NotFoundError(`Data with ID ${id} not found`);
}
dataObject.splice(index, 1);
await fs.promises.writeFile(dataPath, JSON.stringify(dataObject, null, 2));
res
.status(StatusCodes.OK)
.json({ msg: `Data with ID ${id} deleted successfully` });
};
export { createData, getAllData, updateData, deleteData };
|
import React, {MouseEventHandler, useCallback, useEffect, useRef, useState} from "react";
import {Item} from "../../models/item";
import {RecursiveList} from "../RecursiveList/RecursiveList";
import './ListItem.scss';
export const ListItem = ({ item }: {item: Item}) => {
const { name, children } = item;
const [isOpened, setIsOpened] = useState<boolean>(false);
const getClassList = useCallback(() => {
let classList = [];
if(children?.length) {
classList.push('parent');
if(isOpened) {
classList.push('parent--opened');
}
}
return classList.join(' ');
}, [children, isOpened]);
const handleClick: MouseEventHandler<HTMLElement> = (e) => {
e.stopPropagation();
if(children?.length) {
setIsOpened((clicked) => !clicked);
}
};
return (
<li onClick={handleClick} className={getClassList()}>
{name}
{isOpened && children && <RecursiveList items={children} />}
</li>
);
};
|
import ProductCardHome from "deco-sites/fashion/components/product/ProductCardHome.tsx";
import SliderJS from "deco-sites/fashion/islands/SliderJS.tsx";
import Icon from "deco-sites/fashion/components/ui/Icon.tsx";
import Slider from "deco-sites/fashion/components/ui/Slider.tsx";
import { SendEventOnLoad } from "deco-sites/fashion/sdk/analytics.tsx";
import { useId } from "preact/hooks";
import { mapProductToAnalyticsItem } from "deco-sites/std/commerce/utils/productToAnalyticsItem.ts";
import { useOffer } from "deco-sites/fashion/sdk/useOffer.ts";
import type { Product } from "deco-sites/std/commerce/types.ts";
export interface Props {
title: string;
products: Product[][] | null;
itemsPerPage?: number;
shelfTitles: string[];
}
function ProductShelf({
products,
title,
}: { products: Product[]; title: string }) {
const id = useId();
if (!products || products.length === 0) {
return null;
}
return (
<div
id={id}
class="relative grid grid-cols-[48px_1fr_48px] grid-rows-[1fr_48px_1fr] py-10 px-0 sm:px-5"
>
<Slider class="carousel carousel-center sm:carousel-end col-span-full row-start-1 row-end-5">
{products?.map((product, index) => (
<Slider.Item
index={index}
class="carousel-item max-w=[225px] w-[225px] sm:w-[225px] first:ml-6 sm:first:ml-0 last:mr-6 sm:last:mr-0 px-1"
>
<ProductCardHome product={product} itemListName={title} />
</Slider.Item>
))}
</Slider>
<div class="flex items-center justify-center z-10 absolute top-1/2 -translate-y-1/2 left-0">
<Slider.PrevButton class="btn rounded-none text-black border-transparent bg-[hsla(0,0%,100%,.9)] disabled:lg:opacity-50 lg:hover:bg-transparent lg:hover:border-transparent">
<Icon
class=""
size={30}
id="ChevronLeft"
strokeWidth={1}
/>
</Slider.PrevButton>
</div>
<div class="flex items-center justify-center z-10 absolute top-1/2 -translate-y-1/2 right-0">
<Slider.NextButton class="btn rounded-none text-black border-transparent bg-[hsla(0,0%,100%,.9)] disabled:lg:opacity-50 lg:hover:bg-transparent lg:hover:border-transparent">
<Icon
class=""
size={30}
id="ChevronRight"
strokeWidth={1}
/>
</Slider.NextButton>
</div>
<SliderJS rootId={id} />
<SendEventOnLoad
event={{
name: "view_item_list",
params: {
item_list_name: title,
items: products.map((product) =>
mapProductToAnalyticsItem({
product,
...(useOffer(product.offers)),
})
),
},
}}
/>
</div>
);
}
function TabbedShelf({
title,
products,
shelfTitles,
}: Props) {
if (!products || products.length === 0) {
return null;
}
return (
<div class="max-w-[1316px] mx-auto flex flex-col py-10 px-0 sm:px-5 gap-[32px]">
<h2 class="text-center">
<span class="uppercase">{title}</span>
</h2>
<div class="">
{
/* <input type="radio" id="tab2" name="css-tabs" class="hidden" />
<input type="radio" id="tab3" name="css-tabs" class="hidden" />
<input type="radio" id="tab4" name="css-tabs" class="hidden" /> */
}
{shelfTitles?.map((_, index) => (
<input
type="radio"
id={`tab${index}`}
name="css-tabs"
class="hidden peer"
checked={index === 0}
/>
))}
<ul class="flex w-full sm:justify-center peer-[&:nth-of-type(1):checked]:[&_.tab:nth-of-type(1)]:text-black peer-[&:nth-of-type(2):checked]:[&_.tab:nth-of-type(2)]:text-black peer-[&:nth-of-type(1):checked]:[&_.tab:nth-of-type(1)]:border-black peer-[&:nth-of-type(2):checked]:[&_.tab:nth-of-type(2)]:border-black">
{shelfTitles?.map((shelfTitle, index) => (
<li class="tab p-[10px] border-b border-default h-fit ">
<label
for={`tab${index}`}
class="px-2 lg:px-[24px] text-base lg:text-xl whitespace-nowrap"
>
{shelfTitle}
</label>
</li>
))}
</ul>
{products?.map((shelf, index) => (
<div class="hidden peer-[&:nth-of-type(1):checked]:[&:nth-of-type(1)]:flex peer-[&:nth-of-type(2):checked]:[&:nth-of-type(2)]:flex">
<ProductShelf products={shelf} title={shelfTitles[index]} />
</div>
))}
</div>
</div>
);
}
export default TabbedShelf;
|
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batcher
import (
"context"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"sigs.k8s.io/controller-runtime/pkg/log"
)
type CreateFleetBatcher struct {
batcher *Batcher[ec2.CreateFleetInput, ec2.CreateFleetOutput]
}
func NewCreateFleetBatcher(ctx context.Context, ec2api ec2iface.EC2API) *CreateFleetBatcher {
options := Options[ec2.CreateFleetInput, ec2.CreateFleetOutput]{
Name: "create_fleet",
IdleTimeout: 35 * time.Millisecond,
MaxTimeout: 1 * time.Second,
MaxItems: 1_000,
RequestHasher: DefaultHasher[ec2.CreateFleetInput],
BatchExecutor: execCreateFleetBatch(ec2api),
}
return &CreateFleetBatcher{batcher: NewBatcher(ctx, options)}
}
func (b *CreateFleetBatcher) CreateFleet(ctx context.Context, createFleetInput *ec2.CreateFleetInput) (*ec2.CreateFleetOutput, error) {
if createFleetInput.TargetCapacitySpecification != nil && *createFleetInput.TargetCapacitySpecification.TotalTargetCapacity != 1 {
return nil, fmt.Errorf("expected to receive a single instance only, found %d", *createFleetInput.TargetCapacitySpecification.TotalTargetCapacity)
}
result := b.batcher.Add(ctx, createFleetInput)
return result.Output, result.Err
}
func execCreateFleetBatch(ec2api ec2iface.EC2API) BatchExecutor[ec2.CreateFleetInput, ec2.CreateFleetOutput] {
return func(ctx context.Context, inputs []*ec2.CreateFleetInput) []Result[ec2.CreateFleetOutput] {
results := make([]Result[ec2.CreateFleetOutput], 0, len(inputs))
firstInput := inputs[0]
firstInput.TargetCapacitySpecification.TotalTargetCapacity = aws.Int64(int64(len(inputs)))
output, err := ec2api.CreateFleetWithContext(ctx, firstInput)
if err != nil {
for range inputs {
results = append(results, Result[ec2.CreateFleetOutput]{Err: err})
}
return results
}
// we can get partial fulfillment of a CreateFleet request, so we:
// 1) split out the single instance IDs and deliver to each requestor
// 2) deliver errors to any remaining requestors for which we don't have an instance
requestIdx := -1
for _, reservation := range output.Instances {
for _, instanceID := range reservation.InstanceIds {
requestIdx++
if requestIdx >= len(inputs) {
log.FromContext(ctx).Error(fmt.Errorf("received more instances than requested, ignoring instance %s", aws.StringValue(instanceID)), "received error while batching")
continue
}
results = append(results, Result[ec2.CreateFleetOutput]{
Output: &ec2.CreateFleetOutput{
FleetId: output.FleetId,
Errors: output.Errors,
Instances: []*ec2.CreateFleetInstance{
{
InstanceIds: []*string{instanceID},
InstanceType: reservation.InstanceType,
LaunchTemplateAndOverrides: reservation.LaunchTemplateAndOverrides,
Lifecycle: reservation.Lifecycle,
Platform: reservation.Platform,
},
},
},
})
}
}
if requestIdx != len(inputs) {
// we should receive some sort of error, but just in case
if len(output.Errors) == 0 {
output.Errors = append(output.Errors, &ec2.CreateFleetError{
ErrorCode: aws.String("too few instances returned"),
ErrorMessage: aws.String("too few instances returned"),
})
}
for i := requestIdx + 1; i < len(inputs); i++ {
results = append(results, Result[ec2.CreateFleetOutput]{
Output: &ec2.CreateFleetOutput{
Errors: output.Errors,
}})
}
}
return results
}
}
|
## Getting Started <a name="getting-started"></a>
### Getting Started With Obullo 2.0
-----
Any software application requires some effort to learn. We have done our best to minimize the learning curve while making the process as enjoyable as possible.The first step is to install Obullo, then read all the topics in the Introduction section of the Chapters.
### Your Application Always Up to Date
1. Go to [http://obm.obullo.com](http://obm.obullo.com) and find packages for your Obullo
2. Update your packages using your <b>package.json</b> file
3. Run <kbd>obm update</kbd> from your console to make your packages up to date.
### Update your <kbd>package.json</kbd>
If new packages available, the package manager <kbd>Obm</kbd> will upgrade your packages using your package.json. If you need a previous stable version remove the asterisk ( * ) and set it to a specific number. ( e.g. auth: "0.0.3" )
```php
{
"dependencies": {
"obullo": "*",
"acl" : "*"
"auth" : "0.0.3"
}
}
```
### Submit your packages
If you want to add your packages, go to [http://obullo.com](http://obullo.com) and click to <b>Submit Package</b> button.
### Read General Topics
------
Next, read each of the General Topics pages in order. Each topic builds on the previous one, and includes code examples that you are encouraged to try.Once you understand the basics you'll be ready to explore the package reference pages to learn to utilize the packages and components.
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBookingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('bookings', function (Blueprint $table) {
$table->increments('id');
$table->string('piklocation');
$table->string('piktime')->nullable();
$table->string('droplocation');
$table->string('date');
$table->string('days');
$table->string('vtype');
$table->string('fname');
$table->string('lname');
$table->string('nic');
$table->string('email');
$table->string('address1');
$table->string('address2');
$table->string('vehicle_id');
$table->string('driver_id');
$table->timestamps();
$table->foreign('vehicle_id')
->references('id')
->on('vehicles');
$table->foreign('driver_id')
->references('id')
->on('drivers');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('bookings');
}
}
|
import { useState, useEffect } from 'react';
import { Link, Navigate } from 'react-router-dom';
import axios from 'axios';
import AllPeeps from '../Peeps/AllPeeps';
const LoginPage = ({ setUser: setLoginUser }) => {
const [peepData, setPeepData] = useState([]);
const [getError, setGetError] = useState();
const [user, setUser] = useState({
username: ``,
password: ``
});
const [loggedIn, setLoggedIn] = useState(false);
const handleChange = e => {
const { name, value } = e.target;
setUser({
...user,
[name]: value
});
};
const getPeepData = async () => {
try {
const res = await axios.get(`http://localhost:4000/peeps`);
setPeepData(res.data);
} catch (error) {
setGetError(error.message)
}
}
useEffect(() => {
getPeepData();
}, []);
const login = async (e) => {
e.preventDefault();
const res = await axios.post(`http://localhost:4000/login`, user);
alert(res.data.message);
setLoginUser(res.data.user);
setUser({ username: ``, password: `` });
setLoggedIn(res.data.user ? true : false);
}
return (
<>
{loggedIn && <Navigate to="/" />}
<div className='container-fluid'>
<div className='row g-2'>
<div className='col-6 order-last'>
<div className='card mb-3' id='login-card'>
<h3>Log in to Chitter:</h3>
<form onSubmit={login}>
<input type="text" id="sign-in-username" name="username" value={user.username} onChange={handleChange} placeholder="Enter username..." />
<br />
<input type="password" id="sign-in-password" name="password" value={user.password} onChange={handleChange} placeholder="Enter password..." />
<br />
<button type="submit" id='login-button' value="Login" className='btn btn-warning' >Login</button>
</form>
<Link to="/register">
Don't have an account? Register now!
</Link>
</div>
</div>
<div className='col-6 order-first'>
<p id='check-latest-peeps'>Check out the latest peeps:</p>
<div className='card border-warning mb-3' id='login-peeps'>
<AllPeeps peepData={peepData} />
</div>
</div>
</div>
</div>
</>
)
}
export default LoginPage;
|
import Mock from 'mockjs';
import { localDict } from './localDict';
export const mockPrefix = '/mockPrefix';
Mock.setup({
timeout: '500-1000',
});
const mapKeys = (dicts: any) => {
const res: any = {};
const keys = Object.keys(dicts);
keys.forEach((key) => {
res[key] = Object.keys(dicts[key]);
});
return res;
};
const getRandomEnums = (dictKey: string) => {
const dictEnumKeys = mapKeys(localDict);
const enums: any = dictEnumKeys[dictKey];
console.log(Mock.Random.integer(0, enums.length - 1));
return enums[Mock.Random.integer(0, enums.length - 1)];
};
/*
@boolean:生成一个随机的布尔值。
@integer:生成一个随机的整数。
@float:生成一个随机的浮点数。
@date:生成一个随机的日期。
@image:生成一个随机的图片URL
@sentence:生成一个随机的句子。
@paragraph:生成一个随机的段落。
@email:生成一个随机的邮箱地址。
@url:生成一个随机的URL地址。
* */
const name = '@ctitle(2, 3)';
const title = '@ctitle(5, 8)';
const sentence = '@csentence(20,100)';
const img = '@image';
const sex = () => getRandomEnums('sex'); // 性别
const teacherStatus = () => getRandomEnums('studentStatus'); // 学生状态
const studentStatus = () => getRandomEnums('studentStatus'); // 学生状态
const school = () => getRandomEnums('school'); // 学校
const schoolClass = () => getRandomEnums('schoolClass'); // 教室
const schoolSubject = () => getRandomEnums('schoolSubject'); // 科目
const successResult = {
code: 0,
};
const teacherDetail = {
serial_num: '@id',
cn_name: name,
sex,
status: teacherStatus,
phone: '@integer(11)',
branch: school,
class_room: schoolClass,
tech_subject: schoolSubject,
avatar: '@img',
};
Mock.mock(`${mockPrefix}/teacher/list`, 'get', {
...successResult,
'data|0-10': [
teacherDetail,
],
});
Mock.mock(`${mockPrefix}/teacher/detail`, 'post', {
...successResult,
'data|0-10': teacherDetail,
});
const studentDetail = {
serial_num: '@id',
name,
sex,
status: studentStatus,
phone: '@integer(11)',
contact_name: name,
contact_phone: '@integer(11)',
contact_email: '@integer(11).com',
nationality: name,
city: name,
address: title,
school: title,
majors: title,
avatar: img,
};
Mock.mock(`${mockPrefix}/student/list`, 'get', {
...successResult,
'data|5-10': [
studentDetail,
],
});
Mock.mock(`${mockPrefix}/student/add`, 'post', {
...successResult,
});
Mock.mock(`${mockPrefix}/student/detail`, 'get', {
...successResult,
data: studentDetail,
});
export default Mock;
|
import type { NextApiRequest, NextApiResponse } from "next";
import axios from "axios";
import getAPI from "@/util/getAPI";
type CommentReqBody = {
post_id: number;
comment: string;
username: string;
};
type DeleteCommentReqBody = {
comment_id: number;
};
type CommentResBody = {
message?: string;
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<CommentResBody>
) {
const { method } = req;
const API = getAPI();
switch (method) {
case "POST":
try {
const token = req.headers.authorization?.split(' ')[1];
const { post_id, comment, username }: CommentReqBody = JSON.parse(req.body);
const response = await axios.post(`${API}/comment`, { post_id: post_id, comment: comment, username: username},{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
if (response.status === 200) {
const { data } = await response;
return res.status(200).json(data);
} else {
return res.status(400).json({ message: "" });
}
} catch (e) {
return res.status(500).json({ message: "Internal server error" });
}
break;
case "DELETE":
try {
const token = req.headers.authorization?.split(' ')[1];
const { comment_id }: DeleteCommentReqBody = JSON.parse(req.body);
const response = await axios.delete(`${API}/comment/${comment_id}`,{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
if (response.status === 201) {
const { data } = await response;
return res.status(201).json(data);;
} else {
return res.status(400).json({ message: "" });
}
} catch (e) {
return res.status(500).json({ message: "Internal server error" });
}
break;
default:
return res.status(405).json({ message: "Method not allowed" });
}
}
|
import glob
import random
import os
from .base_dataset import BaseImageDataset
from PIL import Image
import torchvision.transforms as transforms
class MaskImageDataset(BaseImageDataset):
def __init__(self, dir, dataroot, transforms_=None, unaligned=False, mode='train'):
"""Used for setting up transforms functions as well as file operations for data retrieval from memory"""
self.transform = transforms.Compose(transforms_)
self.unaligned = unaligned
if mode == 'train': #capturing items from corresponding directory depending on training mode
self.files_A = sorted(glob.glob(os.path.join(dir, dataroot, 'trainA') + '/*.*'))
self.files_B = sorted(glob.glob(os.path.join(dir, dataroot, 'trainB') + '/*.*'))
elif mode == 'test':
self.files_A = sorted(glob.glob(os.path.join(dir, dataroot, 'testA') + '/*.*'))
self.files_B = sorted(glob.glob(os.path.join(dir, dataroot, 'testB') + '/*.*'))
def __getitem__(self, index):
"""used for capturing item A and item B from both domains"""
item_A = self.transform(Image.open(self.files_A[index % len(self.files_A)])) #indexing to location in file directory
if self.unaligned:
item_B = self.transform(Image.open(self.files_B[random.randint(0, len(self.files_B) - 1)])) #capturing random pair from B file directory if unaligned
else:
item_B = self.transform(Image.open(self.files_B[index % len(self.files_B)])) #else, picking match from directory
return {'A': item_A, 'B': item_B} #returning both items as a dictionary
def __len__(self):
"""maximum length of either dataset"""
return max(len(self.files_A), len(self.files_B))
|
<.header>
<%= gettext("Listing Suppliers") %>
<:actions>
<.link patch={~p"/admin/marketplaces/suppliers/new"}>
<.button><%= gettext("New Supplier") %></.button>
</.link>
</:actions>
</.header>
<.table
id="suppliers"
rows={@streams.suppliers}
row_click={
fn {_id, supplier} ->
JS.navigate(~p"/admin/marketplaces/suppliers/#{supplier}")
end
}
>
<:col :let={{_id, supplier}} label={gettext("Name")}>
<%= supplier.name %>
</:col>
<:action :let={{_id, supplier}}>
<div class="sr-only">
<.link navigate={~p"/admin/marketplaces/suppliers/#{supplier}"}>
<%= gettext("Show") %>
</.link>
</div>
</:action>
<:action :let={{_id, supplier}}>
<.link
id={"suppliers-edit-#{supplier.id}"}
patch={~p"/admin/marketplaces/suppliers/#{supplier}/edit"}
class="hover:text-teal-500"
>
<.icon name="hero-pencil-solid" class="h-3 w-3 sm:h-5 sm:w-5 opacity-60" />
</.link>
</:action>
<:action :let={{_id, supplier}}>
<.link
id={"suppliers-delete-#{supplier.id}"}
phx-click={
JS.push("delete", value: %{id: supplier.id}) |> hide("##{supplier.id}")
}
data-confirm={
gettext("Delete supplier \"%{name}\"?", name: supplier.name)
}
class="hover:text-rose-500"
>
<.icon name="hero-trash-solid" class="h-3 w-3 sm:h-5 sm:w-5 opacity-60" />
</.link>
</:action>
</.table>
<.modal
:if={@live_action in [:new, :edit]}
id="supplier-modal"
show
on_cancel={JS.patch(~p"/admin/marketplaces/suppliers")}
>
<.live_component
module={PriceSpotterWeb.Admin.Marketplaces.SupplierLive.FormComponent}
id={@supplier.id || :new}
title={@page_title}
action={@live_action}
supplier={@supplier}
patch={~p"/admin/marketplaces/suppliers"}
/>
</.modal>
|
const Tracking = require("../model/Tracking");
function generateUniqueTrackingNumber() {
const min = Math.pow(10, 10);
const max = Math.pow(10, 11) - 1;
const randomInteger = Math.floor(Math.random() * (max - min + 1)) + min;
return String(randomInteger);
}
generateUniqueTrackingNumber();
const saveTrackingInfo = async (trackingNumber, shippingInfo) => {
const trackingDocument = new Tracking({
...shippingInfo,
trackingNumber,
});
try {
await trackingDocument.save();
return { trackingNumber };
} catch (err) {
if (err.name === "ValidationError") {
console.error("Validation error:", err.errors);
throw new Error("Validation error");
}
else {
console.error("Error saving shipping document", err);
throw new Error("Internal server error")
}
}
};
//function for getting shipping list
const getShippingList = () => {
try {
return Tracking.find()
} catch (error) {
console.error("Error fetching shipping info", error)
throw new Error("Internal server error")
}
}
//configuration for tracking goods
const trackGoods = async (trackingNumber) => {
try {
const shipment = await Tracking.findOne({ trackingNumber })
return shipment || null
} catch (error) {
console.error("Error tracking goods", error)
throw new Error("Internal server error")
}
}
//Configuration for editing Tracking information
const editTrackingInfo = async (trackingNumber, updateInfo) => {
try {
const existingShipment = await Tracking.findOne(
{ trackingNumber }
)
if (!existingShipment) {
return null
}
const commonUpdatedAt = new Date();
if (!existingShipment.commonHistory) {
existingShipment.commonHistory = [];
}
if (updateInfo.date) {
existingShipment.date = updateInfo.date;
}
if (updateInfo.activities) {
existingShipment.activities = updateInfo.activities;
}
if (updateInfo.location) {
existingShipment.location = updateInfo.location;
}
if (updateInfo.details) {
existingShipment.details = updateInfo.details;
}
// Update common history
existingShipment.commonHistory.push({
type: 'common',
value: 'Update occurred',
updatedAt: commonUpdatedAt,
});
const updatedShipment = await existingShipment.save();
return updatedShipment;
} catch (error) {
console.error("Error editing tracking information", error)
throw new Error("Internal server error")
}
}
const trackLog = async (trackingNumber) => {
try {
const tracking = await Tracking.findOne({ trackingNumber })
if (tracking) {
return tracking
} else {
return null
}
} catch (error) {
console.error("Error tracking goods")
throw error
}
}
const deleteTrack = async (trackingNumber) => {
try {
const delTracking = await Tracking.findOneAndDelete(trackingNumber)
if (!delTracking) {
throw new Error("Document not found for deletion")
}
return delTracking
} catch (error) {
console.error("Error deleting tracking numb", error)
throw error
}
}
module.exports = {
generateUniqueTrackingNumber,
saveTrackingInfo,
trackGoods,
editTrackingInfo,
trackLog,
getShippingList,
deleteTrack
};
|
//
// CombatValue.swift
// DungeonDelversOSRToolkit
//
// Created by Curtis DeGidio on 11/25/23.
//
import Foundation
enum CombatValue: CaseIterable {
case armorClass
case meleeBonus
case maxHP
case conBonusHP
case unarmoredAC
case dexBonusAC
case missileAttacks
var name: String {
switch self {
case .armorClass:
return "AC"
case .meleeBonus:
return "Mel"
case .maxHP:
return "Max"
case .conBonusHP, .dexBonusAC:
return "±"
case .unarmoredAC:
return "Un"
case .missileAttacks:
return "Mis"
}
}
var description: String {
switch self {
case .armorClass:
return "Armor Class"
case .meleeBonus:
return "STR modifier to melee attack / damage"
case .maxHP:
return "Maximum hit points"
case .conBonusHP:
return "CON modifier to hit points"
case .unarmoredAC:
return "Unarmored AC: 9 + DEX Modifier"
case .dexBonusAC:
return "DEX modifier to Armor Class"
case .missileAttacks:
return "DEX modifier to missile attacks"
}
}
}
|
<template>
<div v-if="requesting" class="animate-pulse text-center text-gray-600">
<div class="text-3xl">
<IconElem icon="bi bi-arrow-clockwise animate-spin" />
</div>
<h1 class="text-2xl font-semibold mb-2">
Verificando sua conta...
</h1>
</div>
<div v-if="fail" class="text-center text-red-600">
<div class="text-3xl">
<IconElem icon="bi bi-x-lg" />
</div>
<h1 class="text-2xl font-semibold mb-2">
Falha na verificação.
</h1>
<p class="text-lg" v-html="failMessage">
</p>
</div>
<div v-if="success" class="text-center text-emerald-600">
<div class="text-3xl">
<IconElem icon="bi bi-check-lg" />
</div>
<h1 class="text-2xl font-semibold mb-2">
Sucesso!
</h1>
<p class="text-lg">
Sua conta foi verificada com sucesso, agora você tem acesso completo a nossa
aplicação.
</p>
<div class="pt-3">
<DefaultButton icon="bi bi-pie-chart" text="Dashboard"
:to="{ name: 'app.home' }" />
</div>
</div>
</template>
<script>
import messages from '../../services/messages';
import DefaultButton from '../../components/Button/DefaultButton.vue';
import IconElem from '../../components/IconElem.vue';
export default {
components: { IconElem, DefaultButton },
data() {
return {
requesting: true,
fail: false,
failMessage: null,
success: false,
}
},
mounted() {
let token = this.$route.query?.token;
if (!token) {
this.requesting = false;
this.fail = true;
this.failMessage = 'Link de verificação sem token, acesse sua conta e solicite um link de verificação válido.';
return;
}
this.$axios.request('/auth/verify-account/?token=' + token).then(() => {
this.success = true;
}).catch((resp) => {
this.fail = true;
this.failMessage = messages.get(resp.response?.data?.error);
}).then(() => {
this.requesting = false;
});
},
}
</script>
|
using Architecture.Domain.Models;
using Architecture.Impl.Repositories;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Serialization;
using System.Text.Json;
namespace Architecture.Controllers;
[ApiController]
[Route("/api/[controller]")]
public class CustomerController : Controller
{
private readonly ICustomerRepository _customerRepository;
public CustomerController(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
[HttpGet("{customerId}")]
public IActionResult GetCustomerById(Guid customerId)
{
Customer customer = _customerRepository.getCustomerById(customerId);
if (customer == null)
{
return NotFound();
}
var options = new JsonSerializerOptions
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
string json = JsonSerializer.Serialize(customer, options);
return Ok(json);
}
[HttpGet("byName/{clientName}")]
public IActionResult GetCustomerByName(string clientName)
{
Customer customer = _customerRepository.getCustomerByClientName(clientName);
if (customer == null)
{
return NotFound();
}
var options = new JsonSerializerOptions
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
string json = JsonSerializer.Serialize(customer, options);
return Ok(json);
}
[HttpGet]
public IActionResult GetAllCustomers()
{
List<Customer> customerArray = _customerRepository.getAllCustomer();
if (customerArray == null)
{
return NotFound();
}
return Ok(customerArray);
}
[HttpPost]
public IActionResult CreateCustomer(Customer customer)
{
Customer newCustomer = _customerRepository.createCustomer(customer);
if (newCustomer == null)
{
return NotFound();
}
var options = new JsonSerializerOptions
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
string json = JsonSerializer.Serialize(newCustomer, options);
return Ok(json);
}
[HttpPut("{customerId}")]
public IActionResult UpdateCustomer(Customer customer)
{
Customer newCustomer = _customerRepository.updateCustomer(customer);
if (customer == null)
{
return NotFound();
}
var options = new JsonSerializerOptions
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
string json = JsonSerializer.Serialize(newCustomer, options);
return Ok(json);
}
[HttpDelete("{customerId}")]
public IActionResult DeleteCustomer(Guid customerId)
{
string deletedCustomer = _customerRepository.deleteCustomer(customerId);
if (deletedCustomer == null)
{
return NotFound();
}
var options = new JsonSerializerOptions
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
string json = JsonSerializer.Serialize(deletedCustomer, options);
return Ok(json);
}
}
|
#+TITLE: Random Notes
#+SETUPFILE: ../../setup.org
* Managed Service Identities
No need to have credentials or service principal.
Docs - Part of the Active Directory docs
https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/
* Resource Providers
That is, "cloud services".
For example, there is a resource provider that provides virtual machines. It's
called Microsoft.Compute.
Every resource provider exposes a set of actions. That is, the service has an
API.
* RBAC
Fine-grained control to the Azure "control plane".
When you assign a role to a certain scope, resources within that scope inherit
the role assignment.
A *Role* is a collection of actions (i.e. a collection of API operations). A
*Role Assignment* gives a _security principal_ the ability to perform that set
of _actions_ on that _scope_.
There are 3 top level roles in Azure:
1. Owner
2. Contributor
3. Reader
** Security Principal
- User
- Group
- Service Principal
** Role
- Built-in
- Custom
** Scope
- Subscription
- Resource Group
- Resource
* Subscription Model
Scope heirarchy:
Tenant -> Management Group -> Subscription -> Resource Group -> Resource
** Tenant
Azure Active Directory entity that encompasses a whole organization. A tenant
has at least one subscription and user. You use it to manage subscriptions
and users in the organization.
This is kind of like an AWS Organization that is used to manage all the AWS
accounts in a company.
** User
An individual and is associated with only one tenant, the organization that
they belong to. May have access to multiple subscriptions.
A user is a "User" in the Active Directory. That means users are tenant-level
entities. Each user can have multiple subscriptions.
** Subscription
The agreements with Microsoft to use cloud services, including Azure.
Sometimes a "subscription" is referred to as an "account" i.e. "az account
set" command. I think a subscription is the most similar thing to an AWS
account.
The fact that Azure has resource groups adds a layer of isolation within
subscriptions that's harder to attain in AWS accounts, so in Azure you are
likely to have less subscriptions that you'd have accounts in AWS.
** Account
Can mean a few things:
1. The Microsoft Account that was used when signing up for Azure. A Microsoft
Account is the account you use to access Office 365, XBox Live, etc.
- When you sign up for an Azure subscription with a personal Microsoft
Account, an Azure AD Tenant is created for you.
- Or, you can create an Azure subscription associated with an existing
Azure AD Tenant.
2. An Azure subscription. This is what `azure account list` and `azure account
set` do
3. A Service Principal, which is sometimes referred to as using a "service
account". "Service principals are accounts not tied to any particular user" -
https://docs.microsoft.com/en-us/cli/azure/authenticate-azure-cli?view=azure-cli-latest#sign-in-with-a-service-principal
** Management Group
A level of management above subscriptions (but still within a single
tenant). Management Groups allow you to associate certain settings with many
subscriptions.
** Storage Account
How is this different from account or resource group?
** Role
Controls access to resources. Can be assigned to users, groups, or services.
** Resource
Associated with a subscription
** Application
Something in Azure that outsources authentication to Azure AD. AD uses Oauth
2.0 to authenticate to the application, which mean the application must have
a URL.
Sometimes "Application" refers to the entity requesting an auth token in an
Oauth2 authentication flow. I think OAuth2 refers to this entity as the
"client application". See:
https://docs.microsoft.com/en-us/azure/active-directory/develop/developer-glossary#client-application
Sometimes "Application" refers to a VM. For example when adding an access
policy to keyvault; if you add a VM, it is labelled as an "application". In
this case I suppose "application" refers to "code on the VM that needs
keyvault creds".
* IMDS
Available to all vms created with ARM.
Get Token
#+BEGIN_SRC sh
curl -H Metadata:true \
"http://169.254.169.254/metadata/identity/oauth2/token?resource=https://management.azure.com&api-version=2018-04-02"
#+END_SRC
* VM
** List VM offers in region
#+begin_src sh
az vm image list --all -l eastus
#+end_src
* VM Extensions
VM Extensions are run using a vm agent. The agent is installed by default in
Azure Marketplace images.
* API
List vms
#+begin_src sh
r=$(curl -H Metadata:true "http://169.254.169.254/metadata/identity/oauth2/token?resource=https://management.azure.com&api-version=2018-04-02")
access_token=$(echo $r | jq -r '.access_token')
url="https://management.azure.com/subscriptions/10f9b671-4896-4336-ba3d-82e9d4ab0b52/providers/Microsoft.Compute/virtualMachines?api-version=2018-06-01"
curl $url -H "Authorization: Bearer $access_token" | jq
#+end_src
* All Locations
** List
#+begin_src sh
az account list-locations --query "[].name"
#+end_src
** Loop
Create a Public IP in each location
#+begin_src sh
locations=($(az account list-locations | jq -r '.[].name'))
for i in "${!locations[@]}"; do
location=${locations[$i]}
echo ip-$i $$location
az network public-ip create \
-g PublicIpPool \
-n ip-$i \
--allocation-method Static
done
#+end_src
* Load Balancers
** Create LB Rule
#+begin_src sh
az network lb rule create -g $CLUSTER_NAME \
--lb-name fixed-ip-lb \
-n fixed-ip-ssh-rule \
--protocol Tcp \
--frontend-port 443 \
--backend-pool-name fixed-ip-lbbepool \
--backend-port 443
#+end_src
** Create Load Balancer
#+begin_src sh
az network lb create \
-n mylb \
-g $ResourceGroup \
-l westus2 \
--public-ip-address "/subscriptions/$SUBSCRIPTION_ID/resourceGroups/PublicIpPool/providers/Microsoft.Network/publicIPAddresses/$IP_NAME"
#+end_src
* Providers
** All provides and registration state
az provider list --query "[].{Provider:namespace, Status:registrationState}"
--out table
** Registerd namespaces
az provider list --query "[?registrationState == 'Registered'].namespace"
--out table
* Subscription Quotas
#+begin_src fish
function getLimit --description "Get a quota limit in the given region"
set location $argv[1]
set limit (az vm list-usage \
--location $location \
-o json \
| jq -r '.[] | select(.localName == "Total Regional vCPUs") | .limit')
echo "$location: $limit"
end
function getAllLimits --description "Get all Total Region vCPU limits"
set locations (az account list-locations | jq -r '.[].name')
echo $locations | xargs -n 1 -P (count $locations) -I {} fish -c 'getLimit {}'
end
#+end_src
#+begin_src sh
allLocations=$(az account list-locations | jq -r '.[].name')
echo $allLocations | xargs
for location in ; do
limit=$(az vm list-usage \
--location $location \
-o json \
| jq -r '.[] | select(.localName == "Total Regional vCPUs") | .limit')
echo "$location: $limit"
done
#+end_src
* Create Public Static Ip
#+begin_src sh
location="westus2"
az network public-ip create \
-g PublicIpPool \
-n ip-$location-1 \
-l $location \
--allocation-method Static
#+end_src
* ACR
** List registries
#+begin_src sh :results output
az acr list | jq -c '.[] | {name, loginServer, location}'
#+end_src
** List repositories
#+begin_src sh :var name=""
az acr repository list -n $name
#+end_src
** List repository versions
#+begin_src sh :var name=""
az acr repository show-manifests \
-n $name \
--repository quay.io/kubernetes-ingress-controller/nginx-ingress-controller
#+end_src
* Api Versions
Get the latest Api Version for something
#+begin_src sh
az provider list --query "[?namespace=='Microsoft.ClassicNetwork']" > ~/cats/resource_provider.json
jq '.[].resourceTypes[] | select(.resourceType == "reservedIps").apiVersions | first' <~/cats/resource_provider.json
#+end_src
** Python
#+begin_src python
from msrestazure.tools import parse_resource_id
def _get_ip_address(self, resource_id: str) -> str:
# Determine the latest API version for this resource type
parsed_id = parse_resource_id(resource_id)
provider = self.resource_client.providers.get(parsed_id["namespace"])
resource_type_def = next(
i
for i in provider.resource_types
if i.resource_type.lower() == parsed_id["resource_type"].lower()
)
# Supported API versions are ordered from newest to oldest
api_version = resource_type_def.api_versions[0]
# Fetch the IP resource and return its IP address
resource = self.resource_client.resources.get_by_id(resource_id, api_version)
return resource.properties["ipAddress"]
#+end_src
* Users
** Get My User
#+begin_src sh
az ad user list --query "[?mailNickname=='chris.clark']"
#+end_src
|
"""
Problem description:
---------
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
Constraints:
1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s and wordDict[i] consist of only lowercase English letters.
All the strings of wordDict are unique.
"""
def word_break(s, word_dict):
# Brute force: Recursive approach
# Time complexity: O(2 ^ n)
n = len(s)
if n == 0:
return True
for i in range(1, n + 1):
if s[:i] in word_dict and word_break(s[i:], word_dict):
return True
return False
# TODO: Add DP
if __name__ == '__main__':
ex1, ex2, ex3 = ("leetcode", ["leet", "code"]), ("applepenapple", [
"apple", "pen"]), ("catsandog", ["cats", "dog", "sand", "and", "cat"])
print(word_break(ex1[0], ex1[1]))
print(word_break(ex2[0], ex2[1]))
print(word_break(ex3[0], ex3[1]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.