text
stringlengths 184
4.48M
|
---|
PHP Arrays
==========
An array stores multiple values in one single variable:
Example
========
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$cars1="Volvo";
$cars2="BMW";
$cars3="Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
Create an Array in PHP
In PHP, the array() function is used to create an array:
array();
In PHP, there are three types of arrays:
Indexed arrays - Arrays with numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0):
$cars=array("Volvo","BMW","Toyota");
or the index can be assigned manually:
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:
Example
=======
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Get The Length of an Array - The count() Function
The count() function is used to return the length (the number of elements) of an array:
Example
========
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
-----------------------------
To loop through and print all the values of an indexed array, you could use a for loop, like this:
Example
========
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
PHP Associative Arrays
----------------------
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
The named keys can then be used in a script:
Example
=======
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Loop Through an Associative Array
---------------------------------
To loop through and print all the values of an associative array, you could use a foreach loop, like this:
Example
=======
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
|
---
description: ์คํธ๋ฆผ์ด ์ง์ํ๋ ๋ค์ํ ์ฐ์ฐ์ ๋ฐฐ์๋ณด์.
---
# 5์ฅ: ์คํธ๋ฆผ ํ์ฉ
์ด๋ฒ ์ฅ์์๋ ์๋ ๋ฉ์๋๋ค์ ์ฐจ๊ทผ์ฐจ๊ทผ ์ดํด๋ณธ๋ค. ๐ณ
<figure><img src="../../.gitbook/assets/image (29).png" alt=""><figcaption><p><a href="https://javaconceptoftheday.com/java-8-streams-beginners-guide/">https://javaconceptoftheday.com/java-8-streams-beginners-guide/</a></p></figcaption></figure>
## ํํฐ๋ง
### Predicate ํํฐ๋ง
* filter ๋ฉ์๋๋ Predicate(boolean์ ๋ฐํํ๋ ํจ์ํ ์ธํฐํ์ด์ค)๋ฅผ ์ธ์๋ก ๋ฐ์์ Predicate์์ true๋ฅผ ๋ฐํํ๋ ์์๋ง ํฌํจํ๋ ์คํธ๋ฆผ์ ๋ฐํํ๋ค.
```java
List<Integer> numbers = List.of(1,2,4,2,3,5);
numbers.stream()
.filter(i -> i % 2 == 0)
.forEach(System.out::println);
```
### ๊ณ ์ ์์๋ง ํํฐ๋ง
* ๊ณ ์ ์์๋ก ์ด๋ฃจ์ด์ง ์คํธ๋ฆผ์ ๋ฐํํ๋ distinct๋ฉ์๋๋ ์ง์ํ๋ค.
* ๊ฐ์ฒด์ ๊ณ ์ ์ฌ๋ถ๋ ์คํธ๋ฆผ์์ ๋ง๋ ๊ฐ์ฒด์ hashCode, equals๋ก ๊ฒฐ์ ํ๋ค. (equals & hashcode๋ฅผ ์ ์ ์ํดํ๋๋ก ํ์..๐ฅฒ)
```java
List<Integer> numbers = List.of(1,2,4,2,3,5);
numbers.stream()
.filter(i -> i % 2 == 0)
.distinct() // ์ค๋ณต ํํฐ๋ง
.forEach(System.out::println);
```
## ์คํธ๋ฆผ ์ฌ๋ผ์ด์ฑ
* ์คํธ๋ฆผ์ ์์๋ฅผ ์ ํํ๊ฑฐ๋ ์คํตํ๋ ๋ฐฉ๋ฒ
### Predicate๋ฅผ ์ด์ฉํ ์ฌ๋ผ์ด์ฑ
#### TAKEWHILE
* **๋ฐ์ดํฐ๊ฐ ์ ๋ ฌ๋์ด ์๊ณ , ํน์ ์กฐ๊ฑด์ด ์ฐธ์ด ๋์ค๋ฉด ๋ฐ๋ณต ์์
์ ์ค๋จ**ํ๋ ค๋ฉด takeWhile()์ ์ด์ฉํด ์ฒ๋ฆฌํ ์ ์๋ค.
* filter๋ ๋ชจ๋ ๋ฐ์ดํฐ๋ฅผ ๊ฒ์ฌํ๋ฉฐ true์ธ ๊ฒ๋ง ๋ค์์ผ๋ก ๋์ด๊ฐ์ง๋ง, takeWhile์ ์กฐ๊ฑด์ ๋ํด true๊ฐ ์๋๊ฒ ๋ ๊ฒฝ์ฐ ๋ฐ๋ก ๊ฑฐ๊ธฐ์ ๋ฉ์ถ๊ฒ ๋๋ค.
* ์๋ ์์ ๋ 320 ์นผ๋ก๋ฆฌ ๋ฏธ๋ง์ธ ๋ฉ๋ด๋ง ์ฌ๋ผ์ด์ฑํ๋ค.
```java
List<Dish> silcedMenu = specialMenu.stream()
.takeWhile(dish -> dish.getCalories() < 320)
.collect(toList());
```
#### DROPWHILE
* takeWhile๊ณผ ์ ๋ฐ๋๋ก, **๋ฐ์ดํฐ๊ฐ ์ ๋ ฌ๋์ด ์๊ณ , ํน์ ์กฐ๊ฑด์ด ๊ฑฐ์ง์ด ๋์ค๋ฉด ๋ฐ๋ณต ์์
์ ์ค๋จ**ํ๋ ค๋ฉด dropWhile()์ ์ด์ฉํด ์ฒ๋ฆฌํ ์ ์๋ค.
* ํ๋ ๋์ผ์ดํธ๊ฐ ์ฒ์์ผ๋ก ๊ฑฐ์ง์ด ๋๋ ์ง์ ๊น์ง ํ์ํ ํ, ์์
์ ์ค๋จํ๊ณ ํด๋น ์ง์ ์ดํ์ ํ์ํ์ง ์์ ๋ชจ๋ ์์๋ฅผ ๋ฐํํ๋ค.
* ์๋ ์์ ๋ 320 ์นผ๋ก๋ฆฌ ์ด์์ธ ๋ฉ๋ด๋ง ์ฌ๋ผ์ด์ฑํ๋ค.
```java
List<Dish> silcedMenu = specialMenu.stream()
.dropWhile(dish -> dish.getCalories() < 320)
.collect(toList());
```
### ์คํธ๋ฆผ ์ถ์
* ์ฃผ์ด์ง ๊ฐ ์ดํ์ ํฌ๊ธฐ๋ฅผ ๊ฐ๋ ์๋ก์ด ์คํธ๋ฆผ์ ๋ฐํํ๋ limit(n) ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ์ ์๋ค.
* ์ต๋ n๊ฐ์ ์์๋ง์ ๋ฐํํ ์ ์๋ค.
* ์๋๋ ์ต๋ 3๊ฐ์ ์์๋ง์ ๋ฐํํ๋๋ก ํ๋ ์ฝ๋์ด๋ค.
```java
List<Dish> silcedMenu = specialMenu.stream()
.filter(dish -> dish.getCalories() > 300)
.limit(3)
.collect(toList());
```
### ์์ ๊ฑด๋๋ฐ๊ธฐ
* ์ฒ์ n๊ฐ ์์๋ฅผ ์ ์ธํ ์คํธ๋ฆผ์ ๋ฐํํ๋ skip(n) ๋ฉ์๋๋ฅผ ์ ๊ณตํ๋ค.
* n๊ฐ ์ดํ์ ์์๋ฅผ ํฌํจํ๋ ์คํธ๋ฆผ์ skip(n)์ ํธ์ถํ๋ฉด ๋น ์คํธ๋ฆผ์ด ๋ฐํ๋๋ค.
* limit๊ณผ skip์ ์ํธ ๋ณด์์ ์ธ ์ฐ์ฐ์ ์ํํ๋ค.
* ์๋๋ 300์นผ๋ก๋ฆฌ ์ด์์ธ ์์ ์ค ์ฒ์ ๋ ์๋ฆฌ๋ ์คํตํ๊ณ ๋๋จธ์ง ์๋ฆฌ๋ค๋ง ๋ฐํํ๋ ์ฝ๋์ด๋ค.
```java
List<Dish> silcedMenu = specialMenu.stream()
.filter(dish -> dish.getCalories() > 300)
.skip(2)
.collect(toList());
```
## ๋งคํ
* ํน์ ๊ฐ์ฒด์์ ํน์ ๋ฐ์ดํฐ๋ฅผ ์ ํํ๊ธฐ ์ํด ๋งคํ ์์
์ ์ํํ ์ ์๋ค.
### ์คํธ๋ฆผ์ ๊ฐ ์์์ ํจ์ ์ ์ฉํ๊ธฐ
* ํจ์๋ฅผ ์ธ์๋ก ๋ฐ๋ map ๋ฉ์๋๋ฅผ ์ง์ํ๋ค.
* ์ธ์๋ก ์ ๊ณต๋ ํจ์๋ ๊ฐ ์์์ ์ ์ฉ๋๋ฉฐ ํจ์๋ฅผ ์ ์ฉํ ๊ฒฐ๊ณผ๊ฐ ์๋ก์ด ์์๋ก ๋งคํ๋๋ค.
* ๋ค์์ Dish ๋ฆฌ์คํธ๋ฅผ ์คํธ๋ฆผ์ผ๋ก ์ํํ๋ฉฐ Dish์ name ํ๋๋ง ์ถ์ถํ ๋ฆฌ์คํธ๋ฅผ ๋ฐํํ๋ ์ฝ๋์ด๋ค.
```java
List<String> MenuNames = specialMenu.stream()
.map(Dish::getName)
.collect(toList());
```
* ๋ค๋ฅธ map ๋ฉ์๋๋ฅผ ์ฒด์ด๋ํ๋ ๊ฒ๋ ๊ฐ๋ฅํ๋ค.
* ๋ค์์ Dish ๋ฆฌ์คํธ๋ฅผ ์คํธ๋ฆผ์ผ๋ก ์ํํ๋ฉฐ nameํ๋์ ๊ธธ์ด๋ฅผ ์ถ์ถํ ๋ฆฌ์คํธ๋ฅผ ๋ฐํํ๋ ์ฝ๋์ด๋ค.
```java
List<Integer> MenuNameLengths = specialMenu.stream()
.map(Dish::getName)
.map(String::length)
.collect(toList());
```
### ์คํธ๋ฆผ ํ๋ฉดํ
* flatMap์ ๊ฐ ๋ฐฐ์ด์ ์คํธ๋ฆผ์ด ์๋๋ผ **์คํธ๋ฆผ์ ์ฝํ
์ธ ๋ก ๋งคํ**ํ๋ค.
* ์คํธ๋ฆผ์ ๊ฐ ๊ฐ์ ๋ค๋ฅธ ์คํธ๋ฆผ์ผ๋ก ๋ง๋ ๋ค์์, ๋ชจ๋ ์คํธ๋ฆผ์ ํ๋์ ์คํธ๋ฆผ์ผ๋ก ์ฐ๊ฒฐํ๋ ๊ธฐ๋ฅ์ ์ํํ๋ค.
* ์๋ ์ฝ๋์ flatMap์ ๋จ์ด๋ค์ ๋ชจ๋ ์ํ๋ฒณ ๋จ์๋ก ๋ผ์ด๋ธ ํ ์ป๋ ์ฌ๋ฌ ๊ฐ์ String\[] ๋ฐฐ์ด๋ค์ ํ๋์ String Stream์ผ๋ก ๋ชจ์ ์ํํ ์ ์๋๋ก ํด์ค๋ค.
```java
List<String> uniqueChars = words.stream()
.map(word -> word.split("")) // Stream<String[]>
.flatMap(Arrays::stream) // Stream<String>
.distinct()
.collect(toList());
```
## ๊ฒ์๊ณผ ๋งค์นญ
### ์ ์ด๋ ํ ์์์ ์ผ์นํ๋์ง ๊ฒ์ฌ
* Predicate๊ฐ ์ฃผ์ด์ง ์คํธ๋ฆผ์์ ์ ์ด๋ ํ ์์์ ์ผ์นํ๋์ง ํ์ธํ ๋ anyMatch ๋ฉ์๋๋ฅผ ํ์ฉํ๋ค.
```java
boolean isMatch = menu.stream().anyMatch(Dish::isVegetarian);
```
### ๋ชจ๋ ์์์ ์ผ์นํ๋์ง ๊ฒ์ฌ
* Predicate๊ฐ ์ฃผ์ด์ง ์คํธ๋ฆผ์ ๋ชจ๋ ์์์ ์ผ์นํ๋์ง ํ์ธํ ๋ allMatch ๋ฉ์๋๋ฅผ ํ์ฉํ๋ค.
```java
boolean isAllVegiterian = menu.stream().allMatch(Dish::isVegetarian);
```
* Predicate๊ฐ ์ฃผ์ด์ง ์คํธ๋ฆผ์ ๋ชจ๋ ์์์ ์ผ์นํ์ง ์๋์ง ํ์ธํ ๋ noneMatch ๋ฉ์๋๋ฅผ ํ์ฉํ๋ค.
```java
boolean isHealthy = menu.stream().noneMatch(d -> d.getCalories() >= 1000);
```
> ์ผํธ ์ํท
>
> ํ๋๋ผ๋ ์กฐ๊ฑด์ ๋ง์ง ์๋๋ค๋ฉด ๋๋จธ์ง ํํ์์ ๊ฒฐ๊ณผ์ ์๊ด์์ด ์ ์ฒด ๊ฒฐ๊ณผ๊ฐ ์ ํด์ง๊ธฐ ๋๋ฌธ์ ์ ์ฒด ์คํธ๋ฆผ์ ์ฒ๋ฆฌํ์ง ์์๋ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ ์ ์๋ ๊ฒ์ ๋งํ๋ค.
>
> allMatch, noneMatch, findFirst, findAny ๋ฑ์ ์ฐ์ฐ์ด ๋ชจ๋ ์ด์ ํด๋นํ๋ค.
>
>
>
### ์์ ๊ฒ์
* findAny ๋ฉ์๋๋ ํ์ฌ ์คํธ๋ฆผ์์ ์์์ ์์๋ฅผ ๋ฐํํ๋ค.
* ๋ค๋ฅธ ์คํธ๋ฆผ ์ฐ์ฐ๊ณผ ์ฐ๊ฒฐํด์ ์ฌ์ฉํ ์ ์์ผ๋ฉฐ, ๊ฒฐ๊ณผ๋ฅผ ์ฐพ๋ ์ฆ์ ์คํธ๋ฆผ์ ์ข
๋ฃํ๋ค.
* [findFirst ๋ฉ์๋](5.md#undefined-12)๋ฅผ ์ฌ์ฉํ ๊ฒฝ์ฐ ๋ณ๋ ฌ ์คํ ์ ์ฒซ ๋ฒ์งธ ์์๋ฅผ ์ฐพ๊ธฐ ์ด๋ ค์ฐ๋ฏ๋ก ๋ณดํต ๋ณ๋ ฌ์ผ๋ก ์คํ์ํฌ ๋ ์ ์ฝ์ด ์ ์ findAny ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ค.
```java
Optional<Dish> dish = words.stream()
.filter(Dish::isVegetarian)
.findAny();
```
### ์ฒซ ๋ฒ์งธ ์์ ์ฐพ๊ธฐ
* ์คํธ๋ฆผ์ ์ฒซ๋ฒ์งธ ์์๋ฅผ ์ฐพ๋ findFirst ๋ฉ์๋๋ฅผ ์ ๊ณตํ๋ค.
* ๋ฆฌ์คํธ ๋๋ ์ ๋ ฌ๋ ๋ฐ์ดํฐ๋ก๋ถํฐ ์์ฑ๋ ์คํธ๋ฆผ์ ๋
ผ๋ฆฌ์ ์ธ ์์ดํ
์์๊ฐ ์ ํด์ ธ ์์ ์ ์๋ค.
```java
Optional<Integer> first = someNumbers.stream()
.map(n -> n * n)
.filter(n -> n % 3 == 0)
.findFirst();
```
## ๋ฆฌ๋์ฑ
* ์คํธ๋ฆผ์ ์ต์ข
์ฐ์ฐ ์ค ํ๋๋ก ๋ง์ง๋ง ๊ฒฐ๊ณผ๊ฐ ๋์ฌ๋๊น์ง ์คํธ๋ฆผ์ ๋ชจ๋ ์์๋ฅผ ๋ฐ๋ณต์ ์ผ๋ก ์ฒ๋ฆฌํ๋ ๊ณผ์
* ํจ์ํ ํ๋ก๊ทธ๋๋ฐ ์ธ์ด ์ฉ์ด๋ก๋ ์ด๊ณผ์ ์ด ๋ง์น ์ข
์ด๋ฅผ ์์ ์กฐ๊ฐ์ด ๋ ๋๊น์ง ๋ฐ๋ณตํด์ ์ ๋๊ฒ๊ณผ ๋น์ทํ๋ค ํ์ฌ ํด๋(fold)๋ผ๊ณ ๋ถ๋ฅธ๋ค.
* ๋ฆฌ๋์ค์ ํ๋ผ๋ฏธํฐ
* ์ด๊น๊ฐ
* ์คํธ๋ฆผ์ ๋ ์์๋ฅผ ์กฐํฉํด ์๋ก์ด ๊ฐ์ ๋ง๋๋ BinaryOperator\<T> ์ ๊ตฌํ์ฒด(๋๋ค)
* reduce๋ฅผ ์ฌ์ฉํ๋ฉด ์คํธ๋ฆผ์ด ํ๋์ ๊ฐ์ผ๋ก ์ค์ด๋ค ๋ ๊น์ง ๊ฐ ์์๋ฅผ ๋ฐ๋ณตํด ์กฐํฉํ๊ธฐ ๋๋ฌธ์, ์ ํ๋ฆฌ์ผ์ด์
์ ๋ฐ๋ณต๋ ํจํด์ ์ถ์ํ ํ ์ ์๋ค.
### ์์์ ํฉ
* reduce๋ฅผ ์ฌ์ฉํด ์คํธ๋ฆผ์ ๋ชจ๋ ์์๋ค์ ์ดํฉ์ ๊ตฌํด๋ณด์.
* ์ด๊น๊ฐ์ 0์ผ๋ก ๋๊ณ , ๋ํ๊ธฐ ๋ฉ์๋๋ฅผ ํ๋ผ๋ฏธํฐ๋ก ๋๊ธฐ๋ฉด ์คํธ๋ฆผ์ ์ดํฉ๋ง ๋จ์๋๊น์ง ๋ํ๋ ์ฐ์ฐ์ด ์ํ๋๋ค.
```java
// ๊ธฐ์กด ์๋ฐ ๋ฐฉ์
int sum = 0;
for ( int x : numbers ) {
sum += x;
}
// ์คํธ๋ฆผ์ ๋ฆฌ๋์ค ์ฌ์ฉ
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
int multiple = numbers.stream().reduce(1, (a, b) -> a * b); // ๋ชจ๋ ์์๋ฅผ ๊ณฑํ๋ฏ๋ก ์ด๊น๊ฐ์ 1์ด์ด์ผ ํ๋ค.
// ๋ฉ์๋ ์ฐธ์กฐ
int sum = numbers.stream().reduce(0, Integer::sum);
```
* ๋ฆฌ๋์ค ์ฐ์ฐ์ ์ด๊น๊ฐ์ ์ฃผ์ง ์์ผ๋ฉด ์คํธ๋ฆผ์ ์๋ฌด ์์๋ ์๋ ๊ฒฝ์ฐ ๊ฐ์ ๋ฐํํ ์ ์๊ธฐ ๋๋ฌธ์ Optional ๊ฐ์ฒด๋ก ๊ฐ์ผ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ค.
### ์ต๋๊ฐ๊ณผ ์ต์๊ฐ
* ์ต๋๊ฐ๊ณผ ์ต์๊ฐ์ ์ฐพ์ ๋๋ reduce๋ฅผ ํ์ฉํ ์ ์๋ค.
* ์คํธ๋ฆผ์ ๋ชจ๋ ์์๋ฅผ ์๋นํ ๋ ๊น์ง max() ํน์ min() ์ฐ์ฐ์ ํ๋ค.
```java
Optional<Integer> max = numbers.stream().reduce(Integer::max);
Optional<Integer> min = numbers.stream().reduce(Integer::min);
```
> reduce ๋ฉ์๋์ ๋ณ๋ ฌํ
>
> * reduce๋ฅผ ์ด์ฉํ๋ฉด ๋ด๋ถ ๋ฐ๋ณต์ด ์ถ์ํ๋๋ฉด์ ํฌํฌ/์กฐ์ธ ํ๋ ์์ํฌ๋ฅผ ํ์ฉํด ๋ณ๋ ฌ๋ก reduce๋ฅผ ์คํํ ์ ์๊ฒ ๋๋ค.
> * ๋จ๊ณ์ ๋ฐ๋ณต์ผ๋ก ํฉ๊ณ๋ฅผ ๊ตฌํ ๋๋ sum ๋ณ์๋ฅผ ๊ณต์ ํด์ผ ํ๋๋ฐ, ์ด๋ก ์ธํด ๋๊ธฐํ ์ด์๊ฐ ๋ฐ์ํด ๋ณ๋ ฌํ๊ฐ ์ด๋ ต๋ค.
> * ๋ฌผ๋ก ๋ณ๋ ฌ๋ก ์คํํ๊ธฐ ์ํด์๋ ์ฐ์ฐ์ด ์ด๋ค ์์๋ก ์คํ๋๋๋ผ๋ ๊ฒฐ๊ณผ๊ฐ ๋ฐ๋์ง ์๋ ๊ตฌ์กฐ์ฌ์ผ ํ๋ค.
> ์คํธ๋ฆผ ์ฐ์ฐ : ์ํ ์์๊ณผ ์ํ ์์
>
> * ์ํ ์์ (stateless operation)
> * map, filter ๋ฑ์ ์
๋ ฅ ์คํธ๋ฆผ์์ ๊ฐ ์์๋ฅผ ๋ฐ์ 0 ๋๋ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅ ์คํธ๋ฆผ์ผ๋ก ๋ณด๋ธ๋ค.
> * ์ํ ์์ (stateful operation)
> * reduce, sum, max ๊ฐ์ ์ฐ์ฐ์ ๊ฒฐ๊ณผ๋ฅผ ๋์ ํ ๋ด๋ถ ์ํ๊ฐ ํ์ํ์ง๋ง ์ด๋ int, double ๋ฑ๊ณผ ๊ฐ์ด ์์ ๊ฐ์ด๋ฉฐ, ์คํธ๋ฆผ์์ ์ฒ๋ฆฌํ๋ ์์ ์์ ๊ด๊ณ์์ด **ํ์ **(bounded)๋์ด์๋ค.
> * ๋ฐ๋ฉด sorted๋ distinct ๊ฐ์ ์ฐ์ฐ์ ์ํํ๊ธฐ ์ํด์๋ ๊ณผ๊ฑฐ์ ์ด๋ ฅ์ ์๊ณ ์์ด์ผ ํ๋ค. ์๋ฅผ ๋ค์ด ์ด๋ค์์๋ฅผ ์ถ๋ ฅ ์คํธ๋ฆผ์ผ๋ก ์ถ๊ฐํ๋ ค๋ฉด **๋ชจ๋ ์์๊ฐ ๋ฒํผ์ ์ถ๊ฐ๋์ด ์์ด์ผ** ํ๋ค. ๋ฐ๋ผ์ ๋ฐ์ดํฐ ์คํธ๋ฆผ์ ํฌ๊ธฐ๊ฐ ํฌ๊ฑฐ๋ ๋ฌดํ์ด๋ผ๋ฉด ๋ฌธ์ ๊ฐ ์๊ธธ ์ ์๋ค.
## ์ซ์ํ ์คํธ๋ฆผ
* [3์ฅ](3.md#primitive-type) ๋ด์ฉ๊ณผ ๋น์ทํ๊ฒ ์คํ ๋ฐ์ฑ์ ํผํ๊ธฐ ์ํด primitive type์ ์ํ ์คํธ๋ฆผ์ ์ ๊ณตํ๋ค.
* int ์์์ ํนํ๋ IntStream, double ์์์ ํนํ๋ DoubleStream, long ์์์ ํนํ๋ LongStream์ ์ ๊ณตํ๋ค.
### ์ซ์ ์คํธ๋ฆผ์ผ๋ก ๋งคํ
* mapToInt, mapToDouble, mapToLong ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ฉด ๊ธฐ๋ณธํ ํนํ ์คํธ๋ฆผ์ผ๋ก ๋ณํํด์ค๋ค.
* ์๋์ ๊ฐ์ด mapToInt ๋ฉ์๋๋ก ๊ฐ ์๋ฆฌ์์ ๋ชจ๋ ์นผ๋ก๋ฆฌ(Intergerํ์)๋ฅผ ์ถ์ถํ ๋ค์์ IntStream์(Stream\<Integer>๊ฐ ์๋) ๋ฐํํ๋ค. ์คํธ๋ฆผ์ด ๋น์ด์์ผ๋ฉด sum์ ๊ธฐ๋ณธ๊ฐ 0์ ๋ฐํํ๋ค.
```java
int calories = menu.stream()
.mapToInt(Dish::getCalories) // IntStream
.sum();
```
### ๊ฐ์ฒด ์คํธ๋ฆผ์ผ๋ก ๋ณต์
* ์ซ์ ์คํธ๋ฆผ์ ๊ธฐ๋ณธ ์คํธ๋ฆผ์ผ๋ก ๋ณํํ๋ ค๋ฉด boxed() ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ฉด ๋๋ค.
```java
IntStream intStream = menu.stream().mapToInt(Dish::getCalories);
Stream<Integer> stream = intStream.boxed();
```
### OptionalInt
* Optional์ Integer, String ๋ฑ์ ์ฐธ์กฐ ํ์์ผ๋ก ํ๋ผ๋ฏธํฐํํ ์ ์๋ค. 
* OptionalInt, OptionalDouble, OptionalLoing ์ธ ๊ฐ์ง ๊ธฐ๋ณธํ ํนํ ์คํธ๋ฆผ ๋ฒ์ ์ ์ ๊ณตํ์ฌ ์ซ์ ์คํธ๋ฆผ ๋ฉ์๋์ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ์ ์ ์๋ค.
```java
OptionalInt maxCalories = menu.stream().mapToInt(Dish::getCalories).max();
int max = maxCalories.orElse(1);
```
### **์ซ์ ๋ฒ์**
* IntStream๊ณผ LongStream์์๋ range์ rangeClosed๋ผ๋ ๋ ๊ฐ์ง ์ ์ ๋ฉ์๋๋ฅผ ์ ๊ณตํ๋ค. ๋ ๋ฉ์๋ ๋ชจ๋ ์์๊ฐ๊ณผ ์ข
๋ฃ๊ฐ์ ์ธ์๋ก ๊ฐ์ง๋ค.
* range ๋ฉ์๋๋ ์์๊ฐ๊ณผ ์ข
๋ฃ๊ฐ์ด ๊ฒฐ๊ณผ์ ํฌํจ๋์ง ์๋๋ค.
* rangeClosed ๋ฉ์๋๋ ์์๊ฐ๊ณผ ์ข
๋ฃ๊ฐ์ด ๊ฒฐ๊ณผ์ ํฌํจ๋๋ค.
```java
IntStream evenNumbers = IntStream.rangeClosed(1, 100).filter(n -> n % 2 == 0);
System.out.println(evenNumbers.count()); // 50 ์ถ๋ ฅ
```
#### ํผํ๊ณ ๋ผ์ค์ ์๋ฅผ ๊ตฌํ๋ ์์
* 1๋ถํฐ 100๊น์ง ํผํ๊ณ ๋ผ์ค์ ์๋ฅผ ๊ตฌํ๋ค. (a\*a + b\*b = c\*c์ธ ๊ฒฝ์ฐ์ ์๋ฅผ ๋ชจ๋ ๊ตฌํ๊ธฐ)
* a, b๋ฅผ iteration ๋๋ฉด์ a\*a + b\*b ์ ์ ๊ณฑ๊ทผ์ด ์ ์์ผ ๊ฒฝ์ฐ์๋ง int\[a, b, c]๋ฅผ ์คํธ๋ฆผ์ ๋จ๊ฒจ๋๋ค.
```java
Stream<int[]> pythagoreanTriples =
IntStream.rangeClose(1, 100).boxed()
.flatMap(a ->
IntStream.rangeClose(a, 100)
.mapToObj(b -> new int[]{a, b, (int)Math.sqrt(a * a + b * b)})
.filter(t -> t[2] % 1 == 0));
```
## ๋ค์ํ๊ฒ ์คํธ๋ฆผ ๋ง๋ค๊ธฐ
### ๊ฐ์ผ๋ก ์คํธ๋ฆผ ๋ง๋ค๊ธฐ
* ์์์ ์๋ฅผ ์ธ์๋ก ๋ฐ๋ ์ ์ ๋ฉ์๋ Stream.of๋ฅผ ์ด์ฉํด์ ์คํธ๋ฆผ์ ๋ง๋ค ์ ์๋ค.
```java
Stream<String> stream = Stream.of("Modern", "Java", "In", "Action");
```
* Stream.empty() ๋ฉ์๋๋ ์คํธ๋ฆผ์ ๋น์ด๋ค.
```java
Stream<String> emptyStream = Stream.empty();
```
### null์ด ๋ ์ ์๋ **๊ฐ์ฒด๋ก ์คํธ๋ฆผ ๋ง๋ค๊ธฐ**
* ofNullable ๋ฉ์๋๋ก null์ด ๋ ์ ์๋ ๊ฐ์ฒด๋ฅผ ํฌํจํ๋ ์คํธ๋ฆผ์ ๋ง๋ค ์ ์๋ค.
* nullableํ ๊ฐ์ฒด๋ฅผ ํฌํจํ๋ ์คํธ๋ฆผ๊ฐ๊ณผ flatMap์ ํจ๊ป ์ฌ์ฉํ๋ ์ํฉ์์ ์ ์ฉํ๊ฒ ์ฌ์ฉํ ์ ์๋ค.
```java
Stream<String> stream = Stream.ofNullable(System.getProperty("home"));
Stream<String> values = Stream.of("config", "home", "user")
.flatMap(key -> Stream.ofNullable(System.getProperty(key)));
```
### **๋ฐฐ์ด๋ก ์คํธ๋ฆผ ๋ง๋ค๊ธฐ**
* ๋ฐฐ์ด์ ์ธ์๋ก ๋ฐ๋ ์ ์ ๋ฉ์๋ Arrays.stream()์ ์ด์ฉํด์ ์คํธ๋ฆผ์ ๋ง๋ค ์ ์๋ค.
```java
int[] numbers = {2, 3, 5, 7, 11, 13};
int sum = Arrays.stream(numbers).sum();
```
### **ํ์ผ๋ก ์คํธ๋ฆผ ๋ง๋ค๊ธฐ**
* ํ์ผ์ ์ฒ๋ฆฌํ๋ ๋ฑ์ I/O ์ฐ์ฐ์ ์ฌ์ฉํ๋ ์๋ฐ์ NIO API(๋น๋ธ๋ก I/O)๋ ์คํธ๋ฆผ API๋ฅผ ํ์ฉํ ์ ์๋ค.
* Files.lines๋ก ํ์ผ์ ๊ฐ ํ ์์๋ฅผ ๋ฐํํ๋ ์คํธ๋ฆผ์ ์ป์ ์ ์๋ค.
* Stream ์ธํฐํ์ด์ค๋ AutoCloseable ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ๋ฏ๋ก, try ๋ธ๋ก ๋ด์ ์์์ ์๋์ผ๋ก ๊ด๋ฆฌ๋๋ค.
* ๋ค์์ ์
๋ ฅ๋ฐ์ ํ์ผ์์ ๊ฐ ํ์ ๋จ์ด๋ค์ flatMap์ผ๋ก ํ๋์ ์คํธ๋ฆผ์ผ๋ก ํ๋ฉดํํ ํ, ๊ณ ์ ํ ๋จ์ด๊ฐ ๋ช๊ฐ์ธ์ง ๋ฐํํ๋ ์ฝ๋์ด๋ค.
```java
long uniqueWords = 0;
try(Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())) {
uniqueWords = lines.flatMap(line -> Arrays.stream(line.split(" ")))
.distinct()
.count();
} catch (IOException e) {
// ํ์ผ ์ด๋ค๊ฐ ์์ธ ๋ฐ์ ์ ์ฒ๋ฆฌ
}
```
### **ํจ์๋ก ๋ฌดํ ์คํธ๋ฆผ ๋ง๋ค๊ธฐ**
* Stream.iterate์ Stream.generate๋ฅผ ์ด์ฉํด์ ํจ์๋ก๋ถํฐ ํฌ๊ธฐ๊ฐ ๊ณ ์ ๋์ง ์์ ๋ฌดํ ์คํธ๋ฆผ(unbounded stream)์ ๋ง๋ค ์ ์๋ค.
#### iterate ๋ฉ์๋
* ์ด๊น๊ฐ๊ณผ ๋๋ค๋ฅผ ์ธ์๋ก ๋ฐ์์ ์๋ก์ด ๊ฐ์ ๋์์์ด ์์ฐํ ์ ์๋ค.
* ๋ณดํต์ ๋ฌดํํ ๊ฐ์ ์ถ๋ ฅํ์ง ์๋๋ก limit(n) ๋ฉ์๋์ ํจ๊ป ์ฌ์ฉํ๋ค.
* ํน์ ๋ ๋ฒ์งธ ์ธ์๋ก Predicate๋ฅผ ๋ฐ์ ์์
์ค๋จ์ ๊ธฐ์ค์ผ๋ก ์ฌ์ฉํ ์๋ ์๋ค.
```java
Stream.iterate(0, n -> n + 2)
.limit(10)
.forEach(System.out::println);
// 100๋ณด๋ค ํฐ ๊ฐ์ด ๋์ค๋ฉด ์์
์ค๋จ
IntStream.iterate(0, n -> n < 100, n -> n + 4)
.forEach(System.out::println);
```
* filter ๋ฉ์๋๋ ์ธ์ ์์
์ ์ค๋จํ ์ง ์๋ฆด ์ ์๊ธฐ ๋๋ฌธ์, takeWhile ๋ฉ์๋๋ฅผ ์ฌ์ฉํด์ผ ํ๋ค.
```java
IntStream.iterate(0, n -> n + 4)
.takeWhile(n -> n < 100)
.forEach(System.out::println);
```
#### generate ๋ฉ์๋
* iterate์ ๋ฌ๋ฆฌ generate๋ ์์ฐ๋ ๊ฐ ๊ฐ์ ์ฐ์์ ์ผ๋ก ๊ณ์ฐํ์ง ์์ผ๋ฉฐ, Supplier\<T>๋ฅผ ์ธ์๋ก ๋ฐ์์ ์๋ก์ด ๊ฐ์ ์์ฐํ๋ค.
* ์๋ ์ฝ๋๋ 0์์ 1 ์ฌ์ด์ ์์์ double number 5๊ฐ๋ฅผ ๋ง๋ ๋ค.
```java
Stream.generate(Math::random)
.limit(5)
.forEach(System.out::println);
```
* generate ๋ฉ์๋์ ๊ฒฝ์ฐ Supplier์ ์ํ๋ฅผ ๊ฐ์ง ๊ฐ๋ฅ์ฑ์ด ๋์์ง๋ฏ๋ก, ์์ํ ๋ถ๋ณ ์ํ๋ฅผ ์ ์งํ๋ iterate ๋ฉ์๋์ ๋นํด ๋ณ๋ ฌ ํ๊ฒฝ์์ ๋ถ์์ ํ๋ค.
|
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { SpaRessourcePostDto } from './dto/SpaDto/Post'
import Spa from 'App/Models/Spa'
import Image from 'App/Models/Image'
import File from 'App/Models/File'
import { v4 as uuid } from 'uuid'
import { SpaImageRessourcePostDto } from './dto/SpaDto/ImageDto/Post'
import SpaImage from 'App/Models/SpaImage'
import { SpaImageRessourceSortDto } from './dto/SpaDto/ImageDto/Sort'
import { SpaImageRessourceDeleteDto } from './dto/SpaDto/ImageDto/Delete'
import { SpaRessourcePatchDto } from './dto/SpaDto/Patch'
import { SpaRessourceGetDto } from './dto/SpaDto/Get'
import { SpaRessourceDeleteDto } from './dto/SpaDto/Delete'
import { SpaRessourceRestoreDto } from './dto/SpaDto/Restore'
export default class SpasController {
public async index({ response, request }: HttpContextContract) {
const spasQuery = Spa.filter(request.qs())
spasQuery.preload('externalCalendar')
return response.ok(await spasQuery.exec())
}
public async create({}: HttpContextContract) {}
public async store({ request, response }: HttpContextContract) {
const dto = SpaRessourcePostDto.fromRequest(request)
const error = await dto.validate()
if (error.length > 0) {
return response.badRequest(error)
}
const { body } = await dto.after.customTransform
const spa = await Spa.create(body)
if (body.spaImages) {
await spa.related('spaImages').saveMany(
await Promise.all(
body.spaImages.map(async (spaImage) => {
const s = await spa.related('spaImages').create({
order: spaImage.order,
})
await s.related('image').associate(await Image.findOrFail(spaImage.image))
return s
})
)
)
await spa.load('spaImages')
}
if (body.services) {
await spa.related('services').attach(body.services)
}
return response.ok(spa)
}
public async show({ response, request }: HttpContextContract) {
const dto = SpaRessourceGetDto.fromRequest(request)
const error = await dto.validate()
if (error.length > 0) {
return response.badRequest(error)
}
const { params } = await dto.after.customTransform
const spa = params.id
await spa.load('tags')
await spa.load('services')
return response.ok(spa)
}
public async edit({}: HttpContextContract) {}
public async update({ request, response }: HttpContextContract) {
const dto = SpaRessourcePatchDto.fromRequest(request)
const error = await dto.validate()
if (error.length > 0) {
return response.badRequest(error)
}
const { body, params } = await dto.after.customTransform
const spa = params.id
spa.merge(body, true)
if (body.spaImages) {
await spa.spaImages.map(async (spaImage) => {
await spaImage.delete()
})
await spa.related('spaImages').saveMany(
await Promise.all(
body.spaImages.map(async (spaImage) => {
const s = await spa.related('spaImages').create({
order: spaImage.order,
})
await s.related('image').associate(await Image.findOrFail(spaImage.image))
return s
})
)
)
}
if (body.services) {
await spa.related('services').detach()
await spa.related('services').attach(body.services)
}
}
public async destroy({ response, request }: HttpContextContract) {
const dto = SpaRessourceDeleteDto.fromRequest(request)
const error = await dto.validate()
if (error.length > 0) {
return response.badRequest(error)
}
const { params } = await dto.after.customTransform
const spa = params.id
await spa.delete()
return response.ok({ message: 'Spa deleted' })
}
public async restore({ response, request }: HttpContextContract) {
const dto = SpaRessourceRestoreDto.fromRequest(request)
const error = await dto.validate()
if (error.length > 0) {
return response.badRequest(error)
}
const { params } = await dto.after.customTransform
const spa = params.id
await spa.restore()
return response.ok({ message: 'Spa restored' })
}
public async getImages({ request }: HttpContextContract) {
return await SpaImage.query().where('spa_id', request.params().spa).preload('image')
}
public async postImages({ request, response }: HttpContextContract) {
const dto = SpaImageRessourcePostDto.fromRequest(request)
const error = await dto.validate()
if (error.length > 0) {
return response.badRequest(error)
}
const { files, params } = await dto.after.customTransform
const spa = params.spa
const images = files.images
for (let i = 0; i < images.length; i++) {
const image = images[i]
const uniqueId = uuid()
const imageO = await Image.create({
alt: image.clientName,
})
const image0Spa = await spa.related('spaImages').create({})
await image0Spa.related('image').associate(imageO)
const file = await File.create({
name: image.clientName,
extname: image.extname,
size: image.size,
uuid: uniqueId,
})
await imageO.related('file').associate(file)
await image.moveToDisk('', {
name: `${uniqueId}.${image.extname}`,
})
}
return response.ok(spa.spaImages)
}
public async sortImages({ request, response }: HttpContextContract) {
const dto = SpaImageRessourceSortDto.fromRequest(request)
const error = await dto.validate()
if (error.length > 0) {
return response.badRequest(error)
}
const { body, params } = await dto.after.customTransform
const sorted = body.sorted
const spa = params.spa
const spaImages = await spa.related('spaImages').query().orderBy('order', 'asc')
if (!spaImages.every((spaI) => sorted.some((s) => s.id === spaI.id))) {
return response.badRequest({ message: 'Some images are missing' })
}
for (const s of spaImages) {
const sort = sorted.find((so) => so.id === s.id)!
s.order = sort.order
await s.save()
}
return response.ok(spaImages)
}
public async deleteImage({ request, response }: HttpContextContract) {
const dto = SpaImageRessourceDeleteDto.fromRequest(request)
const error = await dto.validate()
if (error.length > 0) {
return response.badRequest(error)
}
const { params } = await dto.after.customTransform
const spa = params.spa
const spaImage = params.spaImage
if (spa.id !== spaImage.spaId) {
return response.badRequest({ message: 'Image does not belong to the spa' })
}
await spaImage.delete()
return response.ok({ message: 'Image deleted' })
}
}
|
import { Router } from "express"; // Importa el Router de Express
import cartDao from "../dao/mongoDao/cart.dao.js"; // Importa el Data Access Object (DAO) para los carritos
const router = Router(); // Crea una nueva instancia del Router de Express
// Ruta para crear un nuevo carrito
router.post("/", async (req, res) => {
try {
const cart = await cartDao.create(); // Crea un nuevo carrito en la base de datos
res.status(201).json({ status: "success", payload: cart }); // Devuelve el nuevo carrito creado en la respuesta
} catch (error) {
console.log(error); // Imprime el error en la consola para depuraciรณn
res.status(500).json({ status: "Error", msg: "Error interno del servidor" }); // Devuelve un error 500 en caso de fallo
}
});
// Ruta para agregar un producto a un carrito
router.post("/:cid/product/:pid", async (req, res) => {
try {
const { cid, pid } = req.params; // Obtiene el ID del carrito y del producto de los parรกmetros de la URL
const cart = await cartDao.addProductToCart(cid, pid); // Aรฑade el producto al carrito
if (cart.product == false) return res.status(404).json({ status: "Error", msg: `No se encontrรณ el producto con el id ${pid}` }); // Si no se encuentra el producto, devuelve un error 404
if (cart.cart == false) return res.status(404).json({ status: "Error", msg: `No se encontrรณ el carrito con el id ${cid}` }); // Si no se encuentra el carrito, devuelve un error 404
res.status(200).json({ status: "success", payload: cart }); // Devuelve el carrito actualizado en la respuesta
} catch (error) {
console.log(error); // Imprime el error en la consola para depuraciรณn
res.status(500).json({ status: "Error", msg: "Error interno del servidor" }); // Devuelve un error 500 en caso de fallo
}
});
// Ruta para actualizar la cantidad de un producto en un carrito
router.put("/:cid/product/:pid", async (req, res) => {
try {
const { cid, pid } = req.params; // Obtiene el ID del carrito y del producto de los parรกmetros de la URL
const { quantity } = req.body; // Obtiene la nueva cantidad del producto del cuerpo de la solicitud
const cart = await cartDao.updateQuantityProductInCart(cid, pid, quantity); // Actualiza la cantidad del producto en el carrito
if (cart.product == false) return res.status(404).json({ status: "Error", msg: `No se encontrรณ el producto con el id ${pid}` }); // Si no se encuentra el producto, devuelve un error 404
if (cart.cart == false) return res.status(404).json({ status: "Error", msg: `No se encontrรณ el carrito con el id ${cid}` }); // Si no se encuentra el carrito, devuelve un error 404
res.status(200).json({ status: "success", payload: cart }); // Devuelve el carrito actualizado en la respuesta
} catch (error) {
console.log(error); // Imprime el error en la consola para depuraciรณn
res.status(500).json({ status: "Error", msg: "Error interno del servidor" }); // Devuelve un error 500 en caso de fallo
}
});
// Ruta para eliminar un producto de un carrito
router.delete("/:cid/product/:pid", async (req, res) => {
try {
const { cid, pid } = req.params; // Obtiene el ID del carrito y del producto de los parรกmetros de la URL
const cart = await cartDao.deleteProductInCart(cid, pid); // Elimina el producto del carrito
if (cart.product == false) return res.status(404).json({ status: "Error", msg: `No se encontrรณ el producto con el id ${pid}` }); // Si no se encuentra el producto, devuelve un error 404
if (cart.cart == false) return res.status(404).json({ status: "Error", msg: `No se encontrรณ el carrito con el id ${cid}` }); // Si no se encuentra el carrito, devuelve un error 404
res.status(200).json({ status: "success", payload: cart }); // Devuelve el carrito actualizado en la respuesta
} catch (error) {
console.log(error); // Imprime el error en la consola para depuraciรณn
res.status(500).json({ status: "Error", msg: "Error interno del servidor" }); // Devuelve un error 500 en caso de fallo
}
});
// Ruta para obtener un carrito por su ID
router.get("/:cid", async (req, res) => {
try {
const { cid } = req.params; // Obtiene el ID del carrito de los parรกmetros de la URL
const cart = await cartDao.getById(cid); // Busca el carrito por su ID
if (!cart) return res.status(404).json({ status: "Error", msg: `No se encontrรณ el carrito con el id ${cid}` }); // Si no se encuentra el carrito, devuelve un error 404
res.status(200).json({ status: "success", payload: cart }); // Devuelve el carrito encontrado en la respuesta
} catch (error) {
console.log(error); // Imprime el error en la consola para depuraciรณn
res.status(500).json({ status: "Error", msg: "Error interno del servidor" }); // Devuelve un error 500 en caso de fallo
}
});
// Ruta para actualizar un carrito por su ID
router.put("/:cid", async (req, res) => {
try {
const { cid } = req.params; // Obtiene el ID del carrito de los parรกmetros de la URL
const body = req.body; // Obtiene los datos del cuerpo de la solicitud
const cart = await cartDao.update(cid, body); // Actualiza el carrito en la base de datos
if (!cart) return res.status(404).json({ status: "Error", msg: `No se encontrรณ el carrito con el id ${cid}` }); // Si no se encuentra el carrito, devuelve un error 404
res.status(200).json({ status: "success", payload: cart }); // Devuelve el carrito actualizado en la respuesta
} catch (error) {
console.log(error); // Imprime el error en la consola para depuraciรณn
res.status(500).json({ status: "Error", msg: "Error interno del servidor" }); // Devuelve un error 500 en caso de fallo
}
});
// Ruta para eliminar todos los productos de un carrito por su ID
router.delete("/:cid", async (req, res) => {
try {
const { cid } = req.params; // Obtiene el ID del carrito de los parรกmetros de la URL
const cart = await cartDao.deleteAllProductsInCart(cid); // Elimina todos los productos del carrito
if (!cart) return res.status(404).json({ status: "Error", msg: `No se encontrรณ el carrito con el id ${cid}` }); // Si no se encuentra el carrito, devuelve un error 404
res.status(200).json({ status: "success", payload: cart }); // Devuelve el carrito actualizado en la respuesta
} catch (error) {
console.log(error); // Imprime el error en la consola para depuraciรณn
res.status(500).json({ status: "Error", msg: "Error interno del servidor" }); // Devuelve un error 500 en caso de fallo
}
});
export default router; // Exporta el router para que pueda ser utilizado en otras partes de la aplicaciรณn
|
navCAS navigation system
@author: Axel Mancino ([email protected])
#ifndef AXIS_ANNOTATION_2D_H
#define AXIS_ANNOTATION_2D_H
#include <mitkVtkAnnotation2D.h>
#include <mitkLocalStorageHandler.h>
#include <mitkAnnotation.h>
#include <vtkSmartPointer.h>
#include <vtkAxisActor2D.h>
class vtkPolyData;
class vtkActor2D;
class vtkPolyDataMapper2D;
/** \brief Displays PolyDatas as overlays */
class AxisAnnotation2D : public mitk::VtkAnnotation2D {
public:
mitkClassMacro(AxisAnnotation2D, mitk::VtkAnnotation2D);
itkFactorylessNewMacro(Self)
itkCloneMacro(Self)
class LocalStorage : public mitk::Annotation::BaseLocalStorage
{
public:
/** \brief Actor of a 2D render window. */
//vtkSmartPointer<vtkAxisActor2D> m_LineActor;
vtkSmartPointer<vtkActor2D> m_LineActor;
vtkSmartPointer<vtkPolyData> m_Line;
vtkSmartPointer<vtkPolyDataMapper2D> m_LineMapper;
mitk::Point2D m_P0;
mitk::Point2D m_P1;
mitk::Point2D m_PrevP0;
mitk::Point2D m_PrevP1;
/** \brief Timestamp of last update of stored data. */
itk::TimeStamp m_LastUpdateTime;
/** \brief Default constructor of the local storage. */
LocalStorage();
/** \brief Default deconstructor of the local storage. */
~LocalStorage();
};
void SetLinePoints(mitk::Point2D point0, mitk::Point2D point1, mitk::BaseRenderer *renderer);
vtkProp* GetInternalVtkProp(mitk::BaseRenderer* renderer)
{
return GetVtkProp(renderer);
}
protected:
/** \brief The LocalStorageHandler holds all LocalStorages for the render windows. */
mutable mitk::LocalStorageHandler<LocalStorage> m_LSH;
virtual vtkActor2D* GetVtkActor2D(mitk::BaseRenderer *renderer) const;
void UpdateVtkAnnotation2D(mitk::BaseRenderer *renderer);
/** \brief explicit constructor which disallows implicit conversions */
explicit AxisAnnotation2D();
/** \brief virtual destructor in order to derive from this class */
virtual ~AxisAnnotation2D();
private:
/** \brief copy constructor */
AxisAnnotation2D(const AxisAnnotation2D&);
/** \brief assignment operator */
AxisAnnotation2D& operator=(const AxisAnnotation2D&);
};
#endif // AXIS_ANNOTATION_2D_H
|
/* eslint import/no-namespace:0 */
/* eslint react/forbid-component-props: 0 */
import React from "react";
import { BsArrowRight } from "react-icons/bs";
import { RiCloseFill } from "react-icons/ri";
import { AirsLink } from "../../AirsLink";
import {
BannerButton,
BannerItem,
BannerList,
BannerTitle,
CloseContainer,
} from "../styles/styledComponents";
interface IProps {
buttonText: string;
close: () => void;
title: string;
url: string;
}
const InformativeBannerItems: React.FC<IProps> = ({
buttonText,
close,
title,
url,
}: IProps): JSX.Element => (
<BannerList>
<div className={"w-auto flex flex-wrap center"}>
<BannerItem>
<BannerTitle>{title} </BannerTitle>
</BannerItem>
<BannerItem>
<AirsLink decoration={"none"} href={url}>
<BannerButton>
{buttonText} <BsArrowRight size={15} />
</BannerButton>
</AirsLink>
</BannerItem>
<CloseContainer>
<RiCloseFill className={"pointer white"} onClick={close} size={25} />
</CloseContainer>
</div>
</BannerList>
);
export { InformativeBannerItems };
|
package GET_Request;
import java.io.IOException;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.markuputils.CodeLanguage;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import Base_Package.Login;
import Base_Package.Path;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
public class Get_the_payslips_of_the_employee extends Login{
static ExtentTest Message;
@Test
public static void get_the_payslips_of_the_employee() throws IOException {
Message=extent.createTest("Get_the_payslips_of_the_employee").assignAuthor("QA_Team").assignCategory("GET_Request");
Userlogin();
Response response = RestAssured.given()
.header("Authorization","jwt "+Token)
.param("year", "2023")
.get(base_url+Path.Get_the_payslips_of_the_employee);
JsonPath JP = response.jsonPath();
//Validation
if(response.getStatusCode()==200) {
Message.pass(MarkupHelper.createLabel("Get_the_payslips_of_the_employee", ExtentColor.GREEN));
Message.info(MarkupHelper.createLabel((String) JP.get("message"), ExtentColor.BLUE));
Message.info(MarkupHelper.createLabel(response.getStatusLine(), ExtentColor.BLUE));
Message.info(MarkupHelper.createCodeBlock(response.getBody().asString(), CodeLanguage.JSON)); }
else{
Message.fail(MarkupHelper.createLabel("Get_the_payslips_of_the_employee", ExtentColor.RED));
Message.warning(MarkupHelper.createLabel(response.getStatusLine(), ExtentColor.ORANGE));
Message.warning(MarkupHelper.createLabel((String) JP.get("message"), ExtentColor.ORANGE));
Message.info(MarkupHelper.createCodeBlock(response.getBody().asString(), CodeLanguage.JSON));}
}
}
|
"use client";
import { useState } from "react";
import Image from "next/image";
const ProductCard = ({ product }) => {
const [toggleText, setToggleText] = useState(false);
return (
<div className="py-8">
<Image
src={product.img}
alt="product_image"
width={480}
height={360}
loading="lazy"
className="duration-300 hover:scale-95"
/>
<h2 className="text-3xl py-4 px-2 ">{product.title}</h2>
<p className="text-sm max-w-md px-2 text-[#606060]">
{product.description.substring(1, toggleText ? 500 : 90)}
{toggleText ? <></> : <span>...</span>}
</p>
<button
className="mx-2 my-4 border-b-[3px] text-red-400 border-red-400"
onClick={() => setToggleText(!toggleText)}
>
{toggleText ? "Read Less" : "Read More"}
</button>
</div>
);
};
export default ProductCard;
|
//
// HomeVideosContainerView.swift
// NewLife
//
// Created by Shadi on 27/02/2019.
// Copyright ยฉ 2019 Inceptiontech. All rights reserved.
//
import UIKit
class HomeVideosContainerView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
var videos: [HomeVideoCellVM] = [] {
didSet {
reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
initialize()
}
private func initialize() {
backgroundColor = UIColor.clear
collectionView.backgroundColor = UIColor.clear
pageControl.tintColor = UIColor.white.withAlphaComponent(0.5)
pageControl.currentPageIndicatorTintColor = UIColor.white
}
private func reloadData() {
pageControl.numberOfPages = videos.count
collectionView.reloadData()
DispatchQueue.main.async { [weak self] in
self?.updatePageControl()
}
}
private func updatePageControl() {
let pageWidth = collectionView.frame.size.width
var page = Int(floor((collectionView.contentOffset.x - pageWidth / 2) / pageWidth) + 1)
page = (videos.count - 1) - page
pageControl.isHidden = true// (videos.count < 2)
pageControl.currentPage = page
}
}
extension HomeVideosContainerView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return videos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeVideoCollectionCell.identifier, for: indexPath) as! HomeVideoCollectionCell
cell.data = videos[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.frame.size
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeVideoCollectionCell.identifier, for: indexPath) as! HomeVideoCollectionCell
cell.pause()
cell.videoBackground = nil
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
updatePageControl()
}
}
|
import Image, { StaticImageData } from 'next/image';
import Grid from './Grid';
interface ProductGridWithImageProps {
image: StaticImageData;
reverseOrder?: boolean;
products: JSX.Element[];
additionalClasses?: string;
}
const ProductGridWithImage = ({
image,
reverseOrder,
products,
additionalClasses,
}: ProductGridWithImageProps) => {
return (
<div
className={`flex flex-1 flex-row w-full gap-16 lg:justify-center xl:justify-start ${
additionalClasses ?? ''
}`}
>
<Image
className={`hidden xl:flex xl:flex-1 w-full h-auto max-w-md ${
reverseOrder ? 'order-1' : 'order-none'
}`}
alt="Side Image"
src={image}
/>
<Grid
columns={3}
additionalClasses="gap-x-10 gap-y-16 pt-5"
elements={products}
/>
</div>
);
};
export default ProductGridWithImage;
|
Welcome
Welcome
Welcome to the Distant Worlds tutorial. In this tutorial you will learn the basics of how to run your empire.
To progress through each step of this tutorial click the 'Continue' button.
You can move this tutorial window by dragging it with the mouse.
Let's get started: click the 'Continue' button below.
~
Introduction
Introduction
Distant Worlds is a complex game, but the goal is simple: build and maintain a galactic empire.
In the game you focus on 4 key areas:
- Explore the galaxy
- Colonize new planets
- Extract valuable resources
- Defend your empire
~
The Galaxy
The Galaxy
The Galaxy is a big place - it's packed with new worlds to find, alien races to discover and resources to exploit.
Let's take a look at how you can move around the galaxy.
~
Moving Around
Moving Around
The main view shows a portion of the galaxy - in this case a small portion of one star system near one of your colony planets.
Move the mouse pointer to the edge of the screen to scroll the main view up, down, left or right. You can also use the arrow keys on your keyboard to do the same thing.
You can also drag the main view by holding down the right mouse button.
~
Moving Around - Zooming
Moving Around - Zooming
You can also zoom the main view in or out to see more or less of the galaxy.
Use the mouse scroll wheel to zoom the main view in or out. You can also use the PageUp and PageDown keys to do the same thing.
~
Zoom buttons
Zoom buttons
The ZoomIn and ZoomOut buttons on the main screen also allow you to zoom in or out.
~
System view
System view
When zoomed out to system level you can identify the colonies and ships for an empire by the empire's main color.
You can zoom in to any location by holding down the 'Ctrl' key while clicking.
~
Sector view
Sector view
As you zoom out further the main view changes to show systems.
At this level ships and bases are shown as icons. The icon color indicates which empire the ship or base belongs to.
~
Explored Systems
Explored Systems
Systems that you have explored have their names displayed next to them.
~
Unexplored Systems
Unexplored Systems
Systems that you have not yet explored have no name displayed next to them.
~
Colonized Systems
Colonized Systems
Systems that have been colonized by an empire are circled with their empire's color.
The size of the circle indicates the system's relative importance - larger systems are more valuable.
~
Empire Territory
Empire Territory
Systems that are part of an empire's territory have a colored background.
A system can be owned by an empire even when it is not colonized.
Colonies project their empire's influence into nearby systems, making them part of their empire's territory.
~
Independent Systems
Independent Systems
Some systems have independent colonies of aliens that do not belong to any empire.
These independent systems are circled with a solid grey line.
They can be good targets for your empire to colonize - the aliens provide a critical boost to the population of your new colony, allowing it to quickly start earning income for your empire.
~
Systems with Potential Colonies
Systems with Potential Colonies
Any systems with potential colonies are indicated by a dashed grey circle.
Build a new colony ship and send it to these uninhabited planets to establish a new colony for your empire.
~
Zoom presets
Zoom presets
The Zoom buttons allow you to instantly zoom to several preset levels:
- 100% (default)
- system view
- sector view
- galaxy view
~
Galactopedia Help
Galactopedia Help
The Galactopedia provides context-sensitive help on the currently selected item or the currently open screen.
It contains detailed information on all the different types of planets and ships you encounter in the galaxy. It also describes game concepts and explains each game screen.
You can access the Galactopedia Help system at any time by pressing F1 or by clicking the Help button.
~
Main Screen elements
Main Screen elements
Let's take a quick tour of some of the other elements on the main screen.
~
Selection Panel
Selection Panel
At the bottom left of the screen is the Selection Panel.
This displays detailed information on the selected item, whether that be a colony, ship, system, etc.
To select an item in the main screen simply click on it with the mouse.
~
Empire Navigation Tool
Empire Navigation Tool
At the left of the screen is the Empire Navigation Tool. This is a set of scrollable lists that provide quick access to everything in your empire.
This includes items like: your colonies, space ports, construction ships, exploration ships, enemy targets, fleets, new potential colonies, potential mining locations, and much more.
Click an icon to open one of the lists. Click the icon again to close the list, or use the close button at the right of the list's title bar.
~
Empire Navigation Tool contd.
Empire Navigation Tool contd.
Click an item in a list to select it in the Selection Panel below.
You can then use the Action buttons under the Selection Panel to access many common tasks for the selected item, allowing you to easily manage most of your empire directly from the main screen.
Double-clicking an item in a list will move the main view to that item.
When you are zoomed out to the sector- or galaxy-level then hovering over an item in a list will 'ping' the location of that item in the galaxy with an expanding yellow circle.
~
Map
Map
At the bottom right is a map. This shows the surrounding area.
The area displayed in the main view is indicated by the blue rectangle in the middle of the map.
Click anywhere on the map to move the main view to that location.
The map automatically zooms in or out when you zoom the main view.
~
Scrolling message list
Scrolling message list
At the top of the screen is a list that displays recent events that have occurred in your empire.
Click on an event in this list to move to the location of the event.
~
Pause/Resume
Pause/Resume
At the top-left of the screen is the Pause button. This allows you to pause or resume the game at any time.
Click once to pause the game. Click again to resume the game.
~
Game Menu
Game Menu
At the top-left of the screen is the Game Menu button.
This accesses the Game Menu where you can load and save games, alter game options or exit the game.
~
Game Options
Game Options
The Game Options screen (O key) allows you to customize game settings.
In particular, you can automate certain empire tasks like Colonization, Ship Building, etc. This allows you to focus on other areas of your empire that interest you more.
When you first start Distant Worlds many tasks are automated for you. The automation of these tasks can be progressively turned off, as you desire greater control over the details of your empire.
~
Your Empire
Your Empire
Now let's get an overview of your empire.
You can view a summary of your empire from the Empire Summary screen (F6). Click the Empire Summary button to show this screen.
~
State vs Private
State vs Private
Your empire is divided into two sections:
- State: the portion you control
- Private: your private citizens who go about their own business without your help
Note that you only control the State portion of your empire. You have no direct control of your private citizens activities.
~
Private Citizens
Private Citizens
Your private citizens go about their own business, improving their colonies.
This means that they trade goods, transport cargo and mine resources - all without any intervention from you.
~
State Activities
State Activities
The state portion of your empire has four basic tasks:
- Exploring the galaxy
- Colonizing new planets
- Constructing new ships
- Defending your empire
~
Government Style
Government Style
Each empire follows a particular style of government. Each government type has specific advantages and disadvantages.
You can change your government style by having a revolution. But there are negative side effects from revolution, including a temporary setback of development at your colonies.
~
State Income
State Income
Money is critical to fund your empire. Your state economy derives income from four areas:
- colony taxes
- transaction fees at your space ports
- purchases of new ships by your private citizens
- bonuses from trade with other empires
~
Colonies
Colonies
Let's take a look at the colonized planets in your empire.
Colonies are the heart of your empire. When you lose all of your colonies, you lose the game.
~
Colonies - Tax
Colonies - Tax
Colonies produce wealth. Your empire's main revenue comes from taxing colonies.
By default colony tax levels are controlled automatically, but you can alter each colony tax rate directly if you prefer.
~
Colonies - Growth
Colonies - Growth
Colonies grow in two ways: population and development level
Population: grows over time until it reaches a maximum level for the planet.
Development Level: when a colony receives a steady supply of luxury resources its general development level grows. Higher development level means more wealth and thus more tax revenue.
~
Population Indicator
Population Indicator
The population size and development level of a colony is indicated by the graph displayed in the colony's name badge.
The horizontal axis indicates the population size. The vertical axis relates to the development level.
~
Empire and Capital
Empire and Capital
The empire owning a colony is indicated by the color of the surrounding circle and name badge. If the colony is the empire capital a gold star also appears to the left of the name.
~
Dominant Race
Dominant Race
The dominant alien race at the colony is displayed at the bottom of the name badge.
~
Resources
Resources
The natural resources present at the colony are also displayed at the bottom of the name badge.
These resources at your colonies are automatically mined and then used, either to build things or to be sold.
~
Colony List
Colony List
A complete list of all the colonies in your empire is available from the Colonies screen.
You can open this screen using the button indicated or by pressing the 'F2' key.
~
Colonies - Cycling
Colonies - Cycling
You can quickly cycle through all of the colonies in your empire by using the Cycle Colonies button.
You can do the same thing by pressing the 'C' key.
~
Ships and Bases
Ships and Bases
Now let's take a look at ships and bases.
Ships travel throughout the galaxy performing a wide range of tasks, from transporting cargo to defending your empire.
Bases are fixed platforms in space, usually located at a planet.
To see a complete list of all the ships and bases in your empire click the Ships and Bases button (F11 key).
~
Ships and Bases - Designing
Ships and Bases - Designing
All your empire's ships and bases can be designed to your exact specifications in the Designs screen (F8 key).
See the Advanced tutorial for more information on how to do this.
~
Assigning Missions
Assigning Missions
You can assign missions to any state-owned ship or base in your empire.
However this does NOT include privately-owned ships like freighters, mining ships or mining stations. You have no control over these privately-owned ships and bases. They go about their business automatically, selecting missions for themselves.
~
Assigning a Mission
Assigning a Mission
To assign a mission to a ship first select it in the main view by left-clicking on it with the mouse.
Then right-click the mouse over the mission target, e.g. to make a ship move to another location right-click the mouse at that location.
Note that you may need to unpause the game to see the ship move.
~
Missions - Popup Menu
Missions - Popup Menu
Right-clicking on the ship or base may also bring up a popup menu listing a number of missions.
These missions are specific to the particular type of ship or base. They may include: Exploration, Colonization, Building, Refueling, or many others.
~
Automating Missions
Automating Missions
Ships can also be completely automated. This means that they assign missions for themselves.
To automate a ship first select it and then press the 'A' key. To turn off automation just assign a mission to the ship.
When a ship is automated a circular blue arrow appears in the bottom-right corner of the Selection Panel.
Note that ALL ships start the game automated.
~
Missions for Bases
Missions for Bases
Although bases are stationary, they can also have missions.
Base missions can include: building new ships, retrofitting to a new design or scrapping the base when it is no longer needed.
~
Types of Ships and Bases
Types of Ships and Bases
Let's take a look at the different types of ships and bases in your empire.
~
Exploration Ships
Exploration Ships
Exploration ships chart unknown areas of the galaxy. As they explore they reveal colonizable planets, uncover valuable resources and make contact with other empires.
Exploration ships can be automated to explore on their own ('A' key).
To cycle through all of your Exploration ships use the Cycle Colony and Exploration Ships button, or use the 'X' key.
~
Colony Ships
Colony Ships
Colony ships allow you to colonize other planets, founding new worlds for your empire.
The ship is consumed when a new colony is established. The resources from the ship are used to give the colony a kickstart.
While most ships are built at space ports, Colony ships can only be built at colonies.
~
Colony Ships contd.
Colony Ships contd.
To start with you can only colonize the native planet type of your race. But as your research uncovers new technology you can progressively colonize other types of planets.
However you can always colonize planets where there is an existing independent alien population - regardless of the type of planet. In these situations the preexisting population may resist your colonization attempt, with the loss of your colony ship.
To cycle through all your colony ships use the Cycle Colony and Exploration Ships button, or use the 'X' key.
~
Space Ports
Space Ports
Space Ports are bases that provide many important services for your empire. Space Ports must always be built at a colony.
They serve as a central point of trade for your empire. Mined resources are brought here by freighters and mining ships.
Space Ports also provide construction facilities for your empire. Both state and private ships are built here. When private citizens purchase freighters or other ships, your empire earns income.
~
Space Ports contd.
Space Ports contd.
Space Ports also provide other vital functions:
- Heavy weapons provide strong defense for the colony
- Research facilities for your scientists and engineers
- Bonuses that help keep the colony population happy: medical facilities and recreation centres
To cycle through all of your Space Ports use the Cycle Space Ports button, or use the 'P' key.
~
Freighters
Freighters
Freighters transport cargo between colonies, mining stations and space ports. They come in small, medium and large sizes.
Freighters work for your empire, but they are not yours. They belong to the private citizens in your empire. All transportation of goods in your empire is performed by private citizens.
Thus you cannot assign missions to Freighters.
~
Mining Ships
Mining Ships
Mining Ships are mobile resource extraction ships. They mine resources that are in high demand, returning them to your nearest space port.
Mining ships work for your empire, but they are not yours. They belong to the private citizens in your empire.
Thus you cannot assign missions to Mining ships.
~
Mining Stations
Mining Stations
Mining Stations are bases that extract resources from planets, moons, asteroids and gas clouds.
They can be either standard mining stations or gas mining stations.
Mining Stations are built by Construction Ships at resource-rich planets.
~
Construction Ships
Construction Ships
Construction Ships are mobile construction yards. They can build bases at uninhabited planets or even in deep space.
Use the Cycle Construction Ships button to cycle through all the construction ships in your empire, or use the 'Y' key.
~
Military Ships
Military Ships
Military ships defend your empire from enemy empires and from marauding pirates.
They can be assigned the following missions:
- Attack an enemy target
- Patrol a colony or base, watching for attackers
- Escort a civilian ship, such as a construction ship or mining ship
There are various sizes and classes of military ships.
Use the Cycle Military Ships button to cycle through them, or use the 'M' key.
~
Find Idle Ships
Find Idle Ships
You can find ships that don't currently have a mission by clicking the Cycle Idle Ships button (or press the I key).
This helps you find ships that are not being used so that you can assign missions to them.
~
Completed
Completed
Thank you for taking this tutorial. Now go and explore the galaxy and build your empire!
When you are ready you can also try the Advanced Tutorial from the main menu.
~
|
#' Create Specifications for R Function
#'
#' @title Create Specifications for R Function
#' @description This function generates specifications for an R function from your selected text or clipboard.
#' It takes in a text input, model name, verbosity, and tone speed to generate the specifications.
#' @param Model A character string specifying the GPT model to be used. Default is "gpt-4-0613".
#' @param SelectedCode A logical flag to indicate whether to read from RStudio's selected text. Default is TRUE.
#' @param verbose A logical value indicating whether to print the output. Default is TRUE.
#' @param SlowTone A logical value indicating whether to print the output slowly. Default is FALSE.
#' @importFrom assertthat assert_that is.string noNA
#' @importFrom rstudioapi isAvailable getActiveDocumentContext
#' @importFrom clipr read_clip write_clip
#' @return The function prints the generated specifications to the console.
#' @export createSpecifications4R
#' @author Satoshi Kume
#' @examples
#' \dontrun{
#' # Option 1
#' # Select some text in RStudio and then run the rstudio addins
#' # Option 2
#' # Copy the text into your clipboard then execute
#' createSpecifications4R(input = "Your R function specification")
#' }
createSpecifications4R <- function(Model = "gpt-4-0613",
SelectedCode = TRUE,
verbose = TRUE,
SlowTone = FALSE) {
# Get input either from RStudio or clipboard
if(SelectedCode){
assertthat::assert_that(rstudioapi::isAvailable())
input <- rstudioapi::getActiveDocumentContext()$selection[[1]]$text
} else {
input <- paste0(clipr::read_clip(), collapse = " \n")
}
if(verbose){
cat("\n", "createSpecifications4R: ", "\n")
pb <- utils::txtProgressBar(min = 0, max = 3, style = 3)
}
# Assertions for input validation
assertthat::assert_that(
assertthat::is.string(input),
assertthat::noNA(input),
Sys.getenv("OPENAI_API_KEY") != ""
)
# Initialize temperature
temperature = 1
if(verbose){utils::setTxtProgressBar(pb, 1)}
# Create template for the prompt
template = "
You are an excellent assistant and a highly skilled genius R programmer to build specifications of R function.
You should always carefully understand the intent of the ideas and concepts you are given,
and be prepared to be specific in your specifications in an appropriate and comprehensive manner.
You need to prepare an R function requirements specification for project and technical overview, main functions,
input parameters, output parameters, use cases or applications, and constraints.
Finally, you need to make proposals for items missing from the above requirements definition.
You are sure to output only the deliverables in the requirements definition.
The language used in the output deliverables must be the same as the language of the following input.
"
template1 = "
Please provide an overview of the requirements definition for an R function based on the following input.:
"
# Substitute arguments into the prompt
template1s <- paste0(template1, paste0(input, collapse = " "), sep=" ")
# Create prompt history
history <- list(list('role' = 'system', 'content' = template),
list('role' = 'user', 'content' = template1s))
if(verbose){utils::setTxtProgressBar(pb, 2)}
# Execute the chat model
res <- chat4R_history(history=history,
Model = Model,
temperature = temperature)
if(verbose){
utils::setTxtProgressBar(pb, 3)
cat("\n")}
# Output
if(SelectedCode){
rstudioapi::insertText(text = as.character(res))
} else {
if(verbose) {
if(SlowTone) {
d <- ifelse(20/nchar(res) < 0.3, 20/nchar(res), 0.3)*stats::runif(1, min = 0.95, max = 1.05)
slow_print_v2(res, delay = d)
} else {
d <- ifelse(10/nchar(res) < 0.15, 10/nchar(res), 0.15)*stats::runif(1, min = 0.95, max = 1.05)
slow_print_v2(res, delay = d)
}
}
return(clipr::write_clip(res))
}
}
|
import { Injectable } from '@angular/core';
import {AuthChangeEvent, createClient, Session, SupabaseClient} from '@supabase/supabase-js';
import {environment} from "../../../environments/environment";
import { Profile } from '../interfaces/profile';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private supabase: SupabaseClient;
constructor() {
this.supabase = createClient(environment.supabaseUrl, environment.supabaseKey);
}
get user() {
return this.supabase.auth.user();
}
get session() {
return this.supabase.auth.session();
}
get profile() {
return this.supabase
.from('profiles')
.select(`first_name, last_name, avatar_url, address`)
.eq('id', this.user?.id)
.single();
}
authChanges(callback: (event: AuthChangeEvent, session: Session | null) => void) {
return this.supabase.auth.onAuthStateChange(callback);
}
signIn(email: string) {
return this.supabase.auth.signIn({email});
}
signOut() {
return this.supabase.auth.signOut();
}
updateProfile(profile: Profile) {
const update = {
...profile,
id: this.user?.id,
updated_at: new Date()
}
console.log(update)
return this.supabase.from('profiles').upsert(update, {
returning: 'minimal', // Don't return the value after inserting
});
}
downLoadImage(path: string) {
return this.supabase.storage.from('avatars').download(path);
}
uploadAvatar(filePath: string, file: File) {
return this.supabase.storage
.from('avatars')
.upload(filePath, file);
}
}
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Template extends MY_Restrictedzone {
public function password()
{
$this->load->model('User_model', 'User');
$data = array(
'controller' => 'template',
'page' => 'password',
'title' => 'Site info',
);
$data['successful'] = false;
$this->form_validation->set_rules('password_old', 'Old password', 'trim|required|callback_oldpassword_check');
$this->form_validation->set_rules('password_new', 'New password', 'trim|required');
$this->form_validation->set_rules('password_re', 'Repeat password', 'trim|required|matches[password_new]');
if ($this->form_validation->run() !== FALSE)
{
$this->User->changePassword($this->User->getAccountId(), $this->input->post('password_new'));
$data['successful'] = true;
}
$this->load->view('admin/page-template-password', $data);
}
public function topmenu($form_lang = NULL)
{
$this->load->model('Siteinfo_model', 'Siteinfo');
$this->load->model('Languages_model', 'LangModel');
$data = array(
'controller' => 'template',
'page' => 'topmenu',
'title' => 'Top menu',
);
$form_lang = ($form_lang == NULL) ? $this->LangModel->get_primary()['lang'] : $form_lang;
$data['form_lang'] = $form_lang;
$data['content_langs'] = $this->LangModel->get();
$data['successful'] = false;
$data['email'] = isset($_POST['email_contact']) ? $this->input->post('email_contact') : $this->Siteinfo->get('email_contact');
for ($i=1; $i<=5; ++$i) {
$this->form_validation->set_rules('topmenu-item-'.$i, 'Item '.$i, 'required');
}
if ($this->form_validation->run() !== FALSE)
{
for ($i=1; $i<=5; ++$i) {
$this->LangModel->save_content('topmenu-item-'.$i, $form_lang, $this->input->post('topmenu-item-'.$i));
}
$data['successful'] = true;
}
for ($i=1; $i<=5; ++$i) {
$data['topmenu_item_'.$i] = isset($_POST['topmenu-item-'.$i])
? $this->input->post('topmenu-item-'.$i)
: $this->LangModel->get_content('topmenu-item-'.$i, $form_lang);
}
$this->load->view('admin/page-template-topmenu', $data);
}
public function footer($form_lang = NULL)
{
$this->load->model('Languages_model', 'LangModel');
$data = array(
'controller' => 'template',
'page' => 'footer',
'title' => 'Template - footer',
);
$form_lang = ($form_lang == NULL) ? $this->LangModel->get_primary()['lang'] : $form_lang;
$data['form_lang'] = $form_lang;
$data['successful'] = false;
$data['content'] = isset($_POST['content'])
? $this->input->post('content')
: $this->LangModel->get_content('pagecontent-footer', $form_lang);
$data['copyright'] = isset($_POST['copyright'])
? $this->input->post('copyright')
: $this->LangModel->get_content('pagecontent-copyright', $form_lang);
$this->form_validation->set_rules('content', 'Content', 'required');
$this->form_validation->set_rules('copyright', 'Copyright', 'required');
if ($this->form_validation->run() !== FALSE)
{
$this->LangModel->save_content('pagecontent-footer', $form_lang, $this->input->post('content'));
$this->LangModel->save_content('pagecontent-copyright', $form_lang, $this->input->post('copyright'));
$data['successful'] = true;
}
$data['content_langs']=$this->LangModel->get();
$this->load->view('admin/page-template-footer', $data);
}
public function pageheader($form_lang = NULL)
{
$this->load->model('Languages_model', 'LangModel');
$this->load->model('Header_model', 'Header');
$data = array(
'controller' => 'template',
'page' => 'pageheader',
'title' => 'Template - Header',
);
$form_lang = ($form_lang == NULL) ? $this->LangModel->get_primary()['lang'] : $form_lang;
$data['form_lang'] = $form_lang;
$data['successful'] = false;
$this->form_validation->set_rules('content', 'Content', 'required');
if ($this->form_validation->run() !== FALSE)
{
$this->LangModel->save_content('pagecontent-header', $form_lang, $this->input->post('content'));
$this->LangModel->save_content('company-name', $form_lang, $this->input->post('company_name'));
$this->LangModel->save_content('company-domain', $form_lang, $this->input->post('company_domain'));
$this->LangModel->save_content('company-register', $form_lang, $this->input->post('company_register'));
$data['successful'] = true;
}
if (isset($_POST['save']))
{
$config=array();
$config['upload_path'] = './assets/img/header/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 3000;
$config['max_width'] = 6000;
$config['max_height'] = 6000;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$upload_image=NULL;
if(isset($_FILES['logo-image']) && !empty($_FILES['logo-image']['name']))
{
if ($this->upload->do_upload('logo-image'))
{
$upload_info=$this->upload->data();
$upload_image = base_url('assets/img/header/'.$upload_info['file_name']);
$this->Header->update_logo_img($upload_image);
}
else
{
echo $this->upload->display_errors();
$this->form_validation->set_message('upload_image', $this->upload->display_errors());
}
}
$upload_image=NULL;
if(isset($_FILES['brand-image']) && !empty($_FILES['brand-image']['name']))
{
if ($this->upload->do_upload('brand-image'))
{
$upload_info=$this->upload->data();
$upload_image = base_url('assets/img/header/'.$upload_info['file_name']);
$this->Header->update_brand_img($upload_image);
}
else
{
echo $this->upload->display_errors();
$this->form_validation->set_message('upload_image', $this->upload->display_errors());
}
}
}
$data['logo_img']=$this->Header->get_logo_img();
$data['content'] = isset($_POST['content'])
? $this->input->post('content')
: $this->LangModel->get_content('pagecontent-header', $form_lang);
$data['company_name'] = isset($_POST['company_name'])
? $this->input->post('company_name')
: $this->LangModel->get_content('company-name', $form_lang);
$data['company_domain'] = isset($_POST['company_domain'])
? $this->input->post('company_domain')
: $this->LangModel->get_content('company-domain', $form_lang);
$data['company_register'] = isset($_POST['company_register'])
? $this->input->post('company_register')
: $this->LangModel->get_content('company-register', $form_lang);
$data['content_langs']=$this->LangModel->get();
$this->load->view('admin/page-template-header', $data);
}
public function oldpassword_check($old_password)
{
$this->load->model('User_model', 'User');
$old_password_hash = md5($old_password);
$old_password_db_hash = $this->User->getPassword($this->User->getAccountId());
if($old_password_hash != $old_password_db_hash)
{
$this->form_validation->set_message('oldpassword_check', 'Old password not match');
return FALSE;
}
return TRUE;
}
public function traffic()
{
$this->load->model('Traffic_model', 'Traffic');
$today=date('Y-m-d');
$range=10;
$stats=array();
for($i=$range; $i>=0; --$i) {
$day = date('Y-m-d', strtotime('-'.$i.' day', strtotime($today)));
$stats[$day]=$this->Traffic->countPerDay($day);
}
$data = array(
'controller' => 'template',
'page' => 'traffic',
'title' => 'Site traffic',
'stats' => $stats
);
$this->load->view('admin/page-template-traffic', $data);
}
}
|
import 'package:dartz/dartz.dart';
import 'package:finjan/core/error/failure.dart';
import 'package:finjan/features/home/data/model/coffe_category.dart/cofffee_category_model.dart';
import 'package:finjan/features/home/data/remote_data/remote_data.dart';
import 'package:finjan/features/home/domain/repository/get_coffe_Repository.dart';
import 'package:finjan/features/test_model.dart';
class GetCoffeRepositoryImpl implements GetCoffeRepository {
RemoteData remoteData;
GetCoffeRepositoryImpl({required this.remoteData});
@override
Future<Either<Failure, List<CoffeeTestModel>>> getCoffe() async {
try {
var response = await remoteData.getCoffe();
return Right(response);
} catch (error) {
return Left(ServerFailure());
}
}
@override
Future<Either<Failure, List<CoffeCategory>>> getHotCoffe() async {
try {
var response = await remoteData.getHotCoffee();
return Right(response);
} catch (error) {
return Left(ServerFailure());
}
}
@override
Future<Either<Failure, List<CoffeCategory>>> getIcedCoffe() async{
try {
var response = await remoteData.getIcedCoffee();
return Right(response);
} catch (error) {
return Left(ServerFailure());
}
}
}
|
class Size : Step {
static [string] hidden $description = @'
Specify the size of your Software Risk Manager deployment using
the following guidelines:
SIZE | TOTAL PROJECTS | DAILY ANALYSES | CONCURRENT ANALYSES
-------------------------------------------------------------------
Small 1 - 100 1,000 8
Medium 100 - 2,000 2,000 16
Large 2,000 - 10,000 10,000 32
Extra Large 10,000+ 10,000+ 64
Note: Select "Unspecified" if you want to enter CPU and memory
requirements on a per-component basis (not recommended).
'@
Size([Config] $config) : base(
[Size].Name,
$config,
'Deployment Size',
[Size]::description,
'What is your deployment size?') { }
[IQuestion] MakeQuestion([string] $prompt) {
return new-object MultipleChoiceQuestion($prompt, @(
[tuple]::create('&Unspecified', 'Size is unknown; specify CPU and memory per component'),
[tuple]::create('&Small', 'Total projects between 1 and 100 with 1,000 daily analyses (8 concurrent)'),
[tuple]::create('&Medium', 'Total projects between 100 and 2000 with 2,000 daily analyses (16 concurrent)'),
[tuple]::create('&Large', 'Total projects between 2,000 and 10,000 with 10,000 daily analyses (32 concurrent)'),
[tuple]::create('&Extra Large', 'Total projects in excess of 10,000 with more than 10,000 daily analyses (64 concurrent)')), 1)
}
[bool]HandleResponse([IQuestion] $question) {
switch (([MultipleChoiceQuestion]$question).choice) {
0 { $this.config.systemSize = [SystemSize]::Unspecified }
1 { $this.config.systemSize = [SystemSize]::Small }
2 { $this.config.systemSize = [SystemSize]::Medium }
3 { $this.config.systemSize = [SystemSize]::Large }
4 { $this.config.systemSize = [SystemSize]::ExtraLarge }
}
return $true
}
[void]Reset(){
$this.config.systemSize = [SystemSize]::Unspecified
}
}
|
import React, { useState } from "react";
import { Button, Card, TextField, Typography } from "@mui/material";
import "./SavingsCard.css"; // Import your CSS for transition
import { useNavigate } from "react-router-dom";
import { dateState } from "./store/atoms/date";
import { useRecoilState } from "recoil";
const SavingsCard = () => {
const [income, setIncome] = useState(0);
const [expense, setExpense] = useState(0);
const [savings, setSavings] = useState(0);
const [selectedDate, setSelectedDate] = useRecoilState(dateState);
const [cardType, setCardType] = useState("income");
const navigate = useNavigate();
// const currentDate = new Date();
console.log("selectedDate at savingcard", selectedDate.year);
const handleContinue = async () => {
await fetch(
`${import.meta.env.VITE_SERVER_URL}/data/update-projected-savings`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: "Bearer " + localStorage.getItem("token"),
},
body: JSON.stringify({
projectedYearlySavings: income - expense,
// year: currentDate.getFullYear(),
year: selectedDate.year,
}),
}
)
.then((resp) => {
if (!resp.ok) {
throw new Error("Network response is not ok");
}
resp.json().then((responseData) => {
console.log("response data at update projeted savings", responseData);
// setCourses(data);
if (responseData.success == true) {
// Clear items array after saving
// setMonthlyExpense(responseData.totalExpenses);
navigate("/dashboard");
// setCurrentUserState({
// userEmail: currentUserState.userEmail,
// isLoading: false,
// imageUrl: currentUserState.imageUrl,
// });
} else {
// setCurrentUserState({
// userEmail: null,
// isLoading: false,
// imageUrl: "",
// });
console.error("Error saving projected data:", responseData.error);
}
});
})
.catch((error) => {
// setCurrentUserState({
// userEmail: null,
// isLoading: false,
// imageUrl: "",
// });
console.error("Error saving projected data");
});
};
const handleSave = async (value: number) => {
if (isNaN(value) || value === 0) {
alert("Please enter valid numeric values for income and expense.");
return;
}
console.log("value", value);
if (cardType === "income") {
setIncome(Number(value));
setCardType("expense");
} else if (cardType === "expense") {
setExpense(Number(value));
setCardType("savings");
console.log(income, value);
setSavings(income - Number(value));
}
};
return (
<>
{cardType === "income" && (
<div
className={`transition-card visible ${cardType}`}
// variant="outlined"
style={{
// width: 400,
// minHeight: "350px",
padding: 20,
borderRadius: "20px",
// display: "flex",
// flexDirection: "column",
// justifyContent: "space-between",
background: "white",
}}
>
<div
style={{
display: "flex",
justifyContent: "space-between",
marginBottom: "15px",
}}
>
<Typography variant="h4">Monthly Income</Typography>
</div>
<TextField
// onChange={(e) => setIncome(e.target.value)}
onChange={(e) => {
// Parse the input value to a number
const inputValue = parseFloat(e.target.value);
// Check if the parsed value is a valid number
if (!isNaN(inputValue)) {
setIncome(inputValue);
} else {
alert("Invalid Input");
}
}}
variant="outlined"
fullWidth
multiline
rows={6} // Adjust the number of rows as needed
label="Enter Income"
InputLabelProps={{ shrink: true }}
style={{ marginTop: "5px" }}
/>
<div>
<Button
variant="outlined"
style={{ background: "pink", marginTop: "20px" }}
onClick={() => handleSave(income)}
>
Save
</Button>
</div>
</div>
)}
{cardType === "expense" && (
<div
className={`transition-card visible ${cardType}`}
// variant="outlined"
style={{
// width: 400,
// minHeight: "350px",
padding: 20,
borderRadius: "20px",
background: "white",
// display: "flex",
// flexDirection: "column",
// justifyContent: "space-between",
}}
>
<div
style={{
display: "flex",
justifyContent: "space-between",
marginBottom: "15px",
}}
>
<Typography variant="h4">Monthly Expense</Typography>
</div>
<TextField
// onChange={(e) => setExpense(e.target.value)}
onChange={(e) => {
// Parse the input value to a number
const inputValue = parseFloat(e.target.value);
// Check if the parsed value is a valid number
if (!isNaN(inputValue)) {
setExpense(inputValue);
} else {
alert("Invalid Input");
}
}}
variant="outlined"
fullWidth
multiline // Add this line to allow multiline input
rows={6} // Adjust the number of rows as needed
label="Enter Expense"
InputLabelProps={{ shrink: true }}
style={{ marginTop: "5px" }}
type="number" // Restrict input to numbers
/>
<div>
<Button
variant="outlined"
style={{ background: "pink", marginTop: "20px" }}
onClick={() => handleSave(expense)}
>
Save
</Button>
</div>
</div>
)}
{cardType === "savings" && (
<div
className={`transition-card visible ${cardType}`}
// variant="outlined"
style={{
// width: 400,
// minHeight: "350px",
padding: 20,
borderRadius: "20px",
// marginTop: "20px",
// display: "flex",
// flexDirection: "column",
background: "white",
// justifyContent: "space-between",
}}
>
<div>
<Typography variant="h4" style={{ paddingTop: "10px" }}>
Projected Savings
</Typography>
<Typography variant="h5">{`$${savings * 12}`}</Typography>
</div>
<div>
<Typography variant="h4" style={{ paddingTop: "70px" }}>
Monthly Savings
</Typography>
<Typography variant="h5">{`$${savings}`}</Typography>
</div>
<div>
<Button
variant="outlined"
style={{ marginTop: "20px" }}
onClick={handleContinue}
>
Continue
</Button>
</div>
</div>
)}
</>
);
};
export default SavingsCard;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<div v-text="message"></div>
<!-- {{}}ๅจ็ฝ็ปๅปถ่ฟๆ
ๅตไธไผๅบ็ฐๆๆพ็ๆ
ๅต๏ผๅฏน็จๆทไธๅๅฅฝ -->
{{message}}
<hr>
<div v-html="message"></div>
</div>
</body>
<script src="/node_modules/vue/dist/vue.js"></script>
<script>
//1.ๅฎไพVue
var vm = new Vue({
el: '#app',
data: {
message: "<a href='#'>Hello</a>"
}
})
//v-text ็จไบ็ปๅฎๆฐๆฎ๏ผ่ฏญๆณv-text="ๅฑๆง"๏ผไผ็ดๆฅๅฐๅผไฝไธบๆๆฌๆพ็คบ
//v-html ไผๅฐๅผ่ฟ่ก็ผ่ฏๅๆพ็คบ
//ไฝ ๅฅฝไธ็
</script>
</html>
|
#!/usr/bin/python3
''' Island Perimeter '''
def island_perimeter(grid):
"""
Args:
grid (list): A list of lists representing the grid.
Returns:
int: The perimeter of the island described in a gird.
"""
if not grid:
return 0
rows = len(grid)
cols = len(grid[0])
perimeter = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
perimeter += 4 # Assume that all sides are exposed
if i > 0 and grid[i-1][j] == 1:
perimeter -= 2 # Minus 2 if the cell above is also land
if j > 0 and grid[i][j-1] == 1:
perimeter -= 2 # Minus 2 if cell to the left is also land
return perimeter
|
use crate::loader_config::Configurable;
use crate::Configs;
use serde::Deserialize;
use std::fs;
use std::path::Path;
#[derive(Debug, Deserialize)]
pub struct Cert {
pub cert: String,
pub key: String,
}
pub struct CertKey {
pub cert: Vec<u8>,
pub key: Vec<u8>,
}
impl CertKey {
pub fn new(cert: Vec<u8>, key: Vec<u8>) -> Self {
Self { cert, key }
}
}
pub trait CertProvider {
fn load_certs(&self) -> Result<CertKey, CertError>;
}
#[derive(Debug)]
pub enum CertError {
IoError(std::io::Error),
}
impl From<std::io::Error> for CertError {
fn from(err: std::io::Error) -> Self {
CertError::IoError(err)
}
}
impl CertProvider for Configs {
fn load_certs(&self) -> Result<CertKey, CertError> {
let cert = fs::read(&self.cert.cert)?;
let key = fs::read(&self.cert.key)?;
Ok(CertKey::new(cert, key))
}
}
fn get_string<P: AsRef<Path>>(path: P) -> Result<Vec<u8>, CertError> {
fs::read(path).map_err(CertError::from)
}
pub fn get_cert_key() -> CertKey {
let config = Configs::config();
let cert = get_string(&config.cert.cert).expect("Invalid certificate");
let key = get_string(&config.cert.key).expect("Invalid certificate");
CertKey::new(cert, key)
}
|
<?php
/* **************************************************************************************
Testimonials Post Type
************************************************************************************** */
add_action( 'init', 'swm_posttype_testimonials' );
function swm_posttype_testimonials() {
$labels = array(
'name' => __( 'Testimonials', 'swmtranslate'),
'singular_name' => __( 'Testimonial' , 'swmtranslate'),
'add_new' => __( 'Add New' , 'swmtranslate'),
'add_new_item' => __('Add New testimonial', 'swmtranslate'),
'edit_item' => __('Edit Testimonial', 'swmtranslate'),
'new_item' => __('New Testimonial Item', 'swmtranslate'),
'view_item' => __('View Testimonial Item', 'swmtranslate'),
'search_items' => __('Search Testimonials', 'swmtranslate'),
'not_found' => __('No testimonial items found', 'swmtranslate'),
'not_found_in_trash' => __('No testimonial items found in Trash', 'swmtranslate'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'rewrite' => array('slug' => 'testimonials'),
'show_ui' => true,
'query_var' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title','editor','thumbnail')
);
register_post_type(__( 'testimonials' , 'swmtranslate'),$args);
flush_rewrite_rules();
}
/* ------------------------------------------------------------------------------ */
add_filter("manage_edit-testimonials_columns", "swm_posttype_testimonials_edit_columns");
function swm_posttype_testimonials_edit_columns($columns){
$columns = array(
"cb" => "<input type=\"checkbox\" />",
"title" => __( 'Client Name' , 'swmtranslate'),
"client-details" => __( 'Client Details' , 'swmtranslate'),
"website-name" => __( 'Company or Website Name' , 'swmtranslate'),
"website-url" => __( 'Website URL' , 'swmtranslate')
);
return $columns;
}
/* ------------------------------------------------------------------------------ */
add_action("manage_posts_custom_column", "swm_posttype_testimonials_image_column");
function swm_posttype_testimonials_image_column($column){
global $post;
switch ($column) {
case "title":
echo get_the_title();
break;
case "client-details":
if(get_post_meta($post->ID, "swm_client_details", true)){
echo get_post_meta($post->ID, "swm_client_details", true);
} else {echo '---';}
break;
case "website-name":
if(get_post_meta($post->ID, "swm_website_title", true)){
echo get_post_meta($post->ID, "swm_website_title", true);
} else {echo '---';}
break;
case "website-url":
if(get_post_meta($post->ID, "swm_website_url", true)){
echo get_post_meta($post->ID, "swm_website_url", true);
} else {echo '---';}
break;
}
}
/* Edit "Featured Image" box text --------------------------------------------------- */
add_filter( 'gettext', 'testimonials_post_edit_change_text', 20, 3 );
function testimonials_post_edit_change_text( $translated_text, $text, $domain )
{
if( ( is_testimonials_admin_page() ) ) {
switch( $translated_text ) {
case 'Featured Image' :
$translated_text = __( 'Add Client Image', 'circle-carousel' );
break;
case 'Set Featured Image' :
$translated_text = __( 'Set client image', 'circle-carousel' );
break;
case 'Set featured image' :
$translated_text = __( 'Set client image', 'circle-carousel' );
break;
case 'Remove featured image' :
$translated_text = __( 'Remove client image', 'circle-carousel' );
break;
}
}
return $translated_text;
}
function is_testimonials_admin_page()
{
global $pagenow;
if( $pagenow == 'post-new.php' ) {
if( isset( $_GET['post_type'] ) && $_GET['post_type'] == 'testimonials' )
return true;
}
if( $pagenow == 'post.php' ) {
if( isset( $_GET['post'] ) && get_post_type( $_GET['post'] ) == 'testimonials' )
return true;
}
return false;
}
if( defined( 'DOING_AJAX' ) && 'DOING_AJAX' ) {
if( isset( $_POST['post_id'] ) && get_post_type( $_POST['post_id'] ) == 'testimonials' )
return true;
}
/* **************************************************************************************
Sort Testimonials
************************************************************************************** */
add_action('admin_menu', 'swm_testimonials_sort_order_page');
function swm_testimonials_sort_order_page() {
$swm_sort_order_page_data = add_submenu_page('edit.php?post_type=testimonials', __('Sort Testimonials', 'swmtranslate'), __('Sort Testimonials', 'swmtranslate'), 'edit_posts', basename(__FILE__), 'swm_testimonials_sort_order_list');
}
function swm_testimonials_sort_order_list() {
$testimonials_items = new WP_Query('post_type=testimonials&posts_per_page=-1&orderby=menu_order&order=ASC');
?>
<div class="wrap">
<div id="icon-edit" class="icon32"><br /></div>
<h2><?php _e('Sort Testimonials', 'swmtranslate'); ?></h2>
<p><?php _e('Re-order testimonials items by drag up/down. The top testimonials item will be displayed first. ', 'swmtranslate'); ?></p>
<ul id="swm_sort_items">
<?php while( $testimonials_items->have_posts() ) : $testimonials_items->the_post(); ?>
<?php if( get_post_status() == 'publish' ) { ?>
<li id="<?php the_id(); ?>" class="menu-item">
<dl class="menu-item-bar">
<dt class="menu-item-handle">
<span class="menu-item-title sortable-item-title"><?php the_title(); ?></span>
</dt>
</dl>
<ul class="menu-item-transport"></ul>
</li>
<?php } ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
</ul>
</div>
<?php }
add_action('wp_ajax_swm_sort_order', 'swm_save_testimonials_sort_order');
function swm_save_testimonials_sort_order() {
global $wpdb;
$sort_order = explode(',', $_POST['order']);
$counter = 0;
foreach($sort_order as $testimonials_item_id) {
$wpdb->update($wpdb->posts, array('menu_order' => $counter), array('ID' => $testimonials_item_id));
$counter++;
}
die(1);
}
|
import axios from 'axios'
import { useQuery } from 'react-query'
import MatchDetailSectionError from '../../error/MatchDetailSectionError'
import SkeltonStatisticsLoader from '../../loader/SkeltonStatisticsLoader'
import { Away, Heading, Home, ItemWrapper, Jursey, Label, Manager, ManagerImage, ManagerName, SummaryWrapper } from './styles/Styles'
type Props = {
id: number
}
export default function Summary({ id }: Props) {
const { data, isFetching, error } = useQuery("match stats", async () => {
const response = await axios.get(`https://api.sofascore.com/api/v1/event/${ id }/managers`)
const data = response.data
return data
})
if(isFetching) return <SkeltonStatisticsLoader />
if(error) return <MatchDetailSectionError message='No data available for this match' />
return (
<SummaryWrapper contentContainerStyle={{ alignItems: 'center' }}>
<Heading>Jursey</Heading>
<ItemWrapper>
<Home>
<Jursey source={{ uri: `https://api.sofascore.app/api/v1/event/${ id }/jersey/home/goalkeeper` }} accessibilityLabel="goalkeeper jursey"></Jursey>
</Home>
<Label>Goalkeeper</Label>
<Away>
<Jursey source={{ uri: `https://api.sofascore.app/api/v1/event/${ id }/jersey/away/goalkeeper` }} accessibilityLabel="goalkeeper jursey"></Jursey>
</Away>
</ItemWrapper>
<ItemWrapper>
<Home>
<Jursey source={{ uri: `https://api.sofascore.app/api/v1/event/${ id }/jersey/home/player` }} accessibilityLabel="goalkeeper jursey"></Jursey>
</Home>
<Label>Players</Label>
<Away>
<Jursey source={{ uri: `https://api.sofascore.app/api/v1/event/${ id }/jersey/away/player` }} accessibilityLabel="goalkeeper jursey"></Jursey>
</Away>
</ItemWrapper>
<Heading>Managers</Heading>
<ItemWrapper>
<Manager>
<ManagerImage source={{ uri: `https://api.sofascore.app/api/v1/manager/${ data?.homeManager?.id }/image` }} accessibilityLabel="home team manager"></ManagerImage>
<ManagerName>{ data?.homeManager?.name }</ManagerName>
</Manager>
<Label>Managers</Label>
<Manager>
<ManagerImage source={{ uri: `https://api.sofascore.app/api/v1/manager/${ data?.awayManager?.id }/image` }} accessibilityLabel="home team manager"></ManagerImage>
<ManagerName>{ data?.awayManager?.name }</ManagerName>
</Manager>
</ItemWrapper>
</SummaryWrapper>
)
}
|
package com.okhttpclientdemo.Room;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.okhttpclientdemo.models.User;
@Database(entities = {Person.class, User.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
private static volatile AppDatabase INSTANCE;
public abstract UserDao getPersonDao();
public static AppDatabase getInstance(Context context) {
if (INSTANCE == null) {
synchronized (AppDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "Sample.db")
.build();
}
}
}
return INSTANCE;
}
}
|
import { expect } from "chai";
import { UsersController } from "../../lib/controllers/users.controller";
import { AuthController } from "../../lib/controllers/auth.controller";
import { checkStatusCode, checkResponseTime } from "../../../helpers/functionsForChecking.helper";
const users = new UsersController();
const auth = new AuthController();
const schemas = require("./schemas_testData.json");
const chai = require("chai");
chai.use(require("chai-json-schema"));
let accessToken: string;
let userId: number;
let email: string;
let userName: string;
let userNameDouble: string;
let password: string;
password = "Qwerty";
//1. Add user
describe("1. Add user", () => {
it(`Registration vith valid data`, async () => {
let userData: object = {
id: 0,
avatar: "string",
email: "[email protected]",
userName: "Olena",
password: password,
};
let response = await users.addUser(userData);
expect(response.statusCode, `Status Code should be 201`).to.be.equal(201);
expect(response.body, "JSON Schema failed").to.be.jsonSchema(schemas.schema_oneUser);
checkResponseTime(response, 1000);
accessToken = response.body.token.accessToken.token;
//console.log(accessToken);
userId = response.body.user.id;
email = response.body.user.email;
userName = response.body.user.userName;
userNameDouble = response.body.user.userName;
//console.log(email, password);
});
});
//1.1. Adding user with inwalid password (less than 4 symbols)
describe("1.1. Adding user with inwalid password (less than 4 symbols)", () => {
it(`Registration vith valid data`, async () => {
let userData: object = {
id: 0,
avatar: "string",
email: "[email protected]",
userName: "Olena",
password: "123",
};
let response = await users.addUser(userData);
expect(response.statusCode, `Status Code should be 400`).to.be.equal(400);
checkResponseTime(response, 1000);
//console.log(response.statusCode);
});
});
//2. Get all users
describe(`2. Get all users`, () => {
it(`should return 200 status code and all users when getting the user collection`, async () => {
let response = await users.getAllUsers();
//console.log("All Users:");
//console.log(response.body);
checkStatusCode(response, 200);
checkResponseTime(response, 1000);
expect(response.body, "JSON schema (all users) is failed!").to.be.jsonSchema(schemas.schema_allUsers);
});
});
//3. Login with creds
describe("3. Login check", () => {
before(`Login and get the token`, async () => {
let response = await auth.login(email, password);
checkStatusCode(response, 200);
});
it(`Login`, async () => {
let userData: object = {
id: userId,
avatar: "string",
email: email,
userName: userName,
};
let response = await users.updateUser(userData, accessToken);
expect(response.statusCode, `Status Code should be 204`).to.be.equal(204);
});
});
//3.1. Login with invalid data
describe("3.1. Login with invalid data check", () => {
let invalidCredentialsDataSet = [
{ email: email, password: "" },
{ email: email, password: " " },
{ email: email, password: "ATest2023! " },
{ email: email, password: "ATest 2021" },
{ email: email, password: "admin" },
{ email: email, password: "[email protected]" },
];
invalidCredentialsDataSet.forEach((credentials) => {
it(`should not login using invalid credentials : '${credentials.email}' + '${credentials.password}'`, async () => {
let response = await auth.login(credentials.email, credentials.password);
checkStatusCode(response, 400);
checkResponseTime(response, 3000);
});
});
});
//4. Get user info from token
describe(`4. Get user info from token`, () => {
it(`should return user details when getting user details with valid token`, async () => {
let response = await users.getCurrentUser(accessToken);
checkStatusCode(response, 200);
checkResponseTime(response, 1000);
//expect(response.body).to.be.not.empty;
expect(response.body).to.be.jsonSchema(schemas.schema_oneUser);
});
it(`Username from response is the same as registered`, async () => {
let response = await users.getCurrentUser(accessToken);
expect(response.body.userName).to.be.equal(userName, "Username is not the same");
});
});
//5. Update user info
describe("5. Update user info", () => {
let userDataBeforeUpdate, userDataToUpdate;
it(`Login and get the token`, async () => {
let response = await auth.login(email, password);
checkStatusCode(response, 200);
});
it(`should return correct details of the currect user`, async () => {
let response = await users.getCurrentUser(accessToken);
checkStatusCode(response, 200);
userDataBeforeUpdate = response.body;
console.log(response.body);
});
it(`should update username using valid data`, async () => {
// replace the last 3 characters of actual username with random characters.
// Another data should be without changes
function replaceLastThreeWithRandom(str: string): string {
return str.slice(0, -3) + Math.random().toString(36).substring(2, 5);
}
userDataToUpdate = {
id: userDataBeforeUpdate.id,
avatar: userDataBeforeUpdate.avatar,
email: userDataBeforeUpdate.email,
userName: replaceLastThreeWithRandom(userDataBeforeUpdate.userName),
};
let response = await users.updateUser(userDataToUpdate, accessToken);
checkStatusCode(response, 204);
});
it(`should return correct user details by id after updating`, async () => {
let response = await users.getUserById(userDataBeforeUpdate.id);
checkStatusCode(response, 200);
expect(response.body).to.be.deep.equal(userDataToUpdate, "User details isn't correct");
userName = response.body.userName;
});
});
//6. Get user info from token again
describe(`6. Get user info from token`, () => {
it(`should return user details when getting user details with valid token`, async () => {
let response = await users.getCurrentUser(accessToken);
checkStatusCode(response, 200);
checkResponseTime(response, 1000);
//expect(response.body).to.be.not.empty;
expect(response.body).to.be.jsonSchema(schemas.schema_oneUser);
});
it(`Username from response is NOT the same as registered after updating`, async () => {
let response = await users.getCurrentUser(accessToken);
expect(response.body.userName).to.be.not.equal(userNameDouble, "Username is the same as before update!");
});
});
//7. Get user info by ID
describe(`7. Users controller`, () => {
before(`Login and get the token`, async () => {
let response = await auth.login(email, password);
});
it(`should return user details when getting user details with valid token`, async () => {
let response = await users.getUserById(userId);
//console.log("Status code " + response.statusCode);
checkStatusCode(response, 200);
checkResponseTime(response, 1000);
expect(response.body).to.be.not.empty;
//expect(response.body.id).to.be.not.NaN;
//expect(response.body.avatar).to.be.not.empty;
// expect(response.body.email).to.be.not.empty;
// expect(response.body.userName).to.be.not.empty;
expect(response.body).to.be.jsonSchema(schemas.schema_oneUser);
});
it(`Username from response is the same as after updating`, async () => {
let response = await users.getCurrentUser(accessToken);
expect(response.body.userName).to.be.equal(userName, "Username is NOT the same as after update!");
});
});
//8. Delete user
describe(`8. Delete user by id`, () => {
it(`Deleting user`, async () => {
let response = await users.deleteUser(userId, accessToken);
checkStatusCode(response, 204);
checkResponseTime(response, 1000);
});
});
|
"""
withdraw!(
model::AbstractModel,
t;
withdraws = Transaction(0.0, -1.0, 0.0)
)
Schedules withdraws from investments as specified in `withdraws`.
# Arguments
- `model::AbstractModel`: an abstract Model object
- `t`: current time of simulation in years
# Keywords
- `withdraws = Transaction(0.0, -1.0, 0.0)`: a transaction or vector of transactions indicating the amount and time period
in which money is withdrawn from investments per time step
"""
function withdraw!(
model::AbstractModel,
t;
withdraws = Transaction(0.0, -1.0, 0.0)
)
state = model.state
state.withdraw_amount = 0.0
state.net_worth == 0.0 ? (return nothing) : nothing
_withdraw!(model, t, withdraws)
return nothing
end
function _withdraw!(model::AbstractModel, t, withdraw::AbstractTransaction)
(; ฮt) = model
if can_transact(withdraw, t; ฮt)
withdraw_amount = transact(model, withdraw; t)
if model.state.net_worth < withdraw_amount
withdraw_amount = model.state.net_worth
end
model.state.withdraw_amount += withdraw_amount
end
return nothing
end
function _withdraw!(model::AbstractModel, t, withdraws)
for withdraw โ withdraws
_withdraw!(model, t, withdraw)
end
return nothing
end
function transact(
model::AbstractModel,
withdraw::AbstractTransaction{T, D};
t
) where {T, D <: AdaptiveWithdraw}
(; ฮt, state) = model
(; min_withdraw, volitility, income_adjustment, percent_of_real_growth) =
withdraw.amount
real_growth_rate = (1 + compute_real_growth_rate(model))^ฮt
mean_withdraw =
state.net_worth * (real_growth_rate - 1) * percent_of_real_growth
mean_withdraw = max(min_withdraw, mean_withdraw)
withdraw_amount =
volitility โ 0.0 ? mean_withdraw :
rand(Normal(mean_withdraw, mean_withdraw * volitility))
withdraw_amount = max(withdraw_amount, min_withdraw)
return max(withdraw_amount - state.income_amount * income_adjustment, 0)
end
|
import { addHours, differenceInSeconds } from "date-fns";
import { useEffect, useMemo, useState } from "react";
import { Swal } from "sweetalert2";
import { useCalendarStore } from "../../hooks";
import { useUiStore } from "./../../hooks/useUiStore";
export const useCalendarState = () => {
const { isDateModalOpen, closeDateModal } = useUiStore();
const [formSubmitted, setFormSubmitted] = useState(false);
const { activeEvent, startSavingEvent } = useCalendarStore();
const [formValues, setformValues] = useState({
title: "",
notes: "",
start: new Date(),
end: addHours(new Date(), 2),
});
const titleClass = useMemo(() => {
if (!formSubmitted) return "";
return formValues.title.length > 0 ? "" : "is-invalid";
}, [formValues.title, formSubmitted]);
const onInputChange = ({ target }) => {
setformValues({
...formValues,
[target.name]: target.value,
});
};
useEffect(() => {
if (activeEvent !== null) {
setformValues({ ...activeEvent });
}
}, [activeEvent]);
const onDateChanged = (event, changing) => {
setformValues({
...formValues,
[changing]: event,
});
};
const onCloseModal = () => {
closeDateModal();
};
const onSubmit = async (event) => {
event.preventDefault();
setFormSubmitted(true);
const diference = differenceInSeconds(formValues.end, formValues.start);
if (isNaN(diference) || diference <= 0) {
Swal.fire({
title: "Error!",
text: "Fechas incorrectas",
icon: "error",
confirmButtonText: "Ok",
});
return;
}
if (formValues.title.length <= 0) return;
//Todo : Enviando
await startSavingEvent(formValues);
onCloseModal();
};
return {
...formValues,
formValues,
formSubmitted,
titleClass,
onInputChange,
onDateChanged,
onSubmit,
onCloseModal,
isDateModalOpen,
};
};
|
# ่ดฃไปป้พๆจกๅผ
## 1.ๅฎไน
> ไฝฟๅคไธชๅฏน่ฑก้ฝๆๆบไผๅค็่ฏทๆฑ๏ผไป่้ฟๅ
ไบ่ฏทๆฑ็ๅ้่
ๅๆฅๆถ่
ไน้ด็่ฆๅๅ
ณ็ณปใ
> ๅฐ่ฟไบๅฏน่ฑก่ฟๆไธๆก้พ๏ผๅนถๆฒฟ็่ฟๆก้พไผ ้่ฏฅ่ฏทๆฑ๏ผ็ดๅฐๆๅฏน่ฑกๅค็ๅฎไธบๆญขใ
> ้็นๅจโ้พโไธ๏ผ็ฑไธๆก้พๅปๅค็็ธไผผ็่ฏทๆฑ๏ผๅจ้พไธญๅณๅฎ่ฐๆฅๅค็่ฟไธช่ฏทๆฑ๏ผๅนถ่ฟๅ็ธๅบ็็ปๆใ
> ๆ ธๅฟๅจโ้พโไธ๏ผโ้พโๆฏ็ฑๅคไธชๅค็่
ConcreteHandler็ปๆ็ใ
## 2.ๅบ็จ
> ๅจๅฎ้
ๅบ็จไธญ๏ผไธ่ฌไผๆไธไธชๅฐ่ฃ
็ฑปๅฏน่ดฃไปปๆจกๅผ่ฟ่กๅฐ่ฃ
๏ผไนๅฐฑๆฏๆฟไปฃClient็ฑป๏ผ็ดๆฅ่ฟๅ้พไธญ็ฌฌไธไธชๅค็่
๏ผ
> ๅ
ทไฝ้พ็่ฎพ็ฝฎไธ้่ฆ้ซๅฑๆฌกๆจกๅๅ
ณ็ณปใ่ฟๆ ท๏ผๆด็ฎๅไบ้ซๅฑๆฌกๆจกๅ็่ฐ็จ๏ผๅๅฐๆจกๅ้ด็่ฆๅ๏ผๆ้ซ็ณป็ป็็ตๆดปๆงใ
### 2.1ไผ็น
> ่ดฃไปป้พๆจกๅผ้ๅธธๆพ่็ไผ็นๅฐฑๆฏๅฐ่ฏทๆฑๅๅค็ๅๅผใ
> ่ฏทๆฑ่
ๅฏไปฅไธ็จ็ฅ้ๆฏ่ฐๅค็็๏ผๅค็่
ๅฏไปฅไธ็จ็ฅ้่ฏทๆฑ็ๅ
จ่ฒ๏ผไธค่
่งฃ่ฆ๏ผๆ้ซ็ณป็ป็็ตๆดปๆงใ
### 2.2็ผบ็น
> ่ดฃไปป้พๆไธคไธช้ๅธธๆพ่็็ผบ็น๏ผ
>
> 1.ๆง่ฝ้ฎ้ข
>> ๆฏไธช่ฏทๆฑ้ฝๆฏไป้พๅคด้ๅๅฐ้พๅฐพ๏ผ็นๅซๆฏๅจ้พๆฏ่พ้ฟ็ๆถๅ๏ผๆง่ฝๆฏไธไธช้ๅธธๅคง็้ฎ้ขใ
> 2.่ฐๅผๅพไธๆนไพฟ
>> ็นๅซๆฏ้พๆกๆฏ่พ้ฟ๏ผ็ฏ่ๆฏ่พๅค็ๆถๅ๏ผ็ฑไบ้็จไบ็ฑปไผผ้ๅฝ็ๆนๅผ๏ผ่ฐ่ฏ็ๆถๅ้ป่พๅฏ่ฝๆฏ่พๅคๆใ
### 2.3ๆณจๆไบ้กน
> ้พไธญ่็นๆฐ้้่ฆๆงๅถ๏ผ้ฟๅ
ๅบ็ฐ่ถ
้ฟ้พ็ๆ
ๅต๏ผไธ่ฌ็ๅๆณๆฏๅจHandlerไธญ่ฎพ็ฝฎไธไธชๆๅคง่็นๆฐ้๏ผๅจsetNextๆนๆณไธญๅคๆญๆฏๅฆๅทฒ็ป
> ่ถ
่ฟๅ
ถ้ๅผ๏ผ่ถ
่ฟๅไธๅ
่ฎธ่ฏฅ้พๅปบ็ซ๏ผ้ฟๅ
ๆ ๆ่ฏๅฐ็ ดๅ็ณป็ปๆง่ฝใ
## 3.ๆไฝณๅฎ่ทต
|
// context/MyContext.js
import { createContext, useContext, useState } from "react";
import { fetchMovies } from "../utils/helpers";
// Create the context
const FetchMovies = createContext();
// Create a provider component
export function FetchMoviesProvider({ children }) {
const [movies, setMovies] = useState([]);
const [searchString, setSearchString] = useState("");
const [searchedMovies, setSearchedMovies] = useState([]);
const [selectedMovies, setSelectedMovies] = useState({});
const handleFetchMovies = async () => {
const result = await fetchMovies();
setSelectedMovies(result[0]);
setMovies(result);
};
const handleChange = (event) => {
event.preventDefault();
setSearchString(event.target.value);
};
const handleSearchMovies = async (searchString) => {
try {
const result = await fetchMovies(searchString);
setSearchedMovies(result);
} catch (error) {
console.log("you will soon find what you are looking for, error");
}
};
const contextValue = {
movies,
searchedMovies,
selectedMovies,
searchString,
handleFetchMovies,
handleSearchMovies,
handleChange,
};
return (
<FetchMovies.Provider value={contextValue}>{children}</FetchMovies.Provider>
);
}
// Create a custom hook to access the context
export function useFetchMovies() {
return useContext(FetchMovies);
}
|
import 'package:ceklpse_pretest_mobiledev/app/data/repositories/updateprofile/update_profile_repository_implementation.dart';
import 'package:ceklpse_pretest_mobiledev/app/domain/entities/common_entity.dart';
import 'package:ceklpse_pretest_mobiledev/app/domain/usecase/updateprofile/verify_password_use_case.dart';
import 'package:ceklpse_pretest_mobiledev/app/utils/colors.dart';
import 'package:ceklpse_pretest_mobiledev/app/utils/helpers.dart';
import 'package:ceklpse_pretest_mobiledev/app/utils/result.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:get/get.dart';
Future<void> verifyPassword({
required GlobalKey<FormState> verifyPasswordFormKey,
required AutovalidateMode autoValidateVerifyPassword,
required TextEditingController verifyPasswordController,
required String username,
required Function successAction
}) async {
final isVerifyPasswordValid = verifyPasswordFormKey.currentState!.validate();
if (isVerifyPasswordValid) {
late VerifyPasswordUseCase verifyPassword;
late Result<CommonEntity> result;
VerifyPasswordParams params = VerifyPasswordParams(
username: username,
password: verifyPasswordController.text.trim()
);
loaderDialog(
loaderIcon: const SpinKitRing(color: AppColors.primaryColor),
message: 'Please wait...'
);
verifyPassword = VerifyPasswordUseCase(
updateProfileRepository: UpdateProfileRepositoryImplementation()
);
result = await verifyPassword.call(params);
if (result.status is Success) {
successAction();
} else {
Get.back();
snackbar(title: 'Oops!', message: result.message);
}
} else {
autoValidateVerifyPassword = AutovalidateMode.always;
}
}
|
<template>
<div class="img3 adminlogin">
<form @submit.prevent="login" method="post">
<div class="form9">
<div class="title4a">Sign In</div>
<div class="input-container3 ic13">
<input id="userid" class="input3" type="text" placeholder=" " name="userid" v-model="adminid" required>
<div class="cut3"></div>
<label for="userid" class="placeholder3">AdminID</label>
</div>
<div class="input-container3 ic23">
<input id="password" class="input3" type="password" placeholder=" " name="password" v-model="password"
required>
<div class="cut3"></div>
<label for="password" class="placeholder3">Password </label>
</div>
<button type="submit" class="submit3">Login</button>
<br><br>
<a href="/admin/register" class="aus" style="font-size: 15px;">New Register?</a>
</div>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
adminid: '',
password: '',
}
},
methods: {
async login() {
try {
// Dispatch Vuex action to handle login
const response = await axios.post('http://127.0.0.1:5000/admin/login', {
adminid: this.adminid,
password: this.password,
});
localStorage.setItem('admintoken', response.data.access_token)
localStorage.setItem('username', response.data.username)
const lastVisitedUrl = localStorage.getItem('lastVisitedUrladm');
if (lastVisitedUrl && lastVisitedUrl != '/admin/login') {
localStorage.removeItem('lastVisitedUrladm');
this.$router.replace(lastVisitedUrl);
} else {
this.$router.replace('/admindash');
}
}
catch (error) {
// Handle errors from POST and GET requests
if (error.response.status === 401) {
alert("Sorry, Invalid credentials")
}
if (error.response.status === 405) {
alert("Sorry, check adminid for any spelling mistakes")
}
}
},
saveLastVisitedUrladm() {
const currentUrl = this.$route.fullPath;
localStorage.setItem('lastVisitedUrladm', currentUrl);
},
},
created() {
window.addEventListener('beforeunload', this.saveLastVisitedUrladm);
},
beforeDestroy() {
window.removeEventListener('beforeunload', this.saveLastVisitedUrladm);
}
}
</script>
<style scoped>
@import '../assets/styles/adminlogin.css';
</style>
|
//React solo puede tener un parametro y puede tener cualquier nombre obviamente. Por practica se lo conoce como props. Ya que son uno o muchos datos enviados a esa componente. Este parametro props va a crear un objeto y dentro va a meter las distintas propiedades
function MiPrimerPromp(props){ // props = {parrafo={"Esto es un jemplo de parrafo"}}
let texto = "Este es mi primer Promp";
let etiquetaSpan = null;
if(props.visualizarSpan){
etiquetaSpan = <span>Soy una etiqueta span</span>
}
return <div>
<h1>{props.titulo}</h1>
<p>{texto}</p>
<p>{props.parrafo}</p>
{etiquetaSpan}
</div>;
}
/*
const root = ReactDOM.createRoot(window.document.getElementById("root"));
root.render(<MiPrimerPromp parrafo={'Esto es un jemplo de parrafo'} titulo={'Titulo de la web'} visualizarSpan={true}/>);
// parrafo seria el atributo y el valor tiene que estar entre llaves como un objeto
*/
|
<template>
<div class="person">
<h2>sum:{{ sum }}</h2>
<button @click="add">add</button>
</div>
<hr>
<img v-for="(dog,index) in dogList" :src="dog" alt="" :key="index">
<button @click="getDog">oneMoreDog</button>
</template>
<script setup lang="ts" name="Person">
import {ref , reactive} from 'vue'
import axios from 'axios'
let sum = ref(0)
let dogList = reactive([
'https:\/\/images.dog.ceo\/breeds\/pembroke\/n02113023_1136.jpg',
'https:\/\/images.dog.ceo\/breeds\/pembroke\/n02113023_6140.jpg'
])
function add(){
sum.value ++
}
async function getDog(){
try{
let result = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')
dogList.push(result.data.message)
}catch(error){
alert(error)
}
}
</script>
<style scoped>
input,
label {
font-size: 2em;
}
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin: 0 1em
}
li {
font-size: 2em;
}
img{
height: 100px;
margin-right: 1em;
}
</style>
|
require('dotenv').config()
const mongoose = require('mongoose');
const cloudinary = require('cloudinary').v2;
const express = require('express');
const Movie = require('./Models/Movie')
const multer = require('multer');
const cors = require('cors')
const { S3Client } = require('@aws-sdk/client-s3')
const multerS3 = require('multer-s3')
const aws = require('aws-sdk')
const fs = require('fs')
const uuid = require("uuid").v4;
const path = require("path")
mongoose.connect('mongodb+srv://Adityaanaparthi:[email protected]/test', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err));
cloudinary.config({
cloud_name: 'dec6gy3wy',
api_key: '355514238263871',
api_secret: 'fkxhW0wjFM1XciQrJGl6kZk-Qn0'
});
const app = express();
const port = 5000;
app.use(express.urlencoded({extended:true}))
app.use(express.json())
app.use(cors())
// multer configuration
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './uploads')
},
filename: (req, file, cb) => {
cb(null, Date.now() + '-' + file.originalname)
}
});
//s3
const s3 = new aws.S3({
secretAccessKey: 'R1yIM21N9cpdx6l5nGg2haYgdXzhw0zKyzr1TAb5',
accessKeyId: 'AKIA4IT3MYK6XCMZPA54',
region: 'us-east-1'
});
const upload = multer({ storage });
app.post('/api/movies', upload.single('poster'), async (req, res) => {
try {
const fileContent = fs.readFileSync(req.file.path);
const params = {
Bucket: 'movie-list1',
Key: `${Date.now()}-${req.file.originalname}`,
Body: fileContent,
ContentType: req.file.mimetype,
ACL: 'public-read',
};
const s3Data = await s3.upload(params).promise();
const movie = new Movie({
title: req.body.title,
director: req.body.director,
releaseYear: req.body.releaseYear,
poster: s3Data.Location,
});
await movie.save();
res.send(movie);
} catch (error) {
console.error(error);
res.status(500).send('Something went wrong');
}
});
app.get('/api/movies', async (req, res) => {
try {
const movies = await Movie.find();
res.send(movies);
} catch (error) {
console.error(error);
res.status(500).send('Something went wrong');
}
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`)
});
|
<div class="form">
<h1>Create Reservation</h1>
<form (ngSubmit)="onSubmit()">
<mat-form-field appearance="fill" class="input-field">
<mat-label>Room Type</mat-label>
<mat-select [(value)]="roomType" name="roomType" [(ngModel)]="roomType" required>
<mat-option value="single">Single</mat-option>
<mat-option value="double">Double</mat-option>
</mat-select>
</mat-form-field>
<br />
<mat-form-field class="input-field" appearance="fill">
<mat-label>From Date</mat-label>
<input matInput [matDatepicker]="fromPicker" name="fromDate" [(ngModel)]="fromDate" required>
<mat-hint>MM/DD/YYYY</mat-hint>
<mat-datepicker-toggle matSuffix [for]="fromPicker"></mat-datepicker-toggle>
<mat-datepicker #fromPicker></mat-datepicker>
</mat-form-field>
<br />
<br />
<mat-form-field class="input-field" appearance="fill">
<mat-label>To Date</mat-label>
<input matInput [matDatepicker]="toPicker" name="toDate" [(ngModel)]="toDate" required>
<mat-hint>MM/DD/YYYY</mat-hint>
<mat-datepicker-toggle matSuffix [for]="toPicker"></mat-datepicker-toggle>
<mat-datepicker #toPicker></mat-datepicker>
</mat-form-field>
<br />
<br />
<mat-label>Breakfast</mat-label>
<mat-radio-group aria-label="Breakfast" name="breakfast" [(ngModel)]="breakfast" required>
<mat-radio-button value="Yes">Yes</mat-radio-button>
<mat-radio-button value="No">No</mat-radio-button><br>
</mat-radio-group>
<br />
<div>
<div class="div">
<mat-checkbox name="air_conditioner" value="yes" [(ngModel)]="air_conditioner"> Air Conditioner</mat-checkbox>
<mat-checkbox name="wakeup_service" value="yes" [(ngModel)]="wakeup_service">Wakeup Service</mat-checkbox>
</div>
</div>
<br />
<input type="submit" value="Submit" class="submit-button" />
</form>
</div>
|
<%@ Page Language="C#" %>
<%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<%@ Register Assembly="Ext.Net.UX" Namespace="Ext.Net.UX" TagPrefix="ux" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>GMap - Ext.NET Examples</title>
<link href="../../../../resources/css/examples.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<ext:ResourceManager runat="server" ID="ResourceManager1" />
<ext:Window ID="PanWin" runat="server"
Title="GPanorama Window"
Width="400"
Height="300"
Layout="Fit"
X="480"
Y="60">
<Items>
<ux:GMapPanel runat="server" GMapType="Panorama">
<CenterMarker lat="42.345573" lng="-71.098326" />
</ux:GMapPanel>
</Items>
<Listeners>
<Show Handler="this.hide();" Single="true" />
</Listeners>
</ext:Window>
<ext:Window ID="MapWin" runat="server"
Hidden="true"
Title="GMap Window"
Width="400"
Height="400"
Layout="Fit"
X="40"
Y="60">
<Items>
<ux:GMapPanel runat="server" ZoomLevel="14" GMapType="Map">
<MapControls GSmallMapControl="true" />
<CenterMarker GeoCodeAddress="4 Yawkey Way, Boston, MA, 02215-3409, USA">
<Options Title="Fenway Park" />
</CenterMarker>
<Markers>
<ux:Marker Lat="42.339641" Lng="-71.094224">
<Options Title="Boston Museum of Fine Arts" />
</ux:Marker>
<ux:Marker Lat="42.339419" Lng="-71.09077">
<Options Title="Northeastern University" />
</ux:Marker>
</Markers>
</ux:GMapPanel>
</Items>
</ext:Window>
<ext:Window ID="mapParis" runat="server"
Title="La Tour Eiffel"
Hidden="true"
Layout="Fit"
Width="400"
Height="400">
<Items>
<ux:GMapPanel ID="GMapPanel1" runat="server" ZoomLevel="16" GMapType="Map">
<MapControls GSmallMapControl="true" />
<MapConfiguration ScrollWheelZoom="true" />
<CenterMarker GeoCodeAddress="La Tour Eiffel">
<Options Title="La Tour Eiffel" />
</CenterMarker>
<Markers>
<ux:Marker Lat="48.858281" Lng="2.294533">
<Options Title="La Tour Eiffel" />
</ux:Marker>
</Markers>
</ux:GMapPanel>
</Items>
</ext:Window>
<ext:Viewport runat="server" ID="ViewPort1" Layout="Fit">
<Items>
<ux:GMapPanel runat="server" ID="CenterMap" Border="false" ZoomLevel="14" GMapType="Map">
<MapControls GHierarchicalMapTypeControl="true" GLargeMapControl="true" />
<MapConfiguration DoubleClickZoom="true" ContinuousZoom="true" GoogleBar="true" ScrollWheelZoom="true" />
<CenterMarker GeoCodeAddress="4 Yawkey Way, Boston, MA, 02215-3409, USA">
<Options Title="Fenway Park" />
</CenterMarker>
<Markers>
<ux:Marker Lat="42.339641" Lng="-71.094224">
<Options Title="Boston Museum of Fine Arts" />
<Listeners>
<Click Handler="Ext.Msg.alert('Its fine', 'and its art.');" />
</Listeners>
</ux:Marker>
<ux:Marker Lat="42.339419" Lng="-71.09077">
<Options Title="Northeastern University" />
</ux:Marker>
</Markers>
<Buttons>
<ext:Button runat="server" ID="PanButton" Text="Fenway Park StreetView">
<Listeners>
<Click Handler="#{PanWin}.show();" />
</Listeners>
</ext:Button>
<ext:Button runat="server" ID="MapButton" Text="Fenway Park Map Window">
<Listeners>
<Click Handler="#{MapWin}.show();" />
</Listeners>
</ext:Button>
<ext:Button runat="server" Text="La Tour Eiffel">
<Listeners>
<Click Handler="#{mapParis}.show();" />
</Listeners>
</ext:Button>
</Buttons>
</ux:GMapPanel>
</Items>
</ext:Viewport>
</form>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* ๅญๅท
ยท่ฎฐๅพๅ px */
.size {
font-size: 30px;
}
/* ๅญไฝ็ฒ็ป
ยทๅ
ณ้ฎๅญใnormalใๆญฃๅธธ ใboldใๅ ็ฒ
ยท็บฏๆฐๅญใ400ใๆญฃๅธธ ใ700ใๅ ็ฒ */
.weight {
font-weight: 700;
}
/* ๆๅญๅพๆ */
.italic {
font-style: italic;
}
/* ๅญไฝๆ ทๅผ */
.family {
/* ่ฟ้็ๆๆๆฏๅ
ผๅฎนๅค็งๅญไฝ ๅฆๆ้ฝๆฒกๆๅฐฑ็จ้ไพฟไธ็ง้่กฌ็บฟๅญไฝserif */
font-family: 'Times New Roman', Times, serif;
}
/* font็ๅคๅๅฑๆง๏ผ่ฟๅ๏ผ */
.fontSimple{
font: italic 700 66px 'Times New Roman';
}
/* ๆๆฌ็ผฉ่ฟ */
.indent {
/* text-indent: 50px; */
/* emๆฏไธไธชๅญ็ๅคงๅฐ */
text-indent: 2em;
}
/* ๆๆฌๆฐดๅนณๅฏน้ฝ
ๅฑๆงๅ๏ผtext-align
ๅๅผ๏ผ
left๏ผๅทฆๅฏน้ฝ
center๏ผๅฑ
ไธญๅฏน้ฝ
rigjt๏ผๅณๅฏน้ฝ */
.align {
text-align: center;
}
/* ๆๆฌไฟฎ้ฅฐ
ไธๅ็บฟ๏ผunderline
ๅ ้ค็บฟ๏ผline- through
ไธๅ็บฟ๏ผoverline
ๆ ่ฃ
้ฅฐ็บฟ๏ผnone */
.decoration {
text-decoration: line-through;
}
/* ่ก้ซ
ๅฑๆงๅ๏ผline-height
ๅๅผ๏ผ
ยทๆฐๅญ+px
ยทๅๆฐ๏ผๅฝๅfont-size็ๅๆฐ๏ผ */
.lineHeight{
line-height: 10px;
/* ่ก้ซไธfont่ฟๅ็ๆณจๆ็น
ยทfont๏ผstyle weight size/line-height family */
}
</style>
</head>
<body>
<!-- ้ป่ฎคๅญๅทๆฏ16px -->
<p class="size">ๆฎต่ฝๆๅญ</p>
<p class="weight">ๆฎต่ฝๆๅญ</p>
<p class="italic">ๆฎต่ฝๆๅญ</p>
<!-- mac้ป่ฎค่นๆนๅญไฝ -->
<p class="family">This is 'Times New Roman' font-family</p>
<p class="fontSimple">This is mixed font style</p>
<p class="indent">ๆไบ Mac๏ผๅฐฑ่ฝๅๅคๆ็่ฎพ็ฝฎ่ฟ็จ่ฏดๅ่งใๅช่ฆ็ปๅฝ iCloud๏ผไฝ ๅจ iPhone ๆ iPad ไธ็่ตๆๅฐฑไผ่ชๅจๅบ็ฐ๏ผไฝฟ็จ่ฟ็งปๅฉ็ๅ่ฝ๏ผไฝ ็่ฎพ็ฝฎใ็จๆท่ดฆๆทๅๅ
ถไปๆฐๆฎ้ฝ่ฝ่ฝปๆพ่ฝฌ็งปใๅฆๆๆ้ฎ้ขๆ้่ฆๅธฎๅฉ๏ผApple ๆฏๆๆๅก้ๆถๅพ
ๅฝ๏ผไฝ ๅช่ฆไธ็ฝ่ใๆ็ต่ฏๆ้ข็บฆๅฐๅบๅฐฑๅฏไปฅใ</p>
<h1 class="align">ๅฑ
ไธญๅฏน้ฝ</h1>
<!-- ่ฅ่ฆ่ฎฉๆๆฌใspanๆ ็ญพใaๆ ็ญพใinputๆ ็ญพใimgๆ ็ญพๆฐดๅนณๅฑ
ไธญ๏ผๅ้่ฆ็ปไปไปฌ็็ถ็บงๅ
็ด ่ฎพ็ฝฎ -->
<div class="align"><img src="32.jpg" alt="" width="300"></div>
<div class="decoration">่ฟๆฏไธไธชdivๆ ็ญพ</div>
<p class="decoration">่ฟๆฏไธไธชpๆ ็ญพ</p>
<h3 class="decoration">่ฟๆฏไธไธชh3ๆ ็ญพ</h3>
<a href="#" class="decoration">่ฟๆฏไธไธช็ฉบ็่ถ
้พๆฅ</a>
<!-- ่ก้ซ=ไธ้ด่ท+ๆๆฌ้ซๅบฆ+ไธ้ด่ท -->
<div class="lineHeight">่ฟๆฏ่ก้ซ็demo</div>
<div class="lineHeight">่ฟๆฏ่ก้ซ็demo</div>
</body>
</html>
|
//@ts-check
import React, { useEffect, useState } from "react";
import { useLocalStorage } from "../hooks/useLocalStorage";
import { v4 as uuid } from "uuid";
//@ts-ignore
import TodoItem from "./TodoItem";
import {
DndContext,
closestCenter,
useSensor,
PointerSensor,
useSensors,
} from "@dnd-kit/core";
import {
SortableContext,
arrayMove,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
/**
* @typedef {Object} Todo
* @property {string} id
* @property {string} message
* @property {boolean} isComplete
*/
/**
*
* @param {string} message
* @param {Todo[]} todos
* @param {function} setTodos
* @returns
*/
const addTodo = (message, todos, setTodos) => {
/**
* @type {Todo}
*/
const newTodo = { id: uuid(), message: message, isComplete: false };
setTodos([...todos, newTodo]);
return [...todos, newTodo];
};
/**
*
* @param {Todo[]} todos
* @param {function} setTodos
*/
const delCompletedTodos = (setTodos, todos) => {
setTodos(todos.filter((todo) => todo.isComplete !== true));
};
/**
*
* @param {Todo} todo
* @returns {true|false}
*/
const showActiveTodos = (todo) => (todo.isComplete === false ? true : false);
/**
*
* @param {Todo} todo
* @returns {true|false}
*/
const showCompletedTodos = (todo) => (todo.isComplete === true ? true : false);
/**
*
* @param {Todo} todo
* @returns {true|false}
*/
const showAllTodos = (todo) => true;
/**
*
* @param {Object} p
* @param {boolean} p.nightMode
* @returns
*/
const Todos = ({ nightMode }) => {
const [todos, setTodos] = useLocalStorage("todos", []);
const [uiState, setUIState] = useState(() => showAllTodos);
const [message, setMessage] = useState("");
/**
*
* @param {string} id
*/
const delTodo = (id) => {
setTodos(todos.filter((/** @type {Todo} */ todo) => todo.id !== id));
};
/**
*
* @param {string} id
*/
const updateCheckMark = (id) => {
setTodos(
todos.map((/** @type {Todo} */ todo) => {
todo.id === id ? (todo.isComplete = !todo.isComplete) : null;
return todo;
})
);
};
/**
*
* DND-Kit manager for when drag click ends
*/
const onDragEnd = (e) => {
const { active, over } = e;
if (active.id === over.id) return;
setTodos((/** @type {Todo[]} */ todos) => {
const oldIndex = todos.findIndex(
(/** @type {Todo} */ todo) => todo.id === active.id
);
const newIndex = todos.findIndex(
(/** @type {Todo} */ todo) => todo.id === over.id
);
return arrayMove(todos, oldIndex, newIndex);
});
};
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 8,
},
})
);
return (
<div
className={
"todos" +
(nightMode ? " night-todos box-shadow-dark" : " box-shadow-light")
}
>
<div
className={
"flex-row todo-input-holder" + (nightMode ? " night-todos" : "")
}
>
<img src="/assets/oval.svg" />
<input
type="text"
style={
nightMode
? { backgroundColor: "#25273D" }
: { backgroundColor: "#FFFFFF" }
}
placeholder="Create a new todo..."
maxLength={50}
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
addTodo(message, todos, setTodos);
setMessage("");
}
}}
/>
</div>
<div className="todo-list">
<DndContext
collisionDetection={closestCenter}
onDragEnd={onDragEnd}
sensors={sensors}
>
<SortableContext items={todos} strategy={verticalListSortingStrategy}>
{todos.map((/** @type {Todo} */ todo) =>
uiState(todo) ? (
<TodoItem
id={todo.id}
key={todo.id}
message={todo.message}
isComplete={todo.isComplete}
del={delTodo}
updateCheckMark={updateCheckMark}
nightMode={nightMode}
/>
) : null
)}
</SortableContext>
</DndContext>
</div>
<div className="flex-row filters">
<p>
{
todos.filter(
(/** @type {Todo} */ todo) => todo.isComplete === false
).length
}{" "}
items left
</p>
<div
className="flex-row filter-controls"
style={{ justifyContent: "center" }}
>
<p
className="pointer"
onClick={(e) => {
setUIState(() => showAllTodos);
}}
>
All
</p>
<p
className="pointer"
onClick={(e) => {
setUIState(() => showActiveTodos);
}}
>
Active
</p>
<p
className="pointer"
onClick={(e) => {
setUIState(() => showCompletedTodos);
}}
>
Completed
</p>
</div>
<p
className="pointer"
onClick={(e) => {
delCompletedTodos(setTodos, todos);
}}
>
Clear Completed
</p>
</div>
<p className="dnd-text">Drag and drop to reorder list</p>
</div>
);
};
export default Todos;
|
๏ปฟusing System.Text.Json.Serialization;
namespace OpayoPaymentsNet.Domain.Entities.Enums
{
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum PaymentAccountAgeIndicator
{
/// <summary>
/// No account (guest check-out).
/// </summary>
GuestCheckout,
/// <summary>
/// During this transaction.
/// </summary>
DuringTransaction,
/// <summary>
/// Less than 30 days.
/// </summary>
LessThanThirtyDays,
/// <summary>
/// 30-60 days
/// </summary>
ThirtyToSixtyDays,
/// <summary>
/// More than 60 days
/// </summary>
MoreThanSixtyDays
}
}
|
package id.arya.portofolio.ecommerce.product;
import id.arya.portofolio.ecommerce.util.WebResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/categories")
public class ProductCategoryController {
@Autowired
private ProductCategoryService productCategoryService;
@PostMapping(
path = "/",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public WebResponse<ProductCategoryResponse> create(@RequestBody CreateProductCategoryRequest request) {
ProductCategoryResponse response = productCategoryService.create(request);
return WebResponse.<ProductCategoryResponse>builder().data(response).build();
}
@GetMapping(
path = "/",
produces = MediaType.APPLICATION_JSON_VALUE
)
public WebResponse<List<ProductCategoryResponse>> getAll() {
List<ProductCategoryResponse> response = productCategoryService.list();
return WebResponse.<List<ProductCategoryResponse>>builder().data(response).build();
}
@PatchMapping(
path = "/{id}",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public WebResponse<ProductCategoryResponse> update(@RequestBody UpdateProductCategoryRequest request, Integer id) {
ProductCategoryResponse response = productCategoryService.update(request, id);
return WebResponse.<ProductCategoryResponse>builder().data(response).build();
}
@DeleteMapping(
path = "/{id}",
produces = MediaType.APPLICATION_JSON_VALUE
)
public WebResponse<String> delete(@PathVariable Integer id) {
productCategoryService.delete(id);
return WebResponse.<String>builder().data("Category Deleted").build();
}
}
|
import 'package:flutter/material.dart';
import 'package:mobix/app/app_theme.dart';
import '../../shared/types/types.dart';
import '../../features/phones/phone_item/phone_item.dart';
class PhoneList extends StatelessWidget {
final List<Phones> phones;
const PhoneList({super.key, required this.phones});
@override
Widget build(BuildContext context) {
return ListView.separated(
separatorBuilder: (BuildContext context, int index) {
return const Divider(
height: 33,
color: AppTheme.dividerColor,
);
},
itemCount: phones.length,
itemBuilder: (BuildContext context, int index) {
if (phones.isEmpty) {
return const Center(
child: Text("ะขะตะปะตัะพะฝะพะฒ ะฝะตัั"),
);
} else {
return PhoneItem(
phoneName: phones[index].phoneName,
phoneSrc: phones[index].imgSrc,
phoneDesc: phones[index].desc,
phonePrice: phones[index].price,
);
}
});
}
}
|
import batFramework as bf
import pygame
import threading
from .style import style
from .customScene import CustomScene
from random import randint
def load_credits():
filepath = bf.ResourceManager().get_path("assets/creditcredit.txt")
res = []
try:
with open(filepath, 'r') as file:
res = [line for line in file.readlines() if line != "\n"]
return res
except FileNotFoundError:
return res
class CreditCreditScene(CustomScene):
def __init__(self):
super().__init__("creditcredit")
self.set_clear_color(bf.color.CLOUD_WHITE)
self.loaded_credits = load_credits()
self.labels = []
self.loaded = False
def do_when_added(self):
# fond
# self.root.add_child(bf.Image(""))
self.hud_camera.zoom(0.5)
# ajout du debugger
self.root.add_child(bf.Debugger())
# รฉcriture des crรฉdits
for line in self.loaded_credits[:10]:
self.labels.append(bf.Label(line).set_text_size(14).add_constraints(bf.ConstraintCenterX()))
self.container = bf.Container(bf.Column(10), *self.labels).add_constraints(bf.ConstraintCenterX())
self.root.add_child(self.container)
self.add_actions(bf.Action("EchapScene").add_key_control(pygame.K_ESCAPE))
self.timer = bf.Timer(0.9, loop=True, end_callback=lambda: self.container.children.pop(
0) if self.container.children else None).start()
self.timer.pause()
def create_labels(self):
for line in self.loaded_credits[10:101]:
self.container.add_child(
bf.Label(line).set_text_size(14).add_constraints(bf.ConstraintCenterX())
)
self.container.add_child(
style(bf.Button("Menu", lambda : self.manager.set_scene("title")))
)
self.loaded = True
def do_on_enter(self):
if self.loaded is False:
thread = threading.Thread(target=lambda: self.create_labels())
thread.start()
pass
def do_on_exit(self):
self.timer.pause()
def do_update(self, dt):
if self.hud_camera.transpose(self.container.rect).bottom > 40:
self.hud_camera.move_by(0,1)
#print(self.hud_camera.rect)
if self.actions.is_active("EchapScene"):
self.manager.set_scene("title")
# print(self.hud_camera.transpose(self.container.rect).bottom)
|
import 'package:flutter/material.dart';
import 'package:tiktok/app/data/service/video_controll.dart';
import 'package:tiktok/app/view/post/videoCrad.dart';
import '../../data/model/video.dart';
Widget feedVideos() {
ViedeoControll videoControll = ViedeoControll();
return FutureBuilder<List<Video>>(
future: videoControll.initializeVideoList(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: SizedBox(
width: 50,
height: 50,
child: CircularProgressIndicator()),
);
} else if (snapshot.hasError) {
return Center(
child: Text('Error loading videos'),);
} else {
return Stack(
children: [
PageView.builder(
controller: PageController(
initialPage: 0,
viewportFraction: 1,
),
itemCount: snapshot.data!.length,
onPageChanged: (index) {
index = index % snapshot.data!.length;
videoControll.changeVideo(index);
},
scrollDirection: Axis.vertical,
itemBuilder: (context, index) {
index = index % snapshot.data!.length;
return videoCard(snapshot.data![index]);
},
),
SafeArea(
child: Container(
padding: EdgeInsets.only(top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('ํ๋ก์',
style: TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.normal,
color: Colors.white70)),
SizedBox(
width: 7,
),
Container(
color: Colors.white70,
height: 10,
width: 1.0,
),
SizedBox(width: 7,),
Text('โค',
style: TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.bold,
color: Colors.white
))
],
)
)
)
],
);
}
}
);
}
|
# ssr
> + [้กน็ฎๅฐๅ](https://github.com/aladingmaideng/ssr)
## ssrไธcsr็ๅบๅซ
> + ssrไธบๆๅก็ซฏๆธฒๆ,csrไธบๅฎขๆท็ซฏๆธฒๆ
```html
<!-- csr -->
<body>
</body>
<script>
document.querySelector('body').innerHTML = `<div>111</div>`
</script>
```
```html
<!-- ssr -->
<body>
<div>111</div>
</body>
```
> + ๆๆพ็ๅบๅซๅฐฑๆฏ๏ผ
> + csr็้ป่พไธบ่ฏทๆฑๅฐhtml๏ผ็ถๅ่ทๅjs๏ผjsๆง่กๆธฒๆdom
> + ssrไธบ่ฏทๆฑๅฐ็htmlๅ
domๅทฒ็ปๅญๅจๆธฒๆไบ
## ssr่งฃๅณไบไปไน้ฎ้ข
> + ้็้ๆฑ็่ฟญไปฃspa้กน็ฎ็ผ่ฏๅบๆฅ็ๅ
็ไฝ็งฏไผ่ถๆฅ่ถๅคง๏ผ้ฃไน่ทๅ้กต้ข่ทๅไธๆฅๅ๏ผๆฏไธไธช็ฉบๆถๅญ๏ผ่ฟๆถๅ่ทๅjs็ๆถ้ดๆฏ่พ้ฟ็่ฏ๏ผไผ้ ๆๅพๆๆพ็็ฝๅฑๆๆ
> + ๆฏๅฆๅฎ็ฝ่ฟ่ฅ็ฑป้กน็ฎ้่ฆ่่seo๏ผ่็พๅบฆ็ฌ่ซๆ่ชๅทฑไบงๅ็บฟ็ฌ่ซ่ฏๅซไธๅบๆฅjsๆธฒๆ็ๅ
ๅฎน๏ผๆ ๆณ่พพๅฐ้ขๆ็ๆๆ๏ผๆฏๅฆๆฃ็ดขใๆจๅนฟ็ญ
## ๅฎ็ฐไธไธชssr้กน็ฎ
> + ๅไธบ2้จๅ๏ผserveๅclient
> + ๆไปฌ้่ฆไบ่งฃไธไธชๅ
ๅฎน๏ผไปฅreact็ssr้กน็ฎไธพไพ๏ผๆๅก็ซฏๆธฒๆๅบhtml้ชจๆถๅ๏ผๅฎขๆท็ซฏๆฅๆถๅฐ๏ผไผๅฐ่ทๅ็jsๅhtml้ชจๆถ่ฟ่ก`ๆฐดๅ`๏ผไนๅฐฑๆฏๆณจๅ
ฅ้ป่พ
### client
> + ไธบๅฎขๆท็ซฏๆธฒๆ้จๅ
> + ๆฐๅปบsrc็ฎๅฝ๏ผๅๅปบmain.tsx
```typescript
import { createRoot, hydrateRoot } from 'react-dom/client';
// ่ฆๆธฒๆ็็ปไปถ
import App from './App';
if (process.env.NODE_ENV == 'development') {
const root = createRoot(document.querySelector('#root') as any);
root.render(<App />);
} else {
hydrateRoot(document.querySelector('#root') as any, <App />);
}
```
```typescript
// App.tsx,ๅ
ๅฎน้ๆ
import { useState, Suspense, lazy } from 'react';
import Style from './styles/App';
import A from '@/components/A';
import B from '@/components/B';
import { DatePicker, Button } from 'antd';
import { Helmet } from 'react-helmet';
const App = () => {
const [show, setShow] = useState(false);
return (
<Style>
<Helmet>
<title>ๆๅกๆ ้ข</title>
<meta name="keywords" content="ๅ
ณ้ฎๅญๅ
ณ้ฎๅญ" />
<meta name="description" content="ๆ่ฟฐๆ่ฟฐ"></meta>
<link
rel="shortcut icon"
href="//mapopen-website-wiki.cdn.bcebos.com/LOGO/lbsyunlogo_icon.ico"
type="image/x-icon"
/>
</Helmet>
<DatePicker />
<Button>11</Button>
<div>็ถ็บงๅฎนๅจ</div>
<button
onClick={() => {
setShow(!show);
}}
>
ๅๅ
</button>
{show ? <A /> : <B />}
</Style>
);
};
export default App;
```
### ๅทฅ็จๅ้จๅ
> + ็ปไธๆพๅจconfig็ฎๅฝไธ๏ผไพฟไบ็ฎก็
> + ๆฝ็ฆปๅบๅ
ฌ็จ้ป่พ๏ผไพฟไบๅค็จ
```js
// base.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
resolve: {
// ไพๆฌก่กฅๅ
ๆไปถๅ็ผ
extensions: ['.tsx', '.jsx', '.ts', '.js'],
// ็ผฉๅๅฐๅๅ็ผ๏ผๅฏไปฅ@/xxx
alias: {
'@': path.resolve('src'),
},
},
module: {
rules: [
{
test: /\.(js|ts|tsx|jsx)/,
use: {
loader: 'babel-loader',
options: {
presets: [
// js็ผ่ฏ้็บง
'@babel/preset-env',
// ็ผ่ฏreact๏ผๅนถไธ็ปๆฏไธชๆไปถๅผๅ
ฅjsx๏ผไธ้่ฆๆฏๆฌก้ฝๆๅจๅผๅ
ฅreactไบ
['@babel/preset-react', { runtime: 'automatic' }],
//็ผ่ฏts
'@babel/preset-typescript',
],
},
},
},
],
},
plugins: [
new webpack.DefinePlugin({
// ็ป้กน็ฎๅ ไธไธชๅ้,main.tsx้็จๆฅๅบๅๅฝๅไฝฟ็จๅช็งๆจกๅผๅผๅ
NODE_ENV: process.env.NODE_ENV,
}),
],
};
```
> + ๅฎขๆท็ซฏ็ผ่ฏ
> + ๆไปฌ้่ฆไบ่งฃๅฐ`ๆฏไธชๆจกๅไน้ด็ไพ่ตๅ
ณ็ณป`๏ผไพฟไบๅ็ปญๆไปฌๅฏน่ตๆบ่ฟ่กๅฏผๅ
ฅ๏ผๆไปฅไฝฟ็จassets-webpack-pluginๆฅ่ฎฐๅฝ๏ผๅฎ`ไผ็ๆไธไธชjson`
> + reactๅreact-domไฝฟ็จcdnๅผๅ
ฅ๏ผๅๅฐๅ
ไฝ็งฏๅ็ผ่ฏๆถ้ฟ
```js
const base = require('./base');
const { merge } = require('webpack-merge');
const AssetsPlugin = require('assets-webpack-plugin');
module.exports = merge(base, {
entry: './src/main.tsx',
externals: {
react: 'React',
'react-dom': 'ReactDOM',
},
output: {
clean: true,
filename: '[name].js?[contenthash]',
publicPath: '/',
},
plugins: [
new AssetsPlugin({
entrypoints: true,
integrity: true,
prettyPrint: true,
includeFilesWithoutChunk: true,
includeAuxiliaryAssets: true,
includeDynamicImportedAssets: true,
}),
],
});
```
> + ๅฎขๆท็ซฏ็ผ่ฏ
> + ไปฃ็ ้ไฝฟ็จไบes module่ฏญๆณ๏ผ้ป่ฎคๆฏไธ่ฏๅซ็๏ผๆไปฅ็ผ่ฏไธ
> + node่ชๅธฆๅ
ไธ้่ฆ็ผ่ฏ่ฟๅป๏ผไฝฟ็จwebpack-node-externals็ปๅฎๆ้คๆ๏ผไนๅๅฐๅ
ไฝ็งฏๅ็ผ่ฏๆถ้ด
```js
// serve.js
const path = require('path');
const base = require('./base');
const nodeExternals = require('webpack-node-externals');
const { merge } = require('webpack-merge');
module.exports = merge(base, {
mode: 'production',
target: 'node',
entry: path.resolve(__dirname, '../serve/index.js'),
output: {
filename: 'serve.js',
},
externals: nodeExternals(),
});
```
> + ๆๅก็ซฏๅๅฎขๆท็ซฏ้ฝๆไบ๏ผไฝๆฏไปไปฌ้ฝๆฏ็ๆ็ฏๅขไฝฟ็จ็๏ผๆๆฌๅฐๅผๅไธ้่ฆ่ฟไน้บป็ฆ๏ผๆไปฅๅๆฅไธไธชdev็ฏๅข
```js
//dev.js
const path = require('path');
const HtmlPlugin = require('html-webpack-plugin');
const base = require('./base');
const { merge } = require('webpack-merge');
module.exports = merge(base, {
mode: 'development',
entry: './src/main.tsx',
externals: {
react: 'React',
'react-dom': 'ReactDOM',
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
output: {
clean: true,
filename: '[name].js?[contenthash]',
publicPath: '/',
},
plugins: [
new HtmlPlugin({
template: './public/index.html',
}),
],
devServer: {
historyApiFallback: true,
hot: true,
},
});
```
### ๆๅก็ซฏ้จๅ
> + ็ปไธๆพๅจserve็ฎๅฝไธ
> + ็จexpress่ตทไบไธไธชๆฌๅฐๆๅก
> + distไฝไธบ้ๆ่ตๆบ็ฎๅฝ
```js
// index.jsไธปๅ
ฅๅฃ,./clientไธบๅทฅๅ
ทๅฝๆฐ
import React from 'react';
import { createCache, extractStyle, StyleProvider } from '@ant-design/cssinjs';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom/server';
import { ServerStyleSheet } from 'styled-components';
import App from '../src/App';
import html from './client/html';
import getJs from './client/getJs';
import getHead from './client/getHead';
import { Helmet } from 'react-helmet';
const fs = require('fs');
const path = require('path');
const assets = JSON.parse(
fs.readFileSync(path.resolve(__dirname, '../webpack-assets.json'), 'utf-8')
);
let jsStr = getJs(assets['main'].js);
const express = require('express');
const app = express();
app.use(express.static('dist'));
app.get('*', (req, res) => {
const cache = createCache();
const sheet = new ServerStyleSheet();
const helmet = Helmet.renderStatic();
let body = renderToString(
sheet.collectStyles(
<StaticRouter>
<StyleProvider cache={cache}>
<App />
</StyleProvider>
</StaticRouter>
)
);
const styles = sheet.getStyleTags();
const styleText = extractStyle(cache);
res.send(
html({ styles: styles + styleText, body, head: getHead(helmet), js: jsStr })
);
});
app.listen(3000, () => {
console.log('http://127.0.0.1:3000');
});
```
```js
//./client/*
//getHead.js
const getHead = (helmet) => {
return (
helmet.title.toString() +
helmet.meta.toString() +
helmet.link.toString() +
helmet.style.toString()
);
};
export default getHead;
//getJs.js
const getJs = (strOrarg) => {
if (typeof strOrarg === 'string')
return `<script src="${strOrarg}"></script>`;
return strOrarg.map((str) => `<script src="${str}"></script>`).join('');
};
export default getJs;
//html.js
/**
* Html
* ่ฟไธช Html.js ๆไปถๅ
ๅฝไบไธไธชๆจกๆฟ๏ผๆไปฌๅฐๆๆ็ๆ็ๅบ็จ็จๅบไปฃ็ ๆๅ
ฅๅ
ถไธญ
* ๆ็ๅบ็จ็จๅบๅญ็ฌฆไธฒๆๅ
ฅ่ฟๅปใ
*/
const Html = ({ body, styles, head, js }) => `
<!DOCTYPE html>
<html>
<head>
${head}
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
${styles}
</head>
<body><div id="root">${body}</div></body>
</html>
${js}
`;
export default Html;
```
### ็ปไธๅฎ่ฃ
ไธไพ่ต
> + ็ดๆฅ่ดดpackage.json
```json
{
"name": "ssr",
"version": "1.0.0",
"description": "react็ssrๆนๆก",
"main": "index.js",
"scripts": {
"build": "webpack --config config/client.js --mode=production",
"dev": "cross-env NODE_ENV=develpoment webpack serve -c config/dev.js",
"serve:build": "webpack -c config/serve.js",
"serve:preview": "node dist/serve.js",
"preview": "npm-run-all --sequential build serve:**"
},
"keywords": [
"ssr",
"react-ssr"
],
"author": "cuishoulong",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.20.12",
"@babel/preset-env": "^7.20.2",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.18.6",
"@types/node": "^18.11.18",
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"@types/react-helmet": "^6.1.6",
"@types/react-router": "^5.1.20",
"@types/react-router-dom": "^5.3.3",
"@types/styled-components": "^5.1.26",
"@typescript-eslint/eslint-plugin": "^5.50.0",
"@typescript-eslint/parser": "^5.50.0",
"assets-webpack-plugin": "^7.1.1",
"babel-loader": "^9.1.2",
"cross-env": "^7.0.3",
"css-loader": "^6.7.3",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-react": "^7.32.2",
"html-webpack-plugin": "^5.5.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.8.3",
"style-loader": "^3.3.1",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"webpack-dev-server": "^4.11.1",
"webpack-merge": "^5.8.0",
"webpack-node-externals": "^3.0.0"
},
"dependencies": {
"antd": "^5.1.7",
"prism-react-renderer": "^1.3.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-helmet": "^6.1.0",
"react-router": "^6.8.0",
"react-router-dom": "^6.8.0",
"styled-components": "^5.3.6"
}
}
```
## ๅขๅ ts็ฑปๅๆ็คบ
> + ็ฐๅจไฝฟ็จ็ๆฏ`@babel/preset-typescript`ๆฅ็ผ่ฏ็tsๆไปถ๏ผๅฎ็ธๆฏ`ts-loaderๅฟซไธไธๅฐ`๏ผไฝ`็ผบไนts็ๆ ก้ช`๏ผ้ฃไนๆไปฌๅ ไธไธชtsconfig.jsonๆฅ่ฟ่ก่ฏญๆณๆ็คบ๏ผไฝ`ไธ้ปๅก็ผ่ฏ`
```json
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"noImplicitAny": false, //้ป่ฎคๆ ๆณจany
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"]
}
```
## ไธไบๆณจๆ็น
> + react็ๆๅก็ซฏๆธฒๆ่ฟ้ไฝฟ็จไบ`renderToString`
### seo
> + seo้จๅไฝฟ็จไบ`react-helmet`๏ผๅจgetheadๅฝๆฐ้ๅฏไปฅๆณจๆๅฐ๏ผๅฎ็ไฝฟ็จๆนๆณๅฐฑๆฏ`ๅฎไพ.ๆ ็ญพ.toString()`,็ฎๅๆฏๆๆๆ็headๅ็ๆ ็ญพ็ฑปๅ
### css
> + ๅฝๆต่งๅจๆธฒๆhtml้ชจๆถ็ๆถๅ๏ผๆไปฌๆๆๅฎๅฐcssๅ ่ฝฝ๏ผ่ฟๆ ท้กต้ขๅฐฑไธไผๆ้ชๅจ็ๆๆ๏ผไนๅฏไปฅ็ๅฐๆด็พ่ง็้กต้ข๏ผๆไปฅ้่ฆๅจๆๅก็ซฏๅค็css
> + ไฝฟ็จ`styled-components`ๆฅๅๆ ทๅผ๏ผๆๅไฝฟ็จ`ServerStyleSheet`ๆนๆณ
> + antd็5็ๆฌไฝฟ็จไบcss in js็ๆฌ๏ผ้ป่ฎคๆฏๆไบๆ้ๅผๅ
ฅ๏ผๆไปฅไปฅๅ็`babel-plugin-importๅจantd้ๆฒกๆๆไนไบ`
> + ๆๅantd็cssไฝฟ็จ`createCache, extractStyle, StyleProvider`,
[ๅฎๆนๆดๆฐๆๆกฃ](https://ant.design/docs/react/migration-v5-cn#%E7%A7%BB%E9%99%A4-babel-plugin-import)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 16 15:58:22 2021
@author: Mark Zaidi
Many of the Nd-conjugated antibodies have been using thresholds on the median cell/nucleus measurement as a means of
classifying a cell as positive or negative for that marker. Now that IMC_despeckler.py removes the speckle artifact
that forced us to use median thresholds, we can go back to using mean measurement thresholds, which is what we used for
all other IHC markers.
Now, we need to find the mean threshold that will result in roughly the same cells being classified as positive, as done using
the median threshold. To do this, we need to:
- load in a per-cell .csv into the "data" dataframe
- find what percent of cells are positive with the current median threshold
- of the cells above the median measurement threshold, what is the minimum mean measurement
- what percent of cells are above this minimum mean measurement (new threshold)
- compare the old median threshold with the new mean threshold via percent positive scoring
"""
#%% load libraries
import pandas
import pandas as pd
import math
import matplotlib
import matplotlib.pyplot as plt
import os
import numpy as np
import seaborn as sns
from scipy import stats
from statannot import add_stat_annotation
import time
from scipy.stats import spearmanr
import winsound
#%% Read data
data=pandas.read_csv(r'C:\Users\Mark Zaidi\Documents\QuPath\PIMO GBM related projects\August 16 2021 - updated panel\August 16 2021 - updated panel.csv')
colnames=data.columns
#%% identify pos cells
#define pos_cells as those with a measurement above threshold defined in thresholds.xlsx
pos_cells_median=data[data["Nd(150)_150Nd-SOX2: Nucleus: Median"]>6.1194]
#find what percent of cells are positive using the current median threshold
pct_pos_median=len(pos_cells_median)/len(data)*100
#of those positive cells, find what the minimum mean threshold is
min_mean_pos_cells=min(pos_cells_median["Nd(150)_150Nd-SOX2: Nucleus: Mean"])
#then on the original data, find what percent of cells are positive using the generated mean threshold
pos_cells_mean=data[data["Nd(150)_150Nd-SOX2: Nucleus: Mean"]>min_mean_pos_cells]
pct_pos_mean=len(pos_cells_mean)/len(data)*100
#%%
|
#include "lists.h"
/**
* reverse_listint - reverse linked list
*
* Return: pointer to the head node
*
* @head: pointer to the first pointer
*
*/
listint_t *reverse_listint(listint_t **head)
{
listint_t *tmp = NULL, *forward = NULL;
while (*head != NULL)
{
forward = (*head)->next;
(*head)->next = tmp;
tmp = *head;
*head = forward;
}
*head = tmp;
return (*head);
}
|
The bug in the provided code is in the inner loop where the value of the loop iterator `i` and the comparison operator are incorrect.
The nested for loop iterates as long as the condition specified is true. However, the condition provided `for (int i = 0; i >= size; i++)` has an incorrect comparison `i >= size` which initially is never true (since `i` is 0 and `size` is at least 1) hence the body of the loop is never executed. Secondly, the loop iterator should be `i < size` for iteration over the queue elements.
The recursive function `kSimilarity` also needs to be corrected with respect to the iteration conditional.
Below is the fixed code with those changes:
```java
import java.util.*;
class Solution {
public int kSimilarity(String s1, String s2) {
HashSet<String> vis = new HashSet<>();
ArrayDeque<String> queue = new ArrayDeque<>();
int level = 0;
queue.add(s1);
while (queue.size() > 0) {
int size = queue.size();
for (int i = 0; i < size; i++) { // Fix: corrected the loop condition and iterator
String rem = queue.remove();
if (vis.contains(rem)) {
continue;
}
vis.add(rem);
if (rem.equals(s2)) {
return level;
}
for (String s : getNeighbors(rem, s2)) {
if (! vis.contains(s)) {
queue.add(s);
}
}
}
level++;
}
return -1;
}
// Remaining code unchanged
}
```
With these changes, the provided code is now bug-free and will correctly determine the smallest k for which s1 and s2 are k-similar.
|
/**
* Adds nullability to given type, an opposite of TS standard NonNullable.
*/
export type Nullable<T> = T | null;
/**
* String containing CommonMark text.
*
* @see https://commonmark.org
*/
export type CommonMarkString = string;
/**
* String representing a URL, or parts of them.
*/
export type URLString = string;
/**
* URI template string, like /list/{from}/{to}
*/
export type ParametrisedURLString = string;
/**
* String representing an e-mail address.
*/
export type EmailString = string;
/**
* String representing a semantic version string.
*/
export type VersionString = string;
/**
* String representing a date/time in ISO8601 format.
*/
export type DateTimeString = string;
/**
* String representing MIME types.
*/
export type MIMETypeString = string;
/**
* Enumerates well-known HTTP request methods.
*/
export type HTTPMethod =
| 'GET'
| 'POST'
| 'PUT'
| 'PATCH'
| 'DELETE'
| 'OPTIONS'
| 'HEAD'
| 'CONNECT'
| 'TRACE';
/**
* Integer, representing HTTP status code.
*/
export type HTTPStatusCode = number;
//
// JSON spec
//
/**
* Primitive JSON values.
*/
export type JSONPrimitive = null | boolean | number | string;
/**
* Any JSON value. This is the root type of JSON spec.
*/
export type JSONValue = JSONPrimitive | JSONArray | JSONObject;
/**
* JSON array.
*/
export type JSONArray = JSONValue[];
/**
* JSON object.
*/
export type JSONObject = {
[key: string]: JSONValue;
};
/**
* Convenience type, representing a record those values are JSONObject-s only.
*/
export type JSONObjectRecord = Record<string, JSONObject>;
/**
* Convenience type, representing an array of JSONObject objects.
*/
export type JSONObjectArray = JSONObject[];
/**
* Convenience type, representing a JSON Pointer string.
*
* @see https://datatracker.ietf.org/doc/html/rfc6901
*/
export type JSONPointerString = string;
/**
* JSON Schema reference.
*
* @see https://json-schema.org/understanding-json-schema/structuring.html#ref
*/
export type JSONRef = {
$ref: string;
};
/**
* Use this if you need to declare some type or a reference to it.
*/
export type ObjectOrRef<T> = T | JSONRef;
/**
* Convenience type, representing an empty JSON object.
*/
export type EmptyObject = Record<string, never>;
//
// JSON:API spec
//
/**
* Meta information.
*
* @see https://jsonapi.org/format/#document-meta
*/
export type JSONAPIMeta = JSONObject;
/**
* Represents a single link.
*
* @see https://jsonapi.org/format/#document-links
*/
export type JSONAPILink = string | { href: string; meta?: JSONAPIMeta };
/**
* Represents a resource ID. `JSONAPIResourceID` must either be a string or a string literal.
*
* @example
* JSONAPIResourceID // generic resource ID object
* JSONAPIResourceID<'employees'> // resource ID for specific resource
*
* @typeParam TResourceType resource type string. To identify specific resource,
* pass a string literal.
*
* @example
* // generic type, able to represent any resource's ID
* type AnyResourceID = JSONAPIResourceID;
*
* // represents a resource with specific type
* type EmployeeResourceID = JSONAPIResourceID<'employees'>;
*
* @see https://jsonapi.org/format/#document-resource-identifier-objects
*/
export interface JSONAPIResourceID<TResourceType extends string = string> {
type: TResourceType;
id: string;
meta?: JSONAPIMeta;
}
/**
* Common part for all resource linkage objects.
*/
interface JSONAPIResourceRelationshipBase {
links?: {
self: JSONAPILink;
related: JSONAPILink;
[other: string]: JSONAPILink;
};
}
/**
* Represents an optional one-to-one (or, 0-1) resource relationship.
*
* @typeParam TResourceType resource type string. To identify specific resource,
* pass a string literal.
*
* @example
* // a 0-1 relationship to any resource
* type AnyRelationship0 = JSONAPIResourceRelationship0;
*
* // a 0-1 relationshop to specific resource
* type CompanyRelationship0 = JSONAPIResourceRelationship0<'companies'>;
*
* @see https://jsonapi.org/format/#document-resource-object-relationships
* @see https://jsonapi.org/format/#document-resource-object-linkage
* @see {@link JSONAPIResourceID}
*/
export interface JSONAPIResourceRelationship0<TResourceType extends string = string>
extends JSONAPIResourceRelationshipBase {
data: JSONAPIResourceID<TResourceType> | null;
}
/**
* Represents a one-to-one resource relationship.
*
* @typeParam TResourceType resource type string. To identify specific resource,
* pass a string literal.
*
* @example
* // a 1-1 relationship to any resource
* type AnyRelationship1 = JSONAPIResourceRelationship1;
*
* // a 1-1 relationshop to specific resource
* type CompanyRelationship1 = JSONAPIResourceRelationship1<'companies'>;
*
* @see https://jsonapi.org/format/#document-resource-object-relationships
* @see https://jsonapi.org/format/#document-resource-object-linkage
* @see {@link JSONAPIResourceID}
*/
export interface JSONAPIResourceRelationship1<TResourceType extends string = string>
extends JSONAPIResourceRelationshipBase {
data: JSONAPIResourceID<TResourceType>;
}
/**
* Represents a one-to-many resource relationship.
*
* @typeParam TResourceType resource type string. To identify specific resource,
* pass a string literal.
*
* @example
* // a 1-N relationship to any resource
* type AnyRelationshipN = JSONAPIResourceRelationshipN;
*
* // a 1-N relationshop to specific resource
* type CompanyRelationshipN = JSONAPIResourceRelationshipN<'companies'>;
*
* @see https://jsonapi.org/format/#document-resource-object-relationships
* @see https://jsonapi.org/format/#document-resource-object-linkage
* @see {@link JSONAPIResourceID}
*/
export interface JSONAPIResourceRelationshipN<TResourceType extends string = string>
extends JSONAPIResourceRelationshipBase {
data: JSONAPIResourceID<TResourceType>[];
}
/**
* Represents a resource relationship of any type (both single and multiple).
*
* @typeParam TResourceType resource type string. To identify specific resource,
* pass a string literal.
*
* @see https://jsonapi.org/format/#document-resource-object-relationships
* @see {@link JSONAPIResourceRelationship0}
* @see {@link JSONAPIResourceRelationship1}
* @see {@link JSONAPIResourceRelationshipN}
*/
export type JSONAPIResourceRelationship<TResourceType extends string = string> =
| JSONAPIResourceRelationship0<TResourceType>
| JSONAPIResourceRelationship1<TResourceType>
| JSONAPIResourceRelationshipN<TResourceType>;
/**
* Base definition of a JSON:API resource.
*
* @typeParam TResourceType resource type string
* @typeParam TAttributesType type of resource attributes.
* By default, resources do not have any attributes.
* @typeParam TRelationshipsType type of resource relationships.
* By default, relationships are empty.
*
* @example
* // this type represents a "pet" resource, which has 2 attributes
* // and 3 relationships
* type PetResource = JSONAPIServerResource<
* 'pets',
* {
* nickName: string;
* age?: number;
* },
* {
* shelter: JSONAPIResourceRelationship1<'shelters'>;
* owner: JSONAPIResourceRelationship0<'people'>;
* siblings: JSONAPIResourceRelationshipN<'pets'>;
* }
* >;
*
* @see https://jsonapi.org/format/#document-resource-objects
* @see {@link JSONAPIServerResource}
* @see {@link JSONAPIClientResource}
*/
interface JSONAPIResourceBase<
TResourceType extends string,
TAttributesType extends JSONObject,
TRelationshipsType extends Record<string, JSONAPIResourceRelationship>,
> {
type: TResourceType;
attributes: TAttributesType;
relationships?: TRelationshipsType;
links?: {
self: JSONAPILink;
};
meta?: JSONAPIMeta;
}
/**
* Represents a JSON:API resource originated from the server.
*
* @typeParam TResourceType resource type string
* @typeParam TAttributesType type of resource attributes.
* By default, resources do not have any attributes.
* @typeParam TRelationshipsType type of resource relationships.
* By default, relationships are empty.
*
* @see https://jsonapi.org/format/#document-resource-objects
* @see {@link JSONAPIResourceBase}
* @see {@link JSONAPIResourceID}
* @see {@link JSONAPIResourceRelationship}
*/
export interface JSONAPIServerResource<
TResourceType extends string = string,
TAttributesType extends JSONObject = JSONObject,
TRelationshipsType extends Record<string, JSONAPIResourceRelationship> = Record<
string,
JSONAPIResourceRelationship
>,
> extends JSONAPIResourceBase<TResourceType, TAttributesType, TRelationshipsType> {
id: string;
}
/**
* Resource originated from the client, that does not yet exist on the server.
*
* @typeParam TResourceType resource type string
* @typeParam TAttributesType type of resource attributes.
* By default, resources do not have any attributes.
* @typeParam TRelationshipsType type of resource relationships.
* By default, relationships are empty.
*
* @see https://jsonapi.org/format/#document-resource-objects
* @see {@link JSONAPIResourceID}
* @see {@link JSONAPIResourceRelationship}
*/
export interface JSONAPIClientResource<
TResourceType extends string = string,
TAttributesType extends JSONObject = JSONObject,
TRelationshipsType extends Record<string, JSONAPIResourceRelationship> = Record<
string,
JSONAPIResourceRelationship
>,
> extends JSONAPIResourceBase<TResourceType, TAttributesType, TRelationshipsType> {
id?: string;
}
/**
* Represents any JSON:API resource.
*
* @see https://jsonapi.org/format/#document-resource-objects
*/
export type JSONAPIResource<
TResourceType extends string = string,
TAttributesType extends JSONObject = EmptyObject,
TRelationshipsType extends Record<string, JSONAPIResourceRelationship> = EmptyObject,
> =
| JSONAPIClientResource<TResourceType, TAttributesType, TRelationshipsType>
| JSONAPIServerResource<TResourceType, TAttributesType, TRelationshipsType>;
/**
* Holds information about JSON:API implementation.
*
* @see https://jsonapi.org/format/#document-jsonapi-object
*/
export interface JSONAPIImplementationInfo {
version?: '1.0';
meta?: JSONAPIMeta;
}
/**
* Holds links for the whole document.
*
* @see https://jsonapi.org/format/#document-top-level
*/
export interface JSONAPITopLevelLinks {
self?: JSONAPILink;
related?: JSONAPILink;
}
/**
* @see https://jsonapi.org/format/#document-top-level
*/
interface JSONAPIDocumentBase {
jsonapi?: JSONAPIImplementationInfo;
links?: JSONAPITopLevelLinks;
meta?: JSONAPIMeta;
}
export type JSONAPIClientDocumentPrimaryData =
| JSONAPIClientResource
| JSONAPIClientResource[]
| JSONAPIResourceID
| JSONAPIResourceID[];
/**
* Client (request) document.
*
* @typeParam TPrimaryData determines the type of document's primary data. This
* must be either resource ID type or a resource type
* @typeParam TIncludedData determines the type(-s) of resources included in
* the document. This must be a resource or a union of resource types.
*
* @example
* type Company = JSONAPIResource<'companies', ...>;
* type Department = JSONAPIResource<'departments', ...>;
* type Person = JSONAPIResource<'people', ...>;
*
* // this document has a single company resource as its primary data,
* // and a list of either department of person resources included
* type CompanyDocument = JSONAPIDataDocument<Company, Department | Person>;
*
* @see https://jsonapi.org/format/#document-top-level
*/
export interface JSONAPIClientDocument<
TPrimaryData extends JSONAPIClientDocumentPrimaryData = JSONAPIClientResource,
TIncludedData extends JSONAPIClientResource = JSONAPIClientResource,
> extends JSONAPIDocumentBase {
data: TPrimaryData;
included?: TIncludedData[];
}
export type JSONAPIPrimaryDocumentData =
| JSONAPIServerResource
| JSONAPIServerResource[]
| JSONAPIResourceID
| JSONAPIResourceID[]
| null;
/**
* Server (response) document that contains data.
*
* @typeParam TPrimaryData determines the type of document's primary data. This
* must be either resource ID type or a resource type
* @typeParam TIncludedData determines the type(-s) of resources included in
* the document. This must be a resource or a union of resource types.
*
* @example
* type Company = JSONAPIResource<'companies', ...>;
* type Department = JSONAPIResource<'departments', ...>;
* type Person = JSONAPIResource<'people', ...>;
*
* // this document has a single company resource as its primary data,
* // and a list of either department of person resources included
* type CompanyDocument = JSONAPIDataDocument<Company, Department | Person>;
*
* @see https://jsonapi.org/format/#document-top-level
*/
export interface JSONAPIDataDocument<
TPrimaryData extends JSONAPIPrimaryDocumentData = JSONAPIServerResource,
TIncludedData extends JSONAPIServerResource = JSONAPIServerResource,
> extends JSONAPIDocumentBase {
data: TPrimaryData;
included?: TIncludedData[];
}
/**
* A single error object.
*
* @see https://jsonapi.org/format/#error-objects
*/
export interface JSONAPIError {
id?: string;
links?: {
about: JSONAPILink;
};
status?: string;
code?: string;
title?: string;
detail?: string;
source?: {
pointer?: JSONPointerString;
parameter?: string;
};
meta?: JSONAPIMeta;
}
/**
* Server (response) document that contains error objects.
*
* @see https://jsonapi.org/format/#document-top-level
*/
export interface JSONAPIErrorDocument extends JSONAPIDocumentBase {
errors: JSONAPIError[];
}
/**
* Represents any document.
*
* @see https://jsonapi.org/format/#document-top-level
*/
export type JSONAPIDocument<
TPrimaryData extends JSONAPIPrimaryDocumentData = JSONAPIServerResource,
TIncludedData extends JSONAPIServerResource = JSONAPIServerResource,
> = JSONAPIDataDocument<TPrimaryData, TIncludedData> | JSONAPIErrorDocument;
//
// General purpose
//
export interface Disposable {
dispose(): void;
}
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe JobOccupationSerializer, type: :serializer do
context 'Individual Resource Representation' do
let(:resource) { FactoryBot.build(:job_occupation, id: '1') }
let(:serialization) { JsonApiSerializer.serialize(resource) }
subject do
JSON.parse(serialization.to_json)
end
described_class::ATTRIBUTES.each do |attribute|
it "has #{attribute.to_s.humanize.downcase}" do
value = resource.public_send(attribute)
expect(subject).to have_jsonapi_attribute(attribute.to_s, value)
end
end
%w(job occupation).each do |relationship|
it "has #{relationship} relationship" do
expect(subject).to have_jsonapi_relationship(relationship)
end
end
it 'is valid jsonapi format' do
expect(subject).to be_jsonapi_formatted('job_occupations')
end
end
end
# == Schema Information
#
# Table name: job_occupations
#
# id :bigint(8) not null, primary key
# job_id :bigint(8)
# occupation_id :bigint(8)
# years_of_experience :integer
# importance :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_job_occupations_on_job_id (job_id)
# index_job_occupations_on_occupation_id (occupation_id)
#
# Foreign Keys
#
# fk_rails_... (job_id => jobs.id)
# fk_rails_... (occupation_id => occupations.id)
#
|
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add("login", (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This is will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
Cypress.Commands.add("checkMeta", (fixture) => {
cy.fixture(fixture).then((meta) => {
cy.get("[cy-data='title']").should("contain.text", meta.title);
cy.get("[cy-data='author']").should("contain.text", meta.author);
cy.get("[cy-data='description']").should("contain.text", meta.description);
meta.keywords.forEach((k) => {
cy.get("[cy-data='keyword']").should("contain.text", k);
});
});
});
|
import pygame
import print_render as pr
import text_wrap as tw
def display_spell_page(screen, spell, marginWidth, marginHeight):
screen.fill((252, 245, 229))
#set fonts
titleFont = pygame.font.Font("assets/RINGM___.TTF", 35)
bodyFont = pygame.font.Font("assets/MorrisRoman-Black.ttf", 18)
#text wrap the spell name in case it is too long
spellName = tw.text_wrap(spell["name"], False, 30)
#render and print line by line
for line in spellName:
pr.print_render(screen, titleFont, line, marginWidth, marginHeight, True)
#move down 2 lines, leaving a space
offset = 40
#render and print the spell's level
pr.print_render(screen, bodyFont, "Level: " + str(spell["level"]), marginWidth, marginHeight + offset, False)
#move down 1 line
offset += 20
#if spell is ritual cast, include it alongside its school of magic
if (spell["ritual"]):
spellSchool = bodyFont.render("School: " + spell["school"]["name"] + " (Ritual)", True, "black")
#otherwise only prepare school of magic
else:
spellSchool = bodyFont.render("School: " + spell["school"]["name"], True, "black")
#print spell's school
screen.blit(spellSchool, (marginWidth, marginHeight + offset))
#move down 1 line
offset += 20
#render and print the spell's casting time
pr.print_render(screen, bodyFont, "Casting Time: " + spell["casting_time"], marginWidth, marginHeight + offset, False)
#move down 1 line
offset += 20
#print and render the spell's range
pr.print_render(screen, bodyFont, "Range: " + spell["range"], marginWidth, marginHeight + offset, False)
#move down 1 line
offset += 20
#loop to combine spell components into one string
for tag in spell["components"]:
#if multiple components, separate by comma
if (tag != spell["components"][-1]):
comps = ""
comps += tag + ", "
#Otherwise you must have either 1 or be at the final one, so do not include comma
else:
comps = ""
comps += tag
#print and render spell components
pr.print_render(screen, bodyFont, "Components: " + comps, marginWidth, marginHeight + offset, False)
#move down 1 line
offset += 20
#if there is a required material, text wrap it, and print line by line
if "material" in spell:
matWrap = tw.text_wrap("Materials: " + spell["material"], False, 30)
for line in matWrap:
pr.print_render(screen, bodyFont, line, marginWidth, marginHeight + offset, False)
offset += 20
#if the spell has concentration, print along side duration
if (spell["concentration"]):
spellDuration = bodyFont.render("Duration: " + spell["duration"] + " (Concentration)", True, "black")
#otherwise print duration only
else:
spellDuration = bodyFont.render("Duration: " + spell["duration"], True, "black")
#print spell duration
screen.blit(spellDuration, (marginWidth, marginHeight + offset))
#move down by 2 lines, leaving a space
offset += 40
#text wrap spell description and print it line by line
spellDesc = tw.text_wrap(spell["desc"][0], True, 65)
for line in spellDesc:
pr.print_render(screen, bodyFont, line, marginWidth, marginHeight + offset, False)
offset += 20
#move down by one more, leaving a space
offset += 20
#if spell can be casted at higher levels, include that
#include by text wrapping and printing line by line
if spell["higher_level"] != []:
spellDmgBoost = tw.text_wrap(spell["higher_level"][0], True, 65)
for line in spellDmgBoost:
pr.print_render(screen, bodyFont, line, marginWidth, marginHeight + offset, False)
offset += 20
|
__author__ = 'prahlad.sharma'
from virgin_utils import *
class SelectShip(General):
"""
Page class for Ship Selection Page
"""
def __init__(self, web_driver):
"""
To initialise the locators
:param web_driver:
"""
super().__init__()
self.webDriver = web_driver
self.locators = General.dict_to_ns({
"loader": "//div[@class='LoaderContainer__div']//img",
"header": "//span[contains(text(),'Select Ship')]",
"all_ships": "//div[@class='column is-one-third false']//div//img",
"all_ships_name": "//div[@class='column is-one-third false']//div//img/../following-sibling::div",
"next_button": "//span[contains(text(),'NEXT')]",
"ship_name": "//div[text()='%s']/preceding-sibling::div"
})
def select_ship(self, test_data):
"""
To get the ship name
"""
self.webDriver.wait_till_element_appear_on_screen(element=self.locators.header, locator_type='xpath')
self.webDriver.click(element=self.locators.ship_name % test_data['shipName'], locator_type='xpath')
self.webDriver.allure_attach_jpeg('select_ship')
self.webDriver.click(element=self.locators.next_button, locator_type='xpath')
# def select_ship(self):
# """
# To select the Ship from Ship Page
# """
# self.webDriver.click(element=self.locators.all_ships, locator_type='xpath')
# self.webDriver.allure_attach_jpeg('select_ship')
# self.webDriver.click(element=self.locators.next_button, locator_type='xpath')
def verify_ship_page_availability(self):
"""
Function to verify ship page availability
"""
self.webDriver.wait_till_element_appear_on_screen(element=self.locators.all_ships, locator_type='xpath')
self.webDriver.allure_attach_jpeg('ship_page_available')
return self.webDriver.is_element_display_on_screen(element=self.locators.all_ships, locator_type='xpath')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 2 12:26:33 2023
@author: yintingchiu
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
from scipy.interpolate import make_interp_spline
plt.rc_context({'axes.edgecolor':'grey', 'xtick.color':'grey', 'ytick.color':'grey', 'figure.facecolor':'grey'})
plt.rcParams['figure.dpi'] = 700
site = pd.read_csv('Research/Nitrate/Nitrate Loss py/hourly_t_losangeles.csv')
site['sfc_temp'] = site['Sample Measurement']
site['sfc_temp'] = ((site['Sample Measurement']-32) *5/9) + 273
#print(site.loc[:,'sfc_temp'].mean())
site = site[['Latitude', 'Longitude', 'Date Local','Time Local','State Name', 'County Name','sfc_temp']]
site['Date Local'] = pd.to_datetime(pd.to_datetime(site['Date Local'], format="%Y-%m-%d"))
site['Year'] = site['Date Local'].dt.year
site['Month'] = site['Date Local'].dt.month
site['Day'] = site['Date Local'].dt.day
site['K'] = ((site['sfc_temp'])**(-6.025))*np.exp(118.87)*(np.exp(-24084/((site['sfc_temp']))))
rh = pd.read_csv('Research/EPA data/hourly_rh_losangeles.csv')
rh = rh[['Latitude', 'Longitude', 'Date Local', 'Time Local','Sample Measurement']]
rh = rh.rename(columns={'Sample Measurement':'RH'})
rh['Date Local'] = pd.to_datetime(pd.to_datetime(rh['Date Local'], format="%Y-%m-%d"))
rh['Year'] = rh['Date Local'].dt.year
rh['Month'] = rh['Date Local'].dt.month
rh['Day'] = rh['Date Local'].dt.day
rh = rh.drop(columns='Date Local')
rh['Season'] = rh['Month']%12 // 3 + 1
rh['Season'] = rh['Season'].replace({1:'Winter', 2:'Spring', 3:'Summer', 4:'Fall'})
rh = rh.pivot_table(index=['Year', 'Month', 'Day', 'Time Local', 'Season'], values='RH', aggfunc=np.median)
rh = rh.reset_index()
site = pd.merge(site, rh, on=['Year','Month','Day', 'Time Local'])
site['sfc_temp'] = site['sfc_temp'].astype(float)
site['DRH%'] = 61.8*np.exp((16254.84/8.3145)*(4.298*((1/site['sfc_temp'])-(1/298))-((-3.623e-2)*np.log(site['sfc_temp']/298))-(7.853e-5*(site['sfc_temp']-298))))
#site['DRH%'] = 62*np.exp(824.3908017*((1/(site['sfc_temp']))-(1/298)))
site['ln P1'] = -135.94 + (8763/site['sfc_temp']) + (19.12*np.log(site['sfc_temp']))
site['ln P2'] = -122.65 + (9969/site['sfc_temp']) + (16.22*np.log(site['sfc_temp']))
site['ln P3'] = -182.61 + (13875/site['sfc_temp']) + (24.46*np.log(site['sfc_temp']))
site['P1'] = np.exp(site['ln P1'])
site['P2'] = np.exp(site['ln P2'])
site['P3'] = np.exp(site['ln P3'])
site['K* factor'] = (site['P1'] - (site['P2']*(1-(site['RH']/100)))+(site['P3']*(1-(site['RH']/100))**2))*(1-(site['RH']/100)**1.75)
#when K is above the DRH
site['K'] = np.where(site['RH'] > site['DRH%'], site['K']*site['K* factor'], site['K'])
#square root K
site['K'] = site['K'].clip(lower=0)
site['sK'] = np.sqrt(site['K'])
site = site.pivot_table(index=['Date Local','State Name',
'County Name','Year', 'Month', 'Day','Season'], values=['sfc_temp', 'sK'],
aggfunc={'sfc_temp':np.mean, 'sK':np.sum}).reset_index()
#volatilized nitrate
site['NO3_v'] = (745.7/site['sfc_temp'])*(site['sK'])*1/24
site = site.pivot_table(index=['Date Local', 'State Name', 'County Name', 'Year', 'Month', 'Day', 'Season'], values=['NO3_v', 'sfc_temp'])
site = site.reset_index()
nitrate = pd.read_csv('Research/Regression Model/PM2.5_NO3_mass_CA.csv')
nitrate['Date Local'] = pd.to_datetime(pd.to_datetime(nitrate['Date Local']))
nitrate['Year'] = nitrate['Date Local'].dt.year
nitrate['Month'] = nitrate['Date Local'].dt.month
nitrate['Day'] = nitrate['Date Local'].dt.day
nitrate = nitrate[nitrate['County Name']=='Los Angeles']
nitrate = nitrate[['Date Local','Arithmetic Mean','Method Name','State Name', 'County Name','Address',
'Average Ambient Temperature','Total Nitrate PM2.5 LC', 'Year', 'Month','Day',
'Latitude', 'Longitude']]
#nitrate = nitrate.dropna()
nitrate['Total Nitrate PM2.5 LC'] = nitrate['Total Nitrate PM2.5 LC'].clip(lower=0)
##finding value counts
#nitrate['monthyear'] = nitrate['Date Local'].dt.to_period('M')
#nitrate = nitrate[['Date Local', 'Arithmetic Mean', 'monthyear', 'Address']].dropna()
#print(nitrate['Address'].unique())
#values = nitrate['monthyear'].value_counts().reset_index()
#values = values.rename(columns={'monthyear':'counts', 'index':'monthyear'})
#values['monthyear'] = values['monthyear'].astype(str)
#values['monthyear'] = pd.to_datetime(values['monthyear'])
#values['month'] = values['monthyear'].dt.month
#values['year'] = values['monthyear'].dt.year
#values = values.set_index(['year', 'month'])
#values = values[['counts']].unstack('month')
#values.to_excel('Research/Manuscript Drafts/no3_data.xlsx')
###
nitrate = nitrate.rename(columns={'Arithmetic Mean':'PM2.5'})
nitrate = nitrate.pivot_table(index=['State Name', 'County Name', 'Year', 'Month', 'Day'],
values=['PM2.5', 'Average Ambient Temperature', 'Total Nitrate PM2.5 LC' ]).reset_index()
nitrate = nitrate.dropna()
site = pd.merge(site, nitrate, on=['State Name', 'County Name','Year', 'Month','Day'])
#dont need lat long anymore, average for whole county
site['sfc_temp'] = site['sfc_temp'] - 273.15
#site = site.dropna()
#site = site[site['Total Nitrate PM2.5 LC']>=0]
site.loc[site['NO3_v']> site['Total Nitrate PM2.5 LC'], 'NO3_v'] = site['Total Nitrate PM2.5 LC']
site['Total PM2.5'] = site['PM2.5'] + site['NO3_v']
site['NO3_v/PM2.5'] = (site['NO3_v']*100/site['Total PM2.5'])
site['NO3_v/NO3'] = site['NO3_v']*100/ site['Total Nitrate PM2.5 LC']
#site.to_csv('Research/Manuscript Drafts/Code for Nitrate_PM/Los Angeles_pm.csv')
#plot PM2.5
fig, ax= plt.subplots()
pmtotal = site.dropna().pivot_table(index='Year', values=['Total PM2.5', 'PM2.5'])
pmtotal = pmtotal.reset_index()
x = pmtotal['Year'].values
y = pmtotal['PM2.5'].values
y1 = pmtotal['Total PM2.5'].values
X_Y_Spline = make_interp_spline(x,y)
X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
# Plotting the Graph
plt.plot(X_, Y_, color='blue')
ax.fill_between(X_, Y_, Y1_, alpha=0.3, color='blue')
plt.plot(X_, Y1_, color='blue', alpha=0.3)
#ax.fill_between(X_, Y_, Y1_, alpha=0.4, color='green')
a, b = np.polyfit(x, y, 1)
print(a,b)
plt.plot(x, a*x+b, color='blue', linestyle='--')
a, b = np.polyfit(x, y1, 1)
print(a,b)
plt.plot(x, a*x+b, color='blue', alpha=0.3, linestyle='--')
plt.legend(['Reported PM2.5', 'Volatilized Nitrate','Ambient Burden'])
#plt.legend(['Reported PM2.5', 'Estimated Nitrate Volatilization'], loc='lower right')
#plt.tick_params(axis='both', which='both', length=0)
plt.xticks(range(2001,2023,2))
plt.yticks(range(0,35,5))
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.title("Los Angeles County")
plt.xlabel("Year")
plt.ylabel("PM2.5 Concentration ${\mu}g m^{-3}$")
plt.show()
fig, ax= plt.subplots()
fig.text(0.5, 0.04, 'Year', ha='center')
#plot Volatlized NO3/PM2.5
vno3pm = site.dropna().pivot_table(index='Year', values=['NO3_v','Total PM2.5'])
vno3pm = vno3pm.reset_index()
vno3pm['NO3_v/PM2.5'] = vno3pm['NO3_v']/vno3pm['Total PM2.5']
x = vno3pm['Year'].values
y = vno3pm['NO3_v/PM2.5'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y_Spline = make_interp_spline(x,y)
Y_ = X_Y1_Spline(X_)
plt.plot(X_, Y1_, color='indigo')
plt.xticks(range(2001,2023,2))
plt.yticks(range(0,35,5))
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.ylabel('%')
plt.title("Percentage NO3 Volatilized from PM2.5 in Kern County")
fig, ax = plt.subplots(2,2)
fig.suptitle('Kern County')
fig.tight_layout(pad=1.5)
fig.text(0.5, 0, 'Year', ha='center')
fig.text(0, 0.25, 'Percentage Mass Volatilized (%)', ha='center', rotation='vertical')
no3vseason = pd.pivot_table(site, index=['Year', 'Season'],values=['NO3_v/PM2.5'])
no3vseason = no3vseason.reset_index()
winter = no3vseason[no3vseason['Season']=='Winter']
spring = no3vseason[no3vseason['Season']=='Spring']
summer = no3vseason[no3vseason['Season']=='Summer']
fall = no3vseason[no3vseason['Season']=='Fall']
x = winter['Year'].values
y1 = winter['NO3_v/PM2.5'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[0,0].plot(x, a*x+b, color='purple', linestyle='--', alpha=0.5)
ax[0,0].plot(X_, Y1_, color='purple')
ax[0, 0].set_title("Winter")
ax[0,0].spines['right'].set_visible(False)
ax[0,0].spines['top'].set_visible(False)
x = spring['Year'].values
y1 = spring['NO3_v/PM2.5'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[0,1].plot(x, a*x+b, color='olive', linestyle='--', alpha=0.5)
ax[0,1].plot(X_, Y1_, color='olive')
ax[0,1].spines['right'].set_visible(False)
ax[0,1].spines['top'].set_visible(False)
ax[0,1].set_title("Spring")
x = summer['Year'].values
y1 = summer['NO3_v/PM2.5'].values
X_ = np.linspace(x.min(), x.max(), 500)
#pch = pchip(x, y1)
#xx=np.linspace(x[0], x[-1], 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[1,0].plot(x, a*x+b, color='pink', linestyle='--', alpha=0.5)
ax[1,0].plot(X_, Y1_, color='pink')
#ax[1,0].plot(xx, pch(xx), color='pink')
ax[1, 0].set_title("Summer")
ax[1,0].spines['right'].set_visible(False)
ax[1,0].spines['top'].set_visible(False)
ax[1,0].set_ylim(ymin=0)
x = fall['Year'].values
y1 = fall['NO3_v/PM2.5'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[1,1].plot(x, a*x+b, color='orange', linestyle='--', alpha=0.5)
ax[1,1].plot(X_, Y1_, color='orange')
ax[1,1].set_title("Fall")
ax[1,1].spines['right'].set_visible(False)
ax[1,1].spines['top'].set_visible(False)
plt.setp(ax, yticks=[0,10,20,30, 40], xticks=[2000,2005,2010,2015,2020])
fig, ax = plt.subplots(2,2)
fig.suptitle('Kern County')
fig.tight_layout(pad=1.5)
fig.text(0.5, 0, 'Year', ha='center')
fig.text(0, 0.25, 'PM2.5 Concentration ${\mu}g m^{-3}$', ha='center', rotation='vertical')
pmseason = site.dropna().pivot_table(index=['Year', 'Season'],values=['PM2.5', 'Total PM2.5'])
pmseason = pmseason.reset_index()
winter = pmseason[pmseason['Season']=='Winter']
spring = pmseason[pmseason['Season']=='Spring']
summer = pmseason[pmseason['Season']=='Summer']
fall = pmseason[pmseason['Season']=='Fall']
x = winter['Year'].values
y = winter['PM2.5'].values
y1 = winter['Total PM2.5']
X_Y_Spline = make_interp_spline(x,y)
X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y, 1)
ax[0,0].plot(x, a*x+b, color='purple', linestyle='--', alpha=0.5)
ax[0,0].plot(X_, Y_, color='purple')
a, b = np.polyfit(x, y1, 1)
ax[0,0].plot(x, a*x+b, color='indigo', linestyle='--', alpha=0.5)
ax[0,0].fill_between(X_, Y_, Y1_, alpha=0.3, color='indigo')
ax[0, 0].set_title("Winter")
ax[0,0].spines['right'].set_visible(False)
ax[0,0].spines['top'].set_visible(False)
x = spring['Year'].values
y = spring['PM2.5'].values
y1 = spring['Total PM2.5']
X_Y_Spline = make_interp_spline(x,y)
X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y, 1)
ax[0,1].plot(x, a*x+b, color='green', linestyle='--', alpha=0.5)
ax[0,1].plot(X_, Y_, color='green')
a, b = np.polyfit(x, y1, 1)
ax[0,1].plot(x, a*x+b, color='olive', linestyle='--', alpha=0.5)
ax[0,1].fill_between(X_, Y_, Y1_, alpha=0.3, color='olive')
ax[0,1].set_title("Spring")
ax[0,1].spines['right'].set_visible(False)
ax[0,1].spines['top'].set_visible(False)
x = summer['Year'].values
y = summer['PM2.5'].values
y1 = summer['Total PM2.5']
X_Y_Spline = make_interp_spline(x,y)
X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y, 1)
ax[1,0].plot(x, a*x+b, color='red', linestyle='--', alpha=0.5)
ax[1,0].plot(X_, Y_, color='red')
a, b = np.polyfit(x, y1, 1)
ax[1,0].plot(x, a*x+b, color='pink', linestyle='--', alpha=0.5)
ax[1,0].fill_between(X_, Y_, Y1_, alpha=0.3, color='pink')
ax[1, 0].set_title("Summer")
ax[1,0].spines['right'].set_visible(False)
ax[1,0].spines['top'].set_visible(False)
x = fall['Year'].values
y = fall['PM2.5'].values
y1 = fall['Total PM2.5']
X_Y_Spline = make_interp_spline(x,y)
X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y, 1)
ax[1,1].plot(x, a*x+b, color='brown', linestyle='--', alpha=0.5)
ax[1,1].plot(X_, Y_, color='brown')
a, b = np.polyfit(x, y1, 1)
ax[1,1].plot(x, a*x+b, color='orange', linestyle='--', alpha=0.5)
ax[1,1].fill_between(X_, Y_, Y1_, alpha=0.3, color='orange')
ax[1,1].set_title("Fall")
ax[1,1].spines['right'].set_visible(False)
ax[1,1].spines['top'].set_visible(False)
plt.setp(ax, yticks=[0,20,40,60], xticks=[2000,2005,2010,2015,2020])
#%NO3V/NO3
fig, ax = plt.subplots(2,2)
fig.suptitle('Percentage NO3 Volatilized from NO3 in Kern County')
fig.tight_layout(pad=1.5)
fig.text(0.5, 0, 'Year', ha='center')
no3vseasonp = pd.pivot_table(site, index=['Year', 'Season'],values=['NO3_v/NO3'])
no3vseasonp = no3vseasonp.reset_index()
winter = no3vseasonp[no3vseasonp['Season']=='Winter']
spring = no3vseasonp[no3vseasonp['Season']=='Spring']
summer = no3vseasonp[no3vseasonp['Season']=='Summer']
fall = no3vseasonp[no3vseasonp['Season']=='Fall']
x = winter['Year'].values
y1 = winter['NO3_v/NO3'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[0,0].plot(x, a*x+b, color='purple', linestyle='--', alpha=0.5)
ax[0,0].plot(X_, Y1_, color='purple')
ax[0, 0].set_title("Winter")
ax[0,0].spines['right'].set_visible(False)
ax[0,0].spines['top'].set_visible(False)
x = spring['Year'].values
y1 = spring['NO3_v/NO3'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[0,1].plot(x, a*x+b, color='olive', linestyle='--', alpha=0.5)
ax[0,1].plot(X_, Y1_, color='olive')
ax[0,1].spines['right'].set_visible(False)
ax[0,1].spines['top'].set_visible(False)
ax[0,1].set_title("Spring")
x = summer['Year'].values
y1 = summer['NO3_v/NO3'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[1,0].plot(x, a*x+b, color='pink', linestyle='--', alpha=0.5)
ax[1,0].plot(X_, Y1_, color='pink')
ax[1, 0].set_title("Summer")
ax[1,0].spines['right'].set_visible(False)
ax[1,0].spines['top'].set_visible(False)
x = fall['Year'].values
y1 = fall['NO3_v/NO3'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[1,1].plot(x, a*x+b, color='orange', linestyle='--', alpha=0.5)
ax[1,1].plot(X_, Y1_, color='orange')
ax[1, 1].set_title("Fall")
ax[1,1].spines['right'].set_visible(False)
ax[1,1].spines['top'].set_visible(False)
plt.setp(ax, yticks=[0,25,50,75,100], xticks=[2000,2005,2010,2015,2020])
fig, ax = plt.subplots(2,2)
fig.suptitle('Kern County')
fig.tight_layout(pad=1.5)
fig.text(0.5, 0, 'Year', ha='center')
fig.text(0, 0.25, 'Nitrate Concentration ${\mu}g m^{-3}$', ha='center', rotation='vertical')
nitrate['Season'] = nitrate['Month']%12 // 3 + 1
nitrate['Season'] = nitrate['Season'].replace({1:'Winter', 2:'Spring', 3:'Summer', 4:'Fall'})
no3season = pd.pivot_table(nitrate, index=['Year', 'Season'],values=['Total Nitrate PM2.5 LC'])
no3season = no3season.reset_index()
winter = no3season[no3season['Season']=='Winter']
spring = no3season[no3season['Season']=='Spring']
summer = no3season[no3season['Season']=='Summer']
fall = no3season[no3season['Season']=='Fall']
x = winter['Year'].values
y = winter['Total Nitrate PM2.5 LC'].values
X_Y_Spline = make_interp_spline(x,y)
X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)
a, b = np.polyfit(x, y, 1)
ax[0,0].plot(x, a*x+b, color='purple', linestyle='--', alpha=0.5)
ax[0,0].plot(X_, Y_, color='purple')
ax[0, 0].set_title("Winter")
ax[0,0].spines['right'].set_visible(False)
ax[0,0].spines['top'].set_visible(False)
x = spring['Year'].values
y = spring['Total Nitrate PM2.5 LC'].values
X_Y_Spline = make_interp_spline(x,y)
X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)
a, b = np.polyfit(x, y, 1)
ax[0,1].plot(x, a*x+b, color='green', linestyle='--', alpha=0.5)
ax[0,1].plot(X_, Y_, color='green')
ax[0,1].set_title("Spring")
ax[0,1].spines['right'].set_visible(False)
ax[0,1].spines['top'].set_visible(False)
x = summer['Year'].values
y = summer['Total Nitrate PM2.5 LC'].values
X_Y_Spline = make_interp_spline(x,y)
X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)
a, b = np.polyfit(x, y, 1)
ax[1,0].plot(x, a*x+b, color='red', linestyle='--', alpha=0.5)
ax[1,0].plot(X_, Y_, color='red')
ax[1, 0].set_title("Summer")
ax[1,0].spines['right'].set_visible(False)
ax[1,0].spines['top'].set_visible(False)
x = fall['Year'].values
y = fall['Total Nitrate PM2.5 LC'].values
X_Y_Spline = make_interp_spline(x,y)
X_ = np.linspace(x.min(), x.max(), 500)
Y_ = X_Y_Spline(X_)
a, b = np.polyfit(x, y, 1)
ax[1,1].plot(x, a*x+b, color='brown', linestyle='--', alpha=0.5)
ax[1,1].plot(X_, Y_, color='brown')
ax[1,1].set_title("Fall")
ax[1,1].spines['right'].set_visible(False)
ax[1,1].spines['top'].set_visible(False)
plt.setp(ax, yticks=[0,5,10], xticks=[2000,2005,2010,2015,2020])
#temperature
fig, ax = plt.subplots(2,2)
fig.suptitle('Kern County')
fig.tight_layout(pad=1.5)
fig.text(0.5, 0, 'Year', ha='center')
fig.text(0, 0.4, 'Temperature (หC)', ha='center', rotation=90)
temp = site.pivot_table(index=['Year', 'Season'], values='sfc_temp')
temp = temp.reset_index()
winter = temp[temp['Season']=='Winter']
spring = temp[temp['Season']=='Spring']
summer = temp[temp['Season']=='Summer']
fall = temp[temp['Season']=='Fall']
x = winter['Year'].values
y1 = winter['sfc_temp'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[0,0].plot(x, a*x+b, color='purple', linestyle='--', alpha=0.5)
ax[0,0].plot(X_, Y1_, color='purple')
ax[0, 0].set_title("Winter")
ax[0,0].spines['right'].set_visible(False)
ax[0,0].spines['top'].set_visible(False)
x = spring['Year'].values
y1 = spring['sfc_temp'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[0,1].plot(x, a*x+b, color='olive', linestyle='--', alpha=0.5)
ax[0,1].plot(X_, Y1_, color='olive')
ax[0,1].spines['right'].set_visible(False)
ax[0,1].spines['top'].set_visible(False)
ax[0,1].set_title("Spring")
x = summer['Year'].values
y1 = summer['sfc_temp'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[1,0].plot(x, a*x+b, color='pink', linestyle='--', alpha=0.5)
ax[1,0].plot(X_, Y1_, color='pink')
ax[1, 0].set_title("Summer")
ax[1,0].spines['right'].set_visible(False)
ax[1,0].spines['top'].set_visible(False)
x = fall['Year'].values
y1 = fall['sfc_temp'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[1,1].plot(x, a*x+b, color='orange', linestyle='--', alpha=0.5)
ax[1,1].plot(X_, Y1_, color='orange')
ax[1, 1].set_title("Fall")
ax[1,1].spines['right'].set_visible(False)
ax[1,1].spines['top'].set_visible(False)
plt.setp(ax, yticks=[0,10,20,30], xticks=[2000,2005,2010,2015,2020])
#nitrate as percent pm2.5
fig, ax = plt.subplots(2,2)
fig.suptitle('Nitrate as % PM2.5 Kern County')
fig.tight_layout(pad=1.5)
fig.text(0.5, 0, 'Year', ha='center')
site['npm25'] = site['Total Nitrate PM2.5 LC']*100/site['PM2.5']
npm25 = site.pivot_table(index=['Year', 'Season'], values='npm25')
npm25 = npm25.reset_index()
winter = npm25[npm25['Season']=='Winter']
spring = npm25[npm25['Season']=='Spring']
summer = npm25[npm25['Season']=='Summer']
fall = npm25[npm25['Season']=='Fall']
x = winter['Year'].values
y1 = winter['npm25'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[0,0].plot(x, a*x+b, color='purple', linestyle='--', alpha=0.5)
ax[0,0].plot(X_, Y1_, color='purple')
ax[0, 0].set_title("Winter")
ax[0,0].spines['right'].set_visible(False)
ax[0,0].spines['top'].set_visible(False)
x = spring['Year'].values
y1 = spring['npm25'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[0,1].plot(x, a*x+b, color='olive', linestyle='--', alpha=0.5)
ax[0,1].plot(X_, Y1_, color='olive')
ax[0,1].spines['right'].set_visible(False)
ax[0,1].spines['top'].set_visible(False)
ax[0,1].set_title("Spring")
x = summer['Year'].values
y1 = summer['npm25'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[1,0].plot(x, a*x+b, color='pink', linestyle='--', alpha=0.5)
ax[1,0].plot(X_, Y1_, color='pink')
ax[1, 0].set_title("Summer")
ax[1,0].spines['right'].set_visible(False)
ax[1,0].spines['top'].set_visible(False)
x = fall['Year'].values
y1 = fall['npm25'].values
X_ = np.linspace(x.min(), x.max(), 500)
X_Y1_Spline = make_interp_spline(x,y1)
Y1_ = X_Y1_Spline(X_)
a, b = np.polyfit(x, y1, 1)
ax[1,1].plot(x, a*x+b, color='orange', linestyle='--', alpha=0.5)
ax[1,1].plot(X_, Y1_, color='orange')
ax[1, 1].set_title("Fall")
ax[1,1].spines['right'].set_visible(False)
ax[1,1].spines['top'].set_visible(False)
plt.setp(ax, yticks=[0,25,50,75,100], xticks=[2000,2005,2010,2015,2020])
|
Option Explicit
Function GetCPMX(Address As String) As String
'-----------------------------------------------------------------------------------------------------
'This function returns the postal code of a given address using the Google Geocoding API.
'The function uses the "simplest" form of Google Geocoding API (sending only the address parameter, filtering for MX country results only),
'so, optional parameters such as bounds, language, region and components are not expected as inputs.
'In case of multiple results (for example two cities sharing the same name), the function
'returns the FIRST OCCURRENCE, so be careful in the input address (tip: use the city name and the
'postal code if they are available).
'NOTE: As Google points out, the use of the Google Geocoding API is subject to a limit of 2500
'requests per day, so be careful not to exceed this limit. For more info check:
'https://developers.google.com/maps/documentation/geocoding/usage-limits
'In order to use this function you must enable the XML, v3.0 library from VBA editor:
'Go to Tools -> References -> check the Microsoft XML, v3.0.
'2018 Update: In order to use this function you will now need a valid API key.
'Check the next link that guides you on how to acquire a free API key:
'https://www.myengineeringworld.net/2018/02/how-to-get-free-google-api-key.html
'This is a modfied version of an original function
'Written By: Christos Samaras
'Date: 12/06/2014
'Last Updated: 07/03/2018
'E-mail: [email protected]
'Site: https://www.myengineeringworld.net
'Modified By: Josรฉ Elรญ Santiago Rodrรญguez
'Date: 17/12/2019
'Last Updated: 17/12/2019
'E-mail: [email protected]
'Site: https://www.facebook.com/elisantiago
'-----------------------------------------------------------------------------------------------------
'Declaring the necessary variables. Using 30 at the first two variables because it
'corresponds to the "Microsoft XML, v3.0" library in VBA (msxml3.dll).
Dim ApiKey As String
Dim Request As New XMLHTTP30
Dim Results As New DOMDocument30
Dim StatusNode As IXMLDOMNode
'Set your API key in this variable. Check this link for more info:
'https://www.myengineeringworld.net/2018/02/how-to-get-free-google-api-key.html
ApiKey = "<YOUR_KEY_GOES_HERE>"
'Check that an API key has been provided.
If ApiKey = vbNullString Or ApiKey = "Your API Key goes here!" Then
GetCPMX = "Invalid API Key"
Exit Function
End If
'Generic error handling.
On Error GoTo errorHandler
'Create the request based on Google Geocoding API. Parameters (from Google page):
'- Address: The address that you want to geocode.
'- Components: Indicates when you are using a component of the response to filter
'- Sensor: Indicates whether your application used a sensor to determine the user's location.
'This parameter is no longer required.
Request.Open "GET", "https://maps.googleapis.com/maps/api/geocode/xml?" _
& "&address=" & Address & "&components=country:MX&sensor=false&key=" & ApiKey, False
'Send the request to the Google server.
Request.send
'Read the results from the request.
Results.LoadXML Request.responseText
'Get the status node value.
Set StatusNode = Results.SelectSingleNode("//status")
'Based on the status node result, proceed accordingly.
Select Case UCase(StatusNode.Text)
Case "OK" 'The API request was successful. At least one geocode was returned.
Dim n As IXMLDOMNode
Dim CPMEX As String
'get all the address components, check their types and save the text for the postal_code one
For Each n In Results.SelectNodes("//result/address_component")
If n.SelectSingleNode("type").Text = "postal_code" Then
CPMEX = n.SelectSingleNode("long_name").Text
Else
CPMEX = "Sin CP"
End If
Next
'Return the postal code as string (postal code).
GetCPMX = CPMEX
Case "ZERO_RESULTS" 'The geocode was successful but returned no results.
GetCPMX = "The address probably not exists"
Case "OVER_QUERY_LIMIT" 'The requestor has exceeded the limit of 2500 request/day.
GetCPMX = "Requestor has exceeded the server limit"
Case "REQUEST_DENIED" 'The API did not complete the request.
GetCPMX = "Server denied the request"
Case "INVALID_REQUEST" 'The API request is empty or is malformed.
GetCPMX = "Request was empty or malformed"
Case "UNKNOWN_ERROR" 'Indicates that the request could not be processed due to a server error.
GetCPMX = "Unknown error"
Case Else 'Just in case...
GetCPMX = "Error"
End Select
'In case of error, release the objects.
errorHandler:
Set StatusNode = Nothing
Set Results = Nothing
Set Request = Nothing
End Function
|
# -*- coding: utf-8 -*-
from mxnet import nd,autograd
from mxnet.gluon import data as gdata
from mxnet.gluon import nn
from mxnet import init
from mxnet.gluon import loss as gloss
from mxnet import gluon
# create dataset
num_inputs = 2
num_examples = 1000
true_w = [2, -3.4]
true_b = 4.2
features = nd.random.normal(scale=1, shape=(num_examples, num_inputs))
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += nd.random.normal(scale=0.01, shape=labels.shape)
# data reader
batch_size = 10
dataset = gdata.ArrayDataset(features, labels)
data_iter = gdata.DataLoader(dataset, batch_size, shuffle=True)
# create model
net = nn.Sequential()
net.add(nn.Dense(1))
net.initialize(init.Normal(sigma=0.01))
# loss
loss = gloss.L2Loss()
# trainer
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.03})
# train
num_epochs = 3
for epoch in range(1, num_epochs + 1):
for X, y in data_iter:
with autograd.record():
l = loss(net(X), y)
l.backward()
trainer.step(batch_size)
print("epoch %d, loss: %f"
% (epoch, loss(net(features), labels).mean().asnumpy()))
dense = net[0]
print('real w',true_w,
'\npred w:\n',dense.weight.data()
)
print('real b:',true_b,
'\npred b:',dense.bias.data()
)
|
import { createAsyncThunk, createSlice, current, Dispatch } from "@reduxjs/toolkit";
import axios from "../../service/axios"
export const fetchFriends = createAsyncThunk(
"friends/fetchFriends",
async () => {
const response = await axios.get("/friendship/friends");
return response.data;
}
)
export const newFriendRequest = createAsyncThunk(
"friends/newFriendRequest",
async (id: number) => {
const response = await axios.post("/friendship/request", {id: id})
return response.data;
}
)
export const acceptFriendRequest = createAsyncThunk(
"friends/acceptFriendRequest",
async (id: number) => {
const response = await axios.put("/friendship/response", {applicant: id, didAccept: true});
return response.data;
}
)
export const removeFriendRequest = createAsyncThunk(
"friends/removeFriendRequest",
async (id: number) => {
const response = await axios.put("/friendship/response", {applicant: id, didAccept: false});
return response.data;
}
)
type friend = {
id: number,
name: string,
picture: string,
status: number
}
const test: friend[] = []
const friendsSlice = createSlice({
name: "friends",
initialState: test,
reducers: {
changeFriendStatus: (state, action) => {
const last = state.filter((e: any) => e.id == action.payload.user_id);
if (last.length) {
if (action.payload.game && action.payload.status) {
last[0].status = 2
} else if (!action.payload.game) {
last[0].status = !action.payload.status ? 1 : 0;
} else {
last[0].status = 0;
}
}
},
},
extraReducers: builder => {
builder.addCase(fetchFriends.fulfilled, (state, {payload}) => {
return payload
})
}
})
export const changeFriendStatus = (type: any) => (dispatch: any) => {
dispatch(friendsSlice.actions.changeFriendStatus(type));
}
export const friendsMethods = {
fetchFriends,
newFriendRequest,
acceptFriendRequest,
removeFriendRequest,
changeFriendStatus
}
export default friendsSlice
|
import SwiftUI
import UniformTypeIdentifiers
@available(macOS 12.0, *)
struct TabFindRotateAndMore: View {
@ObservedObject var doc: GrandArtDocument
@Binding var requiresFullCalc: Bool
var body: some View {
HStack {
Text("Maximum tries:")
DelayedTextFieldDouble(
placeholder: "10,000",
value: $doc.picdef.iterationsMax,
formatter: MAFormatters.fmtSharpeningItMax
)
.textFieldStyle(.roundedBorder)
.multilineTextAlignment(.trailing)
.help(
"Enter the maximum number of tries for a given point in the image. A larger value will increase the resolution, but slow down the calculation and make the coloring more difficult."
)
.frame(maxWidth: 70)
.onChange(of: doc.picdef.iterationsMax) { _ in
requiresFullCalc = true
}
} // end hstack sharpening
.padding(.horizontal)
HStack {
Text("Rotation")
.help("Enter degress to rotate counter-clockwise.")
DelayedTextFieldDouble(
placeholder: "0",
value: $doc.picdef.theta,
formatter: MAFormatters.fmtRotationTheta
)
.textFieldStyle(.roundedBorder)
.multilineTextAlignment(.trailing)
.frame(maxWidth: 60)
.help("Enter the angle to rotate the image counter-clockwise, in degrees.")
.onChange(of: doc.picdef.theta) { _ in
requiresFullCalc = true
}
} // end hstack theta
HStack {
Text("Color smoothing limit:")
DelayedTextFieldDouble(
placeholder: "400",
value: $doc.picdef.rSqLimit,
formatter: MAFormatters.fmtSmootingRSqLimit
)
.textFieldStyle(.roundedBorder)
.multilineTextAlignment(.trailing)
.frame(maxWidth: 60)
.help(
"Enter the minimum value for the square of the distance from origin before the number of tries is ended. A larger value will smooth the color gradient, but slow down the calculation. Must be greater than 4. Rarely needs changing."
)
.onChange(of: doc.picdef.rSqLimit) { _ in
requiresFullCalc = true
}
} // end hstack smoothing
}
}
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {HomepageComponent} from "./homepage/homepage.component";
import {LoginComponent} from "./login/login.component";
import {RegisterComponent} from "./register/register.component";
export const routes: Routes = [
{path: '', component: LoginComponent}, // page default
{path: 'homepage', component: HomepageComponent},
{path: 'register', component: RegisterComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
package thread;
/**
* The TheadLocal construct allows us to store data that will be accessible only by a specific thread.
*
* Let's say that we want to have an Integer value that will be bundled with the specific thread:
*
* ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>();
* Next, when we want to use this value from a thread, we only need to call a get() or set() method. Simply put, we can imagine that ThreadLocal stores data inside of a map with the thread as the key.
*/
public class ThreadLocalPractice {
private static ThreadLocal<String> firstName = new ThreadLocal<>();
public static String getFirstName() {
return firstName.get();
}
public static void setFirstName(String name) {
firstName.set(name);
}
public static void main(String[] args) {
}
}
|
import 'dart:async';
import 'package:control_panel/data_structures/fridge.dart';
import 'package:control_panel/data_structures/hubs.dart';
import 'package:control_panel/libraries/get_updates.dart';
import 'package:flutter/material.dart';
bool _finishedLoading = false;
class OverviewViewModel with ChangeNotifier {
DateTime _lastPing = DateTime.fromMicrosecondsSinceEpoch(0);
bool _hasPinged = false;
int _amountUp = 0;
int _amountDown = 0;
bool? _disposed;
int _radarAngle = 0;
Map<int, List<String>> _radarPoints = {};
bool get finishedLoading => _finishedLoading;
bool get hasPinged => _hasPinged;
DateTime get lastPinged => _lastPing;
int get amountUp => _amountUp;
int get amountDown => _amountDown;
/// The current angle of the sweeper in degrees
int get radarAngle => _radarAngle;
set radarAngle(int radarAngle) {
_radarAngle = radarAngle;
notifyListeners();
}
/// A map of points that should be displayed. The key is the degree where they lie and
/// the value is a list of hub IDs that will be displayed on hover.
Map<int, List<String>> get radarPoints => _radarPoints;
set points(Map<int, List<String>> points) {
_radarPoints = points;
notifyListeners();
}
set finishedLoading(bool finishedLoading) {
_finishedLoading = finishedLoading;
if (_disposed != true) {
notifyListeners();
}
}
set hasPinged(bool hasPinged) {
if (hasPinged != _hasPinged) {
_hasPinged = hasPinged;
if (_disposed != true) {
notifyListeners();
}
}
}
set lastPinged(DateTime lastPing) {
_lastPing = lastPing;
var curTime = DateTime.now();
bool oldHasPinged = hasPinged;
if (curTime.difference(_lastPing) < const Duration(seconds: 5)) {
hasPinged = true;
} else {
hasPinged = false;
}
if (_disposed != true && oldHasPinged != hasPinged) {
notifyListeners();
}
}
set amountUp(int amountUp) {
int oldAmountUp = _amountUp;
_amountUp = amountUp;
if (amountUp != 0) {
hasPinged = true;
}
if (amountUp == 0) {
hasPinged = false;
}
if (_disposed != true && oldAmountUp != _amountUp) {
notifyListeners();
}
}
set amountDown(int amountDown) {
_amountDown = amountDown;
if (_disposed != true) {
notifyListeners();
}
}
Timer? _timer;
List<Hub> _hubs = [];
set hubs(List<Hub> h) {
if (_disposed != true) {
_hubs = h;
var curTime = DateTime.now();
int localAmountUp = 0;
int localAmountDown = 0;
for (Hub h in _hubs) {
if (curTime.difference(h.lastSeen) < const Duration(seconds: 5)) {
localAmountUp++;
} else {
localAmountDown++;
}
}
amountDown = localAmountDown;
amountUp = localAmountUp;
}
}
List<Fridge> _fridges = [];
List<Fridge> get fridges => _fridges;
set fridges(List<Fridge> f) {
_fridges = f;
notifyListeners();
}
bool error = false;
OverviewViewModel() {
_finishedLoading = false;
_disposed = false;
// Since the hub pings every 2 seconds, we need to sweep 360* every 2 seconds,
// and our angular velocity is 180*/second, or one degree every 6 milliseconds.
_timer = Timer.periodic(const Duration(milliseconds: 6), (t) {
// At 359, we roll over back to 0
if (radarAngle == 359) {
radarAngle = 0;
} else {
radarAngle++;
}
var curTime = DateTime.now();
int localAmountUp = 0;
int localAmountDown = 0;
DateTime tmpLastPing = DateTime.fromMicrosecondsSinceEpoch(0);
var points = radarPoints;
points.remove(radarAngle);
for (Hub h in _hubs) {
if (tmpLastPing.isBefore(h.lastSeen)) {
tmpLastPing = h.lastSeen;
// points.remove(radarAngle/.);
}
if (curTime.difference(h.lastSeen) < const Duration(seconds: 10)) {
localAmountUp++;
} else {
localAmountDown++;
}
}
lastPinged = tmpLastPing;
amountDown = localAmountDown;
amountUp = localAmountUp;
});
() async {
messagesSend.add(const UpdateMessage());
await for (Message m in messagesController.stream) {
finishedLoading = true;
if (_disposed != false) {
break;
}
if (m is HubMessage) {
hubs = m.h;
} else if (m is FridgeMessage) {
fridges = m.h;
}
}
}();
}
@override
void dispose() {
_disposed = true;
_timer?.cancel();
super.dispose();
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New year new target</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Work+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<!--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ google Fonts^^^^^^^^^^^^^^^^^^^^^^^^^^ -->
<link rel="shortcut icon" href="img/icons/favicon.png" type="image/x-icon">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header>
<div class="container">
<div class="banner_area">
<div class="banner_text">
<h1>All Thinks Are Possible If You believe</h1>
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words</p>
<button class="btn">Contact Us</button>
</div>
</div>
</div>
</header>
<!--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ header area^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -->
<main>
<div class="container">
<section id="about_section">
<div class="about_text">
<h2>About Me</h2>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock.</p>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Enim quo harum voluptatum.</p>
<ul class="social_media_area">
<li><a href="#"><i class="fa-brands fa-facebook-f"></i></a></li>
<li><a href="#"><i class="fa-brands fa-twitter"></i></a></li>
<li><a href="#"><i class="fa-brands fa-linkedin-in"></i></a></li>
<li><a href="#"><i class="fa-brands fa-instagram"></i></a></li>
</ul>
</div>
<div class="about_image">
<img src="img/hardy.png" alt="">
</div>
</section>
<!--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ About section^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -->
<section id="summary_section">
<div class="summary_image">
<img src="img/person.png" alt="Person image">
</div>
<div class="summary_text">
<h2>My failures of previous year</h2>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock.</p>
<ul>
<li><i class="fa-solid fa-check"></i>Contrary to popular belief, is not simply.</li>
<li><i class="fa-solid fa-check"></i>Contrary to popular belief.</li>
<li><i class="fa-solid fa-check"></i>Contrary to popular , is not simply.</li>
<li><i class="fa-solid fa-check"></i>Contrary to popular belief, is not simply.</li>
<li><i class="fa-solid fa-check"></i>Contrary to popular simply.</li>
</ul>
</div>
</section>
<!--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Summary Section^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -->
<section id="plan_section">
<h2>My Plans</h2>
<div class="plan_container">
<div class="child_plan">
<img src="img/icons/web.png" alt="WEB CODE IMAGE">
<h4>Web Development</h4>
<span>I want to start again</span>
</div>
<div class="child_plan">
<img src="img/icons/js.png" alt="Javascrip image">
<h4>Javascript</h4>
<span>I want to learn more</span>
</div>
<div class="child_plan">
<img src="img/icons/smoke.png" alt="No smoke image">
<h4>Smoking Habit</h4>
<span>Never Start in life</span>
</div>
<div class="child_plan">
<img src="img/icons/js.png" alt="Javascrip image">
<h4>ecommerce</h4>
<span>I want to develop</span>
</div>
</div>
</section>
<!--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Plan Section^^^^^^^^^^^^^^^^^^^^^^^^^^ -->
<section id="advice_area">
<div class="advice_text">
<h2>Always keep a positive mindset</h2>
<button class="btn">Call Now</button>
</div>
</section>
</div>
</main>
<!-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^Advice SEction^^^^^^^^^^^^^^^^^^^^^^^^^^^ -->
<footer>
<div class="container" id="footer_area">
<div class="footer_left">
<h3>Future</h3>
<p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words</p>
<span>Email : [email protected]</span>
<span>Phone : 01500 00 00 00</span>
<ul>
<li><a href="#"><img src="img/icons/fb.png" alt="Facebook LOGO"></a></li>
<li><a href="#"><img src="img/icons/twitter.png" alt="Twitter LOGO"></a></li>
<li><a href="#"><img src="img/icons/youtube.png" alt="Youtube LOGO"></a></li>
</ul>
</div>
<div class="footer_right">
<h5>Subscribe</h5>
<form action="#">
<input type="email" placeholder="Enter your email">
<input type="submit" value="Subscribe">
</form>
</div>
</div>
</footer>
<!--^^^^^^^^^^^^^^^^^^^^^^^^^^^ footer Section^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -->
<script src="https://kit.fontawesome.com/704f46da60.js" crossorigin="anonymous"></script>
</body>
</html>
|
package persistence;
import org.json.*;
import model.Item;
import model.Warehouse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
//allows the reading/ loading of database
public class JsonReader {
private String fileName = "database";
private JSONObject jsonObject;
public JsonReader() {
// pass
}
/*
* REQUIRES: JSON to have all the correct details
* MODIFIES: this
* EFFECTS: parses the JSON file and sends it to makeWarehouse
*/
public Warehouse readDatabase() throws IOException, JSONException {
String fileData = new String(Files.readAllBytes(Paths.get("./data/" + fileName + ".json")),
StandardCharsets.UTF_8);
jsonObject = new JSONObject(fileData);
Item.setFinalID(jsonObject.getInt("FinalID"));
JSONArray itemArray = jsonObject.getJSONArray("Items");
Warehouse warehouse = makeWarehouse(itemArray);
if (jsonObject.getBoolean("Status")) {
warehouse.flipStatus();
}
return warehouse;
}
/*
* REQUIRES: item array to be not null, correct storage of JSON file
* MODIFIES: this
* EFFECTS: makes a new warehouse from the file and returns it.
*/
private Warehouse makeWarehouse(JSONArray itemArray) throws IOException {
Warehouse warehouse = new Warehouse();
try {
for (Object temp : itemArray) {
JSONArray arrObj = (JSONArray) temp;
warehouse.addItem(new Item((int) arrObj.get(0), (String) arrObj.get(1), (int) arrObj.get(2)));
}
} catch (Exception e) {
throw new IOException();
}
return warehouse;
}
/*
* MODIFIES: this
* EFFECTS: sets the database name
*/
public void overrideFileName(String name) {
fileName = name;
}
}
|
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>๋ ์ด์์ ์ ํ1 grid</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
background-color: #fff3e0;
}
#wrap {
width: 1200px;
margin: 0 auto;
display: grid;
grid-template-areas:
"header header"
"nav nav"
"aside section"
"footer footer"
;
grid-template-columns: 400px 800px;
grid-template-rows: 100px 100px 780px 100px;
}
#header {
background-color: #ffe0b2;
grid-area: header;
}
#nav {
background-color: #ffcc80;
grid-area: nav;
}
#aside {
background-color: #ffb74d;
float: left;
grid-area: aside;
}
#section {
background-color: #ffa726;
float: left;
grid-area: section;
}
#footer {
background-color: #ff9800;
clear: both;
grid-area: footer;
}
/* ๋ฏธ๋์ด์ฟผ๋ฆฌ */
@media (max-width: 1300px) {
}
@media (max-width: 768px) {
}
@media (max-width: 480px) {
}
</style>
</head>
<body>
<div id="wrap">
<header id="header"></header>
<nav id="nav"></nav>
<aside id="aside"></aside>
<section id="section"></section>
<footer id="footer"></footer>
</div>
<div class="document">
<h2 class="t_tit2">grid</h2>
<p class="codepen" data-height="500" data-default-tab="css,result" data-slug-hash="ZExJKjN" data-user="kdb6" style="height: 300px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;">
<span>See the Pen <a href="https://codepen.io/kdb6/pen/ZExJKjN">
Untitled</a> by KDB6 (<a href="https://codepen.io/kdb6">@kdb6</a>)
on <a href="https://codepen.io">CodePen</a>.</span>
</p>
<script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>
</div>
<!--
layout 01_01 : float ๋ฐฉ์ ๋ ์ด์์
layout 01_02 : float ๋ฐฉ์ ๋ฐ์ํ ๋ ์ด์์
layout 01_03 : flex ๋ฐฉ์ ๋ ์ด์์
layout 01_04 : flex ๋ฐฉ์ ๋ฐ์ํ ๋ ์ด์์
layout 01_05 : grid ๋ฐฉ์ ๋ ์ด์์
-->
</body>
</html>
|
import React, { Component } from "react";
import {
AppBar,
IconButton,
Link,
Toolbar,
Typography,
Button,
TextField,
CircularProgress,
} from "@material-ui/core";
import GitHubIcon from "@material-ui/icons/GitHub";
const blue = "#80d8ff";
const TitleContents = (props) => {
const {
selectFeature,
setFeature,
feature,
selectK,
setK,
k,
loading,
hideInput,
windowWidth,
} = props.properties;
const isMobile = windowWidth < 980;
const isMobile2 = windowWidth < 650;
return (
<>
<Typography
variant="h6"
style={{
fontWeight: 500,
marginRight: "25px",
marginTop: isMobile ? "10px" : "0px",
marginBottom: isMobile ? "10px" : "0px",
}}
>
<Link underline="none" href="/">
SpatialTranscriptomics.js
</Link>
</Typography>
{!hideInput && (
<div style={{ display: "flex", marginTop: isMobile ? "-5px" : "2px" }}>
<div
style={{
display: isMobile ? "" : "flex",
marginRight: isMobile ? "20px" : "30px",
}}
>
<TextField
style={{ width: "90px", fontWeight: 500, marginRight: "10px" }}
color="secondary"
helperText="Gene name"
defaultValue="Nptxr"
onChange={selectFeature}
/>
<Button
variant="contained"
size="small"
color="primary"
style={{ marginTop: "15px", marginBottom: "15px" }}
onClick={() => setFeature(feature)}
>
Color by Gene
</Button>
</div>
<div style={{ display: "flex" }}>
<div style={{ display: isMobile ? "" : "flex" }}>
<TextField
style={{ width: "100px", marginRight: "10px" }}
color="secondary"
helperText="# of Clusters (k)"
defaultValue="10"
onChange={selectK}
/>
<Button
variant="contained"
size="small"
color="primary"
style={{ marginTop: "15px", marginBottom: "15px" }}
onClick={() => setK(k)}
>
Color by Clusters
</Button>
</div>
{!isMobile2 && (
<div style={{ marginLeft: "30px", marginTop: "10px" }}>
<CircularProgress
disableShrink
size={40}
thickness={5}
style={{ color: !loading ? "transparent" : blue }}
/>
</div>
)}
</div>
</div>
)}
<div style={{ flexGrow: 1 }}></div>
{!isMobile && (
<>
{aboutButton}
{gitButton}
</>
)}
</>
);
};
const Title = (props) => {
const contents = <TitleContents properties={props} />;
if (props.windowWidth < 980) {
return <div>{contents}</div>;
}
return <>{contents}</>;
};
const aboutButton = (
<Typography
style={{ fontSize: "1.1em", fontWeight: 500, marginRight: "5px" }}
>
<Link underline="none" href="/about">
about
</Link>
</Typography>
);
const gitButton = (
<IconButton
disableRipple
edge="end"
color="primary"
style={{ marginRight: "-10px", marginBottom: "-4px" }}
aria-label="menu"
>
<Link
href="https://github.com/JEFworks/SpatialTranscriptomics.js"
target="_blank"
rel="noopener"
color="inherit"
>
<GitHubIcon />
</Link>
</IconButton>
);
class Header extends Component {
state = {
feature: "nptxr",
k: 10,
};
componentDidMount = () => {
this.updateDimensions();
window.addEventListener("resize", this.updateDimensions.bind(this));
};
updateDimensions = () => {
this.setState({ resize: true });
};
selectFeature = (event) => {
this.setState({ feature: event.target.value.trim().toLowerCase() });
};
selectK = (event) => {
const value = Number.parseInt(event.target.value);
this.setState({ k: value });
};
render = () => {
const { loading, hideInput } = this.props;
const { feature, k } = this.state;
return (
<>
<AppBar
style={{
backgroundColor: "#fff",
boxShadow: "rgba(0, 0, 0, 0.1) 0px 0px 12px",
}}
>
<Toolbar>
<Title
selectFeature={this.selectFeature}
setFeature={this.props.setFeature}
feature={feature}
selectK={this.selectK}
setK={this.props.setK}
k={k}
loading={loading}
hideInput={hideInput}
windowWidth={window.innerWidth}
/>
</Toolbar>
</AppBar>
</>
);
};
}
export default Header;
|
---
title: ะะพะฑะฐะฒะธัั ะฐะฝะฝะพัะฐัะธั ัะพ ัััะตะปะบะพะน ะฒ ะดะพะบัะผะตะฝั
linktitle: ะะพะฑะฐะฒะธัั ะฐะฝะฝะพัะฐัะธั ัะพ ัััะตะปะบะพะน ะฒ ะดะพะบัะผะตะฝั
second_title: GroupDocs.ะะฝะฝะพัะฐัะธั .NET API
description: ะฃะทะฝะฐะนัะต, ะบะฐะบ ะดะพะฑะฐะฒะปััั ะฐะฝะฝะพัะฐัะธะธ ัะพ ัััะตะปะบะฐะผะธ ะฒ ะดะพะบัะผะตะฝัั ั ะฟะพะผะพััั GroupDocs.Annotation ะดะปั .NET. ะะพะฒััะฐะนัะต ัะตัะบะพััั ะธ ะธะฝัะตัะฐะบัะธะฒะฝะพััั ะดะพะบัะผะตะฝัะฐ ะฑะตะท ะพัะพะฑัั
ััะธะปะธะน.
type: docs
weight: 11
url: /ru/net/unlocking-annotation-power/add-arrow-annotation/
---
## ะะฒะตะดะตะฝะธะต
ะ ััะพะผ ััะบะพะฒะพะดััะฒะต ะผั ะฟะพะบะฐะถะตะผ ะฒะฐะผ ะฟัะพัะตัั ะดะพะฑะฐะฒะปะตะฝะธั ะฐะฝะฝะพัะฐัะธะน ัะพ ัััะตะปะบะฐะผะธ ะฒ ะฒะฐัะธ ะดะพะบัะผะตะฝัั ั ะฟะพะผะพััั GroupDocs.Annotation ะดะปั .NET. ะะฝะฝะพัะฐัะธะธ ัะพ ัััะตะปะบะฐะผะธ ะฟะพะปะตะทะฝั ะดะปั ัะบะฐะทะฐะฝะธั ะฝะฐะฟัะฐะฒะปะตะฝะธั ะธะปะธ ัะบะฐะทะฐะฝะธั ะพะฟัะตะดะตะปะตะฝะฝัั
ัะปะตะผะตะฝัะพะฒ ะฒ ะดะพะบัะผะตะฝัะต.
## ะัะตะดะฒะฐัะธัะตะปัะฝัะต ััะปะพะฒะธั
ะัะตะถะดะต ัะตะผ ะฝะฐัะฐัั, ัะฑะตะดะธัะตัั, ััะพ ั ะฒะฐั ะตััั ัะปะตะดัััะตะต:
1. GroupDocs.Annotation ะดะปั .NET: ัััะฐะฝะพะฒะธัะต ะฑะธะฑะปะธะพัะตะบั GroupDocs.Annotation ะดะปั .NET. ะั ะผะพะถะตัะต ัะบะฐัะฐัั ะตะณะพ ั[ะทะดะตัั](https://releases.groupdocs.com/annotation/net/).
2. ะกัะตะดะฐ ัะฐะทัะฐะฑะพัะบะธ: ัะฑะตะดะธัะตัั, ััะพ ั ะฒะฐั ะฝะฐัััะพะตะฝะฐ ััะตะดะฐ ัะฐะทัะฐะฑะพัะบะธ ะดะปั ัะฐะทัะฐะฑะพัะบะธ .NET, ะฒะบะปััะฐั Visual Studio ะธะปะธ ะปัะฑัั ะดััะณัั ะฟัะตะดะฟะพััะธัะตะปัะฝัั IDE.
## ะะผะฟะพััะธัะพะฒะฐัั ะฟัะพัััะฐะฝััะฒะฐ ะธะผะตะฝ
ะะพ-ะฟะตัะฒัั
, ะฒะฐะผ ะฝะตะพะฑั
ะพะดะธะผะพ ะธะผะฟะพััะธัะพะฒะฐัั ะฝะตะพะฑั
ะพะดะธะผัะต ะฟัะพัััะฐะฝััะฒะฐ ะธะผะตะฝ ะดะปั ะดะพัััะฟะฐ ะบ ะฝะตะพะฑั
ะพะดะธะผัะผ ะบะปะฐััะฐะผ ะธ ะผะตัะพะดะฐะผ ะดะปั ะฐะฝะฝะพัะฐัะธะน.
```csharp
using System;
using System.Collections.Generic;
using System.IO;
using GroupDocs.Annotation.Models;
using GroupDocs.Annotation.Models.AnnotationModels;
using GroupDocs.Annotation.Options;
```
## ะจะฐะณ 1. ะะฝะธัะธะฐะปะธะทะธััะนัะต ะฐะฝะฝะพัะฐัะพั
ะะฝะธัะธะฐะปะธะทะธััะนัะต ะฐะฝะฝะพัะฐัะพั, ัะบะฐะทะฐะฒ ะฟััั ะบ ัะฐะนะปั ะฒั
ะพะดะฝะพะณะพ ะดะพะบัะผะตะฝัะฐ.
```csharp
string outputPath = Path.Combine("Your Document Directory", "result" + Path.GetExtension("input.pdf"));
using (Annotator annotator = new Annotator("input.pdf"))
{
```
## ะจะฐะณ 2. ะกะพะทะดะฐะนัะต ะฐะฝะฝะพัะฐัะธั ัะพ ัััะตะปะบะพะน
ะกะพะทะดะฐะนัะต ัะบะทะตะผะฟะปัั ะบะปะฐััะฐ ArrowAnnotation ะธ ะพะฟัะตะดะตะปะธัะต ะตะณะพ ัะฒะพะนััะฒะฐ, ัะฐะบะธะต ะบะฐะบ ะฟะพะปะพะถะตะฝะธะต, ัะพะพะฑัะตะฝะธะต, ะฝะตะฟัะพะทัะฐัะฝะพััั, ัะฒะตั ะฟะตัะฐ, ััะธะปั, ัะธัะธะฝะฐ ะธ ั. ะด.
```csharp
ArrowAnnotation arrow = new ArrowAnnotation
{
Box = new Rectangle(100, 100, 100, 100),
CreatedOn = DateTime.Now,
Message = "This is arrow annotation",
Opacity = 0.7,
PageNumber = 0,
PenColor = 65535,
PenStyle = PenStyle.Dot,
PenWidth = 3,
Replies = new List<Reply>
{
new Reply
{
Comment = "First comment",
RepliedOn = DateTime.Now
},
new Reply
{
Comment = "Second comment",
RepliedOn = DateTime.Now
}
}
};
```
## ะจะฐะณย 3. ะะพะฑะฐะฒััะต ะฐะฝะฝะพัะฐัะธั
ะะพะฑะฐะฒััะต ะฐะฝะฝะพัะฐัะธั ัะพ ัััะตะปะบะพะน ะฒ ะดะพะบัะผะตะฝั, ะธัะฟะพะปัะทัั`Add` ะผะตัะพะด ะฐะฝะฝะพัะฐัะพัะฐ.
```csharp
annotator.Add(arrow);
```
## ะจะฐะณ 4: ะกะพั
ัะฐะฝะธัั ะดะพะบัะผะตะฝั
ะกะพั
ัะฐะฝะธัะต ะดะพะบัะผะตะฝั ั ะฐะฝะฝะพัะฐัะธัะผะธ ะฒ ัะบะฐะทะฐะฝะฝะพะผ ะฟััะธ ะฒัะฒะพะดะฐ.
```csharp
annotator.Save(outputPath);
}
```
## ะจะฐะณ 5: ะัะพะฑัะฐะถะตะฝะธะต ะฟะพะดัะฒะตัะถะดะตะฝะธั
ะัะพะฑัะฐะถะตะฝะธะต ะฟะพะดัะฒะตัะถะดะฐััะตะณะพ ัะพะพะฑัะตะฝะธั, ัะบะฐะทัะฒะฐััะตะณะพ ะฝะฐ ััะฟะตัะฝะพะต ัะพั
ัะฐะฝะตะฝะธะต ะดะพะบัะผะตะฝัะฐ.
```csharp
Console.WriteLine($"\nDocument saved successfully.\nCheck output in {outputPath}.");
```
ะขะตะฟะตัั ะฒั ััะฟะตัะฝะพ ะดะพะฑะฐะฒะธะปะธ ะฐะฝะฝะพัะฐัะธั ัะพ ัััะตะปะบะพะน ะฒ ัะฒะพะน ะดะพะบัะผะตะฝั ั ะฟะพะผะพััั GroupDocs.Annotation ะดะปั .NET.
## ะะฐะบะปััะตะฝะธะต
ะ ััะพะผ ััะบะพะฒะพะดััะฒะต ะผั ัะฐััะผะพััะตะปะธ ะฟัะพัะตัั ะดะพะฑะฐะฒะปะตะฝะธั ะฐะฝะฝะพัะฐัะธะน ัะพ ัััะตะปะบะฐะผะธ ะฒ ะดะพะบัะผะตะฝัั ั ะฟะพะผะพััั GroupDocs.Annotation ะดะปั .NET. ะกะปะตะดัั ััะธะผ ัะฐะณะฐะผ, ะฒั ัะผะพะถะตัะต ัะปัััะธัั ัะฒะพะธ ะดะพะบัะผะตะฝัั ั ะฟะพะผะพััั ัะตัะบะธั
ัะบะฐะทะฐัะตะปะตะน ะฝะฐะฟัะฐะฒะปะตะฝะธั, ัะดะตะปะฐะฒ ะธั
ะฑะพะปะตะต ะธะฝัะพัะผะฐัะธะฒะฝัะผะธ ะธ ะฟัะธะฒะปะตะบะฐัะตะปัะฝัะผะธ.
## ะงะฐััะพ ะทะฐะดะฐะฒะฐะตะผัะต ะฒะพะฟัะพัั
### ะะพะณั ะปะธ ั ะฝะฐัััะพะธัั ะฒะฝะตัะฝะธะน ะฒะธะด ะฐะฝะฝะพัะฐัะธะธ ัะพ ัััะตะปะบะพะน?
ะะฐ, ะฒั ะผะพะถะตัะต ะฝะฐัััะพะธัั ัะฐะทะปะธัะฝัะต ัะฒะพะนััะฒะฐ, ัะฐะบะธะต ะบะฐะบ ัะฒะตั, ััะธะปั, ัะธัะธะฝะฐ ะธ ะฝะตะฟัะพะทัะฐัะฝะพััั, ะฒ ัะพะพัะฒะตัััะฒะธะธ ัะพ ัะฒะพะธะผะธ ะฟัะตะดะฟะพััะตะฝะธัะผะธ ะธ ััะตะฑะพะฒะฐะฝะธัะผะธ ะดะพะบัะผะตะฝัะฐ.
### ะกะพะฒะผะตััะธะผ ะปะธ GroupDocs.Annotation ัะพ ะฒัะตะผะธ ัะพัะผะฐัะฐะผะธ ะดะพะบัะผะตะฝัะพะฒ?
GroupDocs.Annotation ะฟะพะดะดะตัะถะธะฒะฐะตั ัะธัะพะบะธะน ัะฟะตะบัั ัะพัะผะฐัะพะฒ ะดะพะบัะผะตะฝัะพะฒ, ะฒะบะปััะฐั PDF, DOCX, PPTX, XLSX ะธ ะดััะณะธะต.
### ะะพะณั ะปะธ ั ะดะพะฑะฐะฒะปััั ะฐะฝะฝะพัะฐัะธะธ ะฟัะพะณัะฐะผะผะฝะพ ั ะฟะพะผะพััั GroupDocs.Annotation?
ะะฐ, GroupDocs.Annotation ะฟัะตะดะพััะฐะฒะปัะตั API, ะบะพัะพััะต ะฟะพะทะฒะพะปััั ะฟัะพะณัะฐะผะผะฝะพ ะดะพะฑะฐะฒะปััั, ัะตะดะฐะบัะธัะพะฒะฐัั ะธ ัะดะฐะปััั ะฐะฝะฝะพัะฐัะธะธ ะธะท ะดะพะบัะผะตะฝัะพะฒ.
### ะัะตะดะปะฐะณะฐะตั ะปะธ GroupDocs.Annotation ะฑะตัะฟะปะฐัะฝัั ะฟัะพะฑะฝัั ะฒะตััะธั?
ะะฐ, ะฒั ะผะพะถะตัะต ะฟะพะฟัะพะฑะพะฒะฐัั GroupDocs.Annotation ะฑะตัะฟะปะฐัะฝะพ, ะทะฐะณััะทะธะฒ ะตะณะพ ั ัะฐะนัะฐ[ะทะดะตัั](https://releases.groupdocs.com/).
### ะะดะต ั ะผะพะณั ะฟะพะปััะธัั ัะตั
ะฝะธัะตัะบัั ะฟะพะดะดะตัะถะบั ะดะปั GroupDocs.Annotation?
ะะปั ะฟะพะปััะตะฝะธั ัะตั
ะฝะธัะตัะบะพะน ะฟะพะดะดะตัะถะบะธ ะธ ะฟะพะผะพัะธ ะฟะพัะตัะธัะต ัะพััะผ GroupDocs.Annotation.[ะทะดะตัั](https://forum.groupdocs.com/c/annotation/10).
|
<template>
<div class="navbar">
<img src="../../assets/images/logo.png" class="sidebar-logo-big">
<breadcrumb class="breadcrumb-container" />
<div class="right-menu">
<el-dropdown class="avatar-container" trigger="click">
<div class="avatar-wrapper">
<el-image
class="icon user-avatar"
:src="user.avatar"
fit="cover">
<div slot="error" class="image-slot">
<svg-icon icon-class="defalut-header-img"></svg-icon>
</div>
</el-image>
<span class="nickname">{{ user.nickname }}</span>
<i class="el-icon-arrow-down" />
</div>
<el-dropdown-menu slot="dropdown" class="user-dropdown">
<router-link to="/">
<el-dropdown-item>
้ฆ้กต
</el-dropdown-item>
</router-link>
<router-link to="/user">
<el-dropdown-item>
ไธชไบบไธญๅฟ
</el-dropdown-item>
</router-link>
<el-dropdown-item divided>
<span style="display:block;" @click="logout">้ๅบ</span>
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</div>
</div>
</template>
<script>
import { mapGetters, mapState } from "vuex";
import Breadcrumb from "@/components/Breadcrumb";
export default {
components: {
Breadcrumb,
},
computed: {
...mapGetters(["sidebar"]),
...mapState({
user: state => state.user.loginData
})
},
methods: {
toggleSideBar() {
this.$store.dispatch("app/toggleSideBar");
},
async logout() {
await this.$store.dispatch("user/logout");
this.$router.push(`/login?redirect=${this.$route.fullPath}`);
location.reload()
},
},
};
</script>
<style lang="scss" scoped>
.navbar {
height: 72px;
overflow: hidden;
position: relative;
background: #fff;
box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
.breadcrumb-container {
float: left;
}
.right-menu {
float: right;
height: 100%;
&:focus {
outline: none;
}
.right-menu-item {
display: inline-block;
padding: 0 8px;
height: 100%;
font-size: 18px;
color: #5a5e66;
vertical-align: text-bottom;
&.hover-effect {
cursor: pointer;
transition: background 0.3s;
&:hover {
background: rgba(0, 0, 0, 0.025);
}
}
}
.avatar-container {
margin-right: 30px;
.avatar-wrapper {
margin-top: 12px;
.user-avatar {
cursor: pointer;
width: 48px;
height: 48px;
border-radius: 50%;
vertical-align: middle;
.image-slot .svg-icon{
width: 48px;
height: 48px;
}
}
.nickname {
margin-left: 6px;
cursor: pointer;
}
.el-icon-caret-bottom {
cursor: pointer;
font-size: 12px;
}
}
}
}
}
</style>
|
from bs4 import BeautifulSoup
from couchpotato.core.event import fireEvent
from couchpotato.core.helpers.encoding import toUnicode
from couchpotato.core.helpers.variable import getTitle, tryInt, cleanHost
from couchpotato.core.logger import CPLog
from couchpotato.core.providers.torrent.base import TorrentProvider
from couchpotato.environment import Env
from urllib import quote_plus
import re
import time
import traceback
log = CPLog(__name__)
class ThePirateBay(TorrentProvider):
urls = {
'detail': '%s/torrent/%s',
'search': '%s/search/%s/0/7/%d'
}
cat_ids = [
([207], ['720p', '1080p']),
([201], ['cam', 'ts', 'dvdrip', 'tc', 'r5', 'scr', 'brrip']),
([202], ['dvdr'])
]
cat_backup_id = 200
disable_provider = False
http_time_between_calls = 0
proxy_list = [
'https://thepiratebay.se',
'https://tpb.ipredator.se',
'https://depiraatbaai.be',
'https://piratereverse.info',
'https://tpb.pirateparty.org.uk',
'https://argumentomteemigreren.nl',
'https://livepirate.com/',
'https://www.getpirate.com/',
]
def __init__(self):
self.domain = self.conf('domain')
super(ThePirateBay, self).__init__()
def getDomain(self, url = ''):
if not self.domain:
for proxy in self.proxy_list:
prop_name = 'tpb_proxy.%s' % proxy
last_check = float(Env.prop(prop_name, default = 0))
if last_check > time.time() - 1209600:
continue
data = ''
try:
data = self.urlopen(proxy, timeout = 3, show_error = False)
except:
log.debug('Failed tpb proxy %s', proxy)
if 'title="Pirate Search"' in data:
log.debug('Using proxy: %s', proxy)
self.domain = proxy
break
Env.prop(prop_name, time.time())
if not self.domain:
log.error('No TPB proxies left, please add one in settings, or let us know which one to add on the forum.')
return None
return cleanHost(self.domain).rstrip('/') + url
def search(self, movie, quality):
results = []
if self.isDisabled() or not self.getDomain():
return results
cache_key = 'thepiratebay.%s.%s' % (movie['library']['identifier'], quality.get('identifier'))
search_url = self.urls['search'] % (self.getDomain(), quote_plus(getTitle(movie['library']) + ' ' + quality['identifier']), self.getCatId(quality['identifier'])[0])
data = self.getCache(cache_key, search_url)
if data:
try:
soup = BeautifulSoup(data)
results_table = soup.find('table', attrs = {'id': 'searchResult'})
if not results_table:
return results
entries = results_table.find_all('tr')
for result in entries[2:]:
link = result.find(href = re.compile('torrent\/\d+\/'))
download = result.find(href = re.compile('magnet:'))
try:
size = re.search('Size (?P<size>.+),', unicode(result.select('font.detDesc')[0])).group('size')
except:
continue
if link and download:
def extra_score(item):
trusted = (0, 10)[result.find('img', alt = re.compile('Trusted')) != None]
vip = (0, 20)[result.find('img', alt = re.compile('VIP')) != None]
confirmed = (0, 30)[result.find('img', alt = re.compile('Helpers')) != None]
moderated = (0, 50)[result.find('img', alt = re.compile('Moderator')) != None]
return confirmed + trusted + vip + moderated
new = {
'id': re.search('/(?P<id>\d+)/', link['href']).group('id'),
'type': 'torrent_magnet',
'name': link.string,
'check_nzb': False,
'description': '',
'provider': self.getName(),
'url': download['href'],
'detail_url': self.getDomain(link['href']),
'size': self.parseSize(size),
'seeders': tryInt(result.find_all('td')[2].string),
'leechers': tryInt(result.find_all('td')[3].string),
'extra_score': extra_score,
'get_more_info': self.getMoreInfo
}
new['score'] = fireEvent('score.calculate', new, movie, single = True)
is_correct_movie = fireEvent('searcher.correct_movie', nzb = new, movie = movie, quality = quality,
imdb_results = False, single = True)
if is_correct_movie:
results.append(new)
self.found(new)
return results
except:
log.error('Failed getting results from %s: %s', (self.getName(), traceback.format_exc()))
return []
def getMoreInfo(self, item):
full_description = self.getCache('tpb.%s' % item['id'], item['detail_url'], cache_timeout = 25920000)
html = BeautifulSoup(full_description)
nfo_pre = html.find('div', attrs = {'class':'nfo'})
description = toUnicode(nfo_pre.text) if nfo_pre else ''
item['description'] = description
return item
|
import UIKit
enum MissmatchError: Error {
case nameMissmatch
case numberMissmatch
}
func test(){
}
// ์๋ฌ๋ฅผ ๋์ง๋ ๋ฉ์๋
func GuessMyName(name input: String) throws{
print("guessMyName() called")
if input != "์น์ฌ"{
print("X")
throw MissmatchError.nameMissmatch
}
print("O")
}
/// Description : ๋ฒํธ๋ฅผ ๋ง์ถ๋ ํจ์
/// - Parameter input: ์ฌ์ฉ์ ์ซ์ ์
๋ ฅ
/// - Returns: bool ๋ง์ท๋์ง ์ฌ๋ถ
func GuessMyNumber(number input: Int) throws -> Bool{
print("guessMyNumber() called")
if input != 10{
print("X")
throw MissmatchError.numberMissmatch
}
print("O")
return true
}
try? GuessMyName(name: "์น์ฌ") // ์๋ฌ๊ฐ ์์ด๋ ์๋ฌด์ฒ๋ฆฌ ํ์ง ์๊ฒ๋ค.
//try! GuessMyName(name: "์น์ฌ2") // ์๋ฌ๊ฐ ๋ฌด์กฐ๊ฑด ์์ ๊ฑฐ๋ค ๋ผ๋ ๋ป
do {
try GuessMyName(name: "์ ์ฉ")
}catch{
print("์ก์ ์๋ฌ \(error)")
}
do {
let receivedValue = try GuessMyNumber(number: 10)
}catch{
print("์ก์ ์๋ฌ \(error)")
}
|
//
// ContentView.swift
// pract
//
// Created by ํ๋น on 2023/01/02.
//
import SwiftUI
struct SettingsView: View {
@State var searchText = ""
@State var toggling = false
@State var wifiConnection = false
var body: some View {
NavigationStack {
Form {
Section {
HStack {
Image(systemName: "magnifyingglass")
.padding(0)
TextField("๊ฒ์", text: $searchText)
}
}
Section {
NavigationLink(destination: Text("Apple ID")) {
Image("blue")
.resizable()
.clipShape(Circle())
.frame(width: 60, height: 60)
VStack(alignment: .leading) {
Text("์๋น")
.font(.title2)
Text("Apple ID, iCloud+, ๋ฏธ๋์ด ๋ฐ ๊ตฌ์
ํญ๋ชฉ")
.font(.system(size: 12))
}
}
}
Section {
HStack {
Image(systemName: "airplane")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
.padding(4)
.background(Color(red: 240/255, green: 154/255, blue: 55/255))
.foregroundStyle(.white)
.cornerRadius(6)
Toggle(isOn: $toggling){
Text("์์ดํ๋ ์ธ ๋ชจ๋")
}
}
NavigationLink(destination: WifiListView()
.navigationBarItems(trailing: EditButton())
.navigationTitle("Wi-Fi") .navigationBarTitleDisplayMode(.inline)) {
Image(systemName: "wifi")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
.padding(4)
.background(Color(red: 52/255, green: 120/255, blue: 246/255))
.foregroundStyle(.white)
.cornerRadius(6)
Text("Wi-Fi")
}
NavigationLink(destination: Text("์
๋ฃฐ๋ฌ ํ๋ฉด")) {
Image(systemName: "antenna.radiowaves.left.and.right")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
.padding(4)
.background(Color(red: 101/255, green: 196/255, blue: 102/255))
.foregroundStyle(.white)
.cornerRadius(6)
Text("์
๋ฃฐ๋ฌ")
}
}
Section {
NavigationLink(destination: Text("์๋ฆผ ํ๋ฉด")) {
Image(systemName: "bell.badge.fill")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
.padding(4)
.background(Color(red: 234/255, green: 78/255, blue: 61/255))
.foregroundStyle(.white)
.cornerRadius(6)
Text("์๋ฆผ")
}
NavigationLink(destination: Text("์ฌ์ด๋ ๋ฐ ํ
ํฑ ํ๋ฉด")) {
Image(systemName: "speaker.wave.3.fill")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
.padding(4)
.background(Color(red: 234/255, green: 68/255, blue: 90/255))
.foregroundStyle(.white)
.cornerRadius(6)
Text("์ฌ์ด๋ ๋ฐ ํ
ํฑ")
}
NavigationLink(destination: Text("์ง์ค๋ชจ๋ ํ๋ฉด")) {
Image(systemName: "moon.fill")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
.padding(4)
.background(Color(red: 87/255, green: 86/255, blue: 206/255))
.foregroundStyle(.white)
.cornerRadius(6)
Text("์ง์ค๋ชจ๋")
}
NavigationLink(destination: Text("์คํฌ๋ฆฐ ํ์ ํ๋ฉด")) {
Image(systemName: "hourglass")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
.padding(4)
.background(Color(red: 87/255, green: 86/255, blue: 206/255))
.foregroundStyle(.white)
.cornerRadius(6)
Text("์คํฌ๋ฆฐ ํ์")
}
}
}
.navigationTitle("์ค์ ")
}
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}
|
import React, { memo } from 'react';
import { IComponentPackage, IStoreMonitor, StoreMonitorContext } from '@lowcode-engine/core';
import { STORE_NAME as RENDERER_STORE_NAME } from '@lowcode-engine/renderer';
import { STORE_NAME as EDITOR_STORE_NAME } from '@lowcode-engine/editor';
import { connectReduxDevtools } from 'mst-middlewares';
import { ComponentPackage as PrimaryComponentPackage } from '@lowcode-engine/primary-component-package';
import { ComponentPackage as VideoPlayerComponentPackage } from '../../packages/video-player';
import { ComponentPackage as ImageViewerComponentPackage } from '../../packages/image-viewer';
// TODO: ไธดๆถๆต่ฏไฝฟ็จ,ๅ้ข็งป้ค
// const MONITOR_STORE = RENDERER_STORE_NAME;
const MONITOR_STORE = EDITOR_STORE_NAME;
const dataStoreMonitor: IStoreMonitor = {
hosting: (name: string, store: any) => {
if (name === MONITOR_STORE) {
connectReduxDevtools(require("remotedev"), store);
}
}
};
const packages: Array<IComponentPackage> = [
PrimaryComponentPackage.instance,
VideoPlayerComponentPackage.instance,
ImageViewerComponentPackage.instance,
];
interface ILowcodeInfrastructureContext {
packages: Array<IComponentPackage>;
}
const LowcodeInfrastructureCtx: ILowcodeInfrastructureContext = {
packages,
};
const LowcodeInfrastructureComponent: React.FC<{ children?: (context: ILowcodeInfrastructureContext) => React.ReactNode }> = memo(props => {
return (
<StoreMonitorContext.Provider value={dataStoreMonitor}>
{props.children && props.children(LowcodeInfrastructureCtx)}
</StoreMonitorContext.Provider>
);
});
LowcodeInfrastructureComponent.displayName = 'LowcodeInfrastructureComponent';
export default LowcodeInfrastructureComponent;
|
<?php
namespace App\Http\Requests;
use App\Extrant;
use Gate;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Response;
class UpdateExtrantRequest extends FormRequest
{
public function authorize()
{
abort_if(Gate::denies('extrant_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden');
return true;
}
public function rules()
{
return [
'code_extrant' => [
[
'string',
'max:20',
'required',
'unique:extrants,code_extrant,' . request()->route('extrant')->id,
],
],
'description' => [
[
'string',
'required',
],
],
'effet_immediat_id' => [
[
'required',
'integer',
],
],
];
}
}
|
# Basic HTML canvas-based game starter
This repository contains basic files to get you started with a canvas based game using Javascript. No library, nothing fancy.
## TODO
- [] Create a rectangle
- [] Make it move
- [] Animation loop
## Docs
- [Canvas API - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API)
- [HTML colour names](https://htmlcolorcodes.com/color-names/)
- [Animation Loop](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
## What's in this project?
โ `README.md`: That's this file, where you can tell people what your cool website does and how you built it.
โ `index.html`: This is the main HTML page for your site.
โ `style.css`: CSS files add styling rules to your content.
โ `script.js`: Add interactivity to your site with JavaScript.
โ `tidbits.js`: Some bits of code to reuse for your project.
โ `favicon.ico`: This is the icon of your website, that appears in the tab.
## How to use this project
You could:
* Use [glitch](https://glitch.com/) to experiment with it directly in your browser - Select `New Project` -> `Import from Github` and paste the URL for this project: `https://github.com/alicelieutier/minimal-html-starter`
* Download the files on your computer. On github, select `Code` -> `Download Zip`. Once you have the files, you can open `index.html` directly in your browser. If you want to have some javascript making API calls, however, you will need to run a local server. The easiest way is to [run one of these lines in the terminal](https://gist.github.com/willurd/5720255) from the directory where `index.html` is.
Once you are able to see the webpage in your browser, change the files to see how it changes.
๐ฅ Happy experimenting!
|
/*
* Copyright IBM Corporation 2021
*
* 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 java
import (
"fmt"
irtypes "github.com/konveyor/move2kube-wasm/types/ir"
"os"
"path/filepath"
"github.com/konveyor/move2kube-wasm/common"
"github.com/konveyor/move2kube-wasm/environment"
//irtypes "github.com/konveyor/move2kube-wasm/types/ir"
transformertypes "github.com/konveyor/move2kube-wasm/types/transformer"
"github.com/konveyor/move2kube-wasm/types/transformer/artifacts"
"github.com/sirupsen/logrus"
)
const (
defaultJbossPort int32 = 8080
)
// Jboss implements Transformer interface
type Jboss struct {
Config transformertypes.Transformer
Env *environment.Environment
JbossConfig *JbossYamlConfig
}
// JbossYamlConfig stores jar related configuration information
type JbossYamlConfig struct {
JavaVersion string `yaml:"defaultJavaVersion"`
}
// JbossDockerfileTemplate stores parameters for the dockerfile template
type JbossDockerfileTemplate struct {
JavaPackageName string
DeploymentFilePath string
BuildContainerName string
Port int32
EnvVariables map[string]string
}
// Init Initializes the transformer
func (t *Jboss) Init(tc transformertypes.Transformer, env *environment.Environment) (err error) {
t.Config = tc
t.Env = env
t.JbossConfig = &JbossYamlConfig{}
err = common.GetObjFromInterface(t.Config.Spec.Config, t.JbossConfig)
if err != nil {
logrus.Errorf("unable to load config for Transformer %+v into %T : %s", t.Config.Spec.Config, t.JbossConfig, err)
return err
}
if t.JbossConfig.JavaVersion == "" {
t.JbossConfig.JavaVersion = defaultJavaVersion
}
return nil
}
// GetConfig returns the transformer config
func (t *Jboss) GetConfig() (transformertypes.Transformer, *environment.Environment) {
return t.Config, t.Env
}
// DirectoryDetect runs detect in each sub directory
func (t *Jboss) DirectoryDetect(dir string) (services map[string][]transformertypes.Artifact, err error) {
return
}
// Transform transforms the artifacts
func (t *Jboss) Transform(newArtifacts []transformertypes.Artifact, alreadySeenArtifacts []transformertypes.Artifact) ([]transformertypes.PathMapping, []transformertypes.Artifact, error) {
pathMappings := []transformertypes.PathMapping{}
createdArtifacts := []transformertypes.Artifact{}
for _, newArtifact := range newArtifacts {
serviceConfig := artifacts.ServiceConfig{}
if err := newArtifact.GetConfig(artifacts.ServiceConfigType, &serviceConfig); err != nil {
logrus.Errorf("unable to load config for Transformer into %T : %s", serviceConfig, err)
continue
}
if serviceConfig.ServiceName == "" {
serviceConfig.ServiceName = common.MakeStringK8sServiceNameCompliant(newArtifact.Name)
}
imageName := artifacts.ImageName{}
if err := newArtifact.GetConfig(artifacts.ImageNameConfigType, &imageName); err != nil {
logrus.Debugf("unable to load config for Transformer into %T : %s", imageName, err)
}
if imageName.ImageName == "" {
imageName.ImageName = common.MakeStringContainerImageNameCompliant(newArtifact.Name)
}
if len(newArtifact.Paths[artifacts.ServiceDirPathType]) == 0 {
logrus.Errorf("service directory missing from artifact: %+v", newArtifact)
continue
}
serviceDir := newArtifact.Paths[artifacts.ServiceDirPathType][0]
relServiceDir, err := filepath.Rel(t.Env.GetEnvironmentSource(), serviceDir)
if err != nil {
logrus.Errorf("failed to make the service directory %s relative to the source code directory %s . Error: %q", serviceDir, t.Env.GetEnvironmentSource(), err)
continue
}
template, err := t.getDockerfileTemplate(newArtifact)
if err != nil {
logrus.Errorf("failed to get the jboss run stage Dockerfile template. Error: %q", err)
continue
}
tempDir := filepath.Join(t.Env.TempPath, newArtifact.Name)
if err := os.MkdirAll(tempDir, common.DefaultDirectoryPermission); err != nil {
logrus.Errorf("failed to create the temporary directory %s . Error: %q", tempDir, err)
continue
}
dockerfileTemplatePath := filepath.Join(tempDir, common.DefaultDockerfileName)
if err := os.WriteFile(dockerfileTemplatePath, []byte(template), common.DefaultFilePermission); err != nil {
logrus.Errorf("Could not write the generated Build Dockerfile template: %s", err)
}
templateData := JbossDockerfileTemplate{}
warConfig := artifacts.WarArtifactConfig{}
if err := newArtifact.GetConfig(artifacts.WarConfigType, &warConfig); err == nil {
// WAR
javaPackage, err := getJavaPackage(filepath.Join(t.Env.GetEnvironmentContext(), versionMappingFilePath), warConfig.JavaVersion)
if err != nil {
logrus.Errorf("Unable to find mapping version for java version %s : %s", warConfig.JavaVersion, err)
javaPackage = defaultJavaPackage
}
templateData.JavaPackageName = javaPackage
templateData.DeploymentFilePath = warConfig.DeploymentFilePath
templateData.Port = defaultJbossPort
templateData.EnvVariables = warConfig.EnvVariables
templateData.BuildContainerName = warConfig.BuildContainerName
} else {
// EAR
logrus.Debugf("unable to load config for Transformer into %T : %s", warConfig, err)
earConfig := artifacts.EarArtifactConfig{}
if err := newArtifact.GetConfig(artifacts.EarConfigType, &earConfig); err != nil {
logrus.Debugf("unable to load config for Transformer into %T : %s", earConfig, err)
}
javaPackage, err := getJavaPackage(filepath.Join(t.Env.GetEnvironmentContext(), versionMappingFilePath), earConfig.JavaVersion)
if err != nil {
logrus.Errorf("Unable to find mapping version for java version %s : %s", earConfig.JavaVersion, err)
javaPackage = defaultJavaPackage
}
templateData.JavaPackageName = javaPackage
templateData.DeploymentFilePath = earConfig.DeploymentFilePath
templateData.Port = defaultJbossPort
templateData.EnvVariables = earConfig.EnvVariables
templateData.BuildContainerName = earConfig.BuildContainerName
}
pathMappings = append(pathMappings, transformertypes.PathMapping{
Type: transformertypes.SourcePathMappingType,
DestPath: common.DefaultSourceDir,
})
pathMappings = append(pathMappings, transformertypes.PathMapping{
Type: transformertypes.TemplatePathMappingType,
SrcPath: dockerfileTemplatePath,
DestPath: filepath.Join(common.DefaultSourceDir, relServiceDir),
TemplateConfig: templateData,
})
paths := newArtifact.Paths
paths[artifacts.DockerfilePathType] = []string{filepath.Join(common.DefaultSourceDir, relServiceDir, common.DefaultDockerfileName)}
dockerfileArtifact := transformertypes.Artifact{
Name: imageName.ImageName,
Type: artifacts.DockerfileArtifactType,
Paths: paths,
Configs: map[transformertypes.ConfigType]interface{}{
artifacts.ImageNameConfigType: imageName,
},
}
dockerfileServiceArtifact := transformertypes.Artifact{
Name: serviceConfig.ServiceName,
Type: artifacts.DockerfileForServiceArtifactType,
Paths: newArtifact.Paths,
Configs: map[transformertypes.ConfigType]interface{}{
artifacts.ImageNameConfigType: imageName,
artifacts.ServiceConfigType: serviceConfig,
},
}
ir := irtypes.IR{}
if err = newArtifact.GetConfig(irtypes.IRConfigType, &ir); err == nil {
dockerfileServiceArtifact.Configs[irtypes.IRConfigType] = ir
}
createdArtifacts = append(createdArtifacts, dockerfileArtifact, dockerfileServiceArtifact)
}
return pathMappings, createdArtifacts, nil
}
func (t *Jboss) getDockerfileTemplate(newArtifact transformertypes.Artifact) (string, error) {
jbossRunTemplatePath := filepath.Join(t.Env.GetEnvironmentContext(), t.Env.RelTemplatesDir, "Dockerfile.jboss")
jbossRunTemplate, err := os.ReadFile(jbossRunTemplatePath)
if err != nil {
return "", fmt.Errorf("failed to read the jboss run stage Dockerfile template at path %s . Error: %q", jbossRunTemplatePath, err)
}
dockerFileHead := ""
if buildContainerPaths := newArtifact.Paths[artifacts.BuildContainerFileType]; len(buildContainerPaths) > 0 {
dockerfileBuildPath := buildContainerPaths[0]
dockerFileHeadBytes, err := os.ReadFile(dockerfileBuildPath)
if err != nil {
return "", fmt.Errorf("failed to read the build stage Dockerfile template at path %s . Error: %q", dockerfileBuildPath, err)
}
dockerFileHead = string(dockerFileHeadBytes)
} else {
licenseFilePath := filepath.Join(t.Env.GetEnvironmentContext(), t.Env.RelTemplatesDir, "Dockerfile.license")
dockerFileHeadBytes, err := os.ReadFile(licenseFilePath)
if err != nil {
return "", fmt.Errorf("failed to read the Dockerfile license at path %s . Error: %q", licenseFilePath, err)
}
dockerFileHead = string(dockerFileHeadBytes)
}
return dockerFileHead + "\n" + string(jbossRunTemplate), nil
}
|
package com.agrapana.arnesys.helper
import android.content.Context
import android.util.Log
import com.agrapana.arnesys.config.*
import info.mqtt.android.service.MqttAndroidClient
import org.eclipse.paho.client.mqttv3.*
import org.eclipse.paho.client.mqttv3.MqttClient
class MqttClientHelper(context: Context?) {
companion object {
const val TAG = "MqttClientHelper"
}
var mqttAndroidClient: MqttAndroidClient
private val clientId: String = MqttClient.generateClientId()
val serverUri = MQTT_HOST
fun setCallback(callback: MqttCallbackExtended?) {
callback?.let { mqttAndroidClient.setCallback(it) }
}
init {
mqttAndroidClient = MqttAndroidClient(context!!, serverUri, clientId)
connect()
}
private fun connect() {
val mqttConnectOptions = MqttConnectOptions()
mqttConnectOptions.isAutomaticReconnect = MQTT_CONNECTION_RECONNECT
mqttConnectOptions.isCleanSession = MQTT_CONNECTION_CLEAN_SESSION
mqttConnectOptions.connectionTimeout = MQTT_CONNECTION_TIMEOUT
mqttConnectOptions.keepAliveInterval = MQTT_CONNECTION_KEEP_ALIVE_INTERVAL
try {
mqttAndroidClient.connect(mqttConnectOptions, null, object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken) {
val disconnectedBufferOptions =
DisconnectedBufferOptions()
disconnectedBufferOptions.isBufferEnabled = true
disconnectedBufferOptions.bufferSize = 100
disconnectedBufferOptions.isPersistBuffer = false
disconnectedBufferOptions.isDeleteOldestMessages = false
mqttAndroidClient.setBufferOpts(disconnectedBufferOptions)
}
override fun onFailure(
asyncActionToken: IMqttToken,
exception: Throwable
) {
Log.w(TAG, "Failed to connect to: $serverUri ; $exception")
}
})
} catch (ex: MqttException) {
ex.printStackTrace()
}
}
fun subscribe(subscriptionTopic: String, qos: Int = 0) {
try {
mqttAndroidClient.subscribe(subscriptionTopic, qos, null, object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken) {
Log.w(TAG, "Subscribed to topic '$subscriptionTopic'")
}
override fun onFailure(
asyncActionToken: IMqttToken,
exception: Throwable
) {
Log.w(TAG, "Subscription to topic '$subscriptionTopic' failed!")
}
})
} catch (ex: MqttException) {
System.err.println("Exception whilst subscribing to topic '$subscriptionTopic'")
ex.printStackTrace()
}
}
fun unsubscribe(topic: String) {
try {
mqttAndroidClient.unsubscribe(topic, null, object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken?) {
Log.d(TAG, "Unsubscribed to $topic")
}
override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
Log.d(TAG, "Failed to unsubscribe $topic")
}
})
} catch (e: MqttException) {
e.printStackTrace()
}
}
fun isConnected() : Boolean {
return mqttAndroidClient.isConnected
}
fun disconnect() {
mqttAndroidClient.disconnect()
}
}
|
# Explore LLaMA-2
Here is an attempt to understand how stable diffusion works through the working code.
Thanks to [Umar Jamil](https://www.youtube.com/watch?v=oM4VmoabDAI) for creating this amazing video tutorial.
LLaMA-2 is not a single model, but rather a collection of four models. The only difference between each of these models is the number of parameters they contain. From smallest to largest, the LLaMA-2 models contain 7B, 13B, 34B, and 70B parameters. But otherwise, everything else about them from activation function to normalization method is identical.

The table above shows some notable differences between LLaMA and LLaMA-2.
- LLaMA-2 is trained with a longer context length of 4K tokens (i.e., LLaMA was trained with a 2K context length). So, context length and supported tokens have doubled.
- LLaMA-2 uses Group Query Attention (GQA) in last two of its models.
## Architecture

Below are a few architectural choices made in LLaMA-2.
### RMS Normalization
Most transformer architectures adopt layer normalization, which is applied after each layer within the transformer block; see above. LLaMA, however, replaces this with a variant called Root Mean Square Layer Normalization (or RMSNorm for short!), which is a simplified version of layer normalization that has been shown to improve training stability and generalization1. RMSNorm is formulated as shown below.

For LLaMA, a pre-normalization variant of RMSNorm is adopted, meaning that normalization is applied prior to the major layers in a transformer block, rather than after, as shown in the architecture diagram above.
### Rotary Positional Embeddings
Instead of using absolute or relative positional embeddings, LLaMA models adopt a Rotary Positional Embeddings (RoPE) scheme, which finds a balance between the absolute and relative position of each token in a sequence. This position embedding approach encodes absolute position with a rotation matrix and adds relative position information directly into the self-attention operation.



The benefit of RoPE embeddings on tasks with longer sequence lengths has led this approach to be adopted by a variety of LLMs (e.g., PaLM and Falcon).
### KV Cache
In the original transformer, since the attention mechanism is causal (i.e., the attention of a token only depends on its preceding tokens), at each generation step we are recalculating the same previous token attention, when we actually just want to calculate the attention for the new token.
This is where KV cache comes into play. By caching the previous Keys and Values, we can focus on only calculating the attention for the new token.

The matrices obtained with KV caching are way smaller, which leads to faster matrix multiplications leading to much less computations involved. The only downside is that it needs more GPU VRAM (or CPU RAM if GPU is not being used) to cache the Key and Value states.
### Grouped Query Attention
Before discussing Grouped Query Attention, letโs quickly review earlier attention mechanisms.
#### Multi-Head Attention(MHA)
Multi-head Attention is the default attention mechanism of the transformer model.

However, there is an issue with auto-regressive language models based on transformer decoders when it comes to text generation.
During training, we have access to the true target sequence and can efficiently implement parallelism.

However, during inference, each positionโs query attends to all the key-value pairs generated at or before that position. In other words, the output of the self-attention layer at a specific position affects the generation of the next token. Due to the inability to perform parallel computation, decoding becomes slower.
#### Multi-Query Attention(MHA)
The approach of MQA is to keep the original number of heads for Q, but have only one head for K and V. This means that all the Q heads share the same set of K and V heads, hence the name Multi-Query.


#### Grouped Query Attention

### SwiGLU Activation
LLaMA models adopt the SwiGLU activation functionโas opposed to the standard ReLU function adopted by most neural networksโwithin their feed-forward layers. The SwiGLU activation function can be formulated as follows.

SwiGLU is an element-wise product of two linear transformations of the input x, one of which has had a Swish activation applied to it. This activation function requires four matrix multiplications (i.e., it is more computationally expensive than a normal activation function such as ReLU), but it has been found to yield improvements in performance relative to other activation functions, even when the amount of compute being used is held constant.
## References
1. [Paper - Llama 2: Open Foundation and Fine-Tuned Chat Models](https://arxiv.org/abs/2307.09288)
2. [Coding LLaMA 2 from scratch in PyTorch - KV Cache, Grouped Query Attention, Rotary PE, RMSNorm](https://www.youtube.com/watch?v=oM4VmoabDAI)
3. [Rotary Positional Embeddings: Combining Absolute and Relative](https://www.youtube.com/watch?v=o29P0Kpobz0)
4. [LLaMA-2 from the Ground Up](https://cameronrwolfe.substack.com/p/llama-2-from-the-ground-up)
5. [Transformers KV Caching Explained](https://medium.com/@joaolages/kv-caching-explained-276520203249)
6. [Multi-Query Attention Explained](https://pub.towardsai.net/multi-query-attention-explained-844dfc4935bf)
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:hive/hive.dart';
import 'consumibles_model.dart';
part 'ambulancia_model.g.dart';
@HiveType(typeId: 1)
class AmbulanciaModel extends HiveObject {
@HiveField(0)
final String tipo;
@HiveField(1)
final String nombre;
@HiveField(2)
final String marca;
@HiveField(3)
final String linea;
@HiveField(4)
final String modelo;
@HiveField(5)
final String placas;
@HiveField(6)
final String color;
@HiveField(7)
final String numeroSerie;
@HiveField(8)
final String combustible;
@HiveField(9)
final String? operador;
@HiveField(10)
final String img;
@HiveField(11)
Map<String, List<ConsumiblesModel>> bitacora;
@HiveField(12)
final String id;
AmbulanciaModel({
required this.tipo,
required this.nombre,
required this.marca,
required this.linea,
required this.modelo,
required this.placas,
required this.color,
required this.numeroSerie,
required this.combustible,
this.operador,
required this.img,
this.bitacora = const {},
required this.id,
});
Map<String, bool> isFinis() {
final auxlist = bitacora;
Map<String, bool> complet = {};
for (var element in auxlist.keys) {
bool iscomplet = true;
for (var el in auxlist[element]!) {
if (el.existencia == null) {
iscomplet = false;
break;
}
}
complet[element] = iscomplet;
}
return complet;
}
AmbulanciaModel copyWith({
String? tipo,
String? nombre,
String? marca,
String? linea,
String? modelo,
String? placas,
String? color,
String? numeroSerie,
String? combustible,
String? operador,
String? img,
Map<String, List<ConsumiblesModel>>? bitacora,
String? id,
}) {
return AmbulanciaModel(
tipo: tipo ?? this.tipo,
nombre: nombre ?? this.nombre,
marca: marca ?? this.marca,
linea: linea ?? this.linea,
modelo: modelo ?? this.modelo,
placas: placas ?? this.placas,
color: color ?? this.color,
numeroSerie: numeroSerie ?? this.numeroSerie,
combustible: combustible ?? this.combustible,
operador: operador ?? this.operador,
img: img ?? this.img,
bitacora: bitacora ?? this.bitacora,
id: id ?? this.id,
);
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'tipo': tipo,
'nombre': nombre,
'marca': marca,
'linea': linea,
'modelo': modelo,
'placas': placas,
'color': color,
'numeroSerie': numeroSerie,
'combustible': combustible,
'operador': operador,
'img': img,
'bitacora': bitacora,
'_id': id,
};
}
factory AmbulanciaModel.fromMap(Map<String, dynamic> map) {
return AmbulanciaModel(
tipo: map['tipo'] as String,
nombre: map['nombre'] as String,
marca: map['marca'] as String,
linea: map['linea'] as String,
modelo: map['modelo'] as String,
placas: map['placas'] as String,
color: map['color'] as String,
numeroSerie: map['numeroSerie'] as String,
combustible: map['combustible'] as String,
operador: map['operador'] != null ? map['operador'] as String : null,
img: map['img'] as String,
bitacora: {},
id: map['_id'] as String,
);
}
String toJson() => json.encode(toMap());
factory AmbulanciaModel.fromJson(String source) =>
AmbulanciaModel.fromMap(json.decode(source) as Map<String, dynamic>);
@override
String toString() {
return 'AmbulanciaModel(tipo: $tipo, nombre: $nombre, marca: $marca, linea: $linea, modelo: $modelo, placas: $placas, color: $color, numeroSerie: $numeroSerie, combustible: $combustible, operador: $operador, img: $img, bitacora: $bitacora, id: $id)';
}
@override
bool operator ==(covariant AmbulanciaModel other) {
if (identical(this, other)) return true;
return other.tipo == tipo &&
other.nombre == nombre &&
other.marca == marca &&
other.linea == linea &&
other.modelo == modelo &&
other.placas == placas &&
other.color == color &&
other.numeroSerie == numeroSerie &&
other.combustible == combustible &&
other.operador == operador &&
other.img == img &&
mapEquals(other.bitacora, bitacora) &&
other.id == id;
}
@override
int get hashCode {
return tipo.hashCode ^
nombre.hashCode ^
marca.hashCode ^
linea.hashCode ^
modelo.hashCode ^
placas.hashCode ^
color.hashCode ^
numeroSerie.hashCode ^
combustible.hashCode ^
operador.hashCode ^
img.hashCode ^
bitacora.hashCode ^
id.hashCode;
}
}
|
"""ๅ ๆๅบ
ๅ ็ๅไธ่ฐๆด็นๆง
"""
def sift(li, low, high):
"""
:note ่พ
ๅฉๅฝๆฐ๏ผ็จๆฅๆๅปบๅฐๆ นๅ ๏ผๆถ้ดๅคๆๅบฆไธบO(logn)
:param li: ๅ่กจ
:param low: ๅ ็ๆ น็ป็นไฝ็ฝฎ
:param high: ๅ ็ๆๅไธไธชๅ
็ด ็ไฝ็ฝฎ
:return:
"""
i = low # iๆๅผๅงๆๅๆ น็ป็น
j = 2 * i + 1 # jๅผๅงๆฏๅทฆๅญฉๅญ
tmp = li[low] # ๆๅ ้กถๅญ่ตทๆฅ
while j <= high: # ๅช่ฆjไฝ็ฝฎๆๆฐ
if j + 1 <= high and li[j + 1] < li[j]: # ๅฆๆๅณๅญฉๅญๅญๅจๅนถไธๆฏ่พๅฐ
j = j + 1 # jๆๅๅณๅญฉๅญ
if li[j] < tmp: # ๅฆๆๆๅฐ็ๅญฉๅญๆฏๅ ้กถๅฐ
li[i] = li[j] # ๅฐ็ถไบฒๅๅญฉๅญๅฏน่ฐ
i = j # ๅพไธๆชไธๅฑ
j = 2 * i + 1 # j็ฐๅจๆฏๆฐ็ๅทฆๅญฉๅญ๏ผๅๅฐๅพช็ฏๅผๅง
else: # tmpๆดๅคง
li[i] = tmp # ๆtmpๆพๅฐi็ไฝ็ฝฎไธ
break
else:
li[i] = tmp # ๆtmpๆพๅฐๅถๅญ่็นไธ
def topk(li, k):
heap = li[0:k] # ๅๅ่กจๅKไธชๆฐ
# 1 ๅปบ็ซๅฐๆ นๅ
for i in range((k - 2) // 2, -1, -1):
sift(heap, i, k - 1) # siftๅฝๆฐ็จๆฅๅปบ็ซๅฐๆ นๅ ๏ผๆไปฅๆญคๆถๅ ้กถๅฟ
ๅฎๆฏๅkไธชๆฐ้็ฌฌkๅคง็ๆฐ
# 2 ๅพช็ฏๆฏ่พๅฉไธ็ๆฐไธๅ ้กถๆฐๅญ
for i in range(k, len(li)):
if li[i] > heap[0]: # ๅฆๆๅฝๅๆฐๆฏๅ ้กถๆฐๅคง๏ผ่ฏๆๅ ้กถ่ฏๅฎไธๆฏ็ฌฌKๅคง็ๆฐ
heap[0] = li[i] # ๅฐๅ ้กถๆฐๅญ่ฎพๆๅฝๅๆฐๅญ
sift(heap, 0, k - 1) # ้ๅปบๅฐๆ นๅ
# 3 ๆญคๆถๅ ้็ๆฐๅทฒ็ปๆฏๅKๅคง็ๆฐๅญ๏ผๅ่ฟ่กไธๆฌกๅ ๆๅบๅณๅฏ
for i in range(k - 1, -1, -1): # iๆฐธ่ฟๆๅๅฝๅๅ ็ๆๅไธไธชๅ
็ด
heap[0], heap[i] = heap[i], heap[0] # ๅฐๅ ้กถๆพๅฐๆๅ
sift(heap, 0, i - 1) # i-1ๆฏๆฐ็่พน็
return heap
li = [i for i in range(15)]
import random
random.shuffle(li)
print(topk(li, 15))
|
import 'package:belin_zayy_admin/bindings/edit_product_binding.dart';
import 'package:belin_zayy_admin/controllerss/all_products_controller.dart';
import 'package:belin_zayy_admin/get/color_manager.dart';
import 'package:belin_zayy_admin/inner_screens/edit_prod.dart';
import 'package:belin_zayy_admin/values/font_manager.dart';
import 'package:belin_zayy_admin/values/style_manager.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../get/routes.dart';
import '../services/utils.dart';
import 'text_widget.dart';
class ProductWidget extends GetView<AllProductCotroller> {
ProductWidget({Key? key, required this.index
// required this.id,
})
: super(key: key);
int index;
// final String id;
// String title = '';
// String productCat = '';
// String imageUrl;
// String price = '0.0';
// double salePrice = 0.0;
// bool isOnSale = false;
// bool isPiece = false;
// @override
@override
Widget build(BuildContext context) {
Size size = Utils(context).getScreenSize;
const color = Colors.blue;
return InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () {
Get.to(
() => EditProductScreen(
id: controller.productList[index].id.toString(),
title: controller.productList[index].title.toString(),
price: double.parse(
controller.productList[index].price.toString()),
imageUrl: controller.productList[index].imageUrl,
),
binding: EditProductBinding());
// Get.toNamed(Routes.editProduct,
// arguments: controller.productList[index].id);
// Get.to(EditProductScreen(
// controller.productList[index].id,
// title: controller.productList[index].title,
// price: controller.productList[index].price,
// salePrice: controller.productList[index].salePrice,
// productCat: controller.productList[index].productCategoryName,
// imageUrl: controller.productList[index].imageUrl,
// ));
// Navigator.of(context).push(
// MaterialPageRoute(
// builder: (context) => EditProductScreen(
// id: id,
// title: title,
// price: price,
// salePrice: salePrice,
// productCat: productCat,
// imageUrl: imageUrl == null
// ? 'https://www.lifepng.com/wp-content/uploads/2020/11/Apricot-Large-Single-png-hd.png'
// : imageUrl!,
// isOnSale: isOnSale,
// isPiece: isPiece,
// ),
// ),
// );
},
child: Card(
elevation: 5,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
CachedNetworkImage(
height: 100,
width: 100,
progressIndicatorBuilder:
(context, url, downloadProgress) => Center(
child: CircularProgressIndicator(
value: downloadProgress.progress),
),
errorWidget: (context, url, error) =>
const Icon(Icons.error),
// imageUrl == null
// ? 'https://www.lifepng.com/wp-content/uploads/2020/11/Apricot-Large-Single-png-hd.png'
imageUrl: controller.productList[index].imageUrl),
Text(
"${controller.productList[index].price.toString()}Ks",
style: getLightStyle(
fontSize: FontSize.defaultFontSize,
color: Colors.black),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
alignment: Alignment.center,
// color: Colors.blue,
width: 130,
child: Text(
overflow: TextOverflow.ellipsis,
controller.productList[index].title.toString(),
style: getRegularStyle(
fontSize: FontSize.defaultFontSize,
color: ColorManager.primaryColor),
),
),
// Icon(Icons.menu)
PopupMenuButton(
onSelected: (value) {
value == 'go'
? Get.to(
() => EditProductScreen(
id: controller.productList[index].id
.toString(),
title: controller
.productList[index].title
.toString(),
price: double.parse(controller
.productList[index].price
.toString()),
imageUrl: controller
.productList[index].imageUrl,
),
binding: EditProductBinding())
: controller.deleteProduct(
controller.productList[index].imageUrl,
controller.productList[index].id);
},
itemBuilder: (context) => [
const PopupMenuItem(
value: 'go',
child: Text("Edit"),
),
const PopupMenuItem(
value: 'delete',
child: Text("Delete"),
)
],
child: const Icon(Icons.more_vert))
])
]))
// Padding(
// padding: const EdgeInsets.all(8.0),
// child: Column(
// mainAxisAlignment: MainAxisAlignment.start,
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Flexible(
// flex: 3,
// child: CachedNetworkImage(
// progressIndicatorBuilder:
// (context, url, downloadProgress) => Center(
// child: CircularProgressIndicator(
// value: downloadProgress.progress),
// ),
// errorWidget: (context, url, error) =>
// const Icon(Icons.error),
// // imageUrl == null
// // ? 'https://www.lifepng.com/wp-content/uploads/2020/11/Apricot-Large-Single-png-hd.png'
// imageUrl: controller.productList[index].imageUrl,
// fit: BoxFit.fill,
// // width: screenWidth * 0.12,
// height: size.width * 0.12,
// ),
// ),
// const Spacer(),
// PopupMenuButton(
// itemBuilder: (context) => [
// PopupMenuItem(
// onTap: () {},
// child: const Text('Edit'),
// value: 1,
// ),
// PopupMenuItem(
// onTap: () {},
// child: const Text(
// 'Delete',
// style: TextStyle(color: Colors.red),
// ),
// value: 2,
// ),
// ])
// ],
// ),
// const SizedBox(
// height: 2,
// ),
// Row(
// children: [
// Text(
// controller.productList[index].price,
// // isOnSale
// // ? '\$${salePrice.toStringAsFixed(2)}'
// // : '\$$price',
// style: getRegularStyle(
// fontSize: FontSize.defaultFontSize,
// color: Colors.black),
// ),
// const SizedBox(
// width: 7,
// ),
// // Visibility(
// // visible: isOnSale,
// // child: Text(
// // '\$$price',
// // style: TextStyle(
// // decoration: TextDecoration.lineThrough,
// // color: color),
// // )),
// const Spacer(),
// // TextWidget(
// // text: isPiece ? 'Piece' : '1Kg',
// // color: color,
// // textSize: 18,
// // ),
// ],
// ),
// const SizedBox(
// height: 2,
// ),
// TextWidget(
// text: controller.productList[index].title,
// color: color,
// textSize: 20,
// isTitle: true,
// ),
// ],
// ),
// ),
);
}
}
|
<?php
/**
* @file
* Base functions and tests for Display Suite.
*/
class dsBaseTest extends BackdropWebTestCase {
/**
* Implementation of setUp().
*/
function setUp() {
parent::setUp('ds', 'ds_extras', 'search', 'ds_search', 'ds_format', 'ds_forms', 'ds_ui', 'ds_test', 'views');
variable_set('search_active_modules', array('node' => '', 'user' => 'user', 'ds_search' => 'ds_search'));
menu_rebuild();
$this->admin_user = $this->backdropCreateUser(array('admin_classes', 'admin_view_modes', 'admin_fields', 'admin_display_suite', 'ds_switch article', 'use text format ds_code', 'access administration pages', 'administer content types', 'administer fields', 'administer users', 'administer comments', 'administer nodes', 'bypass node access', 'administer blocks', 'search content', 'use advanced search', 'administer search', 'access user profiles', 'administer permissions'));
$this->backdropLogin($this->admin_user);
}
/**
* Select a layout.
*/
function dsSelectLayout($edit = array(), $assert = array(), $url = 'admin/structure/types/manage/article/display', $options = array()) {
$edit += array(
'additional_settings[layout]' => 'ds_2col_stacked',
);
$this->backdropPost($url, $edit, t('Save'), $options);
$assert += array(
'regions' => array(
'header' => '<td colspan="8">' . t('Header') . '</td>',
'left' => '<td colspan="8">' . t('Left') . '</td>',
'right' => '<td colspan="8">' . t('Right') . '</td>',
'footer' => '<td colspan="8">' . t('Footer') . '</td>',
),
);
foreach ($assert['regions'] as $region => $raw) {
$this->assertRaw($region, t('Region !region found', array('!region' => $region)));
}
}
/**
* Configure classes
*/
function dsConfigureClasses($edit = array()) {
$edit += array(
'ds_classes_regions' => "class_name_1\nclass_name_2|Friendly name"
);
$this->backdropPost('admin/structure/ds/classes', $edit, t('Save configuration'));
$this->assertText(t('The configuration options have been saved.'), t('CSS classes configuration saved'));
$this->assertRaw('class_name_1', 'Class name 1 found');
$this->assertRaw('class_name_2', 'Class name 1 found');
}
/**
* Configure classes on a layout.
*/
function dsSelectClasses($edit = array(), $url = 'admin/structure/types/manage/article/display') {
$edit += array(
"additional_settings[header][]" => 'class_name_1',
"additional_settings[footer][]" => 'class_name_2',
);
$this->backdropPost($url, $edit, t('Save'));
}
/**
* Configure Field UI.
*/
function dsConfigureUI($edit, $url = 'admin/structure/types/manage/article/display') {
$this->backdropPost($url, $edit, t('Save'));
}
/**
* Edit field formatter settings
*/
function dsEditFormatterSettings($edit, $url = 'admin/structure/types/manage/article/display', $element_value = 'edit body') {
$this->backdropPost($url, array(), $element_value);
$this->backdropPost(NULL, $edit, t('Update'));
$this->backdropPost(NULL, array(), t('Save'));
}
/**
* Create a view mode.
*
* @param $edit
* An optional array of view mode properties.
*/
function dsCreateViewMode($edit = array()) {
$edit += array(
'name' => 'Testing',
'view_mode' => 'testing',
'entities[node]' => '1'
);
$this->backdropPost('admin/structure/ds/view_modes/manage', $edit, t('Save'));
$this->assertText(t('The view mode ' . $edit['name'] . ' has been saved'), t('!name view mode has been saved', array('!name' => $edit['name'])));
}
/**
* Create a code field.
*
* @param $edit
* An optional array of field properties.
*/
function dsCreateCodeField($edit = array(), $url = 'admin/structure/ds/fields/manage_custom') {
$edit += array(
'name' => 'Test field',
'field' => 'test_field',
'entities[node]' => '1',
'code[value]' => 'Test field',
'use_token' => '0',
);
$this->backdropPost($url, $edit, t('Save'));
$this->assertText(t('The field ' . $edit['name'] . ' has been saved'), t('!name field has been saved', array('!name' => $edit['name'])));
}
/**
* Create a block field.
*
* @param $edit
* An optional array of field properties.
*/
function dsCreateBlockField($edit = array(), $url = 'admin/structure/ds/fields/manage_block', $first = TRUE) {
$edit += array(
'name' => 'Test block field',
'entities[node]' => '1',
'block' => 'node|recent',
'block_render' => DS_BLOCK_TEMPLATE,
);
if ($first) {
$edit += array('field' => 'test_block_field');
}
$this->backdropPost($url, $edit, t('Save'));
$this->assertText(t('The field ' . $edit['name'] . ' has been saved'), t('!name field has been saved', array('!name' => $edit['name'])));
}
/**
* Create a block field.
*
* @param $edit
* An optional array of field properties.
*/
function dsCreatePreprocessField($edit = array(), $url = 'admin/structure/ds/fields/manage_preprocess', $first = TRUE) {
$edit += array(
'name' => 'Submitted',
'entities[node]' => '1',
);
if ($first) {
$edit += array('field' => 'submitted');
}
$this->backdropPost($url, $edit, t('Save'));
$this->assertText(t('The field ' . $edit['name'] . ' has been saved'), t('!name field has been saved', array('!name' => $edit['name'])));
}
/**
* Create a dynamic field.
*
* @param $edit
* An optional array of field properties.
*/
function dsCreateDynamicField($edit = array(), $url = 'admin/structure/ds/fields/manage_ctools', $first = TRUE) {
$edit += array(
'name' => 'Dynamic',
'entities[node]' => '1',
);
if ($first) {
$edit += array('field' => 'dynamic');
}
$this->backdropPost($url, $edit, t('Save'));
$this->assertText(t('The field ' . $edit['name'] . ' has been saved'), t('!name field has been saved', array('!name' => $edit['name'])));
}
}
/**
* Test managing of custom fields.
*/
class dsFieldsTests extends dsBaseTest {
/**
* Test Display fields.
*/
function testDSFields() {
$edit = array(
'name' => 'Test field',
'field' => 'test_field',
'entities[node]' => '1',
'code[value]' => 'Test field',
'use_token' => '0',
);
$this->dsCreateCodeField($edit);
// Create the same and assert it already exists.
$this->backdropPost('admin/structure/ds/fields/manage_custom', $edit, t('Save'));
$this->assertText(t('The machine-readable name is already in use. It must be unique.'), t('Field testing already exists.'));
$this->dsSelectLayout();
// Assert it's found on the Field UI for article.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertRaw('fields[test_field][weight]', t('Test field found on node article.'));
// Assert it's not found on the Field UI for users.
$this->backdropGet('admin/config/people/accounts/display');
$this->assertNoRaw('fields[test_field][weight]', t('Test field not found on user.'));
// Update testing label
$edit = array(
'name' => 'Test field 2',
);
$this->backdropPost('admin/structure/ds/fields/manage_custom/test_field', $edit, t('Save'));
$this->assertText(t('The field Test field 2 has been saved'), t('Test field label updated'));
// Use the Field UI limit option.
$this->dsSelectLayout(array(), array(), 'admin/structure/types/manage/page/display');
$this->dsSelectLayout(array(), array(), 'admin/structure/types/manage/article/display/teaser');
$edit = array(
'ui_limit' => 'article|default',
);
$this->backdropPost('admin/structure/ds/fields/manage_custom/test_field', $edit, t('Save'));
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertRaw('fields[test_field][weight]', t('Test field field found on node article, default.'));
$this->backdropGet('admin/structure/types/manage/article/display/teaser');
$this->assertNoRaw('fields[test_field][weight]', t('Test field field not found on node article, teaser.'));
$this->backdropGet('admin/structure/types/manage/page/display');
$this->assertNoRaw('fields[test_field][weight]', t('Test field field not found on node page, default.'));
$edit = array(
'ui_limit' => 'article|*',
);
$this->backdropPost('admin/structure/ds/fields/manage_custom/test_field', $edit, t('Save'));
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertRaw('fields[test_field][weight]', t('Test field field found on node article, default.'));
$this->backdropGet('admin/structure/types/manage/article/display/teaser');
$this->assertRaw('fields[test_field][weight]', t('Test field field found on node article, teaser.'));
// Remove the field.
$this->backdropPost('admin/structure/ds/fields/delete/test_field', array(), t('Delete'));
$this->assertText(t('The field Test field 2 has been deleted'), t('Test field removed'));
// Assert the field is gone at the manage display screen.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertNoRaw('fields[test_field][weight]', t('Test field field not found on node article.'));
// Block fields.
$edit = array(
'name' => 'Test block field',
'field' => 'test_block_field',
'entities[node]' => '1',
'block' => 'node|recent',
'block_render' => DS_BLOCK_TEMPLATE,
);
$this->dsCreateBlockField($edit);
// Create the same and assert it already exists.
$this->backdropPost('admin/structure/ds/fields/manage_block', $edit, t('Save'));
$this->assertText(t('The machine-readable name is already in use. It must be unique.'), t('Block test field already exists.'));
$this->dsSelectLayout();
// Assert it's found on the Field UI for article.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertRaw('fields[test_block_field][weight]', t('Test block field found on node article.'));
// Assert it's not found on the Field UI for users.
$this->backdropGet('admin/config/people/accounts/display');
$this->assertNoRaw('fields[test_block_field][weight]', t('Test block field not found on user.'));
// Update testing label
$edit = array(
'name' => 'Test block field 2',
);
$this->backdropPost('admin/structure/ds/fields/manage_block/test_block_field', $edit, t('Save'));
$this->assertText(t('The field Test block field 2 has been saved'), t('Test field label updated'));
// Remove the block field.
$this->backdropPost('admin/structure/ds/fields/delete/test_block_field', array(), t('Delete'));
$this->assertText(t('The field Test block field 2 has been deleted'), t('Test field removed'));
// Assert the block field is gone at the manage display screen.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertNoRaw('fields[test_block_field][weight]', t('Test block field not found on node article.'));
// Preprocess fields.
$edit = array(
'name' => 'Submitted',
'field' => 'submitted',
'entities[node]' => '1',
);
$this->dsCreatePreprocessField($edit);
// Create the same and assert it already exists.
$this->backdropPost('admin/structure/ds/fields/manage_custom', $edit, t('Save'));
$this->assertText(t('The machine-readable name is already in use. It must be unique.'), t('Submitted already exists.'));
$this->dsSelectLayout();
// Assert it's found on the Field UI for article.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertRaw('fields[submitted][weight]', t('Submitted found on node article.'));
// Assert it's not found on the Field UI for users.
$this->backdropGet('admin/config/people/accounts/display');
$this->assertNoRaw('fields[submitted][weight]', t('Submitted not found on user.'));
// Update testing label
$edit = array(
'name' => 'Submitted by',
);
$this->backdropPost('admin/structure/ds/fields/manage_preprocess/submitted', $edit, t('Save'));
$this->assertText(t('The field Submitted by has been saved'), t('Submitted label updated'));
// Remove a field.
$this->backdropPost('admin/structure/ds/fields/delete/submitted', array(), t('Delete'));
$this->assertText(t('The field Submitted by has been deleted'), t('Submitted removed'));
// Assert the field is gone at the manage display screen.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertNoRaw('fields[submitted][weight]', t('Submitted field not found on node article.'));
// Dynamic fields.
$edit = array(
'name' => 'Dynamic',
'field' => 'dynamic',
'entities[node]' => '1',
);
$this->dsCreateDynamicField($edit);
// Create the same and assert it already exists.
$this->backdropPost('admin/structure/ds/fields/manage_ctools', $edit, t('Save'));
$this->assertText(t('The machine-readable name is already in use. It must be unique.'), t('Dynamic already exists.'));
$this->dsSelectLayout();
// Assert it's found on the Field UI for article.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertRaw('fields[dynamic][weight]', t('Dynamic found on node article.'));
// Assert it's not found on the Field UI for users.
$this->backdropGet('admin/config/people/accounts/display');
$this->assertNoRaw('fields[dynamic][weight]', t('Dynamic not found on user.'));
// Update testing label
$edit = array(
'name' => 'Uber dynamic',
);
$this->backdropPost('admin/structure/ds/fields/manage_ctools/dynamic', $edit, t('Save'));
$this->assertText(t('The field Uber dynamic has been saved'), t('Dynamic label updated'));
// Remove a field.
$this->backdropPost('admin/structure/ds/fields/delete/dynamic', array(), t('Delete'));
$this->assertText(t('The field Uber dynamic has been deleted'), t('Dynamic removed'));
// Assert the field is gone at the manage display screen.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertNoRaw('fields[dynamic][weight]', t('Dynamic field not found on node article.'));
}
}
/**
* Test managing of view modes.
*/
class dsViewModesTests extends dsBaseTest {
/**
* Test managing view modes.
*/
function testDSManageViewModes() {
$edit = array(
'name' => 'Testing',
'view_mode' => 'testing',
'entities[node]' => '1'
);
$this->dsCreateViewMode($edit);
// Create the same and assert it already exists.
$this->backdropPost('admin/structure/ds/view_modes/manage', $edit, t('Save'));
$this->assertText(t('The machine-readable name is already in use. It must be unique.'), t('View mode testing already exists.'));
// Assert it's found on the Field UI for article.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertRaw('additional_settings[modes][view_modes_custom][testing]', t('Testing view mode found on node article.'));
// Assert it's not found on the Field UI for article.
$this->backdropGet('admin/config/people/accounts/display');
$this->assertNoRaw('additional_settings[modes][view_modes_custom][testing]', t('Testing view mode not found on user.'));
// Update testing label
$edit = array(
'name' => 'Testing 2',
);
$this->backdropPost('admin/structure/ds/view_modes/manage/testing', $edit, t('Save'));
$this->assertText(t('The view mode Testing 2 has been saved'), t('Testing label updated'));
// Remove a view mode.
$this->backdropPost('admin/structure/ds/view_modes/delete/testing', array(), t('Delete'));
$this->assertText(t('The view mode Testing 2 has been deleted'), t('Testing view mode removed'));
// Assert the view mode is gone at the manage display screen.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertNoRaw('additional_settings[modes][view_modes_custom][testing]', t('Testing view mode found on node article.'));
}
}
/**
* Test managing of layouts and CSS classes
*/
class dsLayoutsClassesTests extends dsBaseTest {
/**
* Test selecting layouts, classes, region to block and fields.
*/
function testDStestLayouts() {
// Check that the ds_3col_equal_width layout is not available (through the alter).
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertNoRaw('ds_3col_stacked_equal_width', 'ds_3col_stacked_equal_width not available');
// Create code, dynamic, preprocess block field.
$this->dsCreateCodeField();
$this->dsCreateBlockField();
$this->dsCreateDynamicField();
$this->dsCreatePreprocessField();
$layout = array(
'additional_settings[layout]' => 'ds_2col_stacked',
);
$assert = array(
'regions' => array(
'header' => '<td colspan="8">' . t('Header') . '</td>',
'left' => '<td colspan="8">' . t('Left') . '</td>',
'right' => '<td colspan="8">' . t('Right') . '</td>',
'footer' => '<td colspan="8">' . t('Footer') . '</td>',
),
);
$fields = array(
'fields[post_date][region]' => 'header',
'fields[author][region]' => 'left',
'fields[links][region]' => 'left',
'fields[body][region]' => 'right',
'fields[comments][region]' => 'footer',
'fields[test_field][region]' => 'left',
'fields[test_block_field][region]' => 'left',
'fields[submitted][region]' => 'left',
'fields[dynamic][region]' => 'left',
'fields[ds_extras_extra_test_field][region]' => 'header',
);
// Setup first layout.
$this->dsSelectLayout($layout, $assert);
$this->dsConfigureClasses();
$this->dsSelectClasses();
$this->dsConfigureUI($fields);
// Assert the two extra fields are found.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertRaw('ds_extras_extra_test_field');
$this->assertRaw('ds_extras_second_field');
// Assert we have some configuration in our database.
$count = db_query("SELECT COUNT(settings) FROM {ds_layout_settings} WHERE entity_type = 'node' AND bundle = 'article' AND view_mode = 'default'")->fetchField();
$this->assertEqual($count, 1, t('1 record found for layout serttings for node article'));
// Lookup settings and verify.
$data = unserialize(db_query("SELECT settings FROM {ds_layout_settings} WHERE entity_type = 'node' AND bundle = 'article' AND view_mode = 'default'")->fetchField());
$this->assertTrue(in_array('ds_extras_extra_test_field', $data['regions']['header']), t('Extra field is in header'));
$this->assertTrue(in_array('post_date', $data['regions']['header']), t('Post date is in header'));
$this->assertTrue(in_array('test_field', $data['regions']['left']), t('Test field is in left'));
$this->assertTrue(in_array('author', $data['regions']['left']), t('Author is in left'));
$this->assertTrue(in_array('links', $data['regions']['left']), t('Links is in left'));
$this->assertTrue(in_array('test_block_field', $data['regions']['left']), t('Test block field is in left'));
$this->assertTrue(in_array('submitted', $data['regions']['left']), t('Submitted field is in left'));
$this->assertTrue(in_array('dynamic', $data['regions']['left']), t('Dynamic field is in left'));
$this->assertTrue(in_array('body', $data['regions']['right']), t('Body is in right'));
$this->assertTrue(in_array('comments', $data['regions']['footer']), t('Comments is in footer'));
$this->assertTrue(in_array('class_name_1', $data['classes']['header']), t('Class name 1 is in header'));
$this->assertTrue(empty($data['classes']['left']), t('Left has no classes'));
$this->assertTrue(empty($data['classes']['right']), t('Right has classes'));
$this->assertTrue(in_array('class_name_2', $data['classes']['footer']), t('Class name 2 is in header'));
// Extra save for the dynamic field.
$field_settings = ds_get_field_settings('node', 'article', 'default');
$formatter_settings = array(
'show_title' => 0,
'title_wrapper' => '',
'ctools' => 'a:3:{s:4:"conf";a:3:{s:7:"context";s:25:"argument_entity_id:node_1";s:14:"override_title";i:0;s:19:"override_title_text";s:0:"";}s:4:"type";s:14:"node_type_desc";s:7:"subtype";s:14:"node_type_desc";}',
);
$field_settings['dynamic']['formatter_settings'] = $formatter_settings;
$record = new stdClass();
$record->id = 'node|article|default';
$record->entity_type = 'node';
$record->bundle = 'article';
$record->view_mode = 'default';
$record->settings = $field_settings;
backdrop_write_record('ds_field_settings', $record, array('id'));
cache_clear_all('ds_fields:', 'cache', TRUE);
cache_clear_all('ds_field_settings', 'cache');
// Create a article node and verify settings.
$settings = array(
'type' => 'article',
);
$node = $this->backdropCreateNode($settings);
$this->backdropGet('node/' . $node->nid);
// Assert regions.
$this->assertRaw('group-header', 'Template found (region header)');
$this->assertRaw('group-header class_name_1', 'Class found (class_name_1)');
$this->assertRaw('group-left', 'Template found (region left)');
$this->assertRaw('group-right', 'Template found (region right)');
$this->assertRaw('group-footer', 'Template found (region footer)');
$this->assertRaw('group-footer class_name_2', 'Class found (class_name_2)');
// Assert custom fields.
$this->assertRaw('field-name-test-field', t('Custom field found'));
$this->assertRaw('Test field', t('Custom field found'));
$this->assertRaw('field-name-test-block-field', t('Custom block field found'));
$this->assertRaw('<h2>Recent content</h2>', t('Custom block field found'));
$this->assertRaw('Submitted by', t('Submitted field found'));
$this->assertText('Use articles for time-sensitive content like news, press releases or blog posts.', t('Dynamic field found'));
$this->assertText('This is an extra field made available through "Extra fields" functionality.');
// Test disable sidebar regions.
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('sidebar-first', 'Left sidebar found.');
$hide = array(
'additional_settings[hide_sidebars]' => '1',
);
$this->dsConfigureUI($hide);
$this->backdropGet('node/' . $node->nid);
$this->assertNoRaw('sidebar-first', 'Left sidebar not found.');
// Test HTML5 wrappers
$this->assertNoRaw('<header', 'Header not found.');
$this->assertNoRaw('<footer', 'Footer not found.');
$this->assertNoRaw('<article', 'Article not found.');
$wrappers = array(
'additional_settings[region_wrapper][header]' => 'header',
'additional_settings[region_wrapper][right]' => 'footer',
'additional_settings[region_wrapper][layout_wrapper]' => 'article',
);
$this->dsConfigureUI($wrappers);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('<header', 'Header found.');
$this->assertRaw('<footer', 'Footer found.');
$this->assertRaw('<article', 'Article found.');
// Let's create a block field, enable the full mode first.
$edit = array('additional_settings[modes][view_modes_custom][full]' => '1');
$this->backdropPost('admin/structure/types/manage/article/display', $edit, t('Save'));
// Select layout.
$layout = array(
'additional_settings[layout]' => 'ds_2col',
);
$assert = array(
'regions' => array(
'left' => '<td colspan="8">' . t('Left') . '</td>',
'right' => '<td colspan="8">' . t('Right') . '</td>',
),
);
$this->dsSelectLayout($layout, $assert, 'admin/structure/types/manage/article/display/full');
// Create new block field.
$edit = array(
'additional_settings[region_to_block][new_block_region]' => 'Block region',
'additional_settings[region_to_block][new_block_region_key]' => 'block_region',
);
$this->backdropPost('admin/structure/types/manage/article/display/full', $edit, t('Save'));
$this->assertRaw('<td colspan="8">' . t('Block region') . '</td>', 'Block region found');
// Configure fields
$fields = array(
'fields[author][region]' => 'left',
'fields[links][region]' => 'left',
'fields[body][region]' => 'right',
'fields[ds_test_field][region]' => 'block_region',
);
$this->dsConfigureUI($fields, 'admin/structure/types/manage/article/display/full');
// Set block in sidebar
$edit = array(
'blocks[ds_extras_block_region][region]' => 'sidebar_first',
);
$this->backdropPost('admin/structure/block', $edit, t('Save blocks'));
// Assert the block is on the node page.
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('<h2>Block region</h2>', 'Block region found');
$this->assertText('Test code field on node ' . $node->nid, 'Post date in block');
// Change layout via admin/structure/ds/layout-change.
// First verify that header and footer are not here.
$this->backdropGet('admin/structure/types/manage/article/display/full');
$this->assertNoRaw('<td colspan="8">' . t('Header') . '</td>', 'Header region not found');
$this->assertNoRaw('<td colspan="8">' . t('Footer') . '</td>', 'Footer region not found');
// Remap the regions.
$edit = array(
'ds_left' => 'header',
'ds_right' => 'footer',
'ds_block_region' => 'footer',
);
$this->backdropPost('admin/structure/ds/change-layout/node/article/full/ds_2col_stacked', $edit, t('Save'), array('query' => array('destination' => 'admin/structure/types/manage/article/display/full')));
// Verify new regions.
$this->assertRaw('<td colspan="8">' . t('Header') . '</td>', 'Header region found');
$this->assertRaw('<td colspan="8">' . t('Footer') . '</td>', 'Footer region found');
$this->assertRaw('<td colspan="8">' . t('Block region') . '</td>', 'Block region found');
// Verify settings.
$data = unserialize(db_query("SELECT settings FROM {ds_layout_settings} WHERE entity_type = 'node' AND bundle = 'article' AND view_mode = 'full'")->fetchField());
$this->assertTrue(in_array('author', $data['regions']['header']), t('Author is in header'));
$this->assertTrue(in_array('links', $data['regions']['header']), t('Links field is in header'));
$this->assertTrue(in_array('body', $data['regions']['footer']), t('Body field is in footer'));
$this->assertTrue(in_array('ds_test_field', $data['regions']['footer']), t('Test field is in footer'));
// Test that a default view mode with no layout is not affected by a disabled view mode.
$edit = array(
'additional_settings[layout]' => '',
'additional_settings[modes][view_modes_custom][full]' => FALSE,
);
$this->backdropPost('admin/structure/types/manage/article/display', $edit, t('Save'));
$this->backdropGet('node/' . $node->nid);
$this->assertNoText('Test code field on node 1', 'No ds field from full view mode layout');
}
}
/**
* Tests for Display Suite field permissions.
*/
class dsFieldPermissionTests extends dsBaseTest {
function testFieldPermissions() {
$fields = array(
'fields[body][region]' => 'right',
'fields[ds_test_field][region]' => 'left',
);
variable_set('ds_extras_field_permissions', TRUE);
$this->refreshVariables();
module_implements(FALSE, FALSE, TRUE);
$this->dsSelectLayout();
$this->dsConfigureUI($fields);
// Create a node.
$settings = array('type' => 'article');
$node = $this->backdropCreateNode($settings);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('group-right', 'Template found (region right)');
$this->assertNoText('Test code field on node ' . $node->nid, 'Test code field not found');
// Give permissions.
$edit = array(
'2[view author on node]' => 1,
'2[view ds_test_field on node]' => 1,
);
$this->backdropPost('admin/people/permissions', $edit, t('Save permissions'));
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('group-left', 'Template found (region left)');
$this->assertText('Test code field on node ' . $node->nid, 'Test code field found');
}
}
/**
* Tests for Display Suite hooks.
*/
class dsHooksTests extends dsBaseTest {
/**
* Test fields hooks.
*/
function testDSFields() {
$this->dsSelectLayout();
// Find the two extra fields from the test module on the node type.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertText('Test code field from hook', 'Test field found on node.');
$this->assertText('Field altered', 'Test field altered found on node.');
$empty = array();
$edit = array('additional_settings[layout]' => 'ds_2col_stacked');
$this->dsSelectLayout($edit, $empty, 'admin/config/people/accounts/display');
// Fields can not be found on user.
$this->backdropGet('admin/config/people/accounts/display');
$this->assertNoText('Test code field from hook', 'Test field not found on user.');
$this->assertNoText('Field altered', 'Test field altered not found on user.');
// Select layout.
$this->dsSelectLayout();
$fields = array(
'fields[author][region]' => 'left',
'fields[links][region]' => 'left',
'fields[body][region]' => 'right',
'fields[ds_test_field][region]' => 'right',
'fields[ds_test_field_empty_string][region]' => 'right',
'fields[ds_test_field_empty_string][label]' => 'inline',
'fields[ds_test_field_false][region]' => 'right',
'fields[ds_test_field_false][label]' => 'inline',
'fields[ds_test_field_null][region]' => 'right',
'fields[ds_test_field_null][label]' => 'inline',
'fields[ds_test_field_nothing][region]' => 'right',
'fields[ds_test_field_nothing][label]' => 'inline',
'fields[ds_test_field_zero_int][region]' => 'right',
'fields[ds_test_field_zero_int][label]' => 'inline',
'fields[ds_test_field_zero_string][region]' => 'right',
'fields[ds_test_field_zero_string][label]' => 'inline',
'fields[ds_test_field_zero_float][region]' => 'right',
'fields[ds_test_field_zero_float][label]' => 'inline',
);
$this->dsSelectLayout();
$this->dsConfigureUI($fields);
// Create a node.
$settings = array('type' => 'article');
$node = $this->backdropCreateNode($settings);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('group-left', 'Template found (region left)');
$this->assertRaw('group-right', 'Template found (region right)');
$this->assertText('Test code field on node ' . $node->nid, 'Test code field found');
$this->assertNoText('Test code field that returns an empty string', 'Test code field that returns an empty string is not visible.');
$this->assertNoText('Test code field that returns FALSE', 'Test code field that returns FALSE is not visible.');
$this->assertNoText('Test code field that returns NULL', 'Test code field that returns NULL is not visible.');
$this->assertNoText('Test code field that returns nothing', 'Test code field that returns nothing is not visible.');
$this->assertNoText('Test code field that returns an empty array', 'Test code field that returns an empty array is not visible.');
$this->assertText('Test code field that returns zero as an integer', 'Test code field that returns zero as an integer is visible.');
$this->assertText('Test code field that returns zero as a string', 'Test code field that returns zero as a string is visible.');
$this->assertText('Test code field that returns zero as a floating point number', 'Test code field that returns zero as a floating point number is visible.');
}
/**
* Test layouts hook.
*/
function testDSLayouts() {
// Assert our 2 tests layouts are found.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertRaw('Test One column', 'Test One column layout found');
$this->assertRaw('Test Two column', 'Test Two column layout found');
$layout = array(
'additional_settings[layout]' => 'dstest_2col',
);
$assert = array(
'regions' => array(
'left' => '<td colspan="8">' . t('Left') . '</td>',
'right' => '<td colspan="8">' . t('Right') . '</td>',
),
);
$fields = array(
'fields[author][region]' => 'left',
'fields[links][region]' => 'left',
'fields[body][region]' => 'right',
);
$this->dsSelectLayout($layout, $assert);
$this->dsConfigureUI($fields);
// Create a node.
$settings = array('type' => 'article');
$node = $this->backdropCreateNode($settings);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('group-left', 'Template found (region left)');
$this->assertRaw('group-right', 'Template found (region right)');
$this->assertRaw('dstest_2col.css', 'Css file included');
// Alter a region
$settings = array(
'type' => 'article',
'title' => 'Alter me!',
);
$node = $this->backdropCreateNode($settings);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('cool!', 'Region altered');
}
}
class dsNodeTests extends dsBaseTest {
/**
* Utility function to setup for all kinds of tests.
*
* @param $label
* How the body label must be set.
*/
function entitiesTestSetup($label = 'above') {
// Create a node.
$settings = array('type' => 'article', 'promote' => 1);
$node = $this->backdropCreateNode($settings);
// Create field CSS classes.
$edit = array('ds_classes_fields' => "test_field_class\ntest_field_class_2|Field class 2");
$this->backdropPost('admin/structure/ds/classes', $edit, t('Save configuration'));
// Create a token and php field.
$token_field = array(
'name' => 'Token field',
'field' => 'token_field',
'entities[node]' => '1',
'code[value]' => '<div class="token-class">[node:title]</span>',
'use_token' => '1',
);
$php_field = array(
'name' => 'PHP field',
'field' => 'php_field',
'entities[node]' => '1',
'code[value]' => "<?php echo 'I am a PHP field'; ?>",
'use_token' => '0',
);
$this->dsCreateCodeField($token_field);
$this->dsCreateCodeField($php_field);
// Select layout.
$this->dsSelectLayout();
// Configure fields.
$fields = array(
'fields[token_field][region]' => 'header',
'fields[php_field][region]' => 'left',
'fields[body][region]' => 'right',
'fields[node_link][region]' => 'footer',
'fields[body][label]' => $label,
'fields[submitted_by][region]' => 'header',
);
$this->dsConfigureUI($fields);
return $node;
}
/**
* Utility function to clear field settings.
*/
function entitiesClearFieldSettings() {
db_query('TRUNCATE {ds_field_settings}');
cache_clear_all('ds_fields:', 'cache', TRUE);
cache_clear_all('ds_field_settings', 'cache');
}
/**
* Set the label.
*/
function entitiesSetLabelClass($label, $text = '', $class = '', $hide_colon = FALSE) {
$edit = array(
'fields[body][label]' => $label,
);
if (!empty($text)) {
$edit['fields[body][settings_edit_form][settings][ft][lb]'] = $text;
}
if (!empty($class)) {
$edit['fields[body][settings_edit_form][settings][ft][classes][]'] = $class;
}
if ($hide_colon) {
$edit['fields[body][settings_edit_form][settings][ft][lb-col]'] = '1';
}
$this->dsEditFormatterSettings($edit);
}
/**
* Test basic node display fields.
*/
function testDSNodeEntity() {
$node = $this->entitiesTestSetup();
$node_author = user_load($node->uid);
// Test theme_hook_suggestions in ds_entity_variables().
$this->backdropGet('node/' . $node->nid, array('query' => array('store' => 1)));
$cache = cache_get('ds_test');
$this->assertTrue(!empty($cache));
$hook_suggestions = $cache->data['theme_hook_suggestions'];
$expected_hook_suggestions = array(
'node__article',
'node__1',
'ds_2col_stacked',
'ds_2col_stacked__node',
'ds_2col_stacked__node_full',
'ds_2col_stacked__node_article',
'ds_2col_stacked__node_article_full',
'ds_2col_stacked__node__1'
);
$this->assertEqual($hook_suggestions, $expected_hook_suggestions);
// Look at node and verify token and block field.
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('view-mode-full', 'Template file found (in full view mode)');
$this->assertRaw('<div class="token-class">' . $node->title . '</span>', t('Token field found'));
$this->assertRaw('I am a PHP field', t('PHP field found'));
$this->assertRaw('group-header', 'Template found (region header)');
$this->assertRaw('group-footer', 'Template found (region footer)');
$this->assertRaw('group-left', 'Template found (region left)');
$this->assertRaw('group-right', 'Template found (region right)');
$this->assertPattern('/<div[^>]*>Submitted[^<]*<a[^>]+href=".*' . 'user\/' . $node_author->uid . '"[^>]*>' . check_plain($node_author->name) . '<\/a>.<\/div>/', t('Submitted by line found'));
// Configure teaser layout.
$teaser = array(
'additional_settings[layout]' => 'ds_2col',
);
$teaser_assert = array(
'regions' => array(
'left' => '<td colspan="8">' . t('Left') . '</td>',
'right' => '<td colspan="8">' . t('Right') . '</td>',
),
);
$this->dsSelectLayout($teaser, $teaser_assert, 'admin/structure/types/manage/article/display/teaser');
$fields = array(
'fields[token_field][region]' => 'left',
'fields[php_field][region]' => 'left',
'fields[body][region]' => 'right',
'fields[links][region]' => 'right',
);
$this->dsConfigureUI($fields, 'admin/structure/types/manage/article/display/teaser');
// Switch view mode on full node page.
$edit = array('ds_switch' => 'teaser');
$this->backdropPost('node/' . $node->nid . '/edit', $edit, t('Save'));
$this->assertRaw('view-mode-teaser', 'Switched to teaser mode');
$this->assertRaw('group-left', 'Template found (region left)');
$this->assertRaw('group-right', 'Template found (region right)');
$this->assertNoRaw('group-header', 'Template found (no region header)');
$this->assertNoRaw('group-footer', 'Template found (no region footer)');
$edit = array('ds_switch' => 'default');
$this->backdropPost('node/' . $node->nid . '/edit', $edit, t('Save'));
$this->assertRaw('view-mode-full', 'Switched to full mode again');
// Test all options of a block field.
$block = array(
'name' => 'Test block field',
'field' => 'test_block_field',
'entities[node]' => '1',
'block' => 'node|recent',
'block_render' => DS_BLOCK_TEMPLATE,
);
$this->dsCreateBlockField($block);
$fields = array(
'fields[test_block_field][region]' => 'left',
'fields[token_field][region]' => 'hidden',
'fields[php_field][region]' => 'hidden',
'fields[body][region]' => 'hidden',
'fields[links][region]' => 'hidden',
);
$this->dsConfigureUI($fields);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('<h2>Recent content</h2>');
$block = array(
'block_render' => DS_BLOCK_TITLE_CONTENT,
);
$this->dsCreateBlockField($block, 'admin/structure/ds/fields/manage_block/test_block_field', FALSE);
$this->backdropGet('node/' . $node->nid);
$this->assertNoRaw('<h2>Recent content</h2>');
$this->assertRaw('Recent content');
$block = array(
'block_render' => DS_BLOCK_CONTENT,
);
$this->dsCreateBlockField($block, 'admin/structure/ds/fields/manage_block/test_block_field', FALSE);
$this->backdropGet('node/' . $node->nid);
$this->assertNoRaw('<h2>Recent content</h2>');
$this->assertNoRaw('Recent content');
// Remove the page title (we'll use the switch view mode functionality too for this).
$edit = array('additional_settings[ds_page_title][ds_page_title_options][page_option_type]' => '1');
$this->dsConfigureUI($edit, 'admin/structure/types/manage/article/display/teaser');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('<h1 class="title" id="page-title">
'. $node->title . ' </h1>');
$edit = array('ds_switch' => 'teaser');
$this->backdropPost('node/' . $node->nid . '/edit', $edit, t('Save'));
$this->backdropGet('node/' . $node->nid);
$this->assertNoRaw('<h1 class="title" id="page-title">
'. $node->title . ' </h1>');
// Use page title substitutions.
$edit = array('additional_settings[ds_page_title][ds_page_title_options][page_option_type]' => '2', 'additional_settings[ds_page_title][ds_page_title_options][page_option_title]' => 'Change title: %node:type');
$this->dsConfigureUI($edit, 'admin/structure/types/manage/article/display/teaser');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('<h1 class="title" id="page-title">
Change title: '. $node->type . ' </h1>');
$edit = array('additional_settings[ds_page_title][ds_page_title_options][page_option_type]' => '0');
$this->dsConfigureUI($edit, 'admin/structure/types/manage/article/display/teaser');
// Go to home page, page title shouldn't bleed here
// see http://drupal.org/node/1446554.
$edit = array('ds_switch' => 'default');
$this->backdropPost('node/' . $node->nid . '/edit', $edit, t('Save'));
$edit = array('additional_settings[ds_page_title][ds_page_title_options][page_option_type]' => '2', 'additional_settings[ds_page_title][ds_page_title_options][page_option_title]' => 'Bleed title: %node:type');
$this->dsConfigureUI($edit, 'admin/structure/types/manage/article/display');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('<h1 class="title" id="page-title">
Bleed title: article </h1>');
$this->backdropGet('node');
$this->assertNoText('Bleed title');
// Test revisions. Enable the revision view mode
$edit = array('additional_settings[modes][view_modes_custom][revision]' => '1');
$this->backdropPost('admin/structure/types/manage/article/display', $edit, t('Save'));
// Select layout and configure fields.
$edit = array(
'additional_settings[layout]' => 'ds_2col',
);
$assert = array(
'regions' => array(
'left' => '<td colspan="8">' . t('Left') . '</td>',
'right' => '<td colspan="8">' . t('Right') . '</td>',
),
);
$this->dsSelectLayout($edit, $assert, 'admin/structure/types/manage/article/display/revision');
$edit = array(
'fields[body][region]' => 'left',
'fields[links][region]' => 'right',
'fields[author][region]' => 'right',
);
$this->dsConfigureUI($edit, 'admin/structure/types/manage/article/display/revision');
// Create revision of the node.
$edit = array(
'revision' => TRUE,
'log' => 'Test revision',
);
$this->backdropPost('node/' . $node->nid . '/edit', $edit, t('Save'));
$this->assertText('Revisions');
// Assert revision is using 2 col template.
$this->backdropGet('node/' . $node->nid . '/revisions/1/view');
$this->assertText('Body:', 'Body label');
// Change title of revision.
$edit = array('additional_settings[ds_page_title][ds_page_title_options][page_option_type]' => '2', 'additional_settings[ds_page_title][ds_page_title_options][page_option_title]' => 'Custom revision title');
$this->dsConfigureUI($edit, 'admin/structure/types/manage/article/display/revision');
$this->backdropGet('node/' . $node->nid . '/revisions/1/view');
$this->assertText('Custom revision title', 'Custom title on revision view mode');
// Assert full view is using stacked template.
$this->backdropGet('node/' . $node->nid);
$this->assertNoText('Body:', 'Body label');
// Test formatter limit on article with tags.
$edit = array(
'ds_switch' => 'default',
'field_tags[und]' => 'Tag 1, Tag 2'
);
$this->backdropPost('node/' . $node->nid . '/edit', $edit, t('Save'));
$edit = array(
'fields[field_tags][region]' => 'right',
);
$this->dsConfigureUI($edit, 'admin/structure/types/manage/article/display');
$this->backdropGet('node/' . $node->nid);
$this->assertText('Tag 1');
$this->assertText('Tag 2');
$edit = array(
'fields[field_tags][format][limit]' => '1',
);
$this->dsConfigureUI($edit, 'admin/structure/types/manage/article/display');
$this->backdropGet('node/' . $node->nid);
$this->assertText('Tag 1');
$this->assertNoText('Tag 2');
// Test check_plain() on ds_render_field() with the title field.
$edit = array(
'fields[title][region]' => 'right',
);
$this->dsConfigureUI($edit, 'admin/structure/types/manage/article/display');
$edit = array(
'title' => 'Hi, I am an article <script>alert(\'with a javascript tag in the title\');</script>',
);
$this->backdropPost('node/' . $node->nid . '/edit', $edit, t('Save'));
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('<h2>Hi, I am an article <script>alert('with a javascript tag in the title');</script></h2>');
}
/**
* Tests on field templates.
*/
function testDSFieldTemplate() {
// Get a node.
$node = $this->entitiesTestSetup('hidden');
$body_field = $node->body[$node->language][0]['value'];
// -------------------------
// Default theming function.
// -------------------------
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"field field-name-body field-type-text-with-summary field-label-hidden\"><div class=\"field-items\"><div class=\"field-item even\" property=\"content:encoded\"><p>" . $body_field . "</p>
</div></div></div>");
$this->entitiesSetLabelClass('above');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"field field-name-body field-type-text-with-summary field-label-above\"><div class=\"field-label\">Body: </div><div class=\"field-items\"><div class=\"field-item even\" property=\"content:encoded\"><p>" . $body_field . "</p>
</div></div></div>");
$this->entitiesSetLabelClass('above', 'My body');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"field field-name-body field-type-text-with-summary field-label-above\"><div class=\"field-label\">My body: </div><div class=\"field-items\"><div class=\"field-item even\" property=\"content:encoded\"><p>" . $body_field . "</p>
</div></div></div>");
$this->entitiesSetLabelClass('hidden', '', 'test_field_class');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"field field-name-body field-type-text-with-summary field-label-hidden test_field_class\"><div class=\"field-items\"><div class=\"field-item even\" property=\"content:encoded\"><p>" . $body_field . "</p>
</div></div></div>");
$this->entitiesClearFieldSettings();
// -----------------------
// Reset theming function.
// -----------------------
$edit = array(
'additional_settings[fs1][ft-default]' => 'theme_ds_field_reset',
);
$this->backdropPost('admin/structure/ds/list/extras', $edit, t('Save configuration'));
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<p>" . $body_field . "</p>");
$this->entitiesSetLabelClass('above');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"label-above\">Body: </div><p>" . $body_field . "</p>");
$this->entitiesSetLabelClass('inline');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"label-inline\">Body: </div><p>" . $body_field . "</p>");
$this->entitiesSetLabelClass('above', 'My body');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"label-above\">My body: </div><p>" . $body_field . "</p>");
$this->entitiesSetLabelClass('inline', 'My body');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"label-inline\">My body: </div><p>" . $body_field . "</p>");
variable_set('ft-kill-colon', TRUE);
$this->refreshVariables();
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"label-inline\">My body</div><p>" . $body_field . "</p>");
$this->entitiesSetLabelClass('hidden');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<p>" . $body_field . "</p>");
$this->entitiesClearFieldSettings();
// ----------------------
// Custom field function.
// ----------------------
// With outer wrapper.
$edit = array(
'fields[body][settings_edit_form][settings][ft][func]' => 'theme_ds_field_expert',
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div><p>" . $body_field . "</p>
</div> </div>");
// With outer div wrapper and class.
$edit = array(
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][ow-cl]' => 'ow-class'
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class\"><p>" . $body_field . "</p>
</div> </div>");
// With outer span wrapper and class.
$edit = array(
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'span',
'fields[body][settings_edit_form][settings][ft][ow-cl]' => 'ow-class-2'
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<span class=\"ow-class-2\"><p>" . $body_field . "</p>
</span> </div>");
// Clear field settings.
$this->entitiesClearFieldSettings();
// With outer wrapper and field items wrapper.
$edit = array(
'fields[body][settings_edit_form][settings][ft][func]' => 'theme_ds_field_expert',
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][fis]' => '1',
'fields[body][settings_edit_form][settings][ft][fis-el]' => 'div'
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div><div><p>" . $body_field . "</p>
</div></div> </div>");
// With outer wrapper and field items div wrapper with class.
$edit = array(
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][fis]' => '1',
'fields[body][settings_edit_form][settings][ft][fis-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][fis-cl]' => 'fi-class'
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div><div class=\"fi-class\"><p>" . $body_field . "</p>
</div></div> </div>");
// With outer wrapper and field items span wrapper and class.
$edit = array(
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][fis]' => '1',
'fields[body][settings_edit_form][settings][ft][fis-el]' => 'span',
'fields[body][settings_edit_form][settings][ft][fis-cl]' => 'fi-class'
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div><span class=\"fi-class\"><p>" . $body_field . "</p>
</span></div> </div>");
// With outer wrapper class and field items span wrapper and class.
$edit = array(
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][ow-cl]' => 'ow-class',
'fields[body][settings_edit_form][settings][ft][fis]' => '1',
'fields[body][settings_edit_form][settings][ft][fis-el]' => 'span',
'fields[body][settings_edit_form][settings][ft][fis-cl]' => 'fi-class'
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class\"><span class=\"fi-class\"><p>" . $body_field . "</p>
</span></div> </div>");
// With outer wrapper span class and field items span wrapper and class.
$edit = array(
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'span',
'fields[body][settings_edit_form][settings][ft][ow-cl]' => 'ow-class',
'fields[body][settings_edit_form][settings][ft][fis]' => '1',
'fields[body][settings_edit_form][settings][ft][fis-el]' => 'span',
'fields[body][settings_edit_form][settings][ft][fis-cl]' => 'fi-class-2'
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<span class=\"ow-class\"><span class=\"fi-class-2\"><p>" . $body_field . "</p>
</span></span> </div>");
// Clear field settings.
$this->entitiesClearFieldSettings();
// With field item div wrapper.
$edit = array(
'fields[body][settings_edit_form][settings][ft][func]' => 'theme_ds_field_expert',
'fields[body][settings_edit_form][settings][ft][fi]' => '1',
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div><p>" . $body_field . "</p>
</div> </div>");
// With field item span wrapper.
$edit = array(
'fields[body][settings_edit_form][settings][ft][fi]' => '1',
'fields[body][settings_edit_form][settings][ft][fi-el]' => 'span',
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<span><p>" . $body_field . "</p>
</span> </div>");
// With field item span wrapper and class and odd even.
$edit = array(
'fields[body][settings_edit_form][settings][ft][fi]' => '1',
'fields[body][settings_edit_form][settings][ft][fi-el]' => 'span',
'fields[body][settings_edit_form][settings][ft][fi-cl]' => 'fi-class',
'fields[body][settings_edit_form][settings][ft][fi-odd-even]' => '1',
'fields[body][settings_edit_form][settings][ft][fi-first-last]' => '1',
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<span class=\"odd fi-class first last\"><p>" . $body_field . "</p>
</span> </div>");
// With fis and fi.
$edit = array(
'fields[body][settings_edit_form][settings][ft][fis]' => '1',
'fields[body][settings_edit_form][settings][ft][fis-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][fis-cl]' => 'fi-class-2',
'fields[body][settings_edit_form][settings][ft][fi]' => '1',
'fields[body][settings_edit_form][settings][ft][fi-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][fi-cl]' => 'fi-class',
'fields[body][settings_edit_form][settings][ft][fi-odd-even]' => '1',
'fields[body][settings_edit_form][settings][ft][fi-first-last]' => '1',
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"fi-class-2\"><div class=\"odd fi-class first last\"><p>" . $body_field . "</p>
</div></div> </div>");
// With all wrappers.
$edit = array(
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][ow-cl]' => 'ow-class',
'fields[body][settings_edit_form][settings][ft][fis]' => '1',
'fields[body][settings_edit_form][settings][ft][fis-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][fis-cl]' => 'fi-class-2',
'fields[body][settings_edit_form][settings][ft][fi]' => '1',
'fields[body][settings_edit_form][settings][ft][fi-el]' => 'span',
'fields[body][settings_edit_form][settings][ft][fi-cl]' => 'fi-class',
'fields[body][settings_edit_form][settings][ft][fi-odd-even]' => '1',
'fields[body][settings_edit_form][settings][ft][fi-first-last]' => '1',
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class\"><div class=\"fi-class-2\"><span class=\"odd fi-class first last\"><p>" . $body_field . "</p>
</span></div></div> </div>");
// With all wrappers and attributes.
$edit = array(
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][ow-cl]' => 'ow-class',
'fields[body][settings_edit_form][settings][ft][ow-at]' => 'name="ow-att"',
'fields[body][settings_edit_form][settings][ft][fis]' => '1',
'fields[body][settings_edit_form][settings][ft][fis-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][fis-cl]' => 'fi-class-2',
'fields[body][settings_edit_form][settings][ft][fis-at]' => 'name="fis-att"',
'fields[body][settings_edit_form][settings][ft][fi]' => '1',
'fields[body][settings_edit_form][settings][ft][fi-el]' => 'span',
'fields[body][settings_edit_form][settings][ft][fi-cl]' => 'fi-class',
'fields[body][settings_edit_form][settings][ft][fi-at]' => 'name="fi-at"',
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class\" name=\"ow-att\"><div class=\"fi-class-2\" name=\"fis-att\"><span class=\"odd fi-class first last\" name=\"fi-at\"><p>" . $body_field . "</p>
</span></div></div> </div>");
// Remove attributes.
$edit = array(
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][ow-cl]' => 'ow-class',
'fields[body][settings_edit_form][settings][ft][ow-at]' => '',
'fields[body][settings_edit_form][settings][ft][fis]' => '1',
'fields[body][settings_edit_form][settings][ft][fis-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][fis-cl]' => 'fi-class-2',
'fields[body][settings_edit_form][settings][ft][fis-at]' => '',
'fields[body][settings_edit_form][settings][ft][fi]' => '1',
'fields[body][settings_edit_form][settings][ft][fi-el]' => 'span',
'fields[body][settings_edit_form][settings][ft][fi-cl]' => 'fi-class',
'fields[body][settings_edit_form][settings][ft][fi-at]' => '',
);
$this->dsEditFormatterSettings($edit);
// Label tests with custom function.
$this->entitiesSetLabelClass('above');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class\"><div class=\"label-above\">Body: </div><div class=\"fi-class-2\"><span class=\"odd fi-class first last\"><p>" . $body_field . "</p>
</span></div></div> </div>");
$this->entitiesSetLabelClass('inline');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class\"><div class=\"label-inline\">Body: </div><div class=\"fi-class-2\"><span class=\"odd fi-class first last\"><p>" . $body_field . "</p>
</span></div></div> </div>");
$this->entitiesSetLabelClass('above', 'My body');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class\"><div class=\"label-above\">My body: </div><div class=\"fi-class-2\"><span class=\"odd fi-class first last\"><p>" . $body_field . "</p>
</span></div></div> </div>");
$this->entitiesSetLabelClass('inline', 'My body');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class\"><div class=\"label-inline\">My body: </div><div class=\"fi-class-2\"><span class=\"odd fi-class first last\"><p>" . $body_field . "</p>
</span></div></div> </div>");
$this->entitiesSetLabelClass('inline', 'My body', '', TRUE);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class\"><div class=\"label-inline\">My body</div><div class=\"fi-class-2\"><span class=\"odd fi-class first last\"><p>" . $body_field . "</p>
</span></div></div> </div>");
$this->entitiesSetLabelClass('hidden');
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class\"><div class=\"fi-class-2\"><span class=\"odd fi-class first last\"><p>" . $body_field . "</p>
</span></div></div> </div>");
// Test default classes on outer wrapper.
$edit = array(
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][ow-cl]' => 'ow-class',
'fields[body][settings_edit_form][settings][ft][ow-def-cl]' => '1',
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class field field-name-body field-type-text-with-summary field-label-hidden\"><div class=\"fi-class-2\"><span class=\"odd fi-class first last\"><p>" . $body_field . "</p>
</span></div></div> </div>");
// Test default attributes on field item.
$edit = array(
'fields[body][settings_edit_form][settings][ft][ow]' => '1',
'fields[body][settings_edit_form][settings][ft][ow-el]' => 'div',
'fields[body][settings_edit_form][settings][ft][ow-cl]' => 'ow-class',
'fields[body][settings_edit_form][settings][ft][ow-def-cl]' => '1',
'fields[body][settings_edit_form][settings][ft][fi-def-at]' => '1',
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
<div class=\"ow-class field field-name-body field-type-text-with-summary field-label-hidden\"><div class=\"fi-class-2\"><span class=\"odd fi-class first last\" property=\"content:encoded\"><p>" . $body_field . "</p>
</span></div></div> </div>");
// Use the test field theming function to test that this function is
// registered in the theme registry through ds_extras_theme().
$edit = array(
'fields[body][settings_edit_form][settings][ft][func]' => 'ds_test_theming_function',
);
$this->dsEditFormatterSettings($edit);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw("<div class=\"group-right\">
Testing field output through custom function </div>");
}
}
class dsExportablesTests extends dsBaseTest {
/**
* Enables the exportables module.
*/
function dsExportablesSetup() {
module_enable(array('ds_exportables_test'));
backdrop_flush_all_caches();
}
// Test view modes.
function testDSExportablesViewmodes() {
$this->dsExportablesSetup();
// Find a default view mode on admin screen.
$this->backdropGet('admin/structure/ds/view_modes');
$this->assertText('Test exportables', t('Exportables view mode found on admin screen.'));
// Find default view mode on layout screen.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertText('Test exportables', t('Exportables view mode found on display screen.'));
// Override default view mode.
$edit = array(
'name' => 'Testing 2',
);
$this->backdropPost('admin/structure/ds/view_modes/manage/test_exportables', $edit, t('Save'));
$this->assertText(t('The view mode Testing 2 has been saved'), t('Exportables label updated'));
$this->assertText(t('Revert'), t('Revert button found.'));
// Find default view mode on layout screen.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertText('Testing 2', t('Updated exportables view mode found on display screen.'));
// Revert the view mode.
$this->backdropPost('admin/structure/ds/view_modes/revert/test_exportables', array(), t('Revert'));
$this->assertText(t('The view mode Testing 2 has been reverted'), t('Testing view mode reverted'));
$this->assertText('Test exportables', t('Exportables view mode found on admin screen.'));
// Assert the view mode is gone at the manage display screen.
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertNoText('Testing 2', t('Overrided exportables view mode not found on display screen.'));
$this->assertText('Test exportables', t('Default exportables view mode found on display screen.'));
}
// Test layout and field settings configuration.
function testDSExportablesLayoutFieldsettings() {
$this->dsExportablesSetup();
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertNoText(t('This layout is overridden. Click to revert to default settings.'));
$settings = array(
'type' => 'article',
'title' => 'Exportable'
);
$node = $this->backdropCreateNode($settings);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('group-left', 'Left region found');
$this->assertRaw('group-right', 'Right region found');
$this->assertNoRaw('group-header', 'No header region found');
$this->assertNoRaw('group-footer', 'No footer region found');
$this->assertRaw('<h3><a href="'. url('node/1') . '" class="active">Exportable</a></h3>', t('Default title with h3 found'));
$this->assertRaw('<a href="' . url('node/1') . '" class=" active">Read more</a>', t('Default read more found'));
// Override default layout.
$layout = array(
'additional_settings[layout]' => 'ds_2col_stacked',
);
$assert = array(
'regions' => array(
'header' => '<td colspan="8">' . t('Header') . '</td>',
'left' => '<td colspan="8">' . t('Left') . '</td>',
'right' => '<td colspan="8">' . t('Right') . '</td>',
'footer' => '<td colspan="8">' . t('Footer') . '</td>',
),
);
$fields = array(
'fields[post_date][region]' => 'header',
'fields[author][region]' => 'left',
'fields[links][region]' => 'left',
'fields[body][region]' => 'right',
'fields[comments][region]' => 'footer',
);
$this->dsSelectLayout($layout, $assert);
$this->assertText(t('This layout is overridden. Click to revert to default settings.'));
$this->dsConfigureUI($fields);
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('group-left', 'Left region found');
$this->assertRaw('group-right', 'Left region found');
$this->assertRaw('group-header', 'Left region found');
$this->assertRaw('group-footer', 'Left region found');
// Revert.
$edit = array();
$this->backdropPost('admin/structure/ds/revert-layout/node|article|default', $edit, t('Revert'), array('query' => array('destination' => 'admin/structure/types/manage/article/display')));
$this->backdropGet('node/' . $node->nid);
$this->assertRaw('group-left', 'Left region found');
$this->assertRaw('group-right', 'Left region found');
$this->assertNoRaw('group-header', 'Left region found');
$this->assertNoRaw('group-footer', 'Left region found');
$this->assertRaw('<h3><a href="'. url('node/1') . '" class="active">Exportable</a></h3>', t('Default title with h3 found'));
$this->assertRaw('<a href="' . url('node/1') . '" class=" active">Read more</a>', t('Default read more found'));
}
// Test custom field exportables.
function testDSExportablesCustomFields() {
$this->dsExportablesSetup();
// Look for default custom field.
$this->backdropGet('admin/structure/ds/fields');
$this->assertText('Exportable field');
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertText('Exportable field');
// Override custom field.
// Update testing label
$edit = array(
'name' => 'Overridden field',
);
$this->backdropPost('admin/structure/ds/fields/manage_custom/ds_exportable_field', $edit, t('Save'));
$this->assertText(t('The field Overridden field has been saved'), t('Default exportable field label updated'));
$this->assertText('Overridden field');
$this->assertNoText('Exportable field');
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertText('Overridden field');
$this->assertNoText('Exportable field');
// Revert.
$edit = array();
$this->backdropPost('admin/structure/ds/fields/revert/ds_exportable_field', $edit, t('Revert'));
$this->assertText('The field Overridden field has been reverted', t('Field reverted'));
$this->assertText('Exportable field');
$this->backdropGet('admin/structure/types/manage/article/display');
$this->assertNoText('Overridden field');
$this->assertText('Exportable field');
}
}
class dsFormTests extends dsBaseTest {
/**
* Forms tests.
*/
function testDSForms() {
// Create a node.
$node = $this->backdropCreateNode(array('type' => 'article', 'promote' => FALSE));
// Configure teaser layout.
$form = array(
'additional_settings[layout]' => 'ds_2col_stacked',
);
$form_assert = array(
'regions' => array(
'header' => '<td colspan="8">' . t('Header') . '</td>',
'left' => '<td colspan="8">' . t('Left') . '</td>',
'right' => '<td colspan="8">' . t('Right') . '</td>',
'footer' => '<td colspan="8">' . t('Footer') . '</td>',
),
);
$this->dsSelectLayout($form, $form_assert, 'admin/structure/types/manage/article/fields');
$fields = array(
'fields[title][region]' => 'header',
'fields[body][region]' => 'left',
'fields[field_image][region]' => 'right',
'fields[field_tags][region]' => 'right',
);
$this->dsConfigureUI($fields, 'admin/structure/types/manage/article/fields');
// Inspect the node.
$this->backdropGet('node/' . $node->nid . '/edit');
$this->assertRaw('ds_2col_stacked', 'ds-form class added');
$this->assertRaw('group-header', 'Template found (region header)');
$this->assertRaw('group-left', 'Template found (region left)');
$this->assertRaw('group-right', 'Template found (region right)');
$this->assertRaw('group-footer', 'Template found (region footer)');
$this->assertRaw('edit-title', 'Title field found');
$this->assertRaw('edit-submit', 'Submit field found');
$this->assertRaw('edit-field-tags-und', 'Tags field found');
$this->assertRaw('edit-log', 'Revision log found');
}
}
class dsSearchTests extends dsBaseTest {
function testDSSearch() {
// Create nodes.
$i = 15;
while ($i > 0) {
$settings = array(
'title' => 'title' . $i,
'type' => 'article',
'promote' => 1,
);
$this->backdropCreateNode($settings);
$i--;
}
// Set default search.
$edit = array(
'search_default_module' => 'ds_search',
);
$this->backdropPost('admin/config/search/settings', $edit, t('Save configuration'));
// Run cron.
$this->cronRun();
$this->backdropGet('admin/config/search/settings');
$this->assertText(t('100% of the site has been indexed. There are 0 items left to index.'), 'Site has been indexed');
// Configure search result view mode.
$svm = array('additional_settings[modes][view_modes_custom][search_result]' => 'search_result');
$this->dsConfigureUI($svm);
$layout = array(
'additional_settings[layout]' => 'ds_2col_stacked',
);
$assert = array(
'regions' => array(
'header' => '<td colspan="8">' . t('Header') . '</td>',
'left' => '<td colspan="8">' . t('Left') . '</td>',
'right' => '<td colspan="8">' . t('Right') . '</td>',
'footer' => '<td colspan="8">' . t('Footer') . '</td>',
),
);
$this->dsSelectLayout($layout, $assert, 'admin/structure/types/manage/article/display/search_result');
$fields = array(
'fields[title][region]' => 'header',
'fields[post_date][region]' => 'header',
'fields[author][region]' => 'left',
'fields[body][region]' => 'right',
'fields[node_link][region]' => 'footer',
);
$this->dsConfigureUI($fields, 'admin/structure/types/manage/article/display/search_result');
// Configure ds search.
$edit = array('user_override_search_page' => '1');
$this->backdropPost('admin/structure/ds/list/search', $edit, t('Save configuration'));
// Let's search.
$this->backdropGet('search/content/title1');
$this->assertNoRaw('/search/node/title1');
$this->assertRaw('view-mode-search_result', 'Search view mode found');
$this->assertRaw('group-left', 'Search template found');
$this->assertRaw('group-right', 'Search template found');
$this->assertNoText(t('Advanced search'), 'No advanced search found');
$edit = array('ds_search_node_form_alter' => '1');
$this->backdropPost('admin/structure/ds/list/search', $edit, t('Save configuration'));
$this->backdropGet('search/content/title1');
$this->assertText(t('Advanced search'), 'Advanced search found');
// Search on user.
// Configure user. We'll just do default.
$layout = array(
'additional_settings[layout]' => 'ds_2col_stacked',
);
$assert = array(
'regions' => array(
'header' => '<td colspan="8">' . t('Header') . '</td>',
'left' => '<td colspan="8">' . t('Left') . '</td>',
'right' => '<td colspan="8">' . t('Right') . '</td>',
'footer' => '<td colspan="8">' . t('Footer') . '</td>',
),
);
$this->dsSelectLayout($layout, $assert, 'admin/config/people/accounts/display');
$fields = array(
'fields[name][region]' => 'left',
'fields[summary][region]' => 'right',
);
$this->dsConfigureUI($fields, 'admin/config/people/accounts/display');
$this->backdropGet('search/user/' . $this->admin_user->name);
$this->assertRaw('view-mode-search_result', 'Search view mode found');
$this->assertRaw('group-left', 'Search template found');
$this->assertRaw('group-right', 'Search template found');
// Test the group by settings.
$article = array(
'title' => 'group article 1',
'type' => 'article',
'promote' => 1,
);
$this->backdropCreateNode($article);
$page = array(
'title' => 'group page 1',
'type' => 'page',
'promote' => 1,
);
$this->backdropCreateNode($page);
$this->cronRun();
$edit = array(
'ds_search_group_by_type' => '1'
);
$this->backdropPost('admin/structure/ds/list/search', $edit, t('Save configuration'));
// Let's search.
$this->backdropGet('search/content/group');
$this->assertRaw('Results for article');
$this->assertRaw('Results for basic page');
$edit = array(
'ds_search_group_by_type_settings[article][label]' => 'Article results',
);
$this->backdropPost('admin/structure/ds/list/search', $edit, t('Save configuration'));
$this->backdropGet('search/content/group');
$this->assertNoRaw('Results for article');
$this->assertRaw('Article results');
$this->assertRaw('Results for basic page');
$edit = array(
'ds_search_group_by_type_settings[page][status]' => FALSE,
'ds_search_group_by_type_settings[article][label]' => '',
);
$this->backdropPost('admin/structure/ds/list/search', $edit, t('Save configuration'));
$this->backdropGet('search/content/group');
$this->assertNoRaw('Article results');
$this->assertNoRaw('Results for basic page');
$this->assertRaw('Other');
}
}
|
<?php
namespace App\Models;
use App\Exceptions\WrongPasswordException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Http\Response;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\HasApiTokens;
/**
* @mixin Builder
*/
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
'company_id',
'phone_number',
'role'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
/**
* @param string $password
* @param string $storedPassword
* @return void
* @throws WrongPasswordException
*/
public final static function attempt(string $password, string $storedPassword): void
{
if (!Hash::check($password, $storedPassword)) {
throw new WrongPasswordException('Invalid password', Response::HTTP_LOCKED);
}
}
/**
* @param string $validated
* @param Model|User $user
* @return string
*/
public static function roleType(string $validated, Model|User $user): string
{
return $validated == config('constants.ADMIN_NAME') ?
$user->createToken(config('constants.USER_TOKEN_ADMIN'), config('constants.ADMIN_ABILITIES'))->plainTextToken :
$user->createToken(config('constants.USER_TOKEN_USER'), config('constants.USER_ABILITIES'))->plainTextToken;
}
public final function company()
{
return $this->belongsTo(Company::class);
}
}
|
# Denoising Autoencoder for waveform data
This packages contains python scripts to train a neural network for the denoising of waveform data, as used in the publication "Deep neural network based denoising of regional seismic waveforms and impact on analysis of North Korean nuclear tests".
This package is based on the work by
```
* Heuel, J. & Friederich, W. Suppression of wind turbine noise from seismological data using nonlinear thresholding and denoising autoencoder Journal of Seismology, 2022 (https://github.com/JanisHe/seismic_denoiser)
```
and also on:
* Zhu, W.; Mousavi, S. M. & Beroza, G. C. Seismic signal denoising and decomposition using deep neural networks IEEE Transactions on Geoscience and Remote Sensing, IEEE, 2019, 57, 9476-9488
* Tibi, R.; Hammond, P.; Brogan, R.; Young, C. J. & Koper, K. Deep Learning Denoising Applied to Regional Distance Seismic Data in Utah Bulletin of the Seismological Society of America, 2021
# Installation Requirements
Before using the package, ensure that the following dependencies are installed:
* Numpy
* Matplotlib
* Scipy
* Tensorflow >= 2.0
* Obspy
* Joblib
* Pandas
* tqdm
#### Denoise seismograms
The example script "example_denoise.py" denoises all waveforms in an folder "input" using a IMS network trained P-phase denoiser from REB catalog data for events around North Korea.
If you want to use other trained models you have to change the model filename (*h5) and the config filename (*config).
Models delivered here are:
```
IMS_P = General IMS data trained P-phase denoiser model; trained with 60s duration time windows at 20 Hz
IMS_LP = General IMS data trained long period model for surface and S-waves; trained with 360s duration time windows at 20Hz
hydro_IMS = Hydroacustic P-phase denoiser, trained with 60s windows at 100 Hz
```
Furthermore station specific trained models, each trained with 60s windows at 20 Hz sampling rate are available:
```
IMS_model_bjt = BJT station specific P-phase denoiser
IMS_model_jnu = JNU station specific P-phase denoiser
IMS_model_jow = JOW station specific P-phase denoiser
IMS_model_KLR = KLR station specific P-phase denoiser
IMS_model_mja = MJA station specific P-phase denoiser
IMS_model_usa = USA0B station specific P-phase denoiser
IMS_model_ks31 = KS31 station specific P-phase denoiser
```
If your waveform record is longer than your waveform record from the training dataset, the longer time series is split into
overlapping segments, e.g. 60 s segments. Each of these segments is denoised and the overlapping segments are
merged to get one denoises time series.
The script `./denoiser/denoiser_utils.py` contains the function `denoising_stream` that removes the noise
from all traces in a obspy stream object. For more details please read the function description.
You can use the pretrained model and config-file to suppress noise from your data. Try to run the following code:
```
from obspy import read, UTCDateTime
from denoiser.denoise_utils import denoising_stream
st = read(your data) # Read your waveform data here
st_de = st.copy() # Create a copy of your obspy stream
st_de = denoising_stream(stream=st, model_filename="Models/IMS_P.h5",
config_filename="config/IMS_P.config")
```
st_de will then be a list of signal and noise, in this order, for each trace in the stream. Therefore e.g. std_de[0][0] is the predicted signal of the first data in stream.
Compare your original stream and the denoised stream whether some noise is removed from the data.
"denoise_hydro.py" is set to denoise IMS hydroacustic data.
#### Training of own model
Create your own training dataset, that contains earthquake data with an high SNR and noise data. Both datasets
are in two different directories, have the same length and sampling frequency. For the length and sampling frequency of a P-wave denoiser
60 s windows and 20 or 100 Hz are recommended.
For earthquake data, the STanford EArthquake Dataset (STEAD) is a recommended starting point (https://github.com/smousavi05/STEAD), however in this publication the IMS network and REB catalog was used.
Note, each waveform is saved as a `.npz` file. If available, the earthquake data contain onsets of P- and S-arrivals
in samples (`itp` and `its`). This only used for validation and in case of waveform records longer then configured sample length to cut the waveform accordingly. Save your data e.g. by the folllowing commands for earthquakes and noise, repectively:
```
np.savez(data=earthquake_data, file=filename, its=0, itp=0, starttime=str(trace.stats.starttime))
np.savez(data=noise_data, file=filename)
```
Afterwards, adjust the parfile and start your training.
```
python run_model_from_parfile.py
```
The training of the example dataset will take a while. It depends whether you run it on CPU or GPU.
The trained model is saved in the directory `./Models` and is named `model.h5`. The config file is saved
in `./config` und `model.config`.
#### Denoise data
Run the function `predict` from file `prediction_*.py` with your created model and
config file. The parameter data_list is a list with numpy arrays for denoising.
Using `prediction.py` only denoises time windows of the same length as for the training dataset,
but in many cases it is necessary to denoise longer time series (see next section).
|
import Chart from "chart.js/auto";
import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom"
import { getData } from "../util/api";
import BackButton from "../component/button/BackButton";
import HomeButton from "../component/button/HomeButton";
import swal from 'sweetalert'
import '../../style/history.css';
import Loader from "../animation/Loader";
export default function CompanyDetail() {
const { symbol } = useParams();
const navigate = useNavigate()
const oneMonthString = new Date();
oneMonthString.setDate(oneMonthString.getDate() - 30);
const [company, setCompany] = useState(null);
let [chart1, setChart1] = useState();
const [predict, setPredict] = useState(0);
// let chart1, chart2;
useEffect(() => {
(async () => {
getData(`${symbol}/profile`).then(responseData => {
const company = responseData.data.data;
console.log(company);
setCompany(company);
}).catch(error => {
try {
const errorMessage = error.request ? JSON.parse(error.request.response).message : error.message;
swal({
title: errorMessage
}).then(() => {
navigate(-1)
})
} catch (exception) {
swal({
title: error.request.response
}).then(() => {
navigate(-1)
})
}
})
getData(`${symbol}/predict`).then(responseData => {
const datas = responseData.data.data.reverse();
const dates = datas.map(data => data.date);
chart1.data.labels = dates;
const harga = datas.map(data => data.close);
setPredict(responseData.data.predicted)
chart1.data.datasets[0].data = harga;
chart1.update();
}).catch((error) => {
try {
const errorMessage = error.request ? JSON.parse(error.request.response).message : error.message;
swal({
title: errorMessage
}).then(() => {
navigate(-1)
})
} catch (exception) {
swal({
title: error.request.response
}).then(() => {
navigate(-1)
})
}
});
const chart1 = new Chart(
document.getElementById('data-harga'),
{
type: 'bar',
options: {
scales: {
y: {
beginAtZero: true,
ticks: {
callback: function (value, index, values) {
return `${value.toLocaleString('id-ID', { style: 'currency', currency: 'IDR' })}`;
}
},
}
},
plugins: {
title: {
text: 'Riwayat Data Saham Perusahaan',
display: true
},
tooltip: {
callbacks: {
label: (context) => {
let value = context.raw;
return `${value.toLocaleString('id-ID', { style: 'currency', currency: 'IDR' })}`;
}
}
}
},
},
data: {
labels: [],
datasets: [
{
data: [],
label: "Harga Saham",
backgroundColor: 'rgba(54, 162, 235, 1)',
borderColor: "red",
fill: true,
},
]
}
}
);
setChart1(chart1);
})();
}, []);
return (
<>
<div className="main-container">
<div className="header-container">
<BackButton />
<h1>Detail Perusahaan</h1>
<HomeButton />
</div>
<div className="content-container company-detail-content">
{
company ? <>
<div className="company-container">
<div className="company-image">
<img src={company.logo} />
</div>
<h1>{company.name}</h1>
</div>
</> : <div className="loader-container">
<Loader />
<p>Mengambil data, mohon tunggu...</p>
</div>
}
<div className="history-container">
<div className="date-container">
<div className="table-riwayat">
<div style={{ width: "90%" }}><canvas id="data-harga"></canvas></div>
</div>
</div>
</div>
<div className="predict-container">
<div className="h1">Prediksi harga besok: {predict.toLocaleString('id-ID', { style: 'currency', currency: 'IDR' })}</div>
</div>
</div>
</div>
</>
)
}
|
"use client";
import React, { useEffect, useState, useTransition } from 'react'
import { Flex, Grid } from '@mantine/core'
import SpecialtySearch from '../specialtySearch'
import { SpecialtyModal } from '../specialtyModal'
import SpecialtyCard from '../specialtyCard'
import { useDebouncedValue, useDisclosure } from '@mantine/hooks';
type Modules = {
module_id: string,
name: string,
value: number,
}[]
type Specialties = {
category_id: string,
category: string,
stat: string,
data: Modules,
}[]
type Props = {
data: Specialties
}
export default function DashBoardCards({ data }: Props) {
//? create specialty
const [createSpecialtyOpened, { open: openCreateSpecialty, close: closeCreateSpecialty }] = useDisclosure()
//?
//? search stuff
const [searchValue, setSearchValue] = useState('')
const [_data, setData] = useState<Specialties | []>([])
const [isPending, startTransition] = useTransition()
//?
useEffect(() => {
startTransition(() => {
setData(
[
...data.filter((item) => item.category.toLowerCase().includes(searchValue.toLowerCase())),
...data.filter((item) => !(item.category.toLowerCase().includes(searchValue.toLowerCase()))),
]
)
})
}, [searchValue])
return (
<>
<Flex justify={'start'} align={'center'} w={'100%'} px={'md'} py={'xl'}>
<div style={{ width: '50%' }} >
<SpecialtySearch isPending={isPending} searchValue={searchValue} setSearchValue={setSearchValue} />
</div>
</Flex>
<Grid align='stretch' justify='flex-start' columns={6} >
{
searchValue.length > 0 && _data.length > 0 && !isPending ?
_data.map((item) => (
<SpecialtyCard category_id={item.category_id} key={item.category} category={item.category} data={item.data} stat={item.stat} />
)) :
data.map((item) => (
<SpecialtyCard category_id={item.category_id} key={item.category} category={item.category} data={item.data} stat={item.stat} />
))
}
</Grid>
<SpecialtyModal close={closeCreateSpecialty} opened={createSpecialtyOpened} />
</>
)
}
|
import {
Component,
OnInit,
Input,
ContentChildren,
QueryList,
AfterContentInit,
ViewChild,
AfterViewInit,
Output,
EventEmitter,
TemplateRef,
} from "@angular/core";
import { GridMaterialColumnComponent } from "./grid-material-column.component";
import { MatTableDataSource, MatTable } from "@angular/material/table";
import { MatSort } from "@angular/material/sort";
import { MatPaginator } from "@angular/material/paginator";
import { DatePipe } from "@angular/common";
import { SelectionModel } from "@angular/cdk/collections";
export interface ExportColumn {
field: string;
caption?: string;
dataType?: "string" | "date" | "number" | "boolean" | "currency"| "link";
dataTypeFormat?: string;
}
@Component({
selector: "app-grid-material",
templateUrl: "./grid-material.component.html",
styleUrls: ["./grid-material.component.scss"],
})
export class GridMaterialComponent
implements OnInit, AfterViewInit, AfterContentInit {
/* table responsive */
@Input() public enableResponsive : boolean = false;
/* Rรฉfรฉrence du template affichant le dรฉtail d'une ligne */
/* Rรฉfรฉrence du template affichant le dรฉtail d'une ligne */
@Input()
public collapseDetail!: TemplateRef<any>;
@Input() public activateCollapseRow: boolean = false;
public activateCollapseAllRow: boolean = false;
public collapseAmount: number = 0;
public collapseColumnName = "collapseCol";
/* Donnรฉes */
@Input() set dataSource(data: any[]) {
this.dataLength = data ? data.length : 0;
if(this.activateCollapseRow){
data = data.map((d) => {
return { ...d, isExpanded: false, isRowCollapse : ( d.isRowCollapse === true || d.isRowCollapse === undefined ? true : false) };
});
}
if (this.dataLength > 0) {
if (!this.internalDataSource) {
if (data) {
let dataSource = data;
this.internalDataSource = new MatTableDataSource(dataSource);
}
} else {
this.internalDataSource.data = data;
this.initPaginatorAndSort();
if (this.multiEdition) {
this.selection.clear();
}
this.selection.clear();
this.table.renderRows();
}
} else {
this.internalDataSource = new MatTableDataSource(data);
}
}
public internalDataSource!: MatTableDataSource<any>;
/* Gestion du trie surt les colonnes */
@Input() public enableSort = false;
@ViewChild(MatSort, { static: false })
public sort!: MatSort;
@ViewChild(MatTable, { static: false })
public table!: MatTable<any>;
/* Liste des colonnes */
/* Liste des colonnes */
@ContentChildren(GridMaterialColumnComponent)
public columns!: QueryList<GridMaterialColumnComponent>;
public displayedColumns: string[] = [];
/* Nom de la clefs primaire*/
/* Nom de la clefs primaire*/
@Input()
public primaryField!: string;
/* Liste des colonnes en mode รฉdition */
public editingItems: any[] = [];
/* Gestion de l'insertion */
/* Ajout du formulaire directement dans le tableau */
@Input() public enableInlineInsert = false;
/* Le formulaire est exclu du tableau*/
@Input() public enableInsert = false;
/* Action sur lajout d'une nouvelle donnรฉe */
@Output() onInsert: EventEmitter<any> = new EventEmitter();
public inserting = false;
/* Pagination */
@Input() public enablePagination = false;
@ViewChild(MatPaginator, { static: false })
public paginator!: MatPaginator;
@Input() public pageSizeOptions: number[] = [10, 25, 50, 100, 250];
@Input() public pageSize = 10;
public dataLength = 0;
@Input() public enableFilter = false;
/* Exporter les donnรฉes du tableau */
@Input() public enableExport = false;
@Input() public exportColumns: ExportColumn[] = [];
@Input() public exportName = "export.csv";
/* Edition multiple */
@Input() public multiEdition = false;
public selection = new SelectionModel<any>(true, []);
@Input()
public templateMultiEdition!: TemplateRef<any>;
public mutliEditionColumnName = "multiEditionCol";
/* footer */
@Input() public enableFooter = false;
/* Actions supplementaires */
/* Actions supplementaires */
@Input()
public tepmplateActionsSupplementaires!: TemplateRef<any>;
@Input() public enableExpandColumn: boolean = false;
@Input() public expandColumns: boolean = false;
@Input() public enableRefresh: boolean = false;
@Output() onRefresh: EventEmitter<any> = new EventEmitter();
@Input() public persisteVisibilityMultiActions = false;
public emptyDataReference: any;
constructor(
private datePipe: DatePipe,
/*private fileExportService: FileExportService*/
) {
this.saveSuccessCallback = this.saveSuccessCallback.bind(this);
this.saveCancelCallback = this.saveCancelCallback.bind(this);
this.enregistrer = this.enregistrer.bind(this);
this.cancel = this.cancel.bind(this);
}
ngOnInit() {
if (!this.primaryField) {
throw new Error("primaryField obligatoire !");
}
}
ngAfterViewInit(): void {
this.initPaginatorAndSort();
this.internalDataSource.filterPredicate = (item: any, filter) => {
const flatLine = this.columns.filter(c => !!c.field && !c.expandable).map(c => {
const data = this.getData(item, c.field);
if (c.dataType === "date" && data) {
return this.datePipe.transform(data, c.dataTypeFormat);
}
return data;
}).join(';').toLowerCase();
console.log("flat", flatLine);
return flatLine.includes(filter);
};
}
ngAfterContentInit(): void {
this.displayedColumns = this.columns
.filter((x) => !x.expandable)
.map((column: GridMaterialColumnComponent) => {
return column.name;
});
if (this.activateCollapseRow === true) {
this.displayedColumns.unshift(this.collapseColumnName);
}
if(this.multiEdition === true){
this.displayedColumns.unshift(this.mutliEditionColumnName);
}
this.emptyDataReference = this.columns.reduce((json: any, value, key) => {
if (value.field) {
json[value.field] = undefined;
}
return json;
}, {});
}
// Handle events
refreshData(): void {
this.onRefresh.emit(event);
}
private initPaginatorAndSort(): void {
setTimeout(() => {
if (this.sort && this.enableSort && this.dataLength > 0) {
this.internalDataSource.sort = this.sort;
this.internalDataSource.sortingDataAccessor = (item, property) => {
return this.getData(item, property);
};
}
if (this.paginator && this.enablePagination) {
this.internalDataSource.paginator = this.paginator;
}
});
}
saveSuccessCallback(data: any) {
data.editing = false;
const source = this.internalDataSource.data;
const index = source.findIndex(
(x) => x[this.primaryField] === data[this.primaryField]
);
source[index] = Object.assign({}, data);
this.internalDataSource.data = source;
this.table.renderRows();
delete this.editingItems[data[this.primaryField]];
}
saveCancelCallback(data: any) {
this.cancel(data);
}
delete(column: GridMaterialColumnComponent, data: any): void {
if (confirm(column.confirmDelete) && column.onDelete) {
column.onDelete.emit(data);
}
}
edit(column: GridMaterialColumnComponent, data: any): void {
this.editingItems[data[this.primaryField]] = { ...data };
if (column.enableInlineEdit) {
data.editing = true;
} else if (column.enableEdit) {
data.editing = false;
column.onEdit.emit({
data: data,
success: this.saveSuccessCallback,
cancel: this.saveCancelCallback,
});
}
}
insert(): void {
if (this.enableInsert) {
this.onInsert.emit();
} else if (this.enableInlineInsert && !this.inserting) {
this.inserting = true;
const source = this.internalDataSource?.data;
source.unshift(Object.assign({ editing: true }, this.emptyDataReference));
this.internalDataSource.data = source;
}
if (this.internalDataSource) {
this.table.renderRows();
}
}
enregistrer(column: GridMaterialColumnComponent, data: any): void {
if (this.inserting) {
this.inserting = false;
this.onInsert.emit(data);
} else if (column.onEdit) {
column.onEdit.emit({
data: data,
success: this.saveSuccessCallback,
cancel: this.saveCancelCallback,
});
}
}
cancel(data: any): void {
if (this.inserting && !data[this.primaryField]) {
this.inserting = false;
const source = this.internalDataSource.data;
this.internalDataSource.data = source.filter((x) => x[this.primaryField]);
} else if (data[this.primaryField]) {
data.editing = false;
const source = this.internalDataSource.data;
const index = source.findIndex(
(x) => x[this.primaryField] === data[this.primaryField]
);
source[index] = Object.assign(
{},
this.editingItems[data[this.primaryField]]
);
this.internalDataSource.data = source;
delete this.editingItems[data[this.primaryField]];
} else {
this.inserting = false;
data.editing = false;
const source = this.internalDataSource.data;
const index = source.findIndex(
(x) => x[this.primaryField] === data[this.primaryField]
);
this.internalDataSource.data = source.splice(index, 1);
}
this.table.renderRows();
}
getTotals(columnName: string) {
if (this.dataLength > 0) {
if (
this.internalDataSource?.filteredData &&
this.internalDataSource?.filteredData.length > 0
) {
return this.internalDataSource?.filteredData
.map((d) => this.getData(d, columnName))
.reduce((prev_value, value) => prev_value + value);
} else {
return 0;
}
}
return 0;
}
filtrerDataSource(event: any): void {
let value = event.target.value;
this.internalDataSource.filter = value.trim().toLowerCase();
}
/* Exporter les donnรฉes du tableau */
exporter(): void {
let columns: ExportColumn[];
if (this.exportColumns && this.exportColumns.length > 0) {
columns = this.exportColumns;
} else {
if (this.expandColumns) {
columns = this.columns
.filter((c) => !!c.field)
.map((c) => {
const col: ExportColumn = {
field: c.field,
caption: c.caption,
dataType: c.dataType,
dataTypeFormat: c.dataTypeFormat,
};
return col;
});
} else {
columns = this.columns
.filter((c) => !!c.field && !c.expandable)
.map((c) => {
const col: ExportColumn = {
field: c.field,
caption: c.caption,
dataType: c.dataType,
dataTypeFormat: c.dataTypeFormat,
};
return col;
});
}
}
const data = this.flat(this.internalDataSource.filteredData, columns);
/*this.fileExportService.exportCSV(this.exportName, data);*/
}
/* Construction du fichier ร exporter sous format .csv*/
private flat(data: any[], columns: ExportColumn[]): any {
if (!data) {
return null;
}
const header = columns
.filter((c) => !!c.caption)
.map((c) => {
return c.caption;
})
.join(";");
const lignes = data.map((item) => {
const ligne = columns
.map((c) => {
const data = this.getData(item, c.field);
if (c.dataType === "date" && data) {
return this.datePipe.transform(data, c.dataTypeFormat, 'UTC');
}
return data;
})
.join(";");
return ligne;
});
return header + "\r\n" + lignes.join("\r\n");
}
/* Action selection */
isAllSelected(): boolean {
const numSelected = this.selection.selected.length;
const numRows = this.internalDataSource.filteredData.length;
return numSelected === numRows;
}
masterToggle() {
this.isAllSelected()
? this.selection.clear()
: this.internalDataSource.filteredData.forEach((row) =>
this.selection.select(row)
);
}
onChangePage(event: any): void {
console.log(event);
}
etendreColonnes(): void {
this.expandColumns = !this.expandColumns;
if (this.expandColumns) {
this.displayedColumns = this.columns.map(
(column: GridMaterialColumnComponent) => {
return column.name;
}
);
} else {
this.displayedColumns = this.columns
.filter((x) => !x.expandable)
.map((column: GridMaterialColumnComponent) => {
return column.name;
});
}
if (this.multiEdition) {
this.displayedColumns.unshift(this.mutliEditionColumnName);
}
if (this.activateCollapseRow === true) {
this.displayedColumns.unshift(this.collapseColumnName);
}
}
expandCollapse(row:any) {
if (row.isExpanded) {
row.isExpanded = false;
this.collapseAmount--;
} else {
row.isExpanded = true;
this.collapseAmount++;
}
if (this.collapseAmount > 0) {
this.activateCollapseAllRow = true;
} else {
this.activateCollapseAllRow = false;
}
}
expandAllCollapse() {
if (this.activateCollapseAllRow) {
this.activateCollapseAllRow = false;
} else {
this.activateCollapseAllRow = true;
}
if (this.internalDataSource) {
this.internalDataSource.filteredData.map(
(c) => ( c.isRowCollapse ? c.isExpanded = this.activateCollapseAllRow : c.isExpanded = false )
);
}
}
getData(element: any, field: string) {
if (field) {
const fields = field.split(".");
let resultat = element;
for (let i = 0; i < fields.length; i++) {
resultat = resultat[fields[i]];
}
return resultat;
}
}
}
|
import { FC } from 'react'
import {PreviewContainer, TitleContainer,CollectionPreviewContainer } from './CollectionPreview.style'
import CollectionItem from '../collection-item/CollectionItem'
import { CategoryItem } from '../../store/category/category.types'
type CollectionPreviewProps = {
title: string;
products: CategoryItem[];
};
const CollectionPreview: FC<CollectionPreviewProps> = ({title,products}) => {
return (
<CollectionPreviewContainer>
<h2>
<TitleContainer to={title} >
{title.toUpperCase()}
</TitleContainer>
</h2>
<PreviewContainer>
{products.filter((_,idx)=> idx < 4).map((product) => (
<CollectionItem key={product.id} product={product} />
))}
</PreviewContainer>
</CollectionPreviewContainer>
)
}
export default CollectionPreview
|
import { ChangeEvent, useCallback, useEffect, useRef, useState } from 'react';
interface Props {
onChange: (val: string) => void;
characterCount: number;
value?: string;
}
export const useCodeEditor = ({ onChange, value, characterCount }: Props) => {
const inputArr = Array.from(
{ length: characterCount },
(v, index) => value?.[index] || '',
);
const [values, setValues] = useState<Array<string>>(inputArr);
const inputListWrapperRef = useRef<HTMLDivElement>(null);
const handleChangeValue = useCallback(
(index: number) => (event: ChangeEvent<HTMLInputElement>) => {
const value = event.target.value;
const lastSymbol = value[value.length - 1];
const newValues = [...values];
newValues[index] = lastSymbol;
setValues(newValues);
const renderValues = newValues.map((el) => el || '');
onChange(renderValues.join(''));
if (index < values.length - 1) {
const nextInput = event.target.nextSibling;
if (nextInput instanceof HTMLInputElement) {
nextInput.focus();
}
}
},
[onChange, values],
);
const handlePasteContent = useCallback(
(ev: ClipboardEvent) => {
if (inputListWrapperRef.current) {
const clipboardData = ev.clipboardData;
const pastedText = clipboardData?.getData('text');
if (pastedText) {
const pastedValues = pastedText.trim();
const newValues = inputArr.map(
(el, index) => pastedValues[index] || '',
);
if (pastedValues && pastedValues.length) {
ev.stopPropagation();
ev.preventDefault();
onChange(newValues.join(''));
setValues(newValues);
const inputList = inputListWrapperRef.current.children;
const actualIndex =
pastedValues.length === inputArr.length
? pastedValues.length - 1
: pastedValues.length;
const nextInput = inputList[actualIndex];
if (nextInput instanceof HTMLInputElement) {
nextInput.focus();
}
}
}
}
},
[inputArr, onChange],
);
useEffect(() => {
if (inputListWrapperRef && inputListWrapperRef.current) {
const contentElement = inputListWrapperRef.current;
contentElement.addEventListener('paste', handlePasteContent);
return () => {
contentElement?.removeEventListener('paste', handlePasteContent);
};
}
}, [handlePasteContent]);
return { inputArr, handleChangeValue, values, inputListWrapperRef };
};
|
import { Todo, Store } from './types';
// for updating todo
// here todos: Todo[] will takes all the data of todos in an array means it is complete list of todos therefore we've used (todos.map) function because todos will have all the data
export const updateTodo = (todos: Todo[], id: number, text: string): Todo[] =>
todos.map((data) => ({
...data,
text: data.id === id ? text : data.text,
}));
// for check-box
export const toggleTodo = (todos: Todo[], id: number): Todo[] =>
todos.map((data) => ({
...data,
done: data.id === id ? !data.done : data.done,
}));
// for deleting todo
export const removeTodo = (todos: Todo[], id: number): Todo[] =>
todos.filter((data) => data.id !== id);
// for adding todo
export const addTodo = (todos: Todo[], text:string): Todo[] => [
...todos,
{
id: Math.max(0, Math.max(...todos.map(({id}) => id))) + 1,
text,
// by default done (check-box) will be false
done: false
},
];
|
---
title: Chargement des mรฉtadonnรฉes
linktitle: Chargement des mรฉtadonnรฉes
second_title: API GroupDocs.Metadata .NET
description: Gรฉrez sans effort les mรฉtadonnรฉes des fichiers dans .NET avec GroupDocs.Metadata. Apprenez les techniques de chargement, d'รฉdition et bien plus encore pour des capacitรฉs amรฉliorรฉes de manipulation de fichiers.
type: docs
weight: 20
url: /fr/net/metadata-loading/
---
## Introduction
Vous cherchez ร amรฉliorer les capacitรฉs de manipulation de fichiers de vos applications .NETย ? Plongez dans les didacticiels GroupDocs.Metadata pour .NET couvrant divers aspects du chargement des mรฉtadonnรฉes. Du chargement de mรฉtadonnรฉes ร partir de disques locaux ร la gestion de documents protรฉgรฉs par mot de passe, nous avons ce qu'il vous faut.
## Comment charger des mรฉtadonnรฉes ร partir d'un disque local dans .NET
Vous souhaitez gรฉrer efficacement les mรฉtadonnรฉes des fichiers stockรฉs sur votre disque localย ? Notre tutoriel vous guide tout au long du processus avec[GroupDocs.Metadata pour .NET](./load-metadata-local-disk/). Apprenez ร charger sans effort des mรฉtadonnรฉes, ร les modifier et ร optimiser vos tรขches de manipulation de fichiers.
## Comment charger des mรฉtadonnรฉes ร partir d'un flux dans .NET
Rationaliser la gestion des mรฉtadonnรฉes de fichiers dans .NET est un jeu d'enfant avec[GroupDocs.Metadonnรฉes](./load-metadata-stream/). Suivez notre didacticiel รฉtape par รฉtape pour apprendre ร charger des mรฉtadonnรฉes ร partir de flux, ร les modifier ร la volรฉe et ร intรฉgrer de maniรจre transparente la gestion des mรฉtadonnรฉes dans vos applications.
## Chargement de mรฉtadonnรฉes ร partir d'un format spรฉcifique dans .NET
Diffรฉrents formats de fichiers peuvent nรฉcessiter des approches spรฉcifiques pour gรฉrer les mรฉtadonnรฉes. Dans ce tutoriel, nous explorons comment[GroupDocs.Metadata pour .NET](./load-metadata-specific-format/) vous permet de charger facilement des mรฉtadonnรฉes ร partir de diffรฉrents formats de fichiers. Des images aux documents, maรฎtrisez lโart de la manipulation des mรฉtadonnรฉes.
## Comment charger des mรฉtadonnรฉes ร partir d'un document protรฉgรฉ par mot de passe dans .NET
Besoin d'extraire, de modifier ou de gรฉrer des mรฉtadonnรฉes ร partir de documents protรฉgรฉs par mot de passeย ?[GroupDocs.Metadata pour .NET](./load-metadata-password-protected/) apporte la solution. Apprenez ร gรฉrer efficacement les mรฉtadonnรฉes dans des documents sรฉcurisรฉs, garantissant une intรฉgration fluide et une gestion amรฉliorรฉe des documents.
----
Que vous soyez un dรฉveloppeur chevronnรฉ ou que vous dรฉbutiez tout juste avec .NET, nos didacticiels offrent des conseils complets pour exploiter GroupDocs.Metadata pour une gestion transparente des mรฉtadonnรฉes. Libรฉrez tout le potentiel de vos applications .NET et amรฉliorez vos capacitรฉs de manipulation de fichiers dรจs aujourd'huiย !
## Tutoriels de chargement de mรฉtadonnรฉes
### [Comment charger des mรฉtadonnรฉes ร partir d'un disque local dans .NET](./load-metadata-local-disk/)
Gรฉrez sans effort les mรฉtadonnรฉes de fichiers dans les applications .NET avec GroupDocs.Metadata pour des capacitรฉs amรฉliorรฉes de manipulation de fichiers.
### [Chargement des mรฉtadonnรฉes ร partir de Stream dans .NET](./load-metadata-stream/)
Apprenez ร gรฉrer les mรฉtadonnรฉes de fichiers dans .NET avec GroupDocs.Metadata. Guide รฉtape par รฉtape pour charger, modifier et supprimer les mรฉtadonnรฉes des flux.
### [Chargement de mรฉtadonnรฉes ร partir d'un format spรฉcifique dans .NET](./load-metadata-specific-format/)
Dรฉcouvrez comment charger des mรฉtadonnรฉes ร partir de formats de fichiers spรฉcifiques ร l'aide de GroupDocs.Metadata pour .NET dans ce didacticiel complet.
### [Comment charger des mรฉtadonnรฉes ร partir d'un document protรฉgรฉ par mot de passe dans .NET](./load-metadata-password-protected/)
Dรฉcouvrez comment gรฉrer efficacement les mรฉtadonnรฉes des documents avec GroupDocs.Metadata pour .NET. Extrayez, modifiez et gรฉrez les mรฉtadonnรฉes de maniรจre transparente dans vos applications .NET.
|
<script>
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
</script>
<div class="animate__animated animate__fadeInRight animate__faster" [class]="this.uid === 'nuevo' ? '' : 'puebloMix'">
<div class="d-flex justify-content-center">
<div class="card">
<div class="card-body">
<div>
<button type="button" class="btn btn-rounded btn-back" routerLink="/admin/events"><span class="btn-icon-start text-back"><i class="fa fa-arrow-left fa-xs"></i></span>Volver</button>
</div>
<!-- Formulario para cuando se crea un nuevo evento-->
<div *ngIf="wait_form" class="content spinnerCSSMejorado">
<div class="spinner">
</div>
</div>
<form *ngIf="this.uid === 'nuevo' && !wait_form" class="form-horizontal m-t-20" [formGroup]="datosFormNew" (ngSubmit)="newEvent()">
<div class="form-group margLeftRight">
<label for="name">Nombre *</label>
<input type="text" class="form-control" formControlName="name" [ngClass]="{'is-invalid' : campoNoValidoNew('name')}" id="name">
<div class="invalid-feedback">
El nombre es obligatorio
</div>
</div>
<div class="dosMismaFila margLeftRight">
<div class="form-group mitad50">
<label for="name">Fecha *</label>
<input type="date" class="form-control" formControlName="date" [ngClass]="{'is-invalid' : campoNoValidoNew('date')}" id="date">
<div class="invalid-feedback">
El campo fecha es obligatorio y tiene que ser una fecha con formato (yyyy-mm-dd)
</div>
</div>
<div class="form-group mitad50">
<label for="town">Pueblo *</label>
<input (keyup)="selectProvinceTrueKey($event)" (input)="selectProvince()" id="town"
class="form-control" [ngClass]="{'is-invalid' : this.select_province }"
(input)="cargarPueblos()" type="text"
placeholder="Seleccione un pueblo"
formControlName="town"
[formControl]="filterTowns"
[matAutocomplete]="auto">
<mat-autocomplete style="border-radius: 20px; border: 2px solid #f1f2f3;" #auto="matAutocomplete">
<mat-option (click)="selectProvinceTrue()" *ngFor="let option of filteredOptions | async" [value]="option.name">
{{option.name}}
</mat-option>
</mat-autocomplete>
<div class="invalid-feedback">
Seleccione un pueblo de la lista
</div>
</div>
</div>
<div class="form-group margLeftRight">
<label for="name">Descripcion *</label>
<textarea class="form-control" formControlName="description" id="description" [ngClass]="{'is-invalid' : campoNoValidoNew('description')}" rows="3"></textarea>
<div class="invalid-feedback">
El campo descripcion es obligatorio
</div>
</div>
<div class="form-group margLeftRight">
<label for="name">Fotos *</label>
<input type="file" (change)="fileChange($event)" class="form-control" multiple="multiple" formControlName="pictures" [ngClass]="{'is-invalid' : campoNoValidoNew('pictures')}" aria-describedby="inputGroupFileAddon01" name="file" id="fotosubidas">
<div class="invalid-feedback">
Las fotos son obligatorias y tienen que ser ficheros en formato jpg, png o jpeg
</div>
</div>
<!-- FORMULARIO VIEJO
<div class="row m-t-10">
<div class="col-lg-3 col-md-12 text-lg-right">
<span class="">UID</span>
</div>
<div class="col-lg-8 col-md-12">
<input type="text" class="form-control" formControlName="uid" id="uid">
</div>
</div>
<div class="row m-t-10">
<div class="col-lg-3 col-md-12 text-lg-right">
<span class="">Nombre</span>
</div>
<div class="col-lg-8 col-md-12">
<input type="text" class="form-control" formControlName="name" [ngClass]="{'is-invalid' : campoNoValidoNew('name')}" id="name">
<div class="invalid-feedback">
El campo nombre es obligatorio
</div>
</div>
</div>
<div class="row m-t-10">
<div class="col-lg-3 col-md-12 text-lg-right">
<span class="">Fecha</span>
</div>
<div class="col-lg-8 col-md-12">
<input type="date" class="form-control" formControlName="date" [ngClass]="{'is-invalid' : campoNoValidoNew('date')}" id="date">
<div class="invalid-feedback">
El campo fecha es obligatorio y tiene que ser una fecha con formato (yyyy-mm-dd)
</div>
</div>
</div>
<div class="row m-t-10">
<div class="col-lg-3 col-md-12 text-lg-right">
<span class="">Descripciรณn</span>
</div>
<div class="col-lg-8 col-md-12">
<textarea class="form-control" formControlName="description" id="description" [ngClass]="{'is-invalid' : campoNoValidoNew('description')}" rows="3">
</textarea>
<div class="invalid-feedback">
El campo descipciรณn es obligatorio
</div>
</div>
</div>
<div class="row m-t-10">
<mat-form-field class="col-lg-8 col-md-12" appearance="outline">
<mat-label>Pueblo</mat-label>
<input [ngClass]="{'is-invalid' : campoNoValidoNew('town')}" (input)="cargarPueblos()" type="text"
placeholder="Seleccione un pueblo con encanto"
aria-label="Pueblo"
matInput
formControlName="town"
[formControl]="filterTowns"
[matAutocomplete]="auto">
<mat-autocomplete style="border-radius: 20px; border: 2px solid #f1f2f3;" #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
{{option.name}}
</mat-option>
</mat-autocomplete>
<div class="invalid-feedback">
El campo pueblo es obligatorio
</div>
</mat-form-field>
</div>
<div class="row m-t-10">
<div class="col-lg-3 col-md-12 text-lg-right">
<span class="">Fotos</span>
</div>
<div class="col-lg-8 col-md-12">
<input type="file" (change)="fileChange($event)" class="form-control" multiple="multiple" formControlName="pictures" [ngClass]="{'is-invalid' : campoNoValidoNew('pictures')}" aria-describedby="inputGroupFileAddon01" name="file" id="fotosubidas">
<div class="invalid-feedback">
El campo fotos es obligatorio y tienen que ser ficheros en formato jpg, png o jpeg.
</div>
</div>
</div> -->
<div class="d-flex justify-content-center m-t-10 ">
<div class="align-content-center ">
<button class="btn btn-primary m-r-20 " type="submit " id="enviar" [disabled]="datosFormNew.pristine"> <i *ngIf="waiting" style="margin-right: 10px;" class="fas fa-circle-notch fa-spin"></i> Enviar</button>
<button class="btn btn-danger " type="button" (click)="cancelar()" id="cancelar" [disabled]="datosFormNew.pristine">Cancelar</button>
</div>
</div>
</form>
<!-- Formulario para cuando se edita un evento-->
<form *ngIf="this.uid!=='nuevo'" class="form-horizontal m-t-20" [formGroup]="datosForm" (ngSubmit)="updateEvent()">
<div class="form-group margLeftRight">
<label for="name">UID *</label>
<input type="text" class="form-control" formControlName="uid" id="uid">
</div>
<div class="form-group margLeftRight">
<label for="name">Nombre *</label>
<input type="text" class="form-control" formControlName="name" [ngClass]="{'is-invalid' : campoNoValido('name')}" id="name">
<div class="invalid-feedback">
El nombre es obligatorio
</div>
</div>
<div class="dosMismaFila margLeftRight">
<div class="form-group mitad50">
<label for="name">Fecha *</label>
<input type="date" class="form-control" formControlName="date" [ngClass]="{'is-invalid' : campoNoValido('date')}" id="date">
<div class="invalid-feedback">
El campo fecha es obligatorio y tiene que ser una fecha con formato (yyyy-mm-dd)
</div>
</div>
<div class="form-group mitad50">
<label for="town">Pueblo *</label>
<input (keyup)="selectProvinceTrueKey($event)" (input)="selectProvince()" id="town"
class="form-control" [ngClass]="{'is-invalid' : this.select_province }"
(input)="cargarPueblos()" type="text"
formControlName="town"
[formControl]="filterTowns"
[matAutocomplete]="auto">
<mat-autocomplete style="border-radius: 20px; border: 2px solid #f1f2f3;" #auto="matAutocomplete">
<mat-option (click)="selectProvinceTrue()" *ngFor="let option of filteredOptions | async" [value]="option.name">
{{option.name}}
</mat-option>
</mat-autocomplete>
<div class="invalid-feedback">
Seleccione un pueblo de la lista
</div>
</div>
</div>
<div class="form-group margLeftRight">
<label for="name">Descripcion *</label>
<textarea class="form-control" formControlName="description" id="description" [ngClass]="{'is-invalid' : campoNoValido('description')}" rows="3"></textarea>
<div class="invalid-feedback">
El campo descripcion es obligatorio
</div>
</div>
<!-- FORMULARIO VIEJO
<div class="row m-t-10">
<div class="col-lg-3 col-md-12 text-lg-right">
<span class="">UID</span>
</div>
<div class="col-lg-8 col-md-12">
<input type="text" class="form-control" formControlName="uid" id="uid">
</div>
</div>
<div class="row m-t-10">
<div class="col-lg-3 col-md-12 text-lg-right">
<span class="">Nombre</span>
</div>
<div class="col-lg-8 col-md-12">
<input type="text" class="form-control" formControlName="name" [ngClass]="{'is-invalid' : campoNoValido('name')}" id="name">
<div class="invalid-feedback">
El campo nombre es obligatorio
</div>
</div>
</div>
<div class="row m-t-10">
<div class="col-lg-3 col-md-12 text-lg-right">
<span class="">Fecha</span>
</div>
<div class="col-lg-8 col-md-12">
<input type="date" class="form-control" formControlName="date" [ngClass]="{'is-invalid' : campoNoValido('date')}" id="date">
<div class="invalid-feedback">
El campo fecha es obligatorio y tiene que ser una fecha con formato (yyyy-mm-dd)
</div>
</div>
</div>
<div class="row m-t-10">
<div class="col-lg-3 col-md-12 text-lg-right">
<span class="">Descripciรณn</span>
</div>
<div class="col-lg-8 col-md-12">
<textarea class="form-control" formControlName="description" id="description" [ngClass]="{'is-invalid' : campoNoValido('description')}" rows="3">
</textarea>
</div>
</div>
<div class="row m-t-10">
<mat-form-field class="col-lg-8 col-md-12" appearance="outline">
<mat-label>Pueblo</mat-label>
<input [ngClass]="{'is-invalid' : campoNoValido('town')}" (input)="cargarPueblos()" type="text"
placeholder="Seleccione un pueblo con encanto"
aria-label="Pueblo"
matInput
formControlName="town"
[formControl]="filterTowns"
[matAutocomplete]="auto">
<mat-autocomplete style="border-radius: 20px; border: 2px solid #f1f2f3;" #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
{{option.name}}
</mat-option>
</mat-autocomplete>
<div class="invalid-feedback">
El campo pueblo es obligatorio
</div>
</mat-form-field>
</div> -->
<div class="d-flex justify-content-center m-t-10 ">
<div class="align-content-center ">
<button class="btn btn-primary m-r-20 " type="submit " id="enviar" [disabled]="datosForm.pristine"> <i *ngIf="waiting" style="margin-right: 10px;" class="fas fa-circle-notch fa-spin"></i> Enviar</button>
<button class="btn btn-danger " type="button" (click)="cancelar()" id="cancelar" [disabled]="datosForm.pristine">Cancelar</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="fotosArea">
<!-- Div donde se muestra el carusel de imagenes-->
<div *ngIf="this.uid != 'nuevo'" class="d-flex justify-content-center">
<div class="card">
<div class="card-body">
<h2 style="text-align: center;">Imรกgenes totales</h2>
<div *ngIf="totalFotos > 0" class="">
<div class="form-group row m-t-10">
<div class="col-lg-12 col-md-12">
<div class="text-center">
<div *ngIf="cargar_imagen" class="content spinnerCSSMejorado"><div class="spinner"></div></div>
<img style="display: block; margin: auto; max-height: 180px; width: auto; height: auto;" [src]="namefile">
<i (click)="confirmDeletePhoto();" class="fa fa-times borrarFoto" aria-hidden="true"></i>
</div>
</div>
</div>
<p style="text-align: center;">
<i *ngIf="iconoAtras" (click)="cambiarFotosAtras();" style="margin-right: 10px;" class="fas fa-arrow-left"></i>
Foto: {{numFoto}} de {{totalFotos}}
<i *ngIf="iconoAlante" (click)="cambiarFotosAlante();" style="margin-left: 10px;" class="fas fa-arrow-right"></i>
</p>
</div>
<div *ngIf="!wait_form && totalFotos == 0" class="">
<div class="form-group row m-t-10">
<div class="col-lg-12 col-md-12">
<div class="text-center">
<p>No hay imรกgenes de este evento</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Div para subir imagenes -->
<div style="margin-top: 10px;" *ngIf="this.uid != 'nuevo'" class="d-flex justify-content-center">
<div class="card">
<div class="card-body">
<h2>Imagenes</h2>
<div class="">
<form class="form-horizontal m-t-20" (submit)="upload();" enctype="multipart/form-data">
<div class="d-flex justify-content-center m-t-10 ">
<div class="form-group row m-t-10">
<div class="col-lg-3 text-lg-right">
<span class=" ">Imagen</span>
</div>
<div class="col-lg-8 col-md-12">
<div class="custom-file">
<input type="file" (change)="fileChange($event)" class="custom-file-input" multiple="multiple" aria-describedby="inputGroupFileAddon01" name="file" id="fotosubidas">
<label class="custom-file-label" for="fotoperfil" data-browse="Elegir">{{nameFileForm}}</label>
</div>
</div>
</div>
</div>
<div class="d-flex justify-content-center m-t-10 ">
<div class="align-content-center ">
<!-- <button class="btn btn-primary m-r-20 " type="submit" id="enviar"> Aรฑadir imagen</button> -->
<button class="btn btn-primary m-r-20 " type="submit" id="enviar" [disabled]="this.uploadedFiles.length === 0"><i *ngIf="waiting_picture" style="margin-right: 10px;" class="fas fa-circle-notch fa-spin"></i> Enviar</button>
<button class="btn btn-danger " (click)="cancelUpdatePictures();" [disabled]="this.uploadedFiles.length === 0">Cancelar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
|
<script setup>
import HeartOutline from 'icons/HeartOutline.vue';
import Close from 'icons/Close.vue';
import ArrowLeft from 'icons/ArrowLeft.vue';
import LeadPencil from 'icons/LeadPencil.vue';
// import { useStore } from '@/stores/pins';
// const store = useStore();
const route = useRoute();
const user = useSupabaseUser();
const client = useSupabaseClient();
// Local state
const liked = ref(false);
const myComment = ref('');
const openModal = ref(false);
const { data: pin } = await useAsyncData(
route.params.id[0],
async () => {
const { data } = await client.from('pins').select('*').eq('id', `${route.params.id[0]}`);
return data;
},
{
transform: (result) => result[0],
}
);
// console.log(pin);
// onMounted(() => {
// if (pin.likes.length) {
// liked = pin.likes.some((like) => {
// return like.username === user.username;
// });
// }
// });
// const like = async () => {
// liked.value = !liked.value;
// if (liked.value) {
// // await this.$store.dispatch('pins/likePin', this.pin);
// setTimeout(() => {
// // this.$store.dispatch('pins/fetchPins');
// }, 100);
// return;
// }
// // await this.$store.dispatch('pins/unlikePin', this.pin);
// setTimeout(() => {
// // this.$store.dispatch('pins/fetchPins');
// }, 100);
// };
// const commentPin = async () => {
// await this.$store.dispatch('pins/commentPin', {
// pin: this.$route.params.id,
// comment: this.myComment,
// });
// myComment.value = '';
// await this.$store.dispatch('pins/fetchPins');
// };
// const deleteComment = async (id) => {
// await this.$store.dispatch('pins/deleteComment', {
// pin: this.$route.params.id,
// comment: id,
// });
// await this.$store.dispatch('pins/fetchPins');
// };
</script>
<template>
<main class="container">
<button class="mx-4 mb-6 flex gap-x-2 text-gray-500" @click="$router.back()">
<ArrowLeft fill-color="#5481bb" /> Back
</button>
<section
class="relative mx-2 mb-5 flex h-full flex-col rounded-[32px] p-4 shadow-pinterest md:mx-4 md:flex-row"
>
<figure class="mb-4 h-full overflow-hidden rounded-[16px] shadow-pinterest md:mb-0 md:w-1/2">
<img class="w-full" :src="pin.url" alt="" />
</figure>
<div v-if="user" class="relative z-50 mb-4 md:absolute md:right-4 md:top-4">
<div v-if="user.username !== pin.owner" class="flex flex-col items-center">
<HeartOutline
:size="48"
:fill-color="liked ? 'red' : 'gray'"
class="text-white"
:class="user ? 'cursor-pointer' : 'cursor-not-allowed'"
:title="user ? 'Like' : 'You must be logged in to like pins'"
@click="user ? like() : null"
/>
<!-- <span v-if="pin.likes" class="text-sm text-gray-600">{{ pin.likes.length }}</span> -->
</div>
<button v-else class="rounded-lg p-1 text-white transition-all duration-300">
<nuxt-link :to="`/${pin.id}/edit/`">
<LeadPencil :size="32" fill-color="gray" />
</nuxt-link>
</button>
</div>
<article class="flex flex-col items-center justify-between gap-y-8 md:w-1/2 md:px-4">
<div class="flex flex-col items-center justify-between gap-y-8 px-4 md:w-1/2">
<h1 class="w-[20ch] text-center text-3xl text-primary">
{{ pin.title }}
</h1>
<span class="text-center text-sm text-gray-500"
>Uploaded by <span class="text-green-600">{{ pin.owner }}</span></span
>
<p class="w-full px-8 text-xs md:w-[50ch]">
{{ pin.description }}
</p>
</div>
<div class="w-full">
<h2 class="ml-4 mb-2 text-center text-2xl font-bold text-primary">Comments</h2>
<!-- <div v-if="pin.comments.length" class="flex flex-col">
<section
v-for="comment in pin.comments"
:key="comment.id"
class="flex w-full items-center gap-x-4 p-4"
>
<img
class="h-16 w-16 rounded-full bg-gray-200 object-cover"
:src="
comment.username.avatar
? comment.username.avatar
: require('@/assets/user-default.png')
"
/>
<article
class="group relative w-[80%] rounded-[16px] border border-gray-400 p-4 text-gray-500"
>
<Close
v-if="user && user.username === comment.username.username"
class="absolute right-2 top-2 hidden cursor-pointer group-hover:block"
@click="deleteComment(comment.id)"
/>
<span class="font-extrabold text-primary">{{ comment.username.username }}</span>
<p class="text-xs text-gray-500">
{{ comment.comment }}
</p>
</article>
</section>
</div> -->
<div>
<p class="ml-4 mb-2 text-center text-gray-400">No comments yet</p>
</div>
<hr class="ml-4 mb-2 divide-x-2" />
<!-- Comment form -->
<form
v-if="user"
class="flex w-full flex-wrap items-center justify-evenly gap-4 md:justify-start md:gap-2 md:p-4 lg:flex-nowrap"
@submit.prevent="commentPin"
>
<img
class="h-16 w-16 rounded-full object-cover"
:class="!user.avatar && 'bg-gray-200'"
:src="user.avatar ? user.avatar : '/assets/user-default.png'"
alt=""
/>
<input
v-model="myComment"
class="w-auto rounded-[16px] border border-gray-400 p-4 text-gray-500 focus:outline-none focus:ring-1 focus:ring-gray-500"
type="text"
placeholder="Add a comment"
/>
<input
class="m-auto w-32 cursor-pointer self-end rounded-lg bg-primary px-3 py-3 text-white shadow-md disabled:cursor-not-allowed disabled:bg-gray-400"
type="submit"
value="Send"
:disabled="!myComment"
:title="!myComment ? 'Please enter a comment' : 'Send comment'"
/>
</form>
<!-- If the user is not logged in -->
<div v-else class="mx-auto flex w-1/2 flex-col">
<p class="ml-4 mb-2 text-center text-gray-500">You must be logged in to comment</p>
<nuxt-link
:to="{ path: '/login' }"
class="ml-4 mb-2 rounded-lg bg-primary px-3 py-3 text-center text-white shadow-md hover:bg-primary/75"
>
Login
</nuxt-link>
</div>
</div>
</article>
</section>
</main>
</template>
|
//
// SecondaryUserStatusView.swift
// BodyLife3
//
// Created by David Diego Gomez on 10/01/2021.
// Copyright ยฉ 2021 David Diego Gomez. All rights reserved.
//
import Cocoa
extension Notification.Name {
public static let userSecondaryUpdated = Notification.Name(rawValue: "userSecondaryUpdated")
public static let needSecondaryUserLogin = Notification.Name(rawValue: "needSecondaryUserLogin")
}
class SecondaryUserStatusView: NSView {
@IBOutlet weak var subtitleLabel: NSTextField!
@IBOutlet weak var titleLabel: NSTextField!
@IBOutlet weak var roleLabel: NSTextField!
var timer : Timer!
override init(frame frameRect: NSRect) {
super .init(frame: frameRect)
commonInit()
}
required init?(coder: NSCoder) {
super .init(coder: coder)
commonInit()
}
func commonInit() {
let xibName = String(describing: type(of: self))
var topLevelObjects: NSArray?
if Bundle.main.loadNibNamed(xibName, owner: self, topLevelObjects: &topLevelObjects) {
if let myView = topLevelObjects?.first(where: { $0 is NSView } ) as? NSView {
myView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
addSubview(myView)
}
}
NotificationCenter.default.addObserver(self, selector: #selector(secondaryUserUpdatedHandler), name: .userSecondaryUpdated, object: nil)
updateValues()
self.wantsLayer = true
self.layer?.borderWidth = 1
self.layer?.borderColor = NSColor.lightGray.cgColor
}
@IBAction func revokeButtonDidPressed(_ sender: Any) {
timer.invalidate()
SecondaryUserSession.Remove()
NotificationCenter.default.post(name: .needSecondaryUserLogin, object: nil, userInfo: nil)
updateValues()
}
@objc func secondaryUserUpdatedHandler() {
updateValues()
}
private func updateValues() {
DispatchQueue.main.async {
let secondaryUser = SecondaryUserSession.GetUser()
self.titleLabel.stringValue = (secondaryUser?.userName ?? "Sin usuario")
self.roleLabel.stringValue = (secondaryUser?.role ?? "-")
self.setupTimer()
}
}
private func setupTimer() {
if timer != nil {
timer.invalidate()
}
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerHandler), userInfo: nil, repeats: true)
}
@objc func timerHandler() {
let secondaryUser = SecondaryUserSession.GetUser()
let dateDouble = (secondaryUser?.tokenExpiration)
let date = dateDouble?.toDate1970
let seconds = Date().segundosTranscurridos(fecha: date ?? Date())
if seconds ?? 0 <= 0 {
timer.invalidate()
SecondaryUserSession.Remove()
NotificationCenter.default.post(name: .needSecondaryUserLogin, object: nil, userInfo: nil)
}
let secondsString = (seconds ?? 0).secondsToHoursMinutesSeconds()
self.subtitleLabel.stringValue = "\(secondsString)"
}
}
|
# Frontend Mentor - Todo app solution
This is a solution to the [Todo app challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/todo-app-Su1_KokOW). Frontend Mentor challenges help you improve your coding skills by building realistic projects.
## Table of contents
- [Overview](#overview)
- [The challenge](#the-challenge)
- [Screenshot](#screenshot)
- [Links](#links)
- [My process](#my-process)
- [Built with](#built-with)
- [Useful resources](#useful-resources)
- [Author](#author)
## Overview
### The challenge
Users should be able to:
- View the optimal layout for the app depending on their device's screen size
- See hover states for all interactive elements on the page
- Add new todos to the list
- Mark todos as complete
- Delete todos from the list
- Filter by all/active/complete todos
- Clear all completed todos
- Toggle light and dark mode
- **Bonus**: Drag and drop to reorder items on the list
### Screenshot


### Links
- Solution URL: https://github.com/Umlen/todo-app
- Live Site URL: https://todo-app-tau-livid.vercel.app/
## My process
### Built with
- Semantic HTML5 markup
- CSS custom properties
- Flexbox
- JavaScript
### Useful resources
- https://learn.javascript.ru/ - This helped me with JavaScript.
## Author
- GitHub - [Viktor](https://github.com/Umlen)
- Frontend Mentor - [@Umlen](https://www.frontendmentor.io/profile/Umlen)
|
#Author: [email protected]
#Keywords Summary :
#Feature: List of scenarios.
#Scenario: Business rule through list of steps with arguments.
#Given: Some precondition step
#When: Some key actions
#Then: To observe outcomes or validation
#And,But: To enumerate more Given,When,Then steps
#Scenario Outline: List of steps for data-driven as an Examples and <placeholder>
#Examples: Container for s table
#Background: List of steps run before each of the scenarios
#""" (Doc Strings)
#| (Data Tables)
#@ (Tags/Labels):To group Scenarios
#<> (placeholder)
#""
## (Comments)
#Sample Feature Definition Template
@tagMiPrimeraPrueba
Feature: Mi primera prueba
@tagsumasimple
Scenario Outline: Suma Simple
Given Quiero sumar dos numeros
When Sumo <num1> y <num2>
Then Compruebo que el resultado de la suma es <resultado>
Examples:
| num1 | num2 | resultado |
| 2 | 2 | 4 |
| 2 | 3 | 5 |
| 2 | 5 | 7 |
|
import uuid
import json
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from utils.passwords import gen_pass
from constants.bank.models import EXISTING_GROUPS, EXISTING_THEMES, EXISTING_TYPES_OF_RULES, PERMISSIONS, SIGN_SET
class ListField(models.TextField):
description = "Custom list field"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def from_db_value(self, value, expression, connection):
if value is None:
return []
return json.loads(value)
def to_python(self, value):
if isinstance(value, list):
return value
if value is None:
return []
return json.loads(value)
def get_prep_value(self, value):
if value is None:
return ''
return json.dumps(value)
class account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="ะะพะปัะทะพะฒะฐัะตะปั:")
balance = models.FloatField(default=0, verbose_name="ะะฐะปะฐะฝั:")
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ะฃะฝะธะบะฐะปัะฝัะน ID ะฐะบะบะฐัะฝัะฐ.")#, editable=False)
first_name = models.CharField(max_length=40, default='Not stated', verbose_name="ะะผั:") # ะะผั
middle_name = models.CharField(max_length=40, default='Not stated', verbose_name="ะััะตััะฒะพ:") # ะััะตััะฒะพ
last_name = models.CharField(max_length=40, default='Not stated', verbose_name="ะคะฐะผะธะปะธั:") # ะคะฐะผะธะปะธั
user_group = models.CharField(max_length=40, choices=EXISTING_GROUPS, default='None', help_text='ะััะฟะฟะฐ ะพะฑััะตะฝะธั', verbose_name="ะะฐะฝััะธั:")
party = models.IntegerField(default=0, verbose_name="ะัััะด:")
theme_self = models.CharField(max_length=50, choices=EXISTING_THEMES, default='default', help_text="ะะฐะบ ััะพ ะฒัะณะปัะดะธั, ะผะพะถะฝะพ ะฟะพัะผะพััะตัั ะฝะธะถะต.", verbose_name="ะขะตะผะฐ:")
account_status = models.CharField(max_length=100, default='', blank=True, verbose_name="ะกัะฐััั:")
class Meta:
ordering = ["party", "last_name"]
permissions = PERMISSIONS
def get_absolute_url(self):
return reverse('account-detail', args=[str(self.id)])
def get_absolute_url_for_edit(self):
return reverse('account-edit-n', args=[str(self.id)])
def __str__(self):
return f'{self.last_name} {self.first_name[0]}.{self.middle_name[0]}.'
def info(self):
return f'{self.last_name}, {self.first_name} {self.middle_name}: {self.party} ะพัััะด, ะณััะฟะฟะฐ {self.user_group}'
def short_name(self):
return f'{self.last_name} {self.first_name}'
def get_status(self):
return f'"{self.account_status}"' if self.account_status != '' else 'ะฝะต ัััะฐะฝะพะฒะปะตะฝ'
def get_number_f(self) -> int:
fb = [i for i in account.objects.exclude(party=0).order_by('-balance', "party", "last_name")]
for i in range(len(fb)):
if fb[i].id == self.id: return i + 1
return 0
def get_number_a(self) -> int:
fb = [i for i in account.objects.exclude(party=0).order_by('balance', "party", "last_name")]
for i in range(len(fb)):
if fb[i].id == self.id: return i + 1
return 0
def is_ped(self):
group = self.user.groups.get(name="pedagogue")
return group is not None
def get_transactions(self):
ret = list()
arr = transaction.objects.all()
for i in arr:
if f'{i.receiver}' != f'{self}' and f'{i.creator}' != f'{self}':
if f'{self.party}' != f'{i.receiver.last_name[-1]}': continue
ret.append(i)
return ret if ret != list() else None
def account_valid(self, x):
return f'{self.party}'
def renew_transactions(self):
arr = transaction.objects.all()
if arr is None: return 'There are no transactions'
b = False
for i in arr:
if i.counted: continue
i.count()
b = True
return 'Accept!' if b else 'Already accepted'
def undo_transactions(self):
arr = transaction.objects.all()
if arr is None: return 'There are no transactions'
b = False
for i in arr:
if not i.counted: continue
i.uncount()
b = True
return 'Accept!' if b else 'Already accepted'
def update_passwords(self):
def check_user_in_group(user, group_name): return user.groups.filter(name=group_name).exists()
users = User.objects.exclude(username__icontains='admin').order_by('username')
s_write = '-' * 30 + '\n'
for u in users:
len_pass = 12 if check_user_in_group(u, 'pedagogue') else 8
username = u.username
password = gen_pass(len_pass)
s_write += f'login: {username}\npassword: {password}\n' + '-' * 30 + '\n'
u.password = make_password(password)
u.save()
f = open("All_users.txt", "w")
f.write(s_write)
f.close()
return "Done!"
class transaction(models.Model):
date = models.DateField(null=True)
comment = models.CharField(max_length=70, default='ะะต ัะบะฐะทะฐะฝะพ')
receiver = models.ForeignKey('account', related_name='received_trans', on_delete=models.CASCADE, null=True, verbose_name="ะะพะปััะฐัะตะปั:")
creator = models.ForeignKey('account', related_name='created_trans', on_delete=models.CASCADE, null=True, verbose_name="ะัะฟัะฐะฒะธัะตะปั:")
history = models.ForeignKey('account', related_name='history_trans', on_delete=models.CASCADE, null=True, verbose_name="ะกะพะทะดะฐัะตะปั:")
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ะฃะฝะธะบะฐะปัะฝัะน ID ััะฐะฝะทะฐะบัะธะธ.")
counted = models.BooleanField(default=False, editable=False)
sign = models.CharField(max_length=20, choices=SIGN_SET, default='p2p+', verbose_name="ะขะธะฟ ััะฐะฝะทะฐะบัะธะธ:")
cnt = models.FloatField(default=0, verbose_name="ะะพะปะธัะตััะฒะพ:")
class Meta:
ordering = ["-date"]
def __str__(self):
return f'ะั {self.creator} ะบ {self.receiver} ะฝะฐ ััะผะผั {self.cnt}t (ะกะพะทะดะฐะป {self.history}): {dict(SIGN_SET)[self.sign]}'
def get_sum(self):
return f'{self.cnt}t'
def get_type_of(self):
return f'{dict(SIGN_SET)[self.sign]}'
def transaction_valid(self, x):
return f'{self.receiver.last_name[-1]}'
def get_absolute_url(self):
return reverse('transaction-detail', args=[str(self.id)])
def get_absolute_url_for_edit(self):
return reverse('transaction-edit', args=[str(self.id)])
def count(self):
if self.counted: return
rec = self.receiver
crt = self.creator
if '+' in self.sign:
rec.balance = rec.balance + self.cnt
rec.save()
crt.balance = crt.balance - self.cnt
crt.save()
else:
rec.balance = rec.balance - self.cnt
rec.save()
crt.balance = crt.balance + self.cnt
crt.save()
self.counted = True
self.save()
return
def uncount(self):
if not self.counted: return
rec = self.receiver
crt = self.creator
if '+' in self.sign:
rec.balance = rec.balance - self.cnt
rec.save()
crt.balance = crt.balance + self.cnt
crt.save()
else:
rec.balance = rec.balance + self.cnt
rec.save()
crt.balance = crt.balance - self.cnt
crt.save()
self.counted = False
self.save()
return
class rools(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ะฃะฝะธะบะฐะปัะฝัะน ID.")
num_type = models.CharField(max_length=3, choices=EXISTING_TYPES_OF_RULES, default='ะฃะบะข', verbose_name="ะ ะฐะทะดะตะป ะทะฐะบะพะฝะพะฒ:")
num_pt1 = models.IntegerField(default=1, help_text="ะ ะฐะทะดะตะป ะบะพะดะตะบัะฐ")
num_pt2 = models.IntegerField(default=0, help_text="ะงะฐััั ัะฐะทะดะตะปะฐ")
comment = models.CharField(max_length=250, default='ะะต ัะบะฐะทะฐะฝะพ')
punishment = models.CharField(max_length=100, default='ะะต ัะบะฐะทะฐะฝะพ')
class Meta:
ordering = ["num_type", "num_pt1", "num_pt2"]
def get_num(self):
return f'{self.num_type} {self.num_pt1}.0{self.num_pt2}' if len(f'{self.num_pt2}') == 1 else f'ะฃะบะข {self.num_pt1}.{self.num_pt2}'
def __str__(self):
return f'ะฃะบะข {self.num_pt1}.0{self.num_pt2}' if len(f'{self.num_pt2}') == 1 else f'ะฃะบะข {self.num_pt1}.{self.num_pt2}'
class good(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ะฃะฝะธะบะฐะปัะฝัะน ID.")
name = models.CharField(max_length=250, default='', verbose_name="ะะฐะทะฒะฐะฝะธะต:")
comment = models.CharField(max_length=250, default='', verbose_name="ะะพะผะผะตะฝัะฐัะธะน:")
cost = models.FloatField(default=0, verbose_name="ะฆะตะฝะฐ:")
def __str__(self):
return f'{self.name} - {self.cost}t'
def get_num(self):
return f'{self.cost}t'
def get_absolute_url(self):
return reverse('good-renew', args=[str(self.id)])
class Meta:
ordering = ["-cost"]
class plan(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ะฃะฝะธะบะฐะปัะฝัะน ID.")
time = models.CharField(max_length=250, default='', verbose_name="ะะพ ัะบะพะปัะบะพ:")
comment = models.CharField(max_length=250, default='', verbose_name="ะะพะผะผะตะฝัะฐัะธะน:")
number = models.IntegerField(default=0, verbose_name="ะะพะผะตั ะฒ ัะฟะธัะบะต: ")
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ะฃะฝะธะบะฐะปัะฝัะน ID.")
def __str__(self):
return f'{self.number} - {self.time}; {self.comment}'
def get_absolute_url(self):
return reverse('plans-renew', args=[str(self.id)])
class Meta:
ordering = ["number"]
class daily_answer(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ะฃะฝะธะบะฐะปัะฝัะน ID.")
name = models.TextField(max_length=500, verbose_name='ะะฐะทะฒะฐะฝะธะต ะทะฐะดะฐัะธ:', default='none')
text = models.TextField(max_length=1000, verbose_name='ะฃัะปะพะฒะธะต ะทะฐะดะฐัะธ:')
cnt = models.FloatField(default=0, verbose_name="ะะฐะณัะฐะดะฐ:")
status = models.BooleanField(default=False, verbose_name="ะญัะพ ะทะฐะดะฐัะฐ ัะผะตะฝั?")
class Meta:
ordering = ["cnt"]
def __str__(self):
return f'{self.name}: ะฝะฐ {self.cnt}'
def get_absolute_url(self):
return reverse('answers-renew', args=[str(self.id)])
|
######################################################################
### script for analysis of naive hESC scRNA-seq ###
######################################################################
##### Setup #####
library(Seurat)
library(dplyr)
library(ggplot2)
library(sctransform)
rm(list = ls())
shhhh=gc() # perform garbage collection to free RAM
##### Input data #####
###gene###
scFINEmerge2_gene.data <- Read10X(data.dir = "./scFINEmerge2_gene/outs/filtered_feature_bc_matrix/")
# count distribution
hist(colSums(as.data.frame(scFINEmerge2_gene.data)), n=50, main = "scFINEmerge2_gene_count_distribution", xlab = "count")
###TE###
scFINEmerge2_TE.data <- Read10X(data.dir = "./1_cellranger/scFINEmerge2_TE/outs/filtered_feature_bc_matrix/")
# count distribution
hist(colSums(as.data.frame(scFINEmerge2_TE.data)), n=50, main = "scFINEmerge2_gene_count_distribution", xlab = "count")
##### Initialize Seurat object #####
scFINEmerge2_gene <- CreateSeuratObject(scFINEmerge2_gene.data, project = "scFINEmerge2_gene", min.cells = 3, min.features = 200)
scFINEmerge2_TE <- CreateSeuratObject(scFINEmerge2_TE.data, project = "scFINEmerge2_TE")
##### Standard pre-processing workflow #####
## QC and selecting cells for further analysis
# "percent.mt": The percentage of reads that map to the mitochondrial genome
# Low-quality / dying cells often exhibit extensive mitochondrial contamination
scFINEmerge2_gene[["percent.mt"]] <- PercentageFeatureSet(scFINEmerge2_gene, pattern = "^MT-")
### Visualize QC metrics as a violin plot
pdf("./VlnPlot_QC_scFINEmerge2_gene_QC.pdf")
VlnPlot(scFINEmerge2_gene, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3, pt.size = 0.01)
VlnPlot(scFINEmerge2_TE, features = c("nFeature_RNA", "nCount_RNA"), group.by = NULL,ncol = 2, pt.size = 0.01)
dev.off()
##### Remove unwanted cells from the dataset #####
scFINEmerge2_gene <- subset(scFINEmerge2_gene, subset = nFeature_RNA > 200 & percent.mt < 30)
##### Normalizing the data #####
# scale factor (10,000 by default), log-transforms the result, Normalized values are stored in [["RNA"]]@data
scFINEmerge2_gene <- NormalizeData(scFINEmerge2_gene, normalization.method = "LogNormalize", scale.factor = 10000)
scFINEmerge2_TE <- NormalizeData(object = scFINEmerge2_TE, normalization.method = "LogNormalize", scale.factor = 10000)
##### Identification of highly variable features #####
# calculate a subset of features that exhibit high cell-to-cell variation in the dataset
scFINEmerge2_gene <- FindVariableFeatures(scFINEmerge2_gene, selection.method = "vst", nfeatures = 2000)
# Identify the 50 most highly variable genes
top50 <- head(VariableFeatures(scFINEmerge2_gene), 50)
# Store the high variation gene in file
write.table(top50,"./HVGs_top50.txt")
# plot variable features with and without labels
plot1 <- VariableFeaturePlot(scFINEmerge2_gene)
plot2 <- LabelPoints(plot = plot1, points = top10)
CombinePlots(plots = list(plot1, plot2))
dev.off()
scFINEmerge2_TE <- FindVariableFeatures(scFINEmerge2_TE, selection.method = "vst",nfeatures = 200)
# Identify the 50 most highly variable TEs
pdf("./dotplot_scFINEmerge2_TE_varTE.pdf", width = 15, height = 7)
top50 <- head(VariableFeatures(scFINEmerge2_TE), 50)
# Store the high variation TE in file
write.table(top50,"/HVTEs_top50.txt")
# plot variable features with and without labels
plot1 <- VariableFeaturePlot(scFINEmerge2_TE)
plot2 <- LabelPoints(plot = plot1, points = top50, repel = TRUE)
CombinePlots(plots = list(plot1, plot2))
dev.off()
##### Scale the data ######
# a standard pre-processing step prior to dimensional reduction techniques like PCA.
# Shifts the expression of each gene, so that the mean expression across cells is 0
# Scales the expression of each gene, so that the variance across cells is 1
# This step gives equal weight in downstream analyses, so that highly-expressed genes do not dominate
# The results of this are stored in [["RNA"]]@scale.data
all.genes <- rownames(scFINEmerge2_gene)
scFINEmerge2_gene <- ScaleData(scFINEmerge2_gene, features = all.genes)
all.TEs <- rownames(scFINEmerge2_TE)
scFINEmerge2_TE <- ScaleData(scFINEmerge2_TE, features = all.TEs)
##### Perform linear dimensional reduction #####
# perform PCA on the scaled data.
# By default, only the previously determined variable features are used as input, but can be defined using features argument if you wish to choose a different subset.
scFINEmerge2_gene <- RunPCA(scFINEmerge2_gene, features = VariableFeatures(object = scFINEmerge2_gene))
VizDimLoadings(scFINEmerge2_gene, dims = 1:2, reduction = "pca")
DimPlot(scFINEmerge2_gene, reduction = "pca")
scFINEmerge2_TE <- RunPCA(scFINEmerge2_TE, features = VariableFeatures(object = scFINEmerge2_TE))
VizDimLoadings(scFINEmerge2_TE, dims = 1:2, reduction = "pca")
DimPlot(scFINEmerge2_TE, reduction = "pca")
##### Determine the โdimensionalityโ of the dataset #####
ElbowPlot(scFINEmerge2_TE)
##### Cluster the cells #####
# Briefly, these methods embed cells in a graph structure - for example a K-nearest neighbor (KNN) graph, with edges drawn between cells with similar feature expression patterns, and then attempt to partition this graph into highly interconnected โquasi-cliquesโ or โcommunitiesโ.
scFINEmerge2_gene <- FindNeighbors(scFINEmerge2_gene, dims = 1:20) # dims = previously defined dimensionality of the dataset (first 20PCs)
scFINEmerge2_gene <- FindClusters(scFINEmerge2_gene, resolution = 0.5)
# Look at cluster IDs of the first 5 cells
head(Idents(scFINEmerge2_gene), 5)
# scFINEmerge2_TE <- FindNeighbors(scFINEmerge2_TE, dims = 1:20)
# scFINEmerge2_TE <- FindClusters(scFINEmerge2_TE, resolution = 0.5)
# head(Idents(scFINEmerge2_TE), 5)
##### Save the object #####
saveRDS(scFINEmerge2_gene, file = "./scFINEmerge2_gene.rds")
saveRDS(scFINEmerge2_TE, file = "./scFINEmerge2_TE.rds")
##### Finding differentially expressed features #####
# find markers for every cluster compared to all remaining cells, report only the positive ones
scFINEmerge2_gene.markers <- FindAllMarkers(scFINEmerge2_gene, only.pos = TRUE, min.pct = 0.25, logfc.threshold = 0.25)
scFINEmerge2_gene.markers %>% group_by(cluster) %>% top_n(n = 30, wt = avg_log2FC)
write.table(scFINEmerge2_gene.markers, "./list_cluster_markergenes_top30.txt")
scFINEmerge2_TE.markers <- FindAllMarkers(scFINEmerge2_TE, only.pos = TRUE, min.pct = 0.25, logfc.threshold = 0.25)
scFINEmerge2_TE.markers %>% group_by(cluster) %>% top_n(n = 30, wt = avg_log2FC)
write.table(scFINEmerge2_TE.markers, "./list_cluster_markerTEs_top30.txt")
##### Set TE counts in gene #####
TE.count.data <- GetAssayData(object = scFINEmerge2_TE[["RNA"]], slot = "counts")
union_matrix2 = matrix(nrow=1180,ncol=ncol(scFINEmerge2_gene@assays$RNA))
for( i in 1:ncol(scFINEmerge2_gene@assays$RNA)){
ifelse((colnames(scFINEmerge2_gene@assays$RNA)[i] %in% colnames(TE.count.data)),
(TE.count.data.ingene = TE.count.data[,c(colnames(scFINEmerge2_gene@assays$RNA)[i])]),
(TE.count.data.ingene = rep(0,1180)))
union_matrix2[,i] = TE.count.data.ingene
}
colnames(union_matrix2) = colnames(scFINEmerge2_gene@assays$RNA)
row.names(union_matrix2) = row.names(scFINEmerge2_TE[["RNA"]])
scFINEmerge2_gene_TE = scFINEmerge2_gene
scFINEmerge2_gene_TE[["TEcounts"]] <- CreateAssayObject(counts = union_matrix2)
scFINEmerge2_gene_TE <- NormalizeData(scFINEmerge2_gene_TE, assay = "TEcounts", normalization.method = "LogNormalize",
scale.factor = 1000)
scFINEmerge2_gene_TE <- ScaleData(scFINEmerge2_gene_TE, assay = "TEcounts")
saveRDS(scFINEmerge2_gene_TE, file = "./scFINEmerge2_gene_TE.rds")
##### Feature plot #####
genes = read.table("genelist.txt",header = TRUE, stringsAsFactors = FALSE)
folder_featureplot = "./Featureplot/gene/"
folder_violinplot = "./Vlnplot/gene/"
folder_ridgeplot = "./Ridgeplot/gene/"
### featureplot of genes from genelist
pdf(paste0(folder_featureplot,"Featureplot.pdf"),width = 8,height = 8)
for (i in 1:nrow(genes)){
if (genes[i,1] %in% (scFINEmerge2_gene@assays[["RNA"]]@counts@Dimnames[[1]])){
p=FeaturePlot(scFINEmerge2_gene,features = genes[i,1])
print(p)
}
}
dev.off()
TEs = read.table("TElist.txt",header = TRUE, stringsAsFactors = FALSE)
folder_featureplot = "./Featureplot/TE/"
folder_violinplot = "./Vlnplot/TE/"
folder_ridgeplot = "./Ridgeplot/TE/"
### featureplot of TEs from TElist
pdf(paste0(folder_featureplot, "Featureplot_scFINEmerge2_TE_in_gene.pdf"),width = 8,height = 8)
for (i in 1:nrow(TEs)){
if (TEs[i,1] %in% (scFINEmerge2_gene_TE@assays[["RNA"]]@counts@Dimnames[[1]])){
p=FeaturePlot(scFINEmerge2_gene_TE, features = TEs[i,1])
print(p)
}
}
dev.off()
|
import React, { useState } from "react";
async function getOrders(token) {
return fetch("http://localhost:8085/orders/received", {
method: "GET",
headers: {
"Content-Type": "application/json",
authorization: token,
status: "AwaitingApproval",
},
}).then((data) => data.json());
}
async function updateStatus(token, order_id, status) {
return fetch("http://localhost:8085/orders/status", {
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: token,
},
body: JSON.stringify({ order_id: order_id, status: status }),
}).then((data) => data.json());
}
const Pending = ({ token }) => {
const [orders, setOrders] = useState([]);
getOrders(token).then(setOrders);
setInterval(function () {
getOrders(token).then(setOrders);
}, 5000);
const element = orders.map((data1) => {
return (
<div className="hidden md:block">
<div className="grid md:grid-cols-7 gap-6 overflow-auto rounded-lg shadow p-2 text-sm tracking-wide text-left text-gray-700 whitespace-nowrap bg-gray-200 my-1">
<p className="p-1 font-bold text-green-500 hover:underline">
{data1.name}
</p>
<p className="p-1">{data1.isRefill ? "Refill" : "New"}</p>
<p className="p-1">{data1.brand}</p>
<p className="p-1">{data1.paymentMethod}</p>
<p className="p-1">{data1.capacity}</p>
<div>
{/* {show && <p>Accepted!</p>} */}
<button
onClick={(_) => updateStatus(token, data1.orderId, "Approved")}
type="button"
className="ml-14 md:w-[100px] mb-1 inline-block px-3 md:px-6 py-2.5 bg-green-500 text-white font-medium text-xs leading-tight uppercase rounded-full shadow-md hover:bg-green-600 hover:shadow-lg focus:bg-green-600 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-green-700 active:shadow-lg transition duration-150 ease-in-out mx-auto md:mx-0 "
>
{" "}
ACCEPT
{/* {show===true ? 'DECLINE':'ACCEPT'} */}
</button>
</div>
<button
onClick={(_) => updateStatus(token, data1.orderId, "Cancelled")}
type="button"
className="ml-16 md:w-[100px] mb-1 inline-block px-3 md:px-6 py-2.5 bg-gray-500 text-white font-medium text-xs leading-tight uppercase rounded-full shadow-md hover:bg-gray-600 hover:shadow-lg focus:bg-gray-600 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-gray-700 active:shadow-lg transition duration-150 ease-in-out mx-auto md:mx-0 "
>
DECLINE
</button>
</div>
</div>
);
});
const element2 = orders.map((data2) => {
return (
<div class=" m-4 md:hidden grid grid-cols-1 gap-4">
<div class="bg-gray-200 space-y-3 p-2 rounded-lg shadow">
<div class="items-center text-sm grid grid-cols-5 py-2 m-2 p-2">
<div>
<p className="p-1 text-green-500 font-bold hover:underline">
{data2.name}
</p>
</div>
<div>
<p className="p-1 ml-2">{data2.isRefill ? "Refill" : "New"}</p>
</div>
<div>
<p className="p-1 pl-2 hidden">{data2.brand}</p>
</div>
<div>
<p className="p-1 ">{data2.paymentMethod}</p>
</div>
<div>
<p className="pl-2">{data2.capacity}</p>
</div>
<div className="flex mt-2 ">
<button
onClick={(_) => updateStatus(token, data2.orderId, "Approved")}
type="button"
className="ml-1 md:w-[100px] mb-3 inline-block px-3 md:px-6 py-2.5 bg-green-500 text-white font-medium text-xs leading-tight uppercase rounded-full shadow-md hover:bg-green-600 hover:shadow-lg focus:bg-green-600 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-green-700 active:shadow-lg transition duration-150 ease-in-out mx-auto md:mx-0 "
>
ACCEPT
</button>
<button
onClick={(_) => updateStatus(token, data2.orderId, "Cancelled")}
type="button"
className="ml-4 md:w-[100px] mb-3 inline-block px-3 md:px-6 py-2.5 bg-gray-500 text-white font-medium text-xs leading-tight uppercase rounded-full shadow-md hover:bg-gray-600 hover:shadow-lg focus:bg-gray-600 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-gray-700 active:shadow-lg transition duration-150 ease-in-out mx-auto md:mx-0 "
>
DECLINE
</button>
</div>
</div>
</div>
</div>
);
});
return (
<div className="w-full p-5 h-screen bg-gray-100">
<h1 class="text-xl mb-2 ml-4 font-bold md:mx-auto">Pending Orders</h1>
<div className="bg-gray-300 border-b-2 border-gray-400 hidden md:block rounded-lg shadow">
<ul className="grid md:grid-cols-7 gap-8 pl-2 w-full p-3 text-sm font-semibold tracking-wide text-left">
<li className="p-1">Name</li>
<li className="p-1">Refill</li>
<li className="p-1">Brand</li>
<li className="p-1">PayMethod</li>
<li className="p-1">Capacity</li>
</ul>
</div>
{element}
{element2}
</div>
);
};
export default Pending;
|
import express from "express";
import { productModel, userModel } from "../dbRepo/Models.mjs";
import mongoose from "mongoose";
const router = express.Router();
router.post('/product', (req, res) => {
const body = req.body;
if ( // validation
!body.name
&& !body.price
&& !body.description
) {
res.status(400).send({
message: "required parameters missing",
});
return;
}
productModel.create(
{
name: body.name,
price: body.price,
description: body.description,
owner: new mongoose.Types.ObjectId(body.token._id)
},
(err, saved) => {
if (!err) {
console.log(saved);
res.send({
message: "product added successfully",
// data: data,
});
} else {
res.status(500).send({
message: "server error"
})
}
})
})
router.get('/products', (req, res) => {
const userId = new mongoose.Types.ObjectId(req.body.token._id);
productModel.find({ owner: userId, isDeleted: false }, {},
{
sort: { "_id": -1 },
limit: 100,
skip: 0
},
(err, data) => {
if (!err) {
res.send({
message: "got all products successfully",
data: data
})
} else {
res.status(500).send({
message: "server error"
})
}
});
})
// router.get('/product/:id', (req, res) => {
// const id = req.params.id;
// productModel.findOne({ _id: id }, (err, data) => {
// if (!err) {
// if (data) {
// res.send({
// message: `get product by id: ${data._id} success`,
// data: data
// });
// } else {
// res.status(404).send({
// message: "product not found",
// })
// }
// } else {
// res.status(500).send({
// message: "server error"
// })
// }
// });
// })
//
router.get('/product/:name', (req, res) => {
// console.log(req.params.name);
const queryName = req.params.name;
productModel.find({ name: { $regex: `${queryName}` } }
, (err, data) => {
if (!err) {
if (data) {
res.send({
message: 'get product success',
data: data,
});
} else {
res.status(404).send({
message: "product not found",
});
}
} else {
res.status(500).send({
message: "server error",
});
}
});
});
router.delete('/product/:id', (req, res) => {
const id = req.params.id;
productModel.deleteOne({ _id: id }, (err, deletedData) => {
console.log("deleted: ", deletedData);
if (!err) {
if (deletedData.deletedCount !== 0) {
res.send({
message: "Product has been deleted successfully",
})
} else {
res.status(404);
res.send({
message: "No Product found with this id: " + id,
})
}
} else {
res.status(500).send({
message: "server error"
})
}
});
})
router.put('/product/:id', async (req, res) => {
const body = req.body;
const id = req.params.id;
if (
!body.name ||
!body.price ||
!body.description
) {
res.status(400).send(` required parameter missing. example request body:
{
"name": "value",
"price": "value",
"category": "value",
"description": "value"
}`)
return;
}
try {
let data = await productModel.findByIdAndUpdate(id,
{
name: body.name,
price: body.price,
description: body.description
},
{ new: true }
).exec();
console.log('updated: ', data);
res.send({
message: "product modified successfully",
data: data
});
}
catch (error) {
console.log("error: ", error)
res.status(500).send({
message: "server error"
})
}
})
export default router
|
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
margin: 5px;
}
th, td {
padding: 5px;
}
input {
margin-bottom: 5px;
}
</style>
</head>
<body>
<button type="button" onclick="loadXMLDoc()">View Information about the Books</button>
<br><br>
<table id="data-table"></table>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "books.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table = "<tr><th>Title</th><th>Author</th><th>Genre</th><th>Price</th><th>Publish Date</th><th>Description</th></tr>";
var x = xmlDoc.getElementsByTagName("book");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("genre")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("price")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("publish_date")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("data-table").innerHTML = table;
}
</script>
</body>
</html>
|
import {
MigrationInterface,
QueryRunner,
Table,
TableForeignKey,
} from 'typeorm';
export default class CreatePermissionsUsers1611522938020
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
const checkIfTableExist = await queryRunner.hasTable('permissions_users');
if (!checkIfTableExist) {
await queryRunner.createTable(
new Table({
name: 'permissions_users',
columns: [
{
name: 'id',
type: 'int',
isPrimary: true,
isGenerated: true,
generationStrategy: 'increment',
},
{
name: 'permission_id',
type: 'int',
},
{
name: 'user_id',
type: 'int',
},
{
name: 'created_at',
type: 'timestamp',
default: 'now()',
},
{
name: 'updated_at',
type: 'timestamp',
default: 'now()',
},
{
name: 'deleted_at',
type: 'timestamp',
isNullable: true,
},
],
}),
);
await queryRunner.createForeignKey(
'permissions_users',
new TableForeignKey({
name: 'fk_permissions_users',
columnNames: ['permission_id'],
referencedColumnNames: ['id'],
referencedTableName: 'permissions',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
}),
);
await queryRunner.createForeignKey(
'permissions_users',
new TableForeignKey({
name: 'fk_users_permissions',
columnNames: ['user_id'],
referencedColumnNames: ['id'],
referencedTableName: 'users',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
}),
);
}
}
public async down(queryRunner: QueryRunner): Promise<void> {
const checkIfTableExist = await queryRunner.hasTable('permissions_users');
if (checkIfTableExist) {
await queryRunner.dropForeignKey(
'permissions_users',
'fk_permissions_users',
);
await queryRunner.dropForeignKey(
'permissions_users',
'fk_users_permissions',
);
await queryRunner.dropTable('permissions_users');
}
}
}
|
### Creating a new tray
1. If there is not an entry for the data source yet in src/enums/SearchScope.ts, add it.
1. Configure the title for your tray in src/config/ScopeTitleMap.ts
1. Configure the URL for the source in src/config/ScopeUrlMap.ts. This will be shown to
the user when there are no results.
1. Configure the metadata fields that should be displayed in the tray in src/config/ScopeFieldsMap.ts.
For most fields, this gives only a very basic display. If you need something more complex,
don't add it here.
1. If you need a more complex display of a metadata field, create a new component and
corresponding test in src/components/metadata. Then reference your new component in the
switch/case statement in src/components/metadata/SearchMetadata.vue.
1. Add the tray to the appropriate location in src/models/TrayOrder.ts.
* If you want to do this in a test-driven way, you can:
1. Add a new fixture to src/fixtures
1. Add a new test file to src/components/metadata, referencing data from your fixture
1. Add a new component to src/components/metadata to make your test pass
1. Add a failing test to src/components/metadata/SearchMetadata.test.ts for your search scope.
1. Add to the switch/case statement to make it pass.
1. Configure the tray's icon in src/config/ScopeIconMap.ts. If the icon isn't in
assets/app.css, add it there. You can find the appropriate value in
[orangelight](https://github.com/pulibrary/orangelight/blob/main/app/assets/stylesheets/icons/variables.scss).
1. Add the tray in the correct location in src/models/TrayOrder.ts.
|
<template>
<div>
<page-search
:searchItem="formItem"
@searchQueryClick="searchQueryClick"
@resetQueryClick="resetQueryClick"
></page-search>
<page-content
:contentConfig="tableConfig"
@openClick="openClick"
></page-content>
<page-model
:modelConfig="dialogConfig"
ref="model"
:modelData="allModelData"
@changeModel="changeModel"
@changeModelValue="changeModelValue"
:addOrEdit="addOrEdit"
></page-model>
</div>
</template>
<script>
import pageSearch from "@/components/page-search/page-search.vue";
import pageContent from "@/components/page-content/page-content.vue";
import pageModel from "@/components/page-model/page-model.vue";
import { mapGetters, mapState } from "vuex";
export default {
name: "users",
components: {
pageContent,
pageSearch,
pageModel,
},
data() {
return {
formItem: [
{
field: "name",
type: "input",
label: "็จๆทๅ",
placeholder: "่ฏท่พๅ
ฅ็จๆทๅ",
},
{
field: "realname",
type: "input",
label: "็ๅฎๅงๅ",
rules: [],
placeholder: "่ฏท่พๅ
ฅ็ๅฎๅงๅ",
},
{
field: "cellphone",
type: "input",
label: "ๆๆบๅท็ ",
rules: [],
placeholder: "่ฏท่พๅ
ฅๆๆบๅท็ ",
},
{
field: "enable",
type: "select",
label: "็จๆท็ถๆ",
rules: [],
placeholder: "่ฏท้ๆฉ็จๆท็ถๆ",
options: [
{
title: "ๅฏ็จ",
value: "1",
},
{
title: "็ฆ็จ",
value: "0",
},
],
},
{
field: "createTime",
type: "datepicker",
label: "ๅๅปบๆถ้ด",
otherOptions: {
type: "daterange",
startPlaceholder: "ๅผๅงๆถ้ด",
endPlaceholder: "็ปๆๆถ้ด",
rangeSeparator: "-",
},
},
],
tableConfig: {
title: "็จๆทๅ่กจ",
propList: [
{ prop: "name", label: "็จๆทๅ", minWidth: "100", slotName: "name" },
{
prop: "realname",
label: "็ๅฎๅงๅ",
minWidth: "100",
slotName: "realname",
},
{
prop: "cellphone",
label: "็ต่ฏๅท็ ",
minWidth: "100",
slotName: "cellphone",
},
{
prop: "enable",
label: "็ถๆ",
minWidth: "100",
slotName: "enable",
},
{
prop: "createAt",
label: "ๅๅปบๆถ้ด",
minWidth: "100",
slotName: "createAt",
},
{
prop: "updateAt",
label: "ๆดๆฐๆถ้ด",
minWidth: "100",
slotName: "updateAt",
},
{
prop: "",
label: "ๆไฝ",
minWidth: "120",
slotName: "handler",
},
],
showIndexColumn: true,
showSelectColumn: true,
},
dialogConfig: {
formItems: [
{
field: "name",
type: "input",
label: "็จๆทๅ",
placeholder: "่ฏท่พๅ
ฅ็จๆทๅ",
},
{
field: "realname",
type: "input",
label: "็ๅฎๅงๅ",
placeholder: "่ฏท่พๅ
ฅ็ๅฎๅงๅ",
},
{
field: "password",
type: "password",
label: "็จๆทๅฏ็ ",
placeholder: "่ฏท่พๅ
ฅ็จๆทๅฏ็ ",
isHidden: false,
},
{
field: "cellphone",
type: "input",
label: "็ต่ฏๅท็ ",
placeholder: "่ฏท่พๅ
ฅ็ต่ฏๅท็ ",
},
{
field: "departmentId",
type: "select",
label: "้ๆฉ้จ้จ",
placeholder: "่ฏท้ๆฉ้จ้จ",
options: [],
},
{
field: "roleId",
type: "select",
label: "้ๆฉ่ง่ฒ",
placeholder: "่ฏท้ๆฉ่ง่ฒ",
options: [],
},
],
labelWidth: "120px",
colLayout: {
span: 24,
},
itemStyle: {
padding: "10px 0",
},
},
page: {},
allModelData: {},
addOrEdit: false,
offset:0
};
},
provide() {
return {
AllFormData: this.formItem,
AllTableData: this.tableConfig,
};
},
methods: {
searchQueryClick(query) {
console.log(query);
console.log((this.page.currentPage - 1) * this.page.size, this.page.size);
const pageName = this.$route.name;
this.$store.commit("main/getSearchQuery", query);
this.offset = (this.page.currentPage - 1) * this.page.size
if(!this.page.size){
this.offset = 0
this.page.size = 10
}
this.$store.dispatch("main/contentListData", {
pageName,
queryInfo: {
...query,
offset: this.offset,
size: this.page.size,
},
});
},
resetQueryClick(resetData) {
console.log("็นๅปไบ้็ฝฎ");
const pageName = this.$route.name;
this.$store.commit("main/getSearchQuery", resetData);
console.log(resetData);
this.$store.dispatch("main/contentListData", {
pageName,
queryInfo: {
offset: 0,
size: 10,
},
});
},
openClick(changeBool, data) {
console.log(changeBool);
this.$refs.model.dialogVisible = true;
console.log('row',data);
if (changeBool) {
console.log("ไฟฎๆนๆฐๆฎ");
for (const i in data) {
console.log(i);
this.$set(this.allModelData, i, data[i]);
}
console.log(this.allModelData);
this.$store.commit('main/EditId',data.id)
// this.allModelData = data;
this.addOrEdit = true;
console.log("ไผ ็ปpage-model็data", data);
console.log("ไผ ็ปpage-model็ๆฐๆฎ", this.allModelData);
// ๆฏๅฆๆพ็คบpassword
let isPassword = this.$refs.model.modelConfig.formItems.find(
(item) => item.field == "password"
);
isPassword.isHidden = true;
} else {
console.log("ๆฐๅขๆฐๆฎ");
this.dialogConfig.formItems.forEach((item) => {
this.$set(this.allModelData, item.field, "");
});
this.addOrEdit = false;
// ๆฏๅฆๆพ็คบpassword
let isPassword = this.$refs.model.modelConfig.formItems.find(
(item) => item.field == "password"
);
isPassword.isHidden = false;
}
},
changeModel(changeBool) {
this.$refs.model.dialogVisible = changeBool;
},
changeModelValue(itemName, val) {
console.log("userไธญๅพๅฐmodelๆนๅ็ๅผ", itemName, val);
}
},
computed: {
...mapGetters("main", ["departmentOption", "roleOption"]),
...mapState("main", ["menuData"]),
},
watch: {
departmentOption: {
handler(newValue, oldValue) {
console.log("watchไธญ็ๅฌๅฐ็ๆฐๆฎ", newValue);
this.dialogConfig.formItems.forEach((item) => {
if (item.field == "departmentId") {
item.options = this.departmentOption;
}
});
},
},
roleOption: {
handler(newValue, oldValue) {
console.log("watchไธญ็ๅฌๅฐ็ๆฐๆฎ", newValue);
this.dialogConfig.formItems.forEach((item) => {
if (item.field == "roleId") {
item.options = this.roleOption;
}
});
},
},
},
mounted(){
this.resetQueryClick()
}
};
</script>
<style scoped lang="less"></style>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.