text
stringlengths
184
4.48M
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script> <link href="https://fonts.googleapis.com/css?family=Raleway:400,700,800,900&display=swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="styles.css"> <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png"> <link rel="manifest" href="site.webmanifest"> <link rel="mask-icon" href="safari-pinned-tab.svg" color="#5bbad5"> <link rel="stylesheet" href="https://cdn.materialdesignicons.com/5.0.45/css/materialdesignicons.min.css"> <meta name="msapplication-TileColor" content="#da532c"> <meta name="theme-color" content="#ffffff"> <title>Envios.com</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <script src="XML_JSON.js"></script> </head> <body> <!--dir_alta_procesa_noseguro.php--> <div class="container p-5"> <div id="encabezado" class="row"> <div class="encabezado col-md"> <img class="mx-3" src="box.svg" alt="logo" width="60px"> <h1 class="encabezado-text col"><span> envios </span> <span class="com">.com</span> </h1> </div> </div> <div class="row my-3"> <h2 id="personal-info-header"><span class="mdi mdi-account-edit"> </span>Modificación de datos personales </h2> </div> <div class="my-2 row d-flex justify-content-center"> <div class="spinner-border" id="spinner" role="status"> <span class="sr-only">Loading...</span> </div> <div id="personal-info-query"> </div> </div> <div class="row my-3"> <form action="modifica_busca.php" id="personal-info-form" method="post"> Clave de la persona a Actualizar (id): <input class="form-control" type="number" name="id" min="0"><br> <input type="submit" class="btn btn-primary" value="Buscar"> </form> </div> <div class="row my-3" id="modifica-busca"> </div> <div class="row my-3"> <h2 id="shipping-info-header"><span class="mdi mdi-account-edit"> </span>Modificación de datos de envío</h2> </div> <div class="my-2 row d-flex justify-content-center"> <div class="spinner-border" id="spinner-shipping" role="status"> <span class="sr-only">Loading...</span> </div> <div id="shipping-info-query"> </div> </div> <div class="row my-3"> <form action="modifica_busca_direccion.php" id="shipping-info-form" method="post"> Clave de la dirección a Actualizar (id): <input class="form-control" type="number" name="id" min="0"><br> <input type="submit" class="btn btn-primary" value="Buscar"> </form> </div> <div class="row my-3" id="modifica-busca-direccion"> </div> <div class="row my-3"> <a role="button" class="btn btn-danger" href="formulario.html">Regresar</a> </div> </div> <script> $(document).ready(function () { queryPersonalInfo(); queryShippingInfo(); $('#personal-info-form').submit(function (e) { e.preventDefault(); var form_data = new FormData(this); $('#modifica-busca').slideUp(); $.ajax({ type: 'POST', url: 'modifica_busca.php', data: form_data, contentType: false, processData: false, success: function (response) { console.log('success'); $('#modifica-busca').html(response); $('#modifica-busca').slideDown(); }, error: function (response) { console.log(response); console.log('failure'); } }); }) $('#shipping-info-form').submit(function (e) { e.preventDefault(); $('#modifica-busca-direccion').hide(); $.post('modifica_busca_direccion.php', $(this).serialize(), function (data) { $('#modifica-busca-direccion').html(data); $('#modifica-busca-direccion').slideDown(); }) }) $('#personal-info-header').click(function () { $('#personal-info-query').slideToggle(); $('#personal-info-form').slideToggle(); $('#modifica-busca').slideToggle(); }); $('#shipping-info-header').click(function () { $('#shipping-info-query').slideToggle(); $('#shipping-info-form').slideToggle(); }) }); function queryPersonalInfo() { $.get("consulta.php", function (data, status) { if (status === "success") { $('#spinner').hide(); $('#personal-info-query').hide(); $("#personal-info-query").html(data); $('#personal-info-query').slideDown(); } }) } function queryShippingInfo() { $.get('consulta_envio.php', function (data) { $('#spinner-shipping').hide(); $("#shipping-info-query").hide(); $("#shipping-info-query").html(data); $("#shipping-info-query").slideDown(); }) } </script> </body> </html>
package com.entando.bundle.web.rest; import static com.entando.bundle.web.rest.TestUtil.sameInstant; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import com.entando.bundle.IntegrationTest; import com.entando.bundle.domain.Opinion; import com.entando.bundle.domain.enumeration.Sentiment; import com.entando.bundle.repository.OpinionRepository; import com.entando.bundle.service.criteria.OpinionCriteria; import com.entando.bundle.service.dto.OpinionDTO; import com.entando.bundle.service.mapper.OpinionMapper; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; import javax.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; /** * Integration tests for the {@link OpinionResource} REST controller. */ @IntegrationTest @AutoConfigureMockMvc @WithMockUser class OpinionResourceIT { private static final String DEFAULT_USERNAME = "AAAAAAAAAA"; private static final String UPDATED_USERNAME = "BBBBBBBBBB"; private static final String DEFAULT_PAGEID = "AAAAAAAAAA"; private static final String UPDATED_PAGEID = "BBBBBBBBBB"; private static final String DEFAULT_CONTENTID = "AAAAAAAAAA"; private static final String UPDATED_CONTENTID = "BBBBBBBBBB"; private static final String DEFAULT_LANGCODE = "AAAAAAAAAA"; private static final String UPDATED_LANGCODE = "BBBBBBBBBB"; private static final ZonedDateTime DEFAULT_CREATED = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC); private static final ZonedDateTime UPDATED_CREATED = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0); private static final ZonedDateTime SMALLER_CREATED = ZonedDateTime.ofInstant(Instant.ofEpochMilli(-1L), ZoneOffset.UTC); private static final String DEFAULT_TEXT = "AAAAAAAAAA"; private static final String UPDATED_TEXT = "BBBBBBBBBB"; private static final Integer DEFAULT_SENTENCES = 1; private static final Integer UPDATED_SENTENCES = 2; private static final Integer SMALLER_SENTENCES = 1 - 1; private static final Float DEFAULT_SCORE = 1F; private static final Float UPDATED_SCORE = 2F; private static final Float SMALLER_SCORE = 1F - 1F; private static final Sentiment DEFAULT_RESULT = Sentiment.VERY_NEGATIVE; private static final Sentiment UPDATED_RESULT = Sentiment.NEGATIVE; private static final String ENTITY_API_URL = "/api/opinions"; private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; private static Random random = new Random(); private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); @Autowired private OpinionRepository opinionRepository; @Autowired private OpinionMapper opinionMapper; @Autowired private EntityManager em; @Autowired private MockMvc restOpinionMockMvc; private Opinion opinion; /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Opinion createEntity(EntityManager em) { Opinion opinion = new Opinion() .username(DEFAULT_USERNAME) .pageid(DEFAULT_PAGEID) .contentid(DEFAULT_CONTENTID) .langcode(DEFAULT_LANGCODE) .created(DEFAULT_CREATED) .text(DEFAULT_TEXT) .sentences(DEFAULT_SENTENCES) .score(DEFAULT_SCORE) .result(DEFAULT_RESULT); return opinion; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Opinion createUpdatedEntity(EntityManager em) { Opinion opinion = new Opinion() .username(UPDATED_USERNAME) .pageid(UPDATED_PAGEID) .contentid(UPDATED_CONTENTID) .langcode(UPDATED_LANGCODE) .created(UPDATED_CREATED) .text(UPDATED_TEXT) .sentences(UPDATED_SENTENCES) .score(UPDATED_SCORE) .result(UPDATED_RESULT); return opinion; } @BeforeEach public void initTest() { opinion = createEntity(em); } @Test @Transactional void createOpinion() throws Exception { int databaseSizeBeforeCreate = opinionRepository.findAll().size(); // Create the Opinion OpinionDTO opinionDTO = opinionMapper.toDto(opinion); restOpinionMockMvc .perform( post(ENTITY_API_URL) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(opinionDTO)) ) .andExpect(status().isCreated()); // Validate the Opinion in the database List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeCreate + 1); Opinion testOpinion = opinionList.get(opinionList.size() - 1); assertThat(testOpinion.getUsername()).isEqualTo(DEFAULT_USERNAME); assertThat(testOpinion.getPageid()).isEqualTo(DEFAULT_PAGEID); assertThat(testOpinion.getContentid()).isEqualTo(DEFAULT_CONTENTID); assertThat(testOpinion.getLangcode()).isEqualTo(DEFAULT_LANGCODE); assertThat(testOpinion.getCreated()).isEqualTo(DEFAULT_CREATED); assertThat(testOpinion.getText()).isEqualTo(DEFAULT_TEXT); assertThat(testOpinion.getSentences()).isEqualTo(DEFAULT_SENTENCES); assertThat(testOpinion.getScore()).isEqualTo(DEFAULT_SCORE); assertThat(testOpinion.getResult()).isEqualTo(DEFAULT_RESULT); } @Test @Transactional void createOpinionWithExistingId() throws Exception { // Create the Opinion with an existing ID opinion.setId(1L); OpinionDTO opinionDTO = opinionMapper.toDto(opinion); int databaseSizeBeforeCreate = opinionRepository.findAll().size(); // An entity with an existing ID cannot be created, so this API call must fail restOpinionMockMvc .perform( post(ENTITY_API_URL) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(opinionDTO)) ) .andExpect(status().isBadRequest()); // Validate the Opinion in the database List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional void getAllOpinions() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList restOpinionMockMvc .perform(get(ENTITY_API_URL + "?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(opinion.getId().intValue()))) .andExpect(jsonPath("$.[*].username").value(hasItem(DEFAULT_USERNAME))) .andExpect(jsonPath("$.[*].pageid").value(hasItem(DEFAULT_PAGEID))) .andExpect(jsonPath("$.[*].contentid").value(hasItem(DEFAULT_CONTENTID))) .andExpect(jsonPath("$.[*].langcode").value(hasItem(DEFAULT_LANGCODE))) .andExpect(jsonPath("$.[*].created").value(hasItem(sameInstant(DEFAULT_CREATED)))) .andExpect(jsonPath("$.[*].text").value(hasItem(DEFAULT_TEXT))) .andExpect(jsonPath("$.[*].sentences").value(hasItem(DEFAULT_SENTENCES))) .andExpect(jsonPath("$.[*].score").value(hasItem(DEFAULT_SCORE.doubleValue()))) .andExpect(jsonPath("$.[*].result").value(hasItem(DEFAULT_RESULT.toString()))); } @Test @Transactional void getOpinion() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get the opinion restOpinionMockMvc .perform(get(ENTITY_API_URL_ID, opinion.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(opinion.getId().intValue())) .andExpect(jsonPath("$.username").value(DEFAULT_USERNAME)) .andExpect(jsonPath("$.pageid").value(DEFAULT_PAGEID)) .andExpect(jsonPath("$.contentid").value(DEFAULT_CONTENTID)) .andExpect(jsonPath("$.langcode").value(DEFAULT_LANGCODE)) .andExpect(jsonPath("$.created").value(sameInstant(DEFAULT_CREATED))) .andExpect(jsonPath("$.text").value(DEFAULT_TEXT)) .andExpect(jsonPath("$.sentences").value(DEFAULT_SENTENCES)) .andExpect(jsonPath("$.score").value(DEFAULT_SCORE.doubleValue())) .andExpect(jsonPath("$.result").value(DEFAULT_RESULT.toString())); } @Test @Transactional void getOpinionsByIdFiltering() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); Long id = opinion.getId(); defaultOpinionShouldBeFound("id.equals=" + id); defaultOpinionShouldNotBeFound("id.notEquals=" + id); defaultOpinionShouldBeFound("id.greaterThanOrEqual=" + id); defaultOpinionShouldNotBeFound("id.greaterThan=" + id); defaultOpinionShouldBeFound("id.lessThanOrEqual=" + id); defaultOpinionShouldNotBeFound("id.lessThan=" + id); } @Test @Transactional void getAllOpinionsByUsernameIsEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where username equals to DEFAULT_USERNAME defaultOpinionShouldBeFound("username.equals=" + DEFAULT_USERNAME); // Get all the opinionList where username equals to UPDATED_USERNAME defaultOpinionShouldNotBeFound("username.equals=" + UPDATED_USERNAME); } @Test @Transactional void getAllOpinionsByUsernameIsNotEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where username not equals to DEFAULT_USERNAME defaultOpinionShouldNotBeFound("username.notEquals=" + DEFAULT_USERNAME); // Get all the opinionList where username not equals to UPDATED_USERNAME defaultOpinionShouldBeFound("username.notEquals=" + UPDATED_USERNAME); } @Test @Transactional void getAllOpinionsByUsernameIsInShouldWork() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where username in DEFAULT_USERNAME or UPDATED_USERNAME defaultOpinionShouldBeFound("username.in=" + DEFAULT_USERNAME + "," + UPDATED_USERNAME); // Get all the opinionList where username equals to UPDATED_USERNAME defaultOpinionShouldNotBeFound("username.in=" + UPDATED_USERNAME); } @Test @Transactional void getAllOpinionsByUsernameIsNullOrNotNull() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where username is not null defaultOpinionShouldBeFound("username.specified=true"); // Get all the opinionList where username is null defaultOpinionShouldNotBeFound("username.specified=false"); } @Test @Transactional void getAllOpinionsByUsernameContainsSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where username contains DEFAULT_USERNAME defaultOpinionShouldBeFound("username.contains=" + DEFAULT_USERNAME); // Get all the opinionList where username contains UPDATED_USERNAME defaultOpinionShouldNotBeFound("username.contains=" + UPDATED_USERNAME); } @Test @Transactional void getAllOpinionsByUsernameNotContainsSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where username does not contain DEFAULT_USERNAME defaultOpinionShouldNotBeFound("username.doesNotContain=" + DEFAULT_USERNAME); // Get all the opinionList where username does not contain UPDATED_USERNAME defaultOpinionShouldBeFound("username.doesNotContain=" + UPDATED_USERNAME); } @Test @Transactional void getAllOpinionsByPageidIsEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where pageid equals to DEFAULT_PAGEID defaultOpinionShouldBeFound("pageid.equals=" + DEFAULT_PAGEID); // Get all the opinionList where pageid equals to UPDATED_PAGEID defaultOpinionShouldNotBeFound("pageid.equals=" + UPDATED_PAGEID); } @Test @Transactional void getAllOpinionsByPageidIsNotEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where pageid not equals to DEFAULT_PAGEID defaultOpinionShouldNotBeFound("pageid.notEquals=" + DEFAULT_PAGEID); // Get all the opinionList where pageid not equals to UPDATED_PAGEID defaultOpinionShouldBeFound("pageid.notEquals=" + UPDATED_PAGEID); } @Test @Transactional void getAllOpinionsByPageidIsInShouldWork() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where pageid in DEFAULT_PAGEID or UPDATED_PAGEID defaultOpinionShouldBeFound("pageid.in=" + DEFAULT_PAGEID + "," + UPDATED_PAGEID); // Get all the opinionList where pageid equals to UPDATED_PAGEID defaultOpinionShouldNotBeFound("pageid.in=" + UPDATED_PAGEID); } @Test @Transactional void getAllOpinionsByPageidIsNullOrNotNull() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where pageid is not null defaultOpinionShouldBeFound("pageid.specified=true"); // Get all the opinionList where pageid is null defaultOpinionShouldNotBeFound("pageid.specified=false"); } @Test @Transactional void getAllOpinionsByPageidContainsSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where pageid contains DEFAULT_PAGEID defaultOpinionShouldBeFound("pageid.contains=" + DEFAULT_PAGEID); // Get all the opinionList where pageid contains UPDATED_PAGEID defaultOpinionShouldNotBeFound("pageid.contains=" + UPDATED_PAGEID); } @Test @Transactional void getAllOpinionsByPageidNotContainsSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where pageid does not contain DEFAULT_PAGEID defaultOpinionShouldNotBeFound("pageid.doesNotContain=" + DEFAULT_PAGEID); // Get all the opinionList where pageid does not contain UPDATED_PAGEID defaultOpinionShouldBeFound("pageid.doesNotContain=" + UPDATED_PAGEID); } @Test @Transactional void getAllOpinionsByContentidIsEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where contentid equals to DEFAULT_CONTENTID defaultOpinionShouldBeFound("contentid.equals=" + DEFAULT_CONTENTID); // Get all the opinionList where contentid equals to UPDATED_CONTENTID defaultOpinionShouldNotBeFound("contentid.equals=" + UPDATED_CONTENTID); } @Test @Transactional void getAllOpinionsByContentidIsNotEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where contentid not equals to DEFAULT_CONTENTID defaultOpinionShouldNotBeFound("contentid.notEquals=" + DEFAULT_CONTENTID); // Get all the opinionList where contentid not equals to UPDATED_CONTENTID defaultOpinionShouldBeFound("contentid.notEquals=" + UPDATED_CONTENTID); } @Test @Transactional void getAllOpinionsByContentidIsInShouldWork() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where contentid in DEFAULT_CONTENTID or UPDATED_CONTENTID defaultOpinionShouldBeFound("contentid.in=" + DEFAULT_CONTENTID + "," + UPDATED_CONTENTID); // Get all the opinionList where contentid equals to UPDATED_CONTENTID defaultOpinionShouldNotBeFound("contentid.in=" + UPDATED_CONTENTID); } @Test @Transactional void getAllOpinionsByContentidIsNullOrNotNull() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where contentid is not null defaultOpinionShouldBeFound("contentid.specified=true"); // Get all the opinionList where contentid is null defaultOpinionShouldNotBeFound("contentid.specified=false"); } @Test @Transactional void getAllOpinionsByContentidContainsSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where contentid contains DEFAULT_CONTENTID defaultOpinionShouldBeFound("contentid.contains=" + DEFAULT_CONTENTID); // Get all the opinionList where contentid contains UPDATED_CONTENTID defaultOpinionShouldNotBeFound("contentid.contains=" + UPDATED_CONTENTID); } @Test @Transactional void getAllOpinionsByContentidNotContainsSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where contentid does not contain DEFAULT_CONTENTID defaultOpinionShouldNotBeFound("contentid.doesNotContain=" + DEFAULT_CONTENTID); // Get all the opinionList where contentid does not contain UPDATED_CONTENTID defaultOpinionShouldBeFound("contentid.doesNotContain=" + UPDATED_CONTENTID); } @Test @Transactional void getAllOpinionsByLangcodeIsEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where langcode equals to DEFAULT_LANGCODE defaultOpinionShouldBeFound("langcode.equals=" + DEFAULT_LANGCODE); // Get all the opinionList where langcode equals to UPDATED_LANGCODE defaultOpinionShouldNotBeFound("langcode.equals=" + UPDATED_LANGCODE); } @Test @Transactional void getAllOpinionsByLangcodeIsNotEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where langcode not equals to DEFAULT_LANGCODE defaultOpinionShouldNotBeFound("langcode.notEquals=" + DEFAULT_LANGCODE); // Get all the opinionList where langcode not equals to UPDATED_LANGCODE defaultOpinionShouldBeFound("langcode.notEquals=" + UPDATED_LANGCODE); } @Test @Transactional void getAllOpinionsByLangcodeIsInShouldWork() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where langcode in DEFAULT_LANGCODE or UPDATED_LANGCODE defaultOpinionShouldBeFound("langcode.in=" + DEFAULT_LANGCODE + "," + UPDATED_LANGCODE); // Get all the opinionList where langcode equals to UPDATED_LANGCODE defaultOpinionShouldNotBeFound("langcode.in=" + UPDATED_LANGCODE); } @Test @Transactional void getAllOpinionsByLangcodeIsNullOrNotNull() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where langcode is not null defaultOpinionShouldBeFound("langcode.specified=true"); // Get all the opinionList where langcode is null defaultOpinionShouldNotBeFound("langcode.specified=false"); } @Test @Transactional void getAllOpinionsByLangcodeContainsSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where langcode contains DEFAULT_LANGCODE defaultOpinionShouldBeFound("langcode.contains=" + DEFAULT_LANGCODE); // Get all the opinionList where langcode contains UPDATED_LANGCODE defaultOpinionShouldNotBeFound("langcode.contains=" + UPDATED_LANGCODE); } @Test @Transactional void getAllOpinionsByLangcodeNotContainsSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where langcode does not contain DEFAULT_LANGCODE defaultOpinionShouldNotBeFound("langcode.doesNotContain=" + DEFAULT_LANGCODE); // Get all the opinionList where langcode does not contain UPDATED_LANGCODE defaultOpinionShouldBeFound("langcode.doesNotContain=" + UPDATED_LANGCODE); } @Test @Transactional void getAllOpinionsByCreatedIsEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where created equals to DEFAULT_CREATED defaultOpinionShouldBeFound("created.equals=" + DEFAULT_CREATED); // Get all the opinionList where created equals to UPDATED_CREATED defaultOpinionShouldNotBeFound("created.equals=" + UPDATED_CREATED); } @Test @Transactional void getAllOpinionsByCreatedIsNotEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where created not equals to DEFAULT_CREATED defaultOpinionShouldNotBeFound("created.notEquals=" + DEFAULT_CREATED); // Get all the opinionList where created not equals to UPDATED_CREATED defaultOpinionShouldBeFound("created.notEquals=" + UPDATED_CREATED); } @Test @Transactional void getAllOpinionsByCreatedIsInShouldWork() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where created in DEFAULT_CREATED or UPDATED_CREATED defaultOpinionShouldBeFound("created.in=" + DEFAULT_CREATED + "," + UPDATED_CREATED); // Get all the opinionList where created equals to UPDATED_CREATED defaultOpinionShouldNotBeFound("created.in=" + UPDATED_CREATED); } @Test @Transactional void getAllOpinionsByCreatedIsNullOrNotNull() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where created is not null defaultOpinionShouldBeFound("created.specified=true"); // Get all the opinionList where created is null defaultOpinionShouldNotBeFound("created.specified=false"); } @Test @Transactional void getAllOpinionsByCreatedIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where created is greater than or equal to DEFAULT_CREATED defaultOpinionShouldBeFound("created.greaterThanOrEqual=" + DEFAULT_CREATED); // Get all the opinionList where created is greater than or equal to UPDATED_CREATED defaultOpinionShouldNotBeFound("created.greaterThanOrEqual=" + UPDATED_CREATED); } @Test @Transactional void getAllOpinionsByCreatedIsLessThanOrEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where created is less than or equal to DEFAULT_CREATED defaultOpinionShouldBeFound("created.lessThanOrEqual=" + DEFAULT_CREATED); // Get all the opinionList where created is less than or equal to SMALLER_CREATED defaultOpinionShouldNotBeFound("created.lessThanOrEqual=" + SMALLER_CREATED); } @Test @Transactional void getAllOpinionsByCreatedIsLessThanSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where created is less than DEFAULT_CREATED defaultOpinionShouldNotBeFound("created.lessThan=" + DEFAULT_CREATED); // Get all the opinionList where created is less than UPDATED_CREATED defaultOpinionShouldBeFound("created.lessThan=" + UPDATED_CREATED); } @Test @Transactional void getAllOpinionsByCreatedIsGreaterThanSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where created is greater than DEFAULT_CREATED defaultOpinionShouldNotBeFound("created.greaterThan=" + DEFAULT_CREATED); // Get all the opinionList where created is greater than SMALLER_CREATED defaultOpinionShouldBeFound("created.greaterThan=" + SMALLER_CREATED); } @Test @Transactional void getAllOpinionsByTextIsEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where text equals to DEFAULT_TEXT defaultOpinionShouldBeFound("text.equals=" + DEFAULT_TEXT); // Get all the opinionList where text equals to UPDATED_TEXT defaultOpinionShouldNotBeFound("text.equals=" + UPDATED_TEXT); } @Test @Transactional void getAllOpinionsByTextIsNotEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where text not equals to DEFAULT_TEXT defaultOpinionShouldNotBeFound("text.notEquals=" + DEFAULT_TEXT); // Get all the opinionList where text not equals to UPDATED_TEXT defaultOpinionShouldBeFound("text.notEquals=" + UPDATED_TEXT); } @Test @Transactional void getAllOpinionsByTextIsInShouldWork() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where text in DEFAULT_TEXT or UPDATED_TEXT defaultOpinionShouldBeFound("text.in=" + DEFAULT_TEXT + "," + UPDATED_TEXT); // Get all the opinionList where text equals to UPDATED_TEXT defaultOpinionShouldNotBeFound("text.in=" + UPDATED_TEXT); } @Test @Transactional void getAllOpinionsByTextIsNullOrNotNull() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where text is not null defaultOpinionShouldBeFound("text.specified=true"); // Get all the opinionList where text is null defaultOpinionShouldNotBeFound("text.specified=false"); } @Test @Transactional void getAllOpinionsByTextContainsSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where text contains DEFAULT_TEXT defaultOpinionShouldBeFound("text.contains=" + DEFAULT_TEXT); // Get all the opinionList where text contains UPDATED_TEXT defaultOpinionShouldNotBeFound("text.contains=" + UPDATED_TEXT); } @Test @Transactional void getAllOpinionsByTextNotContainsSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where text does not contain DEFAULT_TEXT defaultOpinionShouldNotBeFound("text.doesNotContain=" + DEFAULT_TEXT); // Get all the opinionList where text does not contain UPDATED_TEXT defaultOpinionShouldBeFound("text.doesNotContain=" + UPDATED_TEXT); } @Test @Transactional void getAllOpinionsBySentencesIsEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where sentences equals to DEFAULT_SENTENCES defaultOpinionShouldBeFound("sentences.equals=" + DEFAULT_SENTENCES); // Get all the opinionList where sentences equals to UPDATED_SENTENCES defaultOpinionShouldNotBeFound("sentences.equals=" + UPDATED_SENTENCES); } @Test @Transactional void getAllOpinionsBySentencesIsNotEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where sentences not equals to DEFAULT_SENTENCES defaultOpinionShouldNotBeFound("sentences.notEquals=" + DEFAULT_SENTENCES); // Get all the opinionList where sentences not equals to UPDATED_SENTENCES defaultOpinionShouldBeFound("sentences.notEquals=" + UPDATED_SENTENCES); } @Test @Transactional void getAllOpinionsBySentencesIsInShouldWork() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where sentences in DEFAULT_SENTENCES or UPDATED_SENTENCES defaultOpinionShouldBeFound("sentences.in=" + DEFAULT_SENTENCES + "," + UPDATED_SENTENCES); // Get all the opinionList where sentences equals to UPDATED_SENTENCES defaultOpinionShouldNotBeFound("sentences.in=" + UPDATED_SENTENCES); } @Test @Transactional void getAllOpinionsBySentencesIsNullOrNotNull() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where sentences is not null defaultOpinionShouldBeFound("sentences.specified=true"); // Get all the opinionList where sentences is null defaultOpinionShouldNotBeFound("sentences.specified=false"); } @Test @Transactional void getAllOpinionsBySentencesIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where sentences is greater than or equal to DEFAULT_SENTENCES defaultOpinionShouldBeFound("sentences.greaterThanOrEqual=" + DEFAULT_SENTENCES); // Get all the opinionList where sentences is greater than or equal to UPDATED_SENTENCES defaultOpinionShouldNotBeFound("sentences.greaterThanOrEqual=" + UPDATED_SENTENCES); } @Test @Transactional void getAllOpinionsBySentencesIsLessThanOrEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where sentences is less than or equal to DEFAULT_SENTENCES defaultOpinionShouldBeFound("sentences.lessThanOrEqual=" + DEFAULT_SENTENCES); // Get all the opinionList where sentences is less than or equal to SMALLER_SENTENCES defaultOpinionShouldNotBeFound("sentences.lessThanOrEqual=" + SMALLER_SENTENCES); } @Test @Transactional void getAllOpinionsBySentencesIsLessThanSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where sentences is less than DEFAULT_SENTENCES defaultOpinionShouldNotBeFound("sentences.lessThan=" + DEFAULT_SENTENCES); // Get all the opinionList where sentences is less than UPDATED_SENTENCES defaultOpinionShouldBeFound("sentences.lessThan=" + UPDATED_SENTENCES); } @Test @Transactional void getAllOpinionsBySentencesIsGreaterThanSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where sentences is greater than DEFAULT_SENTENCES defaultOpinionShouldNotBeFound("sentences.greaterThan=" + DEFAULT_SENTENCES); // Get all the opinionList where sentences is greater than SMALLER_SENTENCES defaultOpinionShouldBeFound("sentences.greaterThan=" + SMALLER_SENTENCES); } @Test @Transactional void getAllOpinionsByScoreIsEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where score equals to DEFAULT_SCORE defaultOpinionShouldBeFound("score.equals=" + DEFAULT_SCORE); // Get all the opinionList where score equals to UPDATED_SCORE defaultOpinionShouldNotBeFound("score.equals=" + UPDATED_SCORE); } @Test @Transactional void getAllOpinionsByScoreIsNotEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where score not equals to DEFAULT_SCORE defaultOpinionShouldNotBeFound("score.notEquals=" + DEFAULT_SCORE); // Get all the opinionList where score not equals to UPDATED_SCORE defaultOpinionShouldBeFound("score.notEquals=" + UPDATED_SCORE); } @Test @Transactional void getAllOpinionsByScoreIsInShouldWork() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where score in DEFAULT_SCORE or UPDATED_SCORE defaultOpinionShouldBeFound("score.in=" + DEFAULT_SCORE + "," + UPDATED_SCORE); // Get all the opinionList where score equals to UPDATED_SCORE defaultOpinionShouldNotBeFound("score.in=" + UPDATED_SCORE); } @Test @Transactional void getAllOpinionsByScoreIsNullOrNotNull() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where score is not null defaultOpinionShouldBeFound("score.specified=true"); // Get all the opinionList where score is null defaultOpinionShouldNotBeFound("score.specified=false"); } @Test @Transactional void getAllOpinionsByScoreIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where score is greater than or equal to DEFAULT_SCORE defaultOpinionShouldBeFound("score.greaterThanOrEqual=" + DEFAULT_SCORE); // Get all the opinionList where score is greater than or equal to UPDATED_SCORE defaultOpinionShouldNotBeFound("score.greaterThanOrEqual=" + UPDATED_SCORE); } @Test @Transactional void getAllOpinionsByScoreIsLessThanOrEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where score is less than or equal to DEFAULT_SCORE defaultOpinionShouldBeFound("score.lessThanOrEqual=" + DEFAULT_SCORE); // Get all the opinionList where score is less than or equal to SMALLER_SCORE defaultOpinionShouldNotBeFound("score.lessThanOrEqual=" + SMALLER_SCORE); } @Test @Transactional void getAllOpinionsByScoreIsLessThanSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where score is less than DEFAULT_SCORE defaultOpinionShouldNotBeFound("score.lessThan=" + DEFAULT_SCORE); // Get all the opinionList where score is less than UPDATED_SCORE defaultOpinionShouldBeFound("score.lessThan=" + UPDATED_SCORE); } @Test @Transactional void getAllOpinionsByScoreIsGreaterThanSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where score is greater than DEFAULT_SCORE defaultOpinionShouldNotBeFound("score.greaterThan=" + DEFAULT_SCORE); // Get all the opinionList where score is greater than SMALLER_SCORE defaultOpinionShouldBeFound("score.greaterThan=" + SMALLER_SCORE); } @Test @Transactional void getAllOpinionsByResultIsEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where result equals to DEFAULT_RESULT defaultOpinionShouldBeFound("result.equals=" + DEFAULT_RESULT); // Get all the opinionList where result equals to UPDATED_RESULT defaultOpinionShouldNotBeFound("result.equals=" + UPDATED_RESULT); } @Test @Transactional void getAllOpinionsByResultIsNotEqualToSomething() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where result not equals to DEFAULT_RESULT defaultOpinionShouldNotBeFound("result.notEquals=" + DEFAULT_RESULT); // Get all the opinionList where result not equals to UPDATED_RESULT defaultOpinionShouldBeFound("result.notEquals=" + UPDATED_RESULT); } @Test @Transactional void getAllOpinionsByResultIsInShouldWork() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where result in DEFAULT_RESULT or UPDATED_RESULT defaultOpinionShouldBeFound("result.in=" + DEFAULT_RESULT + "," + UPDATED_RESULT); // Get all the opinionList where result equals to UPDATED_RESULT defaultOpinionShouldNotBeFound("result.in=" + UPDATED_RESULT); } @Test @Transactional void getAllOpinionsByResultIsNullOrNotNull() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); // Get all the opinionList where result is not null defaultOpinionShouldBeFound("result.specified=true"); // Get all the opinionList where result is null defaultOpinionShouldNotBeFound("result.specified=false"); } /** * Executes the search, and checks that the default entity is returned. */ private void defaultOpinionShouldBeFound(String filter) throws Exception { restOpinionMockMvc .perform(get(ENTITY_API_URL + "?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(opinion.getId().intValue()))) .andExpect(jsonPath("$.[*].username").value(hasItem(DEFAULT_USERNAME))) .andExpect(jsonPath("$.[*].pageid").value(hasItem(DEFAULT_PAGEID))) .andExpect(jsonPath("$.[*].contentid").value(hasItem(DEFAULT_CONTENTID))) .andExpect(jsonPath("$.[*].langcode").value(hasItem(DEFAULT_LANGCODE))) .andExpect(jsonPath("$.[*].created").value(hasItem(sameInstant(DEFAULT_CREATED)))) .andExpect(jsonPath("$.[*].text").value(hasItem(DEFAULT_TEXT))) .andExpect(jsonPath("$.[*].sentences").value(hasItem(DEFAULT_SENTENCES))) .andExpect(jsonPath("$.[*].score").value(hasItem(DEFAULT_SCORE.doubleValue()))) .andExpect(jsonPath("$.[*].result").value(hasItem(DEFAULT_RESULT.toString()))); // Check, that the count call also returns 1 restOpinionMockMvc .perform(get(ENTITY_API_URL + "/count?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(content().string("1")); } /** * Executes the search, and checks that the default entity is not returned. */ private void defaultOpinionShouldNotBeFound(String filter) throws Exception { restOpinionMockMvc .perform(get(ENTITY_API_URL + "?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$").isArray()) .andExpect(jsonPath("$").isEmpty()); // Check, that the count call also returns 0 restOpinionMockMvc .perform(get(ENTITY_API_URL + "/count?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(content().string("0")); } @Test @Transactional void getNonExistingOpinion() throws Exception { // Get the opinion restOpinionMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test @Transactional void putNewOpinion() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); int databaseSizeBeforeUpdate = opinionRepository.findAll().size(); // Update the opinion Opinion updatedOpinion = opinionRepository.findById(opinion.getId()).get(); // Disconnect from session so that the updates on updatedOpinion are not directly saved in db em.detach(updatedOpinion); updatedOpinion .username(UPDATED_USERNAME) .pageid(UPDATED_PAGEID) .contentid(UPDATED_CONTENTID) .langcode(UPDATED_LANGCODE) .created(UPDATED_CREATED) .text(UPDATED_TEXT) .sentences(UPDATED_SENTENCES) .score(UPDATED_SCORE) .result(UPDATED_RESULT); OpinionDTO opinionDTO = opinionMapper.toDto(updatedOpinion); restOpinionMockMvc .perform( put(ENTITY_API_URL_ID, opinionDTO.getId()) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(opinionDTO)) ) .andExpect(status().isOk()); // Validate the Opinion in the database List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeUpdate); Opinion testOpinion = opinionList.get(opinionList.size() - 1); assertThat(testOpinion.getUsername()).isEqualTo(UPDATED_USERNAME); assertThat(testOpinion.getPageid()).isEqualTo(UPDATED_PAGEID); assertThat(testOpinion.getContentid()).isEqualTo(UPDATED_CONTENTID); assertThat(testOpinion.getLangcode()).isEqualTo(UPDATED_LANGCODE); assertThat(testOpinion.getCreated()).isEqualTo(UPDATED_CREATED); assertThat(testOpinion.getText()).isEqualTo(UPDATED_TEXT); assertThat(testOpinion.getSentences()).isEqualTo(UPDATED_SENTENCES); assertThat(testOpinion.getScore()).isEqualTo(UPDATED_SCORE); assertThat(testOpinion.getResult()).isEqualTo(UPDATED_RESULT); } @Test @Transactional void putNonExistingOpinion() throws Exception { int databaseSizeBeforeUpdate = opinionRepository.findAll().size(); opinion.setId(count.incrementAndGet()); // Create the Opinion OpinionDTO opinionDTO = opinionMapper.toDto(opinion); // If the entity doesn't have an ID, it will throw BadRequestAlertException restOpinionMockMvc .perform( put(ENTITY_API_URL_ID, opinionDTO.getId()) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(opinionDTO)) ) .andExpect(status().isBadRequest()); // Validate the Opinion in the database List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void putWithIdMismatchOpinion() throws Exception { int databaseSizeBeforeUpdate = opinionRepository.findAll().size(); opinion.setId(count.incrementAndGet()); // Create the Opinion OpinionDTO opinionDTO = opinionMapper.toDto(opinion); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restOpinionMockMvc .perform( put(ENTITY_API_URL_ID, count.incrementAndGet()) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(opinionDTO)) ) .andExpect(status().isBadRequest()); // Validate the Opinion in the database List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void putWithMissingIdPathParamOpinion() throws Exception { int databaseSizeBeforeUpdate = opinionRepository.findAll().size(); opinion.setId(count.incrementAndGet()); // Create the Opinion OpinionDTO opinionDTO = opinionMapper.toDto(opinion); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restOpinionMockMvc .perform( put(ENTITY_API_URL) .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(opinionDTO)) ) .andExpect(status().isMethodNotAllowed()); // Validate the Opinion in the database List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void partialUpdateOpinionWithPatch() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); int databaseSizeBeforeUpdate = opinionRepository.findAll().size(); // Update the opinion using partial update Opinion partialUpdatedOpinion = new Opinion(); partialUpdatedOpinion.setId(opinion.getId()); partialUpdatedOpinion .username(UPDATED_USERNAME) .langcode(UPDATED_LANGCODE) .sentences(UPDATED_SENTENCES) .score(UPDATED_SCORE) .result(UPDATED_RESULT); restOpinionMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedOpinion.getId()) .with(csrf()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(partialUpdatedOpinion)) ) .andExpect(status().isOk()); // Validate the Opinion in the database List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeUpdate); Opinion testOpinion = opinionList.get(opinionList.size() - 1); assertThat(testOpinion.getUsername()).isEqualTo(UPDATED_USERNAME); assertThat(testOpinion.getPageid()).isEqualTo(DEFAULT_PAGEID); assertThat(testOpinion.getContentid()).isEqualTo(DEFAULT_CONTENTID); assertThat(testOpinion.getLangcode()).isEqualTo(UPDATED_LANGCODE); assertThat(testOpinion.getCreated()).isEqualTo(DEFAULT_CREATED); assertThat(testOpinion.getText()).isEqualTo(DEFAULT_TEXT); assertThat(testOpinion.getSentences()).isEqualTo(UPDATED_SENTENCES); assertThat(testOpinion.getScore()).isEqualTo(UPDATED_SCORE); assertThat(testOpinion.getResult()).isEqualTo(UPDATED_RESULT); } @Test @Transactional void fullUpdateOpinionWithPatch() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); int databaseSizeBeforeUpdate = opinionRepository.findAll().size(); // Update the opinion using partial update Opinion partialUpdatedOpinion = new Opinion(); partialUpdatedOpinion.setId(opinion.getId()); partialUpdatedOpinion .username(UPDATED_USERNAME) .pageid(UPDATED_PAGEID) .contentid(UPDATED_CONTENTID) .langcode(UPDATED_LANGCODE) .created(UPDATED_CREATED) .text(UPDATED_TEXT) .sentences(UPDATED_SENTENCES) .score(UPDATED_SCORE) .result(UPDATED_RESULT); restOpinionMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedOpinion.getId()) .with(csrf()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(partialUpdatedOpinion)) ) .andExpect(status().isOk()); // Validate the Opinion in the database List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeUpdate); Opinion testOpinion = opinionList.get(opinionList.size() - 1); assertThat(testOpinion.getUsername()).isEqualTo(UPDATED_USERNAME); assertThat(testOpinion.getPageid()).isEqualTo(UPDATED_PAGEID); assertThat(testOpinion.getContentid()).isEqualTo(UPDATED_CONTENTID); assertThat(testOpinion.getLangcode()).isEqualTo(UPDATED_LANGCODE); assertThat(testOpinion.getCreated()).isEqualTo(UPDATED_CREATED); assertThat(testOpinion.getText()).isEqualTo(UPDATED_TEXT); assertThat(testOpinion.getSentences()).isEqualTo(UPDATED_SENTENCES); assertThat(testOpinion.getScore()).isEqualTo(UPDATED_SCORE); assertThat(testOpinion.getResult()).isEqualTo(UPDATED_RESULT); } @Test @Transactional void patchNonExistingOpinion() throws Exception { int databaseSizeBeforeUpdate = opinionRepository.findAll().size(); opinion.setId(count.incrementAndGet()); // Create the Opinion OpinionDTO opinionDTO = opinionMapper.toDto(opinion); // If the entity doesn't have an ID, it will throw BadRequestAlertException restOpinionMockMvc .perform( patch(ENTITY_API_URL_ID, opinionDTO.getId()) .with(csrf()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(opinionDTO)) ) .andExpect(status().isBadRequest()); // Validate the Opinion in the database List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithIdMismatchOpinion() throws Exception { int databaseSizeBeforeUpdate = opinionRepository.findAll().size(); opinion.setId(count.incrementAndGet()); // Create the Opinion OpinionDTO opinionDTO = opinionMapper.toDto(opinion); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restOpinionMockMvc .perform( patch(ENTITY_API_URL_ID, count.incrementAndGet()) .with(csrf()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(opinionDTO)) ) .andExpect(status().isBadRequest()); // Validate the Opinion in the database List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithMissingIdPathParamOpinion() throws Exception { int databaseSizeBeforeUpdate = opinionRepository.findAll().size(); opinion.setId(count.incrementAndGet()); // Create the Opinion OpinionDTO opinionDTO = opinionMapper.toDto(opinion); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restOpinionMockMvc .perform( patch(ENTITY_API_URL) .with(csrf()) .contentType("application/merge-patch+json") .content(TestUtil.convertObjectToJsonBytes(opinionDTO)) ) .andExpect(status().isMethodNotAllowed()); // Validate the Opinion in the database List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional void deleteOpinion() throws Exception { // Initialize the database opinionRepository.saveAndFlush(opinion); int databaseSizeBeforeDelete = opinionRepository.findAll().size(); // Delete the opinion restOpinionMockMvc .perform(delete(ENTITY_API_URL_ID, opinion.getId()).with(csrf()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); // Validate the database contains one less item List<Opinion> opinionList = opinionRepository.findAll(); assertThat(opinionList).hasSize(databaseSizeBeforeDelete - 1); } }
// Copyright © 2018 Jakkrit Sittiwerapong <EMAIL ADDRESS> // // 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 cmd import ( "fmt" "io/ioutil" "log" "os" "pmi/corpus" "github.com/spf13/cobra" ) var stopwordFlg bool var rootCmd = &cobra.Command{ Use: "pmi", Short: "CACM mutual word count", Long: `This CLI helps user to observe/summarize the various statistics in CACM corpus such as unigram wordcount, bigram wordcount`, Run: func(cmd *cobra.Command, args []string) { content, err := readFileContent(args) if err != nil { log.Fatalln(err) } PMIExecute(content) }, } func init() { rootCmd.Flags().BoolVar(&stopwordFlg, "s", false, "enable stopword remove") } //Execute execute command here. func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func readFileContent(args []string) (string, error) { path := "cacm/cacm.all" // if len(args) < 1 { // return "", fmt.Errorf("no configuration file specified, using default path: %s", path) // } // path = args[0] // if path == "d" { // path = "cacm/cacm.all" // } content, err := readFile(path) if err != nil { return "", fmt.Errorf("no configuration file found with path specified: %s", path) } return content, nil } func getStopwords() []string { var stopwords []string if stopwordFlg { stopwordContent, err := readFile("cacm/common_words") if err != nil { log.Fatalln("error during get stopwords from file") } stopwords = corpus.GetStopWords(stopwordContent) } return stopwords } //PMIExecute execute main function func PMIExecute(filecontent string) { docCollection := corpus.Ingest(filecontent) pmi := corpus.CreatePMI(&docCollection, getStopwords()) pmi.TopCountList(10, "mutual", false) } func readFile(pathToFile string) (string, error) { dat, err := ioutil.ReadFile(pathToFile) return string(dat), err }
import path from "path" import { openSync } from "fs" import { kill as killProcess } from "process" import { spawn } from "child_process" import { DATA_FILE, RESOURCE_FILE } from "../../constants/file" import { sleep } from "../../utils/process" import { createEmitter, Emitter } from "../../utils/emitter" import { readFile } from "../../utils/fs" import { request, Ws } from "../../utils/request" import { AppInitializeForm, ServerConnectionStatus, ServerServiceStatus, ServerPIDFile, ServerConnectionInfo, ServerConnectionError, ServerStaticInfo, WsToastResult } from "./model" /** * 对接后台服务部分的管理器。负责监视本频道对应的后台服务的运行状态,获取其运行参数,提供后台服务的管理功能,提供部分后台服务的功能接口。 * 管理器分为期望状态和实际状态两部分。 * - 实际状态是和实际的server运行状态几乎同步的。它会反映server的CLOSE、READY、OPEN、ERROR状态,以及server的连接信息,并通过事件告知变化。 * - 期望状态则指是否期望server在运行的状态。 * 管理器的工作逻辑通过ws连接实现。 * - 在连接期望为true时,管理器会尝试建立同server的连接。如果建立不能成功,则开始尝试修复连接。 * - 如果server未启动/无法检测到server的运行,则尝试启动server。 * - 如果server已启动,但始终无法成功连接,则认为存在某种连接问题需要报告。 * 在实际状态为已连接的情况下,与server的交互可以展开。 * - 可以获知server的健康检查状态(初始化状态),以及调用API对server进行初始化。 * - 可以通过事件侦听器访问server的ws事件。 */ export interface ServerManager { connection: ConnectionManager service: ServiceManager } interface ConnectionManager { /** * 获得或设定管理器的期望状态。 * @param value */ desired(value?: boolean): boolean /** * 获得当前连接的实际状态。 */ status(): ServerConnectionStatus /** * 获得当前连接的连接信息。 */ connectionInfo(): ServerConnectionInfo | null /** * 获得服务的一些静态信息。 */ staticInfo(): ServerStaticInfo /** * 强制关闭后台服务。 */ kill(): void /** * 连接状态发生改变的事件。 */ statusChangedEvent: Emitter<{ status: ServerConnectionStatus, info: ServerConnectionInfo | null, error: ServerConnectionError | null, appLoadStatus?: ServerServiceStatus }> /** * server ws接口所发送的事件。 */ wsToastEvent: Emitter<WsToastResult> } interface ServiceManager { /** * 获得当前server的加载状态。 */ status(): ServerServiceStatus /** * 对server进行初始化。 * @param form */ appInitialize(form: AppInitializeForm): Promise<void> /** * 加载状态发生改变的事件。 */ statusChangedEvent: Emitter<{ status: ServerServiceStatus }> } /** * 启动参数。 */ interface ServerManagerOptions { /** * app数据目录。 */ userDataPath: string /** * app频道。 */ channel: string /** * 在调试模式运行。 */ debug?: { /** * 使用此Host提供的后台服务,用于后台业务开发。此时后台服务启动管理的功能大部分被禁用。 */ serverFromHost?: string /** * 使用此文件夹下的后台服务,用于管理器的调试。此时不从userData目录下寻找后台服务程序。 */ serverFromFolder?: string } } export function createServerManager(options: ServerManagerOptions): ServerManager { const connectionManager = createConnectionManager(options) const serviceManager = createServiceManager(connectionManager) return { connection: connectionManager, service: serviceManager } } function createConnectionManager(options: ServerManagerOptions) { const debugMode = !!options.debug const serverBinPath = options.debug?.serverFromFolder ? path.resolve(options.debug?.serverFromFolder, RESOURCE_FILE.SERVER.BIN) : path.resolve(options.userDataPath, DATA_FILE.RESOURCE.SERVER_FOLDER, RESOURCE_FILE.SERVER.BIN) const channelPath = path.resolve(options.userDataPath, DATA_FILE.APPDATA.CHANNEL_FOLDER, options.channel) const serverPIDPath = path.resolve(channelPath, DATA_FILE.APPDATA.CHANNEL.SERVER_PID) const serverLogPath = path.resolve(channelPath, DATA_FILE.APPDATA.CHANNEL.SERVER_LOG) const statusChangedEvent = createEmitter<{ status: ServerConnectionStatus, info: ServerConnectionInfo | null, error: ServerConnectionError | null, appLoadStatus?: ServerServiceStatus }>() const wsToastEvent = createEmitter<WsToastResult>() let _desired: boolean = false let _status: ServerConnectionStatus = "CLOSE" let _connectionInfo: ServerConnectionInfo | null = null let _error: ServerConnectionError | null = null let _ws: Ws | null = null async function startConnectionListener() { if(!_desired) { setStatus({status: "CLOSE", info: null}) return } setStatus({status: "CONNECTING", info: null, error: null}) console.log("[ServerManager] Trying connect to server.") let serverStarted = false let pid: ServerConnectionInfo | null let health: ServerServiceStatus | null while(true) { if(!serverStarted) { //在不具备serverStarted标记的情况下,首先检查PID文件。如果不存在此文件,则尝试启动server pid = await checkForPIDFile(serverPIDPath) if(pid == null) { startServerProcess(channelPath, debugMode, serverLogPath, serverBinPath) serverStarted = true } } if(serverStarted) { //已有serverStarted标记时,则直接检查PID文件,开始等待PID文件准备完毕 //此处逻辑不与上一个if组合,因为上一个逻辑流程有可能在检查PID文件时直接将serverStarted置为true,从而复用这个流程 pid = await waitingForPIDFile(serverPIDPath, 10000) if(pid == null) { setStatus({status: "FAILED", info: null, error: {code: "PID_WAITING_TIMEOUT"}}) return } } if(!_desired) { setStatus({status: "CLOSE", info: null}) return } //根据PID地址,尝试请求连接server的/app/health地址,以做连接检查 try { health = await waitingForHealth(pid!.host, pid!.token, serverStarted ? 10000 : 5000) }catch (e) { setStatus({status: "FAILED", info: null, error: {code: "SERVER_REQUEST_ERROR", message: e instanceof Error ? e.message : `${e}`}}) return } if(health == null) { if(serverStarted) { //如果无法连接,且server是确定已经启动过的,那么报告错误 setStatus({ status: "FAILED", info: null, error: {code: "SERVER_WAITING_TIMEOUT"} }) return }else{ //如果无法连接,但还没尝试过启动server,那么先尝试启动server,然后从第1步重新开始 startServerProcess(channelPath, debugMode, serverLogPath, serverBinPath) serverStarted = true } }else{ //已成功验证连接,则主动退出loop,进入下一步 console.log(`[ServerManager] Successfully verified connection to server ${pid!.pid} (${pid!.host}). Server status is ${health}.`) break } } if(!_desired) { setStatus({status: "CLOSE", info: null}) return } //通过之后,尝试建立ws连接。如果无法连接,则报告错误 if(_ws != null) { _ws.terminate() _ws = null } try { _ws = await waitingForWsClient(pid!.host, pid!.token, { onMessage: onWsMessage, onClose: onWsClose }) setStatus({status: "OPEN", info: pid!, error: null, appLoadStatus: health}) console.log(`[ServerManager] Ws connection established.`) }catch (e) { setStatus({status: "FAILED", info: null, error: {code: "SERVER_CONNECT_ERROR", message: e instanceof Error ? e.message : `${e}`}}) } } async function startConnectionListenerInDebug() { if(!_desired) { setStatus({status: "CLOSE", info: null}) return } setStatus({status: "CONNECTING", info: null, error: null}) console.log("[ServerManager] Trying connect to server. Module is working in debug mode.") let health: ServerServiceStatus | null while(true) { //根据提供的debug地址,尝试请求连接server的/app/health地址,以做连接检查 try { health = await waitingForHealth(options.debug!.serverFromHost!, "dev", 1000) }catch (e) { setStatus({status: "FAILED", info: null, error: {code: "SERVER_REQUEST_ERROR", message: e instanceof Error ? e.message : `${e}`}}) console.log("[ServerManager] Trying connect to server failed. SERVER_REQUEST_ERROR.") return } if(health == null) { setStatus({ status: "FAILED", info: null, error: {code: "SERVER_WAITING_TIMEOUT"} }) console.log("[ServerManager] Trying connect to server failed. SERVER_WAITING_TIMEOUT. try again.") }else{ console.log(`[ServerManager] Successfully verified connection to server (${options.debug!.serverFromHost}). Server status is ${health}.`) break } } //通过之后,尝试建立ws连接。如果无法连接,则报告错误 if(_ws != null) { _ws.terminate() _ws = null } try { _ws = await waitingForWsClient(options.debug!.serverFromHost!, "dev", { onMessage: onWsMessage, onClose: startConnectionListenerInDebug }) const info: ServerConnectionInfo = {pid: 0, host: options.debug!.serverFromHost!, token: "dev", startTime: Date.now()} setStatus({status: "OPEN", info, error: null, appLoadStatus: health!}) console.log(`[ServerManager] Ws connection established.`) }catch (e) { setStatus({status: "FAILED", info: null, error: {code: "SERVER_CONNECT_ERROR", message: e instanceof Error ? e.message : `${e}`}}) } } function stopConnectionListener() { if(_ws != null) { _ws.terminate() _ws = null } setStatus({status: "CLOSE", info: null}) } function onWsMessage(data: string) { wsToastEvent.emit(JSON.parse(data)) } function onWsClose() { //监听到关闭消息时,尝试重连 if(!_desired) { setStatus({status: "CLOSE", info: null}) return } console.log("[ServerManager] Ws connection disconnected.") startConnectionListener().finally() } function setStatus(s: {status?: ServerConnectionStatus, info?: ServerConnectionInfo | null, error?: ServerConnectionError | null, appLoadStatus?: ServerServiceStatus}) { const oldStatus = {status: _status, info: _connectionInfo, error: _error} const newStatus = { status: s.status !== undefined ? s.status : _status, info: s.info !== undefined ? s.info : _connectionInfo, error: s.error !== undefined ? s.error : _error, appLoadStatus: s.appLoadStatus } _status = newStatus.status _connectionInfo = newStatus.info _error = newStatus.error if(newStatus.status !== oldStatus.status || newStatus.info !== oldStatus.info || newStatus.error !== oldStatus.error) { statusChangedEvent.emit(newStatus) } } function status(): ServerConnectionStatus { return _status } function desired(value?: boolean): boolean { if(value !== undefined && value !== _desired) { _desired = value if(_desired) { if(options.debug?.serverFromHost) { startConnectionListenerInDebug().finally() }else{ startConnectionListener().finally() } }else{ stopConnectionListener() } } return _desired } function connectionInfo(): ServerConnectionInfo | null { return _connectionInfo } function staticInfo(): ServerStaticInfo { return {logPath: serverLogPath} } function kill() { if(_connectionInfo !== null) { killProcess(_connectionInfo.pid) } } return { desired, status, connectionInfo, staticInfo, kill, statusChangedEvent, wsToastEvent } } function createServiceManager(connectionManager: ConnectionManager): ServiceManager { let _status: ServerServiceStatus = "NOT_CONNECTED" const statusChangedEvent = createEmitter<{ status: ServerServiceStatus }>() function setStatus(status: ServerServiceStatus) { if(status !== _status) { _status = status statusChangedEvent.emit({ status }) } } function status(): ServerServiceStatus { return _status } async function appInitialize(data: AppInitializeForm): Promise<void> { if(_status === "NOT_INITIALIZED" && connectionManager.status() === "OPEN" && connectionManager.connectionInfo() !== null) { const info = connectionManager.connectionInfo()! const res = await request({url: `http://${info.host}/app/initialize`, method: 'POST', headers: {'Authorization': `Bearer ${info.token}`}, data}) if(!res.ok) { throw new Error(`App initialize failed. ${res.message}`) } }else{ throw new Error("App cannot be initialized.") } } connectionManager.statusChangedEvent.addEventListener(({ status, info, appLoadStatus }) => { if(status === "OPEN" && info !== null) { //connection可用时,主动请求一次状态 if(appLoadStatus !== undefined) { setStatus(appLoadStatus) }else{ console.warn("[ServerManager] Connection is opened but appLoadStatus is undefined.") } }else{ //connection不可用时,总是将状态重置为NOT_CONNECTED setStatus("NOT_CONNECTED") } }) connectionManager.wsToastEvent.addEventListener(e => { //接收来自ws通知的appStatus变更事件。仅在connection状态可用时响应 if(e.type === "EVENT" && connectionManager.status() === "OPEN") { if(e.data.eventType === "app/app-status/changed") { setStatus((<{status: ServerServiceStatus}>e.data.events[e.data.events.length - 1].event).status) } } }) return { status, statusChangedEvent, appInitialize } } /** * 检查并收集pid文件内容。 */ async function checkForPIDFile(filepath: string): Promise<ServerConnectionInfo | null> { const serverPID = await readFile<ServerPIDFile>(filepath) return serverPID != null && serverPID.port != null && serverPID.token != null ? {pid: serverPID!.pid, host: `127.0.0.1:${serverPID!.port}`, token: serverPID!.token, startTime: serverPID!.startTime} : null } /** * 轮询等待,直到pid文件可用,或者超出最大等待时间。 */ async function waitingForPIDFile(filepath: string, timeout: number = 10000): Promise<ServerConnectionInfo | null> { let interval = 0 for(let i = 0; i < timeout; i += interval) { await sleep(interval) const result = await checkForPIDFile(filepath) if(result != null) return result if(interval < 200) interval += 50 } return null } /** * 检查server服务是否可用,并报告server的健康检查状态。 * @throws Error 如果接口返回API错误,则构造一个Error异常并抛出。 */ async function checkForHealth(host: string, token: string): Promise<ServerServiceStatus | null> { const res = await request({url: `http://${host}/app/health`, method: 'GET', headers: {'Authorization': `Bearer ${token}`}}) if(res.ok) { return (<{status: ServerServiceStatus}>res.data).status }else if(res.status) { throw new Error(`[${res.status}] ${res.code}: ${res.message}`) }else{ return null } } /** * 轮询等待,直到server服务可用,或超出最大等待时间。 * @throws Error 如果接口返回API错误,则构造一个Error异常并抛出。 */ async function waitingForHealth(host: string, token: string, timeout: number = 10000): Promise<ServerServiceStatus | null> { let interval = 0 for(let i = 0; i < timeout; i += interval) { await sleep(interval) const result = await checkForHealth(host, token) if(result != null) return result if(interval < 200) interval += 50 } return null } /** * 与Ws建立连接,并直到open事件发生之后,返回客户端。 */ function waitingForWsClient(host: string, token: string, events?: WsClientEvent): Promise<Ws | null> { return new Promise((resolve, reject) => { let ws: Ws try { ws = new Ws(`ws://${host}/websocket?access_token=${token}`) }catch (e) { reject(e) return } if(events?.onMessage) ws.on("message", (data) => events.onMessage!((<Buffer>data).toString())) if(events?.onClose) ws.on("close", events.onClose) if(events?.onError) ws.on("error", events.onError) ws.on("open", () => resolve(ws)) }) } /** * 启动server进程。 */ function startServerProcess(channelPath: string, debugMode: boolean, serverLogPath: string, serverBinPath: string) { const baseArgs = ['--channel-path', channelPath] const debugModeArgs = debugMode ? ['--force-token', 'dev'] : [] const args = [...baseArgs, ...debugModeArgs] const out = openSync(serverLogPath, "w") const s = spawn(serverBinPath, args, { detached: true, stdio: ["ignore", out, out] }) s.unref() console.log(`[ServerManager] Start server process: ${serverBinPath} ${args.join(" ")}`) } interface WsClientEvent { onMessage?(data: string): void onError?(e: Error): void onClose?(code: number): void }
import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'first_plugin_platform_interface.dart'; /// An implementation of [FirstPluginPlatform] that uses method channels. class MethodChannelFirstPlugin extends FirstPluginPlatform { /// The method channel used to interact with the native platform. @visibleForTesting final methodChannel = const MethodChannel('first_plugin'); @override Future<String?> getPlatformVersion() async { final version = await methodChannel.invokeMethod<String>('getPlatformVersion'); return version; } }
import React from 'react'; import PropTypes from 'prop-types'; import { dataTestId } from '../../../../utils'; const ProductList = ({ productsList }) => ( <table> <thead> <tr> <th>Item</th> <th>Descrição</th> <th>Quantidade</th> <th>Valor Unitário</th> <th>Sub-total</th> </tr> </thead> <tbody> { productsList.map((product, key) => ( <tr key={ `key-${key}` }> <td data-testid={ `${dataTestId.id41}${key}` }> { product.id } </td> <td data-testid={ `${dataTestId.id42}${key}` }> { product.name } </td> <td data-testid={ `${dataTestId.id43}${key}` }> { product.SalesProducts.quantity } </td> <td data-testid={ `${dataTestId.id46}${key}` }> { product.price } </td> <td data-testid={ `${dataTestId.id44}${key}` }> { (product.SalesProducts.quantity * product.price).toFixed(2) } </td> </tr> )) } </tbody> </table> ); ProductList.propTypes = { productsList: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number, name: PropTypes.string, price: PropTypes.string, SalesProducts: PropTypes.shape({ quantity: PropTypes.number, }), })).isRequired, }; export default ProductList;
class ApplicationController < ActionController::Base before_action :authenticate_user! before_action :configure_permitted_parameters, if: :devise_controller? before_action :set_locale helper_method :admin_user? def admin_user? current_user&.admin? end def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: %i[first_name last_name]) devise_parameter_sanitizer.permit(:account_update, keys: %i[first_name last_name]) end private def set_locale I18n.locale = extracted_locale || I18n.default_locale end def extracted_locale parsed_locale = params[:locale] I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil end end
/* * Copyright (C) 2020 The Android Open Source Project * * 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 com.example.cupcake import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import com.example.cupcake.databinding.FragmentStartBinding import com.example.cupcake.model.OrderViewModel /** * This is the first screen of the Cupcake app. The user can choose how many cupcakes to order. */ // TODO 3 : Memulai fragment awal yaitu fragment_start pada aplikasi class StartFragment : Fragment() { // Menggunakan variabel binding objek instance dengan hak akses private yang sesuai dengan layout fragment_start.xml // Properti ini bukan nol antara pemanggilan kembali siklus fungsi onCreateView() dan onDestroyView() ketika hierarki tampilan dilampirkan ke fragmen. private var binding: FragmentStartBinding? = null // Menggunakan delegasi variabel sharedViewModes kotlin 'by activityViewModels()' dari artefak fragmen-ktx private val sharedViewModel: OrderViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val fragmentBinding = FragmentStartBinding.inflate(inflater, container, false) binding = fragmentBinding return fragmentBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding?.startFragment = this } /** * Memulai pesanan dengan jumlah cupcake yang diinginkan dan menavigasikan ke layar berikutnya yaitu layar pilihan rasa cupcake */ fun orderCupcake(quantity: Int) { // Memperbarui sharedViewModel dengan parameter quantity yang di isi oleh pilihan jumlah cupcake yang akan di order sharedViewModel.setQuantity(quantity) // Seleksi if yang akan dijalankan Jika belum ada rasa yang diatur dalam sharedViewModel, tetapkan vanilla sebagai rasa default if (sharedViewModel.hasNoFlavorSet()) { sharedViewModel.setFlavor(getString(R.string.vanilla)) } // Mengarahkan atau menavigasikan ke tujuan fragment berikutnya yaitu flavorFragment untuk memilih rasa cupcakes findNavController().navigate(R.id.action_startFragment_to_flavorFragment) } /** * Metode siklus fungsi fragmen ini dipanggil saat hierarki tampilan yang terkait dengan fragmen sedang dihapus. * Akibatnya, dilakukan pembersihan objek yang mengikat. */ override fun onDestroyView() { super.onDestroyView() binding = null } }
import tensorflow as tf import numpy as np from PIL import Image # Load the TensorFlow Lite model interpreter = tf.lite.Interpreter(model_path='C:\\University\\FYP\\Code\\converted_model.tflite') interpreter.allocate_tensors() # Get input and output details input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # Load and preprocess the image image_path = 'C:\\University\\FYP\\Code\\result\\0.jpg' img = Image.open(image_path).resize((224, 224)) # Resize the image img_array = np.array(img, dtype=np.float32) / 255.0 # Normalize pixel values img_array = np.expand_dims(img_array, axis=0) # Add batch dimension # Set the input tensor interpreter.set_tensor(input_details[0]['index'], img_array) # Run inference interpreter.invoke() # Get the output tensor output_data = interpreter.get_tensor(output_details[0]['index']) # Assuming you have a classification model, you might want to decode the predictions class_labels = ['0', '1', '2', '3', '4'] predicted_class_index = np.argmax(output_data[0]) predicted_class_name = class_labels[predicted_class_index] # Display the results print("Predicted class: ", predicted_class_name) print("Prediction probabilities: ", output_data[0]) import matplotlib.pyplot as plt # Prediction probabilities probabilities = output_data[0] # Create bar graph plt.figure(figsize=(10,6)) plt.bar(class_labels, probabilities, color='blue') # Adding labels plt.xlabel('Classes') plt.ylabel('Prediction Probabilities') plt.title('Prediction Probabilities Bar Graph') # Show plot plt.xticks(rotation=45) plt.tight_layout() plt.show()
import React, { useState } from 'react'; import "./StyleCV.css" import { storage } from '../../config/firebase'; import { ref, getDownloadURL, uploadBytes } from "firebase/storage"; import axios from 'axios'; import { useSelector } from 'react-redux'; const CVComponent = ({ cvData, onUpdate, onDelete }) => { const tok = useSelector((state) => state.auth.token); const [isEditing, setIsEditing] = useState(false); const [selectedFile, setSelectedFile] = useState(null); const handleUpdate = async () => { const storageRef = ref(storage, `cvs/${selectedFile.name}`); console.log(storageRef); try { const snapshot = await uploadBytes(storageRef, selectedFile); const downloadURL = await getDownloadURL(snapshot.ref); await axios.put(`http://localhost:5292/api/User/Update-CV`, null, { params: { file: downloadURL }, headers: { 'Authorization': 'Bearer ' + tok, 'Content-Type': 'application/json' } }); // take Url onUpdate(downloadURL); setIsEditing(false); console.log(downloadURL); } catch (err) { console.log(err); } }; const handleDelete = () => { onDelete(); }; const handleInputChange = (e) => { if (e.target && e.target.files && e.target.files.length > 0) { setSelectedFile(e.target.files[0]); } }; return ( <div className="cv-container"> {isEditing ? ( <div> <input type="file" name="cv" onChange={handleInputChange} className="input-field" /> <button onClick={handleUpdate} className="action-button">Save</button> </div> ) : ( <div> {cvData ?<h2 className="cv-name"> <a href={cvData} target="_blank" rel="noopener noreferrer">View CV</a> </h2>:" " } <button onClick={() => setIsEditing(true)} className="action-button">{cvData ? (<span>Edite</span>) : (<span>Add CV</span>)}</button> {cvData ?<button onClick={handleDelete} className="action-button" style={{background:"red"}}>Delete</button>:" "} </div> )} </div> ); }; export default CVComponent;
package com.quanly.demo.model.entity; import lombok.Data; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Data @Entity @Table(name = "Customer") public class Customer { @Id @Column(name = "customer_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private int customerId; @Column(name = "contact_name", columnDefinition = "NVARCHAR(255)") private String contactName; @Column(name = "contact_phone", columnDefinition = "NVARCHAR(255)") private String contactPhone; @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "user_info_id") private UserInfo customerUserInfo; @OneToMany(mappedBy = "customerRoomCustomer", cascade = {CascadeType.PERSIST,CascadeType.MERGE}) private List<CustomerRoom> listCustomerRoom = new ArrayList<CustomerRoom>(); @OneToMany(mappedBy = "notifyCustomer", cascade = {CascadeType.PERSIST,CascadeType.MERGE}) private List<Notify> listNotify = new ArrayList<Notify>(); @OneToMany(mappedBy = "regimenDetailsCustomer", cascade = {CascadeType.PERSIST,CascadeType.MERGE}) private List<RegimenDetails> listRegimenDetails = new ArrayList<RegimenDetails>(); }
import 'package:flutter/material.dart'; void main() { runApp(MainApp()); } class MainApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: ThemeExample(), ); } } class ThemeExample extends StatefulWidget { @override _ThemeExampleState createState() => _ThemeExampleState(); } class _ThemeExampleState extends State<ThemeExample> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("主题"), ), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ //背景为蓝色,则title自动为白色 NavBar(color: Colors.blue, title: "标题"), //背景为白色,则title自动为黑色 NavBar(color: Colors.white, title: "标题"), NavBar(color: Color(0xffdc380d), title: "标题"), //如果颜色固定可以直接使用整数值 NavBar(color: Color(int.parse("00ff00", radix:16) | 0xFF000000), title: "标题"), //通过位运算符将Alpha设置为FF NavBar(color: Color(int.parse("0000ff", radix:16)).withAlpha(255), title: "标题"), //通过方法将Alpha设置为FF ], ), ), ); } } class NavBar extends StatelessWidget { final String title; final Color color; //背景颜色 NavBar({ Key key, this.color, this.title, }); @override Widget build(BuildContext context) { return Container( constraints: BoxConstraints( minHeight: 52, minWidth: double.infinity, ), decoration: BoxDecoration( color: color, boxShadow: [ //阴影 BoxShadow( color: Colors.black26, offset: Offset(0, 3), blurRadius: 3, ), ], ), child: Text( title, style: TextStyle( fontWeight: FontWeight.bold, //根据背景色亮度来确定Title颜色 color: color.computeLuminance() < 0.5 ? Colors.white : Colors.black, ), ), alignment: Alignment.center, ); } }
<template> <!-- Button trigger modal --> <div class="btn btn-outline-main" data-bs-toggle="modal" data-bs-target="#addYearModel" @click="atClickGetUsers" > Add year </div> <div class="modal fade" id="addYearModel" tabindex="-1" aria-labelledby="addYearModelLabel" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="addYearModelLabel">Selet a User</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body"> <div v-if="loading" class="mb-3 text-center"> Getting data please wait... </div> <select v-model="selectedUser" @change="changeSelected" class="form-select" aria-label="Default select example" > <option v-for="user in users" :key="user.id"> {{ user.fullName }} </option> </select> <div v-if="user.id !== null"> <input class="form-control mt-1" v-model="user.secret" placeholder="The family secret" /> <input class="form-control mt-1" v-model="user.year[0].vote_year" type="number" placeholder="Year" /> <input class="form-control mt-1" v-model="user.year[0].vote_url" placeholder="https://stem.nporadio2.nl/top2000-2020/share/v8hb9hvov8hb9hvoxl3hzxq33ddhxl3hzxq33ddh" /> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" > Close </button> <button :disabled="loading ?? ''" type="button" class="btn btn-outline-main" @click="atSave()" > Add Year </button> </div> </div> </div> </div> </template> <script> import { mapGetters } from "vuex"; import { updateUser } from "@/service/uploadData"; export default { name: "Add Year Modal", data() { return { users: [], loading: false, selectedUser: null, user: { id: null, secret: null, familyId: null, year: [ { vote_year: null, vote_url: null, }, ], }, }; }, computed: { ...mapGetters([ "getUserById", "getVottersFormSongs", "getIdByFullName", "getMainId", ]), }, methods: { changeSelected() { const userId = this.getIdByFullName(this.selectedUser); this.user.id = userId; }, atClickGetUsers() { // Clear users at click this.users = []; this.getVottersFormSongs.forEach((userId) => { this.users.push(this.getUserById(userId)); }); }, atSave() { this.user.familyId = this.getMainId; this.loading = true; updateUser(this.user, (r) => { if (r.message === "Request failed with status code 409") { this.loading = false; } else { setTimeout(() => { location.reload(); this.loading = false; }, 5000); } }); }, }, }; </script>
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_pdfview/flutter_pdfview.dart'; import 'package:flutter/services.dart'; import 'package:aplikasi_journal_2/models/journal_model.dart'; class JournalViewer extends StatefulWidget { final File file; final Journal journal; const JournalViewer({ Key? key, required this.file, required this.journal }) : super(key: key); @override JournalViewerPageState createState() => JournalViewerPageState(); } class JournalViewerPageState extends State<JournalViewer>{ late PDFViewController controller; int pages = 0; int indexPage = 0; @override Widget build(BuildContext context) { final name = widget.journal.title; final text = '${indexPage + 1} of $pages'; return Scaffold( appBar: AppBar( title: Text(name), actions: pages >= 2 ? [ Center(child: Text(text)), IconButton( icon: const Icon(Icons.chevron_left, size: 32), onPressed: () { final page = indexPage == 0 ? pages : indexPage - 1; controller.setPage(page); }, ), IconButton( icon: const Icon(Icons.chevron_right, size: 32), onPressed: () { final page = indexPage == pages - 1 ? 0 : indexPage + 1; controller.setPage(page); }, ), ] : null, ), body: PDFView( filePath: widget.file.path, pageSnap: false, pageFling: false, onRender: (pages) => setState(() => this.pages = pages!), onViewCreated: (controller) => setState(() => this.controller = controller), onPageChanged: (indexPage, _) => setState(() => this.indexPage = indexPage!), ), floatingActionButton: citateButton(), ); } Widget citateButton() => FloatingActionButton( backgroundColor: Colors.orange, child: const Icon(Icons.copy), onPressed: () { Clipboard.setData(ClipboardData(text:"${widget.journal.title}, ${widget.journal.publication_info}")) .then((_){ ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Journal Citated'))); }); }, ); }
import 'dart:ffi' as ffi; import 'package:yandex_maps_navikit/src/bindings/common/library.dart' as lib; import 'dart:core' as core; import 'package:meta/meta.dart'; import 'package:yandex_maps_navikit/src/bindings/annotations/annotations.dart' as bindings_annotations; import 'package:yandex_maps_navikit/src/bindings/common/native_types.dart' as native_types; import 'package:yandex_maps_navikit/src/bindings/common/string_map.dart' as string_map; import 'package:yandex_maps_navikit/src/bindings/common/to_native.dart' as to_native; import 'package:yandex_maps_navikit/src/bindings/common/vector.dart' as vector; import 'package:yandex_maps_navikit/src/bindings/common/weak_interface_wrapper.dart' as weak_interface_wrapper; import 'package:yandex_maps_navikit/src/mapkit/layers/data_source.dart' as mapkit_layers_data_source; import 'package:yandex_maps_navikit/src/mapkit/layers/layer_loaded_listener.dart' as mapkit_layers_layer_loaded_listener; part 'data_source_layer.containers.dart'; part 'data_source_layer.impl.dart'; abstract class DataSourceLayer implements ffi.Finalizable { /// Manages visibility of the layer. core.bool get active; set active(core.bool val); /// TODO: should be removed when /// https://st.yandex-team.ru/MAPSMOBCORE-16640 is done /// /// Invalidates data source and reloads all tiles. Must not be called if /// DataSource does not support versioning: LayerOptions.versionSupport = /// false; void invalidate(core.String version); /// Clears all cached tiles and starts new requests for tiles that are /// displayed. void clear(); /// Applies JSON style transformation to the layer. Replaces previous /// styling with the specified ID (if such exists). Stylings are applied /// in an ascending order. Set to empty string to clear previous styling /// with the specified ID. Returns true if the style was successfully /// parsed and false otherwise. If the returned value is false, the /// current style remains unchanged. core.bool setStyle({ required core.int id, required core.String style, }); /// Resets all JSON style transformations applied to the layer. void resetStyles(); /// Sets layer loaded listener. /// /// The class does not retain the object in the 'layerLoadedListener' parameter. /// It is your responsibility to maintain a strong reference to /// the target object while it is attached to a class. void setLayerLoadedListener( mapkit_layers_layer_loaded_listener.LayerLoadedListener? layerLoadedListener); /// Removes the data source layer from the parent layer. The object /// becomes invalid after that. void remove(); /// Sets data source listener. Use it to invalidate data source. /// /// The class does not retain the object in the 'dataSourceListener' parameter. /// It is your responsibility to maintain a strong reference to /// the target object while it is attached to a class. void setDataSourceListener( mapkit_layers_data_source.DataSourceListener? dataSourceListener); }
import React from "react"; import { twMerge } from "tailwind-merge"; interface GridProps extends React.HTMLAttributes<HTMLDivElement> { className?: string; rows?: number; columns?: number; } export const Grid: React.FC<GridProps> = ({ ...props }) => { const generateRows = () => { const rows = []; const totalRows = props.rows ? props.rows : 25; for (let i = 1; i <= totalRows; i++) { rows.push(i); } return rows; }; const generateColumns = () => { const columns = []; const totalColumns = props.columns ? props.columns : 25; for (let i = 1; i <= totalColumns; i++) { columns.push(i); } return columns; }; const rows = generateRows(); const columns = generateColumns(); return ( <div className={twMerge(`w-full flex flex-col`, props.className)} {...props} > {rows.map((rowIndex) => ( <div key={rowIndex} className={`flex items-center ${rowIndex === 1 && "[&>*]:border-t-[1px]"}`} > {columns.map((colIndex) => ( <div key={`${rowIndex}-${colIndex}`} className={`border-b-[1px] border-r-[1px] ${colIndex === 1 && "border-l-[1px]"} border-color-border-primary w-full aspect-square`} ></div> ))} </div> ))} </div> ); };
// install | flutter pub add intl //import 'package:intl/date_symbol_data_local.dart'; //import 'package:intl/intl.dart'; //# สามารถ set default lang ได้ที่ main void main() async { Intl.defaultLocale = "th"; initializeDateFormatting(); runApp(MyApp()); } //# รูปแบบการใช้งาน class MyDateFormat extends StatefulWidget { const MyDateFormat({super.key}); @override State<MyDateFormat> createState() => _MyDateFormatState(); } class _MyDateFormatState extends State<MyDateFormat> { var date = DateTime.now(); var formatDate = new DateFormat.yMEd('en'); var formatDate1 = new DateFormat.yMMMMEEEEd('th'); var formatDate2 = new DateFormat("dd/MMM/yyyy และ วันที่ dd เดือน MMMM ปี yyyy", 'th'); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Date formar")), body: Column(children: [ Expanded( child: Container( color: Color.fromARGB(255, 178, 148, 146), child: Center( child: Text( "${formatDate.format(date)}", style: TextStyle(color: Colors.white, fontSize: 25), )), )), Expanded( child: Container( color: Color.fromARGB(255, 203, 196, 196), child: Center( child: Text("${formatDate1.format(date)}", style: TextStyle(color: Colors.white, fontSize: 25))), )), Expanded( child: Container( color: Color.fromARGB(255, 178, 148, 146), child: Center( child: Text("${formatDate2.format(date)}", style: TextStyle(color: Colors.white, fontSize: 25))), )), ]), ); } }
import axios from "axios"; import "./Leaderboard.css"; import { useEffect, useState } from "react"; import { anime } from "../Types"; interface animeLeaderboard extends anime { ranking: number; } export default function Leaderboard() { const [images, setImages] = useState<animeLeaderboard[] | null>(null); const getLeaderboardData = async () => { const response = await axios.get("http://localhost:5000/leaderboard"); if (response.status === 200) { setImages(response.data); } }; useEffect(() => { getLeaderboardData(); }, []); return ( <div className="Leaderboard"> <div className="table-cont"> <table> <thead> <tr> <th>Ranking</th> <th>Image</th> <th>Title</th> <th>Rating</th> </tr> </thead> <tbody> {images && images.map((anime, index) => ( <tr key={index}> <td>{anime.ranking}</td> <td> <img src={`http://localhost:5000/${anime.image}`} width={100} ></img> </td> <td>{anime.title}</td> <td>{anime.rating}</td> </tr> ))} </tbody> </table> </div> </div> ); }
import axios from 'axios'; import React, { useContext, useEffect, useState } from 'react' import { HiOutlineBell } from 'react-icons/hi'; import { useHistory } from 'react-router-dom'; import changePath from '../changePath'; import { GlobalContext } from '../context/GlobalState'; import Post from './Post'; import UserProfile from './UserProfile'; import { format, register } from 'timeago.js'; import czDataFormat from '../format.jsCZ/CzFormat'; import PopupWindown from './global/PopupWindown'; import { AnimatePresence } from 'framer-motion'; const Notifications = () => { // registrovani cestiny do formatjs register('myLanguage', czDataFormat); const { user, socket, backgroundColor1, backgroundColor2, backgroundColor4 } = useContext(GlobalContext); // useState promenne const [notifications, setNotifications] = useState([]); const [numberOfNewNotifications, setNumberOfNewNotifications] = useState(); const [showNotifications, setShowNotifications] = useState(false); const [showPost, setShowPost] = useState(false); const [dataOfPost, setDataOfPost] = useState([]); const [friends, setFriends] = useState(); const history = useHistory(); // useEffect useEffect(() => { const setAllNotifications = async () => { // nacteni vsech notifikaci daneho uzivatele const allNotifications = await axios.get(changePath(`/notifications/getAllNotifications/${user._id}`)); setNotifications(allNotifications.data); setNumberOfNewNotifications(allNotifications.data.filter(notification => notification.readed === false).length); sortNotificationsByDate(); } setAllNotifications(); }, [user._id]) useEffect(() => { socket?.on("getNotification", (data) => { console.log("new notification", data); setNotificationsNewData(data); }) }, [socket]) useEffect(() => { const fetchAllFriends = async () => { const dataOfFriends = await axios.get(changePath(`/users/getAllFriends/${user._id}`)); setFriends(dataOfFriends.data); } fetchAllFriends(); }, []) // funkce const setNotificationsNewData = (data) => { setNumberOfNewNotifications(prev => prev + 1); setNotifications((notifications) => [...notifications, { _id: data.id, senderId: data.senderId, recieverId: data.recieverId, type: data.type, url: data.url, idOfPost: data.idOfPost, text: data.text, createdAt: data.date }]); sortNotificationsByDate(); } const sortNotificationsByDate = () => { setNotifications((prev) => [...prev.sort((p1, p2) => { return new Date(p2.createdAt) - new Date(p1.createdAt) })]); } const getAndShowPost = async (idOfPost, idOfNotification) => { // nacteni prispevku ktery chceme (podle id uzivatele ifOfPost) const currentPost = await axios.get(changePath(`/posts/getPost/${idOfPost}`)); setDataOfPost(currentPost.data); setShowPost(true); setShowNotifications(false); await setReadedToTrue(idOfNotification, false); } const setReadedToTrue = async (idOfNotification, link, senderId) => { var currentNotification = notifications.filter((notification) => notification._id === idOfNotification); !currentNotification[0].readed && setNumberOfNewNotifications(prev => prev - 1); console.log(currentNotification[0].readed); currentNotification[0].readed = true; setNotifications((prev) => [...prev.filter((notification) => notification._id !== idOfNotification)]); setNotifications((notification) => [...notification, currentNotification[0]]); sortNotificationsByDate(); console.log(senderId); await axios.put(changePath(`/notifications/changeReadedToTrue/`), { id: idOfNotification }).then(() => { link == 1 ? history.push(`/profile/${senderId}`) : link === 2 && history.push(`/`); }); } return ( <> <div className="Notifications"> { showNotifications && <div className="allNotificationsContainer" style={{ backgroundColor: "white" }}> { notifications.map((notification) => ( notification.type === 4 ? <div className="notificationMessagge linkNotificationToProfile opacity" style={notification.readed ? { backgroundColor: backgroundColor2, border: "1px solid" + backgroundColor1, color: backgroundColor1 } : { backgroundColor: backgroundColor1, color: backgroundColor4 }} onClick={() => setReadedToTrue(notification._id, 1, notification.senderId)}> <UserProfile friends={friends} idOfUser={notification.senderId} unReaded={!notification.readed} style={{ width: "40px", height: "40px", borderRadius: "50%" }} /> <span>{notification.text}</span> <span className="timeOfCreatedAtNotification">{format(notification.createdAt, 'myLanguage')}</span> </div> : notification.type === 7 ? <div className="notificationMessagge linkNotificationToProfile opacity" style={notification.readed ? { backgroundColor: backgroundColor2, border: "1px solid" + backgroundColor1, color: backgroundColor1 } : { backgroundColor: backgroundColor1, color: backgroundColor4 }} onClick={() => setReadedToTrue(notification._id, 2, notification.senderId)}> <UserProfile friends={friends} idOfUser={notification.senderId} unReaded={!notification.readed} style={{ width: "40px", height: "40px", borderRadius: "50%" }} /> <span>{notification.text}</span> <span className="timeOfCreatedAtNotification">{format(notification.createdAt, 'myLanguage')}</span> </div> : <button className="notificationMessagge opacity" style={notification.readed ? { backgroundColor: backgroundColor2, border: "1px solid" + backgroundColor1, color: backgroundColor1, } : { backgroundColor: backgroundColor1, color: backgroundColor4 }} onClick={() => getAndShowPost(notification.idOfPost, notification._id)}> <UserProfile friends={friends} idOfUser={notification.senderId} unReaded={!notification.readed} style={{ width: "40px", height: "40px", borderRadius: "50%" }} /> <span>{notification.text}</span> <span className="timeOfCreatedAtNotification">{format(notification.createdAt, 'myLanguage')}</span> </button> )) } </div> } <div className="notificationBell scaled pointer" onClick={() => setShowNotifications(prev => !prev)}> {numberOfNewNotifications > 0 && <span className="notificationNubmer">{numberOfNewNotifications}</span>} <HiOutlineBell style={{ color: backgroundColor1, width: "30px", height: "30px" }} /> </div> </div> <AnimatePresence initial={false} exitBeforeEnter={true} onExitComplete={() => null} > { showPost && <PopupWindown classNameMain="mainContainerForPost" classNameContainer="containerForPost" setVisible={setShowPost}> <Post post={dataOfPost} /> </PopupWindown> } </AnimatePresence> </> ) } export default Notifications
<!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> /* 动画 */ @keyframes leftToRight{ 0%{ transform: translateX(0px); } 50%{ transform: translateX(100px); } 100%{ transform: translateX(0px); } } .animation{ animation: leftToRight 3s; } /* 过渡 */ .transition{ transition: 3s background-color ease; } .blue{ background-color: blue; } .green{ background-color: green; } </style> <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> </head> <body> <div id="root"></div> <script> // 过渡:从一个状态变成另一个状态,比如颜色 // 动画:一个元素运动的情况 const app = Vue.createApp({ data(){ return { animate:{ animation:false, }, styleObj:{ background:'blue' } } }, methods:{ handleClick(){ this.animate.animation = !this.animate.animation }, handleTran(){ if(this.styleObj.background ==='blue'){ this.styleObj.background ='green' }else{ this.styleObj.background ='blue' } } }, template: ` <div> <div :class="animate">这是动画</div> <button @click="handleClick">切换</button> <div class="transition" :style="styleObj">这是过渡</div> <button @click="handleTran">切换</button> </div>` }) const vm = app.mount('#root') </script> </body> </html>
import jwt from 'jsonwebtoken' import InternalServerError from '../error/internal-server.error.js' import RedisCache from './redis.js' export const JwtTokenType = { EMAIL_CONFIRMATION: 'EMAIL_CONFIRMATION', ACCESS: 'ACCESS', PASSWORD_RECOVERY: 'PASSWORD_RECOVERY', REFRESH: 'REFRESH', } export const TimeValues = { ONE_HOUR: 3600, TWO_HOURS: 7200, ONE_DAY: 86400, SEVEN_DAYS: 604800, THIRTY_DAYS: 2592000, THREE_MONTHS: 7776000, } export const ExpirationTime = { [JwtTokenType.ACCESS]: TimeValues.THIRTY_DAYS, [JwtTokenType.EMAIL_CONFIRMATION]: TimeValues.ONE_HOUR, [JwtTokenType.PASSWORD_RECOVERY]: TimeValues.ONE_HOUR, [JwtTokenType.REFRESH]: TimeValues.THREE_MONTHS, } export function getCacheKeyAndValueNames({ type, token, value }) { switch (type) { case JwtTokenType.ACCESS: return { key: `${type}-${token}`, value: value } default: return { key: `${type}-${value}`, value: token } } } export function checkCachedValue({ type, token, value, cachedValue }) { switch (type) { case JwtTokenType.ACCESS: return value === cachedValue default: return token === cachedValue } } export async function decodeToken({ token, type }) { try { const secretOrPrivateKey = process.env[`JWT_${type}_SECRET`] const decoded = jwt.verify(token, secretOrPrivateKey) return decoded } catch (err) { throw new InternalServerError('Internal Error.') } } export async function generateJwt({ payload, type, cachedValue }) { try { const secretOrPrivateKey = process.env[`JWT_${type}_SECRET`] const expiresIn = getExpirationTime(type) const token = jwt.sign(payload, secretOrPrivateKey, { expiresIn, }) const { key, value } = getCacheKeyAndValueNames({ type, token, value: cachedValue, }) await RedisCache.setCache({ key, value, expirationTime: expiresIn, }) return token } catch (err) { throw new InternalServerError('Internal Error.') } } export async function getToken({ email, type }) { try { const isCached = await RedisCache.getCache(`${type}-${email}`) if (isCached) { return isCached } return false } catch (err) { throw new InternalServerError('Internal Error.') } } export async function validateToken({ token, type, value = null }) { try { const secretOrPrivateKey = process.env[`JWT_${type}_SECRET`] const decoded = jwt.verify(token, secretOrPrivateKey) if (!decoded) { return false } const { email } = decoded const { key } = getCacheKeyAndValueNames({ type, token, value: value ? value : email, }) const isCached = await RedisCache.getCache(key) if (!isCached) { return false } return checkCachedValue({ type, token, value: value ? value : email, cachedValue: isCached, }) } catch (err) { if (err.name === 'TokenExpiredError' || err.name === 'JsonWebTokenError') return false throw new InternalServerError('Internal Error.') } } export async function removeJwt({ token, type, value = null }) { try { const secretOrPrivateKey = process.env[`JWT_${type}_SECRET`] const decoded = jwt.verify(token, secretOrPrivateKey) if (!decoded) { return false } const { email } = decoded const { key } = getCacheKeyAndValueNames({ type, token, value: value ? value : email, }) const isCached = await RedisCache.deleteCache(key) if (!isCached) { return false } return decoded } catch (err) { if (err.name === 'TokenExpiredError' || err.name === 'JsonWebTokenError') return false throw new InternalServerError('Internal Error.') } } export function getExpirationTime(type) { return ExpirationTime[type] }
#global public #global namespace Time // Represents an interval of time, stored as a 64 bits integer struct TimeSpan { ticks: Ticks } impl TimeSpan { mtd opCmp(other: Self)->s32 { return ticks <=> other.ticks } // Returns the current date and time func now()->TimeSpan { var result: retval = from(DateTime.now()) return result } // Initialize the TimeSpan with the current date and time mtd setNow() { var dateTime = DateTime.now() using dateTime ticks = dateToTicks(year, month, day) ticks += timeToTicks(hour, minute, second, millisecond) } // Creates a TimeSpan with the given DateTime func from(dateTime: DateTime)->TimeSpan { var result: retval = undefined using result, dateTime ticks = dateToTicks(year, month, day) ticks += timeToTicks(hour, minute, second, millisecond) return result } // Converts a TimeSpan to a DateTime mtd toDateTime()->DateTime { var dateTime: retval = undefined using dateTime (year, month, day) = ticksToDate(ticks) (hour, minute, second, millisecond) = ticksToTime(ticks) return dateTime } // Add or remove the given amount of years to the TimeSpan mtd addYears(years: s32) { Debug.assert(-10000 <= years and years <= 10000, "overflow") addMonths(years * 12) } // Add or remove the given amount of months to the TimeSpan mtd addMonths(months: s32) { Debug.assert(-120000 <= months and months <= 120000, "overflow") var (y, m, d) = ticksToDate(ticks) let i = cast(s32) (m - 1) + months if i >= 0 { m = cast(u16) (i % 12 + 1) y += cast(u16) (i / 12) } else { m = cast(u16) (12 + (i + 1) % 12) y += cast(u16) ((i - 11) / 12) } Debug.assert(1 <= y and y <= 9999, "overflow") let days = daysInMonth(y, m) if (d > days) d = days ticks = dateToTicks(y, m, d) + (ticks % TicksPerDay) } // Add or remove the given amount of days to the TimeSpan mtd addDays(days: s32) { if days > 0 add(cast(u32) days, MillisPerDay) else remove(cast(u32) -days, MillisPerDay) } // Add or remove the given amount of hours to the TimeSpan mtd addHours(hours: s32) { if hours > 0 add(cast(u32) hours, MillisPerHour) else remove(cast(u32) -hours, MillisPerHour) } // Add or remove the given amount of minutes to the TimeSpan mtd addMinutes(minutes: s32) { if minutes > 0 add(cast(u32) minutes, MillisPerMinute) else remove(cast(u32) -minutes, MillisPerMinute) } // Add or remove the given amount of minutes to the TimeSpan mtd addSeconds(seconds: s32) { if seconds > 0 add(cast(u32) seconds, MillisPerSecond) else remove(cast(u32) -seconds, MillisPerSecond) } // Add or remove the given amount of minutes to the TimeSpan mtd addMilliSeconds(milliSeconds: s32) { if milliSeconds > 0 add(cast(u32) milliSeconds, 1) else remove(cast(u32) -milliSeconds, 1) } mtd totalDays() => ticks * (1.0'f64 / TicksPerDay) mtd totalHours() => ticks * (1.0'f64 / TicksPerHour) mtd totalMinutes() => ticks * (1.0'f64 / TicksPerMinute) mtd totalSeconds() => ticks * (1.0'f64 / TicksPerSecond) mtd totalMilliSeconds() => ticks * (1.0'f64 / TicksPerMilliSecond) internal mtd add(value: u32, scale: u64) { var millis = value * scale Debug.assert(millis <= MaxMillis, "overflow") millis *= TicksPerMilliSecond Debug.assert(millis <= (MaxTicks - ticks), "overflow") ticks += millis } internal mtd remove(value: u32, scale: u64) { var millis = value * scale Debug.assert(millis <= MaxMillis, "overflow") millis *= TicksPerMilliSecond Debug.assert(millis <= ticks, "ticks overflow") ticks -= millis } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace ProjektZUS { // Klasa głównego okna programu public partial class MainWindow : Form { public int NumerOfWorkers { get; set; } private string ImiePracownika { get; set; } private string NazwiskoPracownika { set; get; } private string PeselPracownika { set; get; } private SqlDataReader reader; private SqlConnection con = null; private Form activePanel; public MainWindow() { InitializeComponent(); OpenNewPanel(new Zakładki.StronaGlowna()); UsernameLabel(); // Przekazanie imienia do textBoxa pod ikoną profilu } /* Metoda odpowiadająca za wymianę panelu w głównym oknie na nowy klikając poszczególne przyciski * posiadające swoje metody poniżej. */ private void OpenNewPanel(Form newPanel) { if (activePanel != null) { activePanel.Close(); } activePanel = newPanel; newPanel.TopLevel = false; newPanel.FormBorderStyle = FormBorderStyle.None; newPanel.Dock = DockStyle.Fill; this.OknoPanel.Controls.Add(newPanel); this.OknoPanel.Tag = newPanel; newPanel.BringToFront(); newPanel.Show(); } // Panel strona główna private void StronaGlownaButton_Click(object sender, EventArgs e) { OpenNewPanel(new Zakładki.StronaGlowna()); titleLabel.Text = "Strona Główna"; UsernameLabel(); // odświeżenie nazwy użytkownika po zmianie } // Panel profilu użytkownika private void ProfilButton_Click(object sender, EventArgs e) { OpenNewPanel(new Zakładki.Profil()); titleLabel.Text = "Profil"; UsernameLabel(); } // Panel pracowników private void PracownicyButton_Click(object sender, EventArgs e) { CountWorkers(); WorkersOnList(); // Pokazanie listy pracowników zaraz obok przycisku MenuPracownikow.Show(PracownicyButton, PracownicyButton.Width, 0); UsernameLabel(); } // Panel przechodzący do podsumowania składek private void PodsumowanieButton_Click(object sender, EventArgs e) { CountWorkers(); ResetPomColumn("", "a"); // resetowanie kolumny pomocniczej w bazie danych for (int i = 0; i < NumerOfWorkers; i++) { ResetPomColumn($"and PeselPrac='{PeselPracownika}'", "z"); GetData(); ResetPomColumn($"and PeselPrac='{PeselPracownika}'", "z"); } OpenNewPanel(new Zakładki.Podsumowanie()); titleLabel.Text = "Podsumowanie"; UsernameLabel(); } // Przycisk obsługujący wylogowanie z okna głównego, przechodzi do panelu logowania private void LogOutButton_Click(object sender, EventArgs e) { new LoginPanel().Show(); Hide(); } /* Metoda przekazuje 'Imie' zalogowanego użytkownika odczytanego ze zmiennej statycznej * do textBoxa pod ikonką usera w lewym górnym rogu okna głównego. */ private void UsernameLabel() { try { using (con = new SqlConnection(StaticPomClass.connectionSting)) { con.Open(); // Komenda bazy danych wybierająca zmienną Imie SqlCommand sqlCmd = new SqlCommand($"select Imie from tabUser where UserID='{StaticPomClass.UserID}'", con); reader = sqlCmd.ExecuteReader(); if (reader.Read()) { textBox1.Text = reader.GetString(0); } } } catch (SqlException ex) { throw new BasicErrorException("Ogólny problem z bazą danych"); } finally { if (reader != null) reader.Close(); if (con != null) con.Close(); } } /* Metoda obsługująca dodanie nowego pracownika, otwiera nowe okno, gdzie nalezy wpsisać oraz zapisać dane * aby został on dodany do bazy danych. */ private void AddWorker_Click(object sender, EventArgs e) { // Liczba pracowników nie może przekroczyć 2999 w danej firmie inaczej przycisk zostanie zablokowany if(NumerOfWorkers > StaticPomClass.WorkerID.Count) { AddWorker.Enabled = false; } OpenNewPanel(new Zakładki.Pracownik()); titleLabel.Text = "Nowy Pracownik"; } // Metoda odpowiada za zliczanie wszystkich pracowników z bazy danych posiadających takie samo ID pracodawcy. private void CountWorkers() { try { using (con = new SqlConnection(StaticPomClass.connectionSting)) { con.Open(); SqlCommand sqlCmd = new SqlCommand($"SELECT COUNT(1) FROM tabWorker WHERE UserIDPrac='{StaticPomClass.UserID}'", con); reader = sqlCmd.ExecuteReader(); if (reader.Read()) { // Przypisanie zwróconej liczby do zmiennej _numOfWorkers NumerOfWorkers = reader.GetInt32(0); StaticPomClass.WorkersNum = NumerOfWorkers; } } } catch (SqlException ex) { throw new BasicErrorException("Ogólny problem z bazą danych"); } finally { if (reader != null) reader.Close(); if (con != null) con.Close(); } } /* Metoda przypisuje pomocnicze 'a' dla wszystkich komórek w kolumnie pomocniczej w SQL. Jest to metoda pomocnicza w celu późniejszego * zczytywania kolejnych pracowników bazdy danych. */ private void ResetPomColumn(string Next, string PomLetter) { try { using (con = new SqlConnection(StaticPomClass.connectionSting)) { con.Open(); SqlDataAdapter adapter = new SqlDataAdapter(); // Podany string ustawia wszystkie komórki w pomocniczej kolumnie dla pracowników danego użytkownika na wartość 'a' string sql = $"Update tabWorker set PomNum='{PomLetter}' WHERE UserIDPrac='{StaticPomClass.UserID}' {Next}"; SqlCommand sqlCmd2 = new SqlCommand(sql, con); adapter.UpdateCommand = new SqlCommand(sql, con); adapter.UpdateCommand.ExecuteNonQuery(); sqlCmd2.Dispose(); } } catch (SqlException ex) { throw new BasicErrorException("Ogólny problem z bazą danych"); } finally { if (reader != null) reader.Close(); if (con != null) con.Close(); } } // Metoda służy pobraniu danych o pracowniku do późniejszego ich użycia przy wyświetlaniu oraz pobraniu pozostałych informacji private void GetData() { try { using (con = new SqlConnection(StaticPomClass.connectionSting)) { con.Open(); // String wybiera zmienne pierwszego napotkanego pracownika w tabeli, któremu odpowiada numerID użytkownika oraz zmienna pomocnicza SqlCommand sqlCmd = new SqlCommand($"SELECT ImiePrac, NazwiskoPrac, PeselPrac, WorkerID FROM tabWorker WHERE UserIDPrac=" + $"'{StaticPomClass.UserID}' and PomNum='a'", con); reader = sqlCmd.ExecuteReader(); if (reader.Read()) { // Tymczasowe przypisanie do zmiennych zczytanych danych z bazy ImiePracownika = reader.GetString(0); NazwiskoPracownika = reader.GetString(1); PeselPracownika = reader.GetString(2); // Zczytanie unikatowego numeru pesel dla pracownika StaticPomClass.WorkerID.Add(reader.GetInt32(3)); reader.Close(); } } } catch (SqlException ex) { throw new BasicErrorException("Ogólny problem z bazą danych"); } finally { if (reader != null) reader.Close(); if (con != null) con.Close(); } } /* Metoda służy do tworzenia ToolStripMenuitemów w wysuwanej liście po kliknięciu przycisku pracownicy. Ilość itemów tworzona jest w * zależności od ilości zliczonych pracowników w bazie danych. */ private void WorkersOnList() { //czyszczenie listy itemów oraz tablicy ID pracowników MenuPracownikow.Items.Clear(); StaticPomClass.WorkerID.Clear(); //deklaracja tablicy obiektów zgodna z liczbą pracowników w bazie danych ToolStripMenuItem[] workerToolStripMenuItem = new ToolStripMenuItem[NumerOfWorkers]; ResetPomColumn("", "a") ; // resetowanie kolumny pomocniczej w bazie danych // Pętla wykonywana jest tyle razy ilu zliczy pracowników użytkownika. Odpowiada za tworzenie itemów na liście. for (int i = 0; i < NumerOfWorkers; i++) { // Pobranie danych z bazy do uzupełnienia menuItemów GetData(); // Ustawienie kolumny pomocniczej na 'z' aby nie zczytywać tego samego użytkownika ponownie dzięki unikatowemu numerowi pesel ResetPomColumn($"and PeselPrac='{PeselPracownika}'", "z"); /* Tworzenie MenuItemów wysuwanych w przypadku kliknięcia przycisku 'pracownicy' w MainWindow, Przycisków zostanie utworzona taka ilość, * ile zostało znalezionych pracowników dla danego użytkownika. Do Każdego Itemu przypisane zostaje zczytane imie oraz nazwisko oraz * metoda odpowiadająca za jego kliknięcie. */ workerToolStripMenuItem[i] = new ToolStripMenuItem($"{ImiePracownika}" + $" {NazwiskoPracownika}", null, WorkerToolStripMenuItem_Click, $"Pracownik{i}"); MenuPracownikow.Items.Add(workerToolStripMenuItem[i]); } } // Obsługa przycisku wcześniej tworzonych MenuItemów. private void WorkerToolStripMenuItem_Click(object? sender, EventArgs e) { // Numer wciśniętego przycisku zostanie wysłany do zmiennej, która będzie wskazywała index danych pracowników ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { StaticPomClass.Index = MenuPracownikow.Items.IndexOf(item); } OpenNewPanel(new Zakładki.EdycjaPracownika()); titleLabel.Text = "Profil Pracownika"; } } }
from __future__ import annotations from image_editor.main_mode_group import MainModeGroup from .status_text_window import StatusTextWindow from .tools_window import ToolsWindow from .image_window import ImageWindow from tgos import * from ascii_sprites.actors import images as hero_img MOCK_DEBUG = False class ImageController(object): def __init__(self, image_window: ImageWindow, tools_window: ToolsWindow, status_window: StatusTextWindow) -> None: self.image_window = image_window self.tools_window = tools_window tools_window.symb_pick_callback = self.on_symb_pick tools_window.color_pick_callback = self.on_color_pick tools_window.bg_color_pick_callback = self.on_bg_color_pick tools_window.tool_pick_callback = self.on_tool_pick image_window.pick_symb_callback = self.on_image_symb_pick status_window.image = image_window.image def on_tool_pick(self, tool: str, active: bool) -> None: if tool == MainModeGroup.DOTPAINT: self.image_window.set_mode(ImageWindow.SYMB_PAINT_MODE) elif tool == MainModeGroup.LINEPAINT: self.image_window.set_mode(ImageWindow.LINE_PAINT_MODE) elif tool == MainModeGroup.SQUAREPAINT: self.image_window.set_mode(ImageWindow.RECT_PAINT_MODE) elif tool == MainModeGroup.PICK: self.image_window.set_mode(ImageWindow.PICK_MODE) def on_color_pick(self, color: str) -> None: self.image_window.color = color def on_bg_color_pick(self, color: str) -> None: self.image_window.bg_color = color def on_symb_pick(self, symb: str) -> None: self.image_window.symb = symb def on_image_symb_pick(self, symb: SymbolInfo) -> None: self.tools_window.color_panel.external_pick(symb.color) if not symb.bg_alpha: self.tools_window.bg_color_panel.external_pick(symb.bg_color) if not symb.alpha: self.tools_window.palette_panel.external_pick(symb.symbol) class ImageEditorContext(AppContext): def _custom_init(self): self.mel = self.instaniate(MouseEventListener()) self.imgwnd: ImageWindow = self.instaniate(ImageWindow()) self.imgwnd.image = hero_img["hero_atack_l"] self.current_focus = None self.toolwnd: ToolsWindow = self.instaniate(ToolsWindow()) self.statwnd: StatusTextWindow = self.instaniate(StatusTextWindow()) self.controller = ImageController(self.imgwnd, self.toolwnd, self.statwnd) def set_focus(self, panel: Panel): if self.current_focus is not None and hasattr(self.current_focus, "on_loose_focus"): self.current_focus.on_loose_focus() self.current_focus = panel if self.current_focus is not None and hasattr(self.current_focus, "on_gain_focus"): self.current_focus.on_gain_focus() class ImageEditorApp(App): CMD_WINDOW_HEIGHT = 4 TOOL_WINDOW_WIDTH = 20 def __init__(self, contextClass: AppContext) -> None: super().__init__(contextClass, mock_mode=MOCK_DEBUG) self.framerate = -1 self.context: ImageEditorContext def _user_update(self): self._split_windows() def _split_windows(self): self.context.imgwnd.rect = Rect( 0, self.CMD_WINDOW_HEIGHT - 1, self.context.scr.scr_size.x - self.TOOL_WINDOW_WIDTH + 1, self.context.scr.scr_size.y - self.CMD_WINDOW_HEIGHT + 1 ) self.context.toolwnd.rect = Rect( self.context.scr.scr_size.x - self.TOOL_WINDOW_WIDTH, self.CMD_WINDOW_HEIGHT - 1, self.TOOL_WINDOW_WIDTH, self.context.scr.scr_size.y - self.CMD_WINDOW_HEIGHT + 1 ) self.context.statwnd.rect = Rect( 0, 0, self.context.scr.scr_size.x, self.CMD_WINDOW_HEIGHT ) def _user_draw(self, draw_callback): return class MouseEventListener(SceneObject): def before_tick(self, delta): if (self.context.mouse_event in (mouse.CLICK, mouse.PRESS) and self.context.mouse_btn == mouse.LBUTTON): for so in self.context.scene_objects: if so.parent is None and isinstance(so, Element): rc_so = so.search_raycast(self.context.mouse_coord) if rc_so is not None: rc_so.on_click() if __name__ == "__main__": ImageEditorApp(ImageEditorContext).start()
package com.bagal.tests.rough; import com.bagal.models.request.user.CreateUserRequestPoJo; import com.bagal.models.response.user.CreateUserResponsePojo; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.restassured.http.ContentType; import io.restassured.module.jsv.JsonSchemaValidator; import io.restassured.response.Response; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import static com.bagal.configs.PropertyConfig.getValue; import static io.restassured.RestAssured.given; public class DemoTests { @Test public void demoTest() throws JsonProcessingException { CreateUserRequestPoJo userPoJo = CreateUserRequestPoJo.builder(). setName("sayaji").setJob("dev").build(); ObjectMapper mapper = new ObjectMapper(); String body = mapper.writeValueAsString(userPoJo); Response response = given() .body(body) .baseUri(getValue("base.uri")) .basePath(getValue("base.path.user")) .contentType(ContentType.JSON) .when() .post(); String resBody = response.body().asString(); CreateUserResponsePojo userResponsePojo = mapper.readValue(resBody, CreateUserResponsePojo.class); System.out.println("userResponsePojo.getCreatedAt() = " + userResponsePojo.getCreatedAt()); System.out.println("userResponsePojo.getId() = " + userResponsePojo.getId()); System.out.println("userResponsePojo.getName() = " + userResponsePojo.getName()); System.out.println("userResponsePojo.getJob() = " + userResponsePojo.getJob()); response.then().body(JsonSchemaValidator.matchesJsonSchema(new File("/Users/sayajirajebagal/repos/reqres-api-framework-demo-dec/src/test/resources/schema/CreateUserSchema.json"))); } @Test(dataProvider = "getData") public void readJsonTest(Object[] data) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); CreateUserRequestPoJo createUserRequestPoJo = mapper.readValue(data[0].toString(), CreateUserRequestPoJo.class); System.out.println("createUserRequestPoJo.getName() = " + createUserRequestPoJo.getName()); System.out.println("createUserRequestPoJo.getJob() = " + createUserRequestPoJo.getJob()); } @DataProvider public Object[] getData() throws JsonProcessingException { CreateUserRequestPoJo userPoJo = CreateUserRequestPoJo.builder().setName("sayaji").setJob("dev").build(); Object[] data = new Object[1]; ObjectMapper mapper = new ObjectMapper(); String createUserRequestPoJo = mapper.writeValueAsString(userPoJo); data[0] = createUserRequestPoJo; return data; } }
# Downloads an image in svg format for each chess pieces import re import urllib.request from html.parser import HTMLParser PIECES = 'rnbkqp' COLORS = 'ld' URL_TEMPLATE = 'http://commons.wikimedia.org/wiki/File:Chess_{}t45.svg' def get_request(url): request = urllib.request.Request(url) request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) ' 'Gecko/20120413 Firefox/13.0a2') return request def get_file_bytes(url): request = get_request(url) return urllib.request.urlopen(request).read() def get_page(url): pagebytes = get_file_bytes(url) return pagebytes.decode('utf-8') def find_link_by_href(pagestring, pattern): class LinkByHrefFinder(HTMLParser): def __init__(self, patter): self.pattern = pattern self.result = None HTMLParser.__init__(self) def handle_starttag(self, tag, attrs): if not self.result: href_attrs = [value for (name, value) in attrs if name == 'href'] href_attr = href_attrs[0] if href_attrs else None if href_attr and re.search(pattern, href_attr): self.result = href_attr linkfinder = LinkByHrefFinder(pattern) linkfinder.feed(pagestring) return linkfinder.result def get_file_url(code): pagestring = get_page(URL_TEMPLATE.format(code)) return 'http:' + find_link_by_href(pagestring, '.*\\.svg$') def get_file(code): url = get_file_url(code) bytes_ = get_file_bytes(url) filename = url.split('/')[-1] with open(filename, 'wb') as file_: file_.write(bytes_) for color in COLORS: for piece in PIECES: get_file(piece + color)
<div class="container" > <div class="content"> <div class="box"> <img class="logo-img" src="assets/images/logo (1).png" alt="logo" > <form *ngIf="!isLoggedIn" name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate > <mat-form-field appearance="outline"> <mat-label>Enter your Name</mat-label> <input matInput placeholder="User Name" type="text" class="form-control" name="username" [(ngModel)]="form.username" required #username="ngModel" [ngClass]="{ 'is-invalid': f.submitted && username.errors }" /> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Enter your password</mat-label> <input matInput [type]="hide ? 'password' : 'text'" type="password" class="form-control" name="password" [(ngModel)]="form.password" required minlength="6" #password="ngModel" [ngClass]="{ 'is-invalid': f.submitted && password.errors }"/> <button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide" type="button"> <mat-icon>{{ hide ? "visibility_off" : "visibility" }}</mat-icon> </button> </mat-form-field> <div class="buttons"> <input type="submit" name="Signup" value="Signup" /> </div> <div class="form-group"> <div *ngIf="f.submitted && isLoginFailed" class="alert alert-danger" role="alert"> Login failed: {{ errorMessage }} </div> </div> <div class="right-content"> <div class="right-content-img"></div> </div>
import 'package:flutter/material.dart'; class HomeView extends StatefulWidget { const HomeView({super.key}); @override State<HomeView> createState() => _HomeViewState(); } class _HomeViewState extends State<HomeView> { String result = ''; void _actions(String buttonText) { if (buttonText == '=') { calculateResult(); } else if (buttonText == 'C') { clearResult(); } else { setState(() { result += buttonText; }); } } void calculateResult() { try { final resultList = result.split("+"); final firstNumber = int.tryParse(resultList[0]) ?? 0.0; final secondNumber = int.tryParse(resultList[1]) ?? 0.0; var calculateResult = firstNumber + secondNumber; setState(() { result = calculateResult.toString(); }); } catch (e) { result = 'Error'; } } void clearResult() { setState(() { result = ''; }); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Column( children: [resultWidget(), buttonsWidget()], ), )); } Expanded resultWidget() { return Expanded( flex: 2, child: Container( color: Colors.deepOrange, child: buildResult(), )); } Align buildResult() { return Align( alignment: Alignment.bottomRight, child: Padding( padding: const EdgeInsets.all(16.0), child: Text( result, style: const TextStyle( color: Colors.white, fontSize: 24.0, ), ), ), ); } Expanded buttonsWidget() { return Expanded( flex: 8, child: Container( color: Colors.deepPurple, child: Column( children: [ buildButton(['7', '8', '9', 'C']), buildButton(['4', '5', '6', '+']), buildButton(['1', '2', '3', '=']), buildButton(['0', '', '', '']), ], ), )); } Widget buildButton(List<String> buttons) { return Expanded( child: Row( children: buttons .map( (buttonText) => Expanded( child: TextButton( onPressed: buttonText != "" ? () => _actions(buttonText) : null, child: Text( buttonText, style: const TextStyle( color: Colors.white, fontSize: 24.0, ), ), ), ), ) .toList(), ), ); } }
import React from 'react'; import { useSetRecoilState, useRecoilValue } from 'recoil'; import { v4 as uuidv4 } from 'uuid'; import { TeamTableHeader } from '@/components/lineup'; import { TeeChoiceDropdown, ManualCHDropdown, WalkRideDropdown, } from '@/components/lineup/dropdowns'; import * as state from '@/store'; import { get, setTeamHcpAndProgs } from '@/components/common/utils'; import '@/styles/App.css'; const TeamTable = ({ teamNumber, teamMembers }) => { const course = useRecoilValue(state.course); const setTeamTables = useSetRecoilState(state.teamTables); const progs069 = useRecoilValue(state.progs069); const progAdj = useRecoilValue(state.progAdj); const showTeamHcp = true; const teesSelected = useRecoilValue(state.teesSelected); const groups = get('groups'); let teamName = 'team' + teamNumber; let teamHcp, teamProgs; let teamHcpAndProgsValues; function setTeamValues() { teamHcpAndProgsValues = setTeamHcpAndProgs( teamName, teamMembers, progAdj, progs069, teesSelected[course] ); teamHcp = teamHcpAndProgsValues[0]; teamProgs = teamHcpAndProgsValues[1]; } setTeamValues(); let rows = teamMembers; let rowsTD = []; let teeCount = teesSelected[course].length; let playerCount; if (teamMembers) { playerCount = teamMembers.length; } else { playerCount = 0; } const handleClick = (teamName, id) => (event) => { setTeamTables((prevTeamTables) => ({ ...prevTeamTables, [teamName]: prevTeamTables[teamName].filter((player) => player.id !== id), })); setTeamValues(); }; function generateRows() { for (let i = 0; i < playerCount; i++) { rowsTD[i] = ( <tr key={rows[i].id}> <td></td> <td className='lineup-table-body_td-left' onClick={handleClick(teamName, teamMembers[i].id)}> {rows[i].playerName} </td> {generateCols(i)} </tr> ); } return rowsTD; } function generateCols(i) { let tds = []; for (var j = 0; j < teeCount; j++) { if (rows[i].teeChoice === teesSelected[course][j].value) { tds[j] = ( <td className='lineup-table-body_td-other-bold' key={uuidv4()}> {rows[i].courseHandicaps[j]} </td> ); } else { tds[j] = ( <td className='lineup-table-body_td-other' key={uuidv4()}> {rows[i].courseHandicaps[j]} </td> ); } } let aChosenTeeIndex = rows[i].courseHandicaps.indexOf(rows[i].teeChoice); let manualCH = rows[i].courseHandicaps[aChosenTeeIndex]; if (showTeamHcp || progs069 > 0) { tds.push( <TeeChoiceDropdown key={uuidv4()} baseTee={rows[i].teeChoice} playerId={rows[i].id} teamNumber={teamNumber} /> ); } if (groups.slice(-1) === 'Walk') { tds.push( <WalkRideDropdown key={uuidv4()} walk={rows[i].walk} playerId={rows[i].id} teamNumber={teamNumber} /> ); } if (showTeamHcp || progs069 > 0) { tds.push( <ManualCHDropdown key={uuidv4()} manualCH={manualCH} playerId={rows[i].id} teamNumber={teamNumber} /> ); } return tds; } return ( <table> <thead> <TeamTableHeader teamNumber={teamNumber} teamMembers={teamMembers} /> </thead> <tbody>{generateRows()}</tbody> <tfoot className='lineup-table-footer'> <tr> <td colSpan={teeCount + 2}> {showTeamHcp || progs069 > 0 ? ( <span>Team Hcp: {teamHcp}</span> ) : ( <></> )} {progs069 > 0 ? ( <span> &nbsp;&nbsp;Team Progs per {progs069}: {teamProgs} </span> ) : ( <></> )} </td> </tr> </tfoot> </table> ); }; export default TeamTable;
// ADD TODO // [X] Slide array containing object with id, image and description. // [X] Component for rendering a slide object. // [X] Footer, buttons to navigate between the onboardings. // [X] Stack all components. import React, {useRef} from 'react'; import { SafeAreaView, Dimensions, StyleSheet, StatusBar, FlatList, View, Image, Text, TouchableOpacity, ImageSourcePropType, } from 'react-native'; import {theme} from '../Constants'; import * as PropTypes from 'prop-types'; import Icon from 'react-native-vector-icons/Ionicons'; import RNBounceable from '@freakycoder/react-native-bounceable'; import {useSelector} from 'react-redux'; import {selectUser} from '../Slices/user'; const {width, height} = Dimensions.get('window'); const slides = [ { id: 1, name: 'water-outline', // title description: "l'endroit où vous pouvez trouver tous les événements.", }, { id: 2, name: 'brush-outline', description: 'Informations en temps réel sur ce qui se passe dans le pays.', }, { id: 3, name: 'timer-outline', description: 'Informations en temps réel sur ce qui se passe dans le pays.', }, ]; const Integration = (props: { navigation: {navigate: (arg0: string) => void}; }) => { const [currentIndicatorIndex, setCurrentIndicatorIndex] = React.useState(0); const ref = useRef(null); // const user = useSelector(selectUser); const Slide = (props: { item: { name: string; description: | boolean | React.ReactChild | React.ReactFragment | React.ReactPortal | null | undefined; }; }) => { return ( <View style={{justifyContent: 'center'}}> <View style={{width, alignItems: 'center'}}> <Icon name={props.item.name} size={250} color={theme.colors.blue} /> <Text style={styles.description}>{props.item.description}</Text> </View> </View> ); }; const Footer = () => { return ( <View style={{ height: height * 0.25, justifyContent: 'space-between', }}> <View style={{ flexDirection: 'row', justifyContent: 'center', marginTop: 20, }}> {slides.map((_, index) => ( <View key={index} style={[ styles.indicator, currentIndicatorIndex == index && { backgroundColor: theme.colors.blue, }, ]} /> ))} </View> <View style={{marginBottom: 30}}> {currentIndicatorIndex === slides.length - 1 ? ( <View style={{height: 50}}> <RNBounceable style={[styles.btn]} onPress={() => props.navigation.navigate('Explorer')}> <Text style={[styles.btntxt]}>Commencez</Text> </RNBounceable> </View> ) : ( <View style={{flexDirection: 'row'}}> <RNBounceable style={[ styles.btn, { backgroundColor: 'transparent', }, ]} onPress={skip}> <Text style={[styles.btntxt, {color: theme.colors.blue}]}> Sauter </Text> </RNBounceable> <View style={{width: 15}} /> <RNBounceable style={[ styles.btn, { backgroundColor: 'transparent', }, ]} onPress={goToNextSlide}> <Text style={[styles.btntxt, {color: theme.colors.blue}]}> Suivant </Text> </RNBounceable> </View> )} </View> </View> ); }; Slide.propTypes = {item: PropTypes.object}; const updateCurrentSlideIndex = (e: { nativeEvent: {contentOffset: {x: any}}; }) => { const contentOffsetX = e.nativeEvent.contentOffset.x; const currentIndex = Math.round(contentOffsetX / width); setCurrentIndicatorIndex(currentIndex); }; const goToNextSlide = () => { const nextSlideIndex = currentIndicatorIndex + 1; if (nextSlideIndex != slides.length) { const offset = nextSlideIndex * width; ref?.current?.scrollToOffset({offset}); setCurrentIndicatorIndex(nextSlideIndex); } }; const skip = () => { const lastSlideIndex = slides.length - 1; const offset = lastSlideIndex * width; ref?.current?.scrollToOffset({offset}); setCurrentIndicatorIndex(lastSlideIndex); }; return ( <SafeAreaView style={{ flex: 1, backgroundColor: '#F6F6F7', }}> <FlatList ref={ref} onMomentumScrollEnd={updateCurrentSlideIndex} pagingEnabled={true} data={slides} contentContainerStyle={{height: height * 0.75}} horizontal showsHorizontalScrollIndicator={false} renderItem={({item}) => <Slide item={item} />} /> <Footer /> </SafeAreaView> ); }; const styles = StyleSheet.create({ description: { fontSize: theme.sizes.h4, fontFamily: 'Nunito-SemiBold', color: theme.colors.black, width: 300, textAlign: 'center', }, indicator: { height: 10, width: 10, borderColor: theme.colors.bluetiful, borderWidth: 1.5, marginHorizontal: 3, borderRadius: 50, }, btn: { flex: 1, height: 40, borderRadius: 3, backgroundColor: theme.colors.blue, justifyContent: 'center', alignItems: 'center', marginHorizontal: 25, }, btntxt: { fontSize: theme.sizes.h6, fontFamily: 'Nunito-SemiBold', color: theme.colors.antiFlashWhite, }, }); export default Integration;
package softuni.exam.models.entity; import javax.persistence.*; import java.math.BigDecimal; @Entity @Table(name = "players") public class Player { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String firstName; @Column(nullable = false) private String lastName; @Column(nullable = false) private Integer number; @Column(nullable = false) private BigDecimal salary; @Column(nullable = false) private String position; @ManyToOne private Picture picture; @ManyToOne private Team team; public Player() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public BigDecimal getSalary() { return salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public Picture getPicture() { return picture; } public void setPicture(Picture picture) { this.picture = picture; } public Team getTeam() { return team; } public void setTeam(Team team) { this.team = team; } }
# Description: This file contains the class that generates the trip recommendation based on the user's input. # The class takes the start date, end date, budget, and city as input and generates a recommendation based on the input. from .vector_database import VectorDatabase from .genai import generativeAI class generateTripRecommendation(): def __init__(self, start_date, end_date, budget, city): self.start_date = start_date self.end_date = end_date self.budget = budget self.city = city self.prompt = self.generatePrompt() self.recommendation = self.generateRecommendation() def generateContext(self, query): print('Searching vector DB for context...') vector_db = VectorDatabase() vector_db.createCollection('recommendations') similar_text = vector_db.searchQuery('recommendations', query) context = '' for i in range(len(similar_text)): context += f"{i+1}. {similar_text[i]['text']}\n" print('Context generated') return context def generatePrompt(self): query = 'I want to visit ' + self.city + ' from ' + self.start_date + ' to ' + self.end_date + ' with a budget of ' + self.budget context = self.generateContext(query) return f"Here is the information we already have:\n{context}\nAnswer the following question: {query}\n" def generateRecommendation(self): print('Generating recommendations through generative AI...') ai = generativeAI(self.prompt) print('Recommendations generated') return ai.generateResponse()
/** * GS1 Syntax Engine * * @author Copyright (c) 2021-2024 GS1 AISBL. * * 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. * */ #ifndef AI_H #define AI_H #include <stdbool.h> #include <stdint.h> #include <string.h> #include "syntax/gs1syntaxdictionary.h" #define MAX_AIS 64 #define MIN_AI_LEN 2 #define MAX_AI_LEN 4 #define MAX_AI_VALUE_LEN 90 #define MAX_AI_ATTR_LEN 64 /* * If these are redefined then the macro expansions for the embedded AI table * will need to be changed. * * One more that last entry since we NULL terminate. * */ #define MAX_PARTS (5 + 1) /* Currently AI (8001) = N4 N5 N3 N1 N1 */ #define MAX_LINTERS (2 + 1) /* Many AIs have, e.g. csum,key */ typedef enum { cset_none = 0, cset_X, // CSET 82 cset_N, // Numeric cset_Y, // CSET 39 cset_Z, // URI-safe base64 } cset_t; // A single AI may consist of multiple concatenated components struct aiComponent { cset_t cset; // CSET table uint8_t min; // Minimum length. Currently 0 for optional, 1 for mandatory uint8_t max; // Maximum length bool opt; // Optional final component gs1_linter_t linters[MAX_LINTERS]; // Linter functions applied to component }; struct aiEntry { char ai[MAX_AI_LEN+1]; // AI itself bool fnc1; // FNC1 required as a separator uint8_t dlDataAttr; // Permitted as a GS1 DL URI data attribute struct aiComponent parts[MAX_PARTS]; // Format specification components char* attrs; // Key-value pair attributes, e.g. req, ex, etc. char* title; // Data title }; typedef enum { aiValue_undef = 0, aiValue_aival, // Extracted AI value pair aiValue_ccsep, // Separater between linear and composite component AIs alValue_dlign, // An ignored (non-numeric) query parameter of a DL URI (stored undecoded in aiValue.value) } aiValueKind_t; struct aiValue { const struct aiEntry *aiEntry; // Entry in AI table; may be an "unknown" placeholder entry const char *ai; // Start of the AI in the underlying buffer uint8_t ailen; // Length of the AI const char *value; // Start of the AI value in the underlying buffer uint8_t vallen; // Length of the AI value aiValueKind_t kind; // Kind of AI value uint8_t dlPathOrder; // Denotes the position in a DL URI path component }; // Features such as validation functions, some of which can be toggled typedef bool (*gs1_encoder_validation_func_t)(gs1_encoder *ctx); struct validationEntry { bool locked; // Feature cannot be enabled/disabled via the API bool enabled; // Feature is enabled gs1_encoder_validation_func_t fn; // Optional validation function for the feature }; /* * Syntactic sugar for initialising an aiEntry * */ #define DO_FNC1 true #define NO_FNC1 false #define NO_DATA_ATTR 0 #define DL_DATA_ATTR 1 #define XX_DATA_ATTR 2 // For unknown AIs, depends on gs1_encoder_vUNKNOWN_AI_DL_ATTR #define MAN false #define OPT true #define AI_VA(a, f, d, c1,mn1,mx1,o1,l00,l01, c2,mn2,mx2,o2,l10,l11, c3,mn3,mx3,o3,l20,l21, c4,mn4,mx4,o4,l30,l31, c5,mn5,mx5,o5,l40,l41, k, t) { \ .ai = a, \ .fnc1 = f, \ .dlDataAttr = d, \ .parts = { \ { .cset = cset_##c1, .min = mn1, .max = mx1, .opt = o1, .linters = { gs1_lint_##l00, gs1_lint_##l01, NULL } }, \ { .cset = cset_##c2, .min = mn2, .max = mx2, .opt = o2, .linters = { gs1_lint_##l10, gs1_lint_##l11, NULL } }, \ { .cset = cset_##c3, .min = mn3, .max = mx3, .opt = o3, .linters = { gs1_lint_##l20, gs1_lint_##l21, NULL } }, \ { .cset = cset_##c4, .min = mn4, .max = mx4, .opt = o4, .linters = { gs1_lint_##l30, gs1_lint_##l31, NULL } }, \ { .cset = cset_##c5, .min = mn5, .max = mx5, .opt = o5, .linters = { gs1_lint_##l40, gs1_lint_##l41, NULL } }, \ { .cset = 0, .min = 0, .max = 0, .opt = 0, .linters = { NULL, NULL, NULL } }, \ }, \ .attrs = k, \ .title = t, \ } #define PASS_ON(...) __VA_ARGS__ #define AI_ENTRY(...) PASS_ON(AI_VA(__VA_ARGS__)) #define cset_0 0 #define gs1_lint__ NULL #define __ 0,0,0,0,_,_ /* NULL placeholder instead of e.g. X,1,30,MAN,csum,key */ #define AI_ENTRY_TERMINATOR AI_ENTRY( "", 0, 0, __, __, __, __, __, "", "" ) // Write to unbracketed AI dataStr checking for overflow #define writeDataStr(v) do { \ if (strlen(dataStr) + strlen(v) > MAX_DATA) \ goto fail; \ strcat(dataStr, v); \ } while (0) #define nwriteDataStr(v,l) do { \ if (strlen(dataStr) + l > MAX_DATA) \ goto fail; \ strncat(dataStr, v, l); \ } while (0) #include "gs1encoders.h" void gs1_setAItable(gs1_encoder *ctx, struct aiEntry *table); const struct aiEntry* gs1_lookupAIentry(const gs1_encoder *ctx, const char *p, size_t ailen); bool gs1_aiValLengthContentCheck(gs1_encoder *ctx, const char *ai, const struct aiEntry *entry, const char *aiVal, size_t vallen); bool gs1_parseAIdata(gs1_encoder *ctx, const char *aiData, char *dataStr); bool gs1_processAIdata(gs1_encoder *ctx, const char *dataStr, bool extractAIs); bool gs1_validateAIs(gs1_encoder* ctx); void gs1_loadValidationTable(gs1_encoder* ctx); #ifdef UNIT_TESTS void test_ai_lookupAIentry(void); void test_ai_checkAIlengthByPrefix(void); void test_ai_AItableVsPrefixLength(void); void test_ai_AItableVsIsFNC1required(void); void test_ai_parseAIdata(void); void test_ai_linters(void); void test_ai_processAIdata(void); void test_ai_validateAIs(void); void test_ai_lint_csumalpha(void); #endif #endif /* AI_H */
<!DOCTYPE html> <html lang="es"> <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"> <!-- Link css local --> <link rel="stylesheet" href="css/estilos.css"> <!-- Bootstrap 5 CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <!-- Link Google Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;600&family=Yellowtail&display=swap" rel="stylesheet"> <!-- Fav icon (Icono en pesaña del navegador) --> <link rel="shortcut icon" href="img/fav_icon_batcakes.png" type="image/x-icon"> <!-- CDN Fontawesome iconos --> <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" /> <title>Batcakes Pastelería</title> <!-- SEO META --> <meta name="description" content="Nos dedicamos a endulzar la vida creando las tortas y postres más ricos, además de dar cursos y recetas para todos lo que quieran entrar en el mundo de la pastelería."> <meta name="keywords" content="batcakes, pastelería, tortas, cupcakes, cosas, ricas, dulces, chocolate, caramelo"> <meta name="author" content="Tortas y pastelería artesanal"> <meta name="title" content="Batcakes - Pastelería artesanal"> <meta name="ROBOTS" content="INDEX, FOLLOW"> <meta name="ROBOTS" content="ALL"> <meta name="revisit-after" content="5 Days"> <meta name="language" content="Spanish"> <meta http-equiv="Content-Language" content="Es"> <meta name="distribution" content="global"> <meta name="city" content="Buenos Aires"> <meta name="country" content="Argentina"> <meta name="resource-type" content="Document"> <meta name="doc-type" content="Web Page"> </head> <body> <!--NAVBAR INICIO--> <nav class="navbar navbar-expand-lg navbar-dark p-3"> <!--div contenedor navbar--> <div class="container-fluid"> <!--logo izq--> <a class="navbarLogo" href="index.html" target="_blank"> <img src="img/logo_batcakes.png" alt="logo_batcakes" width="200"> </a> <!--boton hamburguesa--> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <!--Lista menú--> <div class="collapse navbar-collapse " id="navbarNavAltMarkup"> <div class="navbar-nav ms-auto mb-2 mb-lg-0 p-3 text-center"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a href="index.html" class="nav-link active" target="_blank">INICIO</a> </li> <li class="nav-item"> <a href="paginas/nosotros.html" class="nav-link active" target="_blank">conocenos</a> </li> <!-- desplegable --> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle active" href="paginas/productos.html" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> tortas y más </a> <ul class="dropdown-menu text-center" aria-labelledby="navbarDropdown"> <li class="dropdown-li"><a class="dropdown-item" href="paginas/productos.html" target="_blank">tortas</a></li> <li class="dropdown-li"><a class="dropdown-item" href="#">cupcakes</a></li> <li class="dropdown-li"><a class="dropdown-item" href="#">cookies</a></li> <li class="dropdown-li"><a class="dropdown-item" href="#">cakepops</a></li> <li class="dropdown-li"><a class="dropdown-item" href="#">masas y donas</a></li> <li class="dropdown-li"><a class="dropdown-item" href="#">clásicos</a></li> <li class="dropdown-li"><a class="dropdown-item" href="#">mesas dulces</a></li> <li class="dropdown-li"><a class="dropdown-item" href="#">desayunos</a></li> <li class="dropdown-li"><a class="dropdown-item" href="#">especiales</a></li> </ul> </li> <!-- FIN desplegable --> <li class="nav-item"> <a href="paginas/error404.html" class="nav-link active" target="_blank">cursos</a> </li> <li class="nav-item"> <a href="paginas/recetas.html" class="nav-link active" target="_blank">recetas</a> </li> <li class="nav-item"> <a href="paginas/contacto.html" class="nav-link active" target="_blank">contacto</a> </li> </ul> </div> </div> <!-- FIN Lista menú--> </div> <!--FIN div contenedor navbar--> </nav> <!--NAVBAR FIN--> <div class="color"> </div> <!--CARROUSEL INICIO--> <div id="carouselExampleSlidesOnly" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="img/slider_img01.jpg" class="d-block w-100" alt="slider_inicio"> </div> <div class="carousel-item"> <img src="img/slider_img02.jpg" class="d-block w-100" alt="slider_cursos01"> </div> <div class="carousel-item"> <img src="img/slider_img03.jpg" class="d-block w-100" alt="slider_cursos02"> </div> </div> </div> <!--CARROUSEL FIN--> <!--SECCION TENTATE--> <section id="ribbon" class="container-fluid"> <div id="tentate" class="container w-50 p-6 rounded"> <div class="row align-items-center"> <div class="col-sm p-2 m-1"> <img src="img/nosotros_01.jpg" class="fotoIntro mx-auto d-block" alt="foto_yami"> </div> <div class="col-sm p-2 mx-2 text-center"> <h1 class="titu_intro"> ¡Tentáte conmigo! </h1> <p class="texto_intro"> <span> Te invito a imaginar y endulzar la vida. Juntos vamos a contagiarnos de mucho aprendizaje, ideas ¡y cosas muy ricas! </span> </p> <span>¡Gracias por visitarme!</span> </div> </div> </div> </section> <!--FIN SECCION TENTATE--> <!-- Sección Productos destacados--> <section id="destacados"> <div class="container-fluid p-5"> <div class="row pt-5 mt-4 mb-2"> <h2 class="titu_prod text-start pb-2">Los productos más solicitados</h2> </div> <div class="row"> <!-- row 2 --> <div class="col-sm"> <div class="card w-70 card-border mb-3 shadow-sm"> <img src="img/prod_masventa01.jpg" class="card-img-top" alt="producto_destacado_01"> <div class="card-body"> <h3 class="card-text">BANDEJA DESAYUNO PERSONALIZADA</h3> </div> </div> </div> <div class="col-sm"> <div class="card w-70 card-border mb-5 shadow-sm"> <img src="img/prod_masventa02.jpg" class="card-img-top" alt="producto_destacado_02"> <div class="card-body"> <h3 class="card-text">CAJA DE CUPCAKES SURTIDOS</h3> </div> </div> </div> </div> <!-- fin row 2 --> </div> <!-- fin container --> </section> <!--FIN Productos destacados--> <!-- Sección Recetas destacadas--> <section id="recetas"> <div class="container-fluid p-5"> <div class="row pt-5 mt-4 mb-2"> <h2 class="titu_prod text-start pb-2">Recetas de la semana</h2> </div> <div class="row"> <!-- row 2 --> <div class="col-sm"> <div class="card w-70 card-border mb-3 shadow"> <img src="img/index_receta_01.jpeg" class="card-img-top" alt="receta_01"> <div class="card-body"> <h3 class="card-text">GALLETITAS BROWNIE</h3> </div> </div> </div> <div class="col-sm"> <div class="card w-70 card-border mb-3 shadow"> <img src="img/index_receta_02.png" class="card-img-top" alt="receta_02"> <div class="card-body"> <h3 class="card-text">BUDIN DE NARANJA Y CHOCOLATE</h3> </div> </div> </div> <div class="col-sm"> <div class="card w-70 card-border mb-3 shadow"> <img src="img/index_receta_03.jpg" class="card-img-top" alt="receta_03"> <div class="card-body"> <h3 class="card-text">TORTA DE CHOCOLATE NESQUIK</h3> </div> </div> </div> </div> <!-- fin row 2 --> </div><!-- fin container --> </section> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <a href="https://api.whatsapp.com/send?phone=01234568798&text=Dejanos tu consulta o pedido%21%20" class="float" target="_blank"> <i class="fa fa-whatsapp my-float"></i> </a> <!--FIN recetas--> <!--fondo borde INICIO--> <section id="cierre"> <div class="container-fluid p-5"> </div> </section> <!--fondo borde FIN--> <!--FOOTER INICIO--> <footer class="footer"> <div class="container__footer"> <!-- Contenedor footer --> <div class="row__footer"> <!--FILA 1--> <div class="footer-col"> <!--COL 1--> <h4>Batcakes</h4> <ul> <li> <a href="index.html" target="_blank"> Inicio </a> </li> <li> <a href="paginas/nosotros.html" target="_blank"> Conocenos </a> </li> <li> <a href="paginas/productos.html" target="_blank"> Tortas y más </a> </li> <li> <a href="paginas/cursos.html" target="_blank"> Cursos </a> </li> <li> <a href="paginas/recetas.html" target="_blank"> Recetas </a> </li> <li> <a href="paginas/contacto.html" target="_blank"> Contacto </a> </li> </ul> </div> <div class="footer-col"> <!--COL 2--> <h4>Suscribite y recibi las últimas novedades</h4> <form action="enviar.php" method="post" enctype="application/x-www-form-urlencoded"> <label for="email" class="label_suscribe">Ingresa tu email</label> <input type="email" placeholder="Tu email" class="form_suscribe"> <input type="submit" value="SUSCRIBIRSE" class="btn_suscribe"> </form> </div> <div class="footer-col"> <!--COL 3--> <ul> <li> <h4>Horarios</h4> </li> <li class="lista_footer">Lunes a Sabado</li> <li class="lista_footer">10 a 18 hs</li> <li class="lista_footer"><br></li> <li> <h4>¡Visitanos!</h4> </li> <li class="lista_footer">Alvarez Jonte 2200</li> <li class="lista_footer">CABA, Bs As, Argentina</li> </ul> </div> <div class="footer-col"> <!--COL 4--> <h4>follow us</h4> <div class="social-links"> <a href="#"><i class="fab fa-facebook-f" target="_blank"></i></a> <a href="#"><i class="fab fa-twitter" target="_blank"></i></a> <a href="#"><i class="fab fa-instagram" target="_blank"></i></a> <a href="#"><i class="fab fa-linkedin-in" target="_blank"></i></a> </div> </div> </div> <!-- FIN FILA 1 --> </div> <!-- FIN Contenedor footer 1 --> <div class="container__footer"> <!-- Contenedor footer 2 --> <div class="row__footer p-2 justify-content-md-center"> <!--FILA 1--> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3283.720958099582!2d-58.476170157116755!3d-34.611216973577136!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x95bcc9fb2ce92301%3A0x4c90fa59de78e3a5!2sGral.%20Jos%C3%A9%20Gervasio%20Artigas%201800-1700%2C%20C1416AKP%20CABA!5e0!3m2!1ses!2sar!4v1624315947583!5m2!1ses!2sar" width="800" height="200" style="border:0;" allowfullscreen="" loading="lazy"> </iframe> </div> <div class="row__footer p-1 justify-content-center"> <!--FILA 2--> <div class="footer-copyright"> <h4>Copyright Batcakes 2021 - Ariel Alonso - CODERHOUSE </h4> </div> </div> </div> <!-- FIN Contenedor footer 2 --> </footer> <!--FOOTER FIN--> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"> </script> </body> </html>
# Alphacado ## Action Id - `1`: UniV2TokenAdapter - `2`: UniV2LpAdapter - `3`: KlayBankAdapter - `4`: KlayStationAdapter - `5`: VaultAdapter ## How to send request? ![Alt text](public/layer-based-image.png) Alphacado use layer-based message mechanism. Each layer has its own type of payload encode-decode. Adapter payload need to be encoded off-chain. ### Uniswap Adapter Payload #### Token Adapter When to use this adapter? Sourchain: If users has token differ than USDC => use this adapter to swap to USDC Targetchain: If users want to receive/interact with other protocol require token differ than USDC => send message to this adapter Payload schema to encode off-chain when using this adapter on target chain: `(address router, address tokenB, uint256 minimumReceive, bytes additionActionIdPayload)` - `router`: protocol router address to swap on target chain - `tokenB`: token to receive when swap from USDC - `minimumReceive`: minimum tokenB receive What is `additionActionIdPayload`? If user just want to receive token on target chain (which means no other protocol to interact) => `additionActionIdPayload` = "" (an empty string) Otherwise, `additionActionIdPayload` is the encoded of `(uint16 actionId, bytes additionActionPayload)` - See `actionId` list above - See how to encode `additionActionPayload` for each protocol below #### Lp Adapter When to use this adapter? Sourchain: If users has LP => use this adapter to swap to USDC Targetchain: If users want to receive/interact other protocol require LP => send message to this adapter Payload schema to encode off-chain when using this adapter on target chain: `(address router, address tokenB, uint256 minimumReceiveLiquidity, bytes additionActionIdPayload)` - `router`: protocol router address to add liquidity - `tokenB`: tokenB in USDC-tokenB pair to add liquidity - `minimumReceiveLiquidity`: minimum liquidity receive What is `additionActionIdPayload`? If user just want to receive token on target chain (which means no other protocol to interact) => `additionActionIdPayload` = "" (an empty string) Otherwise, `additionActionIdPayload` is the encoded of `(uint16 actionId, bytes additionActionPayload)` - See `actionId` list above - See how to encode `additionActionPayload` for each protocol below ## KlayBank, KlayStation payload When to use this adapter: When user want to interact with these protocol on target chain - If user has USDC on source chain: pass these payload directly to alphacado contract (Not implemented) - If user has other token or lp: encode this payload in `additionActionPayload` of Uniswap adapter Payload schema to encode off-chain when using this adapter on target chain: `(address pool, uint16 referralCode) ` - `pool`: address of KlayBank/KlayStation pool contract - `referralCode`: KlayBank/KlayStation referralCode (can be use 0 right now for placeholder) ## Vault adapter When to use this adapter: When user want to interact with Alphacado Vault on target chain - If user has USDC on source chain: pass these payload directly to alphacado contract (Not implemented) - If user has other token or lp: encode this payload in `additionActionPayload` of Uniswap adapter Payload schema to encode off-chain when using this adapter on target chain: `(address vault)` - `vault`: address of Alphacado Vault ## Example What if user want to stake token to a pool in KlayBank that use token differ than USDC: ```typescript import { AbiCoder } from "ethers"; // use ethersv6 const encodeTokenToKlayBank = ( targetChainRouter: string, targetChainTokenB: string, minimumTokenReceive: bigint, klayBankpool: string, klayBankreferralCode: number, ): string => { const defaultEncoder = AbiCoder.defaultAbiCoder(); const klayBankPayload = defaultEncoder.encode( ["address", "uint16"], [klayBankpool, klayBankreferralCode], ); const KLAYBANK_ACTION_ID = 2; const klayBankActionPayload = defaultEncoder.encode( ["uint16", "bytes"], [KLAYBANK_ACTION_ID, klayBankPayload], ); const uniswapTokenPayload = defaultEncoder.encode( ["address", "address", "uint256", "bytes"], [ targetChainRouter, targetChainTokenB, minimumTokenReceive, klayBankActionPayload, ], ); return uniswapTokenPayload; }; ``` ## Deployed Address ### Mumbai - SourceChain - `Alphacado`: 0xbb3e887Db9a28A63e391fe4fFDbB61bA42977c09 - `Registry`: 0xC1Cc9c48DB05e7475FB5aB1B1b7DcA53615903F1 - `TokenFactory`: 0x46Bf7cf267Fa7063c1aA3EEe2EEF4d502aAD30bB Adapters: - `UniV2LPAdapter`: 0x4498aDc1205e7c6Ab49db7dAAC5327C519792972 - `UniV2TokenAdapter`: 0x4498aDc1205e7c6Ab49db7dAAC5327C519792972 ### BNB Testnet - TargetChain - `Alphacado`: 0x872E29b3daeF949848F386bc86Ac9Db5F3301ed3 - `Registry`: 0xcE748352AaffDfEB3A9948802e99Ed035d3Ed0fD - `VaultFactory`: 0xd3D8273B675F546a3f9e4A9AFE207296019647B6 - `TokenFactory`: 0x1013E9348671a5f289dCf0960DaE2f5D7C970191 Mock Addresses: - `MockKlayBankPool`: 0xb29e7e287bD2faf8Fb78abB9Ed2F1c94e3A64b73 - `MockKlayStationPool`: 0xc065aC9C3fA25D6f14b9b8fbf3293A94158237f1 Adapters: - `UniV2LPAdapter`: 0xAd7D3761e2db63d75155a6f5d9D612B02B78923b - `UniV2TokenAdapter`: 0xAd7D3761e2db63d75155a6f5d9D612B02B78923b - `KlayBankAdapter`: 0x6E26145410f452156c52eb15837D9a4c7737A927 - `KlayStationAdapter`: 0xBbD61d22E2eB5667191B7aAFbbbD9e6A5aFA0df5 - `VaultAdapter`: 0x4fF499D8422fC9431176ce7D6A9a47ef33933c6D ### Klaytn - `VaultFactory`: 0x8843010C138A3eBF5080C6c6374BeA29A2de9e4C ## Simple Working case Send `fromUniV2` on UniV2Adapters on Mumbai testnet with these following params: - msg.value: 0.018 ether - router: 0x8954afa98594b838bda56fe4c12a09d7739d179b (UniV2 router) - tokenB: 0x87A35f50E570F909F275F5C8AEC40FbeB9e76D17 (any address must work now) - liquidity: 10^18 = 1 ether (any amount must work now) - minimumSendAmount: 10^18 = 1 ether (any amount must work now) - target chain: 4 (BNB Testnet) - target chain action Id: 1 (UniV2Adapter) - receipient: your address - payload: abi encode of (targetChainRouter, targetChainTokenB, targetChainMinimumReceiveLiquidity) (you can use the gen_payload.ts file) ![Alt text](public/image.png)
import { Component } from '@angular/core'; import { FormBuilder, Validators, FormGroup } from '@angular/forms'; import { NotificacionesService } from 'src/app/shared/services/notificaciones.service'; import { AccesoClientService } from '../../services/acceso-client.service'; import { ClienteInformacionService } from '../../services/cliente-informacion.service'; import { Router } from '@angular/router'; import { New_Password_Client } from '../../interfaces/new-password-client'; @Component({ selector: 'app-new-password-client', templateUrl: './new-password-client.component.html', styleUrls: ['./new-password-client.component.css'] }) export class NewPasswordClientComponent { formulario: FormGroup; cargando: boolean = false; constructor( private fb: FormBuilder, private router: Router, private notificacionesService: NotificacionesService, private accesoClientService: AccesoClientService, private clienteInformacionService: ClienteInformacionService) { this.formulario = this.fb.group({ claveAntigua: ["", Validators.required], claveNueva: ["", Validators.required], confirmarClaveNueva: ["", Validators.required] }) } nuevaClave(){ this.cargando = true; var claveAntigua = this.formulario.value.claveAntigua; var claveNueva = this.formulario.value.claveNueva; var confirmarClaveNueva = this.formulario.value.confirmarClaveNueva; if(claveNueva !== confirmarClaveNueva){ this.cargando = false; this.notificacionesService.notifiWarning("Las contraseñas nuevas no son iguales"); }else{ const _newPasswordClient: New_Password_Client = { idCliente: this.clienteInformacionService.getUserId(), claveAntigua: claveAntigua, claveNueva: claveNueva } this.accesoClientService.nuevaClave(_newPasswordClient).subscribe({ next: (response) => { if(response.status){ this.cargando = false; this.notificacionesService.notificacionSuccess("Clave Configurada Correctamente"); this.router.navigate(["/"]); } }, error: (error) => { console.log("false"); this.notificacionesService.notificacionWarning(error.error.msg); this.cargando = false; } }) } } }
// Controllers for the Travel Collection import 'dotenv/config'; import express from 'express'; import * as travels from './travels-model.mjs'; const PORT = process.env.PORT; const app = express(); app.use(express.json()); // REST needs JSON MIME type. // CREATE controller ****************************************** app.post ('/travels', (req,res) => { travels.createTravel( req.body.location, req.body.age, req.body.date ) .then(travel => { res.status(201).json(travel); }) .catch(error => { console.log(error); res.status(400).json({ Error: 'Creation of a Travel was unsuccesful.' }); }); }); // RETRIEVE controller **************************************************** app.get('/travels', (req, res) => { travels.retrieveTravels() .then(travels => { if (travels !== null) { console.log(`All travels were retrieved from the collection.`); res.json(travels); } else { res.status(404).json({ Error: 'This travel does not exist.' }); } }) .catch(error => { console.log(error); res.status(400).json({ Error: 'Retrieval of this travel was unsuccesful.' }); }); }); // RETRIEVE by ID controller app.get('/travels/:_id', (req, res) => { travels.retrieveTravelByID(req.params._id) .then(travel => { if (travel !== null) { res.json(travel); } else { res.status(404).json({ Error: 'This travel does not exist.' }); } }) .catch(error => { console.log(error); res.status(400).json({ Error: 'Retrieval of this travel was unsuccesful.' }); }); }); // UPDATE controller ************************************ app.put('/travels/:_id', (req, res) => { travels.updateTravel( req.params.id, req.body.location, req.body.age, req.body.date ) .then(travel => { res.json(travel); }) .catch(error => { console.log(error); res.status(400).json({ Error: 'Unable to update this travel.' }); }); }); // DELETE Controller ****************************** app.delete('/travels/:_id', (req, res) => { travels.deleteTravelById(req.params._id) .then(deletedCount => { if (deletedCount === 1) { res.status(204).send({ Success: 'This travel was successfully deleted.' }); } else { res.status(404).json({ Success: 'This travel was successfully deleted.' }); } }) .catch(error => { console.error(error); res.send({ Error: 'Unable to delete this travel.' }); }); }); app.listen(PORT, () => { console.log(`Server listening on port ${PORT}...`); });
# CCSK-Certificate-of-Cloud-Security-Knowledge-Exam-Preparation The CCSK exam is a vendor-neutral certification exam that measures your knowledge of cloud security. Are you considering taking the CCSK exam? The CCSK, or Certificate of Cloud Security Knowledge, is an exam that measures your knowledge of cloud security concepts, principles, and best practices. ## Introduction The CCSK exam is a vendor-neutral certification exam that measures your knowledge of cloud security. It was created by the Cloud Security Alliance, a non-profit organization that promotes best practices for cloud security. The CCSK exam covers various topics related to cloud security, including governance, risk management, compliance, and data security. Why is CCSK certification important? CCSK certification demonstrates to employers and clients that you have a strong understanding of cloud security principles and best practices. As more and more companies move their data and applications to the cloud, the demand for cloud security professionals is increasing. Earning a CCSK certification can help you stand out in the job market and advance your career. ## Exam Overview The CCSK exam is a multiple-choice exam that consists of 60 questions. You have 90 minutes to complete the exam. The minimum passing score for CCSK is 80%. The exam covers six domains: - Cloud Computing Concepts and Architecture - Governance and Enterprise Risk Management - Legal Issues, Contracts, and Electronic Discovery - Compliance and Audit Management - Information Governance - Management Plane and Business Continuity Each domain has a different weighting, with the first domain having the highest weighting and the last domain having the lowest weighting. ## Exam Preparation Preparing for the CCSK exam requires a combination of study materials, practice exams, and study tips and strategies. ### Study Materials The official study guide is the primary resource for studying for the CCSK exam. It covers all six domains and provides in-depth explanations of each topic. In addition to the official study guide, there are also supplementary materials available, such as online courses and webinars. ### Practice Exams **[CCSK practice exams](https://www.certqueen.com/CCSK.html)** are an essential part of CCSK exam preparation. They help you evaluate your knowledge and identify areas where you need to improve. ### Study Tips and Strategies Effective time management is critical when studying for the CCSK exam. Set aside dedicated study time each day and create a study schedule to help you stay on track. Take notes while studying, and use them as a reference when reviewing material. Finally, make sure you understand the types of questions that will be on the exam, and practice answering them. ## Exam Day Preparing for the CCSK exam doesn't end when you walk into the testing center. Here are some tips to help you succeed on exam day: ### Pre-Exam Preparation Getting enough sleep is essential for optimal performance on the CCSK exam. Make sure you get a good night's sleep before the exam. Additionally, make sure you pack all the necessary items, such as identification and a calculator. ### During the Exam Read the instructions carefully before beginning the exam. Manage your time effectively, and don't spend too much time on any one question. If you don't know the answer to a question, don't panic. Use the process of elimination to eliminate obviously incorrect answers and make an educated guess. ## Conclusion Preparing for the CCSK exam requires dedication and hard work, but the rewards are worth it. By earning a CCSK certification, you demonstrate to employers and clients that you have a strong understanding of cloud security principles and best practices.
import { Optional } from "@nestjs/common"; import { IsAlphanumeric, IsEmail, IsNotEmpty, IsNumber, IsString, Length, Matches } from "class-validator"; export class UserDto { @IsNotEmpty() role:number; @IsNotEmpty() @IsEmail() email:string @IsNotEmpty() @IsString() @Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]+$/, { message: 'Password too weak. It must contain at least one uppercase letter, one lowercase letter, one number, and one special character.', }) password: string; @IsNotEmpty() @IsString() @IsAlphanumeric() @Length(2, 50) name: string; @IsNotEmpty() @IsString() mobile: string; @IsNotEmpty() @IsNumber() agency:number; @Optional() // @IsString() department:string; }
package com.example.deckofcards.api; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.DeleteMapping; import java.time.LocalDateTime; import java.util.List; @RestController @RequestMapping("/game") public class GameController { private Game game; EventPublisher publisher = new EventPublisher(); EventHistory history = new EventHistory(); public GameController() { // Register event listener publisher.addEventListener(new EventListener() { @Override public void onEvent(Event event) { history.addEvent(event); } }); } @PostMapping(value="/create", produces="application/json") public String createGame() { this.game = new Game(); Event e = new Event("Create", "Game", LocalDateTime.now()); publisher.publishEvent(e); return "Game Created"; } @DeleteMapping(value="/delete", produces="application/json") public String deleteGame() { game = null; Event e = new Event("Delete", "Game", LocalDateTime.now()); publisher.publishEvent(e); return "Game Deleted"; } @PostMapping(value="/deck", produces="application/json") public String addDeck() { Deck deck = new Deck(); game.addDeck(deck); Event e = new Event("Add", "Deck", LocalDateTime.now()); publisher.publishEvent(e); return "New Deck Added"; } @PostMapping(value="/player/{id}", produces="application/json") public Player addPlayer(@PathVariable String id) { Player player = new Player(id); game.addPlayer(player); Event e = new Event("Add", String.format("Player with name %s", id), LocalDateTime.now()); publisher.publishEvent(e); return player; } @DeleteMapping(value="/player/{id}", produces="application/json") public String removePlayer(@PathVariable String id) { Player player = new Player(id); game.removePlayer(player); Event e = new Event("Remove", String.format("Player with name %s", id), LocalDateTime.now()); publisher.publishEvent(e); return String.format("Player %s removed from game", id); } @GetMapping(value="/cards", produces="application/json") public SuitValues getRemainder() { return game.getRemainder(); } @GetMapping(value="/player/list", produces="application/json") public List<Player> getPlayers() { return game.getPlayers(); } @GetMapping(value="/player/{id}/cards", produces="application/json") public List<Card> getCardsForPlayer(@PathVariable String id) { Player player = new Player(id); return game.getCardsForPlayer(player); } @PostMapping(value="/player/{id}/deal/{number}", produces="application/json") public Player dealCards(@PathVariable String id, @PathVariable Integer number) { Player player = new Player(id); Event e = new Event("Deal", String.format("%d cards to %s", number, id), LocalDateTime.now()); publisher.publishEvent(e); return game.dealCardsToPlayer(player, number); } @GetMapping(value="/events", produces="application/json") public List<Event> getEventHistory() { // Return event history return history.getHistory(); } }
package com.github.fallback.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Index; import org.hibernate.annotations.Table; import com.github.fallback.biz.i.FallbackJobStatus; /** * Describes a Job * * @author jon */ @Entity(name = "job") @Table(appliesTo = "job", indexes = { @Index(name = "status", columnNames = { "status" }) }) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class FallbackJob { /** */ @Id @GeneratedValue private Long id; /** */ @Column(nullable = false) private Long clientId; /** */ @Column(nullable = false) private Date createdDate; /** */ @Column(nullable = false) private Date reportFrom; /** */ @Column(nullable = false) private Date reportTo; /** */ @Column(nullable = false) @Enumerated(EnumType.STRING) private FallbackJobStatus status; /** */ @Column(nullable = true, length = 2048) private String message; /** */ public FallbackJob() { } /** * Main constructor that should be used to create a new job. */ public FallbackJob(Long clientId, Date reportFrom, Date reportTo) { this.clientId = clientId; this.reportFrom = reportFrom; this.reportTo = reportTo; this.status = FallbackJobStatus.CREATED; this.createdDate = new Date(); } /** */ public Long getId() { return id; } /** */ public Long getClientId() { return clientId; } /** */ public Date getReportFrom() { return reportFrom; } /** */ public Date getReportTo() { return reportTo; } /** */ public FallbackJobStatus getStatus() { return status; } /** */ public void setStatus(FallbackJobStatus status) { this.status = status; } /** */ public Date getCreatedDate() { return createdDate; } /** * A place to detail why an error occurred. */ public String getMessage() { return message; } /** * A place to detail why an error occurred. */ public void setMessage(String message) { this.message = message; } /** */ @Override public String toString() { return "FallbackJob [id=" + id + ", clientId=" + clientId + ", createdDate=" + createdDate + ", reportFrom=" + reportFrom + ", reportTo=" + reportTo + ", status=" + status + ", message=" + message + "]"; } }
<?php declare(strict_types=1); namespace App\Infrastructure\Database\Persistence; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class RoleRepository extends \App\Infrastructure\Database\Persistence\AbstractRepository implements \App\Domain\RoleRepositoryInterface { protected const SELECTION_KEY = 'roles'; /** * @inheritDoc */ public function save(\App\Domain\Role $role): bool { try { return $role->save(); } catch (\Exception $exception) { throw new \App\Domain\DomainException\DomainRecordNotSavedException( 'repository.error.not_saved', (int) $exception->getCode(), $exception ); } } /** * @inheritDoc */ public function get(string $roleCode): \App\Domain\Role { try { /** @var \App\Domain\Role $role */ $role = \App\Domain\Role::query()->findOrFail($roleCode); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) { throw new \App\Domain\DomainException\DomainRecordNotFoundException( 'repository.error.not_found', (int) $exception->getCode(), $exception ); } return $role; } /** * @inheritDoc */ public function delete(\App\Domain\Role $role): bool { try { $role->delete(); } catch (\LogicException $exception) { throw new \App\Domain\DomainException\DomainRecordNotRemovedException( 'repository.error.not_removed', (int) $exception->getCode(), $exception ); } return true; } /** * @inheritDoc */ public function deleteByCode(string $roleCode): bool { $this->delete($this->get($roleCode)); return true; } }
#include <linux/delay.h> #include <linux/init.h> #include <linux/kthread.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/slab.h> MODULE_LICENSE("GPL"); struct task_struct **threads; int counter; static int atomic_add_func(void *arg) { int num; while (!kthread_should_stop()) { num = __sync_fetch_and_add(&counter, 1); printk("PID[%u] %s: counter is %d\n", current->pid, __func__, num); msleep(500); } return (0); } int __init atomic_practice_init(void) { int i; printk ("Atomic with fetch_and_add Start: 20194094 Yongmin Yoo\n"); threads = (struct task_struct **)kmalloc(sizeof(struct task_struct *) * 4, GFP_KERNEL); for (i = 0; i < 4; i++) { threads[i] = kthread_run (&atomic_add_func, NULL, "Atomic Add"); } return (0); } void __exit atomic_practice_cleanup(void) { int i; for(i = 0; i < 4; i++) { if (threads[i]) { kthread_stop(threads[i]); threads[i] = NULL; kfree(threads[i]); } } kfree(threads); printk ("Atomin with fetch_and_add Exit: Module Removed\n"); } module_init(atomic_practice_init); module_exit(atomic_practice_cleanup);
package br.com.popularjavareposapp.ui.view.content import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import br.com.popularjavareposapp.ui.theme.PopularJavaReposAppTheme import br.com.popularjavareposapp.ui.view.TopBar @OptIn(ExperimentalMaterial3Api::class) @Composable fun LoginScreen(focusRequester: FocusRequester, navigate: () -> Unit) { PopularJavaReposAppTheme { Scaffold(modifier = Modifier.fillMaxSize(), topBar = { TopBar() } ) { paddingValues -> Box( modifier = Modifier .padding(paddingValues) .background(Color.White) ) { LoginContent(focusRequester, navigate) } } } } @Composable @OptIn(ExperimentalMaterial3Api::class) private fun LoginContent(focusRequester: FocusRequester, navigate: () -> Unit) { var text by remember { mutableStateOf("") } var password by rememberSaveable { mutableStateOf("") } Column(modifier = Modifier.padding(16.dp)) { OutlinedTextField( placeholder = { }, value = text, onValueChange = { text = it }, shape = RectangleShape, label = { Text(text = "E-mail") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, imeAction = ImeAction.Next ), modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester) ) OutlinedTextField( placeholder = { }, value = password, onValueChange = { password = it }, shape = RectangleShape, label = { Text(text = "Password") }, visualTransformation = PasswordVisualTransformation(), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password, imeAction = ImeAction.Next ), modifier = Modifier.fillMaxWidth() ) Button( onClick = navigate, border = ButtonDefaults.outlinedButtonBorder, shape = RectangleShape, modifier = Modifier .fillMaxWidth() .padding(top = 8.dp) .size(48.dp) ) { Text("Enviar") } } } @OptIn(ExperimentalMaterial3Api::class) @Preview(showBackground = true) @Composable fun preview() { PopularJavaReposAppTheme { Scaffold(modifier = Modifier.fillMaxSize(), topBar = { TopBar() } ) { paddingValues -> Box( modifier = Modifier .padding(paddingValues) .background(Color.White) ) { LoginContent(FocusRequester(), {}) } } } }
import { useEffect, useState } from 'react'; import app from './firebase'; import { getAuth, onAuthStateChanged } from "firebase/auth"; import { getDatabase, ref, get } from 'firebase/database'; export default function Success() { const [user, setUser] = useState<any>(null); const [userData, setUserData] = useState<any>(null); useEffect(() => { const auth = getAuth(app); const unsubscribe = onAuthStateChanged(auth, async (currentUser) => { setUser(currentUser); if (currentUser) { const db = getDatabase(app); const userRef = ref(db, `/${currentUser.uid}`); try { const snapshot = await get(userRef); if (snapshot.exists()) { setUserData(snapshot.val()); } else { setUserData(null); } } catch (error) { console.error("Error fetching user data:", error); } } else { setUserData(null); } }); return () => { unsubscribe(); }; }, []); return ( <section className="bg-warning pt-3 pb-5 flex-grow-1"> {user && userData ? <div className='container bg-white p-3'> <h2>Welcome, {userData.firstName} {userData.lastName}</h2> <p>Username: {userData.username}</p> <p>Email: {user.email}</p> <p>User Type: {userData.userType}</p> <p>Language: {userData.language}</p> </div> : <h2 className='container bg-white'>Success</h2>} </section> ); }
package com.redexbackend.config; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import com.redexbackend.util.JWTUtil; @Component public class JwtRequestFilter extends OncePerRequestFilter { @Autowired private JWTUtil jwtUtil; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String token = request.getHeader("Authorization"); if (jwtUtil.validateToken(token)) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( null, null, null); usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } chain.doFilter(request, response); } }
<template> <div class="container"> <div class="favorites-list"> <div class="control"> <div class="options"> <span :class="{ active: selectedAll }"></span> <label @click="toggleAll">Select All</label> <button type="button">DELETE</button> </div> </div> <ul class="list"> <li v-for="(obj, index) of list" :key="obj.id"> <div class="item"> <div class="info"> <div class="checkbox" :class="{ active: obj.selected }" @click="toggleSelected(index)"> <span></span> </div> <div class="pic"> <img :src="obj.src" alt="" /> </div> </div> <div class="box"> <div class="text"> <h3>{{ obj.name }}</h3> <p class="price">{{ obj.price }}</p> <p class="discount"> <fa v-if="obj.discount.icon === 'shipping'" :icon="['fas', 'truck']"></fa> <span>{{ obj.discount.text }}</span> </p> </div> <div class="list-control"> <button type="button" class="add">ADD TO CART</button> <button type="button" class="checkout">BUY NOW</button> <button type="button" class="delete"> <fa :icon="['far', 'trash-alt']"></fa> </button> </div> </div> </div> </li> </ul> <div class="pages"> <div class="prev"> <fa :icon="['fas', 'angle-left']"></fa> </div> <div class="next"> <fa :icon="['fas', 'angle-right']"></fa> </div> <ul> <li class="active">1</li> <li>2</li> <li>3</li> </ul> </div> </div> </div> </template> <script> export default { name: 'LayoutFavorites', data() { return { list: [ { id: 1, src: 'https://picsum.photos/140/140?random=201', name: 'Chocolate', price: '10.00', discount: { icon: 'shipping', text: 'Freeshipping' }, selected: false, }, { id: 2, src: 'https://picsum.photos/140/140?random=202', name: 'Chocolate', price: '11.00', discount: { icon: 'discount', text: 'Discount 10%' }, selected: false, }, { id: 3, src: 'https://picsum.photos/140/140?random=203', name: 'Chocolate', price: '12.00', discount: { icon: 'shipping', text: 'Freeshipping' }, selected: false, }, ], selectedAll: false, } }, methods: { toggleSelected(index) { this.list[index].selected = !this.list[index].selected this.checkSelectedAll() }, toggleAll() { this.selectedAll = !this.selectedAll this.list.forEach((obj) => { obj.selected = this.selectedAll }) }, checkSelectedAll() { this.selectedAll = this.list.every((obj) => { return obj.selected }) }, }, } </script> <style lang="scss" scoped> @import '@/assets/scss/variable'; .favorites-list { width: 100%; margin-bottom: 24px; position: relative; .control { display: flex; justify-content: space-between; align-items: center; padding-bottom: 12px; margin-bottom: 12px; border-bottom: 1px solid #aaa; .options { font-size: 1.6rem; display: flex; align-items: center; span { width: 20px; height: 20px; border: 1px solid #666; border-radius: 4px; display: inline-block; margin-right: 8px; position: absolute; z-index: -1; &.active { background-color: map-get($color, main); border-color: map-get($color, main); &::after { content: ''; display: block; width: 60%; height: 3px; background-color: #fff; position: absolute; top: 8px; left: 7px; transform: rotate(-45deg); } &::before { content: ''; display: block; width: 40%; height: 3px; background-color: #fff; position: absolute; top: 9px; left: 3px; transform: rotate(45deg); } } } label { color: #666; margin-right: 48px; user-select: none; cursor: pointer; padding-left: 28px; } button { border: 0; border-radius: 4px; background-color: map-get($color, main); color: #fff; padding: 12px; font-weight: 600; font-size: 1.2rem; cursor: pointer; } } } .pages { display: inline-flex; position: absolute; top: 0; right: 0; @include media(640) { position: relative; right: -50%; transform: translateX(-50%); } ul { padding: 0 24px 0; margin: 0; } li { display: inline-block; list-style: none; width: 30px; height: 30px; border-radius: 50%; margin: 0 4px; text-align: center; line-height: 30px; font-size: 1.4rem; user-select: none; cursor: pointer; color: map-get($color, main); &.active { color: #fff; background-color: map-get($color, main); } } .prev, .next { font-size: 1.8rem; position: absolute; top: 50%; transform: translateY(-50%); color: map-get($color, main); cursor: pointer; } .prev { left: 0; } .next { right: 0; } } .list { margin: 0; padding: 0; li { list-style: none; padding-bottom: 12px; margin-bottom: 12px; border-bottom: 1px solid #aaa; } .item { display: flex; align-items: center; justify-content: space-between; } .info { display: flex; align-items: center; .checkbox { margin: 0 24px; span { width: 20px; height: 20px; border: 1px solid #666; border-radius: 4px; display: inline-block; margin-right: 8px; position: relative; cursor: pointer; } &.active > span { background-color: map-get($color, main); border-color: map-get($color, main); &::after { content: ''; display: block; width: 60%; height: 3px; background-color: #fff; position: absolute; top: 8px; left: 7px; transform: rotate(-45deg); } &::before { content: ''; display: block; width: 40%; height: 3px; background-color: #fff; position: absolute; top: 9px; left: 3px; transform: rotate(45deg); } } } .pic { padding-right: 12px; @include media(640) { display: none; } } } .box { flex-basis: 100%; display: flex; align-items: center; justify-content: space-between; @include media(1024) { flex-wrap: wrap; justify-content: flex-end; } .text { @include media(1024) { flex-basis: 90%; margin-bottom: 12px; } @include media(640) { flex-basis: 100%; } } .list-control { display: flex; @include media(1024) { flex-basis: 90%; } @include media(640) { flex-basis: 100%; } } h3 { font-size: 1.8rem; margin: 0 0 8px; } p { margin: 0 0 8px; font-size: 1.4rem; } .price { color: map-get($color, main); font-weight: 600; &::before { content: '$'; display: inline-block; padding-right: 2px; } } .discount { color: map-get($color, aid); font-weight: 500; } button { border: 0; background: transparent; cursor: pointer; padding: 8px; margin-right: 12px; font-weight: 900; border-radius: 4px; &:last-child { margin-right: 0; padding: 0; } } .add { border: 1px solid map-get($color, main); color: map-get($color, main); } .checkout { background-color: map-get($color, main); color: #fff; } .delete { color: map-get($color, main); font-size: 1.8rem; } } } } </style>
use bevy::prelude::*; // use bevy::render::render_resource::Texture; // use bevy_xpbd_2d::prelude::*; //doesn't work. use bevy::app::AppExit; use std::f32; mod rigidbody2d; //create some people #[derive(Component)] struct Person { name: String, } #[derive(Component)] struct Enemy { speed: f32, acceleration: f32, velocity: (f32, f32), } #[derive(Component)] enum Direction { Up, Down, Left, Right, } //for spawning enemies at a regular basis. fn add_people( time: Res<Time>, //time mut commands: Commands, //for spawning enemies asset_server: Res<AssetServer>, //for spawning from assets. ) { //speed and acceleration of enemies as we go, // as well as how far away we want to spawn our enemies. let range: f32 = 700.0; let local_speed: f32 = 50.0 + time.elapsed_seconds(); let local_accel: f32 = local_speed * 2.0 + time.elapsed_seconds() / 20.0; //spawn in 4 enemies every few seconds. if time.elapsed_seconds() % 4. <= time.delta_seconds() { commands.spawn(( Enemy { speed: local_speed, acceleration: local_accel, velocity: (0., 0.), }, SpriteBundle { texture: asset_server.load("sprites/EnemySprite.png"), transform: Transform::from_xyz(range, range, 0.), ..default() }, )); commands.spawn(( Enemy { speed: local_speed, acceleration: local_accel, velocity: (0., 0.), }, SpriteBundle { texture: asset_server.load("sprites/EnemySprite.png"), transform: Transform::from_xyz(-range, range, 0.), ..default() }, )); commands.spawn(( Enemy { speed: local_speed, acceleration: local_accel, velocity: (0., 0.), }, SpriteBundle { texture: asset_server.load("sprites/EnemySprite.png"), transform: Transform::from_xyz(range, -range, 0.), ..default() }, )); commands.spawn(( Enemy { speed: local_speed, acceleration: local_accel, velocity: (0., 0.), }, SpriteBundle { texture: asset_server.load("sprites/EnemySprite.png"), transform: Transform::from_xyz(-range, -range, 0.), ..default() }, )); } } //player controls. fn control_player( time: Res<Time>, // to keep track of time mut sprite_position: Query<(&mut Direction, &mut Transform)>, //player position keyboard: Res<Input<KeyCode>>, // player input ) { for (mut player, mut transform) in &mut sprite_position { match *player { Direction::Down => transform.translation.y -= 150. * time.delta_seconds(), Direction::Up => transform.translation.y += 150. * time.delta_seconds(), Direction::Right => transform.translation.x += 150. * time.delta_seconds(), Direction::Left => transform.translation.x -= 150. * time.delta_seconds(), } //don't let the player go out of bounds! if transform.translation.length() > 700.0 { // transform.translation = Vec3{x:0., y:0., z:0.}; transform.translation = -transform.translation; } if keyboard.pressed(KeyCode::Right) { *player = Direction::Right; transform.rotation = Quat::from_rotation_z(f32::consts::PI * 1.5); //works swimmingly! } else if keyboard.pressed(KeyCode::Down) { *player = Direction::Down; transform.rotation = Quat::from_rotation_z(f32::consts::PI * 1.); //works swimmingly! } else if keyboard.pressed(KeyCode::Left) { *player = Direction::Left; transform.rotation = Quat::from_rotation_z(f32::consts::PI * 0.5); //works swimmingly! } else if keyboard.pressed(KeyCode::Up) { *player = Direction::Up; transform.rotation = Quat::from_rotation_z(f32::consts::PI * 0.); //works swimmingly! } } } //for collision between characters fn circle_collision(enemy: Vec3, player: Vec3) -> bool { enemy.distance(player) < 5. } //for handling the rotation of enemies. fn enemy_rotation(velocity: (f32, f32)) -> Quat { //do our rotation // transform.rotation = Quat::from_rotation_z(3.14 * 0.5);//works swimmingly! //if y.abs > x.abs //it will face up or down if velocity.1.abs() > velocity.0.abs() { //if y > 0 //it faces up if velocity.1 > 0. { //if y.abs < x.abs * 2 //it will be diagonal if velocity.1.abs() < velocity.0.abs() * 2.0 { //if x > 0 //up-right if velocity.0 > 0. { return Quat::from_rotation_z(f32::consts::PI * 1.75); } //else //up-left return Quat::from_rotation_z(f32::consts::PI * 0.25); } //else //faces up Quat::from_rotation_z(0.) } else { //if y.abs < x.abs * 2 //it will be diagonal if velocity.1.abs() < velocity.0.abs() * 2.0 { //if x > 0 //up-right if velocity.0 > 0. { return Quat::from_rotation_z(f32::consts::PI * 1.25); } //else //up-left return Quat::from_rotation_z(f32::consts::PI * 0.75); } //else //faces down Quat::from_rotation_z(f32::consts::PI * 1.) } } else { //if x > 0 //it faces right if velocity.0 > 0. { //if x.abs < y.abs * 2 //it will be diagonal if velocity.0.abs() < velocity.1.abs() * 2.0 { //if y > 0 //up-right if velocity.1 > 0. { return Quat::from_rotation_z(f32::consts::PI * 1.75); } //else //down-right return Quat::from_rotation_z(f32::consts::PI * 1.25); } //else //faces right Quat::from_rotation_z(f32::consts::PI * 1.5) } else { //if x.abs < y.abs * 2 //it will be diagonal if velocity.0.abs() < velocity.1.abs() * 2.0 { //if y > 0 //up-left if velocity.1 > 0. { return Quat::from_rotation_z(f32::consts::PI * 0.25); } //else //down-left return Quat::from_rotation_z(f32::consts::PI * 0.75); } //else //faces left Quat::from_rotation_z(f32::consts::PI * 0.5) } } } //note: we'll give the ai a tuple for their velocity and have the below code affect the velocity. //then we have the ai move according to their velocity (meaning that they accelerate toward their targets.) //also, depending on which absolute value in the tuple is larger, and whether it's positive or negative, we will rotate the sprite accordingly! fn enemy_ai( time: Res<Time>, mut enemies: Query<(&mut Enemy, &mut Transform)>, //the enemies. mut target: Query<(&mut Person, &mut Transform, Without<Enemy>)>, //the player mut exit: EventWriter<AppExit>, //for exiting the system ) { for (mut pawn, mut transform) in &mut enemies { for (person, targetpos, _) in &mut target { println!("{}", person.name); // if transform.translation.distance(targetpos.translation) < 5.{ if circle_collision(transform.translation, targetpos.translation) { exit.send(AppExit); //this works! } if targetpos.translation.y > transform.translation.y { // transform.translation.y += pawn.speed * time.delta_seconds(); if pawn.velocity.1 > pawn.speed { pawn.velocity.1 = pawn.speed; } else { pawn.velocity.1 += pawn.acceleration * time.delta_seconds(); } } else if targetpos.translation.y < transform.translation.y { // transform.translation.y -= pawn.speed * time.delta_seconds(); if pawn.velocity.1 < -pawn.speed { pawn.velocity.1 = -pawn.speed; } else { pawn.velocity.1 -= pawn.acceleration * time.delta_seconds(); } } if targetpos.translation.x > transform.translation.x { // transform.translation.x += pawn.speed * time.delta_seconds(); if pawn.velocity.0 > pawn.speed { pawn.velocity.0 = pawn.speed; } else { pawn.velocity.0 += pawn.acceleration * time.delta_seconds(); } } else if targetpos.translation.x < transform.translation.x { // transform.translation.x -= pawn.speed * time.delta_seconds(); if pawn.velocity.0 < -pawn.speed { pawn.velocity.0 = -pawn.speed; } else { pawn.velocity.0 -= pawn.acceleration * time.delta_seconds(); } } //do our rotation transform.rotation = enemy_rotation(pawn.velocity); //move our character transform.translation.x += pawn.velocity.0 * time.delta_seconds(); transform.translation.y += pawn.velocity.1 * time.delta_seconds(); } } } //also for ai sprites, let's give them the shape of manta rays, with a black and white color scheme, //where some parts of them hide in the white and it appears larger in the dark. //We could even spook the player with this potentially with a large enough sprite that appears small at the beginning! fn start(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn(Camera2dBundle::default()); //background image commands.spawn(SpriteBundle { texture: asset_server.load("sprites/background1.png"), transform: Transform::from_xyz(0., 0., -100.), ..default() }); commands.spawn(( Person { name: "Reu".to_string(), }, SpriteBundle { texture: asset_server.load("sprites/PlayerSprite.png"), transform: Transform::from_xyz(100., 0., 0.), ..default() }, Direction::Up, )); } fn start_game() { App::new() //adding plugins .add_plugins( DefaultPlugins, //2D/3D renderer, asset-loading, UI system, window, input, etc. //PhysicsPlugins::default() ) //void start() .add_systems(Startup, start) //add our system to the update schedule. //sounds line Update() .add_systems(Update, (add_people, control_player, enemy_ai)) // .add_systems(Update, (control_player, enemy_ai)) .run(); } fn main() { start_game(); } //test collision #[test] fn test_collision() { //a false collision, // assert_eq!(circle_collision(Vec3{x: 0., y: 0., z: 0.}, Vec3{x: 0., y: 10., z: 0.}), false); assert_eq!( circle_collision( Vec3 { x: 0., y: 0., z: 0. }, Vec3 { x: 0., y: 10., z: 0. } ), false ); //a true collision. assert_eq!( circle_collision( Vec3 { x: 0., y: 0., z: 0. }, Vec3 { x: 0., y: 0., z: 0. } ), true ); } //test rotation #[test] fn test_rotation() { //if x > 0 //up-right assert_eq!( Quat::from_rotation_z(f32::consts::PI * 1.75), enemy_rotation((5., 5.)) ); //else //faces left assert_eq!( Quat::from_rotation_z(f32::consts::PI * 0.5), enemy_rotation((-5., 0.)) ); //faces down assert_eq!( Quat::from_rotation_z(f32::consts::PI * 1.), enemy_rotation((0., -5.)) ); }
import { InputType, Int, Field } from '@nestjs/graphql'; import { IsNotEmpty, IsOptional, IsString } from 'class-validator'; @InputType() export class CreateReportGroupInput { @Field(() => String, { nullable: false }) @IsNotEmpty() @IsString() groupId: string; @Field(() => String, { nullable: true }) @IsOptional() @IsString() description: string; @Field(() => String, { nullable: false }) @IsNotEmpty() @IsString() reportType: string; }
import { useState, useMemo } from "react"; import { useGetAllAvailableAffectation, useUpdateAffectation, } from "../../../hooks/api/useAffectationApi"; import { Alert, Box, Button, TextField, Typography } from "@mui/material"; import PlaylistAddRoundedIcon from "@mui/icons-material/PlaylistAddRounded"; import { useLocation, useNavigate } from "react-router-dom"; import { useGetAllNotAvailableAttachment, useUpdateAttachment, } from "../../../hooks/api/useAttachmentApi"; export default function Recuperer() { const location = useLocation(); const searchParams = new URLSearchParams(location.search); const initialHostName = searchParams.get("host_name") || ""; const [hostname, setHostname] = useState(initialHostName); const [dateRetour, setDateRetour] = useState(""); const [errors, setErrors] = useState(null); const navigate = useNavigate(); const { data: availableAffectations = [] } = useGetAllAvailableAffectation(); const { data: notAvailableAttachments = [] } = useGetAllNotAvailableAttachment(); const allData = useMemo( () => [...availableAffectations, ...notAvailableAttachments], [availableAffectations, notAvailableAttachments] ); const currentInventaire = useMemo( () => allData.find((inv) => inv.hostname === hostname), [allData, hostname] ); const mutationCreateAffectation = useUpdateAffectation({ onSuccess: () => navigate("/dashboard/inventaire/liste-inventaire"), onError: () => setErrors("vérifiez vos informations"), idAffectation: currentInventaire?.idAffectation, }); const mutationCreateAttachment = useUpdateAttachment({ onSuccess: () => navigate("/dashboard/inventaire/liste-inventaire"), onError: () => setErrors("vérifiez vos informations"), idAttachment: currentInventaire?.idAttachment, }); const onSubmit = () => { if (currentInventaire?.immatricule && dateRetour) { mutationCreateAffectation.mutate({ idAffectation: currentInventaire.idAffectation, dateAffectation: currentInventaire.dateAffectation, dateRetour, idTravail: currentInventaire.idTravail, idInventaire: currentInventaire.idInventaire, }); setErrors(null); return true; } else if (currentInventaire?.idAttachment && dateRetour) { mutationCreateAttachment.mutate({ idAttachment: currentInventaire.idAttachment, dateAttachment: currentInventaire.dateAttachment, dateRetoure: dateRetour, entiteTravail: { idEntiteTravail: currentInventaire.idEntiteTravail }, inventaire: { idInventaire: currentInventaire.idInventaire }, }); setErrors(null); return true; } else { setErrors("veuillez remplir tous les champs correctement"); return false; } }; return ( <Box sx={{ my: 5, mb: 5, mx: "5%", "& input , & .MuiFormLabel-root , & .MuiInputBase-root": { background: "#fff", }, }} > <Typography component="h2" variant="h5" sx={{ mt: 2, mb: 6, fontWeight: 700, borderLeft: "4px solid", borderLeftColor: "primary.main", pl: 2, }} > Enregister retour </Typography> <Box sx={{ display: "flex", flexDirection: "column" }}> {errors && ( <Alert sx={{ width: "100%" }} severity="error"> {errors} </Alert> )} <TextField type="text" fullWidth required label="Hostname du machine" variant="outlined" value={hostname} sx={{ mt: 2 }} onChange={(e) => setHostname(e.target.value)} /> {currentInventaire && ( <Box> <TextField type="text" fullWidth required label="Nom du machine" variant="outlined" sx={{ mt: 2 }} value={currentInventaire.nomMachine} disabled /> {currentInventaire.immatricule && ( <TextField fullWidth required label="Immatricule" variant="outlined" sx={{ mt: 2 }} value={currentInventaire.immatricule} disabled /> )} <TextField fullWidth required label="Place" variant="outlined" sx={{ mt: 2 }} value={currentInventaire.place} disabled /> <TextField fullWidth required label={ currentInventaire.immatricule ? "Date affectation" : "Date attachment" } variant="outlined" sx={{ mt: 2 }} value={ currentInventaire.dateAffectation || currentInventaire.dateAttachment || "" } disabled /> <TextField type="date" fullWidth required label="Date de retour" variant="outlined" sx={{ mt: 2 }} onChange={(e) => setDateRetour(e.target.value)} /> <Button type="submit" variant="contained" color="secondary" size="large" sx={{ p: 1.5, mt: 2 }} endIcon={<PlaylistAddRoundedIcon />} onClick={onSubmit} > Récupérer </Button> </Box> )} </Box> </Box> ); }
import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { Observable, ReplaySubject, of } from 'rxjs'; import { shareReplay, tap, catchError } from 'rxjs/operators'; //import { StateStorageService } from 'app/core/auth/state-storage.service';// import { environment } from 'src/environments/environment'; import { IUser } from '../users/user.interface'; @Injectable({ providedIn: 'root' }) export class AccountService { private userIdentity: IUser | null = null; private authenticationState = new ReplaySubject<IUser | null>(1); private accountCache$?: Observable<IUser | null>; constructor( private sessionStorage: SessionStorageService, private http: HttpClient, //private stateStorageService: StateStorageService, private router: Router, private localStorageService: LocalStorageService ) { } // save(account: Account): Observable<{}> { // // return this.http.post(SERVER_API + 'api/account', account); // } authenticate(identity: IUser | null): void { this.userIdentity = identity; // TODO da error // environment.userLoged = this.userIdentity?.login; this.authenticationState.next(this.userIdentity); } hasAnyAuthority(authorities: string[] | string): boolean { if (!this.userIdentity || !this.userIdentity.authorities) { return false; } if (!Array.isArray(authorities)) { authorities = [authorities]; } return this.userIdentity.authorities.some((authority: string) => authorities.includes(authority)); } identity(force?: boolean): Observable<IUser | null> { if (!this.accountCache$ || force || !this.isAuthenticated()) { this.accountCache$ = this.fetch().pipe( catchError(() => { return of(null); }), tap((user: IUser | null) => { // console.log(user); this.authenticate(user); if (user) { this.navigateToStoredUrl(); } this.localStorageService.store('idUser', user?.id); this.localStorageService.store('roles', user?.authorities); }), shareReplay() ); } return this.accountCache$; } isAuthenticated(): boolean { return this.userIdentity !== null; } getAuthenticationState(): Observable<IUser | null> { return this.authenticationState.asObservable(); } // getImageUrl(): string { // return this.userIdentity ? this.userIdentity.imageUrl : ''; // } private fetch(): Observable<IUser>{ return this.http.get<IUser>(environment.baseUrl + 'account'); } private navigateToStoredUrl(): void { // previousState can be set in the authExpiredInterceptor and in the userRouteAccessService // if login is successful, go to stored previousState and clear previousState // const previousUrl = this.stateStorageService.getUrl(); // if (previousUrl) { // this.stateStorageService.clearUrl(); // this.router.navigateByUrl(previousUrl); // } } }
import React from 'react' import { Pressable, StyleSheet, TextInput } from 'react-native' import { useTestIdBuilder } from '../../services/test-id/test-id' import { useTranslation } from '../../services/translation/translation' import { spacing } from '../../theme/spacing' import { SvgImage } from '../svg-image/svg-image' import { AvailableTranslations } from '../translated-text/types' import { TextFormField, TextFormFieldProps } from './text-form-field' type SearchFormField = TextFormFieldProps & { onClear?: () => void; accessibilityLabelI18nKey?: AvailableTranslations } export const SearchFormField = React.forwardRef<TextInput, SearchFormField>( ({ onClear, accessibilityLabelI18nKey, ...textFormFieldProps }, ref) => { const { t } = useTranslation() const { addTestIdModifier } = useTestIdBuilder() return ( <TextFormField ref={ref} {...textFormFieldProps} accessibilityRole="search"> <Pressable style={[styles.inputIcon, !textFormFieldProps.value ? styles.hidden : undefined]} onPress={onClear} accessible accessibilityRole="button" accessibilityLabel={t(accessibilityLabelI18nKey)} testID={addTestIdModifier(textFormFieldProps.testID, 'clearSearchTextButton')}> <SvgImage type={'x-circle'} width={24} height={24} /> </Pressable> </TextFormField> ) }, ) const styles = StyleSheet.create({ inputIcon: { position: 'absolute', top: 0, bottom: 0, justifyContent: 'center', right: spacing[5], }, hidden: { display: 'none', }, })
from django.db import models import hashlib def md5_set(password): m = hashlib.md5() m.update(password.encode("utf8")) return m.hexdigest() # Create your models here. class ParentCateName(models.Model): part = models.CharField(max_length=50, null=False, help_text='系统名') class Meta: db_table = "ParentCateName" managed = True def __str__(self): return self.part class CateFolder(models.Model): id = models.IntegerField(primary_key=True, auto_created=True) parent = models.IntegerField(verbose_name='所属系统名称', blank=False, help_text='所属系统名称') folder_name = models.CharField(max_length=50, blank=False, verbose_name='文件夹名称', help_text='文件夹名称') class Meta: db_table = "CateFolder" managed = True def __str__(self): return ParentCateName.objects.get(id=self.parent).__str__() class TestCase(models.Model): level_choice = ((1, 'Level 1'), (2, 'Level 2'), (3, 'Level 3'), (4, 'Level 4') ) id = models.IntegerField(primary_key=True,auto_created=True) create_worker = models.CharField(max_length=255, blank=True, null=True, verbose_name='创建人',help_text='创建人') create_time = models.DateTimeField(verbose_name='创建时间' ,help_text='创建时间') case_name = models.CharField(max_length=255, blank=True, null=True, verbose_name='用例名称', help_text='用例名称') case_number = models.CharField(max_length=255, blank=True, null=True, verbose_name="用例编号" , help_text="用例编号") case_level = models.IntegerField(default=3, choices=level_choice, help_text='用例等级', verbose_name='用例等级') case_modify_worker = models.CharField(max_length=255, verbose_name='修改人',blank=True, help_text='修改人') case_modify_time = models.DateTimeField(auto_now=True, verbose_name='用例修改时间', help_text='用例修改时间') case_belongs = models.IntegerField(verbose_name='用例所属文件夹', null=True, blank=True, help_text='用例所属文件夹') case_pre = models.CharField(max_length=255, blank=True, null=True, verbose_name='预置步骤',help_text='预置步骤') case_process = models.CharField(max_length=255, blank=True, null=True, verbose_name="用例过程", help_text="用例过程") case_expect = models.CharField(max_length=255, blank=True, null=True, verbose_name='预期结果', help_text='预期结果') class Meta: managed = True db_table = 'TestCase' def __str__(self): return self.case_number class TestCaseResult(models.Model): id = models.IntegerField(primary_key=True) create_worker = models.CharField(max_length=30, blank=True, null=True, verbose_name='创建人',help_text='创建人') create_time = models.DateTimeField(blank=True, null=True, verbose_name='创建时间', help_text='创建时间') ending_worker = models.CharField(max_length=30, blank=True, null=True, verbose_name='结束人', help_text='结束人') ending_time = models.DateTimeField(blank=True, null=True, verbose_name='结束时间', help_text='结束时间') logs = models.TextField(blank=True, null=True, verbose_name='执行日志', help_text='执行日志') result = models.CharField(max_length=30, blank=True, null=True, verbose_name='执行结果', help_text='执行结果') case_name = models.CharField(max_length=255, blank=True, null=True, verbose_name='用例名', help_text='用例名') case_number = models.CharField(max_length=100, blank=True, null=True, verbose_name='用例编号', help_text='用例编号') marker = models.CharField(max_length=255, blank=True, null=True, verbose_name='关键字' , help_text='关键字') caselevel = models.IntegerField(blank=True, null=True, verbose_name='用力等级', help_text='用力等级') imgurl = models.CharField(max_length=255, blank=True, null=True, verbose_name='图片url(UI失败时自动截图)', help_text='图片url(UI失败时自动截图)') taskname = models.CharField(max_length=255, blank=True, null=True, verbose_name='任务名', help_text='任务名') request_time = models.CharField(max_length=10, blank=True, null=True ,verbose_name='请求时间(API用例)', help_text='请求时间(API用例)') class Meta: managed = True db_table = 'TestCaseResult' class TestTask(models.Model): id = models.IntegerField(primary_key=True) create_worker = models.CharField(max_length=30, blank=True, null=True, verbose_name='创建人', help_text='创建人') create_time = models.DateTimeField(blank=True, null=True, verbose_name='创建时间', help_text='创建时间') taskname = models.CharField(max_length=255, blank=True, null=True, verbose_name='任务名', help_text='任务名') run_time = models.CharField(max_length=255, blank=True, null=True, help_text='运行开始时间', verbose_name='运行开始时间') contain_args = models.CharField(max_length=255, blank=True, null=True, verbose_name='包含参数', help_text='包含参数') passrate = models.CharField(max_length=30, blank=True, null=True, verbose_name='通过率', help_text='通过率') class Meta: managed = True db_table = 'TestTask' class TeskDetail(models.Model): taskid = models.IntegerField(verbose_name='所属任务id', blank=False, null=False, help_text='所属任务id') caseid = models.IntegerField(verbose_name='包含用例id',blank=False, null=False, help_text='包含用例id') class Meta: managed = True db_table = 'TeskDetail' class User(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(max_length=32, unique=True, verbose_name='用户名', help_text='用户名') password = models.CharField(max_length=256, verbose_name='密码',help_text='密码') mobile = models.CharField(max_length=11, blank=True, unique=True, verbose_name='手机号码', help_text='手机号码') email = models.EmailField(max_length=64, blank=True, unique=True, verbose_name='邮箱', help_text='邮箱') def set_password(self, password): self.password = md5_set(password) def check_password(self, password): return self.password == md5_set(password) def __str__(self): return self.username
import request, { RequestOptions } from "./request"; export type Course = Partial<{ // the unique identifier for the course "id": number, // the SIS identifier for the course, if defined. This field is only included if // the user has permission to view SIS information. "sis_course_id": null, // the UUID of the course "uuid": string, // the integration identifier for the course, if defined. This field is only // included if the user has permission to view SIS information. "integration_id": null, // the unique identifier for the SIS import. This field is only included if the // user has permission to manage SIS information. "sis_import_id": number, // the full name of the course. If the requesting user has set a nickname for // the course, the nickname will be shown here. "name": string, // the course code "course_code": string, // the actual course name. This field is returned only if the requesting user // has set a nickname for the course. "original_name": string, // the current state of the course one of 'unpublished', 'available', // 'completed', or 'deleted' "workflow_state": "unpublished" | "available" | "completed" | "deleted", // the account associated with the course "account_id": number, // the root account associated with the course "root_account_id": number, // the enrollment term associated with the course "enrollment_term_id": number, // A list of grading periods associated with the course "grading_periods": null, // the grading standard associated with the course "grading_standard_id": number, // the grade_passback_setting set on the course "grade_passback_setting": string, // the date the course was created. "created_at": Date, // the start date for the course, if applicable "start_at": Date, // the end date for the course, if applicable "end_at": Date, // the course-set locale, if applicable "locale": string, // A list of enrollments linking the current user to the course. for student // enrollments, grading information may be included if include[]=total_scores "enrollments": null, // optional: the total number of active and invited students in the course "total_students": number, // course calendar "calendar": null, // the type of page that users will see when they first visit the course - // 'feed': Recent Activity Dashboard - 'wiki': Wiki Front Page - 'modules': // Course Modules/Sections Page - 'assignments': Course Assignments List - // 'syllabus': Course Syllabus Page other types may be added in the future "default_view": string, // optional: user-generated HTML for the course syllabus "syllabus_body": string, // optional: the number of submissions needing grading returned only if the // current user has grading rights and include[]=needs_grading_count "needs_grading_count": number, // optional: the enrollment term object for the course returned only if // include[]=term "term": null, // optional: information on progress through the course returned only if // include[]=course_progress "course_progress": null, // weight final grade based on assignment group percentages "apply_assignment_group_weights": boolean, // optional: the permissions the user has for the course. returned only for a // single course and include[]=permissions "permissions": { "create_discussion_topic": boolean, "create_announcement": boolean }, "is_public": boolean, "is_public_to_auth_users": boolean, "public_syllabus": boolean, "public_syllabus_to_auth": boolean, // optional: the public description of the course "public_description": string, "storage_quota_mb": number, "storage_quota_used_mb": number, "hide_final_grades": boolean, "license": string, "allow_student_assignment_edits": boolean, "allow_wiki_comments": boolean, "allow_student_forum_attachments": boolean, "open_enrollment": boolean, "self_enrollment": boolean, "restrict_enrollments_to_course_dates": boolean, "course_format": string, // optional: this will be true if this user is currently prevented from viewing // the course because of date restriction settings "access_restricted_by_date": boolean, // The course's IANA time zone name. "time_zone": string, // optional: whether the course is set as a Blueprint Course (blueprint fields // require the Blueprint Courses feature) "blueprint": boolean, // optional: Set of restrictions applied to all locked course objects "blueprint_restrictions": { "content": boolean, "points": boolean, "due_dates": boolean, "availability_dates": boolean }, // optional: Sets of restrictions differentiated by object type applied to // locked course objects "blueprint_restrictions_by_object_type": { "assignment": { "content": boolean, "points": boolean }, "wiki_page": { "content": boolean } }, // optional: whether the course is set as a template (requires the Course // Templates feature) "template": boolean, // course image include[] = "course_image" "image_download_url": string // banner image include[] = "banner_image" "banner_image_download_url": string, // is in favorites include[] = "favorites" "is_favorite": boolean }> type CourseIncludeParam = "needs_grading_count" | "syllabus_body" | "public_description" | "total_scores" | "current_grading_period_scores" | "grading_periods" | "term" | "account" | "course_progress" | "sections" | "storage_quota_used_mb" | "total_students" | "passback_status" | "favorites" | "teachers" | "observed_users" | "course_image" | "banner_image" | "concluded"; type CourseRequestParams = { enrollment_type: "teacher" | "student" | "ta" | "observer" | "designer", enrollment_role: string, enrollment_role_id: number, enrollment_state: "active" | "invited_or_pending" | "completed", exclude_blueprint_courses: boolean, include: CourseIncludeParam[] } export type RequestCoursesOptions = Omit<RequestOptions, "params"> & { params?: Partial<CourseRequestParams> }; const courses = async (options: RequestCoursesOptions) => { const data = await request({ ...options, path: "/api/v1/courses" }); return data as Course[]; } export default courses;
<?php declare(strict_types=1); namespace OpenEuropa\CdtClient\Model\Request; /** * Class SourceDocument. * * Represents the single source document sent to the CDT API. */ class SourceDocument { protected File $file; /** * @var string[] */ protected array $sourceLanguages; protected string $outputDocumentFormatCode; /** * @var array<int, \OpenEuropa\CdtClient\Model\Request\TranslationJob> */ protected array $translationJobs; protected bool $isPrivate; protected string $confidentialityCode; public function getFile(): File { return $this->file; } public function setFile(File $file): self { $this->file = $file; return $this; } /** * @return string[] */ public function getSourceLanguages(): array { return $this->sourceLanguages; } /** * @param string[] $sourceLanguages */ public function setSourceLanguages(array $sourceLanguages): self { $this->sourceLanguages = $sourceLanguages; return $this; } public function getOutputDocumentFormatCode(): string { return $this->outputDocumentFormatCode; } public function setOutputDocumentFormatCode(string $outputDocumentFormatCode): self { $this->outputDocumentFormatCode = $outputDocumentFormatCode; return $this; } /** * @return array<int, \OpenEuropa\CdtClient\Model\Request\TranslationJob> */ public function getTranslationJobs(): array { return $this->translationJobs; } /** * @param array<int, \OpenEuropa\CdtClient\Model\Request\TranslationJob> $translationJobs */ public function setTranslationJobs(array $translationJobs): self { $this->translationJobs = $translationJobs; return $this; } public function getConfidentialityCode(): string { return $this->confidentialityCode; } public function setConfidentialityCode(string $confidentialityCode): self { $this->confidentialityCode = $confidentialityCode; return $this; } public function isPrivate(): bool { return $this->isPrivate; } public function setIsPrivate(bool $isPrivate): self { $this->isPrivate = $isPrivate; return $this; } }
import React, { useMemo } from "react"; import { Group } from "@visx/group"; import { Tree, hierarchy } from "@visx/hierarchy"; import { HierarchyPointNode } from "@visx/hierarchy/lib/types"; import { LinkHorizontal } from "@visx/shape"; import { LinearGradient } from "@visx/gradient"; import { Zoom } from "@visx/zoom"; import { localPoint } from "@visx/event"; const peach = "#fd993"; const pink = "#fe69e"; const blue = "#030dc"; const green = "#2deb0"; const plum = "#7148e"; const lightpurple = "#34469"; const white = "#ffffff"; export const background = "#ffffff"; interface TreeNode { name: string; children?: this[]; } type HierarchyNode = HierarchyPointNode<TreeNode>; /** Handles rendering Root, Parent, and other Nodes. */ function Node({ node }: { node: HierarchyNode }) { const width = 40; const height = 20; const centerX = -width / 2; const centerY = -height / 2; return ( <Group top={node.x} left={node.y}> <rect height={height} width={width} y={centerY} x={centerX} fill={background} stroke={green} strokeWidth={1} strokeDasharray="2,2" strokeOpacity={0.6} rx={10} onClick={() => { alert(`clicked: ${JSON.stringify(node.data.name)}`); }} /> <text dy=".33em" fontSize={9} fontFamily="Arial" textAnchor="middle" fill={green} style={{ pointerEvents: "none" }} > {node.data.name} </text> </Group> ); } function RootNode({ node }: { node: HierarchyNode }) { return ( <Group top={node.x} left={node.y}> <circle r={12} fill="url('#lg')" /> <text dy=".33em" fontSize={9} fontFamily="Arial" textAnchor="middle" style={{ pointerEvents: "none" }} fill={plum} > {node.data.name} </text> </Group> ); } function ParentNode({ node }: { node: HierarchyNode }) { const width = 40; const height = 20; const centerX = -width / 2; const centerY = -height / 2; return ( <Group top={node.x} left={node.y}> <rect height={height} width={width} y={centerY} x={centerX} fill={background} stroke={blue} strokeWidth={1} onClick={() => { alert(`clicked: ${JSON.stringify(node.data.name)}`); }} /> <text dy=".33em" fontSize={9} fontFamily="Arial" textAnchor="middle" style={{ pointerEvents: "none" }} fill={white} > {node.data.name} </text> </Group> ); } const defaultMargin = { top: 10, left: 80, right: 80, bottom: 10 }; export type TreeProps = { width: number; height: number; margin?: { top: number; right: number; bottom: number; left: number }; }; const initialTransform = { scaleX: 1.27, scaleY: 1.27, translateX: -211.62, translateY: 162.59, skewX: 0, skewY: 0 }; export default function Example({ width, height, margin = defaultMargin }: TreeProps) { const data = useMemo(() => hierarchy(rawTree), []); const yMax = height - margin.top - margin.bottom; const xMax = width - margin.left - margin.right; return ( <> <Zoom<SVGSVGElement> width={width} height={height} scaleXMin={1 / 2} scaleXMax={4} scaleYMin={1 / 2} scaleYMax={4} initialTransformMatrix={initialTransform} > {(zoom) => ( <> <svg width={width} height={height} style={{ cursor: zoom.isDragging ? "grabbing" : "grab", touchAction: "none" }} ref={zoom.containerRef} > <LinearGradient id="lg" from={peach} to={pink} /> <rect width={width} height={height} rx={14} fill={background} onTouchStart={zoom.dragStart} onTouchMove={zoom.dragMove} onTouchEnd={zoom.dragEnd} onMouseDown={zoom.dragStart} onMouseMove={zoom.dragMove} onMouseUp={zoom.dragEnd} onMouseLeave={() => { if (zoom.isDragging) zoom.dragEnd(); }} onDoubleClick={(event) => { const point = localPoint(event) || { x: 0, y: 0 }; zoom.scale({ scaleX: 1.1, scaleY: 1.1, point }); }} /> <Tree<TreeNode> root={data} size={[yMax, xMax]}> {(tree) => ( <Group top={margin.top} left={margin.left}> {tree.links().map((link, i) => ( <LinkHorizontal key={`link-${i}`} data={link} stroke={lightpurple} strokeWidth="1" fill="none" /> ))} {tree.descendants().map((node, i) => ( <Node key={`node-${i}`} node={node} /> ))} </Group> )} </Tree> </svg> <div className="controls"> <button type="button" className="btn btn-zoom" onClick={() => zoom.scale({ scaleX: 1.2, scaleY: 1.2 })} > + </button> <button type="button" className="btn btn-zoom btn-bottom" onClick={() => zoom.scale({ scaleX: 0.8, scaleY: 0.8 })} > - </button> <button type="button" className="btn btn-lg" onClick={zoom.center} > Center </button> <button type="button" className="btn btn-lg" onClick={zoom.reset}> Reset </button> <button type="button" className="btn btn-lg" onClick={zoom.clear}> Clear </button> </div> </> )} </Zoom> <style jsx>{` .btn { margin: 0; text-align: center; border: none; background: #2f2f2f; color: #888; padding: 0 4px; border-top: 1px solid #0a0a0a; } .btn-lg { font-size: 12px; line-height: 1; padding: 4px; } .btn-zoom { width: 26px; font-size: 22px; } .btn-bottom { margin-bottom: 1rem; } .description { font-size: 12px; margin-right: 0.25rem; } .controls { position: absolute; top: 15px; right: 15px; display: flex; flex-direction: column; align-items: flex-end; } .mini-map { position: absolute; bottom: 25px; right: 15px; display: flex; flex-direction: column; align-items: flex-end; } .relative { position: relative; } `}</style> </> ); }
import { StyleSheet, Text, View, SafeAreaView, Image, TouchableOpacity, Button, ImageBackground, TextInput, Platform, TouchableNativeFeedback } from 'react-native'; import React, {useState, useEffect, useRef} from 'react'; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from 'react-native-responsive-screen'; import MapIcon from '../assests/svgs/Map.png'; import LeftArrowIcon from '../assests/svgs/leftarrowIcon.svg'; import HistoryIcon from '../assests/svgs/HistoryIcon.svg'; import HistoryIcon2 from '../assests/svgs/HistoryIcon2.svg'; import MapLayer from '../assests/svgs/MapLayer.svg'; import FullScreen from '../assests/svgs/fullscreen.svg'; import fonts from '../constants/font'; import {useNavigation} from '@react-navigation/native'; import {AuthRoutes} from '../constants/routes'; import NavigationIcon from '../assests/svgs/navigation.svg'; import PlusIcon from '../assests/svgs/PlusIcon.svg'; import MinusIcon from '../assests/svgs/MinusIcon.svg'; import CurrentLocation from '../assests/svgs/currentLocationIcon.svg'; import ShareIcon from '../assests/svgs/Share1.svg'; import CopyIcon from '../assests/svgs/Copy1.svg'; import MapView, {PROVIDER_GOOGLE, Marker} from 'react-native-maps'; import Geolocation from '@react-native-community/geolocation'; import {useDispatch} from 'react-redux'; import {setinittialRoute} from '../store/actions/InittailRouteActions'; import LocationPin from '../assests/svgs/Locationpin.svg'; const GPSCordinateScreen = () => { const navigation = useNavigation(); const dispatch = useDispatch(); useEffect(() => { dispatch(setinittialRoute('gpscordinatescreen')); }, []); const MapRef = useRef(null) const [currentLocation, setCurrentLocation] = useState({ latitude: 0, longitude: 0, }); const [selectedLayer, setSelectedLayer] = useState('standard'); const [markerLocation, setMarkerLocation] = useState(null); const [title, setTitle] = useState('Rawalpindi'); const initialLatitude = currentLocation.latitude.toString(); const initialLongitude = currentLocation.longitude.toString(); const [inputLatitude, setInputLatitude] = useState(initialLatitude); const [inputLongitude, setInputLongitude] = useState(initialLongitude); const [coordinatesEdited, setCoordinatesEdited] = useState(false); const [zoomLevel, setZoomLevel] = useState(15); const handleTrafficLayer = () => { if (selectedLayer === 'satellite') { setSelectedLayer('standard'); } else { setSelectedLayer('satellite'); } }; useEffect(() => { const getLocation = () => { Geolocation.getCurrentPosition( position => { setCurrentLocation({ latitude: position.coords.latitude, longitude: position.coords.longitude, }); _animateMapToRegion({ latitude: position.coords.latitude, longitude: position.coords.longitude, }) setMarkerLocation({ latitude: position.coords.latitude, longitude: position.coords.longitude, }); getAddress({ lat: position.coords.latitude, lng: position.coords.longitude, }); }, error => { console.log(error); }, {enableHighAccuracy: false, timeout: 20000, maximumAge: 1000}, ); }; getLocation(); }, []); const getAddress = ({lat, lng}) => { const requestOptions = { method: 'GET', redirect: 'follow', }; fetch( `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&zoom=18&addressdetails=1&accept-language=en`, requestOptions, ) .then(response => response.json()) .then(result => { setTitle(result.display_name); }) .catch(error => console.error(error)); }; const onZoomInPress = () => { const currentMap = MapRef.current; if (currentMap) { currentMap.getCamera().then((cam) => { cam.zoom += 1; currentMap.animateCamera(cam); }); } }; const onZoomoutPress = () => { const currentMap = MapRef.current; if (currentMap) { currentMap.getCamera().then((cam) => { cam.zoom -= 1; currentMap.animateCamera(cam); }); } }; const handleGetLocation = () => { const latitude = parseFloat(inputLatitude); const longitude = parseFloat(inputLongitude); if (!isNaN(latitude) && !isNaN(longitude)) { setMarkerLocation({latitude, longitude}); setCurrentLocation({latitude, longitude}); getAddress({lat: latitude, lng: longitude}); } else { console.error('Invalid latitude or longitude'); } }; const handleMarkerPress = (event) => { const { latitude, longitude } = event.nativeEvent.coordinate; setInputLatitude(latitude.toString()); setInputLongitude(longitude.toString()); setCoordinatesEdited(true); getAddress({ lat: latitude, lng: longitude }); }; const handleMapPress = (event) => { const { latitude, longitude } = event.nativeEvent.coordinate; setMarkerLocation({ latitude, longitude }); setInputLatitude(latitude.toString()); setInputLongitude(longitude.toString()); getAddress({ lat: latitude, lng: longitude }); }; const _animateMapToRegion = (Location) => { const { latitude, longitude } = Location; const newRegion = { latitude:latitude, longitude:longitude, latitudeDelta: 0.015 , longitudeDelta: 0.0121 , }; setInputLatitude(latitude.toString()); setInputLongitude(longitude.toString()); MapRef.current.animateToRegion(newRegion, 1000); }; const addressLines = title.split(','); const firstLine = addressLines.slice(0, 5).join(','); return ( <> <View style={{flex: 1, backgroundColor: '#fff'}}> <View style={styles.container}> <MapView ref={MapRef} provider={'google'} style={styles.map} zoomEnabled={true} mapType={selectedLayer === 'standard' ? 'standard' : 'satellite'} onPress={handleMapPress} initialRegion={{ latitude: currentLocation.latitude, longitude: currentLocation.longitude, latitudeDelta: 0.015 * zoomLevel, longitudeDelta: 0.0121 * zoomLevel, }} > {markerLocation && ( <Marker coordinate={markerLocation} onPress={handleMarkerPress}> <LocationPin width={40} height={40} /> </Marker> )} </MapView> <View style={{position: 'absolute', top: hp('30%'), right: 5}}> {/* <TouchableOpacity onPress={handleTrafficLayer}> <MapLayer width={60} height={60} /> </TouchableOpacity> */} </View> </View> <View style={{ position: 'absolute', ...Platform.select({ ios: { marginTop: 50, }, }), }}> <TouchableOpacity onPress={() => navigation.navigate(AuthRoutes.MainScreen)}> <LeftArrowIcon width={70} height={70} style={styles.LeftArrowIcon} /> </TouchableOpacity> <View style={{left: 80, marginTop: 25}}> <Text style={{color: '#3972FE', fontSize: 18, fontWeight: '700'}}> GPS{' '} <Text style={{color: '#1E1F4B', fontSize: 18, fontWeight: '700'}}> Cordinate </Text> </Text> </View> </View> {/* Location pin icon */} {/* <View style={{position:'absolute',alignSelf:'center',top:hp(40),gap:10}}> <LocationPin /> </View> */} {/* icons */} <View style={{ position: 'absolute', justifyContent: 'center', alignItems: 'center', alignSelf: 'flex-end', top: hp(30), right: 30, }}> <TouchableOpacity onPress={onZoomInPress} > <View style={{ position: 'absolute', right: wp('-5%'), // marginTop:60, // // top: hp('53%'), backgroundColor:'#fff', elevation:10, ...Platform.select({ ios:{ width:wp(12), height:hp(5), }, android:{ width:wp(12), height:hp(5.5), } }), borderRadius:10 }}> <PlusIcon width={40} height={40} style={styles.PlusIcon} /> </View> </TouchableOpacity> <TouchableOpacity onPress={onZoomoutPress} > <View style={{ position: 'absolute', right: wp('-5%'), // marginTop:60, top: hp('7%'), backgroundColor:'#fff', elevation:10, ...Platform.select({ ios:{ width:wp(12), height:hp(5), }, android:{ width:wp(12), height:hp(5.5), } }), borderRadius:10 }}> <MinusIcon width={40} height={40} style={styles.MinusIcon} /> </View> </TouchableOpacity> <TouchableOpacity onPress={handleTrafficLayer} > <View style={{ position: 'absolute', right: wp('-5%'), top: hp('14%'), backgroundColor:'#fff', elevation:10, ...Platform.select({ ios:{ width:wp(12), height:hp(5), }, android:{ width:wp(12), height:hp(5.5), } }), borderRadius:10 }}> <MapLayer width={40} height={40} style={styles.maplayer} /> </View> </TouchableOpacity> <TouchableOpacity onPress={()=>{ MapRef.current.animateToRegion({ latitude:currentLocation.latitude, longitude:currentLocation.longitude, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }) }} > <View style={{ position: 'absolute', right: wp('-5%'), top: hp('21%'), backgroundColor:'#fff', elevation:10, ...Platform.select({ ios:{ width:wp(12), height:hp(5), }, android:{ width:wp(12), height:hp(5.5), } }), borderRadius:10 }}> <CurrentLocation width={40} height={40} style={styles.CurrentLocation} /> </View> </TouchableOpacity> </View> <View style={styles.BottomContainer}> <View> <Text style={{textAlign: 'center', marginTop: 10}}>{firstLine}</Text> </View> <View style={{ flexDirection: 'row', justifyContent: 'center', margin: 15, columnGap: 10, marginTop: 20, }}> <View style={{ width: '50%', height: 60, borderRadius: 12, }}> <TextInput style={styles.input} placeholder="Enter latitude" onChangeText={text => { setInputLatitude(text); setCoordinatesEdited(true); }} value={inputLatitude} keyboardType="numeric" /> </View> <View style={{ width: '50%', height: 60, borderRadius: 12, }}> <TextInput style={styles.input} placeholder="Enter longitude" onChangeText={text => { setInputLongitude(text); setCoordinatesEdited(true); }} value={inputLongitude} keyboardType="numeric" /> </View> </View> {coordinatesEdited && ( <TouchableOpacity onPress={handleGetLocation} style={{ backgroundColor: '#3972FE', width: '90%', height: 50, borderRadius: 5, marginLeft: 18, justifyContent: 'center', alignItems: 'center', bottom: 10, }}> <Text style={{ color: '#fff', textAlign: 'center', fontFamily: fonts.Bold, fontWeight: '500', }}> Get Location </Text> </TouchableOpacity> )} </View> </View> </> ); }; export default GPSCordinateScreen; const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, height: hp('100%'), width: wp('100%'), justifyContent: 'flex-end', alignItems: 'center', }, map: { ...StyleSheet.absoluteFillObject, }, LeftArrowIcon: { position: 'absolute', }, RefreshIcon: { position: 'absolute', top: 20, left: 20, }, BottomContainer: { position: 'absolute', backgroundColor: '#fff', bottom: 0, borderRadius: 15, width: wp('100%'), height: hp('25%'), shadowOffset: { width: 0, }, shadowColor: 'black', shadowOpacity: 0.24, shadowRadius: 10, }, TextContainer: { textAlign: 'center', marginTop: 15, borderRadius: 7, backgroundColor: '#F9F9F9', width: wp('100%'), height: hp('30%'), shadowOffset: { width: 0, }, shadowColor: 'black', }, NavigationIcon: { alignSelf: 'center', marginTop: 15, }, button: { backgroundColor: '#F9F9F9', width: wp('30%'), height: hp('7%'), borderRadius: 8, }, buttonText: { color: '#1E1F4B', fontSize: 8, fontWeight: '700', justifyContent: 'center', }, HideContainer: { backgroundColor: '#fff', width: wp('90%'), height: hp('50%'), shadowColor: 'black', borderRadius: 10, shadowOffset: { width: 0, }, }, cordinatesContainer: { backgroundColor: 'red', width: '50%', height: 60, shadowColor: 'black', shadowOffset: { width: 0, height: 2, }, }, input: { height: 40, borderColor: 'gray', borderWidth: 1, borderRadius: 5, margin: 10, paddingLeft: 10, }, CurrentLocation:{ justifyContent:'center', alignItems:'center', marginLeft:2, bottom:2 }, PlusIcon:{ justifyContent:'center', alignItems:'center', marginLeft:2, marginTop:2 }, MinusIcon:{ justifyContent:'center', alignItems:'center', marginLeft:2, marginTop:2 }, maplayer:{ justifyContent:'center', alignItems:'center', marginLeft:2, marginTop:2 }, });
import StudentReminderGenerator from "./StudentReminderGenerator"; import Message from "../Message"; const NOW = 1521032816573; const EXPECTED_QUERY = "AND(DATETIME_DIFF({Start time}, 1521032816573, 'minutes') < 10, DATETIME_DIFF({Start time}, 1521032816573, 'minutes') > 0, {Visible to students?} = 1, {Reminder given?} = 0)"; describe("#produce", () => { it("returns messages for the events in the next 10 minutes", async () => { const getTasks = fakeGetTasksFor(EXPECTED_QUERY, [ { Name: "Retro", "Start time": NOW + 60000 * 9, Cohorts: ["55"] }, { Name: "Metro", "Start time": NOW + 60000 * 10, Cohorts: ["56"] } ]); const generator = new StudentReminderGenerator(getTasks, cohortLookup); const messages = await generator.produce(NOW); expect(messages).toEqual([ new Message("<!channel> Retro starting in 9 minutes!", "#january2018"), new Message("<!channel> Metro starting in 10 minutes!", "#february2018") ]); }); it("returns messages when an event has multiple cohorts", async () => { const getTasks = fakeGetTasksFor(EXPECTED_QUERY, [ { Name: "Retro", "Start time": NOW + 60000 * 9, Cohorts: ["55", "56"] } ]); const generator = new StudentReminderGenerator(getTasks, cohortLookup); const messages = await generator.produce(NOW); expect(messages).toEqual([ new Message("<!channel> Retro starting in 9 minutes!", "#january2018"), new Message("<!channel> Retro starting in 9 minutes!", "#february2018") ]); }); it("ignores tasks with no cohorts", async () => { const getTasks = fakeGetTasksFor(EXPECTED_QUERY, [ { Name: "Retro", "Start time": NOW + 60000 * 9, Cohorts: undefined } ]); const generator = new StudentReminderGenerator(getTasks, cohortLookup); const messages = await generator.produce(NOW); expect(messages).toEqual([]); }); }); describe("#markComplete", async () => { const completedItems = []; const markCompleter = id => new Promise(resolve => { completedItems.push(id); resolve(); }); const generator = new StudentReminderGenerator(() => {}, () => {}, markCompleter); const message = new Message("<!channel> Retro starting in 9 minutes!", "#january2018", 4); await generator.markComplete(message); expect(completedItems).toContain(4); }); const cohortLookup = async key => ({ "55": "january2018", "56": "february2018" }[key]); const fakeGetTasksFor = (expectedQuery, value) => query => { if (query !== expectedQuery) { throw new Error( `Fake getTasks called with wrong query.\nGot ${query}\nExpected ${expectedQuery}` ); } return value.map(fakeRecord); }; const fakeRecord = (attributes = {}) => { return { get: key => attributes[key] }; };
// use client import React, { Suspense, lazy } from "react"; import { UserContextProvider } from "@/app/utils/UserContext"; import AuthHandler from "@/app/utils/AuthHandler"; import { ToastContainer } from "react-toastify"; import Spinner from "@/app/components/Spinner"; // Lazy load ParticleBackground component const ParticleBackground = lazy(() => import('@/app/components/ParticleBackground')); // Lazy load ToastContainer component const LazyToastContainer = lazy(() => import("react-toastify").then(module => ({ default: module.ToastContainer }))); export function InnerLayout({ children }: { children: React.ReactNode }) { return ( <UserContextProvider> <AuthHandler /> <Suspense fallback={<Spinner />}> <Suspense fallback={null}> <ParticleBackground> {children} </ParticleBackground> </Suspense> <Suspense fallback={null}> <LazyToastContainer /> </Suspense> </Suspense> </UserContextProvider> ) }
function speckle2bin(file_sc,n_repeat,sc_range,averaged,bin_size,varargin) %speckle2bin Generates image from speckle contrast data and bins them into %.sc files. Trial based averaging % speckle2bin(file_sc,n_repeat,sc_range,averaged,bin_size) load, average, and render speckle % contrast data to an image file. % % file_sc = Path to directory of speckle contrast files % n_repeat = Number of sequences in each trial (Length of trial) % sc_range = Display range for speckle contrast data [min max] % averaged = Binary indicator. True if you averaged the 15 frames in FOIL % bin_size = Size of each time bin in # of sequences % speckle2Image(___,Name,Value) modifies the image appearance using one or % more name-value pair arguments. % % 'show_scalebar': Toggle display of the scalebar (Default = true) % Scale is hard-coded in SpeckleFigure to that of the multimodal system % % 'formattype': Specify output file format (Default = 'png') % Select either lossy 'png' or lossless 'bmp' % % 'resolution': Specify output file resolution (Default = System Resolution) % Output image resolution in pixels-per-inch % 'trials': Specify the number of trials performed for stimulation. ie % the number of stimulation experiments performed close all; p = inputParser; addRequired(p, 'file_sc', @(x) exist(x, 'dir')); addRequired(p, 'n_repeat', @isscalar); addRequired(p, 'sc_range', @(x) validateattributes(x, {'numeric'}, {'numel', 2, 'increasing'})); addRequired(p, 'averaged', @isscalar); addRequired(p, 'bin_size', @isscalar); addParameter(p, 'show_scalebar', true, @islogical); addParameter(p, 'formattype', 'png', @(x) any(validatestring(x, {'png', 'bmp'}))); addParameter(p, 'resolution', get(0, 'screenpixelsperinch'), @isscalar); addParameter(p, 'trials', @isscalar); addOptional(p,'trials_initial',''); parse(p, file_sc, n_repeat, sc_range,averaged,bin_size,varargin{:}); file_sc = p.Results.file_sc; n_repeat = p.Results.n_repeat; sc_range = p.Results.sc_range; averaged = p.Results.averaged; bin_size = p.Results.bin_size; show_scalebar = p.Results.show_scalebar; formattype = p.Results.formattype; resolution = p.Results.resolution; trials = p.Results.trials; trials_initial = p.Results.trials_initial; if (~isscalar(trials_initial)) trials_initial = 1; end % Read and average the first n speckle contrast frames files = dir_sorted(fullfile(file_sc, '*.sc')); if (~exist(fullfile(pwd,'results'),'dir')) mkdir('results'); % create directory to store processed data end % My code to create 'n_repeat' bins if averaged == 1 x = floor(n_repeat/bin_size); % number of bins fprintf('Total # of bins created: %d\n',x); start_trial = [1:n_repeat:1000*n_repeat]; start_trial = start_trial(trials_initial:trials+trials_initial-1); for j = [1:x] arr = int32.empty(0,bin_size*trials); % v1 = bin_size*[j:bin_size:trials*bin_size]; for i = 1:trials add_arr = [start_trial(i)+(j-1)*bin_size:start_trial(i)+(bin_size-1)+(j-1)*bin_size]; % add_arr = [v1(i)-bin_size+1:v1(i)]; arr = [arr,add_arr]; end fprintf('Bin #%d created\n',j); sc = read_subimage(files, -1 , -1 ,arr); sc = mean(sc, 3)'; % Create the figure F = SpeckleFigure(sc, sc_range); if show_scalebar F.showScalebar(); end % Write the image to file im_ext = '.sc'; name_sc = ['Bin', num2str(j,2), im_ext]; name_png = ['Bin_fig', num2str(j,2)]; filename_sc = fullfile(pwd,'results',name_sc); filename_png = fullfile(pwd,'results',name_png); write_sc(sc',filename_sc); if strcmp(formattype, 'png') F.savePNG(filename_png, resolution); elseif strcmp(formattype, 'bmp') F.saveBMP(filename_png, resolution); end clear arr; end else frame_seq = 15; % Need to add code here end end
function printMatrix(matrix) { for (let i = 0; i < matrix.length; i++) { console.log(matrix[i].join('\t')); } } function matrixMultiplication(matrixA, matrixB) { const rowsA = matrixA.length; const colsA = matrixA[0].length; const rowsB = matrixB.length; const colsB = matrixB[0].length; if (colsA !== rowsB) { console.log("Não é possível calcular a multiplicação das matrizes."); return null; } const resultMatrix = []; for (let i = 0; i < rowsA; i++) { resultMatrix[i] = []; for (let j = 0; j < colsB; j++) { resultMatrix[i][j] = 0; for (let k = 0; k < colsA; k++) { resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j]; } } } return resultMatrix; } const matrixA = [ [1, 3], [2, 5] ]; const matrixB = [ [2, 2], [0, 1] ]; const matrixC = matrixMultiplication(matrixA, matrixB); console.log("Matriz A:"); printMatrix(matrixA); console.log("\nMatriz B:"); printMatrix(matrixB); console.log("\nMatriz C (Resultado da multiplicação AxB):"); if (matrixC) { printMatrix(matrixC); }
import * as React from 'react'; import Backdrop from '@mui/material/Backdrop'; import CircularProgress from '@mui/material/CircularProgress'; import Button from '@mui/material/Button'; import { Typography, Stack } from '@mui/material'; export default function SimpleBackdrop({title, subtitle, body, imageSrc}) { const [open, setOpen] = React.useState(false); const handleClose = () => { setOpen(false); }; const handleOpen = () => { setOpen(true); }; return ( <div> <Button onClick={handleOpen}>Show backdrop</Button> <Backdrop sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }} open={open} onClick={handleClose} > <Stack spacing={2} direction="column" alignItems='center' justifyContent="center"> <Typography variant="h5">{title}</Typography> <div style={{width: '35%', boxSizing: 'border-box'}}> {/* <img src={imageSrc} alt="Loading" width="100%" height="100%" /> */} <CircularProgress color="inherit" size='100px' /> </div> <Typography variant="subtitle1">{subtitle}</Typography> <Typography variant="body2">{body}</Typography> </Stack> </Backdrop> </div> ); }
# Attribute Table Script # Created by: Jay Gaines # Created on: 03DEC2020 # THis script will deomstrate how Python can be used to manipulate attribute tables. # Import Arcpy site package and env class import arcpy from arcpy import env # Set environments env.workspace = r"C:/Users/Jay/Desktop/GIS4411/GIS4411/L2/GE2/Missouri.gdb" env.overwriteOutput = True # Create variables cnty = "counties" tor = "tornadoes" updateFields = ["Dens_1970", "Dens_1980", "Dens_1990", "Dens_2000", "POP70", "POP80", "POP90", "POP00", "AREA_KM"] torCopy = "tornadoes_copy" cntyTor = "counties_tornadoes" keepList = ["OBJECTID", "Shape", "Join_Count", "COUNTY", "REGION", "Shape_Length", "Shape_Area"] deleteList = [] # Create search cursor to print list of counties rows = sorted(arcpy.da.SearchCursor(cnty, ["COUNTY"]), reverse=True) print("The counties are: ") for row in rows: print(row[0]) # Create search cursor to calculate Missouri's population pop = 0 rows = arcpy.da.SearchCursor(cnty, ["POP00"]) for row in rows: pop += row [0] print("Missouri's total population in 2000 was: " + str(pop)) # Creat a new field and calculate the area in square kilometers arcpy.AddField_management(cnty, "AREA_KM", "DOUBLE") arcpy.CalculateField_management(cnty, "AREA_KM", "!Shape_Area!/1000000", "PYTHON") print("AREA_KM field created and calculated.") # Use a while loop to create three new fields counter = 1 while counter <4: arcpy.AddField_management(cnty, "Change_" + str(counter), "LONG") counter += 1 print("Change fields created.") # Calculate Change_1, CHange_2, CHange_3 fields arcpy.CalculateField_management(cnty, "Change_1", "!POP80! - !POP70!", "PYTHON") arcpy.CalculateField_management(cnty, "Change_2", "!POP90! - !POP80!", "PYTHON") arcpy.CalculateField_management(cnty, "Change_3", "!POP00! - !POP90!", "PYTHON") print("Change fields calculated.") # Calculate Population Density Per County-Use while loop to creat four new fields counter = 1970 while counter < 2001: arcpy.AddField_management(cnty, "Dens_" + str(counter), "DOUBLE") counter +=10 # Use an update cursor to calculate Density fields cursor = arcpy.da.UpdateCursor(cnty, updateFields) for row in cursor: row[0] = row[4] / row[8] row[1] = row[5] / row[8] row[2] = row[6] / row[8] row[3] = row[7] / row[8] cursor.updateRow(row) print("Density fields created and calculated.") # Copy tornado feature class arcpy.Copy_management(tor, torCopy, "FeatureClass") # Use an update cursor to remove F0 tornadoes cursor = arcpy.da.UpdateCursor(torCopy, ["F_SCALE"]) for row in cursor: if row[0] == 0: cursor.deleteRow() print("F0 tornadoes deleted.") # Join the counties and tornadoes_copyfeature class arcpy.SpatialJoin_analysis(cnty, torCopy, cntyTor, "JOIN_ONE_TO_ONE", "KEEP_ALL", "", "INTERSECT") print("Feature classes joined.") # Delete unecessary fields fieldsList = arcpy.ListFields(cntyTor) for field in fieldsList: if field.name not in keepList: deleteList.append(field.name) arcpy.DeleteField_management(cntyTor, deleteList) print("Fields deleted.") # Select large tornadoes and southeast counties arcpy.Select_analysis(torCopy, "large_tornadoes", "F_SCALE = 3 or F_SCALE = 4") arcpy.Select_analysis(cntyTor, "southeast_region", "REGION = 'Southeast'") print("Features selected.") print("The script has completed.")
const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); app.use(express.json()); require('dotenv').config(); const { Configuration, OpenAiApi } = require("openai"); const fs = require('fs'); const multer = require('multer'); const OpenAi = require('openai'); const openai = new OpenAi({ apiKey: process.env.OPENAI_API_KEY, }); const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'public'); }, filename: (req, file, cb) => { console.log('file'); cb(null, Date.now() + "-" + file.originalname); } }); const upload = multer({ storage: storage }).single('file'); let filePath; app.post('/images', async (req, res) => { try { const response = await openai.images.generate({ prompt: req.body.message, n: 1, size: "1024x1024", }); console.log(response); res.send(response.data); } catch (error) { console.error(error); res.status(500).send('Picture generation error'); } }); app.post('/upload', (req, res) => { upload(req, res, (err) => { if (err instanceof multer.MulterError) { return res.status(500).json(err); } else if (err) { return res.status(500).json(err); } console.log(req.file.path); filePath = req.file.path; res.status(200).json({ message: 'File uploaded successfully' }); }); }); app.post('/variations', async (req, res) => { try { const image = await openai.images.createVariation({ image: fs.createReadStream(filePath), }); res.send(image.data); // Changed from `response.data` console.log(image.data); } catch (error) { console.error(error); } }); const PORT = 8000; app.listen(PORT, () => console.log('Your server is running on PORT ' + PORT));
import uuid from "react-uuid"; export interface Todo { id: string; title: string; content: string; isDone: boolean; } const ADD_TODO = "ADD_TODO" as const; const DELETE_TODO = "DELETE_TODO" as const; const DONE_TODO = "DONE_TODO" as const; const CANCEL_TODO = "CANCEL_TODO" as const; export const addTodo = (payload: Todo) => ({ type: ADD_TODO, payload, }); export const deleteTodo = (payload: string) => ({ type: DELETE_TODO, payload, }); export const doneTodo = (payload: string) => ({ type: DONE_TODO, payload, }); export const cancelTodo = (payload: string) => ({ type: CANCEL_TODO, payload, }); type TodoAction = | ReturnType<typeof addTodo> | ReturnType<typeof deleteTodo> | ReturnType<typeof doneTodo> | ReturnType<typeof cancelTodo>; //초기 상태값(state) const initialState = [ { id: uuid(), title: "리액트 공부하기", content: "열심히 공부하기", isDone: false, }, ]; //리듀서 : 함수 const todos = (state = initialState, action: TodoAction) => { switch (action.type) { case ADD_TODO: return [...state, action.payload]; case DELETE_TODO: return state.filter((item) => item.id !== action.payload); case DONE_TODO: return state.map((item) => item.id === action.payload ? { ...item, isDone: true } : item ); case CANCEL_TODO: return state.map((item) => item.id === action.payload ? { ...item, isDone: false } : item ); default: return state; } }; export default todos;
use crate::clusters::cluster::Cluster; use crate::connection::handler::ConnectionHandler; use sdk::commands::hello::Hello; use sdk::error::SystemError; use std::rc::Rc; use tracing::{info, warn}; pub(crate) async fn handle( handler: &mut ConnectionHandler, command: &Hello, cluster: Rc<Cluster>, ) -> Result<(), SystemError> { if !cluster.validate_secret(&command.secret) { warn!( "Invalid cluster secret: {} from node ID: {}.", command.secret, command.node_id ); handler .send_error_response(SystemError::InvalidClusterSecret) .await?; return Err(SystemError::InvalidClusterSecret); } info!( "Received a valid cluster secret from node ID: {}.", command.node_id ); handler.node_id = command.node_id; handler.send_empty_ok_response().await?; info!("Sent a hello response to node ID: {}.", command.node_id); cluster.election_manager.set_term(command.term).await; if let Some(leader_id) = command.leader_id { cluster.set_leader(command.term, leader_id).await; } if cluster.is_connected_to(command.node_id).await { info!( "The node: {}, ID: {} is already connected.", command.name, command.node_id ); return Ok(()); } info!( "Connecting to the disconnected node: {}, ID: {}...", command.name, command.node_id ); cluster.connect_to(command.node_id).await?; info!( "Connected to the previously disconnected node: {}, ID: {}.", command.name, command.node_id ); Ok(()) }
import {Loader2, Plus} from "lucide-react"; import {Avatar, AvatarFallback, AvatarImage} from "../ui/avatar"; import {Input} from "../ui/input"; import {Label} from "../ui/label"; import {PreviewComponent} from "searchpal"; import {Field, Form, Formik} from "formik"; import {convertStringToJSON} from "@/lib/utils"; import {useEffect, useState} from "react"; import {Button} from "@/components/ui/button"; import { ResponsiveDialogComponent, ResponsiveDialogComponentContent, ResponsiveDialogComponentDescription, ResponsiveDialogComponentFooter, ResponsiveDialogComponentHeader, ResponsiveDialogComponentTitle, } from "@/components/ui/ResponsiveDialog"; import {emoji} from "../../lib/emoji"; import {useContractFunctionContextHook} from "@/Context/ContractContext"; import {Skeleton} from "../ui/skeleton"; import {toast} from "sonner"; function debounce<F extends (...args: any[]) => any>(func: F, delay: number) { let debounceTimer: NodeJS.Timeout; return function (this: ThisParameterType<F>, ...args: Parameters<F>) { clearTimeout(debounceTimer); debounceTimer = setTimeout(() => func.apply(this, args), delay); }; } const AddMembers = ({ datastring, groupId, membersArray, }: { datastring: string; groupId: string; membersArray: any; }) => { const [data, setData] = useState(convertStringToJSON(datastring)); const [openAvatarModal, setOpenAvatarModal] = useState(false); const getRandomEmoji = () => emoji[Math.floor(Math.random() * emoji.length)]; const randomAvatar = getRandomEmoji(); const [results, setResults] = useState<string[]>([]); console.log(data, "from add members"); const {fetchAddress, fetchNameAndAvatar, gaslessTransaction} = useContractFunctionContextHook(); const [loading, setLoading] = useState(false); const [gaslessTransactionLoading, setGaslessTransactionLoading] = useState(false); const handleAddGroupMember = async (walletAddress: string) => { setGaslessTransactionLoading(true); if (!gaslessTransaction || !groupId) return; try { const res = await gaslessTransaction("addMember", [ groupId, walletAddress, ]); console.log(res, "res"); toast( "Member added successfully, please refresh the page to see the changes" ); } catch (err) { console.log(err, "err"); } finally { setGaslessTransactionLoading(false); } }; useEffect(() => { (async function () { if (fetchAddress && fetchNameAndAvatar && data) { setLoading(true); // Set loading to true when starting the fetch process try { const response = await fetchAddress(data.member!); console.log("Address response:", response); if (response) { console.log("Fetching name and avatar for response:", response); const res = await fetchNameAndAvatar(response); console.log("Name and Avatar response:", res); const arr = [response, res]; console.log("Final result array:", arr); setResults(arr); } else { console.warn("No response from fetchAddress"); setResults([]); } } catch (error) { console.error("Error fetching data:", error); setResults([]); } finally { setLoading(false); // Set loading to false when the fetch process is completed } } })(); }, [data, fetchAddress, fetchNameAndAvatar]); console.log(results, "results"); return ( <div className="w-full flex flex-col"> <p className="text-lg font-semibold text-center w-full">Member Details</p> {loading === true && <Skeleton className="w-full h-[200px]" />} {!loading && results && results[1] && results[1][1] === "" && results[1][0] === "" && <div>not found</div>} {!loading && results && results[1] && results[1][1] !== "" && results[1][0] !== "" && ( <Formik initialValues={{ name: data.member || "", wallet: results[0], avatarPath: results[1][1], }} onSubmit={(values, action) => { // console.log(values, "values"); handleAddGroupMember(values.wallet); }} > {(formik) => ( <Form className="w-full"> <div className="w-full pt-6 flex items-center flex-col gap-6"> <Avatar className="w-32 h-32 relative overflow-visible" onClick={() => setOpenAvatarModal((prev) => !prev)} > <AvatarImage src={formik.values.avatarPath} /> <AvatarFallback>CN</AvatarFallback> </Avatar> <div className="flex flex-col w-full gap-2"> <div className="flex items-center"> <Label htmlFor="name" className="w-32"> Name </Label> <Field as={Input} name="name" id="name" type="text" placeholder="Name" className="w-full focus-visible:ring-0" /> </div> <div className="flex items-center"> <Label htmlFor="wallet" className="w-32"> Wallet Address </Label> <Field as={Input} name="wallet" id="wallet" type="text" placeholder="Wallet Address (0x..)" className="w-full focus-visible:ring-0" /> </div> </div> </div> {gaslessTransactionLoading ? ( <Button disabled> <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Please wait </Button> ) : ( <Button type="submit" className="bg-[#81B29A] hover:bg-[#81B29A] w-full mt-6" disabled={ membersArray && membersArray.find( (item: any) => item.address === results[0] ) } > {membersArray && membersArray.find( (item: any) => item.address === results[0] ) ? "Already a Member" : "Add Member"} </Button> )} </Form> )} </Formik> )} </div> ); }; export default AddMembers;
using GameboyEmu.Logic.Cpu.Extensions; namespace GameboyEmu.Logic.Cpu.Instructions; public static class LoadInstructions { public static List<Instruction> Instructions = new() { new LoadFromRegisterToRegister(0x40, "LD B,B", 4, RegisterType.B, RegisterType.B), new LoadFromRegisterToRegister(0x41, "LD B,C", 4, RegisterType.B, RegisterType.C), new LoadFromRegisterToRegister(0x42, "LD B,D", 4, RegisterType.B, RegisterType.D), new LoadFromRegisterToRegister(0x43, "LD B,E", 4, RegisterType.B, RegisterType.E), new LoadFromRegisterToRegister(0x44, "LD B,H", 4, RegisterType.B, RegisterType.H), new LoadFromRegisterToRegister(0x45, "LD B,L", 4, RegisterType.B, RegisterType.L), new LoadFromRegisterToRegister(0x47, "LD B,A", 4, RegisterType.B, RegisterType.A), new LoadFromRegisterToRegister(0x48, "LD C,B", 4, RegisterType.C, RegisterType.B), new LoadFromRegisterToRegister(0x49, "LD C,C", 4, RegisterType.C, RegisterType.C), new LoadFromRegisterToRegister(0x4A, "LD C,D", 4, RegisterType.C, RegisterType.D), new LoadFromRegisterToRegister(0x4B, "LD C,E", 4, RegisterType.C, RegisterType.E), new LoadFromRegisterToRegister(0x4C, "LD C,H", 4, RegisterType.C, RegisterType.H), new LoadFromRegisterToRegister(0x4D, "LD C,L", 4, RegisterType.C, RegisterType.L), new LoadFromRegisterToRegister(0x4F, "LD C,A", 4, RegisterType.C, RegisterType.A), new LoadFromRegisterToRegister(0x50, "LD D,B", 4, RegisterType.D, RegisterType.B), new LoadFromRegisterToRegister(0x51, "LD D,C", 4, RegisterType.D, RegisterType.C), new LoadFromRegisterToRegister(0x52, "LD D,D", 4, RegisterType.D, RegisterType.D), new LoadFromRegisterToRegister(0x53, "LD D,E", 4, RegisterType.D, RegisterType.E), new LoadFromRegisterToRegister(0x54, "LD D,H", 4, RegisterType.D, RegisterType.H), new LoadFromRegisterToRegister(0x55, "LD D,L", 4, RegisterType.D, RegisterType.L), new LoadFromRegisterToRegister(0x57, "LD D,A", 4, RegisterType.D, RegisterType.A), new LoadFromRegisterToRegister(0x58, "LD E,B", 4, RegisterType.E, RegisterType.B), new LoadFromRegisterToRegister(0x59, "LD E,C", 4, RegisterType.E, RegisterType.C), new LoadFromRegisterToRegister(0x5A, "LD E,D", 4, RegisterType.E, RegisterType.D), new LoadFromRegisterToRegister(0x5B, "LD E,E", 4, RegisterType.E, RegisterType.E), new LoadFromRegisterToRegister(0x5C, "LD E,H", 4, RegisterType.E, RegisterType.H), new LoadFromRegisterToRegister(0x5D, "LD E,L", 4, RegisterType.E, RegisterType.L), new LoadFromRegisterToRegister(0x5F, "LD E,A", 4, RegisterType.E, RegisterType.A), new LoadFromRegisterToRegister(0x60, "LD H,B", 4, RegisterType.H, RegisterType.B), new LoadFromRegisterToRegister(0x61, "LD H,C", 4, RegisterType.H, RegisterType.C), new LoadFromRegisterToRegister(0x62, "LD H,D", 4, RegisterType.H, RegisterType.D), new LoadFromRegisterToRegister(0x63, "LD H,E", 4, RegisterType.H, RegisterType.E), new LoadFromRegisterToRegister(0x64, "LD H,H", 4, RegisterType.H, RegisterType.H), new LoadFromRegisterToRegister(0x65, "LD H,L", 4, RegisterType.H, RegisterType.L), new LoadFromRegisterToRegister(0x67, "LD H,A", 4, RegisterType.H, RegisterType.A), new LoadFromRegisterToRegister(0x68, "LD L,B", 4, RegisterType.L, RegisterType.B), new LoadFromRegisterToRegister(0x69, "LD L,C", 4, RegisterType.L, RegisterType.C), new LoadFromRegisterToRegister(0x6A, "LD L,D", 4, RegisterType.L, RegisterType.D), new LoadFromRegisterToRegister(0x6B, "LD L,E", 4, RegisterType.L, RegisterType.E), new LoadFromRegisterToRegister(0x6C, "LD L,H", 4, RegisterType.L, RegisterType.H), new LoadFromRegisterToRegister(0x6D, "LD L,L", 4, RegisterType.L, RegisterType.L), new LoadFromRegisterToRegister(0x6F, "LD L,A", 4, RegisterType.L, RegisterType.A), new LoadFromRegisterToRegister(0x78, "LD A,B", 4, RegisterType.A, RegisterType.B), new LoadFromRegisterToRegister(0x79, "LD A,C", 4, RegisterType.A, RegisterType.C), new LoadFromRegisterToRegister(0x7A, "LD A,D", 4, RegisterType.A, RegisterType.D), new LoadFromRegisterToRegister(0x7B, "LD A,E", 4, RegisterType.A, RegisterType.E), new LoadFromRegisterToRegister(0x7C, "LD A,H", 4, RegisterType.A, RegisterType.H), new LoadFromRegisterToRegister(0x7D, "LD A,L", 4, RegisterType.A, RegisterType.L), new LoadFromRegisterToRegister(0x7F, "LD A,A", 4, RegisterType.A, RegisterType.A), new LoadDirectToRegisterInstruction(0x06, "LD B,d8", 8, InstructionSize.D8, RegisterType.B), new LoadDirectToRegisterInstruction(0x0E, "LD C,d8", 8, InstructionSize.D8, RegisterType.C), new LoadDirectToRegisterInstruction(0x16, "LD D,d8", 8, InstructionSize.D8, RegisterType.D), new LoadDirectToRegisterInstruction(0x1E, "LD E,d8", 8, InstructionSize.D8, RegisterType.E), new LoadDirectToRegisterInstruction(0x26, "LD H,d8", 8, InstructionSize.D8, RegisterType.H), new LoadDirectToRegisterInstruction(0x2E, "LD L,d8", 8, InstructionSize.D8, RegisterType.L), new LoadDirectToRegisterInstruction(0x3E, "LD A,d8", 8, InstructionSize.D8, RegisterType.A), new LoadDirectToRegisterInstruction(0x01, "LD BC,d16", 12, InstructionSize.D16, RegisterType.BC), new LoadDirectToRegisterInstruction(0x11, "LD DE,d16", 12, InstructionSize.D16, RegisterType.DE), new LoadDirectToRegisterInstruction(0x21, "LD HL,d16", 12, InstructionSize.D16, RegisterType.HL), new LoadDirectToRegisterInstruction(0x31, "LD SP,d16", 12, InstructionSize.D16, RegisterType.SP), new GenericInstruction( 0x08, "LD (a16),SP", 20, InstructionSize.D16, action: (instruction, cpu, data) => { var sp = cpu.SP; var (high, low) = sp.GetValue().ToBytes(); cpu.WriteByte(data.ToUshort(), low); cpu.WriteByte((ushort)(data.ToUshort() + 1), high); } ), new LoadAddressToRegister(0x46, "LD B,(HL)", 8, InstructionSize.None, RegisterType.B, RegisterType.HL), new LoadAddressToRegister(0x4E, "LD C,(HL)", 8, InstructionSize.None, RegisterType.C, RegisterType.HL), new LoadAddressToRegister(0x56, "LD D,(HL)", 8, InstructionSize.None, RegisterType.D, RegisterType.HL), new LoadAddressToRegister(0x5E, "LD E,(HL)", 8, InstructionSize.None, RegisterType.E, RegisterType.HL), new LoadAddressToRegister(0x66, "LD H,(HL)", 8, InstructionSize.None, RegisterType.H, RegisterType.HL), new LoadAddressToRegister(0x6E, "LD L,(HL)", 8, InstructionSize.None, RegisterType.L, RegisterType.HL), new LoadAddressToRegister(0x7E, "LD A,(HL)", 8, InstructionSize.None, RegisterType.A, RegisterType.HL), new LoadRegisterIntoAddress(0x02, "LD (BC),A", 8, InstructionSize.None, RegisterType.BC, RegisterType.A), new LoadRegisterIntoAddress(0x12, "LD (DE),A", 8, InstructionSize.None, RegisterType.DE, RegisterType.A), new LoadRegisterIntoAddress(0x70, "LD (HL),B", 8, InstructionSize.None, RegisterType.HL, RegisterType.B), new LoadRegisterIntoAddress(0x71, "LD (HL),C", 8, InstructionSize.None, RegisterType.HL, RegisterType.C), new LoadRegisterIntoAddress(0x72, "LD (HL),D", 8, InstructionSize.None, RegisterType.HL, RegisterType.D), new LoadRegisterIntoAddress(0x73, "LD (HL),E", 8, InstructionSize.None, RegisterType.HL, RegisterType.E), new LoadRegisterIntoAddress(0x74, "LD (HL),H", 8, InstructionSize.None, RegisterType.HL, RegisterType.H), new LoadRegisterIntoAddress(0x75, "LD (HL),L", 8, InstructionSize.None, RegisterType.HL, RegisterType.L), new LoadRegisterIntoAddress(0x77, "LD (HL),A", 8, InstructionSize.None, RegisterType.HL, RegisterType.A), new GenericInstruction( 0x32, "LD (HL-),A", 8, action: (instr, cpu, data) => { var hl = cpu.ReadUshortRegister(RegisterType.HL); cpu.WriteByte(hl, cpu.A); hl--; cpu.WriteUshortRegister(RegisterType.HL, hl); } ), new GenericInstruction( 0x22, "LD (HL+),A", 8, action: (instr, cpu, data) => { var hl = cpu.ReadUshortRegister(RegisterType.HL); cpu.WriteByte(hl, cpu.A); hl++; cpu.WriteUshortRegister(RegisterType.HL, hl); } ), new GenericInstruction( 0x2A, "LD A,(HL+)", 8, action: (instr, cpu, data) => { var hl = cpu.ReadUshortRegister(RegisterType.HL); var value = cpu.ReadByte(hl); cpu.WriteByteRegister(RegisterType.A, value); hl++; cpu.WriteUshortRegister(RegisterType.HL, hl); } ), new GenericInstruction( 0x3A, "LD A,(HL-)", 8, action: (instr, cpu, data) => { var hl = cpu.ReadUshortRegister(RegisterType.HL); var value = cpu.ReadByte(hl); cpu.WriteByteRegister(RegisterType.A, value); hl--; cpu.WriteUshortRegister(RegisterType.HL, hl); } ), new GenericInstruction( 0x36, "LD (HL),d8", 12, action: (instruction, cpu, data) => { var hl = cpu.ReadUshortRegister(RegisterType.HL); cpu.WriteByte(hl, data.ToByte()); } ) }; } public class LoadFromRegisterToRegister : Instruction { public LoadFromRegisterToRegister( byte opcode, string mnemonic, int cycles, RegisterType register1 = RegisterType.None, RegisterType register2 = RegisterType.None) : base(opcode, mnemonic, cycles, InstructionSize.None, register1, register2) { } public override void Execute(GameboyEmu.Cpu.Cpu cpu, FetchedData data) { var regVal = cpu.ReadByteRegister(Register2); cpu.WriteByteRegister(Register1, regVal); } }
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: io_indexmap = defaultdict(int) for idx, value in enumerate(inorder): io_indexmap[value] = idx self.post_idx = len(postorder)-1 def recursive(left, right): if left > right: return None curr_parent = postorder[self.post_idx] self.post_idx -= 1 root = TreeNode(curr_parent) root.right = recursive(io_indexmap[curr_parent] + 1, right) root.left = recursive(left, io_indexmap[curr_parent]-1) return root return recursive(0, len(inorder)-1)
import { Injectable } from '@angular/core'; import { environment } from '../../../environments/environment'; import { Observable } from 'rxjs'; import { scan } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class HistoryService { /** * Organizes the values emitted from the `dataSource$` observables the into arrays * of the size `historySize`. The emitted arrays contain the no more than `historySize` * last values of the dataSource$ organized by LIFO principle (old values in the end of * the array, new values are at the beginning of the array) * dataSource$: ---1-----2-------3----------| * function: ---[1]---[2,1]---[3,2,1]----| * @example see marble tests in history.service.spec.ts */ getReverseChronologicalHistory<T>(dataSource$: Observable<T>, historySize = environment.historySize): Observable<T[]> { return dataSource$.pipe( scan((acc: T[], curr: T) => { const res = [curr].concat(acc); if (res.length > historySize) { res.pop(); } return res; }, [] as T[]) ); } }
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.exceptions import ValidationError from django.db import transaction from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse from django.utils.decorators import method_decorator from django.views.generic import RedirectView from articleapp.models import Article from likeapp.models import Like @transaction.atomic def db_transaction(user, article): if Like.objects.filter(user=user, article=article).exists(): raise ValidationError('Like already exists') else: Like(user=user, article=article).save() article.num_like += 1 article.save() # Create your views here. @method_decorator(login_required, 'get') class LikeArticleView(RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse('articleapp:detail', kwargs={'pk': kwargs['pk']}) # kwargs['pk'] 대신 article.pk 로 써도 된다 def get(self, *args, **kwargs): user = self.request.user article = get_object_or_404(Article, pk=kwargs['pk']) try: db_transaction(user, article) messages.add_message(self.request, messages.SUCCESS, 'Liked') except ValidationError: messages.add_message(self.request, messages.ERROR, 'You cannot like a article more than once.') return HttpResponseRedirect(reverse('articleapp:detail', kwargs={'pk': kwargs['pk']})) return super(LikeArticleView, self).get(self.request, *args, **kwargs)
/* * Copyright (C) 2014 The Android Open Source Project * * 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 com.orlanth23.annoncesnc.provider; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.orlanth23.annoncesnc.provider.contract.AnnonceContract; import com.orlanth23.annoncesnc.provider.contract.InfosServerContract; import com.orlanth23.annoncesnc.provider.contract.MessageContract; import com.orlanth23.annoncesnc.provider.contract.PhotoContract; import com.orlanth23.annoncesnc.provider.contract.UtilisateurContract; public class AnnoncesDbHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "annonces.db"; private static final int DATABASE_VERSION = 19; public AnnoncesDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(UtilisateurContract.CREATE_TABLE); sqLiteDatabase.execSQL(AnnonceContract.CREATE_TABLE); sqLiteDatabase.execSQL(PhotoContract.CREATE_TABLE); sqLiteDatabase.execSQL(MessageContract.CREATE_TABLE); sqLiteDatabase.execSQL(InfosServerContract.CREATE_TABLE); sqLiteDatabase.execSQL(InfosServerContract.FIRST_INSERT_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + MessageContract.TABLE_NAME); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + PhotoContract.TABLE_NAME); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + AnnonceContract.TABLE_NAME); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + UtilisateurContract.TABLE_NAME); sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + InfosServerContract.TABLE_NAME); onCreate(sqLiteDatabase); } }
// SPDX-License-Identifier: MIT package dev.andrybak.util.function.kotlin /** * Implementation of functional programming abstraction `Either` for Kotlin. * * Objects of type `Either<A, B>` represent values with two possibilities: they contain either a value * of type `A` ([Left] alternative) or of type `B` ([Right] alternative). * This type is often used to represent a result of an operation that may result in an error, * for example, `Either<Exception, Result>`. * * The most basic and most important part of API of this class is instance method [match]. * It allows to structurally pattern match on the left and right alternatives and to access the values stored in * objects of type `Either`. * * Inspired by [Haskell's data type `Either`](https://hackage.haskell.org/package/base/docs/Data-Either.html). * * @param A type for [Left] * @param B type for [Right] */ sealed class Either<out A, out B> { /** * Pattern matches on this [Either] and returns result of applying the corresponding function. * * @param f function to apply to a value of [Left] * @param g function to apply to a value of [Right] * @param R return type of functions * @return result of applying one of the functions to this [Either] */ inline fun <R> match(f: (A) -> R, g: (B) -> R): R { return when (this) { is Left -> f(leftValue) is Right -> g(rightValue) } } /** * If this [Either] is [Left], performs the first given action with its value. * If this [Either] is [Right], performs the second given action with its value. * * @param f consumer to apply to a value of [Left] * @param g consumer to apply to a value of [Right] */ inline fun accept(f: (A) -> Unit, g: (B) -> Unit) { when (this) { is Left -> f(leftValue) is Right -> g(rightValue) } } /** * If this [Either] is [Left], performs the first given action with its value and returns this [Either]. * If this [Either] is [Right], performs the second given action with its value and returns this [Either]. * * @param f consumer to apply to a value of [Left] * @param g consumer to apply to a value of [Right] */ inline fun peek(f: (A) -> Unit, g: (B) -> Unit): Either<A, B> { when (this) { is Left -> f(leftValue) is Right -> g(rightValue) } return this } /** * Left alternative of the [Either&lt;A, B&gt;][Either] type, containing a value of type `A`. * * @param A type of the value in this [Left] * @param B type of the value in the corresponding [Right] * @param leftValue the `A` value stored in this [Left] */ data class Left<A, B>(val leftValue: A) : Either<A, B>() /** * Right alternative of the [Either&lt;A, B&gt;][Either] type, containing a value of type `B`. * * @param A type of the value in the corresponding [Left] * @param B type of the value in this [Right] * @param rightValue the `B` value stored in this [Right] */ data class Right<A, B>(val rightValue: B) : Either<A, B>() companion object { /** * Returns a [Left] containing given value of type `A`. * * @param A type for returned [Left] * @param B type for corresponding [Right] * @param a value to be stored in the returned [Left] */ @JvmStatic fun <A, B> left(a: A): Either<A, B> = Left(a) /** * Returns a [Right] containing given value of type `B`. * * @param A type for corresponding [Left] * @param B type for returned [Right] * @param b value to be stored in the returned [Right] */ @JvmStatic fun <A, B> right(b: B): Either<A, B> = Right(b) } } /** * If given [Either] is [Left][Either.Left], returns result of applying the first given function to its value, * if it is [Right][Either.Right], returns result of applying the second given function to its value. * * @param f function to apply to [Either.Left] * @param g function to apply to [Either.Right] * @param A type for [Either.Left] * @param B type for [Either.Right] * @param C return type of functions * @return result of applying one of the given functions to given [Either] value. */ inline fun <A, B, C> either(f: (A) -> C, g: (B) -> C, e: Either<A, B>): C { return when (e) { is Either.Left -> f(e.leftValue) is Either.Right -> g(e.rightValue) } } /** * Converts two functions, one which takes `A` and returns `C` and another which takes `B` and * returns `C`, into a function that takes an [`Either<A, B>`][Either] and returns `C`. * * Second implementation of the function [either] to allow partial application. * * Implementation of [Haskell function `either`](https://hackage.haskell.org/package/base/docs/Data-Either.html#v:either) * in Kotlin. * * @param f function to apply to [Either.Left] * @param g function to apply to [Either.Right] * @param A type for [Either.Left] * @param B type for [Either.Right] * @param C return type of functions * @return function which takes an [Either] and returns result of applying the function corresponding to its type. */ inline fun <A, B, C> either(crossinline f: (A) -> C, crossinline g: (B) -> C): (Either<A, B>) -> C { return { e -> when (e) { is Either.Left -> f(e.leftValue) is Either.Right -> g(e.rightValue) } } }
package com.steven.saar.common.plugin.entity; /** * 项目名称:com.steven.saar.common.plugin.entity * 类名称:Stateable * 描述: * 创建人:steven * 创建时间:2018-05-20 00:32 */ public interface Stateable<T extends Enum<? extends Stateable.Status>> { public void setStatus(T status); public T getStatus(); /** * 标识接口,所有状态实现,需要实现该状态接口 */ public static interface Status { } /** * 审核状态 */ public static enum AuditStatus implements Status { waiting("等待审核"), fail("审核失败"), success("审核成功"); private final String info; private AuditStatus(String info) { this.info = info; } public String getInfo() { return info; } } /** * 是否显示 */ public static enum ShowStatus implements Status { hide("不显示"), show("显示"); private final String info; private ShowStatus(String info) { this.info = info; } public String getInfo() { return info; } } }
import './App.scss' import { FC, useState } from 'react' import { Todolist } from './components/todoList/TodoList' import { TaskType, TasksType, TodolistType, FilterType } from './store/store' import { v1 } from 'uuid' import { FormControl } from './components/formControl/FormControl' type AppPropsType = { initTodolists: TodolistType[] initTasks: TasksType } export const App: FC<AppPropsType> = (props) => { // Props const { initTodolists, initTasks } = props // Global State const [todolists, setTodolists] = useState<TodolistType[]>(initTodolists) const [tasks, setTasks] = useState<TasksType>(initTasks) // Create Task const createTask = (title: string, todoListId: string) => { const newTask: TaskType = { id: v1(), title: title.toLowerCase(), isDone: false, } const updatedTasks: TaskType[] = [newTask, ...tasks[todoListId]] setTasks({ ...tasks, [todoListId]: updatedTasks }) } // Create Todolist const createTodolist = (title: string) => { const newTodolist: TodolistType = { id: v1(), title: title.toLowerCase(), filter: 'all', } setTodolists([newTodolist, ...todolists]) setTasks({ ...tasks, [newTodolist.id]: [] }) } // Update Task const updateTask = (taskId: string, todolistId: string, newTitle: string) => { const updatedTask: TaskType[] = tasks[todolistId].map((t: TaskType) => t.id === taskId ? { ...t, title: newTitle } : t ) setTasks({ ...tasks, [todolistId]: updatedTask }) } // Change Tasks Filter const changeTaskFilter = (value: FilterType, todoListId: string) => { const updatedTaskFilter: TodolistType[] = todolists.map( (tl: TodolistType) => tl.id === todoListId ? { ...tl, filter: value } : tl ) setTodolists(updatedTaskFilter) } // Change Task Status const changeTaskStatus = (taskId: string, todolistId: string) => { const updatedTaskStatus: TaskType[] = tasks[todolistId].map((t: TaskType) => t.id === taskId ? { ...t, isDone: !t.isDone } : t ) setTasks({ ...tasks, [todolistId]: updatedTaskStatus }) } // Delete Task const deleteTask = (id: string, todolistId: string) => { const updatedTask: TaskType[] = tasks[todolistId].filter( (t: TaskType) => t.id !== id ) setTasks({ ...tasks, [todolistId]: updatedTask }) } // Delete Todolist const deleteTodolist = (todolistId: string) => { const filteredTodolist: TodolistType[] = todolists.filter( (tl) => tl.id !== todolistId ) setTodolists(filteredTodolist) delete tasks[todolistId] setTasks(tasks) } return ( <div className="app"> <FormControl label="New todolist" action={createTodolist} /> <div className="wrapper"> {todolists.map((tl) => { // Filtered Tasks let filteredTasks = tasks[tl.id] if (tl.filter === 'active') filteredTasks = filteredTasks.filter((t) => t.isDone === false) if (tl.filter === 'completed') filteredTasks = filteredTasks.filter((t) => t.isDone === true) return ( <Todolist key={tl.id} id={tl.id} title={tl.title} filter={tl.filter} tasks={filteredTasks} changeTaskFilter={changeTaskFilter} createTask={createTask} changeTaskStatus={changeTaskStatus} deleteTask={deleteTask} deleteTodolist={deleteTodolist} updateTask={updateTask} /> ) })} </div> </div> ) }
import React, { createContext, useContext, useState } from 'react'; import Peticiones from '../Library/Peticiones'; const AuthContext = createContext(); export function AuthProvider({ children }){ const [user, setUser] = useState(null); const [access, setAccess]= useState(false); const login = async (username, password) => { try { const response = await Peticiones.login(username, password); if (response && response.usuario) { setUser(response.usuario); setAccess(true); } else { setAccess(false); setUser(null); } } catch (error) { console.error('Error al iniciar sesión:', error); setAccess(false); setUser(null); } }; /*const login = async(username, password)=>{ const loguear = Peticiones.login(username, password) (loguear.usuario)?setUser(loguear.usuario) : setUser(null) (loguear.usuario)?setAccess(true) : setAccess(false) }*/ const logout = () => { setAccess(false) setUser(null) }; return ( <AuthContext.Provider value={{access, user, login, logout }}> {children} </AuthContext.Provider> ); }; export function useAuth() { return useContext(AuthContext); } /*const login = (username, password)=>{ if (username === 'admin' && password === 'adminpassword') { setUser({ username: 'admin', role: 'admin'}); setAccess(true) }else if (username === 'operador' && password === 'operadorpassword') { // Usuario operador setUser({ username: 'operador', role: 'operador'}); setAccess(true) }else if (username === 'superAdmin' && password === 'superAdminpassword') { // Usuario operador setUser({ username: 'superAdmin', role: 'superAdmin'}); setAccess(true) } else { // Autenticación fallida setAccess(false) setUser(null); } }*/
Python Dictionary pop() usuli Misol Lug'atdan "model" ni olib tashlang: car = { "brand": "Ford", "model": "Mustang", "year": 1964 } car.pop("model") print(car) Ta'rifi va qo'llanilishi Usul pop()belgilangan elementni lug'atdan olib tashlaydi. O'chirilgan elementning qiymati usulning qaytish qiymatidir pop() , quyidagi misolga qarang. Sintaksis dictionary.pop(keyname, defaultvalue) Parametr qiymatlari Parameter Description keyname Required. The keyname of the item you want to remove defaultvalue Optional. A value to return if the specified key do not exist. If this parameter is not specified, and the no item with the specified key is found, an error is raised Ko'proq misollar Misol O'chirilgan elementning qiymati pop() usulining qaytish qiymatidir: car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.pop("model") print(x)
import React, { useState } from "react"; import { Image, Pressable, StyleSheet, Text, View, TouchableOpacity } from "react-native"; function App() { const [coloredCircles, setColoredCircles] = useState([]); const [coloredCircles1, setColoredCircles1] = useState([]); const addcircle = () => { setColoredCircles([...coloredCircles, false]); }; const click = (index) => { const coloredCircles1 = [...coloredCircles]; coloredCircles1[index] = !coloredCircles[index]; setColoredCircles(coloredCircles1); colouredchangedball(); }; const colouredchangedball = () => { const ball = coloredCircles.filter((item) => item === true); console.log("ball", ball); return ball.length; }; return ( <View style={styles.app}> <View style={styles.header}> <Text style={styles.title}>total:{coloredCircles.length}</Text> <Text style={styles.title}>total:{colouredchangedball()}</Text> </View> <Pressable onPress={() => { addcircle(); }} style={buttonStyles.button} > <Text style={buttonStyles.text}>add button</Text> {coloredCircles.map((item, index) => ( <View key={index}> <Text>{JSON.stringify(item)}</Text> <TouchableOpacity key={index} style={[ styles.circle, { backgroundColor: item ? "blue" : "gray" } ]} onPress={() => click(index)} > <Text style={styles.text}>{JSON.stringify(item)}</Text> </TouchableOpacity> </View> ))} </Pressable> </View> ); } const styles = StyleSheet.create({ app: { marginHorizontal: "auto", maxWidth: 500 }, logo: { height: 80 }, header: { padding: 20 }, title: { fontWeight: "bold", fontSize: "1.5rem", marginVertical: "1em", textAlign: "center" }, text: { lineHeight: "1.5em", fontSize: "1.125rem", marginVertical: "1em", textAlign: "center" }, link: { color: "#1B95E0" }, code: { fontFamily: "monospace, monospace" } }); const buttonStyles = StyleSheet.create({ button: { backgroundColor: "#2196F3", borderRadius: 2 }, text: { color: "#fff", fontWeight: "500", padding: 8, textAlign: "center", textTransform: "uppercase" } }); export default App;
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { Routes, RouterModule } from '@angular/router'; import { HttpClientModule } from "@angular/common/http"; import {MenubarModule} from "primeng/menubar"; import {InputTextModule} from "primeng/inputtext"; import {ButtonModule} from "primeng/button"; import {MenuModule} from "primeng/menu"; import {CardModule} from "primeng/card"; import { AppComponent } from './app.component'; import { TopBarComponent } from './top-bar/top-bar.component'; import { FooterComponent } from './footer/footer.component'; import { SideMenuComponent } from './side-menu/side-menu.component'; import { HomeComponent } from './home/home.component'; import { JournalsComponent } from './journals/journals.component'; import { ClassesComponent } from './classes/classes.component'; import { NotFoundComponent } from './not-found/not-found.component'; import { ScheduleComponent } from './schedule/schedule.component'; import { AccountComponent } from './account/account.component'; import {TableModule} from "primeng/table"; import { ClassComponent } from './class/class.component'; import { StudentComponent } from './student/student.component'; const appRoutes: Routes =[ { path: '', component: HomeComponent}, { path: 'journals', component: JournalsComponent}, { path: 'schedule', component: ScheduleComponent}, { path: 'account', component: AccountComponent }, { path: 'classes', component: ClassesComponent }, { path: 'class/:id', component: ClassComponent }, { path: '**', component: NotFoundComponent } ]; @NgModule({ declarations: [ AppComponent, TopBarComponent, FooterComponent, SideMenuComponent, HomeComponent, JournalsComponent, ClassesComponent, NotFoundComponent, ScheduleComponent, AccountComponent, ClassComponent, StudentComponent ], imports: [ BrowserModule, BrowserAnimationsModule, RouterModule.forRoot(appRoutes), HttpClientModule, MenuModule, MenubarModule, InputTextModule, ButtonModule, CardModule, TableModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
#!/usr/bin/env python3 """Module for task 0 """ import asyncio import random from typing import Generator async def async_generator() -> Generator[float, None, None]: """Coroutine that generates random numbers between 0 and 10, one number at a time. Yields: Generator[float, None, None]: A random number between 2 and 10. """ for _ in range(10): await asyncio.sleep(1) yield random.random() * 10
package com.java.udemy.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import com.java.udemy.config.Constants; import com.java.udemy.exception.BadRequestException; import com.java.udemy.models.CourseObjective; import com.java.udemy.request.CreateObjectivesRequest; import com.java.udemy.response.CreateObjectivesResponse; import com.java.udemy.response.GetCourseObjectivesResponse; import com.java.udemy.service.abstractions.IObjectivesService; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping(path = "/objectives", produces = MediaType.APPLICATION_JSON_VALUE) public class ObjectivesController { @Autowired private IObjectivesService objectivesService; @PostMapping(value = "/") @Secured(value = "ROLE_ADMIN") public CreateObjectivesResponse addNewObjectives(@RequestBody @Valid CreateObjectivesRequest request) { try { List<CourseObjective> coList = objectivesService.createObjectives(request); CreateObjectivesResponse response = new CreateObjectivesResponse(); response.setMessage(Constants.MESSAGE_ALL_SAVE); return response; } catch (Exception e) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, Constants.MESSAGE_CAN_NOT_SAVE_OBJECTIVE, e); } } @GetMapping(value = "/course/{courseId}") public GetCourseObjectivesResponse getCourseObjectives(@PathVariable Integer courseId) { try { List<CourseObjective> courseObjectivesList = objectivesService.getCourseObjectivesByCourseId(courseId); GetCourseObjectivesResponse response = new GetCourseObjectivesResponse(); response.setGetCourseObjectives(courseObjectivesList); return response; } catch (Exception ex) { throw new BadRequestException(ex.getMessage()); } } }
# Lab3_5 ## Get dataset of Power Consumption. Choose one zone and create forecasting model to predict future power Consumption. Use both statistics models and deep learning methods. ### [**Code**](/Lab3_5/lab3_5.ipynb) ### [**Data set**](https://www.kaggle.com/datasets/fedesoriano/electric-power-consumption/data) ### Procedure 1. The dataset was split into a training and testing set, with the first 80% of samples comprising the training set and the last 20% forming the testing set. 2. A time series plot was created. 3. The forecasting horizon was chosen based on the testing set. 4. Metrics including MAE, medAE, MSE, MSLE, and MAPE were collected for each model. 5. A naive forecast was made using the strategy - last. The results were not very good. 6. A model for naive forecasting was built using the strategy - mean for the last 30 observations. 7. A forecast was made using exponential smoothing. 8. The presence of a trend was explicitly specified in the exponential smoothing method. 9. The coefficient auto-tuning method was applied to the exponential smoothing model. 10. Autocorrelation and partial autocorrelation plots of the original time series were constructed - the series is non-stationary. 11. An ADF test was conducted to confirm that the series is non-stationary. 12. The series was differenced to check if it became stationary. The series is now stationary. An ADF test was conducted to confirm this. 13. Based on the autocorrelation and partial autocorrelation plots, as well as using auto ARIMA, coefficients for the ARIMA model were determined - 0, 1, 1. 14. A residual plot, a histogram of residual distribution, an autocorrelation plot of residuals, and a partial autocorrelation plot of residuals were created. 15. A SARIMA model with coefficients 0, 1, 1 and seasonal coefficients 0, 1, 1, 31 (indicating one month) was built. 16. A simple LSTM model was created to predict the next value. 17. A GRU model with the same architecture was created. 18. A model with two inputs - direct and inverted - for the GRU model was created. 19. A model with three inputs - direct, inverted for the GRU layers and one to attentions with LSTM layers was created. 20. The performance of each model was displayed, and the training graph was created.
1. Import a class/ value from another file - To import a class from another file: // item.py class Item(): pass // phone.py from item import Item class Phone(Item): pass 2. classmethod and staticmethod decorator - @classmethod: https://www.programiz.com/python-programming/methods/built-in/classmethod#google_vignette - @staticmethod: https://www.programiz.com/python-programming/methods/built-in/staticmethod 3. property decorator / query function - In cpp, we have query function that it cannot access and modify the class attribute directly. - In python, we can create a query function by using the "property" decorator: // item.py @property def name(self): return self.name 4. private attributes and methods - To set an attribute or method private, we use double underscore: - example: // item.py def __init__(self, name: str, price: float, quantity = 0):= self.__name = name // set name attribute private @property def name(self): return self.__name def __printName(self): // set printName() function private print("fasdfasdf") item1 = Item("MyItem", 750) item1.name = "Henry" // this line got an error print(item1.name) // MyItem 5. modifier function in class - We use "setter" decorator to modify a private class attribute. - syntax: @<attributeName>.setter - Example: // item.py @name.setter def name(self, value): if(len(value) > 10): raise Exception("Name is too long") else: self.__name = value 6. Priv
import { ChangeEvent, useState, useEffect } from "react"; import Layout from "../../components/Layout"; import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import { Logout, LoginDispatch } from "../../redux/reducers/dispatch"; import { useDispatch } from "react-redux"; import LoadScreen from "../../components/Loading"; import LoginForm from "../home/Login"; import { toast } from "react-toastify"; import Api from "../../api.config"; import { TaskEntry } from "./TaskItem"; import { FaTasks, FaBook } from "react-icons/fa"; import { IoMdSchool } from "react-icons/io"; import { useLocation, Link } from "react-router-dom"; import ViewDox from "./ViewDox"; function ViewTask() { const authority = useSelector( (state: RootState) => state.authority.authority ); const loggedIn = useSelector((state: RootState) => state.loggedIn.loggedIn); const [data, setData] = useState<TaskEntry | null>(null); const [lecturer, setLecturer] = useState(false); const [student, setStudent] = useState(false); const [error, setError] = useState(false); const [found, setFound] = useState(true); const [loginDetails, setLoginDetails] = useState({ email: "", password: "", }); const [submitting, setSubmitting] = useState(false); const [submitted, setSubmitted] = useState(false); const [expiry, setExpiry] = useState(""); const dispatch = useDispatch(); const location = useLocation(); const currentDate = Date.parse(new Date().toString()); const queryParams = new URLSearchParams(location.search); const id = queryParams.get("id") || ""; function fillLoginForm(e: ChangeEvent<HTMLInputElement>) { const { name, value } = e.target; setLoginDetails({ ...loginDetails, [name]: value }); } function handleLogin() { if (!submitting) { setSubmitting(true); LoginDispatch(loginDetails, dispatch) .then((res) => { const { status, message } = res; if (status) { toast.success(message); } else { toast.error(message); } setSubmitting(false); }) .catch(() => { setSubmitting(false); }); setLoginDetails({ email: "", password: "" }); } } useEffect(() => { Api.get(`/task/view?id=${id}`) .then((res) => { const { data, lecturer, student } = res.data; setFound(true); setData(data); setExpiry(data.deadline); setLecturer(lecturer); setStudent(student); }) .catch((err) => { setError(true); if (err.response) { console.log(err.response); if (err.response.status === 401) { Logout(dispatch); } else if (err.response.status === 404) { setFound(false); } else { toast.error(err.response.data.message); } } }); }, [loggedIn, id]); useEffect(() => { if (authority === 0) { Api.get(`/submit/student?id=${id}`).then(() => { setSubmitted(true); }); } }, [student]); if (!loggedIn) { return ( <div className="w-full md:w-1/3 mx-auto flex items-center h-screen"> <LoginForm display={true} details={loginDetails} fill={fillLoginForm} id="login" submit={handleLogin} /> </div> ); } if (!data && !error) { return ( <Layout activeNav="assignments"> <LoadScreen /> </Layout> ); } if (!id || !found) { return ( <Layout activeNav="assignments"> <div> <p>Assignment not found</p> </div> </Layout> ); } return ( <Layout activeNav="assignments"> <div className="w-full md:w-3/4 p-3 rounded-lg bg-white mx-auto my-5"> <div className="mb-4 text-center"> <div className="flex gap-4 items-center justify-center "> <FaTasks className="text-xl" /> <h2 className="text-xl">{data?.name.toUpperCase()}</h2> </div> </div> <div className="w-full flex flex-col justify-between gap-3"> <div className="flex gap-4 items-center"> <FaBook className="text-xl" /> <p className="text-lg">{data?.course.name}</p> </div> <div className="flex gap-4 items-center"> <IoMdSchool className="text-xl" /> <p className="text-lg"> {data?.lecturer.lastName}, {data?.lecturer.firstName} </p> </div> <div className="text-center text-lg"> {currentDate > Date.parse(expiry) ? ( <p className="text-red-500">Closed</p> ) : ( <p className="text-green-500"> Open till {new Date(expiry).toString()} </p> )} </div> </div> </div> {data && <ViewDox title={data?.name} document={data?.document} />} {lecturer && ( <div className="w-full md:w-3/4 p-5 rounded-lg bg-white mx-auto my-5"> <div className="text-center"> <Link to="#" className="bg-pGreen rounded-md py-2 px-4 text-white hover:opacity-80" > View Submissions </Link> </div> </div> )} {student && ( <div className="w-full md:w-3/4 p-5 rounded-lg bg-white mx-auto my-5"> <div className="text-center"> <Link to={`/assignment/submit?id=${id}`} className="bg-pGreen rounded-md py-2 px-4 text-white hover:opacity-80" > {submitted ? "Resubmit" : "Submit"} </Link> </div> </div> )} </Layout> ); } export default ViewTask;
import { PayloadAction, createSlice } from "@reduxjs/toolkit"; import { ITemplate, ITemplateContent } from "./interfaces/templates"; import { AVAILABLE_TEMPLATES } from "@/lib/availableTemplates"; interface TemplateState { availableTemplate: ITemplate; activeTemplate: ITemplateContent; } const initialState: TemplateState = { availableTemplate: AVAILABLE_TEMPLATES, activeTemplate: AVAILABLE_TEMPLATES['prisma'], }; const templateSlice = createSlice({ name: 'template', initialState, reducers: { setTemplate: (state, action: PayloadAction<ITemplateContent>) => { state.activeTemplate = action.payload; }, }, }); export const { setTemplate } = templateSlice.actions; export const selectTemplate = (state: { template: TemplateState }) => state.template.activeTemplate; export default templateSlice.reducer;
import React, { useContext, useEffect, useRef } from "react"; import { AuthContext } from "../context/AuthContext"; import { ChatContext } from "../context/ChatContext"; const Message = ({ message }) => { const { currentUser } = useContext(AuthContext); const { data } = useContext(ChatContext); const messagesEndRef = useRef(null); const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }; useEffect(() => { scrollToBottom(); }, [message]); return ( <div className={`message ${message.senderId === currentUser.uid && "owner"}`} > <div className="messageInfo"> <img src={ message.senderId === currentUser.uid ? currentUser.photoURL : data.user.photoURL } alt="" /> <span>Just now</span> </div> <div className="messageContent" ref={messagesEndRef}> <p>{message.text}</p> {message && <img src={message.img} alt="" />} </div> </div> ); }; export default Message;
#pragma once #include <string> #include <map> /// Class used to save and load configs class MenuConfig { public: int GetInt(const char* key, int defaultVal); bool GetBool(const char* key, bool defaultVal); float GetFloat(const char* key, float defaultVal); std::string GetStr(const char*, const char* defaultVal); void SetInt(const char*, int val); void SetBool(const char*, bool val); void SetFloat(const char*, float val); void SetStr(const char*, const char* val); void LoadFromFile(); void SaveToFile(); /// Sets a prefix to all the keys provided in all the Get/Set calls. void SetPrefixKey(std::string prefixKey); std::string GetPrefixKey(); /// Gets singleton instance static MenuConfig* Get() { if (instance == nullptr) { instance = new MenuConfig(); instance->LoadFromFile(); } return instance; } bool configChanged; private: static MenuConfig* instance; std::string prefixKey; std::map<std::string, std::string> rawValues; };
import { Injectable } from '@angular/core'; import { environment } from '../../environments/environment'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root', }) export class UserService { [x: string]: any; url = environment.apiUrl; constructor(private httpClient: HttpClient) {} // Método para realizar o cadastro do usuário, retornando a URL + o método + data signup(data: any) { return this.httpClient.post(this.url + '/user/cadastrarUsuarios/', data, { headers: new HttpHeaders().set('Content-Type', 'application/json') }); } // Método esqueciSenha esqueciSenha(data: any) { return this.httpClient.post(this.url + '/user/esqueciSenha/', data, { headers: new HttpHeaders().set('Content-Type', 'application/json') }) } // Método login login(data: any) { return this.httpClient.post(this.url + '/user/login/', data, { headers: new HttpHeaders().set('Content-Type', 'application/json') }) } // Método para checar Token checkToken() { return this.httpClient.get(this.url + '/user/checarToken') } // Método para mudar a senha mudarSenha(data: any) { return this.httpClient.post(this.url + '/user/alterarSenha/', data, { headers: new HttpHeaders().set('Content-Type', 'application/json') }) } // Método para recuperar o usuário getUsuario() { return this.httpClient.get(this.url + '/user/get/') } // Método para atualizar o status e role do usuário updateUsuarioStatusERole(data: any) { return this.httpClient.patch(this.url + '/user/updateStatusERole/', data, { headers: new HttpHeaders().set('Content-Type', 'application/json') }) } }
import { CommandInteraction, Client, ApplicationCommandType, ApplicationCommandOptionType, EmbedBuilder } from 'discord.js' import { Multi } from 'univ-lorraine-api' import { Command } from '../../Command' import restos from './restos.json' export const CrousMenu: Command = { name: 'ru', description: "Les menus des Restos U'", options: [ { name: 'ru', required: true, description: "Le Resto U'", type: ApplicationCommandOptionType.String, choices: restos }, { name: 'time', required: false, description: 'Midi/Soir', type: ApplicationCommandOptionType.String, choices: [ { name: 'Midi', value: 'MIDI' }, { name: 'Soir', value: 'SOIR' } ] }, { name: 'date', required: false, description: 'Date', type: ApplicationCommandOptionType.String } ], type: ApplicationCommandType.ChatInput, run: async (client: Client, interaction: CommandInteraction) => { try { const ru = interaction.options.get('ru')?.value const date = new Date((interaction.options.get('date')?.value ?? Date.now()) as string|number) const time = (interaction.options.get('time')?.value ?? (new Date().getHours() <= 14 ? 'MIDI' : 'SOIR')) as string const resto = (await Multi.getCROUSmenu()).find(resto => resto.title === ru) if (!resto) throw new Error("Ce RU n'existe pas.") const dateFormatted = date.toISOString().split('T')[0] const menu = resto.menus.find(menu => menu.date === dateFormatted) if (!menu) throw new Error(`Pas de menu disponible pour le ${new Date(dateFormatted).toLocaleDateString('fr')}.`) const meal = menu.meal.find(meal => meal.name.toUpperCase() === time) if (!meal) throw new Error(`Pas de menu disponible pour le ${time.toLowerCase()}.`) await interaction.reply({ embeds: [new EmbedBuilder({ color: 0xe4010b, author: { name: 'mULti', icon_url: 'https://multi.univ-lorraine.fr/img/crous.png', url: 'https://multi.univ-lorraine.fr/crous' }, thumbnail: { url: resto.thumbnail_url }, title: `🍔 ${resto.title} | ${date.toLocaleDateString('fr')} le ${meal.name.toUpperCase()}`, description: resto.short_desc, fields: meal.foodcategory.map(fc => ({ name: fc.name, value: fc.dishes.map(d => d.name).join(' - ') })), footer: { text: 'Source: multi.univ-lorraine.fr' }, timestamp: new Date() })] }) } catch (e: any) { await interaction.reply({ ephemeral: true, content: '❌ ' + e.message ?? 'Erreur' }) } } }
@extends('layouts.scaffold') @section('title') Formulário @endsection @section('content') <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-body"> <h4 class="header-title">{{ (@$data)?'Editar':'Cadastrar' }} Projeto</h4> <form class="needs-validation" method='POST' action="{{ @$data ? route('projeto.update', $data->id) : route('projeto.store') }}" novalidate> @csrf @if (@$data) @method('PATCH') @endif <x-fields :title="'Título do Projeto'" :name="'titulo'" :description="'Nome do Projeto'" :type="'text'" :required="true" :data="@$data" /> <div class="row"> <x-fields :title="'Instituição executora'" :name="'instituicao_executora'" :description="'Nome da instituição executora'" :type="'text'" :class="'mb-3 col-md-6'" :data="@$data"/> <x-fields :title="'Responsável da Instituição Executora'" :name="'responsavel_ie'" :description="'Nome do Responsável da Instituição Executora'" :type="'text'" :class="'mb-3 col-md-6'" :data="@$data" /> </div> <div class="row"> <x-fields :title="'Instituição Concedente'" :name="'instituicao_concedente'" :description="'Nome da instituição concedente'" :type="'text'" :class="'mb-3 col-md-6'" :data="@$data"/> <x-fields :title="'Responsável da Instituição Concedente'" :name="'responsavel_ic'" :description="'Nome do Responsável da Instituição Concedente'" :type="'text'" :class="'mb-3 col-md-6'" :data="@$data"/> </div> <x-fields :title="'Objeto'" :name="'objeto'" :description="'Objeto do projeto'" :type="'text'" :data="@$data" /> <x-fields :title="'Meta'" :name="'meta'" :description="'Meta do projeto'" :type="'text'" :data="@$data" /> <div class="row"> <x-fields :title="'Gestor do projeto'" :name="'gestor'" :description="'Nome do gestor do projeto'" :type="'text'" :required="true" :class="'mb-3 col-md-6'" :data="@$data"/> <x-fields :title="'Líder do Projeto'" :name="'lider'" :description="'Nome do líder do projeto'" :type="'text'" :required="true" :class="'mb-3 col-md-6'" :data="@$data"/> </div> <div class="row"> <x-fields :title="'Valor do Projeto'" :name="'valor'" :description="'0,00'" :type="'text'" :required="true" :class="'mb-3 col-md-4'" :mask="'#.##0,00'" :data_reverse=true :data="@$data"/> <x-fields :title="'Data Início'" :name="'data_inicio'" :description="''" :type="'date'" :required="true" :class="'mb-3 col-md-4'" :data="@$data"/> <x-fields :title="'Data Término'" :name="'data_termino'" :description="''" :type="'date'" :required="true" :class="'mb-3 col-md-4'" :data="@$data"/> </div> <div style="display: flex; justify-content: space-between"> <a href="{{ url()->previous() }}" class="btn btn-danger">Voltar</a> <button class="btn btn-primary" type="submit">{{ (@$data)?'Editar':'Cadastrar' }}</button> </div> </form> </div> <!-- end card-body--> </div> <!-- end card--> </div> <!-- end col--> </div> @endsection
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } .diamond { width: 100px; height: 100px; background: rgb(255, 255, 0); position: relative; transform: rotate(45deg); transition: all 0.3s ease; position: absolute; bottom: 10%; left: 50%; transform: translateX(-50%) rotate(45deg); } /*Syazwan 22043300*/ .diamond:hover { background: rgb(0, 0, 255); transform: scale(1.5) rotate(45deg); } /*Syazwan 22043300*/ .parallelogram { margin-left: 50px; width: 200px; height: 100px; transform: skew(20deg); background: rgba(238, 130, 238, 1); transition: transform 2s ease; } /*Yoon Long 22021421*/ .rotate { transform: skew(20deg) rotate(360deg); } /*Yoon Long 22021421*/ .parallelogram:hover { transform: skew(20deg) rotate(360deg); } /*Yoon Long 22021421*/ .star { margin-left: 50px; width: 0; height: 0; border-left: 50px solid transparent; border-right: 50px solid transparent; border-bottom: 100px solid rgba(238, 130, 238, 1); transform: rotate(35deg); transition: transform 5s ease; } /*Tan Jin Wei 22035553*/ .star:hover { transform: rotate(360deg); } /*Tan Jin Wei 22035553*/ .octagon { margin-left: 350px; width: 100px; height: 100px; background: rgb(171, 105, 241); clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%); transition: transform 1s; } /*Tan Jin Wei 22035553*/ .octagon:hover { transform: scale(2); } /*Tan Jin Wei 22035553*/ /*Nur Azimah 22037444*/ .circle { margin-left: 350px; width: 100px; height: 100px; border-radius: 50%; background: rgb(171, 105, 241); transition: transform 1s; } .circle:hover { transform: scale(2); } /*Nur Azimah 22037444*/ /*Bridget Wong 22013272*/ .oval { width: 200px; height: 100px; background: rgb(197, 238, 245); border-radius: 50%; transition: transform 0.5s ease; } /*Bridget Wong 22013272*/ .oval:hover { transform: scale(1.1); } </style> <title>Shapes</title> </head> <body> <div class="diamond"></div> <div class="parallelogram"></div> <div class="star"></div> <div class="octagon"></div> <div class="circle"></div> <div class="oval"></div> </div> </body> </html>
# Nemesis STG Engine: How to use This engine constructs its nodes on-the-fly using just scripts and resources, and uses an object pool. A lot of behavior is handled by the engine itself, simplifying your work. > Note: Despite the amount of things that can simply be done without code, this engine does expect you to do some programming. However, some additional friendliness to non-programmers is underway. > Note: A common way to set up collisions is to have one collision layer for the world, another for players, and another for enemies. ## How to create a stage 1. Create a new scene with an STGController node; it is a Node2D. 1. Set the node's stageMovement variable to determine the direction the stage should be moving. 1. Add any objects and scene-related items as a child of this node. Special nodes can be found in the [objects](#objects) section. You may also be interested in the [player creation](#creating-a-player) and [entity creation](#creating-an-entity) section. 1. Save the scene as a file. 1. Optionally, you may create and save another scene with a ParallaxBackground and its layers to be spawned later with the scene. ## How to load a stage 1. Create a new function where your loading will be done. This can be either C# or GDScript. > Note: If you are using GDScript, you will have to load the STGController script from disk using `preload`. This way you can access static functions. 1. Load your new scene(s) from disk via `preload` (other methods work too, so long as it's acquired), but do not instantiate it. 1. Locate the node you want the scene to spawn on. Preferably you can just use `this`/`self`. 1. Call `STGController.LoadStage` with your stage scene and the node, and optionally what it should do (ClearStats is the default). This will return the new instance. > Note: If you have a parallax background scene, you can instantiate it and set the stage instance's `parallaxBgPath` to its path in the current scene tree. 1. The instance now also exists in `STGController.Instance` and can be unloaded with `STGController.UnloadStage` (and reloaded with `STGController.ReloadStage`, utilizing optional behavior; UseCheckpoint is the default). ## Creating an entity > Entities are simply objects in the game world that are normally removed when they move out of sight. This can be like a projectile or non-playable ship. 1. In a folder, create an EntityResource. 1. Scrolling down to the "SpawnResource" section, we can set its: - Name - Sprite sequence (if you want it to be not animated, you can just put one frame with your desired texture and nothing else. See [named animations](#named-sprite-animations) for event-based animations) - Whether or not the texture stays fixed (won't rotate with the entity) - Script override, in case we want the entity to use a different script (must be a Spawnable!) - Sounds - Collision shape (can be copied over from a dummy CollisionShape2D) - Collision layer and mask (same as above; you may have to right-click these variables in the inspector to do so) - SpawnResource that is spawned when this entity despawns (useful for spawning special FX) - SpawnResource that is spawned on an interval. This is usually where bullets are spawned from ships - Interval period; think of this like the fire rate 1. In the "EntityResource" section, we can set its: - Motion type ("Standard" means it will move in a straight line) - Path that it follows, if the motion type is set to "Path" - Option to loop the above path - Follow a given node that exists or will be created (SpawnResources spawn and set their name using the "Name" variable), if the motion type is set to "follow" - Speed - Turn speed (turns constantly in standard, will turn towards what it's supposed to be following if set to "follow") - Ability to move with its spawner - Time until it should move with the stage (0 to never do this) - Collision damage - Miscellaneous/world collision damage - HP (can be 0) - Score (only applies when destroyed by the player) - Identity as a boss (can be used to identify minibosses too) - Ends the stage on despawn/destruction - What should be spawned when it takes damage and HP reaches 0 1. If you want multiple of these to spawn or want them to appear in the stage, a spawner can be created. See [creating a spawner](#creating-a-spawner) for more info. ## Creating a player > Players are entities with player control attached to them. They cannot escape the screen and can use its interval on-command. 1. Follow the steps in [entity creation](#creating-an-entity), but instead of an EntityResource, create a PlayerResource. Withhold for now on spawner creation. 1. In the "PlayerResource" section, we can set its: - Device ID (not needed if keyboard-controlled) - Ability to be listened to via keyboard 1. When [creating a spawner](#creating-a-spawner), set the trigger to PlayerSpawnEvent and despawn condition to "None." It will automatically move with the scene, so it will stay in the same place on-screen. ## Creating a spawner > Spawners are what place entities in the world. They can spawn multiple objects, can be spawned by other objects, and can be triggered via different ways. 1. In a folder, create a SpawnerDataResource. 1. Though the "SpawnResource" section can be ignored, we can set its: - Name - Sprite sequence (not required; it might not play out as you expect, considering the spawner behaves and disables itself independently) - Whether or not the texture stays fixed (won't rotate with the entity) - Script override, in case we want the spawner to use a different script (must be a Spawnable!) - Sounds - Collision shape (can be copied over from a dummy CollisionShape2D) - Collision layer and mask (same as above; you may have to right-click these variables in the inspector to do so) - SpawnResource that is spawned when this item despawns (useful for spawning special FX or [pickups](#creating-a-pickup), if despawn condition is set to "RequireKill") - SpawnResource that is spawned on an interval. Not recommended to be used for this type of resource. - Interval period 1. In the "SpawnerDataResource" section, we can set its: - Trigger condition ("OnEvent" will listen to the _OnEvent function, which can be hooked up to any signal. "OnPlaced" is when the spawner is either spawned or is ready in a scene) - SpawnResource to spawn - Spawn points (multiple can be set in the same place) - Starting rotation of all objects - Rotation increment per spawn point - Ability to move with its spawner - Time to spawn all objects (0 is instant) - Despawn condition 1. If this will be placed in the world, create a Spawner node in your scene and set its spawn data to the resource you just created. ## Creating a pickup > Pickups are things that the player can collide with. They will only collide with the player. 1. In a folder, create a PickupResource. 1. Scrolling down to the "SpawnResource" section, we can set its: - Name - Sprite sequence (if you want it to be not animated, you can just put one frame with your desired texture and nothing else) - Whether or not the texture stays fixed (won't rotate with the entity) - Script override, in case we want the pickup to use a different script (must be a Spawnable!) - Sounds - Collision shape (can be copied over from a dummy CollisionShape2D) - Collision layer and mask (same as above; you may have to right-click these variables in the inspector to do so) - SpawnResource that is spawned when this item despawns - SpawnResource that is spawned on an interval - Interval period 1. In the "PickupResource" section, we can set its: - Type - Value ("ScoreBonus" gives score, "Health" gives HP, not used in "WeaponOption") - Weapon (Only used by "WeaponOption" type) 1. It's now free to be placed anywhere, like a spawner's despawn spawn ## Objects - Resources - EntityResource: Data for bullets and other entities. SpawnResource. - EntityPhasedResource: Entity data with phases. - EntityPhase: Data that specifically defines one phase. - PlayerResource: Entity data specifically for players. - PickupResource: Data for pickup objects. SpawnResource. - WeaponResource: Data provided to all PickupResources and EntityPhases that overrides the usual interval spawn. - SpawnerDataResource: Data used for spawners. SpawnResource. - SpecialFXResource: Data for special particle effects. SpawnResource. - SpawnableSounds: Sound data provided to all SpawnResources. - Nodes - StageTrigger: A node that sends out a signal when a condition is met, with various condition options and prebuilt behaviors. - Spawner: A node that spawns other nodes that inherit from Spawnable. They utilize SpawnerDataResource for their `spawnData`, and will instantiate a new Spawnable node from the data's `spawn` variable on every spawn point defined in `spawnPoints`. Spawnable. - SpecialFXNode: A particle effect node that uses SpecialFXResource data from `fxResource`. Triggers on spawned. Spawnable. - Entity: An entity that moves around in the world, based on an EntityResource (or extending resource) provided to `entityData`. Spawners are a better approach as entities will even perform their behavior off-screen. Despawned when seen once and exits the player's view. Spawnable. - PlayerEntity: Same as above, but requires a PlayerResource instead of an EntityResource. Stays within screen bounds. - Pickup: A pickup item that the player can collect. Despawned when seen once and exits the player's view. Spawnable. ## Named sprite animations > There are predefined names for animations that will trigger based on certain events. Naming your sequence this will cause it to be played based on its event. - "spawn": Plays on spawn, and the collision will wait until it is complete before being enabled. - "idle"/"default": Plays on idle. - "destroy": Plays when the entity's health reaches zero from damage. Will not despawn until the animation is complete.
#if !defined(FORMALISM_STATE_HPP_) #define FORMALISM_STATE_HPP_ #include "../libraries/murmurhash3.hpp" #include "action.hpp" #include "action_schema.hpp" #include "atom.hpp" #include "literal.hpp" #include "transition.hpp" #include <map> #include <memory> #include <unordered_set> #include <vector> namespace formalism { class StateImpl { private: std::vector<uint32_t> ranks_; formalism::ProblemDescription problem_; mutable std::size_t hash_; public: StateImpl(); StateImpl(const std::vector<uint32_t>& atoms, const formalism::ProblemDescription& problem); StateImpl(const formalism::AtomList& atoms, const formalism::ProblemDescription& problem); StateImpl(const formalism::AtomSet& atoms, const formalism::ProblemDescription& problem); bool operator<(const StateImpl& other) const; bool operator==(const StateImpl& other) const; bool operator!=(const StateImpl& other) const; formalism::AtomList get_atoms() const; formalism::AtomList get_static_atoms() const; formalism::AtomList get_dynamic_atoms() const; std::vector<uint32_t> get_ranks() const; std::vector<uint32_t> get_static_ranks() const; std::vector<uint32_t> get_dynamic_ranks() const; formalism::ProblemDescription get_problem() const; std::map<formalism::Predicate, formalism::AtomList> get_atoms_grouped_by_predicate() const; std::size_t hash() const; friend bool is_applicable(const formalism::Action& action, const formalism::State& state); friend formalism::State apply(const formalism::Action& action, const formalism::State& state); friend bool is_in_state(uint32_t rank, const formalism::State& state); friend bool is_in_state(const formalism::Atom& atom, const formalism::State& state); friend std::ostream& operator<<(std::ostream& os, const formalism::State& state); template<typename T> friend class std::hash; }; // friend functions formalism::State apply(const formalism::Action& action, const formalism::State& state); bool is_in_state(uint32_t atom, const formalism::State& state); bool is_in_state(const formalism::Atom& atom, const formalism::State& state); // non-friend functions State create_state(); State create_state(const formalism::AtomList& atoms, formalism::ProblemDescription problem); State create_state(const formalism::AtomSet& atoms, formalism::ProblemDescription problem); bool is_applicable(const formalism::Action& action, const formalism::State& state); bool atoms_hold(const AtomList& atoms, const formalism::State& state); bool literal_holds(const formalism::Literal& literal, const formalism::State& state); bool literals_hold(const LiteralList& literal_list, const formalism::State& state, std::size_t min_arity = 0); std::ostream& operator<<(std::ostream& os, const formalism::State& state); std::ostream& operator<<(std::ostream& os, const formalism::StateList& states); } // namespace formalism namespace std { // Inject comparison and hash functions to make pointers behave appropriately with ordered and unordered datastructures template<> struct hash<formalism::State> { std::size_t operator()(const formalism::State& state) const; }; template<> struct less<formalism::State> { bool operator()(const formalism::State& left_state, const formalism::State& right_state) const; }; template<> struct equal_to<formalism::State> { bool operator()(const formalism::State& left_state, const formalism::State& right_state) const; }; } // namespace std #endif // FORMALISM_STATE_HPP_
cat("\014") # Clear Console rm(list=ls()) # clear all variables graphics.off() # clear all plots library(tidyverse) # load functions for data manipulation and visualization library(imputeTS) # imputation of missing values library(here) library(readxl) #source("API.R") myRemover <- function(df, fld){ with_dirt <- df[[fld]] # extract vector to be cleaned outliers <- boxplot.stats(with_dirt)$out # use box plots to identify outliers with_na <- ifelse(with_dirt %in% outliers, NA, with_dirt) # replace outliers with NA cleanVals <- na_interpolation(with_na) # replace NA with imputed values df[[paste(fld,'clean',sep = '_')]] <- cleanVals # assign the vector with clean data back to dataframe return(df) # return results back to the function call } ## monthly clean data <- read_excel("data_facility.xlsx") data_p <- read_rds("impute_i.rds") pattern <- "(.{4})(.*)$" data_p$periodname <- gsub(pattern, "\\1/\\2", data_p$periodname) data_f <- data_p%>% janitor::clean_names() %>% mutate(period = lubridate::ym(periodname), values = as.numeric(values)) %>% filter(period< "2023-07-01") # %>% # pivot_longer(cols = 6:15,names_to = "variable",values_to = "values")%>% # select(-c(orgunitlevel4)) #names(data_f) <- c("periodname","region","district","facility","variable","values") data_clean <- data_f #data_clean$period <- lubridate::my(data_clean$periodname) ## orgunit org_unit <- data_p %>% group_by(region,district,facility) %>% count() flagger <- function(facility_i, variable_i){ #facility_i <- "Kitwe Health Centre IV" #variable_i <- sample(data_clean$variable,1) data_interest <- data_clean %>% filter( facility == facility_i & variable == variable_i ) %>% group_by(facility,period,variable) %>% summarise(variable = sum(values,na.rm = T)) l <- arrange(data_interest,period) l <- myRemover(l,"variable") l <- l %>% mutate(flag = as.character(ifelse(variable==variable_clean,"None","Outlier"))) return(l) } flagger("Life Star Clinic",sample(data_clean$variable,1)) #--------- ## Sample districts districts_sample <- sample(unique(data_clean$district),20,replace = FALSE) sample_df <- data_clean %>% filter(district %in% districts_sample) length(unique(sample_df$facility)) facilities <- unique(sample_df$facility) elements <- sample(unique(data_clean$variable),9) i <- 1 for (fac in facilities){ for (element in elements) { x <- flagger(fac,element) x$indicator <- element print(i) if(i == 1){ data_df <- x }else{ data_df <- rbind(data_df,x) } i <- i+1 } } data_df_c <- data_df %>% left_join(org_unit) %>% select(-n) saveRDS(data_df_c,"impute.rds") write_csv(data_df_c,"impute.csv") ## summary data_summary <- data_df %>% mutate(outlier = is.na(flag)) %>% group_by(district,outlier) %>% count() %>% filter(outlier == FALSE) write_csv(data_df,("data_df.csv")) ##--------------- testing plotter <- function(district, variable){ district <- "Abim District" variable <- "x105_an01a_anc_1st_visit_for_women" data_interest <- data_monthly %>% group_by(orgunitlevel3,period) %>% summarise(variable = sum(get(variable),na.rm = T)) %>% filter(orgunitlevel3 == district) l <- arrange(data_interest,period) l <- myRemover(l,"variable") l <- l %>% mutate(flag = ifelse(variable==variable_clean,NA,variable_clean)) if (is.na(sum(l$flag))){ l %>% ggplot(aes(x=period)) + geom_step(aes(y=variable))+ labs(title="There is no outlier") } else { l %>% ggplot(aes(x=period)) + geom_step(aes(y=variable) ) + geom_point(aes(y=flag), color="red" ) + facet_wrap( vars(orgunitlevel3) )+ labs(title = "There is an outlier in red") } } plotter("Amuru District","x105_an02_anc_4th_visit_for_women")
import { UserRoundPlus } from 'lucide-react' import React, { useState } from 'react' import { Button } from './ui/button' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue, } from "@/components/ui/select" import { Label } from '@radix-ui/react-label' import { Input } from './ui/input' import { addCollaborator } from '@/api/docs' import { z } from 'zod' import { useForm } from 'react-hook-form' import { zodResolver } from '@hookform/resolvers/zod' import { Form, FormField, FormItem } from './ui/form' import { toast } from 'sonner' interface props { id: string } const AddCollaborator: React.FC<props> = ({ id }) => { const [loading, setLoading] = useState(false) const FormSchema = z.object({ email: z .string({ required_error: "Please enter an email.", }) .email(), permission: z .string({ required_error: "Please select permission" }) }) const form = useForm<z.infer<typeof FormSchema>>({ resolver: zodResolver(FormSchema), }) const SendInvitation = async (data: z.infer<typeof FormSchema>) => { console.log(data) setLoading(true) const res = await addCollaborator(id, data.email, data.permission) toast.success(res.message) setLoading(false) } return ( <Dialog> <DialogTrigger><Button variant={"ghost"} className='h-full'><UserRoundPlus /></Button></DialogTrigger> <DialogContent className='border-none p-6'> <DialogHeader> <DialogTitle className='text-2xl font-bold'>Add a collaborator</DialogTitle> <DialogDescription> Start collaborating with other people by sending them a simple invitaion and adding them to your project. </DialogDescription> </DialogHeader> <Form {...form}> <form onSubmit={form.handleSubmit(SendInvitation)}> <Label>Email Address</Label> <div className='flex gap-3 items-center'> {/* <FormField control={form.control} name="email", render={({ field }) => ( <FormItem> <Input value={email} onChange={(e) => setEmail(e.target.value)} type="email" placeholder='johndoe@gmail.com ' /> </FormItem> )} /> */} <FormField control={form.control} name="email" render={({ field }) => ( <Input value={field.value} onChange={field.onChange} type="email" placeholder='johndoe@gmail.com ' /> )} /> <FormField control={form.control} name="permission" render={({ field }) => ( <Select onValueChange={field.onChange} value={field.value}> <SelectTrigger className="w-[140px]"> <SelectValue placeholder="Permission" /> </SelectTrigger> <SelectContent> <SelectGroup> <SelectLabel>Permission</SelectLabel> <SelectItem value="r">Read Only</SelectItem> <SelectItem value="rw">Read and Write</SelectItem> </SelectGroup> </SelectContent> </Select> )} /> </div> <Button type='submit' className='mt-2 w-full bg-secondary'>Add +</Button> </form> </Form> </DialogContent> </Dialog> ) } export default AddCollaborator
// Package perrors defines protocol errors. package perrors import ( "errors" "fmt" "github.com/RTann/libsignal-go/protocol/address" ) var ( ErrDuplicateMessage = errors.New("duplicate message") ErrNoCurrentSession = errors.New("no current session") ) var ( _ error = (*errInvalidKeyLength)(nil) _ error = (*errSessionNotFound)(nil) _ error = (*errUntrustedIdentity)(nil) ) type errInvalidKeyLength struct { expected int got int } func ErrInvalidKeyLength(expected, got int) error { return errInvalidKeyLength{ expected: expected, got: got, } } func (e errInvalidKeyLength) Error() string { return fmt.Sprintf("invalid key length: %d != %d", e.got, e.expected) } type errSessionNotFound struct { remoteAddress address.Address } func ErrSessionNotFound(remoteAddress address.Address) error { return errSessionNotFound{ remoteAddress: remoteAddress, } } func (e errSessionNotFound) Error() string { return "session with " + e.remoteAddress.String() + " not found" } type errUntrustedIdentity struct { remoteAddress address.Address } func ErrUntrustedIdentity(remoteAddress address.Address) error { return errUntrustedIdentity{ remoteAddress: remoteAddress, } } func IsErrUntrustedIdentity(e error) bool { _, ok := e.(errUntrustedIdentity) return ok } func (e errUntrustedIdentity) Error() string { return "untrusted identity for address " + e.remoteAddress.String() }
import React, {useEffect, useState } from 'react'; import ReactDOM from 'react-dom'; import axios from "axios"; import List from './components/List.jsx'; import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import Header from './componentsClient/Header.jsx'; import Login from './componentsClient/Login.jsx'; import Home from './componentsClient/Home.jsx'; import Checkout from './componentsClient/Checkout.jsx'; const App = () => { const [items, setItems] = useState([]) const [name, setName] = useState("") const [category, setCategory] = useState("") const [price, setPrice] = useState(0) const [image, setImage] = useState("") const [quantity, setQuantity] = useState(0) const [refresh, setRefresh] = useState(false); useEffect(() => { axios.get('/api/item/') .then(result=> { setItems(result.data) }) .catch(err=>{ console.error(err) }) }, [refresh]) const addItem = (req, res)=>{ axios.post('/api/item/add', {name, category, price, image, quantity}) .then((res)=> setRefresh(!refresh)) .catch((err)=>console.log(err)) } const search = (name)=>{ (!name) ? setRefresh(!refresh) : axios.get(`/api/item/${name}`) .then((res) => { setItems(res.data) }) } const uploadImage = () => { const data = new FormData() data.append('file', image) data.append('upload_preset', 'fatengh') data.append("cloud_name", "danknc4xt") fetch("https://api.cloudinary.com/v1_1/danknc4xt/image/upload", { method: "post", body: data }) .then((res) => res.json()) .then((data) => { setImage(data.secure_url); }).catch((err) => { console.log(err) }) } return( <> <Router> <div className='ap'> <Routes> <Route path ="/checkout" element= {<><Header/><Checkout/></>}/> <Route path="/login" element={<><Login /></>} /> <Route path ="/" element= {<><Header/><Home/></>}/> </Routes> </div> <div> <h1>Food Supplements Shop</h1> <div className = "addcontainer"> <input placeholder='Search a product' onChange={(e) => search(e.target.value)}></input> </div> <div className = "App"> <input type = "file" onChange = {(e)=> {console.log(e.target.files), setImage(e.target.files[0]) }}/> <br/> <button className = 'btn-upload' onClick = {uploadImage}>upload !</button> </div> <div className = "adcontainer"> <button className = 'btn-addItem' onClick={()=>addItem()}>Add Item</button> <br/> <br/> <input placeholder='Name' onChange={(e)=>setName(e.target.value)} /> <br/> <br/> <input placeholder='Category' onChange={(e)=>setCategory(e.target.value)} /> <br/> <br/> <input placeholder='Price' onChange={(e)=>setPrice(e.target.value)} /> <br/> <br/> <input placeholder='Image' value = {image} onChange={(e)=>setImage(e.target.value)} /> <br/> <br/> <input placeholder='Quantity' onChange={(e)=>setQuantity(e.target.value)} /> </div> <List items={items} setRefresh={setRefresh} refresh={refresh}/> <br/> </div> </Router> </> ) } ReactDOM.render(<App />, document.getElementById('app'));
(this is NOT the OXXA API documentation v1.99; because wdoekes modified it) OXXA.COM API DOCUMENTATIE (V 1.99) Inhoud OXXA.com API DOCUMENTATIE (V 1.99) INTRODUCTIE DEFINITIES DOMAIN IDENTITIES NSGROUPS MANAGED DNS RESELLER PROFIELEN FOA EMAIL VERBINDING MAKEN TEST TRANSACTIES COMMANDO’S AUTORENEW CART_ADD CART_DEL CART_GET CART_LIST CART_PURCHASE CART_UPD DNSRECORD_ADD DNSRECORD_DEL DNSRECORD_LIST DNSSEC_ADD DNSSEC_DEL DNSSEC_INFO DNSTEMPLATE_ADD DNSTEMPLATE_DEL DNSTEMPLATE_GET DNSTEMPLATE_LIST DNSTEMPLATE_RECORD_ADD DNSTEMPLATE_RECORD_DEL DOMAIN_CHECK DOMAIN_DEL DOMAIN_EPP DOMAIN_INF DOMAIN_LIST DOMAIN_NS_UPD DOMAIN_PUSH DOMAIN_RESTORE FUNDS_GET FUNDS_LIST GLUE_ADD GLUE_DEL GLUE_GET GLUE_LIST GLUE_UPD IDENTITY_ADD IDENTITY_DEL IDENTITY_GET IDENTITY_LIST IDENTITY_UPD LOCK NSGROUP_ADD NSGROUP_DEL NSGROUP_GET NSGROUP_LIST NSGROUP_UPD ORDER_LIST PRICECHECK QUEUE_GET QUEUE_LIST QUEUE_UPD QUEUE_DEL REGISTER REGISTER_STATUS RENEW RESELLERADD RESELLERDEL RESELLERGET RESELLERLIST RESELLERUPD SERVER_CREATE SERVER_LIST SERVER_GET SERVER_DELETE SERVER_UPDATE SSL_LIST SSL_AUTORENEW SSL_APPROVERLIST SSL_STATUS SSL_EXTENDED_STATUS SSL_CANCEL SSL_NEW SSL_REISSUE SSL_CHANGE_APPROVER SSL_DOWNLOAD SSL_RESEND_APPROVER SSL_REVOKE TASK_GET TASK_LIST TRANSFER TRANSFER_STATUS USER_FUNDS USER_RESET USER_TLD_LIST OWNERCPENDING OWNERCRESEND ## INTRODUCTIE ## Dit document bevat een omschrijving van beschikbare commando’s voor de API. Ieder commando wordt omschreven, de in en uitvoer wordt gedefinieerd en er worden voorbeelden van toepassing gegeven. De API is gebaseerd op http requests waarin met de GET variabele waarden kunnen worden meegegeven. Vrijwel alle API aanroepen moeten worden voorzien van login gegevens. De respons is geformatteerd in XML. Het is belangrijk dat u ieder commando test en uw code baseert op de daadwerkelijke reactie van de API. Alle invoer variabelen (behalve wachtwoorden) zijn niet hoofdlettergevoelig, maar houdt rekening met het feit dat de door u gehanteerde programmeertaal dit wel kan zijn. Parameters zelf dienen in kleine letters ingevoerd te worden. De voorbeelden in dit document zijn opgemaakt om prettig leesbaar te zijn en zijn niet maatgevend voor de daadwerkelijke reactie van de API. De invoer dient URL encoded te worden aangeleverd voor een goede verwerking van de gegevens. Eventuele vreemde tekens dienen in PUNY gecodeerd te zijn. ## CHANGELOG ## Overzicht van alle wijzigen van de API. Versie 1.99 • Introductie van de auto-install en auto-validate van SSL-certificaten. Hiervoor is het SSL_NEW commando voorzien van nieuwe parameters (privatekey en client_server_id) en er zijn een aantal nieuwe commando’s om servers te beheren voor het automatisch installeren van SSL-certificaten. Versie 1.98 • Nieuwe commando’s OWNERCPENDING en OWNERCRESEND toegevoegd waarmee inzicht in de openstaande ownerc-verificaties kan worden verkregen en dit bericht ook opnieuw verstuurd kan worden. Versie 1.97 • Uitbreiding response en parameters van commando’s SSL_PRODUCT_LIST, SSL_LIST, SSL_REISSUE, • Nieuw commando SSL_EXTENDED_STATUS voor uitgebreide status van validatie, ook voor multi- domein Extended Validatie. • Nieuw commando SSL_CANCEL voor het binnen 30 dagen annuleren van aanvragen en nieuwe SSL- certificaten. • Documentatie wijziging TRANSFER commando. Autorenew parameter toegevoegd met default waarde = Y. Versie 1.96 • Uitbreiding response van commando’s CART_GET en CART_LIST met expire_date_registry. • Uitbreiding response van commando SSL_LIST met product en period, waarbij product het ID bevat het van bewuste SSL en period het aantal jaren betreft. • Nieuwe parameter “global_search” voor commando IDENTITY_LIST en NSGROUP_LIST waardoor in alle velden gezocht kan worden van zowel nameservers als contactgegevens. Versie 1.95 • Deprecated: commando DOMAIN_LIST parameters TRANSFERD en DELETED. • Deprecated: commando DOMAIN_LIST parameter STATUS, zoekwaarden A, Q, D, A. • Nieuwe zoekwaarden voor parameter STATUS voor commando DOMAIN_LIST. • Nieuwe parameter “excecution_at” voor REGISTER, TRANSFER, CART_UPD, CART_ADD commando’s. • Nieuwe output parameter “execution_at” bij CART_LIST en CART_GET commando’s. • Nieuwe commando’s QUEUE_GET, QUEUE_LIST, QUEUE_UPD en QUEUE_DEL. Deze nieuwe commando’s maken toekomstige registraties en verhuizingen inzichtelijk. Versie 1.94 • Documentatie commando’s IDENTITY_ADD / IDENTITY_UPD uitgebreid met betrekking tot verplichte velden voor bepaalde landen. • Parameter “epp” toegevoegd aan DOMAIN_UPD commando voor het direct valideren van .be domeinnaamhouder wijzigingen. Versie 1.93 • Uitbreiding parameters FUNDS_LIST commando. • Uitbreiding parameters IDENTITY_ADD commando. • Toevoeging parameter OVERRIDE_MANAGED_DNS_CHECK bij commando DNSSEC_DEL. • Correctie documentie API response glue_list, glue_add. Versie 1.92 • DNS records verwijderen nieuwe variabelen (DNSRECORD_DEL). • Inzage in de EPP-code (DOMAIN_EPP). • Variabele toegevoegd voor het aanvragen van premium domeinen (REGISTER) • TLD informatie uitbreiding, nu ook met DNSSEC (USER_TLD_LIST) • Output voorbeeld SSL_DOWNLOAD commando gecorrigeerd in documentatie. • Toevoeging parameter start bij API commando TASK_LIST. Bedoeld voor introductie limiet a 500 regels voor commando. • DOMAIN_NS_DATE parameter gemaakt “DNSSEC_DELETE”. Dit betreft een optionele parameter en verwijderd DNSSEC materiaal bij wisselen nameservers. Versie 1.91 • SSL reissue toegevoegd • SSL approver adressen ophalen met domain Versie 1.9 • Aanvragen van SSL certificaten via de API Versie 1.82 • Alias niet meer verplicht bij aanmaken identity, bij geen waarde zal de interne handle als alias gebruikt worden • Start en records variabel bij het cart_list commando Versie 1.81 • Verbinding maken via https Versie 1.8 • FOA e-mail her sturen • Status FOA opvragen via order_list commando Versie 1.7 • Nieuwe functionaliteit SIDN registraties, het meegeven van een reseller profiel. Let op de reseller profielen zijn niet dezelfde profielen als die van het commando identity_add, voor het aanmaken van een reseller profiel gebruik je het commando reselleradd. Versie 1.6: • Extra veld toegevoegd aan het commando domain_list om alle verhuisde domeinen van de afgelopen 24 uur weer te geven. • Extra veld toegevoegd aan het commando domain_list om alle verwijderde domeinen van de afgelopen 24 uur weer te geven. Versie 1.5: • Commando dnssec_add toegevoegd. • Commando dnssec_del toegevoegd. • Commando dnssec_info toegevoegd. ## DEFINITIES ## In de documentatie worden diverse termen gehanteerd. Voor een beter begrip van de uitleg wordt in dit hoofdstuk worden enkele van deze veel voorkomende termen gedefinieerd . DOMAIN Het begrip Domeinnaam of Domeinnamen bestaan in de context van dit document altijd uit een aantal attributen. Allereerst is de domeinnaam opgesplitst in twee gedeelten: - SLD (Second Level Domain) - TLD (Top Level Domain) In het voorbeeld example.org is ‘example’ de SLD en ‘org’ de TLD. Verder bevat een domeinnaam diverse gegevens die worden gebruikt voor WHOIS weergave of andere doeleinden, hierbij onderscheiden we 4 categorieën: - Registrant_identity: Een houder (registrant in het Engels) is een instantie/persoon op wiens naam een domeinnaam na registratie is gesteld. De houder draagt de verantwoordelijkheid voor deze domeinnaam en het gebruik ervan, alsmede voor de juistheid van de voor deze domeinnaam vastgelegde gegevens. - Admin_identity: De admin-c is het aanspreekpunt voor de registry en anderen indien er zich niet- technische problemen met de betreffende domeinnaam voordoen. U kunt hierbij denken aan meldingen inzake een aangemelde arbitrageprocedure of een melding van de registry dat uw domeinnaam om een bepaalde reden wordt opgeheven. Mededelingen die per e-mail gedaan worden aan het opgegeven admin-c e-mailadres worden geacht de domeinnaamhouder bereikt te hebben. Daarnaast vertegenwoordigt het opgegeven admin-c contact de domeinnaamhouder. De admin-c is gerechtigd om wijzigingen ten aanzien van uw domeinnaam door te voeren. Gezien het bovenstaande is het verstandig om een admin-c e-mailadres door te geven dat daadwerkelijk door of namens u als domeinnaamhouder wordt gelezen. - Billing_identity: De billing is het aanspreekpunt voor de registry van een TLD (extensie) indien er zich financiële problemen met de betreffende domeinnaam voordoen. - Tech_identity: De tech-c is het aanspreekpunt voor de registry van een TLD (extensie) indien er zich technische problemen met de betreffende domeinnaam voordoen.. Bij elke domeinaanvraag of verhuizing moeten deze 4 groepen opgegeven worden door het aanwijzen van bestaande contact profielen (identities). Tevens bevat een domeinnaam een nsgroup attribuut. Dit is een referentie naar de nameservergroep die voor het domeinnaam is gespecificeerd. In een nsgroup kunnen maximaal 6 nameservers zijn opgenomen. Ten slotte bevat een domeinnaam ook nog een aantal andere administratieve attributen: - Autorenew: Bepaald of het betreffende domein automatisch verlengd moet worden of niet. - Lock: Bepaald de verhuisstatus van het domein. - Expire_date: Vertegenwoordigd de eind- of vervaldatum van een domeinnaam. ## IDENTITIES ## Een identity (profiel) is een set gegevens welke gezamenlijk een contactpersoon vertegenwoordigen. Profielen kunnen in diverse rollen worden toegepast: registrant_identity, admin_identity, billing_identity en tech_identity. De WHOIS gegevens van een domeinnaam zijn gebaseerd op de aan het domein gekoppelde identities. Wanneer een identity wordt bijgewerkt, worden de wijzigingen direct verwerkt in alle aan het profiel gekoppelde domeinnamen. NSGROUPS Een nsgroup is een set van nameservers welke gezamenlijk de dns resolving van een domeinnaam verzorgen. Deze groep bestaat minimaal uit 2 en maximaal uit 6 individuele nameservers. Als een nsgroup wordt bijgewerkt, worden alle domeinnamen die aan deze nsgroup zijn gekoppeld bijgewerkt. MANAGED DNS Bij registratie van domeinnamen kan er gebruik worden gemaakt van de whitelable systeem nameservers voor domeinnaamregistraties in plaats van gebruik te maken van uw eigen nameservers. De nameservers zijn whitelable door gebruik van de anonieme namen ns1.yourdomainnameregistrar.com, ns2.yourdomainnameregistrar.com en ns3.yourdomainnameregistrar.com Per domein kunnen in de portal en middels de API dns records als MX, A records en CNAMES worden beheerd per domeinnaam. Tevens kunnen er vooraf geconfigureerde instellingen worden opgeslagen in dns templates zodat niet bij iedere registratie dezelfde instellingen opnieuw te hoeven worden gemaakt. RESELLER PROFIELEN Sinds kort is het mogelijk om in de WHOIS van de SIDN jouw gegevens als reseller te vermelden. Voordeel hiervan is dat voortaan jouw gegevens als reseller ook vermeld staan in de WHOIS naast de gegevens van de registrar. FOA EMAIL Voor een aantal gTLDS wordt een FOA e-mail verzonden wanneer je een domein probeert te verhuizen naar ons. Deze moet bevestigd worden door de huidige registrant van het domein. ## VERBINDING MAKEN ## Om verbinding te maken met de API dient er een http request gemaakt te worden over een beveiligde verbinding naar https://api.oxxa.com/command.php waarbij de waarden in de GET variabelen wordt geplaatst. Iedere API call begint met de authenticatie van de gebruiker. Door middel van het verstrekken van gebruikersnaam en wachtwoord wordt de authenticatie volbracht: Voorbeeld: https://api.oxxa.com/command.php?apiuser=GEBRUIKERSNAAM&apipassword=WACHTWOORD Er kan gebruik gemaakt worden van een MD5 gecodeerd wachtwoord. Converteer het wachtwoord naar MD5 en plaats voor het wachtwoord de string ‘MD5’. Voorbeeld: MD57c3ac9af1e799e123864bc23e1851a2f Na authenticatie wordt het gewenste commando aangegeven door deze toe te voegen aan de API call Voorbeeld: Met de hierna volgende url wordt het commando ‘domain_list’ uitgevoerd. https://api.oxxa.com/command.php?apiuser=GEBRUIKERSNAAM&apipassword=WACHTWOORD&command=d omain_list De API uitvoer is geformatteerd in XML, bijvoorbeeld: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>1234567</order_id> <command>domain_list</command> <status_code>XMLOK18</status_code> <status_description>In DETAILS vind u de uitgebreide informatie</status_description> <price>0.00</price> <details> <domains_total>1</domains_total> <domains_found>1</domains_found> - <domain> <domainname>example.org</domainname> <nsgroup>ABCD123456</nsgroup> <start_date>2009-04-08</start_date> <expire_date>2010-04-08</expire_date> <autorenew>Y</autorenew> <lock>Y</lock> </domain> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> <order_id> het ordernummer van de actie. <command> het ingegeven commando. <status_code> resultaat van de http call. <status_description> omschrijving van de resultaat gegevens behorende bij status_code. <price> gerekende tarief voor de uitvoer van deze call. <details> eventuele uitgebreide informatie (niet altijd van toepassing). <order_complete> status van de order, kan TRUE, PENDING of FALSE zijn. <done> geeft aan of het einde van de output is bereikt. ## TEST TRANSACTIES ## Test transacties kunnen worden uitgevoerd door de _GET variabele test=Y toe te voegen aan de http request string. Door toevoeging van deze variabele worden de commando’s REGISTER en TRANSFER in testmodus uitgevoerd en worden er geen daadwerkelijke orders tot registratie of verhuizing verwerkt. ## COMMANDO’S ## AUTORENEW Beschrijving: Met dit commando kan worden bepaald of een domeinnaam 30 dagen voor de afloopdatum automatisch door het systeem wordt verlengd. Variabelen: - SLD (verplicht) Sld van de aan te passen domeinnaam. - TLD (verplicht) Tld van de aan te passen domeinnaam. - AUTORENEW (verplicht) Waarde van de automatisch verlengen (Y of N). Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=autorenew&autorenew =Y&sld=EXAMPLE&tld=ORG Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>autorenew</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 2</status_code> <status_description>Autorenew voor dit domein is aangepast</status_description> <price>1.993</price> <details>Autorenew aangepast naar: Y</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## CART_ADD ## Beschrijving: Met dit commando kunnen items in de cart van de user worden geplaatst. Variabelen: - SLD (verplicht) Sld van het domein. - TLD (verplicht) Tld van het domein. - PRODUCTTYPE (verplicht) Type van een item (renew/register/transfer/uit quarantaine). - IDENTITY-ADMIN (optioneel) Handle van de admin identity. - IDENTITY-TECH (optioneel) Handle van de tech identity. - IDENTITY-BILLING (optioneel) Handle van de billing identity. - IDENTITY-REGISTRANT (optioneel) Handle van de registrant identity. - IDENTITY-RESELLER (optioneel) Handle van een reseller (alleen voor .NL) - NSGROUP (optioneel) Handle van de nameserver groep. - TRANS_EPP (optioneel) Eventuele authorisatiecode van het domein. - ENDUSERIP (verplicht) IP adres van de eindgebruiker. - QUANTITY (optioneel) Aantal van de cart-regel (default: 1) - AUTORENEW (optioneel) Domein op autorenew (Y of N) (default: Y). - USETRUSTEE (optioneel) Domein op trustee (Y of N) (default: N). - LOCK (optioneel) Moet het domein op LOCK staan (Y of N)(default: Y). - EXECUTION_AT (optioneel) Datum waarop de order uitgevoerd wordt (DD-MM-YYYY) Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=cart_add&tld=ORG& sld=EXAMPLE&producttype=RENEW&enduserip=1.99.3.4 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>cart_add</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 32</status_code> <status_description>Het item is aan de cart toegevoegd</status_description> <price /> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## CART_DEL ## Beschrijving: Met dit commando kan een item uit de cart worden verwijdert of de hele cart worden leeg gemaakt. Variabelen: - ENDUSERIP (verplicht) IP adres van eindgebruiker waar dit item onder staat. - ITEMID (verplicht) ID van het item (uit te lezen met card_get). - EMPTYCART (verplicht) Haal de hele cart leeg (Y) of alleen het betreffende item (N). Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=cart_del& enduserip=1.99.3.4&emptycart=Y Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>cart_del</command> <status_code>XMLOK 36</status_code> <status_description>De cart is leeg gemaakt</status_description> <price /> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## CART_GET ## Beschrijving: Met dit commando kan de configuratie van een item in de cart van de user worden opgevraagd. Het benodigde cart_id kan wordt verstrekt bij het in de cart plaatsen (cart_add) en kan worden teruggelezen in het cart overzicht (cart_list). Variabelen: - CART_ID (verplicht) ID nummer van het cart item. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=cart_get&cart_id=999 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>cart_get</command> <status_code>XMLOK 49</status_code> <status_description>De informatie vind u in DETAILS</status_description> <price>0</price> - <details> <sld>example</sld> <tld>org</tld> <command>register</command> <amount>1</amount> <identity-admin>ABCD1234</identity-admin> <identity-tech> ABCD1234</identity-tech> <identity-billing> ABCD1234</identity-billing> <identity-registrant> ABCD1234</identity-registrant> <identity-reseller>ABCD1234</identity-reseller> <nsgroup>ABCD1234</nsgroup> <template>ABCD1234</ template > <trustee>N</trustee> <epp></epp> <autorenew>Y</autorenew> <lock>Y</lock> <execution_at> 20-11-2018</ execution_at> <expire_date_registry> 20-11-2018</ expire_date_registry > </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## CART_LIST ## Beschrijving: Dit commando geeft een lijst van alle items die momenteel in de cart van de user aanwezig zijn. Variabelen: - START (optioneel) Om te bepalen om op te halen vanaf ID x. - RECORDS (optioneel) Het aantal records dat opgehaald moet worden. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=cart_list&start=0&recor ds=20 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>cart_list</command> <status_code>XMLOK 33</status_code> <status_description> Cart succesvol opgevraagd, uitgebreide informatie vind u in details </status_description> <price>0</price> - <details> <cartcount>3</cartcount> <totalcartcount>3</totalcartcount> - <item> <itemid>96</itemid> <producttype>register</producttype> <productdesc>example1.org</productdesc> <itemprice>6.36</itemprice> <quantity>1</quantity> <autorenew>Y</autorenew> <trustee>N</trustee> <lock>Y</lock> <configok>Y</configok> <execution_at>20-11-2018</ execution_at> <expire_date_registry> 20-11-2018</ expire_date_registry > </item> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## CART_PURCHASE ## Beschrijving: Dit commando biedt de gedeeltelijke óf de volledige inhoud van de cart ter bestelling aan. Let op: items in de cart dienen eerst correct geconfigureerd te zijn alvorens de cart_purchase kan worden uitgevoerd. Variabelen: - CART_ID (verplicht) Cart_id van het item of ALL om de volledige cart aan te schaffen. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=cart_purchase& cart_id=ALL Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command> cart_purchase </command> <status_code>XMLOK 47</status_code> <status_description>De cart is succesvol ge-purchased, in de details vind u informatie over de individuele items</status_description> <price>0</price> - <details> - <cartitem> <cartitemid>96</cartitemid> <command>register</command> <sld>example1</sld> <tld>org</tld> <status_code>XMLERR 19</status_code> <status_description> Dit domein kan niet geregistreerd worden omdat het bezet is. </status_description> </cartitem> - <cartitem> <cartitemid>97</cartitemid> <command>register</command> <sld>example2</sld> <tld>org</tld> <status_code>XMLERR 19</status_code> <status_description> Dit domein kan niet geregistreerd worden omdat het bezet is. </status_description> </cartitem> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## CART_UPD ## Beschrijving: Dit commando configureert een item in de cart zodat deze middels een cart_purchase besteld kan worden. Variabelen: - ENDUSERIP (verplicht) IP adres van eindgebruiker waar dit item onder staat. - ITEMID (verplicht) ID van het item (uit te lezen met card_get). - IDENTITY-ADMIN (optioneel) Handle van de admin identity. - IDENTITY-TECH (optioneel) Handle van de tech identity. - IDENTITY-BILLING (optioneel) Handle van de billing identity. - IDENTITY-REGISTRANT (optioneel) Handle van de registrant identity. - IDENTITY-RESELLER (optioneel) Handle van een reseller (alleen voor .NL) - NSGROUP (optioneel) Handle van de nameserver groep. - TEMPLATE (optioneel) Handle van een DNS template bij managed dns service - TRANS_EPP (optioneel) Eventuele authorisatiecode van het domein. - QUANTITY (optioneel) Nieuwe waarde voor AANTAL. - AUTORENEW (optioneel) Nieuwe waarde voor AUTORENEW (Y of N). - LOCK (optioneel) Nieuwe waarde voor LOCK (Y of N). - USETRUSTEE (optioneel) Nieuwe waarde voor USETRUSTEE (Y of N). - EXECUTION_AT (optioneel) Datum waarop de order uitgevoerd wordt (DD-MM-YYYY) Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=cart_upd& enduserip=1.99.3.4&itemid=12345&quantity=5&autorenew=Y&lock=Y Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>cart_upd</command> <status_code>XMLOK 34</status_code> <status_description>Het cartitem is succesvol geupdate</status_description> <price /> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DNSRECORD_ADD ## Beschrijving: Met dit commando kan er een DNS record toegevoegd worden aan een domein. Variabelen: - SLD (verplicht) Sld van het domein waaraan DNS records toegevoegd worden. - TLD (verplicht) Tld van het domein waaraan DNS records toegevoegd worden. - VALUE (verplicht) Waarde (bijv. www.example.com). - TYPE (verplicht) Type van het record (MX, A, AAAA,CNAME, TXT). - DATA (verplicht) Bijvoorbeeld IP adres bij A-record. - PRIORITY (optioneel) Prioriteit van MX record. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnsrecord_add&sld=EX AMPLE&tld=COM&value=WWW.EXAMPLE.COM&type=MX&data=192.168.0.1&priority=1 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1"?> - <channel> - <order> <order_id>123456</order_id> <command>dnsrecord_add</command> <sld>example</sld> <tld>com</tld> <status_code>XMLOK 60</status_code> <status_description>Het DNS record is succesvol toegevoegd</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DNSRECORD_DEL ## Beschrijving: Met dit commando kan er een DNS record verwijderd worden welke aan een domein toegewezen is. Variabelen: - SLD (verplicht) Sld van het domein waaraan DNS records toegevoegd worden. - TLD (verplicht) Tld van het domein waaraan DNS records toegevoegd worden. - VALUE (verplicht) Waarde (bijv. www.example.com). - TYPE (verplicht) Type van het record (MX, A, AAAA,CNAME, TXT). - DATA (verplicht) Bijvoorbeeld IP adres bij A-record. - PRIORITY (optioneel) Prioriteit van MX record. - TTL (verplicht) DE TTL van de record. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnsrecord_del&sld=EXA MPLE&tld=COM&value=WWW.EXAMPLE.COM&type=MX&data=192.168.0.1&priority=1&ttl=3600 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1"?> - <channel> - <order> <order_id>123456</order_id> <command> dnsrecord_del</command> <status_code>XMLOK 59</status_code> <status_description>Het DNS template record is verwijderd</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DNSRECORD_LIST ## Beschrijving: Met dit commando is een lijst op te halen van alle DNS records welke er toegevoegd zijn aan een domein. Variabelen: - START (optioneel) Om te bepalen om op te halen vanaf ID x. - RECORDS (optioneel) Het aantal records dat opgehaald moet worden. - SORTNAME (optioneel) Sorteren op value, data of type. - SORTORDER (optioneel) Sorteren van de lijst op ASC of DESC. - VALUE (optioneel) Zoeken op bepaalde value. - DATA (optioneel) Zoeken op bepaalde data. - TYPE (optioneel) Zoeken op bepaalde type. - TLD (verplicht) Tld van het domein waarvan de gegevens opgehaald worden. - SLD (verplicht) Sld van het domein waarvan de gegevens opgehaald worden. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnsrecord_list&start=0 &records=5&sortname=VALUE&sortorder=ASC&value=&data=&type=&tld=COM&sld=EXAMPLE Uitvoer: <?xml version="1.0" encoding="ISO-8859-1"?> - <channel> - <order> <order_id>123456</order_id> <command>dnsrecord_list</command> <status_code>XMLOK 61</status_code> <status_description>In DETAILS vind u de uitgebreide informatie</status_description> <price>0</price> - <details> <records_total>2</ records _total> < records _found>2</ records _found> - <record> <record_id>1</template_id> <value>www.example.com</ value> <type>MX</ type> <data>192.168.0.1</ data> <priority>1</ priority> </ record > </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DNSSEC_ADD ## Beschrijving: Met dit commando kan er een DNSSEC record toegevoegd worden aan een domein. Variabelen: - SLD (verplicht) Domein waar het aan toegevoegd moet worden - TLD (verplicht) Extensie van het domein - FLAG (verplicht) Het type publieke sleutel - PROTOCOL (verplicht) Domein waar het aan toegevoegd moet worden - ALG (verplicht) Algoritme waarmee de sleutel is aangemaakt - PUBKEY (verplicht) De publieke sleutel Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnssec_add&sld=SLD&tl d=TLD&flag=FLAG&protocol=PROTOCOL&alg=ALG&pubkey=PUBKEY Uitvoer: <?xml version="1.0" encoding="ISO-88591"?> - <channel> - <order> <order_id>123456</order_id> <command>dnssec_add</command> <status_code>XMLOK 82</status_code> <status_description>DNSSEC record is toegevoegd aan het domein</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DNSSEC_DEL ## Beschrijving: Met dit commando kan er een DNSSEC verwijderd worden, hiervoor zijn dezelfde gegevens noodzakelijk als bij het aanmaken van een DNSSEC record. DNSSEC records kunnen niet aangepast worden en moeten altijd eerst verwijderd worden en daarna opnieuw toegevoegd worden. Variabelen: - SLD (verplicht) Domein waar het aan toegevoegd moet worden - TLD (verplicht) Extensie van het domein - FLAG (verplicht) Het type publieke sleutel - PROTOCOL (verplicht) Domein waar het aan toegevoegd moet worden - ALG (verplicht) Algoritme waarmee de sleutel is aangemaakt - PUBKEY (verplicht) De publieke sleutel - OVERRIDE_MANAGED_DNS_CHECK (optioneel) DNSSEC verwijderen bij gebruik Managed DNS Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnssec_del&sld=SLD&tl d=TLD&flag=FLAG&protocol=PROTOCOL&alg=ALG&pubkey=PUBKEY Uitvoer: <?xml version="1.0" encoding="ISO-88591"?> - <channel> - <order> <order_id>123456</order_id> <command>dnssec_del</command> <status_code>XMLOK 81</status_code> <status_description>DNSSEC record is verwijderd van het domein</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DNSSEC_INFO ## Beschrijving: Met dit commando kunnen alle DNSSEC records opgehaald worden van het domein. Deze informatie kan je gebruiken om records te verwijderen Variabelen: - SLD (verplicht) Domein waar het aan toegevoegd moet worden - TLD (verplicht) Extensie van het domein Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnssec_info&sld=SLD&t ld=TLD Uitvoer: <?xml version="1.0" encoding="ISO-88591"?> - <channel> - <order> <order_id>123456</order_id> <command>dnssec_info</command> <status_code>XMLOK 80</status_code> <status_description>DNSSEC informatie opgehaald, zie details element</status_description> <price>0</price> <details> <ns> <nameserver>ns1.xxx.nl</nameserver> <nameserver>ns2.xxx.nl</nameserver> <nameserver>ns3.xxx.nl</nameserver> </ns> <dnssec> <key> < flags>…</flags> < protocol>…</protocol> < alg>…</alg> < pubKey>…</pubKey> </key> <key> < flags>…</flags> < protocol>…</protocol> < alg>…</alg> < pubKey>…</pubKey> </key> </dnssec> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DNSTEMPLATE_ADD ## Beschrijving: Met dit commando kan er een nieuwe dns template toegevoegd worden aan de server. Server zal als return de handle teruggeven van de desbetreffende template. Deze is noodzakelijk om een dns record toe te kunnen voegen aan een template. Variabelen: - ALIAS (verplicht) Alias van de dns template Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnstemplate_add&alias =ALIAS Uitvoer: <?xml version="1.0" encoding="ISO-88591"?> - <channel> - <order> <order_id>123456</order_id> <command>dnstemplate_add</command> <status_code>XMLOK 57</status_code> <status_description>DNS template succesvol aangemaakt</status_description> <price>0</price> - <details> <handle>RXZP69272</handle> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DNSTEMPLATE_DEL ## Beschrijving: Met dit commando kan een aangemaakte template verwijderd worden. Variabelen: - HANDLE (verplicht) Handle van de template Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnstemplate_del&hand le=HANDLE Uitvoer: <?xml version="1.0" encoding="ISO-8859-1"?> - <channel> - <order> <order_id>123456</order_id> <command>dnstemplate_del</command> <status_code>XMLOK 59</status_code> <status_description>Het DNS template record is verwijderd</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DNSTEMPLATE_GET ## Beschrijving: Met dit commando is de template DNS data op te halen welke aan een bepaalde template toegevoegd zijn. Variabelen: - HANDLE Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnstemplate_get&hand le=HANDLE Uitvoer: <?xml version="1.0" encoding="ISO-8859-1"?> - <channel> - <order> <order_id>123456</order_id> <command>dnstemplate_get</command> <status_code>XMLOK 61</status_code> <status_description>In DETAILS vind u de uitgebreide informatie</status_description> <price>0</price> <details> <record> <record_id>14</record_id> <value>WWW.EXAMPLE.COM</value> <type>MX</type> <data>192.168.0.1</data> <priority>1</priority> </record> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DNSTEMPLATE_LIST ## Beschrijving: Met dit commando is een lijst van DNS records op te halen welke aan een DNS template gekoppeld zijn. Variabelen: - START (optioneel) Om te bepalen om op te halen vanaf ID x. - RECORDS (optioneel) Het aantal records dat opgehaald moet worden. - SORTNAME (optioneel) Sorteren op alias. - SORTORDER (optioneel) Sorteren van de lijst op ASC of DESC. - ALIAS (optioneel) Bepaalde template ophalen. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnstemplate_list&start =25&records=25&sortname=ALIAS&sortorder=DESC&alias=TEMPLATE Uitvoer: <?xml version="1.0" encoding="ISO-8859-1"?> - <channel> - <order> <order_id>123456</order_id> <command>dnstemplate_list</command> <status_code>XMLOK 62</status_code> <status_description>In de DETAILS vind u de uitgebreide informatie</status_description> <price>0</price> - <details> <templates_total>2</templates_total> <templates_found>2</templates_found> - <template> <handle> RXZP69272</ handle > <name>Voorbeeld 1</name> </template> - <template> < handle > RXZP69272</ handle > <name>Voorbeeld 2</name> </template> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DNSTEMPLATE_RECORD_ADD ## Beschrijving: Met dit commando kan er een nieuw record toegevoegd worden aan een template. Variabelen: - HANDLE (verplicht) Deze waarde is gelijk aan de handle van de template - VALUE (verplicht) Waarde van het record (bijv. www.example.com) - TYPE (verplicht) Type van het record (MX, A, AAAA,CNAME, TXT) - DATA (verplicht) Bijvoorbeeld IP adres bij A-record - PRIORITY (optioneel) Prioriteit van MX record - TTL (verplicht) Tijd welke minimaal 120 moet zijn Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnstemplate_record_ad d&handle=VOORBEELD&value=WWW.EXAMPLE.NL&type=MX&data=192.168.0.1&priority=1&ttl=120 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1"?> - <channel> - <order> <order_id>123456</order_id> <command>dnstemplate_record_add</command> <status_code>XMLOK 58</status_code> <status_description>Het DNS template record is succesvol toegevoegd</status_description> <price>0</price> <order_complete>TRUE</order_complete> <details>RECORD_ID</details> <done>TRUE</done> </order> </channel> ## DNSTEMPLATE_RECORD_DEL ## Beschrijving: Met dit commando kan er een dns template record verwijderd worden. Variabelen: - RECORDID (verplicht) Het ID van de te verwijderen DNS template record. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=dnstemplate_record_de l&recordid=ID Uitvoer: <?xml version="1.0" encoding="ISO-8859-1"?> - <channel> - <order> <order_id>123456</order_id> <command>dnstemplate_record_del</command> <status_code>XMLOK 59</status_code> <status_description>Het DNS template record is verwijderd</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DOMAIN_CHECK ## Beschrijving: Met dit commando kan de beschikbaarheid van een domein worden gecontroleerd (vrij of bezet). Er is een daglimiet van 9.999 op het aantal bevragingen ingesteld. Variabelen: - SLD (verplicht) Sld van de te controleren domeinnaam - TLD (verplicht) Tld van de te controleren domeinnaam Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=domain_check&tld=OR G&sld=EXAMPLE Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>domain_check</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 10</status_code> <status_description>Domein is bezet</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DOMAIN_DEL: ## Beschrijving: Dit commando plaatst een domein onmiddellijk in quarantaine. Let op: de quarantaine status is alleen terug te draaien door het domein uit quarantaine te halen, hier zijn altijd kosten aan verbonden. Variabelen: - SLD (verplicht) Sld van de domeinnaam die in quarantaine moet worden geplaatst. - TLD (verplicht) Tld van de domeinnaam die in quarantaine moet worden geplaatst. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=domain_del& sld=EXAMPLE&tld=ORG Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>domain_del</command> <sld>example</sld> <tld>org</tld> <status_code>XMLPEN 11</status_code> <status_description>De domeinnaam wordt opgeheven</status_description> <price>0</price> <order_complete>FALSE</order_complete> <done>TRUE</done> </order> </channel> ## DOMAIN_EPP ## Beschrijving: Dit commando zendt de EPP code van een domein per email aan de registrant. In het veld details kunt u bij een aantal TLD’s gelijk de verhuiscode inzien. Dit is helaas niet mogelijk bij alle TLD’s en daarom worden deze per e- mail verzonden. Variabelen: - SLD (verplicht) Sld van het domein. - TLD (verplicht) Tld van het domein. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=domain_epp& sld=EXAMPLE&tld=ORG Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>domain_epp</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 39</status_code> <status_description>De EPP code is verstuurd naar de registrant</status_description> <price /> <details>EPPCODE</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DOMAIN_INF ## Beschrijving: Dit commando geeft de actuele configuratie van een domeinnaam registratie. Relevant zijn: NSGROUP, IDENTITIES, EXPIRE_DATE,AUTORENEW,LOCK Variabelen: - SLD (verplicht) Sld van de domeinnaam. - TLD (verplicht) Tld van de domeinnaam. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=domain_inf&tld=ORG& sld=EXAMPLE Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id /> <command>domain_inf</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 16</status_code> <status_description>In DETAILS vind u de uitgebreide informatie</status_description> <price>0.00</price> - <details> <identity-registrant>ABCD147258</identity-registrant> <identity-admin> ABCD147258</identity-admin> <identity-billing> ABCD147258</identity-billing> <identity-tech> ABCD147258</identity-tech> <identity-reseller/> <nsgroup>EFGH1234</nsgroup> <expire_date>04-10-2009 (dd-mm-yyyy)</expire_date> <autorenew>Y</autorenew> <lock>N</lock> <dnssec>N</dnssec> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> * Let op, indien een TLD DNSSEC ondersteunt is het desondanks mogelijk dat niet alle domeinnamen met deze extensie ook de mogelijkheid hebben om DNSSEC te beheren doordat niet alle domeinnamen bij dezelfde registry zijn geregistreerd. Neem contact op met Customer Support indien u DNSSEC wilt toepassen op dergelijke domeinnamen. ## DOMAIN_LIST ## Beschrijving: Dit commando geeft een lijst van domeinnamen die onder beheer zijn van de gebruiker. Diverse zoekopties behoren tot de mogelijkheden. Voor het veld transferd en deleted moet een Y meegegeven worden. Variabelen: - START (optioneel) Startveld van de lijstweergave (standaard = 0) - RECORDS (optioneel) Maximaal te tonen records in lijstweergave (standaard = 25, bij een waarde van -1 wordt de volledige lijst getoond) - SORTNAME (optioneel) Veld waarop de lijstweergave gesorteerd wordt - SORTORDER (optioneel) Sorteervolgorde aflopend of oplopend (ASC / DESC) - SLD (optioneel) Zoekvoorwaarde voor de SLD - TLD (optioneel) Zoekvoorwaarde voor de TLD - NSGROUP (optioneel) Zoekvoorwaarde voor de nsgroup - IDENTITY (optioneel) Zoekvoorwaarde voor een van de identities - AUTORENEW (optioneel) Zoekvoorwaarde voor de autorenew - LOCK (optioneel) Zoekvoorwaarde voor de lock - EXPIRE_DATE (optioneel) Zoekvoorwaarde voor de expire_date - STATUS (optioneel) Zoekvoorwaarde voor status: o Active Alle actieve domeinnamen o Quarantaine Alle domeinnamen in quarantaine o Delete Alle verwijderde domeinnamen o Inactive Alle in-actieve domeinnamen o Transferd Alle wegverhuisde domeinnamen (te combineren met DAYS) o Expired Alle verlopen domeinnamen (te combineren met DAYS) o Renewed Alle verlengde domeinnamen (te combineren met DAYS) o Renew Alle aankomende verlengingen (te combineren met DAYS) - DAYS (optioneel) Zoekwaarde die te combineren is met status parameters. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=domain_list&tld=ORG &sortname=SLD&sortorder=ASC&start=0&records=2&transferd=Y&deleted=Y Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>domain_list</command> <tld>org</tld> <status_code>XMLOK18</status_code> <status_description>In DETAILS vind u de uitgebreide informatie</status_description> <price>0.00</price> - <details> <domains_total>100</domains_total> <domains_found>25</domains_found> - <domain> <domainname>example1.org</domainname> <nsgroup>EFGH123456</nsgroup> <identity-registrant> ABCD123456</identity-registrant> <identity-admin> ABCD 123456</identity-admin> <identity-tech> ABCD 123456</identity-tech> <identity-billing> ABCD 123456</identity-billing> <expire_date>2009-10-06</expire_date> <autorenew>Y</autorenew> <lock>Y</lock> </domain> - <domain> <domainname>example2.org</domainname> <nsgroup>EFGH123456</nsgroup> <identity-registrant> ABCD123456</identity-registrant> <identity-admin> ABCD123456</identity-admin> <identity-tech> ABCD123456</identity-tech> <identity-billing> ABCD123456</identity-billing> <expire_date>2008-10-09</expire_date> <autorenew>Y</autorenew> <lock>Y</lock> </domain> - <domain> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DOMAIN_NS_UPD ## Beschrijving: Dit commando werkt de configuratie van een domeinnaam bij met nieuwe nameserver profiel instellingen. Variabelen: - SLD (verplicht) Sld van de domeinnaam die wordt aangepast. - TLD (verplicht) Tld van de domeinnaam die wordt aangepast. - NSGROUP (optioneel) Nieuwe waarde NSGROUP (handle) - handle (optioneel) Het meegeven van een dns handle aan het domein - DNSSEC_DELETE (optioneel) Verwijderd DNSSEC materiaal bij wisselen nameservers (Y/N) Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=domain_ns_upd& sld=EXAMPLE&tld=ORG&nsgroup=EFGH123456 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>domain_ns_upd</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 12</status_code> <status_description>Domein succesvol aangepast</status_description> <price>0</price> <order_complete>FALSE</order_complete> <done>TRUE</done> </order> </channel> ## DOMAIN_PUSH ## Beschrijving: Dit commando plaatst een domein onder beheer van een andere gebruiker. Variabelen: - SLD (verplicht) Sld van het domein. - TLD (verplicht) Tld van het domein. - USERNAME (verplicht) Gebruikersnaam van de nieuwe eigenaar. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=domain_push& sld=EXAMPLE&tld=ORG&username=NEW_USER Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>domain_push</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 38</status_code> <status_description>Domeinpush succesvol uitgevoerd</status_description> <price /> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## DOMAIN_RESTORE ## Beschrijving: Dit commando herstelt een domeinnaam uit quarantaine. Variabelen: - SLD (verplicht) Sld van het domein. - TLD (verplicht) Tld van het domein. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=domain_restore& sld=EXAMPLE&tld=ORG&nsgroup=EFGH1234 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>domain_restore</command> <sld>example</sld> <tld>org</tld> <status_code>XMLPEN 12</status_code> <status_description>Het domein wordt uit quarantaine heeft gehaald</status_description> <price /> <order_complete>PENDING</order_complete> <done>TRUE</done> </order> </channel> ## DOMAIN_UPD: ## Beschrijving: Dit commando werkt de configuratie van een domeinnaam bij met nieuwe contact profiel instellingen. Alle velden zijn optioneel, maar er moet tenminste 1 wijziging worden doorgegeven. Let op: een wijziging van de IDENTITY-REGISTRANT wordt opgevat als een domeinnaam overdracht naar een nieuwe houder. Afhankelijk van de domeinnaam extensie kan de registry hiervoor kosten in rekening brengen die worden doorberekend. Variabelen: - SLD (verplicht) Sld van de domeinnaam die wordt aangepast. - TLD (verplicht) Tld van de domeinnaam die wordt aangepast. - IDENTITY-REGISTRANT (optioneel) Nieuwe waarde registry-identity (handle) - IDENTITY-ADMIN (optioneel) Nieuwe waarde admin-identity (handle) - IDENTITY-BILLING (optioneel) Nieuwe waarde billing-identity (handle) - IDENTITY-TECH (optioneel) Nieuwe waarde tech-identity (handle) - IDENTITY-RESELLER (optioneel) Nieuwe waarde reseller-identity alleen voor .NL (handle). Gebruik de waarde 'noprofile' om het profiel te ontkoppelen. - EPP (optioneel) Ter validatie van domeinnaamhouder wijzigingen (.BE) Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=domain_upd& sld=EXAMPLE&tld=ORG&identity-registrant=ABCD123456&identity-admin=ABCD123456&identity- billing=ABCD123456&identity-tech=ABCD123456&identity-reseller=ABCD123456&epp=XXX Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>domain_upd</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 12</status_code> <status_description>Domein succesvol aangepast</status_description> <price>0</price> <order_complete>FALSE</order_complete> <done>TRUE</done> </order> </channel> ## FUNDS_GET ## Beschrijving: Dit commando geeft het actuele krediet saldo in euros van een gebruiker. Variabelen: - APIUSER (verplicht) Account gebruikersnaam - APIPASSWORD (verplicht) Account wachtwoord Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=funds_get Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>funds_get</command> <status_code>XMLOK 40</status_code> <status_description>De credits zijn opgevraagd, u vind dit in de DETAILS</status_description> <price /> - <details> <funds_total>9999.99</funds_total> <funds_reserved>150.00</funds_reserved> <funds_available>9849.99</funds_available> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## FUNDS_LIST ## Beschrijving: Dit commando geeft de financiële transacties op over een bepaalde periode voor de gegeven gebruiker. Variabelen: - BEGIN (optioneel) Begindatum voor overzicht (DD-MM-YYYY). - END (optioneel) Einddatum voor overzicht (DD-MM-YYYY). - SORTORDER (optioneel) Aflopend/ Oplopend (parameter DESC/ASC). - START (optioneel) Records weergeven vanaf regelnummer. - RECORDS (optioneel) Aantal records (-1 geeft alles weer). - SORTNAME (optioneel) Type sortering (date/description). - DESCRIPTION (optioneel) Filter van het description veld. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=funds_list& end=01-12-2018 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>funds_list</command> <status_code>XMLOK 41</status_code> <status_description>Financiele mutaties opgevraagd, u vindt ze in DETAILS</status_description> <price /> - <details> - <order> <orders_id>123456</orders_id> <price>0.00</price> <date>02-12-2008</date> <note>bijgeboekt vanwege storting</note> </order> - <order> <orders_id>123456</orders_id> <price>0.00</price> <date>02-12-2008</date> <note>bijgeboekt vanwege storting</note> </order> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## FOARESEND ## Beschrijving: Dit commando geeft je de mogelijkheid om de FOA e-mail opnieuw te versturen. Variabelen: - SLD (verplicht) Sld van de domeinnaam. - TLD (verplicht) Tld van de domeinnaam. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=foaresend& sld=SLD&tld=TLD Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>foa_resend</command> <status_code> XMLOK 109</status_code> <status_description> FOA opnieuw verzonden aan registrant</status_description> <price /> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## GLUE_ADD ## Beschrijving: Met dit commando kan er aan een nameserver een IP adres gekoppeld worden. Dit is noodzakelijk wanneer het domein gelijk is aan de opgegeven nameservers. Variabelen: - NS_FQDN (verplicht) De nameserver waaraan het IP adres toegevoegd moet worden. - NS_IP (verplicht) Het IP adres wat toegevoegd moet worden aan de nameserver Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=glue_add&ns_fqdn=ns 1.website.nl&ns_ip=192.168.0.1 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order <order_id>123456</order_id> <command>glue_add</command> <status_code>XMLOK 69</status_code> <status_description>Glue record succesvol aangemaakt</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## GLUE_DEL ## Beschrijving: Met dit commando kan er een IP adres ontkoppeld worden van een nameserver. Variabelen: - NS_FQDN (verplicht) De nameserver waarvan het IP adres verwijderd moet worden. - NS_IP (verplicht) Het IP adres wat verwijderd moet worden. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=glue_del&ns_fqdn=ns1. website.nl&ns_ip=192.168.0.1 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order <order_id>123456</order_id> <command>glue_del</command> <status_code>XMLOK 70</status_code> <status_description> Glue record succesvol verwijderd</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## GLUE_GET ## Beschrijving: Met dit commando kan er van een nameserver de glue record opgehaald worden. Variabelen: - NS_FQDN (verplicht) De nameservers waarvan de glue records opgehaald moeten worden. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=glue_get&ns_fqdn=ns1. website.nl Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order <order_id>123456</order_id> <command>glue_get</command> <status_code>XMLOK 227</status_code> <status_description>Glue record succesvol opgehaald</status_description> <price>0</price> <details> <ip_adres>192.168.0.1</ip_adres> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## GLUE_LIST ## Beschrijving: Met dit commando kan er een lijst opgehaald worden van alle gluerecords welke er aan nameservers gekoppeld zijn. Variabelen: - NS_FQDN (optioneel) De nameservers waarvan de glue records opgehaald worden. - NS_IP (optioneel) Het IP adres wat toegevoegd moet worden aan de nameserver. - START (optioneel) Bij welk veld moet worden begonnen met weergave. - RECORDS (optioneel) Hoeveel records moeten er opgehaald worden. - SORTNAME (optioneel) Veld waarop de lijst gesorteerd moet worden. - SORTORDER (optioneel) Sorteren op ASC of DESC. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=glue_list&ns_fqdn=ns1. website.nl&ns_ip=192.168.0.1&start=0&records=10&sortorder=asc Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order <order_id>123456</order_id> <command>glue_get</command> <status_code>XMLOK 67</status_code> <status_description>Glue record succesvol opgehaald</status_description> <price>0</price> <details> <ns1.doubleserver.net>192.168.0.1</ ns1.doubleserver.net > </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## GLUE_UPD ## Beschrijving: Met dit commando kan er een IP aangepast worden welke gekoppeld is aan een nameserver. Variabelen: - NS_FQDN (verplicht) De nameserver waaraan het IP adres toegevoegd moet worden. - NS_IP (verplicht) Het IP adres wat toegevoegd moet worden aan de nameserver Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=glue_upd&ns_fqdn=ns 1.website.nl&ns_ip=192.168.0.1 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order <order_id>123456</order_id> <command>glue_add</command> <status_code>XMLOK 71</status_code> <status_description>Glue records succesvol aangepast</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## IDENTITY_ADD ## Beschrijving: Dit commando voegt een contact profiel (identity) aan het systeem toe. Variabelen: - ALIAS (optioneel) Alias van de identity (default is de interne handle) - COMPANY (optioneel) Is opgegeven identity een bedrijf (Y of N). - COMPANY_NAME (optioneel) Bedrijfsnaam voor identity. - JOBTITLE (optioneel) Aanhef van personen, verplicht veld bij bedrijven* - FIRSTNAME** (verplicht) Voornaam voor identity. - LASTNAME** (verplicht) Achternaam voor identity. - STREET** (verplicht) Straatnaam voor identity. - NUMBER** (verplicht) Huisnummer voor identity. - SUFFIX** (optioneel) Toevoeging huisnummer voor identity. - POSTALCODE** (verplicht) Postcode voor identity. - CITY** (verplicht) Woonplaats voor identity. - STATE** (verplicht) State/provincie voor identity. - TEL** (verplicht) Telefoonnummer voor identity. - FAX*** (optioneel) Faxnummer voor identity. - EMAIL (verplicht) E-mailadres voor identity. (toegestane tekens A-Z0-9._%-) - COUNTRY (verplicht) Landcode voor identity. - DATEBIRTH (optioneel) Geboorte datum van de contactpersoon(DD-MM-YYYY). - PLACEBIRTH (optioneel) Geboorteplaats van de contactpersoon. - COUNTRYBIRTH (optioneel) Geboortelandcode (bijvoorbeeld NL of BE). - POSTALBIRTH (optioneel) Geboorteland postcode. - IDNUMBER (optioneel) Alleen van toepassing op particulieren: het identificatie-nummer. - REGNUMBER (optioneel) Alleen van toepassing op bedrijven: kamer van koophandel nummer. - VATNUMBER (optioneel) Alleen van toepassing op bedrijven: BTW nummer. - TMNUMBER (optioneel) Alleen van toepassing op trademarks: identificatie nummer. - TMCOUNTRY (optioneel) Alleen van toepassing op trademarks: trademark land. - IDCARDDATE (optioneel) Id nummer van legitimatiebewijs van contactpersoon. - IDCARDISSUER (optioneel) Uitegevende instantie van het legitimatiebewijs. - XXXMEMBERID (optioneel) Member ID van de sponsored community. - XXXPASSWORD (optioneel) Wachtwoord van XXXMEMBERID. - ENS_ID (optioneel) Luchtvaart ENS ID. Benodigd voor .AERO domeinnamen. - ENS_PASSWORD (optioneel) Wachtwoord van ENS_ID. - PROFESSION (optioneel) Benodigd voor .PRO domeinnamen. - TRAVEL_UIN_ID (optioneel) Benodigd voor .TRAVEL domeinnamen. * Let op, de aanhef is een veld waarbij bijvoorbeeld dhr., mevr., prof, dr, CEO, etc meegegeven kan worden. ** Deze parameter is standaard verplicht, per land is een uitzondering mogelijk (voorbeeld Bonaire). *** Deze parameter is standaard optioneel, per land is een uitzondering mogelijk. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=identity_add& company=Y&company_name=BEDRIJFSNAAM&firstname=VOORNAAM&lastname=ACHTERNAAM& street=STRAAT&number=66&postalcode=POSTCODE&city=WOONPLAATS&country=NL&tel=0123456789& email=ADRES@EXAMPLE.ORG&state=NB&jobtitle=DHR Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>identity_add</command> <status_code>XMLOK 7</status_code> <status_description> De identity is succesvol aangemaakt, de handle vind u in de details </status_description> <price>0.00</price> <details>ABCD123456</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## IDENTITY_DEL ## Beschrijving: Dit commando verwijdert een aangemaakte identity uit het systeem. De betreffende identity kan niet meer gebruikt worden voor nieuwe domeinen; domeinen die reeds gebruik maken van deze identity blijven ongewijzigd. Variabelen: - IDENTITY (verplicht) Handle van de te verwijderen identity. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=identity_del& identity=ABCD123456 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>identity_del</command> <status_code>XMLOK 9</status_code> <status_description>Identity is succesvol verwijdert</status_description> <price>0.00</price> <details>ABCD123456</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## IDENTITY_GET ## Omschrijving: Dit commando geeft alle attributen van een bestaande identity. Variabelen: - IDENTITY (verplicht) De handle van de op te vragen identity. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=identity_get& identity=ABCD123456 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>identity_get</command> <status_code>XMLOK 23</status_code> <status_description>De uitgebreide gegevens vind u in DETAILS</status_description> <price>0.00</price> - <details> <company>Y</company> <company_name>Bedrijfsnaam</company_name> <jobtitle>CEO</jobtitle> <firstname>A</firstname> <lastname>Janssen</lastname> <street>Adres</street> <number>4</number> <suffix /> <postalcode>1234AB</postalcode> <city>STAD</city> <state>NB</state> <tel>0123456789</tel> <fax /> <email>adres@example.org</email> <country>NL</country> <last_updated>07-08-2008 11:06 (d-m-y h:m)</last_updated> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## IDENTITY_LIST ## Beschrijving: Dit commando geeft een lijst met identities. Diverse zoekfunctionaliteiten zijn beschikbaar. Variabelen: - HANDLE (optioneel) Zoekwaarde voor de identity handle. - NAME (optioneel) Zoekwaarde voor de naam. - COMPANY_NAME (optioneel) Zoekwaarde voor bedrijfsnaam. - ALIAS (optioneel) Zoekwaarde voor de alias. - SORTNAME (optioneel) Veld waarop gesorteerd moet worden. - SORTORDER (optioneel) Sorteervolgorde (ASC of DESC). - GLOBAL_SEARCH (optioneel) Zoekwaarde voor alle velden. - START (optioneel) Bij welk veld moet worden begonnen met weergave (standaard: 0). - RECORDS (optioneel) Hoeveel records moeten er worden weergegeven (standaard: 25, -1 is alles). Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=identity_list& sortname=NAME&sortorder=ASC&identity=A&name=A&company_name=A&records=2&start=0 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>identity_list</command> <status_code>XMLOK 22</status_code> <status_description>In DETAILS vind u de uitgebreide informatie</status_description> <price>0.00</price> - <details> <identities_total>100</identities_total> <identities_found>2</identities_found> - <identity> <handle>ABCD123456</handle> <alias>naamalias</alias> <company_name>bedrijfsnaam1</company_name> <name>Achternaam, voornaam</name> </ identity > - < identity > <handle>ABCD654321</handle> <alias>naamalias</alias> <company_name>bedrijfsnaam1.</company_name> <name>Achternaam, voornaam</name> </ identity > </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## IDENTITY_UPD ## Beschrijving: Dit commando werkt de waarden van de attributen van een identity bij. Let op: wijzigingen die van invloed zijn op het formele eigendom van een domeinnaam worden opgevat als een domeinnaam overdracht. Hierom is het niet mogelijk middels het commando IDENTITY_UPD de attributen FIRSTNAME, LASTNAME, COMPANY en COMPANY_NAME te wijzigen. Aanpassingen in deze gegevens kunnen alleen worden volbracht door een nieuw profiel aan te maken en het commando DOMAIN_UPD te voltooien. Variabelen: - IDENTITY (verplicht) Handle ID - Zie commando identity_add voor volledige beschrijving van de variabelen. Indien u een parameter niet opgeeft en deze niet verplicht is worden de waarden geleegd. Afhankelijk van het land kunnen de verplichte velden anders zijn. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&PASS=PASS&command=identity_upd& identity=ABCD123456&street=STRAAT&number=66&postalcode=1234AB&city=WOONPLAATS&state=NB&co untry=NL&tel=0123456789&email=ADRES@EXAMPLE.ORG Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>identity_upd</command> <status_code>XMLOK 8</status_code> <status_description>Identity is succesvol aangepast</status_description> <price>0.00</price> <details>ABCD123456</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## LOCK ## Beschrijving: Dit commando wijzigt de LOCK waarde van een domeinnaam. Variabelen: - SLD (verplicht) Sld van de domeinnaam. - TLD (verplicht) Tld van de domeinnaam. - LOCK (verplicht) Nieuwe LOCK waarde (Y of N). Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=lock&sld=EXAMPLE& tld=ORG&lock=N Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>lock</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 3</status_code> <status_description>Lock voor dit domein is aangepast</status_description> <price>0.00</price> <details>Lock aangepast naar: N</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## NSGROUP_ADD ## Beschrijving: Dit commando voegt een nameservergroep toe aan het systeem. Variabelen: - ALIAS (verplicht) Naam van de nameservergroep. - NS1_FQDN (verplicht) FQDN van de 1e nameserver (Fully Qualified Domain Name). - NS2_FQDN (verplicht) FQDN van de 2e nameserver (Fully Qualified Domain Name). - NS3_FQDN (optioneel) FQDN van de 3e nameserver (Fully Qualified Domain Name). - NS4_FQDN (optioneel) FQDN van de 4e nameserver (Fully Qualified Domain Name). - NS5_FQDN (optioneel) FQDN van de 5e nameserver (Fully Qualified Domain Name). - NS6_FQDN (optioneel) FQDN van de 6e nameserver (Fully Qualified Domain Name). Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=nsgroup_add& alias=NSGROUPNAME&ns1_fqdn=NS1.EXAMPLE.ORG&ns2_fqdn= NS2.EXAMPLE.ORG Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>nsgroup_add</command> <status_code>XMLOK 4</status_code> <status_description> De nameservergroep is succesvol aangemaakt, de handle vind u in de details </status_description> <price>0.00</price> <details>EFGH1234</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## NSGROUP_DEL ## Beschrijving: Dit commando verwijdert een NSGROUP uit het systeem. Er kunnen hier geen nieuwe domeinen mee aangevraagd worden; domeinen die reeds gebruik maken van deze NSGROUP blijven ongewijzigd. Variabelen: - NSGROUP (verplicht) Handle van de te verwijderen nameserver groep. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=nsgroup_del& nsgroup=DEFG456789 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>nsgroup_del</command> <status_code>XMLOK 5</status_code> <status_description>Nameserver group succesvol verwijdert</status_description> <price>0.00</price> <details>YTZJ779672</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## NSGROUP_GET ## Omschrijving: Dit commando geeft de waarden van alle attributen van een NSGROUP. Variabelen: - NSGROUP (verplicht) Handle van de nameserver groep. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=nsgroup_get& nsgroup=DEFG456789 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>nsgroup_get</command> <status_code>XMLOK 25</status_code> <status_description>De uitgebreide gegevens vind u in DETAILS</status_description> <price>0.00</price> - <details> <alias>Managed DNS service</alias> <ns1_fqdn>ns1.example.org</ns1_fqdn> <ns2_fqdn>ns2.example.org</ns2_fqdn> <last_updated>17-12-2009 16:01</last_updated> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## NSGROUP_LIST ## Beschrijving: Dit commando geeft een lijst van alle nameserver groepen. Diverse zoekfunctionaliteiten zijn beschikbaar. Variabelen: - SORTNAME (optioneel) Veld waarop gesorteerd moet worden. - SORTORDER (optioneel) Sorteervolgorde (ASC of DESC). - NSGROUP (optioneel) Zoekwaarde voor de nsgroup handle. - GLOBAL_SEARCH (optioneel) Zoekwaarde voor alle velden. - ALIAS (optioneel) Zoekwaarde voor de naam. - START (optioneel) Bij welk veld moet worden begonnen met weergave (standaard: 0). - RECORDS (optioneel) Hoeveel records moeten er worden weergegeven (standaard: 25, -1 is alles). Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=nsgroup_list Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>nsgroup_list</command> <status_code>XMLOK 24</status_code> <status_description>In DETAILS vind u de uitgebreide informatie</status_description> <price>0.00</price> - <details> <nsgroups_total>5</nsgroups_total> <nsgroups_found>51</nsgroups_found> - <nsgroup> <handle>EFGH1234</handle> <alias>Managed DNS service</alias> - <nameservers> <ns1_fqdn>ns1.thednscompany.com</ns1_fqdn> <ns2_fqdn>ns2.thednscompany.com</ns2_fqdn> <ns3_fqdn>ns3.thednscompany.com</ns3_fqdn> </nameservers> </nsgroup> - <nsgroup> <handle>EFGH1234</handle> <alias>NS2</alias> </nsgroup> - <nsgroup> <handle>EFGH1234</handle> <alias>NS3</alias> </nsgroup> - <nsgroup> <handle>EFGH1234</handle> <alias>NS4</alias> </nsgroup> - <nsgroup> <handle>EFGH1234</handle> <alias>NS5</alias> </nsgroup> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## NSGROUP_UPD ## Beschrijving: Dit commando werkt de waarden van de attributen van een NSGROUP bij. De mutaties worden doorgevoerd op alle domeinen die gebruik maken van het profiel. Variabelen: - NSGROUP (verplicht) Handle van de nameserver groep. - ALIAS (optioneel) Naam van de nameservergroep. - NS1_FQDN (optioneel) FQDN van de 1e nameserver (Fully Qualified Domain Name). - NS2_FQDN (optioneel) FQDN van de 2e nameserver (Fully Qualified Domain Name). - NS3_FQDN (optioneel) FQDN van de 3e nameserver (Fully Qualified Domain Name). - NS4_FQDN (optioneel) FQDN van de 4e nameserver (Fully Qualified Domain Name). - NS5_FQDN (optioneel) FQDN van de 5e nameserver (Fully Qualified Domain Name). - NS6_FQDN (optioneel) FQDN van de 6e nameserver (Fully Qualified Domain Name). Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=nsgroup_upd& ns1_fqdn=NS1.EXAMPLE.ORG&ns2_fqdn= NS2.EXAMPLE.ORG &name=NIEUWENAAM&nsgroup=EFGH1234 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>nsgroup_upd</command> <status_code>XMLOK 6</status_code> <status_description>De nameserver is succesvol aangepast</status_description> <price>0.00</price> <details>EFGH1234</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## ORDER_LIST ## Beschrijving: Dit commando geeft een lijst van orders. Diverse zoekfunctionaliteiten zijn beschikbaar. Als je de status van de FOA wilt weten gebruik dan het veld FOA, deze kan de volgende waarde bevatten: - Y = FOA kan opnieuw verzonden worden, zie commando FOARESEND - N = geen lopende FOA - D = FOA reeds afgerond Variabelen: - START (optioneel) Startveld van de lijstweergave (standaard = 0). - RECORDS (optioneel) Maximaal te tonen records in lijstweergave (standaard = 25, bij een waarde van -1 wordt de volledige lijst getoond). - SORTNAME (optioneel) Veld waarop de lijstweergave gesorteerd wordt. - SORTORDER (optioneel) Sorteervolgorde aflopend of oplopend (ASC / DESC). - ORDER_ID (optioneel) Geeft een zoekstring op voor de orders_is. - SLD (optioneel) Zoekvoorwaarde voor de SLD. - TLD (optioneel) Zoekvoorwaarde voor de TLD. - STATUS (optioneel) Zoekvoorwaarde voor status: (E)rror, (P)ending, (S)uccess. (standaard = A) - TYPE (optioneel) Transfer / register. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=order_list&status=P& type=TRANSFER&sortname=SLD&sortorder=ASC Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>order_list</command> <status_code>XMLOK18</status_code> <status_description>In DETAILS vind u de uitgebreide informatie</status_description> <price>0</price> - <details> <domains_total>1234</domains_total> <domains_found>1</domains_found> - <domain> <orders_id>123456</orders_id> <sld>example1</sld> <tld>org</tld> <status>transfer</status> <type>pending</type> <foa>Y</foa> <description> Oude eigenaar heeft niet op de mail geantwoord, een fax is vereist. </description> <date_created>2009-01-26 11:37:29</date_created> </domain> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## PRICECHECK ## Omschrijving: Dit commando geeft het tarief voor een gegeven API commando en een gegeven TLD. Variabelen: - TLD (verplicht) Tld waarvan de prijs moet worden opgevraagd. - COMMANDNAME (optioneel) Naam van commando, indien niet opgegeven, alle commando’s. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=pricecheck&tld=ORG& commandname=TRANSFER Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>pricecheck</command> <tld>org</tld> <status_code>XMLOK 27</status_code> <status_description>De prijs vind u in de details</status_description> <price>0.00</price> - <details> - <id1> <commandname>transfer</commandname> <tld>org</tld> <price>0.00</price> <period>1</period> <currency>EUR</ currency> </id1> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## QUEUE_GET ## Omschrijving: Dit commando geeft de details van een queue item weer. Variabelen: - QUEUE_ID (verplicht) Het queue_id van het op te vragen item. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=queue_get&queue_id=1 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>cart_get</command> <status_code>XMLOK 49</status_code> <status_description>De informatie vind u in DETAILS</status_description> <price>0</price> - <details> <sld>example</sld> <tld>org</tld> <command>register</command> <amount>1</amount> <identity-admin>ABCD1234</identity-admin> <identity-tech> ABCD1234</identity-tech> <identity-billing> ABCD1234</identity-billing> <identity-registrant> ABCD1234</identity-registrant> <identity-reseller>ABCD1234</identity-reseller> <nsgroup>ABCD1234</nsgroup> <template>ABCD1234</ template > <trustee>N</trustee> <epp></epp> <autorenew>Y</autorenew> <lock>Y</lock> <execution_at>20-11-2018</ execution_at> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## QUEUE_LIST ## Omschrijving: Dit commando geeft de details van een queue item weer. Variabelen: - START (optioneel) Om te bepalen om op te halen vanaf ID x. - RECORDS (optioneel) Het aantal records dat opgehaald moet worden. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=queue_list&start=1&rec ords=50 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>queue_list</command> <status_code>XMLOK 132</status_code> <status_description>De informatie vindt u in DETAILS</status_description> <price/> <details> <queue_total>0</queue_total> <queue_found>0</queue_found> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## QUEUE_UPD ## Omschrijving: Dit commando geeft de details van een queue item weer. Variabelen: - QUEUE_ID (verplicht) Het queue_id van het op te vragen item. - EPP (optioneel) Indien u de verhuiscode (EPP) wilt aanpassen. - EXECUTION_AT (optioneel) Indien u de uitvoerdatum wilt aanpassen. (DD-MM-YYYY) Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=queue_upd&queue_id= 1&epp=12345678&execution_at=20-01-2018 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>queue_upd</command> <status_code>XMLOK 608</status_code> <status_description> Geplande registratie of verhuizing is gewijzigd.</status_description> <price/> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## QUEUE_DEL ## Omschrijving: Dit commando geeft de details van een queue item weer. Variabelen: - QUEUE_ID (verplicht) Het queue_id van het item wat u wilt verwijderen. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=queue_del&queue_id=1 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>queue_del</command> <status_code>XMLOK 604</status_code> <status_description> Geplande registratie of verhuizing is verwijderd.</status_description> <price/> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## REGISTER ## Beschrijving: Registreert een domeinnaam met de opgegeven identities en nsgroup. Vermelde prijs in dit commando is in euros. Variabelen: - IDENTITY-ADMIN (verplicht) Handle van admin identity. - IDENTITY-TECH (optioneel) Handle van tech identity. - IDENTITY-BILLING (optioneel) Handle van billing identity. - IDENTITY-REGISTRANT (verplicht) Handle van registrant identity. - IDENTITY-RESELLER (optioneel) Handle van een reseller (alleen voor .NL) - NSGROUP (verplicht) Handle van de nameserver groep. - DNSTEMPLATE (optioneel) Handle van een template wanneer voor managed dns - SLD (verplicht) Sld van te registreren domein. - TLD (verplicht) Tld van te registreren domein. - PERIOD (verplicht) Registratieperiode in jaren. - AUTORENEW (verplicht) Moet het domein op autorenew staan (Y of N). - LOCK (optioneel) Moet het domein op LOCK staan (Y of N) (default: Y) - USETRUSTEE (optioneel) Moet de trustee service mee besteld worden - PREMIUM_PRICE (optioneel) Exacte premium prijs (enkel voor premium registraties) - EXECUTION_AT (optioneel) Datum waarop de order uitgevoerd wordt (DD-MM-YYYY) Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=register&sld=EXAMPLE &tld=ORG&identity-admin=ABCD123456&identity-tech=ABCD123456&identity-billing=ABCD123456& nsgroup=EFGH1234&dnstemplate=EFGH1234&period=1&autorenew=Y&identity- registrant=ABCD123456&lock=Y Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>register</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 1</status_code> <status_description>Het domein is succesvol geregistreerd</status_description> <price>7.20</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## REGISTER_STATUS ## Beschrijving: Dit commando geeft de status van een aanvraag. Variabelen: - SLD (verplicht) Sld van het te controleren domein. - TLD (verplicht) Tld van het te controleren domein. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=register_status& sld=EXAMPLE&tld=ORG Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>register_status</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 1</status_code> <status_description>Het domein is succesvol geregistreerd</status_description> <price>0.00</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## RENEW ## Beschrijving: Dit commando voert een handmatige verlenging van een domeinnaam uit met een gegeven aantal jaren. Vermelde prijs in dit commando is in euros. Variabelen: - SLD (verplicht) Sld van het domein. - TLD (verplicht) Tld van het domein. - PERIOD (verplicht) Aantal jaren van vernieuwing. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=renew&sld=EXAMPLE& tld=ORG&period=1 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>renew</command> <sld>example</sld> <tld>org</tld> <status_code>XMLOK 14</status_code> <status_description>Renew_periode succesvol aangepast</status_description> <price>7.20</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## RESELLERADD ## Beschrijving: Dit commando voegt een contact profiel aan het systeem toe welke gebruikt kan worden als reseller profiel. Deze informatie zal getoond worden als reseller in de WHOIS informatie van de SIDN (.NL). Variabelen: - ALIAS (verplicht) Alias van de identity. - COMPANY (verplicht) Bedrijfsnaam voor identity. - URL (optioneel) Website van de reseller - FIRSTNAME (verplicht) Voornaam voor identity. - LASTNAME (verplicht) Achternaam voor identity. - STREET (verplicht) Straatnaam voor identity. - NUMBER (verplicht) Huisnummer voor identity. - SUFFIX (optioneel) Toevoeging huisnummer voor identity. - POSTAL (verplicht) Postcode voor identity. - CITY (verplicht) Woonplaats voor identity. - TEL (verplicht) Telefoonnummer voor identity. - EMAIL (verplicht) E-mailadres voor identity. - COUNTRY (verplicht) Landcode voor identity. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=reselleradd& &company_name=BEDRIJFSNAAM&url=URL&firstname=VOORNAAM&lastname=ACHTERNAAM& street=STRAAT&number=66&postal=POSTCODE&city=WOONPLAATS&country=NL&tel=0123456789& email=ADRES@EXAMPLE.ORG Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>reselleradd</command> <status_code>XMLOK 104</status_code> <status_description> Reseller profiel aangemaakt </status_description> <price>0.00</price> <details>ABCD123456</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## RESELLERDEL ## Beschrijving: Dit commando verwijdert een aangemaakte reseller identity uit het systeem. De betreffende identity kan niet meer gebruikt worden voor nieuwe domeinen; domeinen die reeds gebruik maken van deze identity blijven ongewijzigd. Variabelen: - IDENTITY (verplicht) Handle van de te verwijderen identity. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=resellerdel& identity=ABCD123456 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>resellerdel</command> <status_code>XMLOK 105</status_code> <status_description>Reseller profiel verwijderd</status_description> <price>0.00</price> <details>ABCD123456</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## RESELLERGET ## Omschrijving: Dit commando geeft alle attributen van een bestaande reseller identity. Variabelen: - IDENTITY (verplicht) De handle van de op te vragen identity. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=resellerget& identity=ABCD123456 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>resellerget</command> <status_code>XMLOK 23</status_code> <status_description>De uitgebreide gegevens vind u in DETAILS</status_description> <price>0.00</price> - <details> <alias>bedrijfsalias</alias> <company>Bedrijfsnaam</company> <url>www.website.nl</url> <street>Adres</street> <number>4</number> <suffix /> <postalcode>1234AB</postalcode> <city>STAD</city> <tel>0123456789</tel> <email>adres@example.org</email> <country>NL</country> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## RESELLERLIST ## Beschrijving: Dit commando geeft een lijst met reseller identities. Diverse zoekfunctionaliteiten zijn beschikbaar. Variabelen: - HANDLE (optioneel) Zoekwaarde voor de identity handle. - NAME (optioneel) Zoekwaarde voor de naam. - COMPANY_NAME (optioneel) Zoekwaarde voor bedrijfsnaam. - ALIAS (optioneel) Zoekwaarde voor de alias. - SORTNAME (optioneel) Veld waarop gesorteerd moet worden. - SORTORDER (optioneel) Sorteervolgorde (ASC of DESC). - START (optioneel) Bij welk veld moet worden begonnen met weergave (standaard: 0). - RECORDS (optioneel) Hoeveel records moeten er worden weergegeven (standaard: 25, -1 is alles). Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=resellerlist& sortname=NAME&sortorder=ASC&identity=A&name=A&company_name=A&records=2&start=0 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>resellerlist</command> <status_code>XMLOK 22</status_code> <status_description>In DETAILS vind u de uitgebreide informatie</status_description> <price>0.00</price> - <details> <identities_total>100</identities_total> <identities_found>2</identities_found> - <identity> <handle>ABCD123456</handle> <alias>bedrijfsalias</alias> <company>bedrijfsnaam1</company> </ identity > - < identity > <handle>ABCD654321</handle> <alias>bedrijfsalias</alias> <company>bedrijfsnaam1</company> </ identity > </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## RESELLERUPD ## Beschrijving: Dit commando werkt de waarden van de attributen van een reseller identity bij. Variabelen: - Zie commando reselleradd voor volledige beschrijving van de variabelen. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&PASS=PASS&command=identity_upd& identity=ABCD123456&street=STRAAT&number=66&postal=1234AB&city=WOONPLAATS& country=NL&tel=0123456789&email=ADRES@EXAMPLE.ORG Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>identity_upd</command> <status_code>XMLOK 106</status_code> <status_description>Reseller profiel aangepast</status_description> <price>0.00</price> <details>ABCD123456</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SERVER_CREATE ## Beschrijving: Met dit commando kun je een nieuwe server toevoegen voor de auto-validate en auto-install van een SSL- certificaat. Variabelen: - TYPE (verplicht) Type control panel momenteel D = DirectADmin en S = SatServer. - NAME (verplicht) Een naam om de server te omschrijven. - HOST (verplicht) Hostname van de server (alleen verplicht voor DirectAdmin). - USERNAME (verplicht) Gebruikersnaam van de server / reseller of user. - PASSWORD (verplicht) Wachtwoord om mee in te loggen. Voor DirectAdmin kan dit ook een login key met beperkte rechten zijn. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=server_create& type=TYPE&name=NAME&host=HOST&username=USERNAME&password=PASSWORD Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>server_create</command> <status_code>XMLOK 212</status_code> <status_description> Server is aangemaakt </status_description> <price>0.00</price> - <details>2113B9D9-4779-4B4D-9314-A463A33620D5</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SERVER_LIST ## Beschrijving: Met dit commando kun je overzicht generen met alle aangemaakt servers in je account. Variabelen: - SEARCH (optioneel) Doorzoeken van alle servers. - PER_PAGE (optioneel) Aantal resultaten per pagina. - PAGE (optioneel) Pagina die je terug wil zien, verplicht in combinatie met PER_PAGE. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=server_list& search=SEARCH&per_page=PER_PAGE&page=PAGE Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>server_list</command> <status_code>XMLOK 213</status_code> <status_description> In de details vindt je een overzicht van al je servers.</status_description> <price>0.00</price> - <details> - <server> <id>2113B9D9-4779-4B4D-9314-A463A33620D5</id> <type>D</type> <name>Server 1</name> <host>https://www.direct-admin.com:2222</host> <created_at>2021-01-01</created_at> </server> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SERVER_GET ## Beschrijving: Met dit commando kun je de informatie van een server ophalen. Variabelen: - SERVER_ID (verplicht) ID van de server. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=server_get& server_id=SERVER_ID Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>server_get</command> <status_code>XMLOK 214</status_code> <status_description> Server informatie opgehaald.</status_description> <price>0.00</price> - <details> <id>2113B9D9-4779-4B4D-9314-A463A33620D5</id> <type>D</type> <name>Server 1</name> <host>https://www.direct-admin.com:2222</host> <username>mijnserver</username> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SERVER_DELETE ## Beschrijving: Met dit commando kun je een server verwijderen. Variabelen: - SERVER_ID (verplicht) ID van de server. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=server_delete& server_id=SERVER_ID Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>server_get</command> <status_code>XMLOK 215</status_code> <status_description> De server is verwijderd.</status_description> <price>0.00</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SERVER_UPDATE ## Beschrijving: Met dit commando kun je een server aanpassen. Variabelen: - NAME (verplicht) Een naam om de server te omschrijven. - HOST (verplicht) Hostname van de server (alleen verplicht voor DirectAdmin). - USERNAME (verplicht) Gebruikersnaam van de server / reseller of user. - PASSWORD (verplicht) Wachtwoord om mee in te loggen. Voor DirectAdmin kan dit ook een login key met beperkte rechten zijn. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=server_update& server_id=SERVER_ID Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>server_update</command> <status_code>XMLOK 217</status_code> <status_description> Server is aangepast.</status_description> <price>0.00</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SSL_LIST ## Beschrijving: Met dit commando haal je alle SSL op die er in je account staan. Variabelen: - sslid (optioneel) Haal de data van één SSL op, wanneer niet opgegeven dan worden alle SSL’s in je account opgehaald. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_list Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_list</command> <status_code>XMLOK 115</status_code> <status_description>U vind de uitgebreide info in DETAILS</status_description> <price>0</price> - <details> <ssl> <sslid>123</sslid> <product>1</product> <period>2</period> <ssl>Positive SSL</ssl> <identity-organisation>JASDJ12345 </identity-organisation> <identity-tech>JASDJ12345 </identity-tech> <identity-admin>JASDJ12345 </identity- admin> <autorenew>Y</autorenew> <domain>www.domain.nl</domain> <sans>www.site.nl.www.site2.nl</sans> <csr>CSR VAN SSL</csr> <start_date>2014-12-01</start_date> <end_date>2015-12-01</end_date> <status>Active</status> </ssl> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> Wanneer het SSL nog pending is wordt extra validatie informatie meegegeven via onderstaande detail response: Wanneer file auth gekozen is. <authentication> <AuthFileContent></AuthFileContent> <AuthFileName></AuthFileName> </authentication> Wanneer CNAME auth gekozen is. <authentication> <CNAMEAuthValue></CNAMEAuthValue> <CNAMEAuthName></CNAMEAuthName> </authentication> Wanneer email auth gekozen is. <authentication> <ApproverEmail></ApproverEmail> </authentication> ## SSL_AUTORENEW ## Beschrijving: Met die commando kan je de autorenew aan of uit zetten. Wanneer de autorenew uit staan zal het SSL certificaat niet automatisch verlengd worden. Variabelen: - sslid (verplicht) ID van de SSL op te halen met SSL_list. - autorenew (verplicht) Autorenew optie Y of N Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_autorenew&sslid=1 234&autorenew=Y Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_autorenew</command> <status_code>XMLOK 120</status_code> <status_description> De autorenew van het SSL certificaat is aangepast</status_description> <price>0</price> - <details></details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SSL_PRODUCT_LIST ## Beschrijving: Dit commando geeft een lijst terug met alle mogelijke aan te vragen SSL certificaten en hun configuratie. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_product_list Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_product_list</command> <status_code>XMLOK 115</status_code> <status_description>U vind de uitgebreide info in DETAILS</status_description> <price>0</price> - <details> <ssl> <ssl> <id>1</id> <name>Rapid SSL</name> <pricing> <period months=”12”> <price>6.950</price> </period> <period months=”24”> <price>12.950</price> </period> </pricing> <config> <type>DV</type> <wildcard>N</wildcard> <type>DV</type> <wildcard>N</wildcard> <price_extra_domain>N</price_extra_domain> <cname_auth>N</cname_auth> <warranty></warranty> <greenbar></greenbar> <vendor></vendor> <delivery_time></delivery_time> </config> </ssl> </ssl> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SSL_APPROVERLIST ## Beschrijving: Dit commando geeft een lijst met mogelijk validatie email adressen terug aan de hand van de meegegeven CSR. Voor het ophalen van de email adressen dient of een domein of een CSR meegegeven te worden. Variabelen: - ssl (verplicht) Het product ID van de SSL (ophalen met ssl_product_list) - period (verplicht) De aanvraag periode van het SSL in maanden - csr (optioneel) De CSR van de SSL (base64encoded) - domain (optioneel) Hoofd domain van het SSL Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_approverlist&ssl=50 &period=12&csr=CSR&domain=WEBSITE.NL Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_approverlist</command> <status_code>XMLOK 115</status_code> <status_description>U vind de uitgebreide info in DETAILS</status_description> <price>0</price> - <details> <approver>admin@domein.nl</approver> <approver>webmaster@domein.nl</approver> … </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SSL_STATUS ## Beschrijving: Dit commando geeft de status terug van een lopende SSL aanvraag. Variabelen: - sslid (verplicht) ID van de lopende SSL aanvraag Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_status&sslid=1234 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_status</command> <status_code>XMLOK 116</status_code> <status_description> De aanvraag van de SSL is nog niet afgerond</status_description> <price>0</price> <details>Awaiting Validation (Full)</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> De volgende response mogelijkheden zijn er: 1. WF_AUTHORIZATION 2. AUTHORIZATION_FAILED 3. WF_DOMAIN_APPROVAL_ADDRESS 4. WF_DOMAIN_APPROVAL 5. WF_EXTERNAL_APPROVALS 6. SECURITY_REVIEW_FAILED 7. WF_MANUAL_VETTING 8. WF_VETTING_REVIEW 9. CERTGEN_FAILED 10. AWAITING VALIDATION 11. ISSUED 12. VALID 13. COMPLETE 14. REPLACED 15. REVOKED 16. REJECTED 17. EXPIRED ## SSL_EXTENDED_STATUS ## Beschrijving: Dit commando geeft dezelfde status terug van een lopende SSL aanvraag als het commando SSL_STATUS aangevuld met de validatie status en stappen bij bijvoorbeeld Extended Validatie SSL-certificaten. Bij multi- domein SSL-certificaten wordt per domeinnaam (SAN) de status weergegeven. Variabelen: - sslid (verplicht) ID van de lopende SSL aanvraag Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_extended_status&ss lid=1234 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_ extended _status</command> <status_code>XMLOK 116</status_code> <status_description> De aanvraag van de SSL is nog niet afgerond</status_description> <price>0</price> <details>Awaiting Validation (Full)</details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> De volgende response mogelijkheden zijn er: 18. WF_AUTHORIZATION 19. AUTHORIZATION_FAILED 20. WF_DOMAIN_APPROVAL_ADDRESS 21. WF_DOMAIN_APPROVAL 22. WF_EXTERNAL_APPROVALS 23. SECURITY_REVIEW_FAILED 24. WF_MANUAL_VETTING 25. WF_VETTING_REVIEW 26. CERTGEN_FAILED 27. AWAITING VALIDATION 28. ISSUED 29. VALID 30. COMPLETE 31. REPLACED 32. REVOKED 33. REJECTED 34. EXPIRED ## SSL_CANCEL ## Beschrijving: Dit commando geeft de mogelijkheid om aanvragen of nieuwe SSL-certificaten van ten hoogste 30 dagen oud. Variabelen: - sslid (verplicht) ID van de lopende SSL aanvraag Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_cancel &sslid=1234 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_cancel</command> <status_code>XMLOK 148</status_code> <status_description> Het certificaat is geannuleerd.</status_description> </price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SSL_NEW ## Beschrijving: Met dit commando kan je een nieuwe SSL aanvraag starten. Er is de mogelijkheid om een SSL te valideren via een approver email adres of via een file_auth. Bij validatie met de file_auth krijg je na aanvraag een bestandsnaam en inhoud voor het bestand welke je in de root van het domein moet zetten voor validatie dat het domein van jou is. Variabelen: - identity-organisation (verplicht) Houder contact gegevens van SSL - identity-admin (verplicht) Admin contact gegevens van de SSL - identity-tech (verplicht) Tech contact gegevens van SSL - ssl (verplicht) Het ID van het SSL certificaat - period (verplicht) De periode in maanden, uit te lezen via ssl_product_list - csr (verplicht) De CSR van het SSL ceritficaat (base64encoded) - privatekey * (optioneel) De privatekey voor de installatie (base64encoded) - file_auth (optioneel) Enkel verplicht wanneer geen approver opgegeven - approver (optioneel) Enkel verplicht wanneer geen file_auth - sans (optioneel) Komma geschieden lijst van extra SSL domeinen - autorenew (verplicht) Autorenew aan of uit bij aanvraag SSL (waarde Y of N) - renewal_order (optioneel) Meenemen van resterende dagen oude SSL - cname_auth (optioneel) Wanneer je wilt valideren via CNAME - file_auth_https (optioneel) Wanneer je wilt valideren via file met HTTPS - renewal_order_ssl_id (optioneel) Met de bestaande gegevens een SSL verlengen. - client_server_id (optioneel) De server UUID voor de auto-validate en auto-install. * Deze wordt encrypted opgeslagen en 4 weken na installatie verwijderd uit ons systeem. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_new&identity- organisation=IDEN12345&identity-admin=IDEN12345&identity- tech=IDEN12345&ssl=123&period=12&csr=CSR&approver=admin@domain.nl&sans=website.nl,website2.nl&a utorenew=Y&file_auth=Y Voorbeeld: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_new</command> <status_code>XMLOK 119</status_code> <status_description>SSL aanvraag is in behandeling.</status_description> <price>0</price> <details> <sslid>12345</sslid> <filename>validatie.txt</filename> <filecontent>de content voor validatie.txt</filecontent> <cnamevalue>de content voor DNS validatie</cnamevalue> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SSL_REISSUE ## Beschrijving: Met dit commando kan je een her uitgifte aanvragen van je bestaande SSL certificaat. Op dit moment is het nog niet mogelijk om een multi SSL uit te breiden met extra SANS. Variabelen: - sslid (verplicht) Het ID van het SSL certificaat - csr (verplicht) De CSR van het SSL ceritficaat (base64encoded) - file_auth (optioneel) Enkel verplicht wanneer geen approver opgegeven - approver (optioneel) Enkel verplicht wanneer geen file_auth - cname_auth (optioneel) Wanneer je wilt valideren via CNAME (Y/N) - file_auth_https (optioneel) Wanneer de site al een SSL heeft. (Y/N) Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_reissue&sslid=123& csr=CSR&approver=admin@domain.nl&file_auth=Y Voorbeeld: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_reissue</command> <status_code>XMLOK 126</status_code> <status_description> De SSL reissue van het SSL certificaat is in behandeling</status_description> <price>0</price> <details> <sslid>12345</sslid> <filename>validatie.txt</filename> <filecontent>de content voor validatie.txt</filecontent> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SSL_CHANGE_APPROVER ## Beschrijving: Met dit commando kan je een het approver adres aanpassen. Variabelen: - sslid (verplicht) ID van de SSL aanvraag - approver (verplicht) Het nieuwe approver adres Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_change_approver &sslid=1234&approver=nieuw@domein.nl Voorbeeld: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_change_approver</command> <status_code>XMLOK 123</status_code> <status_description> Het approver adres is gewijzigd.</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SSL_DOWNLOAD ## Beschrijving: Met dit commando kan je het SSL certificaat downloaden. De response dien je te base64deconden en daarna op te slaan als een ZIP bestand, Variabelen: - sslid (verplicht) ID van de SSL aanvraag Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_download&sslid=12 34 Voorbeeld: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_download</command> <status_code>XMLOK 121</status_code> <status_description> In het details veld vind je de SSL als base64 string in ZIP formaat.</status_description> <details>BASE64 gecodeerde string welke als ZIP opgeslagen dient te worden</details> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> Simpel PHP voorbeeld downloaden SSL: header($_SERVER['SERVER_PROTOCOL'].' 200 OK'); header("Content-Type: application/zip"); header("Content-Transfer-Encoding: Binary"); header("Content-Disposition: attachment; filename=ssl.zip"); echo base64_decode(‘RESPONSE DOWNLOAD COMMANDO’); ## SSL_RESEND_APPROVER ## Beschrijving: Her sturen van de approver email Variabelen: - sslid (verplicht) ID van de SSL aanvraag Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_resend_approve&ssl id=1234 Voorbeeld: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_resend_approver</command> <status_code>XMLOK 122</status_code> <status_description> Approver resend verzonden.</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## SSL_REVOKE ## Beschrijving: Intrekken van het SSL certificaat. Variabelen: - sslid (verplicht) ID van de SSL aanvraag Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ssl_revoke&sslid=1234 Voorbeeld: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ssl_revoke</command> <status_code>XMLOK 125</status_code> <status_description>De SSL revoke is uitgevoerd.</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## TASK_GET ## Beschrijving: Dit commando geeft de detail gegevens van een openstaande taak en, indien van toepassing, het HTML formulier om de taak af te handelen. Variabelen: - TASK_ID (verplicht) ID nummer van de taak. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=task_get&task_id=999 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>task_get</command> <status_code>XMLOK 48</status_code> <status_description>U vind de uitgebreide info in DETAILS</status_description> <price>0</price> - <details> <sld>example</sld> <tld>org</tld> <description>3 werkdagen wachten op reactie</description> <datetime>2009-01-15 23:30:11</datetime> <type>form</type> - <info> - <![CDATA[ <form>HTML FORM</form> ]]> </info> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## TASK_LIST ## Beschrijving: Dit commando geeft een lijst van alle openstaande taken. Variabelen: - START (optioneel) Taken weergeven vanaf taak nummer... Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=task_list Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>task_list</command> <status_code>XMLOK 22</status_code> <status_description>In DETAILS vind u de uitgebreide informatie</status_description> <price>0</price> - <details> <tasks_total>1</tasks_total> - <task> <description>Verhuisformulieren insturen</description> <sld>example</sld> <tld>org</tld> <datetime>2008-11-14 13:29:52</datetime> - <![CDATA[ <form>HTML FORM</form> ]]> </task> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## TRANSFER ## Beschrijving: Dit commando initieert een domeinnaam verhuizing van een andere provider naar de user account. Vermelde prijs in dit commando is in euros. Variabelen: - SLD (verplicht) Sld van het domein. - TLD (verplicht) Tld van het domein. - TRANS_EPP (optioneel) Eventuele authorisatiecode van het domein. - IDENTITY-ADMIN (verplicht) Handle van de admin identity. - IDENTITY-TECH (optioneel) Handle van de tech identity. - IDENTITY-BILLING (optioneel) Handle van de billing identity. - IDENTITY-REGISTRANT (verplicht) Handle van de registrant identity. - IDENTITY-RESELLER (optioneel) Handle van een reseller (alleen voor .NL) - NSGROUP (verplicht) Handle van de nameserver groep. - PERIOD (verplicht) Registratieperiode in jaren. - USETRUSTEE (optioneel) Moet de trustee service mee besteld worden - PREMIUM_PRICE (optioneel) Exacte premium prijs (enkel voor premium registraties) - EXECUTION_AT (optioneel) Datum waarop de order uitgevoerd wordt (DD-MM-YYYY) - AUTORENEW (optioneel) Y of N. Default waarde bij niet opgeven parameter = Y. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=transfer&sld=EXAMPLE &tld=ORG&trans_epp=EPP_CODE&identity-admin=ABCD1234&identity-tech=ABCD1234& identity-billing=ABCD1234&nsgroup= EFGH1234&period=1&autorenew=Y& identity-registrant=ABCD1234&identity-reseller=ABCD1234 Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>transfer</command> <sld>example</sld> <tld>org</tld> <status_code>XMLPEN 3</status_code> <status_description>Domeinverhuizing is geïnitieerd</status_description> <price>7.20</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## TRANSFER_STATUS ## Beschrijving: Dit commando geeft de status van geïnitieerde verhuizing. Variabelen: - SLD (verplicht) Sld van het domein. - TLD (verplicht) Tld van het domein. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=transfer_status& sld=EXAMPLE&tld=ORG Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>transfer_status</command> <sld>example</sld> <tld>org</tld> <status_code>XMLPEN 4</status_code> <status_description>Transfer Pending - Awaiting Release by Current Registrar</status_description> <price>0.00</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## USER_FUNDS ## Beschrijving: Dit commando geeft een credit overzicht van de onderliggende gebruiker. Variabelen: - USERNAME (optioneel) Filter op gebruikersnaam. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=user_funds Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>user_funds</command> <status_code>XMLOK 44</status_code> <status_description> credits van onderliggende users opgevraagd, de gegevens vind u in de DETAILS </status_description> <price /> - <details> - <user> <username>USER</username> <funds_total>9999.79</funds_total> <funds_reserved>150.00</funds_reserved> <funds_available>9849.79</funds_available> </user> - <user> <username>USER2</username> <funds_total>221.00</funds_total> <funds_reserved /> <funds_available221</funds_available> </user> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## USER_RESET ## Beschrijving: Dit commando maakt een nieuw wachtwoord aan voor de gebruiker en mailt deze naar het email adres van het gekoppelde profiel. Variabelen: - USERNAME (verplicht) Gebruikersnaam van de gebruiker. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=user_reset& username=GEBRUIKERSNAAM Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>user_reset</command> <status_code>XMLOK 53</status_code> <status_description> Er is een nieuw wachtwoord verzonden naar het bij ons bekende e-mail adres </status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## USER_TLD_LIST ## Beschrijving: Dit commando geeft een lijst van toegestane TLD’s en overeenkomende toegestane commando’s. Hiermee kan ondermeer worden opgevraagd of bijvoorbeeld de verhuizing van een bepaalde TLD mogelijk is en of voor een verhuizing een EPP code vereist is. Met de variabel with_price kan je ook de prijs informatie per commando ophalen. Houdt er rekening mee dat dit de API call vertraagt. Naast deze gegevens geeft dit commando ook informatie over de vereiste contactprofielen en mogelijkheden van deze TLD, zoals DNSSEC. Variabelen: - WITH_PRICE (optioneel) Toont per TLD de prijs per commando (langzaam) - CONVERTED (optioneel) Rekent prijzen om naar EUR - TLD (optioneel) Toont één specifieke TLD Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=user_tld_list&with_pric e=Y &converted=EUR Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>user_tld_list</command> <status_code>XMLOK 46</status_code> <status_description>De lijst met TLD's is opgevraagd, u vind ze in de details</status_description> <price>0</price> - <details> <abogado> <register/> <transfer> <lock>Y</lock> <epp>Y</epp> </transfer> <renew/> <domain_restore/> <registrant>Y</registrant> <admin>Y</admin> <billing>Y</billing> <tech>Y</tech> <dnssec>Y</dnssec> <price> <register>127.07</register> <transfer>127.07</transfer> <renew>127.07</renew> <domain_restore>72.63</domain_restore> <currency>EUR</currency> </price> </abogado> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## OWNERCPENDING ## Beschrijving: Toont een lijst met alle lopende owner-c verificaties die nog gevalideerd moeten worden. Variabelen: - WITH_PRICE (optioneel) Toont per TLD de prijs per commando (langzaam) - CONVERTED (optioneel) Rekent prijzen om naar EUR - TLD (optioneel) Toont één specifieke TLD Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ownercpending Uitvoer: Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ownercpending</command> <status_code>XMLOK 153</status_code> <status_description>Lopende ownerc verificaties</status_description> <price>0</price> - <details> <ownerc> <id>123456</id> <email>dummy@dummy.com</email> <send_date>2020-06-15 11:06:30</send_date> <reminded_date/> </ownerc> <ownerc> <id>789023</id> <email>dummy@dummy.com</email> <send_date>2020-06-15 11:06:30</send_date> <reminded_date/> </ownerc> </details> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel> ## OWNERCRESEND ## Beschrijving: Dit commando maakt het mogelijk om een ownerc-verificatie opnieuw te versturen. Let op het is maar eenmaal per 6 uur mogelijk of een verificatie opnieuw te sturen. Variabelen: - id Het ID van de ownerc die je wilt her sturen. Voorbeeld: https://api.oxxa.com/command.php?apiuser=USER&apipassword=PASS&command=ownercresend&id=1234 Uitvoer: Uitvoer: <?xml version="1.0" encoding="ISO-8859-1" ?> - <channel> - <order> <order_id>123456</order_id> <command>ownercresend</command> <status_code>XMLOK 108</status_code> <status_description> Owner-c vertificatie opnieuw verzonden</status_description> <price>0</price> <order_complete>TRUE</order_complete> <done>TRUE</done> </order> </channel>
{% extends 'base.html' %} {% load static %} {% block body %} <div class="container my-3 py-3"> <div class="row"> <div class="col-sm-3"> <div class="card" style="width: 15rem"> <div class="card border border-danger bg-danger text-light" style="width: 15rem" > <div class="card-body"> <h2 class="card-title text-center"> <span id="text_v_likes">{{total_likes}}</span> Likes </h2> </div> </div> </div> </div> <div class="col-sm-3"> <div class="card" style="width: 15rem"> <div class="card border border-danger bg-danger text-light" style="width: 15rem" > <div class="card-body"> <h2 class="card-title text-center"> {{user_data.subscribers.all.count}} Subscribers </h2> </div> </div> </div> </div> <div class="col-sm-3"> <div class="card" style="width: 15rem"> <div class="card border border-danger bg-danger text-light" style="width: 15rem" > <div class="card-body"> <h2 class="card-title text-center"> <span id="text_v_count">{{videos.count}}</span> Videos </h2> </div> </div> </div> </div> <div class="col-sm-3"> <div class="card" style="width: 15rem"> <div class="card border border-danger bg-danger text-light" style="width: 15rem" > <div class="card-body"> <h2 class="card-title text-center"> <span id="text_v_count">{{total_views}}</span> Views </h2> </div> </div> </div> </div> </div> </div> <div class="container"> <div class="d-flex align-items-start"> <div class="nav flex-column nav-pills px-4 py-4 me-3 border" id="v-pills-tab" role="tablist" aria-orientation="vertical" > <a class="nav-link active h5" id="v-pills-home-tab" data-bs-toggle="pill" href="#v-pills-home" role="tab" aria-controls="v-pills-home" aria-selected="true" >Videos</a > <a class="nav-link h5" id="v-pills-profile-tab" data-bs-toggle="pill" href="#v-pills-profile" role="tab" aria-controls="v-pills-profile" aria-selected="false" >Profile</a > </div> <div class="tab-content" id="v-pills-tabContent"> <div class="tab-pane fade show active" id="v-pills-home" role="tabpanel" aria-labelledby="v-pills-home-tab" > <div class="container"> {% for video in videos %} <div class="card my-3 border-dark" id="{{video.id}}"> <h5 class="card-header">{{video.title}}</h5> <div class="card-body"> <img src="{% static video.thumbnail.url %}" class="img-thumbnail w-25" /> <p class="card-text">{{video.desc|truncatewords:5}}</p> <a href="{% url 'watch_video' video.id %}" class="btn btn-primary" >Watch Now</a > <span class="mx-4"> <button class="btn btn-danger"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16" > <path d="M8 2.748l-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z" /> </svg> <b>{{video.likes.count}}</b> </button> <button class="btn btn-warning"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-eye-fill" viewBox="0 0 16 16" > <path d="M10.5 8a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0z" /> <path d="M0 8s3-5.5 8-5.5S16 8 16 8s-3 5.5-8 5.5S0 8 0 8zm8 3.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z" /> </svg> <b>{{video.video_views.count}}</b> </button> <!-- <button class="btn btn-info"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-vector-pen" viewBox="0 0 16 16" > <path fill-rule="evenodd" d="M10.646.646a.5.5 0 0 1 .708 0l4 4a.5.5 0 0 1 0 .708l-1.902 1.902-.829 3.313a1.5 1.5 0 0 1-1.024 1.073L1.254 14.746 4.358 4.4A1.5 1.5 0 0 1 5.43 3.377l3.313-.828L10.646.646zm-1.8 2.908l-3.173.793a.5.5 0 0 0-.358.342l-2.57 8.565 8.567-2.57a.5.5 0 0 0 .34-.357l.794-3.174-3.6-3.6z" /> <path fill-rule="evenodd" d="M2.832 13.228L8 9a1 1 0 1 0-1-1l-4.228 5.168-.026.086.086-.026z" /> </svg> <b>{{video.comment_set.all.count}}</b> </button> --> <button class="btn btn-info" style=" background-color: rgb(49, 215, 49); border-color: rgb(49, 215, 49); " > <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-vector-pen" viewBox="0 0 16 16" > <path fill-rule="evenodd" d="M10.646.646a.5.5 0 0 1 .708 0l4 4a.5.5 0 0 1 0 .708l-1.902 1.902-.829 3.313a1.5 1.5 0 0 1-1.024 1.073L1.254 14.746 4.358 4.4A1.5 1.5 0 0 1 5.43 3.377l3.313-.828L10.646.646zm-1.8 2.908l-3.173.793a.5.5 0 0 0-.358.342l-2.57 8.565 8.567-2.57a.5.5 0 0 0 .34-.357l.794-3.174-3.6-3.6z" /> <path fill-rule="evenodd" d="M2.832 13.228L8 9a1 1 0 1 0-1-1l-4.228 5.168-.026.086.086-.026z" /> </svg> <b>{{video.positive_comment}}</b> </button> <button class="btn btn-info" style=" background-color: rgb(227, 85, 85); border-color: rgb(227, 85, 85); " > <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-vector-pen" viewBox="0 0 16 16" > <path fill-rule="evenodd" d="M10.646.646a.5.5 0 0 1 .708 0l4 4a.5.5 0 0 1 0 .708l-1.902 1.902-.829 3.313a1.5 1.5 0 0 1-1.024 1.073L1.254 14.746 4.358 4.4A1.5 1.5 0 0 1 5.43 3.377l3.313-.828L10.646.646zm-1.8 2.908l-3.173.793a.5.5 0 0 0-.358.342l-2.57 8.565 8.567-2.57a.5.5 0 0 0 .34-.357l.794-3.174-3.6-3.6z" /> <path fill-rule="evenodd" d="M2.832 13.228L8 9a1 1 0 1 0-1-1l-4.228 5.168-.026.086.086-.026z" /> </svg> <b>{{video.negative_comment}}</b> </button> </span> <a class="btn btn-outline-danger mx-2 del_btn" id="{{video.id}}" style="float: right" >Delete</a > <a href="#" class="btn btn-outline-success mx-2" data-bs-toggle="modal" data-bs-target="#exampleModal{{video.id}}" style="float: right" >Edit</a > <!-- Button trigger modal --> <!-- Edit Video Modal --> <div class="modal fade" id="exampleModal{{video.id}}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"> Edit Video Details </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body"> <form action="{% url 'edit_video' video.id %}" method="post" > {% csrf_token %} <div class="form-floating"> <input type="text" placeholder="Title" name="new_title" class="form-control my-2 new_title" id="new_title{{video.id}}" value="{{video.title}}" /> <label for="floatingInput">Title</label> </div> <div class="form-floating"> <textarea class="form-control my-2 new_desc" id="new_desc{{video.id}}" placeholder="Description" name="new_desc" style="height: 300px" > {{video.desc}}</textarea > <label for="floatingInput">Description</label> </div> <div class="form-floating"> <select name="new_cate" class="form-control new_cate" id="new_cate{{video.id}}" name="category" > <option>{{video.category}}</option> <option>Science & Techanology</option> <option>Fashion</option> <option>Food</option> <option>Education</option> <option>Blogs</option> </select> <label for="floatingInput">Category</label> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" > Close </button> <button type="submit" id="edit_btn{{video.id}}" class="btn btn-primary edit_btn" > Save changes </button> </div> </form> </div> </div> </div> </div> </div> </div> {% endfor %} </div> </div> <div class="tab-pane fade" style="width: 800px" id="v-pills-profile" role="tabpanel" aria-labelledby="v-pills-profile-tab" > <div class="container"> <div class="container"> <h3>Additional Data</h3> <form action="{% url 'update_details' %}" method="post" enctype="multipart/form-data" > {% csrf_token %} <div class="row"> <div class="col-sm-8 my-auto"> <input type="file" name="img_field" accept="image/*" class="form-control" /> </div> <div class="col-sm-4"> <b><label>Current Profile Pic</label></b> <img src="{% static user_data.profile_pic.url %}" class="rounded" style="width: 150px; height: 200px" alt="{{user_data.profile_pic}}" /> </div> </div> <div class="row"> <div class="col-sm-8"> <b><label for="about_text">About</label></b> <textarea placeholder="About yourself..." class="form-control" style="height: 100px" name="about_text" > {{user_data.about}}</textarea > </div> </div> <input type="submit" id="update_btn" value="Update" class="btn btn-outline-success my-3" /> </form> </div> <hr /> <div class="container"> <h3 class="text-danger">Danger Zone</h3> <form> <input type="text" name="" placeholder="Type Your Username to Verify" class="form-control" /> <input type="submit" name="" value="Deactivate Your Account" class="btn btn-outline-danger my-3" /> </form> </div> </div> </div> </div> </div> </div> <script type="text/javascript"> var btn = $(".del_btn"); btn.on("click", function (event) { event.preventDefault(); var vid = $(this).attr("id"); var v_count = $("#text_v_count"); var v_likes = $("#text_v_likes"); $.ajax({ type: "GET", url: '{% url "delete_video" %}', data: { videoId: vid }, dataType: "json", success: function (data) { if (data.video_id) { var vid = data.video_id; $("div").remove("#" + vid); v_count.text(data.videosCount); v_likes.text(data.videosLikes); } }, }); }); </script> {% endblock %}
<div class="cards"> <div class="row"> <div class="col-8"> <mat-card *ngFor="let item of dataService.cartItems" class="card-container"> <mat-card-content> <div class="d-flex"> <div class="flex-grow-1"> {{item.courseName}} </div> <div> <button mat-icon-button (click)="addToWishList(item)" title="Add to WishList"> <mat-icon color="primary">playlist_add</mat-icon> </button> <button mat-icon-button (click)="removeFromCart(item)" title="Remove from Cart"> <mat-icon color="warn">delete</mat-icon> </button> </div> </div> </mat-card-content> </mat-card> </div> <div class="col-4"> <mat-card> <mat-card-title>Your Cart</mat-card-title> <mat-card-content *ngIf="dataService.cartItems.length == 0"> No items aded in the Cart! </mat-card-content> <mat-card-content *ngIf="dataService.cartItems.length > 0"> <p *ngIf="dataService.cartItems.length == 1">You have {{dataService.cartItems.length}} item in your cart</p> <p *ngIf="dataService.cartItems.length >1">You have {{dataService.cartItems.length}} items in your cart</p> <div class="total"> SubTotal: <s>&#8377;{{totalAmount}}</s>&nbsp; &#8377;{{discountedAmount}} <br><br> Saved Amount: &#8377;{{savedAmount}} <br> </div> <button mat-raised-button (click)="checkOut()" color="primary" class="full-width"> Checkout <mat-icon>logout</mat-icon> </button> </mat-card-content> </mat-card> </div> </div> </div>