language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C
UTF-8
999
4.34375
4
[]
no_license
//Reference https://www.geeksforgeeks.org/quick-sort/ #include <stdio.h> void swap(int *a, int *b) { //swapping using pointers //t = temporal variable to store int a int t = *a; *a = *b; *b = t; } int partition(int *arr, int low, int high) { int pivot_elem = arr[high]; int min_elem = (low - 1); for (int i = low; i <= high - 1; i++) { if (arr[i] < pivot_elem) { min_elem++; swap(&arr[min_elem], &arr[i]); } } swap(&arr[min_elem + 1], &arr[high]); return (min_elem + 1); } void quick_sort(int *arr, int low, int high) { if (low < high) { int ind = partition(arr, low, high); //sorting before partitions quick_sort(arr, low, ind-1); quick_sort(arr, ind + 1, high); } } int main() { int arr [] = {22, 88, 2, 0, 12, 20}; int len = sizeof(arr)/sizeof(arr[0]); //low value int low = 0; //high value int high = len - 1; quick_sort(arr, low, high); for(int i = 0; i < len; i++) { printf("%d\n", arr[i]); } return 0; }
Markdown
UTF-8
1,939
3.265625
3
[]
no_license
# Simple Container project Python sucks ! Well the language is OK but the damn environment mess is a disaster. Try to use multiple projects on your machine lands you in hell. The solution - containerize your projects. The docker lab example is fine but there's a few bugs - so this is the simple guide with fixes and gotchas. ## The app Create the following directory structure with two files, requirements.txt and server.py. Note: the docker website code example had a couple of issues. The code sample had a misplaced indent and the code returned a null response. This is fixed in the example below. ``` app ├─── requirements.txt └─── src └─── server.py ``` In server.py add the following ``` from flask import Flask import os server = Flask(__name__) @server.route("/") def hello(): return "Hello World!" if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) server.run(debug=True,host='0.0.0.0',port=port) ``` In the requirements.txt file add the dependencies ``` Flask==1.1.1 ``` In the app root directory create a Dockerfile and add the following instructions. ``` # set base image (host OS) FROM python:3.8 # set the working directory in the container WORKDIR /code # copy the dependencies file to the working directory COPY requirements.txt . # install dependencies RUN pip install -r requirements.txt # copy the content of the local src directory to the working directory COPY src/ . # command to run on container start CMD [ "python", "./server.py" ] ``` Now build the docker image ``` docker build -t myimage . ``` List the images ``` docker images ``` Run the image ``` docker run -d -p 5000:5000 myimage ``` Check the container is running ``` docker ps -a ``` Check the logs if the container fails ``` docker logs <container_name> ``` If the container is running - test the app using cURL ``` curl http://localhost:5000 ```
Python
UTF-8
491
3.671875
4
[]
no_license
""" 문제 첫째 줄에는 별 1개, 둘째 줄에는 별 3개, ..., N번째 줄에는 별 2*N-1개를 찍는 문제 별은 가운데를 기준으로 대칭이어야 한다. 입력 첫째 줄에 N (1<=N<=100)이 주어진다. 출력 첫째 줄부터 N번째 줄 까지 차례대로 별을 출력한다. 예제 입력 1 5 예제 출력 1 * *** ***** ******* ********* """ N=int(input()) a=1 for i in range(0, N): print(" "*(N-1), end="") print("*"*a) N-=1 a+=2
Java
UTF-8
1,615
3.546875
4
[]
no_license
package com.youmu.maven.Algorithm.leetcode; public class S1190 { public String reverseParentheses(String s) { char[] stack = new char[s.length()]; int top = 0; for (int x = 0; x < s.length(); x++) { char c = s.charAt(x); if (c != ')') { stack[top++] = c; } else { for (int i = top - 1; i < top && i >= 0; i--) { if (stack[i] == '(') { //找到第一个( //翻转后退栈一个元素,这个元素将是( reverse(stack, i, top); top--; break; } } } } return new String(stack, 0, top); } private void reverse(char[] arr, int start, /*exclusive*/int end) { for (int i = start, j = end - 1; i < j; i++, j--) { char t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } public static void main(String[] args) { S1190 s1190 = new S1190(); System.out.println(s1190.reverseParentheses("(abcd)")); System.out.println(s1190.reverseParentheses("(u(love)i)")); System.out.println(s1190.reverseParentheses("(ed(et(oc))el)")); System.out.println(s1190.reverseParentheses("a(bcdefghijkl(mno)p)q")); System.out.println(s1190.reverseParentheses("ta()usw((((a))))")); // char[] chars = "ta()usw((((a))))".toCharArray(); // s1190.reverse(chars, 0, chars.length); // System.out.println(chars); } }
C#
UTF-8
3,192
2.59375
3
[]
no_license
using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using nucleocs.DTO; using nucleocs.Models; namespace nucleocs.MVDTO{ public class MVProduct{ public int ProductId { get; set; } public string Name { get; set; } public double WidthMin { get; set; }//largura minima public double WidthMax { get; set; }//largura maxima public double HeightMin { get; set; }//altura minima public double HeightMax { get; set; }//altura maxima public double DepthMin { get; set; }//profundidade minima public double DepthMax { get; set; }//profundidade maxima public double Weight { get; set; } public double Price { get; set; } public IEnumTypeProd DimensionType { get; set; } public MVCategory Category { get; set; } public ICollection<MVMaterial> MvMaterial { get; set; } public ICollection<MVAggregation> MVProductsSon { get; set; } public MVProduct(){} public MVProduct(int productId, string name, MVCategory category){ this.ProductId = productId; this.Name = name; this.Category = category; } public MVProduct(int productId, string name, double widthMin, double widthMax, double heightMin, double heightMax, double depthMin, double depthMax, double weight, double price, IEnumTypeProd dimensionType, MVCategory categoryMV, ICollection<MVMaterial> materialMV, ICollection<MVAggregation> productsSonMV){ this.ProductId = productId; this.Name = name; this.WidthMin = widthMin; this.WidthMax = widthMax; this.HeightMin = heightMin; this.HeightMax = heightMax; this.DepthMax = depthMax; this.DepthMin = depthMin; this.Weight = weight; this.Price = price; this.DimensionType = dimensionType; this.Category = categoryMV; this.MvMaterial = new List<MVMaterial>(materialMV); this.MVProductsSon = new List<MVAggregation>(productsSonMV); } public static MVProduct FromFull(ProductDTO p){ var material = new List<MVMaterial>(); var category = MVCategory.From(p.CategoryD); var productsSon = new List<MVAggregation>(); foreach(var mt in p.MaterialD){ material.Add(MVMaterial.From(mt)); } foreach (var agg in p.ProductsSon) { if(agg.RestrictionsDTO.Count != 0) productsSon.Add(MVAggregation.From(agg)); } return new MVProduct(p.ProductId, p.Name, p.WidthMin, p.WidthMax, p.HeightMin, p.HeightMax, p.DepthMin, p.DepthMax, p.Weight, p.Price, p.DimensionType, category, material, productsSon); } public static MVProduct FromLitle(ProductDTO p){ var category = MVCategory.From(p.CategoryD); return new MVProduct(p.ProductId, p.Name, category); } } }
Java
UTF-8
6,556
2.75
3
[]
no_license
package salesforce.core.selenium; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; public class WebDriverTools { private final String JS_SCRIPT = "document.querySelector(\"a[title='%s']\").click();"; private WebDriver driver; private WebDriverWait wait; public WebDriverTools() { this.driver = WebDriverManager.getInstance().getWebDriver(); this.wait = WebDriverManager.getInstance().getWait(); } /** * Waits and clear the WebElement * * @param webElement WebElement to wait and clear */ public void clearTextField(WebElement webElement) { wait.until(ExpectedConditions.visibilityOf(webElement)); webElement.clear(); } /** * Sets an Input Field. * * @param webElement Input WebElement * @param text Text to fill */ public void setInputField(WebElement webElement, String text) { wait.until(ExpectedConditions.visibilityOf(webElement)); clearTextField(webElement); webElement.sendKeys(text); } /** * Waits and click on the webElement. * * @param webElement WebElement to wait and click */ public void clickElement(WebElement webElement) { wait.until(ExpectedConditions.elementToBeClickable(webElement)); wait.until(ExpectedConditions.visibilityOf(webElement)); webElement.click(); } /** * Waits and click on the webElement. * * @param by By to wait and click */ public void clickElement(By by) { wait.until(ExpectedConditions.visibilityOfElementLocated(by)); wait.until(ExpectedConditions.elementToBeClickable(by)); driver.findElement(by).click(); } /** * Wits and gets the text of a WebElement * * @param webElement WebElement to wait and get the text * @return Text of the WebElement */ public String getTextElement(WebElement webElement) { wait.until(ExpectedConditions.visibilityOf(webElement)); return webElement.getText(); } /** * Verifies if the WebElement is displayed * * @param webElement WebElement * @return True if the WebElement is displayed */ public boolean isElementDisplayed(WebElement webElement) { wait.until(ExpectedConditions.visibilityOf(webElement)); return webElement.isDisplayed(); } /** * Verifies if the WebElement is selected * * @param element WebElement * @return True if the WebElement is selected */ public boolean isElementSelected(WebElement element) { wait.until(ExpectedConditions.elementToBeClickable(element)); return element.isSelected(); } /** * Selects the checkBox * * @param element WebElement */ public void selectCheckBox(WebElement element) { if (!isElementSelected(element)) { clickElement(element); } } /** * Clears the checkBox * * @param element WebElement */ public void clearCheckBox(WebElement element) { if (isElementSelected(element)) { clickElement(element); } } /** * <p>This method performs selection of element of a list.</p> * * @param webElements is a lis of WebElement elements. * @param keyWord is the value to compare element attribute with. */ public void selectElementInList(List<WebElement> webElements, String keyWord) { for (WebElement element : webElements) { String value = element.getText(); if (value.contains(keyWord)) { clickElement(element); break; } } } /** * <p>This method performs selection of value inside a dropdown list.</p> * * @param dropDown is the dropdown web element given. * @param value is the value to select. */ public void selectDropDownValue(WebElement dropDown, String value) { Select selector = new Select(dropDown); wait.until(ExpectedConditions.visibilityOf(dropDown)); selector.selectByValue(value); } /** * <p>This method performs selection of text inside a dropdown list.</p> * * @param dropDown is the dropdown web element given. * @param text is the text to select. */ public void selectDropDownLinkText(WebElement dropDown, String text) { Select selector = new Select(dropDown); wait.until(ExpectedConditions.visibilityOf(dropDown)); selector.selectByVisibleText(text); } /** * Wait until the item is no longer visible. * * @param element WebElement. */ public void waitUntilMessageDisappear(WebElement element) { try { while (element.isDisplayed()) { } } catch (Exception e) { } } /** * Wait until the item is no longer visible. * * @param by By of the WebElement. */ public void waitUntilMessageDisappear(By by) { try { WebElement message= driver.findElement(by); while (message.isDisplayed()) { } } catch (Exception e) { } } /** * Check when an element is displayed. * * @param by is the xpath. * @return as a boolean. */ public boolean isElementDisplayed(By by) { WebElement webElement = driver.findElement(by); return isElementDisplayed(webElement); } /** * Check when an element is visible. * * @param by is the path. * @return as a boolean. */ public boolean isElementVisibility(By by) { try { return isElementDisplayed(by); } catch (Exception e) { return false; } } /** * Wait until an element is available by xpath. * * @param by is the xpath. */ public void waitUntilAvailable(By by) { WebElement webElement = driver.findElement(by); waitAvailable(webElement); } /** * Wait until an element is available by element. * * @param element is the element. */ public void waitUntilAvailable(WebElement element) { waitAvailable(element); } /** * Wait until a element is visible and clickable. * * @param element is the element. */ public void waitAvailable(WebElement element) { wait.until(ExpectedConditions.elementToBeClickable(element)); } /** * This method perform a click in a non visible element in the UI using class locator. * * @param webElement the WebElement non visible in the UI. */ public void jsClickClassButton(WebElement webElement) { ((JavascriptExecutor) driver) .executeScript("arguments[0].click();", webElement); } }
Java
UTF-8
5,153
2.296875
2
[]
no_license
package com.xdx97.bean; import com.fasterxml.jackson.annotation.JsonFormat; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; import java.util.Date; /** * msg_info * @author */ public class MsgInfo implements Serializable { /** * 消息id */ private String id; /** * 客服账号 */ private String kfId; /** * 客服名称 */ private String kfName; /** * 用户id */ private String userId; /** * 用户名 */ private String userName; /** * 消息内容 */ private String content; /** * 消息发送时间 */ @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime; /** * 是否已读(1 已读) */ private Integer unReadFlag; /** * 来源1客服 0用户 */ private Integer source; private static final long serialVersionUID = 1L; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getKfId() { return kfId; } public void setKfId(String kfId) { this.kfId = kfId; } public String getKfName() { return kfName; } public void setKfName(String kfName) { this.kfName = kfName; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getUnReadFlag() { return unReadFlag; } public void setUnReadFlag(Integer unReadFlag) { this.unReadFlag = unReadFlag; } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } MsgInfo other = (MsgInfo) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getKfId() == null ? other.getKfId() == null : this.getKfId().equals(other.getKfId())) && (this.getKfName() == null ? other.getKfName() == null : this.getKfName().equals(other.getKfName())) && (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId())) && (this.getUserName() == null ? other.getUserName() == null : this.getUserName().equals(other.getUserName())) && (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent())) && (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime())) && (this.getUnReadFlag() == null ? other.getUnReadFlag() == null : this.getUnReadFlag().equals(other.getUnReadFlag())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getKfId() == null) ? 0 : getKfId().hashCode()); result = prime * result + ((getKfName() == null) ? 0 : getKfName().hashCode()); result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode()); result = prime * result + ((getUserName() == null) ? 0 : getUserName().hashCode()); result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode()); result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode()); result = prime * result + ((getUnReadFlag() == null) ? 0 : getUnReadFlag().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", kfId=").append(kfId); sb.append(", kfName=").append(kfName); sb.append(", userId=").append(userId); sb.append(", userName=").append(userName); sb.append(", content=").append(content); sb.append(", createTime=").append(createTime); sb.append(", unReadFlag=").append(unReadFlag); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } public Integer getSource() { return source; } public void setSource(Integer source) { this.source = source; } }
TypeScript
UTF-8
867
2.6875
3
[ "MIT" ]
permissive
import FS from 'fs-extra'; import path from 'path'; import { getTrendingData, ITrendingData } from './utils/index.js'; async function saveTrendingData(data: ITrendingData[], type: string = 'daily') { await FS.outputFile(path.join(process.cwd(), 'dist', `trending-${type}.json`), JSON.stringify(data, null, 2)); } ;(async () => { let data: ITrendingData[] = await getTrendingData('daily'); await saveTrendingData(data); console.log(`> 共获取 \x1b[32;1m${data.length}\x1b[0m 个日趋势榜数据!`); data = await getTrendingData('weekly'); await saveTrendingData(data, 'weekly'); console.log(`> 共获取 \x1b[32;1m${data.length}\x1b[0m 个周趋势榜数据!`); data = await getTrendingData('monthly'); await saveTrendingData(data, 'monthly'); console.log(`> 共获取 \x1b[32;1m${data.length}\x1b[0m 个月趋势榜数据!`); })();
Markdown
UTF-8
7,097
2.59375
3
[]
no_license
--- published: true layout: default-theme-wet-boew-fr title: Envelopper et tronquer le texte hide_breadcrumb: false date_modified: 2019-04-11 --- {::nomarkdown} {% raw %} <span class="wb-prettify all-pre"></span> <div class="row"> <nav role="navigation" class="col-md-8"> <div class="panel panel-default"> <header class="panel-heading"> <h2 class="panel-title">Table des matières</h2> </header> <div class="panel-body"> <ul> <li><a href="#purpose">Usage</a></li> <li><a href="#design">Conception et codage</a> <ul> <li><a href="#basic">Utilisation de base</a></li> <li><a href="#enhanced">Utilisation améliorée</a></li> </ul> </li> </ul> </div> </div> </nav> <section class="col-md-4"> <div class="panel panel-warning"> <div class="panel-body"> <h2 class="mrgn-tp-0 h4 text-warning"><span class="fa fa-exclamation-triangle"></span> Chantier</h2> <p>Cette page est en chantier.</p> <p>Veuillez <a href="https://github.com/wet-boew/wet-boew-styleguide/issues/new">transmettre un problème</a> ou soumettre une demande de tirage s'il manque des renseignements ou des codes ou si la synchronisation est incorrecte ou déphasée avec le principal référentiel (wet-boew/wet-boew).</p> </div> </div> </section> </div> <h2 id="purpose"><span class="fa-stack"><span class="fa fa-circle fa-stack-2x"></span><span class="fa fa-info fa-stack-1x fa-inverse"></span></span> Usage</h2> <p>Les utiliser pour empêcher que du texte retourne à la ligne suivante.</p> <h2 id="design"><span class="fa-stack"><span class="fa fa-circle fa-stack-2x"></span><span class="fa fa-paint-brush fa-stack-1x fa-inverse"></span></span> Conception et codage</h2> <h3 id="basic">Utilisation de base</h3> <h4 id="default"><span class="fa-stack"><span class="fa fa-circle fa-stack-2x"></span><span class="fas fa-cogs fa-stack-1x fa-inverse"></span></span> Défaut</h4> <p>S'en servir pour contrôler où et comment les mots retournent automatiquement à la ligne suivante à l'intérieur d'une ligne de texte. </p> <div class="row"> <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-body"> <h5 class="mrgn-tp-0">Apparence</h5> <p>Défaut :</p> <p>Lorem ipsum dolor sit amet, consectetur <strong>30 avril</strong>.</p> <p class="mrgn-tp-lg">Avec <code>.nowrap</code> :</p> <p>Lorem ipsum dolor sit amet, consectetur <span class="nowrap"><strong>30 avril</strong></span>.</p> </div> </div> </div> <div class="col-md-4"> <h5 class="mrgn-tp-0 text-success"><span class="glyphicon glyphicon-ok-circle"></span> Bonne utilisation</h5> <p><span class="nowrap">Points de conformité&nbsp;:</span></p> <ul> <li>L'utiliser pour empêcher que des éléments de contenu comme le numéro de téléphone, le code postal, une équation mathématique, une date et la ponctuation française (le deux-points, les crochets et les autres éléments qui nécessitent des espaces) retournent automatiquement à la ligne suivante sur plusieurs lignes</li> <li>Rappelez-vous que la page est réactive à la largeur du navigateur <ul> <li>Le texte retourne automatiquement à la ligne suivante à des points différents sur des appareils et des espaces de visionnement différents</li> <li>Ajoutez <code>.nowrap</code> pour convenir aux résolutions différentes</li> </ul> </li> </ul> <h5 class="mrgn-tp-0 text-danger"><span class="glyphicon glyphicon-remove-circle"></span> Mauvaise utilisation</h5> <p><span class="nowrap">Points de conformité&nbsp;:</span></p> <ul> <li>N'utilisez pas cet élément d'une façon qui entre en conflit avec <span class="nowrap">les points</span> de conformité <span class="nowrap">précédents</span></li> <li>Ne l'utilisez pas pour renvoyer automatiquement des phrases complètes à la ligne suivante</li> <li>Ne l'utilisez pas pour l'information non textuelle</li> </ul> </div> <div class="col-md-4"> <h5 class="mrgn-tp-0">Code</h5> <pre><code>&lt;p&gt;... &lt;span<strong> class=&quot;nowrap&quot;</strong>&gt;30 avril&lt;/span&gt;.&lt;/p&gt;</code></pre> </div> </div> <h3 id="enhanced">Utilisation améliorée</h3> <h4 id="default"><span class="fa-stack"><span class="fa fa-circle fa-stack-2x"></span><span class="fa fa-ellipsis-h fa-stack-1x fa-inverse"></span></span> Tronqué</h4> <p>Utiliser pour tronquer le texte pour qu'il s'insère dans une colonne de grille sur une seule ligne. Tout texte au-delà de la bordure de la grille sera recadré et remplacé par un trois points. Le texte disparaît seulement visuellement, il peut cependant toujours être lu par les lecteurs d'écran.</p> <div class="row"> <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-body"> <h5 class="mrgn-tp-0">Apparence</h5> <p>Défaut :</p> <p>Lorem ipsum dolor sit amet, consectetur <strong>30 avril</strong>.</p> <p>Avec <code>.wb-elps</code> : <p class="wb-elps">Lorem ipsum dolor sit amet, consectetur <strong>30 avril</strong>.</p> </div> </div> </div> <div class="col-md-4"> <h5 class="mrgn-tp-0 text-success"><span class="glyphicon glyphicon-ok-circle"></span> Bonne utilisation</h5> <p>Point de conformité :</p> <ul> <li>Utilisez principalement avec des hyperliens pour prévenir un retour automatique à la ligne (si la hauteur est une préoccupation et que <code>.wb-eqht</code> ne peut être appliqué) ou s'il affiche en dehors des colonnes d'une grille (quand <code>.nowrap</code> est appliqué)</li> </ul> <h5 class="mrgn-tp-0 text-danger"><span class="glyphicon glyphicon-remove-circle"></span> Mauvaise utilisation</h5> <p>Points de conformité :</p> <ul> <li>Ne pas utiliser ce style pour des phrases, car il peut cacher des informations à un utilisateur visuel</li> <li>Ne pas utiliser à la place de <code>.wb-eqht</code> lorsque vous tentez d'obtenir une hauteur égale sur une rangée de grille</li> <li>N'utilisez pas cet élément d'une façon qui entre en conflit avec le point de conformité précédent</li> </ul> </div> <div class="col-md-4"> <h5 class="mrgn-tp-0">Code</h5> <pre>&lt;p class=&quot;wb-elps&quot;&gt;...&lt;/p&gt;</pre> </div> </div> <!-- SEARCH CONTENT ENDS / CONTENU RECHERCHE TERMINE --> <!--[if gte IE 9 | !IE ]><!--> <script src="/wet40/js/jquery.js"></script> <script src="/wet40/js/wet-boew.min.js"></script> <!--<![endif]--> <!--[if lt IE 9]> <script src="/wet40/js/ie8-wet-boew2.min.js"></script> <![endif]--> <script src="/wet40/js/theme.min.js"></script> </body> </html> {% endraw %} {:/}
Java
UTF-8
846
1.820313
2
[]
no_license
package test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import test.testsaplicacion.AplicacionTest; import test.testsarticulos.MenudenciaTest; import test.testsarticulos.VoluminosoTest; import test.testspersona.ClienteTest; import test.testspersona.EstandarTest; import test.testsventas.SubastaTest; import test.testsventas.VentaDomicilioTest; import test.testsventas.VentaTest; /** * @author Javier Gomez &lt;javier.gomezmartinez@estudiante.uam.es&gt; * @author Carlos Li &lt;carlos.li@estudiante.uam.es&gt; * * Test secuencial de las pruebas unitarias */ @RunWith(Suite.class) @SuiteClasses({ AplicacionTest.class, MenudenciaTest.class, VoluminosoTest.class, ClienteTest.class, EstandarTest.class, SubastaTest.class, VentaDomicilioTest.class, VentaTest.class }) public class AllTest { }
Java
UTF-8
3,254
1.945313
2
[]
no_license
package com.example.vaibhav.udhaar; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class Main5Activity extends AppCompatActivity { private TextView reqinfo; private Button accept; private DatabaseReference m4; private EditText accnum; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main5); reqinfo=(TextView)findViewById(R.id.textView7); accept=(Button)findViewById(R.id.button7); m4= FirebaseDatabase.getInstance().getReference(); accnum=(EditText)findViewById(R.id.editText2); Bundle bundle=getIntent().getExtras(); if(bundle!=null){ reqinfo.setText(bundle.getString("RequestInfo")); } String x=bundle.getString("RequestInfo"); // char a[]=x.toCharArray(); accept.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String accnum1=accnum.getText().toString(); Bundle bundle=getIntent().getExtras(); String phone = bundle.getString("Phone"); String reqmail=bundle.getString("reqmail"); reqmail=reqmail.replace(".",","); m4.child("Pending").child(reqmail).setValue(accnum1); FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); String mail = user.getEmail(); String TruecurrentUser = mail.replace(".", ","); m4.child("Lenders").child(TruecurrentUser).child("Pender").setValue(reqmail); m4.child("Accepted").child(reqmail).setValue(accnum1); ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("number",phone); clipboard.setPrimaryClip(clip); Toast.makeText(Main5Activity.this,"Phone number copied to ClipBoard",Toast.LENGTH_LONG).show(); try{ Intent i = new Intent(Intent.ACTION_MAIN); PackageManager managerclock = getPackageManager(); i = managerclock.getLaunchIntentForPackage("net.one97.paytm"); i.addCategory(Intent.CATEGORY_LAUNCHER); startActivity(i); }catch(Exception e){ reqinfo.setText(bundle.getString("RequestInfo")+" \nPhone number has been copied to clipboard :)"); Toast.makeText(Main5Activity.this,"Please install the Paytm App",Toast.LENGTH_LONG).show(); } } }); } }
SQL
UTF-8
58,122
3.3125
3
[]
no_license
# создаем таблицы CREATE TABLE Out_categories ( outcome_id integer NOT NULL PRIMARY KEY, outcome_count varchar(50) NOT NULL ); CREATE TABLE Inc_categories ( income_id integer NOT NULL PRIMARY KEY, income_count varchar(50) NOT NULL ); CREATE TABLE Outcome ( outcome_num varchar(50) NOT NULL PRIMARY KEY, count varchar(50) NOT NULL, category integer REFERENCES Out_categories(outcome_id), amount real NOT NULL, date timestamp NOT NULL, tag varchar(100) ); CREATE TABLE Income ( income_num varchar(50) NOT NULL PRIMARY KEY, count varchar(50) NOT NULL, category integer REFERENCES Inc_categories(income_id), amount real NOT NULL, date timestamp NOT NULL, tag varchar(100) ); #Вносим данные в таблицу Inc_categories: INSERT INTO Inc_categories (income_id, income_count) VALUES (1, 'Работа Лев'); INSERT INTO Inc_categories (income_id, income_count) VALUES (2, 'Работа Юля'); INSERT INTO Inc_categories (income_id, income_count) VALUES (3, 'Пассивный доход'); INSERT INTO Inc_categories (income_id, income_count) VALUES (4, 'Налоговый вычет'); INSERT INTO Inc_categories (income_id, income_count) VALUES (5, 'Продажа вещей'); INSERT INTO Inc_categories (income_id, income_count) VALUES (6, 'Подарки'); INSERT INTO Inc_categories (income_id, income_count) VALUES (7, 'Прочие источники'); INSERT INTO Inc_categories (income_id, income_count) VALUES (8, 'Премия'); INSERT INTO Inc_categories (income_id, income_count) VALUES (9, 'Возмещения по работе Лев'); INSERT INTO Inc_categories (income_id, income_count) VALUES (10, 'Дивиденды'); #Вносим данные в таблицу Out_categories: INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33000, 'Без категории'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33001, 'Коммуникации'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33002, 'Сотовая связь'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33003, 'Интернет'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33004, 'Транспорт'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33005, 'Такси'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33006, 'Общественный транспорт'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33007, 'Рекс'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33008, 'Электричка'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33009, 'Автобусы/троллейбусы/трамваи'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33010, 'Метро'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33011, 'Транспорт по работе'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33012, 'Транспорт при путешествиях'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33013, 'Психотропы'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33014, 'Алкоголь'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33015, 'Курение'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33016, 'Обустройство и ремонт'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33017, 'Посуда'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33018, 'Мебель'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33019, 'Растения'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33020, 'Инструменты'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33021, 'Стройматериалы'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33022, 'Химчистка'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33023, 'Расходные материалы'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33024, 'Бытовая техника'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33025, 'Ремонт одежды и обуви'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33026, 'Банковские услуги'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33027, 'Красота'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33028, 'Солярий'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33029, 'Косметика'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33030, 'Процедуры'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33031, 'Парикмахер'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33032, 'Здоровье'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33033, 'Аптека'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33034, 'Медицинские услуги'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33035, 'Судебные издержки'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33036, 'Проезд адвоката'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33037, 'Оплата адвокату'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33038, 'Налоги, пошлины, штрафы'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33039, 'Содержание квартиры'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33040, 'ЖКУ'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33041, 'Страхование квартиры'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33042, 'Подарки'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33043, 'Подарки семье (мы)'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33044, 'Подарки родным (родители)'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33045, 'Подарки на работе'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33046, 'Подарки друзьям'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33047, 'Пресса и книги'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33048, 'Журналы'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33049, 'Книги'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33050, 'Возврат долгов'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33051, 'Живность'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33052, 'Аквариум'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33053, 'Сувениры'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33054, 'Одежда/Аксессуары (сумки и т.д.)'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33055, 'Физкультура'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33056, 'Оплата посещений'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33057, 'Спортивная форма'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33058, 'Спортпит'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33059, 'Автомобиль'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33060, 'Досуг'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33061, 'Софт'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33062, 'Питание'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33063, 'Продукты'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33064, 'Кафе'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33065, 'Вода'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33066, 'Бытовая химия'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33067, 'Правовые услуги'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33068, 'Нотариус'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33069, 'Заказ декларации и пр. услуги'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33070, 'Оценка квартиры'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33071, 'Канцтовары'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33072, 'Кредиты'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33073, 'Кредитка'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33074, 'Ипотека'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33075, 'Страхование'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33076, 'Обучение'); INSERT INTO Out_categories (outcome_id, outcome_count) VALUES (33077, 'Инвестиции'); #Вносим данные в таблицу Income: INSERT INTO Income (income_num, count, category, amount, date, tag) VALUES ('outid00269', 'Кошелёк Юля', 2, 15000, '2018-09-28', ''); INSERT INTO Income (income_num, count, category, amount, date, tag) VALUES ('outid00268', 'Карта ВТБ 5906 Юля', 2, 17500, '2018-09-28', ''); INSERT INTO Income (income_num, count, category, amount, date, tag) VALUES ('outid00267', 'Карта 0013 Лев', 1 , 44100, '2018-09-25', ''); INSERT INTO Income (income_num, count, category, amount, date, tag) VALUES ('outid00266', 'Кошелёк Лев', 7 , 385.44, '2018-09-18', 'ФНС'); INSERT INTO Income (income_num, count, category, amount, date, tag) VALUES ('outid00265', 'Кошелёк Лев', 7, 458.73, '2018-09-18', 'ФНС'); INSERT INTO Income (income_num, count, category, amount, date, tag) VALUES ('outid00264', 'Карта ВТБ 5906 Юля', 2, 17500, '2018-09-14', ''); INSERT INTO Income (income_num, count, category, amount, date, tag) VALUES ('outid00263', 'Кошелёк Лев', 1, 900, '2018-09-11', 'Донорство'); INSERT INTO Income (income_num, count, category, amount, date, tag) VALUES ('outid00262', 'Кошелёк Юля', 2, 15000, '2018-09-10', 'Премия'); INSERT INTO Income (income_num, count, category, amount, date, tag) VALUES ('outid00261', 'Карта 0013 Лев', 1, 67120, '2018-09-10', ''); INSERT INTO Income (income_num, count, category, amount, date, tag) VALUES ('outid00260', 'Кошелёк Юля', 7, 255, '2018-09-09', 'Корректировка баланса'); INSERT INTO Income (income_num, count, category, amount, date, tag) VALUES ('outid00259', 'Карта Сбер 6161 Юля', 7 , 105.71, '2018-09-07', 'Корректировка баланса'); #Вносим данные в таблицу Outcome: INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004670', 'Карта Сбер 6161 Юля', 33014, 289.69, '2018-09-30', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004669', 'Карта Сбер 6161 Юля', 33014, 389.9, '2018-09-29', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004668', 'Карта Сбер 6161 Юля', 33021, 235, '2018-09-29', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004667', 'Кошелёк Юля', 33023, 156, '2018-09-29', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004666', 'Карта Сбер 6161 Юля', 33021, 110, '2018-09-29', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004665', 'Карта Сбер 6161 Юля', 33030, 1000, '2018-09-29', 'Маникюр'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004664', 'Кредитка 8423 Лев', 33063, 546.35, '2018-09-28', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004663', 'Кошелёк Юля', 33029, 176, '2018-09-28', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004662', 'Карта Сбер 6161 Юля', 33063, 3577, '2018-09-28', 'Перекрёсток'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004661', 'Карта Сбер 6161 Юля', 33030, 2550, '2018-09-28', 'Пиллинг [Жена]'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004660', 'Карта Сбер 6161 Юля', 33063, 836, '2018-09-28', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004659', 'Карта Сбер 6161 Юля', 33063, 800, '2018-09-28', 'Сухофрукты'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004658', 'Кредитка 8423 Лев', 33063, 244.61, '2018-09-28', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004657', 'Карта 4137 Лев', 33064, 30, '2018-09-27', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004656', 'Карта Сбер 6161 Юля', 33063, 0.1, '2018-09-27', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004655', 'Карта 4137 Лев', 33014, 85, '2018-09-27', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004654', 'Кредитка 8423 Лев', 33005, 353, '2018-09-27', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004653', 'Кошелёк Юля', 33008, 88, '2018-09-27', 'Рекс'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004652', 'Кредитка 8423 Лев', 33060, 1643.13, '2018-09-27', 'Моделизм краски'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004651', 'Кредитка 8423 Лев', 33063, 278.25, '2018-09-27', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004650', 'Кредитка 8423 Лев', 33063, 289, '2018-09-27', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004649', 'Карта 4137 Лев', 33064, 188, '2018-09-27', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004648', 'Карта Сбер 6161 Юля', 33045, 150, '2018-09-27', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004647', 'Карта Сбер 6161 Юля', 33064, 254.5, '2018-09-27', 'Обед [Жена]'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004646', 'Карта Сбер 6161 Юля', 33064, 139, '2018-09-27', 'Кофе [Жена]'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004645', 'Карта Сбер 6161 Юля', 33010, 50, '2018-09-27', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004644', 'Карта Сбер 6161 Юля', 33064, 160, '2018-09-26', 'Обед [Жена]'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004643', 'Карта Сбер 6161 Юля', 33054, 250, '2018-09-26', 'Колготки [Жена]'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004642', 'Карта 4137 Лев', 33043, 620, '2018-09-26', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004641', 'Карта 4137 Лев', 33066, 60, '2018-09-26', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004640', 'Карта 4137 Лев', 33009, 2500, '2018-09-26', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004639', 'Карта 4137 Лев', 33063, 284.54, '2018-09-26', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004638', 'Карта ВТБ 5906 Юля', 33064, 185, '2018-09-25', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004637', 'Карта ВТБ 5906 Юля', 33064, 160, '2018-09-25', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004636', 'Карта 4137 Лев', 33052, 93, '2018-09-25', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004635', 'Карта 4137 Лев', 33063, 191.1, '2018-09-25', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004634', 'Карта 4137 Лев', 33010, 1250, '2018-09-25', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004633', 'Кредитка 8423 Лев', 33064, 295, '2018-09-25', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004632', 'Карта ВТБ 5906 Юля', 33064, 230, '2018-09-24', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004631', 'Кредитка 8423 Лев', 33063, 253.34, '2018-09-24', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004630', 'Кредитка 8423 Лев', 33023, 308, '2018-09-24', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004629', 'Кредитка 8423 Лев', 33005, 738, '2018-09-24', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004628', 'Кредитка 8423 Лев', 33064, 240, '2018-09-24', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004627', 'Карта 0013 Лев', 33045, 600, '2018-09-24', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004626', 'Кредитка 8423 Лев', 33005, 757, '2018-09-23', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004625', 'Кредитка 8423 Лев', 33005, 631, '2018-09-23', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004624', 'Кредитка 8423 Лев', 33060, 90, '2018-09-22', 'Лейкопластырь'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004623', 'Кредитка 8423 Лев', 33063, 1244.21, '2018-09-22', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004622', 'Карта ВТБ 5906 Юля', 33010, 100, '2018-09-21', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004621', 'Карта ВТБ 5906 Юля', 33063, 239.6, '2018-09-21', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004620', 'Кредитка 8423 Лев', 33063, 115, '2018-09-21', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004619', 'Кредитка 8423 Лев', 33005, 1020, '2018-09-21', 'Каршеринг'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004618', 'Кредитка 8423 Лев', 33063, 1016.53, '2018-09-21', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004617', 'Кредитка 8423 Лев', 33005, 559, '2018-09-21', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004616', 'Кошелёк Лев', 33064, 200, '2018-09-21', 'Чаевые'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004615', 'Карта ВТБ 5906 Юля', 33064, 160, '2018-09-20', 'Обед [Жена]'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004614', 'Кредитка 8423 Лев', 33064, 159, '2018-09-20', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004613', 'Кредитка 8423 Лев', 33063, 47, '2018-09-20', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004612', 'Кредитка 8423 Лев', 33045, 150, '2018-09-20', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004611', 'Карта Сбер 6161 Юля', 33064, 98.5, '2018-09-20', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004610', 'Кошелёк Лев', 33063, 180, '2018-09-20', 'Арбузик'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004609', 'Кошелёк Лев', 33064, 229, '2018-09-19', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004608', 'Кредитка 8423 Лев', 33063, 43343, '2018-09-19', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004607', 'Карта ВТБ 5906 Юля', 33064, 160, '2018-09-19', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004606', 'Кошелёк Лев', 33063, 98, '2018-09-19', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004605', 'Кошелёк Лев', 33018, 474, '2018-09-19', 'Подставка для посуды и анкеры'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004604', 'Кошелёк Юля', 33063, 1043, '2018-09-18', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004603', 'Кошелёк Лев', 33040, 6602, '2018-09-18', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004602', 'Карта Сбер 6161 Юля', 33064, 160, '2018-09-18', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004601', 'Карта Сбер 6161 Юля', 33008, 660, '2018-09-18', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004600', 'Карта Сбер 6161 Юля', 33064, 100, '2018-09-17', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004599', 'Кошелёк Юля', 33064, 298, '2018-09-17', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004598', 'Кредитка 8423 Лев', 33063, 78.37, '2018-09-17', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004597', 'Кредитка 8423 Лев', 33063, 115.03, '2018-09-17', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004596', 'Кредитка 8423 Лев', 33064, 268, '2018-09-17', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004595', 'Счет ВТБ 3786 (ипотечный)', 33074, 46314.23, '2018-09-17', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004594', 'Карта Сбер 6161 Юля', 33060, 320, '2018-09-15', 'Мангал'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004593', 'Карта Сбер 6161 Юля', 33063, 679.01, '2018-09-15', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004592', 'Кредитка 8423 Лев', 33018, 2499, '2018-09-14', 'Турник'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004591', 'Кошелёк Юля', 33025, 700, '2018-09-14', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004590', 'Карта Сбер 6161 Юля', 33054, 1069, '2018-09-14', 'Зонтик'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004589', 'Карта Сбер 6161 Юля', 33063, 658, '2018-09-14', 'Сухофрукты'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004588', 'Карта Сбер 6161 Юля', 33064, 160, '2018-09-14', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004587', 'Карта Сбер 6161 Юля', 33063, 2666, '2018-09-14', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004586', 'Карта Сбер 6161 Юля', 33014, 1034.88, '2018-09-14', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004585', 'Карта 4137 Лев', 33063, 211.64, '2018-09-14', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004584', 'Кредитка 8423 Лев', 33023, 196, '2018-09-14', 'Анкеры'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004583', 'Карта 4137 Лев', 33063, 264.58, '2018-09-13', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004582', 'Карта 4137 Лев', 33064, 199, '2018-09-13', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004581', 'Карта 4137 Лев', 33063, 39, '2018-09-13', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004580', 'Кошелёк Юля', 33023, 149, '2018-09-12', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004579', 'Кошелёк Лев', 33063, 93, '2018-09-12', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004578', 'Карта 4137 Лев', 33064, 201, '2018-09-12', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004577', 'Карта 4137 Лев', 33063, 72.8, '2018-09-12', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004576', 'Карта 4137 Лев', 33064, 194, '2018-09-11', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004575', 'Кошелёк Юля', 33065, 1000, '2018-09-11', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004574', 'Карта ВТБ 5906 Юля', 33063, 450, '2018-09-11', 'Сухофрукты'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004573', 'Кредитка 8423 Лев', 33005, 224, '2018-09-11', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004572', 'Кошелёк Лев', 33063, 19, '2018-09-11', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004571', 'Кредитка 8423 Лев', 33063, 86.8, '2018-09-11', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004570', 'Кредитка 8423 Лев', 33064, 143, '2018-09-11', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004569', 'Карта Сбер 6161 Юля', 33064, 100, '2018-09-10', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004568', 'Кредитка 8423 Лев', 33057, 5196, '2018-09-10', 'H&M спорт'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004567', 'Кредитка 8423 Лев', 33054, 2249, '2018-09-10', 'Mango сумка'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004566', 'Кредитка 8423 Лев', 33054, 10598, '2018-09-10', 'Zara'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004565', 'Карта Сбер 6161 Юля', 33029, 1350, '2018-09-10', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004564', 'Карта Сбер 6161 Юля', 33029, 2490, '2018-09-10', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004563', 'Кредитка 8423 Лев', 33064, 510, '2018-09-10', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004562', 'Карта ВТБ 5906 Юля', 33010, 100, '2018-09-10', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004561', 'Кошелёк Юля', 33012, 5000, '2018-09-10', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004560', 'Кредитка 8423 Лев', 33010, 1050, '2018-09-10', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004559', 'Кошелёк Лев', 33000, 140.1, '2018-09-09', 'Корректировка баланса'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004558', 'Кредитка 8423 Лев', 33031, 1200, '2018-09-09', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004557', 'Кошелёк Юля', 33065, 42, '2018-09-09', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004556', 'Кошелёк Юля', 33063, 29, '2018-09-08', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004555', 'Кредитка 8423 Лев', 33063, 1218.7, '2018-09-08', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004554', 'Кредитка 8423 Лев', 33052, 93, '2018-09-08', 'Корм'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004553', 'Кредитка 8423 Лев', 33063, 774, '2018-09-08', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004552', 'Кошелёк Юля', 33063, 170, '2018-09-08', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004551', 'Кошелёк Юля', 33014, 130, '2018-09-08', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004550', 'Кошелёк Юля', 33065, 120, '2018-09-08', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004549', 'Карта Сбер 6161 Юля', 33063, 643, '2018-09-08', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004548', 'Карта Сбер 6161 Юля', 33030, 1000, '2018-09-08', 'Маникюр'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004547', 'Кошелёк Юля', 33064, 228, '2018-09-07', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004546', 'Карта ВТБ 5906 Юля', 33045, 210, '2018-09-07', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004545', 'Кредитка 8423 Лев', 33064, 260, '2018-09-07', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004544', 'Кошелёк Юля', 33000, 563, '2018-09-07', 'Корректировка баланса'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004543', 'Карта Сбер 6161 Юля', 33005, 563, '2018-09-07', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004542', 'Кредитка 8423 Лев', 33063, 144.39, '2018-09-07', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004541', 'Кредитка 8423 Лев', 33045, 476.7, '2018-09-06', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004540', 'Кредитка 8423 Лев', 33064, 220, '2018-09-06', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004539', 'Кредитка 8423 Лев', 33014, 138.7, '2018-09-06', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004538', 'Кредитка 8423 Лев', 33049, 1397.02, '2018-09-06', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004537', 'Кошелёк Юля', 33063, 119, '2018-09-06', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004536', 'Кошелёк Юля', 33010, 50, '2018-09-06', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004535', 'Кредитка 8423 Лев', 33064, 225, '2018-09-05', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004534', 'Кредитка 8423 Лев', 33063, 100.5, '2018-09-05', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004533', 'Кредитка 8423 Лев', 33060, 42.79, '2018-09-04', 'Лезвия для резака'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004532', 'Кредитка 8423 Лев', 33064, 177, '2018-09-04', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004531', 'Кошелёк Лев', 33010, 300, '2018-09-04', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004530', 'Кошелёк Лев', 33065, 45, '2018-09-04', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004529', 'Кошелёк Лев', 33060, 85.9, '2018-09-04', 'Резак'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004528', 'Кредитка 8423 Лев', 33063, 286.76, '2018-09-04', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004527', 'Карта Сбер 6161 Юля', 33064, 466, '2018-09-04', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004526', 'Кошелёк Юля', 33033, 993, '2018-09-04', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004525', 'Карта Сбер 6161 Юля', 33054, 2699, '2018-09-04', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004524', 'Кошелёк Юля', 33029, 576, '2018-09-04', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004523', 'Карта Сбер 6161 Юля', 33064, 99, '2018-09-04', 'Кофе'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004522', 'Кошелёк Юля', 33024, 450, '2018-09-04', 'Чехол [Жена]'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004521', 'Кошелёк Юля', 33010, 200, '2018-09-04', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004520', 'Карта 4137 Лев', 33064, 161, '2018-09-03', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004519', 'Кошелёк Лев', 33045, 45, '2018-09-03', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004518', 'Кредитка 8423 Лев', 33014, 129.98, '2018-09-03', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004517', 'Карта Сбер 6161 Юля', 33045, 300, '2018-09-03', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004516', 'Кошелёк Юля', 33044, 5050, '2018-09-03', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004515', 'Кошелёк Юля', 33012, 5000, '2018-09-03', 'Взнос за корпоратив [Жена]'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004514', 'Кредитка 8423 Лев', 33052, 229.98, '2018-09-02', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004513', 'Кредитка 8423 Лев', 33014, 59.99, '2018-09-02', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004512', 'Карта Сбер 6161 Юля', 33054, 4690, '2018-09-02', 'Тренч [Жена]'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004511', 'Карта Сбер 6161 Юля', 33026, 60, '2018-09-02', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004510', 'Карта Сбер 6161 Юля', 33060, 1020, '2018-09-01', 'Бирстория'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004509', 'Кошелёк Лев', 33014, 398, '2018-09-01', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004508', 'Карта Сбер 6161 Юля', 33024, 521.74, '2018-09-01', 'Чехлы и браслеты'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004507', 'Карта Сбер 6161 Юля', 33018, 2315, '2018-09-01', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004506', 'Карта Сбер 6161 Юля', 33009, 500, '2018-09-01', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004505', 'Кошелёк Юля', 33063, 800, '2018-09-01', ''); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004504', 'Карта Сбер 6161 Юля', 33030, 2150, '2018-09-01', 'Эпиляция [Жена]'); INSERT INTO Outcome (outcome_num, count, category, amount, date, tag) VALUES ('incid1004503', 'Кошелёк Лев', 33033, 507, '2018-09-01', ''); #Запросы: #1 Вывести топ-10 самых крупных трат за период с 15 по 30 сентября в формате название категории затрат (не id, а название), сумма, дата. #Использование CTE WITH t1 AS ( SELECT outcome_id, outcome_count, amount, date FROM OUTCOME JOIN out_categories ON outcome.category = out_categories.outcome_id ) SELECT outcome_count AS largest_expences, amount AS largest_costs, date AS date_of_high_expences FROM t1 WHERE date BETWEEN '2018-09-15' AND '2018-09-30' ORDER BY amount DESC LIMIT 10; largest_expences | largest_costs | date_of_high_expences ------------------------------+---------------+----------------------- Ипотека | 46314.2 | 2018-09-17 00:00:00 Продукты | 43343 | 2018-09-19 00:00:00 ЖКУ | 6602 | 2018-09-18 00:00:00 Продукты | 3577 | 2018-09-28 00:00:00 Процедуры | 2550 | 2018-09-28 00:00:00 Автобусы/троллейбусы/трамваи | 2500 | 2018-09-26 00:00:00 Досуг | 1643.13 | 2018-09-27 00:00:00 Метро | 1250 | 2018-09-25 00:00:00 Продукты | 1244.21 | 2018-09-22 00:00:00 Продукты | 1043 | 2018-09-18 00:00:00 (10 rows) #2 Выведите в процентах долю категории затрат "Ипотека" от общей суммы затрат за рассматриваемый период (сентябрь 2018). # Аналогичным образом посчитайте в процентах долю категории затрат "Ипотека" от общей суммы доходов. #Исползование вложенных запросов. SELECT ( ( SELECT amount FROM outcome WHERE category = 33074 ) / ( SELECT SUM(amount) FROM outcome ) )*100 AS percent_of_a_loan_in_outcome; percent_of_a_loan_in_outcome ------------------------------ 21.8287363648415 (1 row) SELECT ( ( SELECT amount FROM outcome WHERE category = 33074 ) / ( SELECT SUM(amount) FROM Income ) )*100 AS percent_of_a_loan_in_income; percent_of_a_loan_in_income ----------------------------- 25.9718298912048 (1 row) #3 Выведите баланс семейного бюджета после каждой транзакции (любой расход или доход) в порядке возрастания даты. #Предполагается, что на момент совершения самой первой транзакции баланс семейного бюджета был равен 0. # Результат представить в виде: категория затрат или доходов (не айдишник, а расшифрованное название), сумма, дата (может повторяться, если за одну дату было совершено более 1 транзакции, #баланс сразу после совершения транзакции (трата или доход). # Использование CTE, оконных и агрегирующих функций, создание комбинированных запросов. WITH balance AS ( SELECT transactions, categories, amounts, dates, row_number() OVER () AS num FROM ( SELECT Income.income_num AS transactions, income_count AS categories, Income.amount AS amounts, Income.date AS dates FROM Income, Inc_categories WHERE Inc_categories.income_id = Income.category UNION SELECT Outcome.outcome_num, outcome_count, Outcome.amount * (-1), Outcome.date FROM Outcome, Out_categories WHERE Out_categories.outcome_id = Outcome.category ORDER BY dates ) AS numeric_transactions ORDER BY num ) SELECT num, categories, amounts, dates, sum(amounts) OVER(ORDER BY num) as daily_balance FROM balance ORDER BY num; -----+----------------------------------+--------------------+---------------------+------------------- 1 | Досуг | -1020 | 2018-09-01 00:00:00 | -1020 2 | Автобусы/троллейбусы/трамваи | -500 | 2018-09-01 00:00:00 | -1520 3 | Алкоголь | -398 | 2018-09-01 00:00:00 | -1918 4 | Процедуры | -2150 | 2018-09-01 00:00:00 | -4068 5 | Продукты | -800 | 2018-09-01 00:00:00 | -4868 6 | Бытовая техника | -521.739990234375 | 2018-09-01 00:00:00 | -5389.73999023438 7 | Аптека | -507 | 2018-09-01 00:00:00 | -5896.73999023438 8 | Мебель | -2315 | 2018-09-01 00:00:00 | -8211.73999023438 9 | Аквариум | -229.979995727539 | 2018-09-02 00:00:00 | -8441.71998596191 10 | Алкоголь | -59.9900016784668 | 2018-09-02 00:00:00 | -8501.70998764038 11 | Банковские услуги | -60 | 2018-09-02 00:00:00 | -8561.70998764038 12 | Одежда/Аксессуары (сумки и т.д.) | -4690 | 2018-09-02 00:00:00 | -13251.7099876404 ... 179 | Алкоголь | -289.690002441406 | 2018-09-30 00:00:00 | -33846.0604301468 (179 rows) #4 Выведите список всех трат, имеющих комментарий (tag), содержащий любое из слов: "обед", "кофе" "резак"(независимо от табуляции). # Результат вывести в виде: категория затрат (не айдишник, а расшифрованное название), сумма, дата, комментарий. # Использование комбинированных запросов, предиката LIKE. SELECT outcome_count AS "Категория_затрат", amount AS "Сумма", date AS "Дата", tag AS "Комментарий" FROM out_categories, Outcome WHERE outcome_id = category AND (lower(tag) LIKE '%обед%' OR lower(tag) LIKE '%резак%' OR lower(tag) LIKE '%кофе%'); Категория_затрат | Сумма | Дата | Комментарий ------------------+-------+---------------------+------------------- Досуг | 85.9 | 2018-09-04 00:00:00 | Резак Досуг | 42.79 | 2018-09-04 00:00:00 | Лезвия для резака Кафе | 99 | 2018-09-04 00:00:00 | Кофе Кафе | 160 | 2018-09-20 00:00:00 | Обед [Жена] Кафе | 160 | 2018-09-26 00:00:00 | Обед [Жена] Кафе | 139 | 2018-09-27 00:00:00 | Кофе [Жена] Кафе | 254.5 | 2018-09-27 00:00:00 | Обед [Жена] (7 rows) #5 Создайте список трат, имеющих любой комментарий (tag), в формате "Кафе (99 руб., Кофе)". # Вывести Наименование затрат (как указано выше) и вторым столбцом длину тега. Упорядочить по убыванию длины комментария. # Создание представлений, использование предиката LIKE. CREATE VIEW tagged_costs AS SELECT outcome_count, amount, date, tag FROM out_categories, Outcome WHERE outcome_id = category AND tag NOT LIKE ''; SELECT RTRIM(outcome_count) || ' (' || CAST(amount AS VARCHAR) || ' руб., ' || tag || ')' AS "Затраты", LENGTH(tag) AS "Длина комментария" FROM tagged_costs ORDER BY "Длина комментария" DESC; Затраты | Длина комментария --------------------------------------------------------------------+------------------- Мебель (474 руб., Подставка для посуды и анкеры) | 29 Транспорт при путешествиях (5000 руб., Взнос за корпоратив [Жена]) | 26 Без категории (140.1 руб., Корректировка баланса) | 21 Без категории (563 руб., Корректировка баланса) | 21 Досуг (42.79 руб., Лезвия для резака) | 17 Бытовая техника (521.74 руб., Чехлы и браслеты) | 16 Процедуры (2150 руб., Эпиляция [Жена]) | 15 Досуг (1643.13 руб., Моделизм краски) | 15 Одежда/Аксессуары (сумки и т.д.) (250 руб., Колготки [Жена]) | 15 Процедуры (2550 руб., Пиллинг [Жена]) | 14 Досуг (90 руб., Лейкопластырь) | 13 Одежда/Аксессуары (сумки и т.д.) (4690 руб., Тренч [Жена]) | 12 Бытовая техника (450 руб., Чехол [Жена]) | 12 Кафе (254.5 руб., Обед [Жена]) | 11 Продукты (3577 руб., Перекрёсток) | 11 Кафе (160 руб., Обед [Жена]) | 11 Кафе (139 руб., Кофе [Жена]) | 11 Кафе (160 руб., Обед [Жена]) | 11 Одежда/Аксессуары (сумки и т.д.) (2249 руб., Mango сумка) | 11 Продукты (658 руб., Сухофрукты) | 10 Продукты (800 руб., Сухофрукты) | 10 Продукты (450 руб., Сухофрукты) | 10 Спортивная форма (5196 руб., H&M спорт) | 9 Досуг (1020 руб., Бирстория) | 9 Такси (1020 руб., Каршеринг) | 9 Продукты (180 руб., Арбузик) | 7 Процедуры (1000 руб., Маникюр) | 7 Процедуры (1000 руб., Маникюр) | 7 Одежда/Аксессуары (сумки и т.д.) (1069 руб., Зонтик) | 6 Мебель (2499 руб., Турник) | 6 Расходные материалы (196 руб., Анкеры) | 6 Кафе (200 руб., Чаевые) | 6 Досуг (320 руб., Мангал) | 6 Досуг (85.9 руб., Резак) | 5 Кафе (99 руб., Кофе) | 4 Аквариум (93 руб., Корм) | 4 Одежда/Аксессуары (сумки и т.д.) (10598 руб., Zara) | 4 Электричка (88 руб., Рекс) | 4 (38 rows) #6 Создайте список категорий затрат с указанием количества их повторений. Вывести топ-10 самых частых затрат за месяц. #Применение аналитической функции COUNT() SELECT outcome_count AS "Что покупаем", COUNT(amount) AS "Как часто?" FROM Outcome, Out_categories WHERE Out_categories.outcome_id = Outcome.category GROUP BY outcome_count ORDER BY "Как часто?" DESC LIMIT 10; Что покупаем | Как часто? ----------------------------------+------------ Продукты | 43 Кафе | 35 Алкоголь | 9 Метро | 8 Такси | 8 Подарки на работе | 7 Досуг | 6 Одежда/Аксессуары (сумки и т.д.) | 6 Косметика | 4 Вода | 4 (10 rows) #7 Для каждого из мест хранения найти средний размер трат. #Вывести в порядке возрастания среднего размера покупки два столбца: место хранения и средняя покупка. #Применение аналитической функции AVG() SELECT count AS "Чем расплачиваемся?", AVG(amount) AS "Средний чек" FROM Outcome, Out_categories WHERE Out_categories.outcome_id = Outcome.category GROUP BY count ORDER BY AVG(amount) DESC; Чем расплачиваемся? | Средний чек ---------------------------+------------------ Счет ВТБ 3786 (ипотечный) | 46314.23046875 Кредитка 8423 Лев | 1568.66907324614 Кошелёк Юля | 925.2 Карта Сбер 6161 Юля | 894.620909118686 Кошелёк Лев | 627.73333384196 Карта 0013 Лев | 600 Карта 4137 Лев | 369.147777981228 Карта ВТБ 5906 Юля | 199.460000610352 (8 rows) #8 Построить список категорий затрат, которые совершались как в первую неделю месяца, так и в последнюю. #Операция пересечения CREATE VIEW main_table AS SELECT * FROM out_categories, Outcome WHERE outcome_id = category; SELECT DISTINCT outcome_count FROM main_table WHERE (date BETWEEN '2018-09-01' AND '2018-09-07') INTERSECT SELECT DISTINCT outcome_count FROM main_table WHERE (date BETWEEN '2018-09-24' AND '2018-09-30') ORDER BY outcome_count; outcome_count ---------------------------------- Автобусы/троллейбусы/трамваи Аквариум Алкоголь Досуг Кафе Косметика Метро Одежда/Аксессуары (сумки и т.д.) Подарки на работе Продукты Процедуры Такси (12 rows) #9 Выполнить то же, что и в задании 8, но только при помощи предиката EXISTS. SELECT DISTINCT outcome_count FROM main_table AS mt WHERE (date BETWEEN '2018-09-01' AND '2018-09-07') AND EXISTS (SELECT outcome_count FROM main_table WHERE (date BETWEEN '2018-09-24' AND '2018-09-30') AND outcome_count = mt.outcome_count) ORDER BY outcome_count; outcome_count ---------------------------------- Автобусы/троллейбусы/трамваи Аквариум Алкоголь Досуг Кафе Косметика Метро Одежда/Аксессуары (сумки и т.д.) Подарки на работе Продукты Процедуры Такси (12 rows) #10 Вывести долю во всем объеме затрат ждя каждой категории трат (категория затрат, доля в процентах), расположить в порядке убывания. # В выборку должны попасть затраты, которые занимают не менее 1 процента от всего объема затрат. #Применение аналитической функции SUM() SELECT outcome_count AS "категория затрат", (SUM(amount) * 100) / (SELECT SUM(amount) FROM Outcome) AS "процент от всего объема" FROM main_table GROUP BY outcome_count HAVING (SUM(amount) * 100) / (SELECT SUM(amount) FROM Outcome) >= 1 ORDER BY "процент от всего объема" DESC; категория затрат | процент от всего объема ----------------------------------+------------------------- Продукты | 30.3270656860599 Ипотека | 21.8287360301125 Одежда/Аксессуары (сумки и т.д.) | 10.1592620748941 Транспорт при путешествиях | 4.71318119920857 Кафе | 3.32609197228149 Процедуры | 3.15783140346974 ЖКУ | 3.1116422277175 Мебель | 2.49233021814149 Спортивная форма | 2.44896895110877 Подарки родным (родители) | 2.38015650560033 Такси | 2.28353629101655 Косметика | 2.16429280667657 Досуг | 1.50907569987611 Метро | 1.46108617175466 Автобусы/троллейбусы/трамваи | 1.41395435976257 Алкоголь | 1.25188686041671 (16 rows)
SQL
UTF-8
902
3.09375
3
[]
no_license
--- File: faculty.sql --- Date: 2019/01/27 --- Name: Ian Carlos --- Description: This SQL file will be used to store and retrieve data for the Faculty.java class. DROP TABLE IF EXISTS faculty CASCADE; CREATE TABLE faculty( id BIGINT PRIMARY KEY REFERENCES users(id), schoolCode CHAR(5) NOT NULL, schoolDesc VARCHAR(70) NOT NULL, office VARCHAR(6) NOT NULL, extension INT NOT NULL ); ALTER TABLE faculty OWNER TO webd4201_admin; INSERT INTO faculty(id, schoolCode, schoolDesc, office, extension) values ( 100123456, 'BITM', 'School of Business, IT & Management', 'C-315', 2044 ); INSERT INTO faculty(id, schoolCode, schoolDesc, office, extension) values ( 100789012, 'BITM', 'School of Business, IT & Management', 'H-216', 2646 ); INSERT INTO faculty(id, schoolCode, schoolDesc, office, extension) values ( 100678321, 'BITM', 'School of Business, IT & Management', 'C-307', 1234 );
Java
UTF-8
519
2.515625
3
[]
no_license
package cimi.com.easeinterpolator; import android.content.Context; import android.util.AttributeSet; import android.view.animation.Interpolator; /** * Created by cimi on 15/7/3. */ public class EaseSineInOutInterpolator implements Interpolator { public EaseSineInOutInterpolator() { } public EaseSineInOutInterpolator(Context context, AttributeSet attrs) { } public float getInterpolation(float input) { return (float) (-1 * 0.5f * (Math.cos(MathConstants.PI * input) - 1)); } }
Python
UTF-8
269
4.5625
5
[]
no_license
#Program to print Odd and Even numbers in range(0,100) in Python def check_odd_even(): for num in range(0,100): if num % 2 == 0: print(f"Even Numbers are : {num}") else: print(f"Odd Numbers are : {num}")
Java
UTF-8
254
1.820313
2
[]
no_license
package com.APISpring.service; import java.util.List; import com.APISpring.entities.CTHoaDon; import com.APISpring.entities.HoaDon; public interface ICTHoaDonService { public CTHoaDon save(CTHoaDon cthd); public List<CTHoaDon> findAll(HoaDon hd); }
Python
UTF-8
844
4.1875
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Feb 26 18:41:40 2019 @author: student-03 """ #List 串列 #可以存多型別資料(陣列僅能存單型別資料) #可以變換元素 income=[] while True: salary=input("輸入數字") if salary!='q': income.append(salary) else: break print(type(income)) #確認型別 print(type(income[0])) print(type(int(income[0]))) #轉型別 for i in range(len(income)): income[i]=int(income[i]) for i in income: i=int(i) max(income) sum(income) #加總 print("before %s"%(income)) income.insert(1,"250") print(income) income.pop(1) print(income) income.sort print(income) #income2=income.copy() #print(income2) #income2.clear() #print(income2) strToList="I love 台灣" print(list(strToList))
Java
UTF-8
1,526
2.109375
2
[]
no_license
package com.home.entities; import java.util.Date; public class ReportInvoiceDaily { public int no; public String staff_name; public String customer1_codes; public String customer1_names; public Date date1_receipt_of_product; public Date date2_company_receipt_of_invoice; public Date getDate2_company_receipt_of_invoice() { return date2_company_receipt_of_invoice; } public void setDate2_company_receipt_of_invoice( Date date2_company_receipt_of_invoice) { this.date2_company_receipt_of_invoice = date2_company_receipt_of_invoice; } public String total_moneys; public int getNo() { return no; } public String getStaff_name() { return staff_name; } public String getCustomer1_codes() { return customer1_codes; } public String getCustomer1_names() { return customer1_names; } public String getTotal_moneys() { return total_moneys; } public void setNo(int no) { this.no = no; } public void setStaff_name(String staff_name) { this.staff_name = staff_name; } public void setCustomer1_codes(String customer1_codes) { this.customer1_codes = customer1_codes; } public void setCustomer1_names(String customer1_names) { this.customer1_names = customer1_names; } public void setTotal_moneys(String total_moneys) { this.total_moneys = total_moneys; } public Date getDate1_receipt_of_product() { return date1_receipt_of_product; } public void setDate1_receipt_of_product(Date date1_receipt_of_product) { this.date1_receipt_of_product = date1_receipt_of_product; } }
Java
UTF-8
1,093
3.65625
4
[]
no_license
package leetcode101_200; public class L116_PopulatingNextRightPointersInEachNode_medium { // https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/ // 不要提交这个类 public static class Node { public int val; public Node left; public Node right; public Node next; } // 提交下面的代码 // 主函数 public Node connect(Node root) { if (root == null) return null; // 遍历「三叉树」,连接相邻节点 traverse(root.left, root.right); return root; } // 三叉树遍历框架 public void traverse(Node node1, Node node2) { if (node1 == null || node2 == null) { return; } /**** 前序位置 ****/ // 将传入的两个节点穿起来 node1.next = node2; // 连接相同父节点的两个子节点 traverse(node1.left, node1.right); traverse(node2.left, node2.right); // 连接跨越父节点的两个子节点 traverse(node1.right, node2.left); } }
PHP
UTF-8
2,857
2.703125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "employee". * * @property integer $id * @property integer $branch_id * @property string $name * @property string $surname * @property string $password * @property string $create_time * @property string $update_time * * @property Branch $branch */ class Employee extends \yii\db\ActiveRecord { /** * @inheritdoc */ const SPLITER = "C139A"; const IDSPLITTER = "9138B"; const TIMELIMIT = 86400; public static function tableName() { return 'employee'; } /** * @inheritdoc */ public function rules() { return [ [['branch_id', 'name', 'password'], 'required'], [['branch_id'], 'integer'], [['password'], 'string'], [['create_time', 'update_time'], 'safe'], [['name'], 'string', 'max' => 100], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'branch_id' => 'Branch ID', 'name' => 'Name', 'password' => 'Password', 'create_time' => 'Create Time', 'update_time' => 'Update Time', ]; } /** * @return \yii\db\ActiveQuery */ public function getBranch() { return $this->hasOne(Branch::className(), ['id' => 'branch_id']); } public function beforeSave($insert) { $this->update_time = date('Y-m-d H:i:s'); return parent::beforeSave($insert); } public static function encodePassword($password, $salt) { return base64_encode($password.$salt); } public function getToken() { $key = self::encodePassword($this->password, time()); $key = substr($key, count($key) - 10); return $key.self::SPLITER.time().SELF::IDSPLITTER.$this->id; } public static function findIdentityByAccessToken($token) { $data = explode(self::IDSPLITTER, $token); if( count($data) != 2) return null; $id = $data[1]; $key = $data[0]; $data = explode(self::SPLITER, $key); if( count($data) != 2) return null; $key = $data[0]; $old_time = $data[1]; $diff_time = (time() - $old_time) ; if($diff_time >= self::TIMELIMIT) return null; //decode from url $key = urldecode($key); $key_time = $data[1]; $employee = static::findOne($id); $real_key = self::encodePassword($employee->password, $key_time); $real_key = substr($real_key, count($real_key) - 10); if($real_key != $key) return null; return $employee; } public static function isValidToken($token) { } }
C
UTF-8
344
3.28125
3
[]
no_license
#include <stdio.h> int main(){ int a[3]; for (register int i = 0; i < 3; i++) scanf("%d", &a[i]); for (register int i = 0; i < 3; i++) for (register int j = i + 1; j < 3; j++) if (a[i] > a[j]) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } printf("%d->%d->%d\n", a[0], a[1], a[2]); return 0; }
Python
UTF-8
82
3.453125
3
[]
no_license
a=int(input()) b=0 c=0 while(a!=0): c=a%10 b=(b*10)+c a=int(a/10) print (b)
JavaScript
UTF-8
339
3.890625
4
[ "MIT" ]
permissive
let nums = []; do { let num = prompt("Enter Number"); if (Number.isNaN(parseInt(num))) { break; } else { nums.push(parseInt(num)); } } while(true); let c = 0; let sum = () => nums.forEach(element => { c = c + element; }); let display = function(sum) { sum(); alert(c) } display(sum)
C#
UTF-8
4,468
2.71875
3
[]
no_license
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; namespace FreelanceHuntApi.Model { public class Review { /// <summary> /// Середнє арфиметичне оцінок для цього відгуку(замовник, фрілансер) /// </summary> public double? GradeAverage { get; private set; } /// <summary> /// Своєчасність оплати, відповідність зазначеним умовам (Замовник) /// </summary> public int? GradePay { get; private set; } /// <summary> /// Чіткість і ясність поставленого завдання, наявність чіткого ТЗ (Замовник) /// </summary> public int? GradeDefinition { get; private set; } /// <summary> /// Обґрунтованість та адекватність вимог до проекту (Замовник) /// </summary> public int? GradeRequirements { get; private set; } /// <summary> /// Загальний рівень виконаної роботи, відсутність помилок, наявність документації (Фрілансер) /// </summary> public int? GradeQuality { get; private set; } /// <summary> /// Ступінь відповідності отриманого результату вартості проекту (Фрілансер) /// </summary> public int? GradeCost { get; private set; } /// <summary> /// Володіння технологіями, рівень спілкування з замовником (Фрілансер) /// </summary> public int? GradeProfessionalism { get; private set; } /// <summary> /// Легкість виходу на контакт, доступність виконавця (Фрілансер) /// </summary> public int? GradeConnectivity { get; private set; } /// <summary> /// Наскільки фрілансер дотримувався обумовлених термінів /// </summary> public int? GradeSchedule { get; private set; } /// <summary> /// текст відгуку /// </summary> public string ReviewComment { get; private set; } /// <summary> /// Дата залишення відгуку /// </summary> public DateTime? ReviewTime { get; private set; } public From From { get; private set; } /// <summary> /// Проект який зв'язаний з відгуком /// </summary> public Project Project { get; private set; } private static Review FromJson(string json) { JObject jObject = JObject.Parse(json); return new Review { GradeAverage = jObject["grade_average"].ToObject<double?>(), GradePay = jObject["grade_pay"]?.ToObject<int>(), GradeDefinition = jObject["grade_definition"]?.ToObject<int>(), GradeRequirements = jObject["grade_requirements"]?.ToObject<int>(), GradeConnectivity = jObject["grade_connectivity"]?.ToObject<int>(), ReviewComment = jObject["review_comment"]?.ToObject<string>(), ReviewTime = jObject["review_time"]?.ToObject<DateTime>(), From = Model.From.FromJson(jObject["from"].ToString()), Project = Model.Project.FromJson(jObject["project"].ToString()), GradeCost = jObject["grade_cost"]?.ToObject<int>(), GradeQuality = jObject["grade_quality"]?.ToObject<int>(), GradeSchedule = jObject["grade_schedule"]?.ToObject<int>(), GradeProfessionalism = jObject["grade_professionalism"]?.ToObject<int>() }; } internal static List<Review> ReviewsFromJson(string json) { var reviews = new List<Review>(); JObject jObject = JObject.Parse(json); JArray jArray = JArray.Parse(jObject["reviews"].ToString()); foreach (var review in jArray) { reviews.Add(FromJson(review.ToString())); } return reviews; } } }
Python
UTF-8
926
3.828125
4
[ "MIT" ]
permissive
class Range: '''Range of lines in file from a to b (including a and b). a, b >=0''' def __init__(self, start: int, end: int = None): self._start = start self._end = end or start assert self._start <= self._end @staticmethod def from_str(s: str) -> 'Range': if isinstance(s, list): start, end = s else: start, end = eval(s) return Range(start, end) @property def start(self) -> int: return self._start @property def end(self) -> int: return self._end def __repr__(self): return self.__str__() def __str__(self): return f'[{self._start},{self._end}]' def __eq__(self, other: 'Range'): return self._start == other._start and self._end == other._end def contains(self, range: 'Range') -> bool: return self._start <= range.start and self._end >= range.end
Python
UTF-8
2,577
3.4375
3
[]
no_license
import pygame from tictactoe import Game SCREEN_WIDTH = 640 SCREEN_HEIGHT = 640 GRID_SIZE = 3 CELL_WIDTH = SCREEN_WIDTH / GRID_SIZE CELL_HEIGHT = SCREEN_HEIGHT / GRID_SIZE BLACK = (0, 0, 0) WHITE = (255, 255, 255) class Renderer: def __init__(self): pygame.init() pygame.display.set_caption("TicTacToe") self._screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) self._font = pygame.font.SysFont("monospace", 64) def draw(self, game: Game): self.draw_board() for i, row in enumerate(game.board): for j, value in enumerate(row): if value == Game.BLACK: self.draw_o(i, j) elif value == Game.WHITE: self.draw_x(i, j) winner = game.get_winner() if winner: if winner == Game.BLACK: text = "O Wins" elif winner == Game.WHITE: text = "X Wins" else: text = "Draw" rendered_text = self._font.render(text, True, BLACK, WHITE) pos_x = (SCREEN_WIDTH - rendered_text.get_width()) / 2 pos_y = (SCREEN_HEIGHT - rendered_text.get_height()) / 2 self._screen.blit(rendered_text, (pos_x, pos_y)) pygame.display.flip() def draw_board(self): self._screen.fill(WHITE) pygame.draw.line(self._screen, BLACK, (CELL_WIDTH, 0), (CELL_WIDTH, SCREEN_HEIGHT)) pygame.draw.line(self._screen, BLACK, (2 * CELL_WIDTH, 0), (2 * CELL_WIDTH, SCREEN_HEIGHT)) pygame.draw.line(self._screen, BLACK, (0, CELL_HEIGHT), (SCREEN_WIDTH, CELL_HEIGHT)) pygame.draw.line(self._screen, BLACK, (0, 2 * CELL_HEIGHT), (SCREEN_WIDTH, 2 * CELL_HEIGHT)) def draw_o(self, row, col): pygame.draw.circle( self._screen, BLACK, ( (col * CELL_WIDTH) + CELL_WIDTH / 2, (row * CELL_HEIGHT) + CELL_HEIGHT / 2, ), CELL_WIDTH / 2, 1, ) def draw_x(self, row, col): pygame.draw.line( self._screen, BLACK, (col * CELL_WIDTH, row * CELL_HEIGHT), ((col + 1) * CELL_WIDTH, (row + 1) * CELL_HEIGHT), ) pygame.draw.line( self._screen, BLACK, ((col + 1) * CELL_WIDTH, row * CELL_HEIGHT), (col * CELL_WIDTH, (row + 1) * CELL_HEIGHT), ) def convert_coords(self, x, y): return int(y // CELL_HEIGHT), int(x // CELL_WIDTH)
Java
UTF-8
707
1.867188
2
[]
no_license
package us.com.plattrk.service; import us.com.plattrk.api.model.EmailAddress; import us.com.plattrk.api.model.Incident; import us.com.plattrk.api.model.IncidentReportByProduct; import java.util.Date; import java.util.List; public interface Report { public void generateDailyReport(List<Incident> incidents, Date previousDayDate); public void generateWeekEndReport(List<Incident> incidents, Date previousWeekEndDate, Date previousDayDate); public boolean generateWeeklyReport(List<Incident> incidents, Date previousWeeklyDate, Date previousDayDate, EmailAddress address); public boolean generateReportByProduct(List<Incident> incidents, IncidentReportByProduct incidentReport); }
PHP
UTF-8
13,185
2.53125
3
[]
no_license
<?php namespace HomeOffice\AlfrescoApiBundle\Repository; use GuzzleHttp\Client as Guzzle; use HomeOffice\AlfrescoApiBundle\Service\DateHelper; use HomeOffice\ProcessManagerAuthenticatorBundle\Security\SessionTicketStorage; use HomeOffice\AlfrescoApiBundle\Service\AtomHelper; use HomeOffice\AlfrescoApiBundle\Service\QueryHelper; use HomeOffice\AlfrescoApiBundle\Service\CTSHelper; use HomeOffice\AlfrescoApiBundle\Factory\CtsCaseStandardLineFactory; use HomeOffice\AlfrescoApiBundle\Entity\CtsCaseStandardLine; use GuzzleHttp\Exception\RequestException; /** * Class CtsCaseStandardLineRepository * * @package HomeOffice\AlfrescoApiBundle\Repository */ class CtsCaseStandardLineRepository { const DEFAULT_ERROR = 'An error occurred trying to add the standard line, please try again later.'; const VIRUS_ERROR = "A Virus was found in the file. Do not try again."; /** * @var Guzzle */ private $apiClient; /** * @var CtsCaseStandardLineFactory */ private $factory; /** * @var SessionTicketStorage */ private $tokenStorage; /** * @var AtomHelper */ private $atomHelper; /** * @var QueryHelper */ private $queryHelper; /** * @var CTSHelper */ private $ctsHelper; /** * @var string */ private $workspace; /** * @var string */ private $store; /** * @var array */ private $caseStandardLineProperties; /** * @var CtsCaseDocumentRepository */ private $ctsCaseDocumentRepository; private $environment; /** * Constructor * * @param String $env * @param Guzzle $apiClient * @param CtsCaseStandardLineFactory $ctsCaseStandardLineFactory * @param SessionTicketStorage $tokenStorage * @param AtomHelper $atomHelper * @param QueryHelper $queryHelper * @param CTSHelper $ctsHelper * @param string $workspace * @param string $store * @param array $caseStandardLineProperties * @param CtsCaseDocumentRepository $ctsCaseDocumentRepository */ public function __construct( $env, Guzzle $apiClient, CtsCaseStandardLineFactory $ctsCaseStandardLineFactory, SessionTicketStorage $tokenStorage, AtomHelper $atomHelper, QueryHelper $queryHelper, CTSHelper $ctsHelper, $workspace, $store, array $caseStandardLineProperties, CtsCaseDocumentRepository $ctsCaseDocumentRepository ) { $this->apiClient = $apiClient; $this->apiClient->setDefaultOption('version', [ 'CURLOPT_HTTP_VERSION' => 'CURL_HTTP_VERSION_1_0', "CURLOPT_SSL_VERIFYHOST" => "0", "CURLOPT_SSL_VERIFYPEER" => "0" ]); $this->factory = $ctsCaseStandardLineFactory; $this->tokenStorage = $tokenStorage; $this->atomHelper = $atomHelper; $this->queryHelper = $queryHelper; $this->ctsHelper = $ctsHelper; $this->workspace = $workspace; $this->store = $store; $this->caseStandardLineProperties = $caseStandardLineProperties; $this->ctsCaseDocumentRepository = $ctsCaseDocumentRepository; $this->environment = $env; } /** * Create * * @param CtsCaseStandardLine $standardLine * * @return array|bool */ public function create(CtsCaseStandardLine $standardLine) { try { $standardLine->upload(); $file1 = fopen($standardLine->getWebPath(), 'r'); $file2 = fopen($standardLine->getWebPath(), 'r'); //Virus scan if ($this->environment != "dc") { $virusBody = array( 'file' => $file1, 'name' => $standardLine->getName() ); $virusClient = new Guzzle(); $virusClient->setDefaultOption('version', [ 'CURLOPT_HTTP_VERSION' => 'CURL_HTTP_VERSION_1_0', "CURLOPT_SSL_VERIFYHOST" => "0", "CURLOPT_SSL_VERIFYPEER" => "0" ]); try { $virusResponse = $virusClient->post('https://clamav.virus-scan.svc.cluster.local/scan', [ 'body' => $virusBody, 'verify' => false ]); if (strpos($virusResponse, 'Everything ok : false')) { return $responseArray = [ 'code' => 500, 'message' => BulkDocumentRepository::VIRUS_ERROR ]; } } catch (RequestException $exception) { return $responseArray = [ 'code' => 500, 'message' => BulkDocumentRepository::DEFAULT_ERROR ]; } } $response = $this->apiClient->post('s/homeoffice/cts/standardLine', [ 'query' => [ 'alf_ticket' => $this->tokenStorage->getAuthenticationTicket() ], 'body' => [ 'file' => $file2, 'name' => rawurlencode($standardLine->getName()), 'associatedUnit' => rawurlencode($standardLine->getAssociatedUnit()), 'associatedTopic' => rawurlencode($standardLine->getAssociatedTopic()), 'reviewDate' => rawurlencode(DateHelper::fromNativeOrNullToIso($standardLine->getReviewDate())), 'updateVersion' => $standardLine->isNew() ? "false" : "true", 'originalName' => rawurlencode($standardLine->getOriginalName()), ], ]); } catch (RequestException $exception) { $response = $exception->getResponse(); } if ($response->getStatusCode() !== 200) { switch ($response->getStatusCode()) { case '409': $responseBody = json_decode($response->getBody()->__toString()); return ['code' => 409, 'message' => $responseBody->message]; default: return ['code' => -1, 'message' => self::DEFAULT_ERROR]; } } return true; } /** * @param CtsCaseStandardLine $ctsCaseStandardLine * * @return bool */ public function update(CtsCaseStandardLine $ctsCaseStandardLine) { $ctsCaseStandardLine->setMimeType($ctsCaseStandardLine->getMimeType()); $nodeId = $ctsCaseStandardLine->getNodeId(); $response = $this->apiClient->put("s/api/node/$this->workspace/$this->store/$nodeId", [ 'headers' => ['Content-Type' => 'application/atom+xml;type=entry'], 'query' => ['alf_ticket' => $this->tokenStorage->getAuthenticationTicket()], 'body' => $this->atomHelper->generateAtomEntry( $ctsCaseStandardLine, $ctsCaseStandardLine->getName(), $this->caseStandardLineProperties ), ]); return $response->getStatusCode() == '200'; } /** * Get StandardLines * * @param string|null $unit * @param string|null $topic * @param string|null $documentName * * @return CtsCaseStandardLine[]|bool */ public function getStandardLines($unit, $topic, $documentName = null) { $select = [ 'cmis:objectId', 'cmis:name', 'cmis:creationDate', 'cmis:contentStreamMimeType', 'cts:reviewDate', 'cts:associatedTopic', 'cts:associatedUnit' ]; $from = 'cts:standardLine'; $where = $orWhere = $andWhere = []; $this->queryHelper ->addToWhereStatement($where, 'cts:associatedUnit', ' LIKE ', $unit) ->addToWhereStatement($where, 'cts:associatedTopic', ' LIKE ', $topic) ->addToWhereStatement($where, 'cmis:name', ' LIKE ', $documentName, true, true); $orderBy = $this->queryHelper->getQueueOrderByStatement('cts:reviewDate', 'ASC'); $query = $this->queryHelper ->constructQueryWithMultipleFilters($select, $from, $where, $orWhere, $andWhere, $orderBy); $response = $this->apiClient->get("s/cmis/query", ['query' => [ 'alf_ticket' => $this->tokenStorage->getAuthenticationTicket(), 'q' => $query ]]); if ($response->getStatusCode() != '200') { return false; } $standardLinesArray = $this->atomHelper->multiEntryFeedToArray( $response->getBody()->__toString(), 'cmisra:object', $this->caseStandardLineProperties ); $standardLines = []; foreach ($standardLinesArray as $standardLine) { array_push($standardLines, $this->factory->build($standardLine)); } return $standardLines; } /** * Get Standard Line * * @param string $nodeRef * * @return bool|CtsCaseStandardLine */ public function getStandardLine($nodeRef) { $response = $this->apiClient->get("s/api/node/$this->workspace/$this->store/$nodeRef", [ 'query' => ['alf_ticket' => $this->tokenStorage->getAuthenticationTicket()], ]); if ($response->getStatusCode() != '200') { return false; } return $this->factory->build($this->atomHelper->singleEntryFeedToArray( $response->getBody()->__toString(), 'cmisra:object', $this->caseStandardLineProperties, null )); } /** * Get StandardLines By Topics * * @param string[] $topics * @param string|null $unit * * @return CtsCaseStandardLine[]|bool */ public function getStandardLinesByTopics(array $topics, $unit = null) { $select = [ 'cmis:objectId', 'cmis:name', 'cmis:creationDate', 'cmis:contentStreamMimeType', 'cts:reviewDate', 'cts:associatedTopic', 'cts:associatedUnit' ]; $from = 'cts:standardLine'; $where = $orWhere = $andWhere = []; if (is_null($unit) === false) { $this->queryHelper->addToWhereStatement($where, 'cts:associatedUnit', '=', $unit); } $this->queryHelper->addWhereInToWhereStatement($where, 'cts:associatedTopic', $topics); $orderBy = $this->queryHelper->getQueueOrderByStatement('cts:reviewDate', 'ASC'); $query = $this->queryHelper ->constructQueryWithMultipleFilters($select, $from, $where, $orWhere, $andWhere, $orderBy); $response = $this->apiClient->get("s/cmis/query", ['query' => [ 'alf_ticket' => $this->tokenStorage->getAuthenticationTicket(), 'q' => $query ]]); if ($response->getStatusCode() != '200') { return false; } $standardLinesArray = $this->atomHelper->multiEntryFeedToArray( $response->getBody()->__toString(), 'cmisra:object', $this->caseStandardLineProperties ); $standardLines = []; foreach ($standardLinesArray as $standardLine) { array_push($standardLines, $this->factory->build($standardLine)); } return $standardLines; } /** * Delete Standard Line * * @param string $nodeRef * * @return bool */ public function deleteStandardLine($nodeRef) { $ctsCaseStandardLine = new CtsCaseStandardLine($this->workspace, $this->store); $ctsCaseStandardLine->setId($nodeRef); $nodeId = $ctsCaseStandardLine->getNodeId(); $response = $this->apiClient->delete("s/api/node/$this->workspace/$this->store/$nodeId", [ 'query' => ['alf_ticket' => $this->tokenStorage->getAuthenticationTicket()], ]); return $response->getStatusCode() == '204'; } /** * Get Standard Line File * * Given a CtsCaseStandardLine object, this function will download the file to /tmp/{nodeId} * and return the CtsCaseStandardLine object. * * @param string $nodeRef * * @return bool|CtsCaseStandardLine */ public function getStandardLineFile($nodeRef) { $standardLine = $this->getStandardLine($nodeRef); $nodeId = $standardLine->getNodeId(); $response = $this->apiClient->get("s/api/node/$this->workspace/$this->store/$nodeId/content", [ 'query' => ['alf_ticket' => $this->tokenStorage->getAuthenticationTicket()], 'save_to' => "/tmp/$nodeId", ]); if ($response->getStatusCode() != '200') { return false; } return $standardLine; } }
Java
UTF-8
4,737
3.1875
3
[]
no_license
package dp_6; import lombok.Getter; import lombok.Setter; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import static java.awt.BorderLayout.*; import static javax.swing.JFrame.*; import static javax.swing.JOptionPane.*; class Solitaer { @Getter private JFrame gui; private JPanel mainPanel; @Getter @Setter Model model; Solitaer() { this.model = new Model(); } void showGUI() { gui = new JFrame("Solitaer"); mainPanel = new MyPanel(); JPanel buttonPanel = createButtonPanel(); gui.add(mainPanel, CENTER); gui.add(buttonPanel, SOUTH); gui.setDefaultCloseOperation(EXIT_ON_CLOSE); gui.setSize(750, 700); gui.setVisible(true); } private JPanel createButtonPanel() { JPanel buttonPanel = new JPanel(); JButton undo = new JButton("undo"); JButton newGame = new JButton("new game"); buttonPanel.add(undo); buttonPanel.add(newGame); undo.addActionListener(e -> { boolean moveSuccessful = getModel().undoMove(); if (moveSuccessful) { mainPanel.repaint(); } else { showMessageDialog(mainPanel, "There are no moves to undo.", "Error", ERROR_MESSAGE); } }); newGame.addActionListener(e -> { setModel(new Model()); mainPanel.repaint(); }); return buttonPanel; } private class MyPanel extends JPanel implements MouseListener { boolean moveStarted = false; Point startPoint; Point endPoint; MyPanel() { this.addMouseListener(this); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); for (int row = 0; row < 7; row++) for (int col = 0; col < 7; col++) { g.setColor(Color.WHITE); g.draw3DRect(100 + row * 80, 100 + col * 80, 80, 80, true); if (model.field[row][col] == State.NOT) { g.setColor(Color.LIGHT_GRAY); g.fill3DRect(100 + col * 80, 100 + row * 80, 80, 80, true); } else if (model.field[row][col] == State.FREE) { g.setColor(Color.green); g.fill3DRect(100 + col * 80, 100 + row * 80, 80, 80, true); } else if (model.field[row][col] == State.USED) { g.setColor(Color.green); g.fill3DRect(100 + col * 80, 100 + row * 80, 80, 80, true); g.setColor(Color.red); g.fillOval(130 + 80 * col, 130 + 80 * row, 20, 20); } } } @Override public void mouseClicked(MouseEvent e) { int x = e.getX(); int y = e.getY(); int row = (y - 100) / 80; int col = (x - 100) / 80; if (moveStarted) { endPoint = new Point(row, col); boolean moveSuccessful = model.move(new Move(startPoint, endPoint)); if (moveSuccessful) { this.repaint(); if (model.gameIsWon()) { int n = showConfirmDialog(mainPanel, "Well done! You won... \n Would you like to play again?", "Congratulations", YES_NO_OPTION); if (n == YES_OPTION) { setModel(new Model()); this.repaint(); } else { getGui().setVisible(false); getGui().dispose(); } } } else{ showMessageDialog(mainPanel, "This move is not allowed.", "Error", ERROR_MESSAGE); } moveStarted = false; } else { moveStarted = true; startPoint = new Point(row, col); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } } }
JavaScript
UTF-8
4,268
2.59375
3
[ "MIT" ]
permissive
// TCPTransport.js "use strict"; var util = require("util"); var Slip = require("node-slip"); var events = require("events"); var net = require('net'); var log = require('./Logger'); // CRC algorithm based on Xmodem AVR code var calcCrc = function(data) { var crc = 0; var size = data.length; var i; var index = 0; while(--size >= 0) { crc = (crc ^ data[index++] << 8) & 0xFFFF; i = 8; do { if(crc & 0x8000) { crc = (crc << 1 ^ 0x1021) & 0xFFFF; } else { crc = (crc << 1) & 0xFFFF; } } while(--i); } return crc & 0xFFFF; }; var checkCrc = function(data) { var dataCrc, calcdCrc; // Getting crc from packet dataCrc = (data[data.length - 1]) << 8; dataCrc |= (data[data.length - 2]) & 0x00FF; // Calculating crc calcdCrc = calcCrc(data.slice(0, data.length - 2)); // Comparing return calcdCrc === dataCrc; }; var TCPTransport = function(port) { var self = this; self.noBind = true; self.fake = false; self.alreadyReady = false; self.port = port; // Serial port write buffer control self.writing = false; self.writeBuffer = []; var receiver = { data: function(input) { // Check CRC var crcOk = checkCrc(input); // Strip CRC data var data = input.slice(0, input.length - 2); if(crcOk) { self.emit("data", data); } else { self.emit("crcError", data); } }, framing: function( input ) { self.emit("framingError", input); }, escape: function( input ) { self.emit("escapeError", input); } }; self.parser = new Slip.parser(receiver); }; util.inherits(TCPTransport, events.EventEmitter); TCPTransport.prototype.connect = function() { var self = this; if(self.server != null) return; // Already connected self.server = net.createServer(function(sock) { log.info('TCP client connected: ' + sock.remoteAddress +':'+ sock.remotePort); if(self.sock != null) { log.warn('There is a bridge already connected, ignoring new connection'); return; } self.sock = sock; // TODO: Keep alive not working, try: https://www.npmjs.com/package/net-keepalive //self.sock.setTimeout(10000); self.sock.setKeepAlive(true, 0); self.sock.on("data", function(data) { self.parser.write(data); }); self.sock.on("connect", function() { self.emit("ready"); }); self.sock.on("error", function(err) { log.debug("Socket error"); self.emit("error", err); }); self.sock.on("end", function(err) { log.debug("Socket end"); self.emit("disconnect", err); self.sock = null; }); self.sock.on("close", function() { log.debug("Socket close"); self.emit("close"); self.sock = null; }); self.sock.on("timeout", function() { log.debug("Socket timeout"); self.sock.end(); }); if(!self.alreadyReady) self.emit("ready"); self.alreadyReady = true; }).listen(self.port); log.info("TCP Transport server listening on port", self.port); }; TCPTransport.prototype.close = function(callback) { if(!callback) callback = function(){}; var self = this; if(self.sock == null) return; self.sock.close(function(err) { if(err) return callback(err); }); }; TCPTransport.prototype.write = function(data) { var self = this; data = new Buffer(data); // Append CRC var crc = calcCrc(data); var crcBuf = new Buffer(2); crcBuf.writeUInt16LE(crc, 0); var buffer = Buffer.concat([data, crcBuf]); // Convert to Slip var slipData = Slip.generator(buffer); self.writeBuffer.push(slipData); self.writeNow(); }; TCPTransport.prototype.writeNow = function() { var self = this; if(self.sock == null) return; // Nothing to do here if(self.writeBuffer.length <= 0) return; // We are busy, do nothing if(self.writing) return; self.writing = true; // do nothing if we are in fake mode if(self.fake) { self.writing = false; return; } var data = self.writeBuffer.shift(); self.sock.write(data); //if(config.debug) console.log("Sending:", data); self.writing = false; if(self.writeBuffer.length > 0) self.writeNow(); }; module.exports = TCPTransport;
C#
UTF-8
14,615
2.640625
3
[]
no_license
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; namespace WindowsFormsApp4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } int Pic; //สถาณะของรูป private void pictureBox1_Click(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { Random zxc = new Random(); //สร้างตัวแปล แลนด้อม int bb = zxc.Next(1, 21); //จัดเก็บตัวแปล เเลนด้อม เพื่อสุ่มตัวเลข (1,21) button3.Enabled = true; //ทำใหปุ่มกดได้ button4.Enabled = true; //ทำให้ปุ่มกดได้ button5.Enabled = true; //ทำให้ปุ่มกดได้ button6.Enabled = true; //ทำให้ปุ่มกดได้ switch (bb) //ตรวจสอบเงื่อนไข { case 1: pictureBox1.Image = Properties.Resources.a1; //ถ้าสุ่มเเล้วได้ 1 มันจะทำการโชว์รูปที่ 1 Pic = 1; //สถาณะของรูปภาพ button3.Text = "Motorcycle"; button4.Text = "Shose";button5.Text = "Turtle";button6.Text = "Rocket"; //กำหนดคำตอบ break; //คำสั้งหยุด case 2: pictureBox1.Image = Properties.Resources.a2; //ถ้าสุ่มแล้วได้ 2 มันจะทำการโชว์รูปที่ 2 Pic = 2; //สถาณะของรูปภาพ button3.Text = "Bird"; button4.Text = "Cat"; button5.Text = "Lion"; button6.Text = "Tiger"; //กำหนดคำตอบ break; //คำสั่งหยุด case 3: pictureBox1.Image = Properties.Resources.a3; //ถ้าสุ่มแล้วได้ 3 มันจะโชว์รูปภาพที่ 2 Pic = 3; //สถาณะของรูปภาพ button3.Text = "Camera"; button4.Text = "Glass"; button5.Text = " Girl"; button6.Text = "Box"; //กำหนดคำตอบ break; //คำสั่งหยุด case 4: pictureBox1.Image = Properties.Resources.a4; //ถ้าสุ่มแล้วได้ 4 มันจะโชว์รูปภาพที่ 4 Pic = 4; //สถาณะของรูปภาพ button3.Text = "Door"; button4.Text = "Dog"; button5.Text = "Farm"; button6.Text = "Pig"; //กำหนดคำตอบ break; //คำสั่งหยุด case 5: pictureBox1.Image = Properties.Resources.a5; //ถ้าสุ่มแล้วได้ 5 มันจะโชว์ 5 Pic = 5; //สถาณะของรูปภาพ button3.Text = "Boat"; button4.Text = "Cake"; button5.Text = "Tiger"; button6.Text = "Duck"; //กำหนดคำตอบ break; //คำสั่งหยุด case 6: pictureBox1.Image = Properties.Resources.a6; Pic = 6; button3.Text = "Forest"; button4.Text = "Sock"; button5.Text = "Book"; button6.Text = "Bat"; break; case 7: pictureBox1.Image = Properties.Resources.a7; Pic = 7; button3.Text = "Orange"; button4.Text = "Market"; button5.Text = "Banana"; button6.Text = "Hat"; break; case 8: pictureBox1.Image = Properties.Resources.a8; Pic = 8; button3.Text = "Monkey"; button4.Text = "Glass"; button5.Text = "Glove"; button6.Text = "Apple"; break; case 9: pictureBox1.Image = Properties.Resources.a9; Pic = 9; button3.Text = "Island"; button4.Text = "Chick"; button5.Text = "Sport car"; button6.Text = "Bear"; break; case 10: pictureBox1.Image = Properties.Resources.a10; Pic = 10; button3.Text = "Boy"; button4.Text = "Starwberry"; button5.Text = "Heart"; button6.Text = "Money"; break; case 11: pictureBox1.Image = Properties.Resources.a11; Pic = 11; button3.Text = "Clock"; button4.Text = "Cutter"; button5.Text = "Pants"; button6.Text = "Bed"; break; case 12: pictureBox1.Image = Properties.Resources.a12; Pic = 12; button3.Text = "Bread"; button4.Text = "Rat"; button5.Text = "Knife"; button6.Text = "Glass"; break; case 13: pictureBox1.Image = Properties.Resources.a13; Pic = 13; button3.Text = "Flag"; button4.Text = "Fridge"; button5.Text = "Phone"; button6.Text = "Hand"; break; case 14: pictureBox1.Image = Properties.Resources.a14; Pic = 14; button3.Text = "Bike"; button4.Text = "Corn"; button5.Text = "Gun"; button6.Text = "Bus"; break; case 15: pictureBox1.Image = Properties.Resources.a15; Pic = 15; button3.Text = "Cow"; button4.Text = "Coffee"; button5.Text = "Mountain "; button6.Text = "Earth"; break; case 16: pictureBox1.Image = Properties.Resources.a16; Pic = 16; button3.Text = "Pen"; button4.Text = "Snake"; button5.Text = "Chair"; button6.Text = "Beer"; break; case 17: pictureBox1.Image = Properties.Resources.a17; Pic = 17; button3.Text = "Hen"; button4.Text = "Pencil"; button5.Text = "Mouse"; button6.Text = "Fruit"; break; case 18: pictureBox1.Image = Properties.Resources.a18; Pic = 18; button3.Text = "Food"; button4.Text = "Plane"; button5.Text = "Ruler"; button6.Text = "Home"; break; case 19: pictureBox1.Image = Properties.Resources.a19; Pic = 19; button3.Text = "Foot"; button4.Text = "Guitar"; button5.Text = "Feather"; button6.Text = "Horse"; break; case 20: pictureBox1.Image = Properties.Resources.a20; Pic = 20; button3.Text = "Nose"; button4.Text = "Car"; button5.Text = "Ring"; button6.Text = "Insect"; break; } } private void button3_Click(object sender, EventArgs e) { if (button3.Text == "Motorcycle"|| button3.Text == "Orange" || button3.Text == "Camera" || button3.Text == "Clock" || button3.Text == "Bike" || button3.Text == "Pen") //ถ้าเท็กบล็อคมีชื่อตามที่กำหนดไว้ { label3.Text = Convert.ToString(int.Parse(label3.Text) + 10); //จะเพิ่มคะแนนทีละ 10 MessageBox.Show("คุณตอบถูก"); //ถ้าตอบถูกจะโชว์คำว่า (คุณตอบถูก) button2_Click(sender, e); //คำสั่งกดปุ่มอัตโนมัติ } else { wrong(); //เรียกใช้เม็ดตอด button2_Click(sender, e); //คำสั่งกดปุ่มอัตโนมัติ } } private void timer1_Tick(object sender, EventArgs e) { int boss = Convert.ToInt32(label5.Text); //สร้าตัวแปล อิน เพื่อแทรค่าใน ลาเบลล์ boss = boss - 1; //ค่าของตัวแปลลดลงทีละ 1 label5.Text = Convert.ToString(boss); //แปลงค่าให้เป็นสติง if (boss == 0) //ถ้า บอส == 0 { label5.Text = "60"; //ให้ ลาเบลล์ มีค่าเท่ากับ 60 จะลดลงไปเลื่อยๆ label4.Text = Convert.ToString(int.Parse(label4.Text) - 1); //รับค่ามาเล้วจะลดลงทีละ 1 if (label4.Text == "0") //กำหนดค่าให้ ลาเบลล์ เป็น 0 { label4.Text = "00"; //กำหนดให้ ลาเบลล์ เวลาเป็น 00 label5.Text = "00"; //กำหนดให้ ลาเบลล์ เวลาเป็น 00 timer1.Stop(); //หยุดการจับเวลา MessageBox.Show("ได้คะแนนทั้งหมด : " + label3.Text); //หลังจกาทำงานเสร็จจะโชว์ผลคะแนนทั้งหมด Close(); //ปุ่มปิด } } } private void button6_Click(object sender, EventArgs e) { if(button6.Text=="Pig"|| button6.Text == "Apple") //ถ้าเท็กบล็อคมีชื่อตามที่กำหนดไว้ { label3.Text = Convert.ToString(int.Parse(label3.Text) + 10); //จะเพิ่มคะแนนทีละ 10 MessageBox.Show("คุณตอบถูก"); //ถ้าตอบถูกจะโชวขึ้นว่า (คุณตอบถูก) button2_Click(sender, e); //คำสั่งกดปุ่มอัตโนมัติ } else { wrong(); //เช็คเม็ดตอด button2_Click(sender, e); //คำสั่งกดปุ่มอัตโนมัติ } } private void Form1_Load(object sender, EventArgs e) { button2.Visible = false; //ซ่อนปุ่ม } private void button1_Click(object sender, EventArgs e) { timer1.Start(); //เริ่มจับเวลา label4.Text = "14"; //กดหนดให้เป็นเลข 14 label5.Text = "60"; //กดหนดให้เป็นเลข 60 button1.Visible = false; //ซ่อนปุ่ม 1 button2.Visible = true; //เปิดปุ่ม 2 } private void button4_Click(object sender, EventArgs e) { if(button4.Text=="Starwberry"|| button4.Text == "Coffee" || button4.Text == "Pencil" || button4.Text == "Plane" || button4.Text == "Guitar") //ถ้าเท็กบล็อคมีชื่อตามที่กำหนดไว้ { label3.Text = Convert.ToString(int.Parse(label3.Text) + 10); //จะเพิ่มทีละ 10 MessageBox.Show("คุณตอบถูก"); //ถ้าตอบถูกจะขึ้นว่า (คุณตอบถูกต้อง) button2_Click(sender, e); //คำสั่งกดปุ่มอัตโนมัติ } else { wrong(); //เช็คเม็ดตอด button2_Click(sender, e); //คำสั่งกดปุ่มอัตโนมัติ } } private void button5_Click(object sender, EventArgs e) { if(button5.Text == "Lion"|| button5.Text == "Tiger" || button5.Text == "Book" || button5.Text == "Sport car" || button5.Text == "Knife" || button5.Text == "Phone"|| button5.Text == "Ring") //ถ้าเท็กบล็อคมีชื่อตามที่กำหนดไว้ { label3.Text = Convert.ToString(int.Parse(label3.Text) + 10); //จะเพิ่มทีละ 10 MessageBox.Show("คุณตอบถูก"); //ถ้าตอบถูกจะขึ้นว่า (คุณตอบถูกต้อง) button2_Click(sender, e); //คำสั่งกดปุ่มอัตโนมัติ } else { wrong(); //เช็คเม็ดตอด button2_Click(sender, e); //คำสั่งกดปุ่มอัตโนมัติ } } void wrong() //สร้างเม็ดตอดเวลาตอบผิด { label3.Text = Convert.ToString(int.Parse(label3.Text) - 5); //ถ้าคุณตอบผิดจะลดลงทีละ 5 MessageBox.Show("คุณตอบผิด"); //ถ้าคุณตอบผิดจะโชว์ขึ้นว่า (คุณตอบผิด) if (int.Parse(label3.Text) < 0) //ถ้าคะแนนน้อยกว่า 0 { timer1.Stop(); //จะหยุดเวลา MessageBox.Show("Game Over!!!!" + "\r\n" + "ได้คะแนนทั้งหมด : " + label3.Text); //แล้วจะขึ้นโชว์ว่าเกมส์ โอเวอร์ Application.Exit(); } } } }
TypeScript
UTF-8
165
2.609375
3
[]
no_license
export interface BaseModel { id?: string; createdAt: Date; updatedAt: Date; } export interface IndexedBaseModel extends BaseModel { index: number; }
Java
UTF-8
4,821
3.015625
3
[]
no_license
package mapdemo; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class Mapdemo { public static void main(String[] args) { // Mapfunction(); tongjiguanjianzichuxiancishu(); } public static void tongjiguanjianzichuxiancishu() { final String fileName = "/Users/qilu/eclipse-workspace/exercice/src/main/java/mapdemo/Mapdemo.java"; final String keywords = "package ,import,public,void,final,static,new,file,if,catch,for,try,return"; List<String> contenList = ReadSourceFile(fileName); Set<String> keywordsSet = new HashSet(); keywordsSet.addAll(Arrays.asList(keywords.split(","))); //简单做法String[]keywordsArray=keywords.split(""); Map<String, Integer> keywordsmap = new HashMap<>(); for (String keyword : keywordsSet) {// 遍历关键字集合 keyword=keyword.trim(); for (String line : contenList) {// 内循环 每个关键字都遍历一次原码的所有行 // 统计每一行中keyword出现次数 int count = getLinekeyWordCont(line, keyword); // 将count放到map集合中 if (count == 0) continue; if (keywordsmap.containsKey(keyword)) { int oldCount = keywordsmap.get(keyword).intValue(); keywordsmap.put(keyword, new Integer(count + oldCount)); } else { keywordsmap.put(keyword, count); } } }//3遍历map集合(以关键字出现的次数来排序) for(Map.Entry<String,Integer>entry:keywordsmap.entrySet()) { System.out.println(entry.getKey()+"\t"+entry.getValue()); } //排序 System.out.println("-----------"); Map<String,Integer>treemap=new TreeMap<>(); treemap.putAll(keywordsmap); for(Map.Entry<String,Integer>entry:treemap.entrySet()) { System.out.println(entry.getKey()+"\t"+entry.getValue()); } } private static int getLinekeyWordCont(String line, String keyword) { if (line == null || line.length() == 0) return 0; // 可以在这添加其他逻辑判断 比如 跳过注释行 if (line.startsWith("/")) { return 0; } int count = 0; String strLine = new String(line); int index = -1; while ((index = strLine.indexOf(keyword)) != -1) { count++; strLine = strLine.substring(index + keyword.length() + 1); } return count; } private static List<String> ReadSourceFile(String fileName) { List<String> contenList = new ArrayList<>(); try (FileReader freader = new FileReader(fileName); BufferedReader reader = new BufferedReader(freader);) { String line = null; while ((line = reader.readLine()) != null) { if (line.trim().length() == 1) continue; contenList.add(line.trim()); } } catch (Exception e) { e.printStackTrace(); } return contenList; } public static void Mapfunction() { Map<String, Integer> hashMap = new HashMap<>(); hashMap.put("Monkey", 18); hashMap.put("Nami", 19); hashMap.put("sanji", 25); hashMap.put("nico", 26); hashMap.put("Rorona", 21); System.out.println("hashmap" + hashMap); Map<String, Integer> linkedHashMap = new LinkedHashMap<>(); linkedHashMap.put("Monkey", 18); linkedHashMap.put("Nami", 19); linkedHashMap.put("sanji", 25); linkedHashMap.put("nico", 26); linkedHashMap.put("Rorona", 21); System.out.println("linkedhashmap" + linkedHashMap); Map<String, Integer> treeMap = new TreeMap<>(); treeMap.put("Monkey", 18); treeMap.put("Nami", 19); treeMap.put("sanji", 25); treeMap.put("nico", 26); treeMap.put("Rorona", 21); System.out.println("treeMap" + treeMap); System.out.println("第一中遍历方式,通过map。keyset遍历key,通过key取出valeur"); for (String key : treeMap.keySet()) { System.out.println(key + "--" + treeMap.get(key)); } System.out.println("第二中遍历方式,通过map.entrySet迭代器遍历key和value"); Set<Map.Entry<String, Integer>> entrySet11 = treeMap.entrySet(); Iterator<Map.Entry<String, Integer>> entrySetIt = entrySet11.iterator(); while (entrySetIt.hasNext()) { Map.Entry<String, Integer> entry = entrySetIt.next(); System.out.println(entry.getKey() + "\t\t" + entry.getValue()); } System.out.println("第3中遍历方式,直接遍历map.entrySet集合"); for (Map.Entry<String, Integer> entry : treeMap.entrySet()) { System.out.println(entry.getKey() + "--" + entry.getValue()); } } } class MyTreeComparator implements Comparator<String> { //map的比较只对key进行 @Override public int compare(String key1, String key2) { if (key1.compareTo(key2) > 0) { return 1; } if (key1.compareTo(key2) > 0) { return -1; } return 0; } }
C++
UTF-8
409
2.984375
3
[ "MIT" ]
permissive
#pragma once #include <cstring> #include <type_traits> namespace kae { template <typename Result, typename Arg> Result bit_cast(const Arg& src) noexcept { static_assert(sizeof(Arg) == sizeof(Result)); static_assert(std::is_trivially_copyable_v<Arg>); static_assert(std::is_trivial_v<Result>); Result dst; std::memcpy(&dst, &src, sizeof(Result)); return dst; } } // namespace kae
Java
UTF-8
401
1.632813
2
[ "Apache-2.0" ]
permissive
package com.filip.versu.model.view; import com.filip.versu.model.Searchable; import com.filip.versu.model.view.abs.AbsBaseFeedViewModel; public class SearchHistoryFeedViewModel extends AbsBaseFeedViewModel<Searchable> { @Override public SearchHistoryFeedViewModel removeReferencesBeforeSerialization() { return this; } @Override public void fixReferences() { } }
Markdown
UTF-8
2,487
3.671875
4
[]
no_license
### JavaScript Loops and Repetitive Tasks This folder is the dedicated walkthrough regarding JavaScript Loops and executing repetitive code in JS. Some of the topics involve different types of loops, methods for exiting the loops, skipping loops and more. Full module's objectives can be found inside the walkthrough's link below. Beware of the code next to each file's name. This code corresponds to an exercise lecture in goconqr platform, inside the following link module below. ### JS Loops Working with loops in JS walkthrough. [Find more here](https://www.goconqr.com/en-US/c/60238/course_modules/106652) #### The trainer's path to this module: 1. Trainer introduces the need of executing code repeatedly and how hard would be otherwise. 2. The trainer introduces real world problems that can be executed easily by defining repetitive tasks 3. The trainer shows the individual parts a loop is comprised of. What are all the intermediate steps? 4. The trainer introduces the while loop. How it is used? Which problem does it solve? * **L-1** multiples_of_10s.js: **_Prereqisites_**: * >While loop basic functionality. * **L-2** odd_or_even.js: **_Prereqisites_**: * >While loop * >conditional_decisions-D module. * **L-3** fizzbuzz_loop.js: **_Prereqisites_**: * >All L-1 Prerequisites * **L-4** container_initial.js: **_Prereqisites_**: * >All L-1 Prerequisites 5. The trainer introduces the **break** keyword inside a while loop. Use an exercise to add this progressively. * **L-5** container_break.js: **_Prereqisites_**: * >All L-4 Prerequisites * >the break keyword. 6. The trainer introduces the **continue** keyword. Use an existing exercise to add this concept progressively * **L-6** container_continue.js: **_Prereqisites_**: * >All L-5 Prerequisites * >the continue keyword. 7. The trainer shows the alternative option of a for loop. Modify an existing exercise with this new concept. * **L-7** container_for.js: **_Prereqisites_**: * >All L-6 Prerequisites * >for loop. * **L-8** employees.js: **_Prereqisites_**: * >For loop * >conditional_decisions-D module. * **L-9** selling_clothes.js: **_Prereqisites_**: * >All L-8 Prerequisites 8. The trainer introduces the concept of nested loops, by showing the prime numbers from 1 to 100 problem. * **L-10** matrix_multiplication.js: **_Prereqisites_**: * > Nested for loops * **L-11** prime_numbers_refactor.js: **_Prereqisites_**: * >Nested loops * >conditional_decisions-D module.
Markdown
UTF-8
519
2.53125
3
[]
no_license
## 自己 Leetcode 刷题 的 代码 1. 分各种类别 --》每个不同的数据结构、不同的算法思想 2. 大都 记录了 自己的理解,心得 3. 后期开始,也 督促下 自己 做题 要有 时间概念,所以 记录了 几个时间点 1. 第一遍 做的时候,肯定 会很慢,套路见得少,不要 想不出来,还死扣。。。--》看答案去 2. `理解官方答案 和 自己落笔、整理完` 有一个 **鸿沟** --》 非常 费时间,但是 这步 必不可少!
Markdown
UTF-8
12,729
3.140625
3
[ "MIT" ]
permissive
# City Explorer **Author**: Eugene Monnier **Version**: 1.02.0 ## Overview The *City Explorer* project is a project to develop a backend server for a website that allows a user to request weather and event information by city. ## Getting Started ### Documentation [Node JS Docs](https://nodejs.org/en/) [NPM JS Docs](https://docs.npmjs.com/) [Express JS Docs](http://expressjs.com/en/4x/api.html) [Dotenv Docs](https://www.npmjs.com/package/dotenv) ### Configuration - `data` directory - with `geo.json` and `darksky.json`. - `.env` - with your PORT. Make sure this file is in your `.gitignore`. - `.gitignore` - with standard NodeJS configurations. - `.eslintrc.json` - with Code 301 course standards for the linter - `package.json` - with all dependencies and any associated details related to configuration. Dependencies required: - express - cors - dotenv - Note that the `package-lock.json` file is automatically created when dependencies are installed and ensures that future installations of the project use the same versions of the dependencies. ## Architecture This backend utilizes the JavaScript language including the following libraries: - Node JS - Express JS - Dotenv - cors ## Change Log <!-- Use this area to document the iterative changes made to your application as each feature is successfully implemented. Use time stamps. Here's an examples: --> 01-14-2020 11:30 - Application now has a fully-functional express server, with a GET route for the location resource. Returns location data for Lynwood for any search request. 01-14-2020 18:00 - Added Dark Sky daily weather forecast from darksky.json. 01-14-2020 20:00 - Included error handling ## Credits and Collaborations <!-- <Give credit (and a link) to other people or resources that helped you build this application. --> Ken Dickey Blandine Dasilveria Jin Kim ## Feature Request 1: *Locations* As a user of City Explorer, I want to enter the name of a location so that I can see data about the area of interest to me. ### Description **Given** that a user enters a valid location in the input **When** the user click the "Explore!" button **Then** the map will be populated with the location centered on the latititude and longitude of the search query Endpoint: `/location` Example Response: ``` { "search_query": "seattle", "formatted_query": "Seattle, WA, USA", "latitude": "47.606210", "longitude": "-122.332071" } ``` ### Features - [x] Create a route with a method of `get` and a path of `/location`. The route callback should invoke a function to convert the search query to a latitude and longitude. The function should use the provided JSON data. - [x] A constructor function will ensure that each object is created according to the same format when your server receives the external data. Ensure your code base uses a constructor function for this resource. - [x] Return an object which contains the necessary information for correct client rendering. See the sample response. - [x] Deploy your updated express server to Heroku. - [x] Confirm that your route is responding as expected by entering your deployed backend URL on the City Explorer app's welcome page. Then search for a location. You should see the map, but not any other data yet. ### Time Estimate ``` Estimate of time needed to complete: 1 hour Start time: 10:30 Finish time: 11:30 Actual time needed to complete: 1 hour ``` ## Feature Request 2: *Weather* As a user of City Explorer, I want to request current weather information so that I can learn more about the typical weather patterns in the location I had entered. ### Description **Given** that a user enters a valid location in the input **When** the user clicks the "Explore!" button **Then** the weather forecast for the upcoming eight days will be displayed in the browser Endpoint: `/weather` Example Response: ``` [ { "forecast": "Partly cloudy until afternoon.", "time": "Mon Jan 01 2001" }, { "forecast": "Mostly cloudy in the morning.", "time": "Tue Jan 02 2001" }, ... ] ``` ### Features - [x] Create a route with a method of `get` and a path of `/weather`. The callback should use the provided JSON data. - [x] A constructor function will ensure that each object is created according to the same format when the server receives data. Ensure your code base uses a constructor function for this resource. - [x] Using each weather object of the result, return an array of objects for each day of the response which contains the necessary information for correct client rendering. See the sample response. - [x] Deploy your updated server code to Heroku. - [x] Confirm that your route is responding as expected by entering your deployed backend URL on the City Explorer app's welcome page. Then search for a location. You should see the map, and now weather data. ### Time Estimate ``` Estimate of time needed to complete: 2 hours Start time: 12:00 Finish time: 18:00 Actual time needed to complete: 2.5 hours ``` ## Feature Request 3: *Errors* As a user, I want clear messages if something goes wrong so I know if I need to make any changes or try again in a different manner. ### Description **Given** that a user does not enter a valid location in the input **When** the user clicks the "Explore!" button **Then** the user will receive an error message on the page and the data will not be rendered properly Endpoints: `/location`, `/weather` Example Response: ``` { status: 500, responseText: "Sorry, something went wrong", ... } ``` ### Features - [x] Create a function to handle errors from any API call. - [x] Send a status of 500 and an error message to the client. - [x] Deploy your updated sever code to Heroku. - [x] Confirm that your route is responding as expected by entering your deployed backend URL on the City Explorer app's welcome page. Then search for an invalid location. The network inspector panel should show a 500 for the response to the AJAX query. ### Time Estimate ``` Estimate of time needed to complete: 1 hour Start time: 20:00 Finish time: 20:30 Actual time needed to complete: 30 mins ``` ## Feature Request 4: *Data Formatting* As a user, I want the application to provide properly formatted data so that I can view similar sata for any location I choose. ### Description **Given** that a user enters a valid location in the input **When** the user clicks the "Explore!" button **Then** the data will be rendered in the same format every time ### Features - [x] Refactor your getWeather callback to use .map and send the resulting array as your response to the client. Continue to use .map for the remainder of labs 7, 8, and 9. - [x] Redeploy your application. ### Time Estimate ``` Estimate of time needed to complete: 30 min Start time: 10:30 Finish time: 10:45 Actual time needed to complete: 15 min ``` ## Feature Request 5: *Location Name* As a user, I want to enter the name of a location so that I do not need to look up the latitude & longitude every time I learn about a new location. ### Description **Given** that a user enters a valid location in the input **When** the user clicks the "Explore!" button **Then** the map will be populated with the location centered on the latitude and longitude of the search query Endpoint: `/location` Example Response: ``` { "search_query": "seattle", "formatted_query": "Seattle, WA, USA", "latitude": "47.606210", "longitude": "-122.332071" } ``` ### Features - [x] Add an environment variable to your server named GEOCODE_API_KEY, and use it appropriately in your code. - [x] Your app should have a route with a method of get and a path of /location. Update the route callback to invoke a function to convert the search query to a latitude and longitude. The function should make a Superagent-proxied request to the Google Maps Geocoding API. - [x] Return an object which contains the necessary information for correct client rendering. See the sample response. - [x] Deploy your application. - [x] Confirm that your route is responding as expected by entering your deployed backend URL on the City Explorer app's welcome page. Then search for a location. ### Time Estimate ``` Estimate of time needed to complete: 1 hour Start time: 10:45 Finish time: Actual time needed to complete: ``` ## Feature Request 6: *Current Weather From Any Location* As a user, I want to request current weather information at any location, so that I can learn more about the typical weather patterns in the area of interest. ### Description **Given** that a user enters a valid location in the input **When** the user clicks the "Explore!" button **Then** the weather forecast for the upcoming eight days will be displayed in the browser Endpoint: `/weather` Example Response: ``` [ { "forecast": "Partly cloudy until afternoon.", "time": "Mon Jan 01 2001" }, { "forecast": "Mostly cloudy in the morning.", "time": "Tue Jan 02 2001" }, ... ] ``` ### Features - [x] Add an environment variable to your server named WEATHER_API_KEY, and use it appropriately in your code. - [x] Your app should have a route with a method of get and a path of /weather. The callback should make a Superagent-proxied request to the Dark Sky API for weather information. You will need to include in this request the latitude and longitude sent from the client in the query parameters. - [x] Using each weather object of the result, return an array of objects for each day of the response which contains the necessary information for correct client rendering. See the sample response. - [x] Deploy your application. - [x] Confirm that your route is responding as expected by entering your deployed backend URL on the City Explorer app's welcome page. Then search for a location. Verify weather data is displayed properly. ### Time Estimate ``` Estimate of time needed to complete: 1 hour Start time: 12:30 Finish time: 13:25 Actual time needed to complete: 55 minutes ``` ## Feature Request 6: *Eventful* As a user, I want to request information about events in the area, so that I can learn about what is taking place there. ### Description **Given** that a user enters a valid location in the input **When** the user clicks the "Explore!" button **Then** the first twenty events hosted in the area will be displayed in the browser Endpoint: `/events` Example Response: ``` [ { "link": "http://seattle.eventful.com/events/seattle-code-101-explore-software-development-/E0-001-126675997-3?utm_source=apis&utm_medium=apim&utm_campaign=apic", "name": "Seattle Code 101: Explore Software Development", "event_date": "Sat Dec 7 2019", "summary": "Thinking about a new career in software development? Start here! In this one-day workshop, you&#39;ll get a taste of a day in the life of a software developer. Code 101 helps you learn what it’s like to be a software developer through a day-long immersive course for beginners that focuses on front-end web development technologies. " }, { "link": "http://seattle.eventful.com/events/geekzonehosting-raspberry-pi-jam-session-code-c-/E0-001-121109275-3?utm_source=apis&utm_medium=apim&utm_campaign=apic", "name": "GeekZoneHosting Raspberry Pi Jam Session & Code Carnival 2019", "event_date": "Sat Dec 7 2019", "summary": "Join fellow coders, builders, and Raspberry Pi makers in an 8 hour all day event Jam Session builder and code-a-thone to celebrate computer science education week 2019." }, ... ] ``` ### Features: - [ ] Add an environment variable to your server named EVENTFUL_API_KEY, and use it appropriately in your code. - [ ] Create a route with a method of get and a path of /events. The callback should make a Superagent-proxied request to the Ticketmaster API using the necessary location information. - [ ] Create a corresponding constructor function for the result. - [ ] For each event in the result, return an object which contains the necessary information for correct client rendering. See the sample response. - [ ] Use your existing error handler function. - [ ] Redeploy your application. - [ ] Confirm that your route is responding as expected by entering your deployed backend URL on the City Explorer app's welcome page. Then search for a location. Verify event data is displayed properly. ### Time Estimate ``` Estimate of time needed to complete: 30 min Start time: 13:30 Finish time: Actual time needed to complete: ```
PHP
UTF-8
308
2.984375
3
[]
no_license
<?php class Enseignant{ private $login; private $password; public function __construct($_login, $_password){ $this->login = $_login; $this->password = $_password; } public function getLogin(){ return $this->login; } public function getPassword(){ return $this->password; } }
Java
UTF-8
5,479
2.078125
2
[ "MIT" ]
permissive
package com.apoem.mmxx.eventtracking.infrastructure.dao.support; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.apoem.mmxx.eventtracking.DateUtils; import com.apoem.mmxx.eventtracking.infrastructure.common.holder.SpringContextHolder; import com.apoem.mmxx.eventtracking.infrastructure.po.ro.support2.RoSupport3; import com.apoem.mmxx.eventtracking.infrastructure.po.ro.support2.Rooobject; import com.mongodb.client.result.DeleteResult; import lombok.extern.slf4j.Slf4j; import org.apache.commons.text.StringSubstitutor; import org.bson.Document; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions; import org.springframework.data.mongodb.core.mapreduce.MapReduceResults; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors; import java.util.stream.StreamSupport; /** * <p>Project: Event Tracking </p> * <p>Name: AbstractMapReduceDmDao </p> * <p>Description: 抽象mr dm </p> * <p>Date: 2020/7/14 12:47 </p> * <p>Company: Apoem, Co. All Rights Reserved. </p> * * @author papafan * @version v1.0 */ @Slf4j public class AbstractMapReduceDmDaoV4 { public MongoTemplate mongoTemplate() { return SpringContextHolder.getBean(MongoTemplate.class); } public void executeRemoveHistory(Dictate dictate, LocalDateTime localDateTime) { Map<String, Object> paramMap = new HashMap<>(); paramMap.put("date", Integer.parseInt(dateDayFormat(localDateTime))); StringSubstitutor stringSubstitutor = new StringSubstitutor(paramMap); String condition = stringSubstitutor.replace(dictate.getTargetQuery()); QuerySub query = new QuerySub(Document.parse(condition)); DeleteResult remove = mongoTemplate().remove(query, dictate.getTargetCollection()); } public MapReduceResults<Rooobject> mr(Dictate dictate) { String mapFunction = getMapFunction(dictate); String reduceFunction = getReduceFunction(dictate); QuerySub query = new QuerySub(Document.parse(dictate.getSourceQuery())); String temporaryCollectionName = dictate.getTemporaryCollection(); String sourceCollectionName = dictate.getSourceCollection(); return mongoTemplate().mapReduce( query, sourceCollectionName, mapFunction, reduceFunction, // new MapReduceOptions().outputCollection(temporaryCollectionName).finalizeFunction(finalizeFunction), new MapReduceOptions().outputCollection(temporaryCollectionName), Rooobject.class ); } protected String getReduceFunction(Dictate dictate) { String valueFieldNames = dictate.getValueFieldNames(); Map<String, String> valueMap = new Gson().fromJson(valueFieldNames, new TypeToken<Map<String, String>>() {}.getType()); return RoSupport3.gentReduce(valueMap); } private String getMapFunction(Dictate dictate) { Map<String, String> keyMap = new Gson().fromJson(dictate.getKeyFieldNames(), new TypeToken<Map<String, String>>() {}.getType()); Map<String, String> valueMap = new Gson().fromJson(dictate.getValueFieldNames(), new TypeToken<Map<String, String>>() {}.getType()); List<String> uniqueFieldName = new Gson().fromJson(dictate.getSourceUniqueFieldName(), new TypeToken<List<String>>() {}.getType()); return RoSupport3.gentMap(uniqueFieldName, keyMap, valueMap); } public String dateDayFormat(LocalDateTime localDateTime) { return DateUtils.literalYyyyMmDd(localDateTime); } public void insert(LocalDateTime localDateTime, MapReduceResults<Rooobject> rooobjects, Dictate dictate) { String targetCollectionName = dictate.getTargetCollection(); Iterator<Rooobject> iterator = rooobjects.iterator(); List<Map<String, Object>> maps = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false) .filter(Objects::nonNull) .map(ro -> { Map<String, Object> map = new HashMap<>(); // String keyFieldNames = dictate.getKeyFieldNames(); String valueFieldNames = dictate.getValueFieldNames(); Map<String, String> keyMap = new Gson().fromJson(keyFieldNames, new TypeToken<Map<String, String>>() {}.getType()); Map<String, String> valueMap = new Gson().fromJson(valueFieldNames, new TypeToken<Map<String, String>>() {}.getType()); keyMap.values().forEach(o -> map.put(o, ro.getId().get(o))); valueMap.values().forEach(o -> map.put(o, ro.getValue().get(o))); // map.put("pv", ro.getValue().get("pv")); map.put("uv", ro.getValue().get("uv")); // map.put("date_day", Integer.parseInt(dateDayFormat(localDateTime))); map.put("period_type", dictate.getPeriod()); Date current = new Date(); map.put("create_time", current); map.put("update_time", current); map.put("mark", 0); return map; }) .collect(Collectors.toList()); mongoTemplate().insert(maps, targetCollectionName); } }
JavaScript
UTF-8
162
2.75
3
[]
no_license
// console.log("Notes") // module.exports.age = 25 const addNote = (title, note) => { console.log("Adding", title, note); } module.exports = { addNote }
C#
UTF-8
5,555
2.671875
3
[]
no_license
using Lab_26.Models; using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; namespace Lab_26.Controllers { [Authorize] public class ItemsController : Controller { private ItemDAO dao = new ItemDAO(); // GET: Items public ActionResult Index() { return View(dao.GetItemList()); } // GET: Items/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Item item = dao.GetItem((int)id); if (item == null) { return HttpNotFound(); } return View(item); } // GET: Items/Create public ActionResult Create() { return View(); } // POST: Items/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ID,Name,Description,Quantity,Price,Image")] Item item) { try { if (ModelState.IsValid) { dao.AddItem(item); return RedirectToAction("Index"); } } catch (Exception e) { ViewBag.Message = $"Something went wrong: {e.Message}"; } return View(item); } // GET: Items/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Item item = dao.GetItem((int)id); if (item == null) { return HttpNotFound(); } return View(item); } // POST: Items/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ID,Name,Description,Quantity,Price,Image")] Item item) { try { if (ModelState.IsValid) { dao.EditItem(item); return RedirectToAction("Index"); } } catch (Exception e) { ViewBag.Message = $"Something went wrong: {e.Message}"; } return View(item); } public ActionResult Delete(int id) { dao.DeleteItem(id); return RedirectToAction("Index"); } public ActionResult ItemList() { dao.GetItemList(); List<Item> items = dao.GetItemList(); ViewBag.Items = items; return View(); } public ActionResult ViewCart() { return View("Cart"); } public ActionResult EmptyCart(int? id) { if (Session["Cart"] == null && id == null) { ViewBag.Message = "Nothing in cart"; return View(); } else { return View("Cart"); } } public ActionResult Cart(int id) { if (Session["Cart"] == null) { List<Item> cart = new List<Item>(); cart.Add((from i in dao.GetItemList() where i.ID == id select i).Single()); Session.Add("Cart", cart); } else { List<Item> cart = (List<Item>)(Session["Cart"]); cart.Add((from i in dao.GetItemList() where i.ID == id select i).Single()); } return View(); } //Sort Items in Store public ActionResult ItemListSorted(string column) { // LINQ Query if (column == "Name") { ViewBag.Items = (from i in dao.GetItemList() orderby i.Name select i).ToList(); } else if (column == "Description") { ViewBag.Items = (from i in dao.GetItemList() orderby i.Description select i).ToList(); } else if (column == "Price") { ViewBag.Items = (from i in dao.GetItemList() orderby i.Price select i).ToList(); } return View("ItemList"); } public ActionResult ItemListByDescription(string description, string name) { List<Item> items = (from i in dao.GetItemList() where i.Description.Contains(description) select i).ToList(); ViewBag.Items = items; return View("ItemList"); } protected override void Dispose(bool disposing) { if (disposing) { dao.Dispose(); } base.Dispose(disposing); } } }
JavaScript
UTF-8
2,631
2.59375
3
[ "MIT" ]
permissive
import React from 'react'; import Select from 'react-select'; function getStringValue(value) { return value ? value.value : ''; } function handleCallback(cb, value) { if (cb) { cb(value); } } class FormControlSelect extends React.Component { constructor(props) { super(props); this.state = { initialValue: true, }; } componentDidMount() { const { input, options, onSelect, autoSelect = false, autoFocus } = this.props; if (autoSelect && this.state.initialValue && options.length >= 1) { if (!input.value || options.length === 1) { input.onChange(getStringValue(options[0])); handleCallback(onSelect, options[0]); } } if (autoFocus && this.component) { this.component.focus(); } } /* * If there is only option and run only once to avoid duplicated calls and allow deleting initialValue */ componentWillReceiveProps(nextProps) { const { input, options, onSelect, autoSelect = true } = nextProps; if (autoSelect && this.state.initialValue && options.length >= 1) { if (!input.value || options.length === 1) { input.onChange(getStringValue(options[0])); handleCallback(onSelect, options[0]); } this.setState({ initialValue: false, }); } } render() { const { id, label, input, hasLabel, meta: { touched, error }, onSelect } = this.props; const formGroupClass = !touched ? 'form-group' : `form-group ${error ? 'has-error' : 'has-success'}`; return ( <div className={formGroupClass}> {hasLabel && <label htmlFor={id} className="control-label">{label}</label>} <Select ref={(component) => this.component = component} id={id} {...input} {...this.props} backspaceRemoves={false} placeholder={label} onChange={(value) => { const selected = getStringValue(value); input.onChange(selected); handleCallback(onSelect, value); }} onBlur={() => { input.onBlur(input.value.value); }} /> {touched && error && <span className="help-block">{error}</span>} </div> ); } } FormControlSelect.propTypes = { meta: React.PropTypes.object.isRequired, id: React.PropTypes.string, label: React.PropTypes.string.isRequired, input: React.PropTypes.object.isRequired, options: React.PropTypes.array.isRequired, onSelect: React.PropTypes.func, hasLabel: React.PropTypes.bool, autoSelect: React.PropTypes.bool, autoFocus: React.PropTypes.bool, }; export default FormControlSelect;
Java
UTF-8
1,974
2.171875
2
[ "Apache-2.0" ]
permissive
package org.folio.support.http; import org.folio.support.ProxyRelationship; import org.folio.support.ProxyRelationships; import io.restassured.response.ValidatableResponse; import lombok.NonNull; public class ProxiesClient { private final RestAssuredCollectionApiClient<ProxyRelationship, ProxyRelationships> client; public ProxiesClient(OkapiUrl okapiUrl, OkapiHeaders defaultHeaders) { client = new RestAssuredCollectionApiClient<>(okapiUrl.asURI("/proxiesfor"), defaultHeaders, ProxyRelationship.class, ProxyRelationships.class); } public ProxyRelationship createProxyRelationship( @NonNull ProxyRelationship proxyRelationship) { return client.createRecord(proxyRelationship); } public ValidatableResponse attemptToCreateProxyRelationship( @NonNull ProxyRelationship proxyRelationship) { return client.attemptToCreateRecord(proxyRelationship); } public ProxyRelationships getAllProxyRelationships() { return client.getAllRecords(); } public ProxyRelationships getProxyRelationships(String cqlQuery) { return client.getRecords(cqlQuery); } public void deleteProxyRelationship(String id) { client.attemptToDeleteRecord(id); } public ValidatableResponse attemptToDeleteProxyRelationship(String id) { return client.attemptToDeleteRecord(id); } public void deleteAllProxies() { final var proxyRelationships = getAllProxyRelationships(); proxyRelationships.getProxiesFor() .forEach(relationship -> deleteProxyRelationship(relationship.getId())); } public ProxyRelationship getProxyRelationship(String id) { return client.getRecord(id); } public ValidatableResponse attemptToGetProxyRelationship(String id) { return client.attemptToGetRecord(id); } public ValidatableResponse attemptToUpdateProxyRelationship( ProxyRelationship proxyRelationship) { return client.attemptToUpdateRecord(proxyRelationship.getId(), proxyRelationship); } }
Python
UTF-8
297
3.328125
3
[]
no_license
def spiralNumbers(n): m = [[0] * n for _ in range(n)] i, j, di, dj = 0, 0, 0, 1 for k in range(n * n): m[i][j] = k + 1 if (not -1 < i + di < n) or (not -1 < j + dj < n) or m[i + di][j + dj] != 0: di, dj = dj, -di i, j = i + di, j + dj return m
JavaScript
UTF-8
1,846
2.65625
3
[]
no_license
import React from 'react'; class Note extends React.Component { constructor(props) { super(props); this.state = { error: null, isLoaded: false, notes: [] }; } componentDidMount() { /*fetch("http://devb/projects/github/php-starter/starter/api/note")*/ fetch("http://localhost:8000/api/notes") //fetch("https://localhost:44356/api/note") .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, notes: result }); console.log(result); }, (error) => { console.log(error); this.setState({ isLoaded: true, error }); console.log(error); } ) } render() { const {error, isLoaded, notes} = this.state; if (error) { return <div className={'container mt-5'}>Erreur : {error.message}</div>; } else if (!isLoaded) { return <div className={'container mt-5'}>Chargement…</div>; } else { return ( <div className='container mt-5'> <div className='row'> <div className='col-12'> <table className='table'> <thead> <tr> <th scope="col">id</th> <th scope="col">title</th> <th scope="col">content</th> </tr> </thead> <tbody> {notes.map(note => ( <tr key={note.id}> <td>{note.id}</td> <td>{note.title}</td> <td>{note.content}</td> </tr> ))} </tbody> </table> </div> </div> </div> ); } } } export default Note;
Java
UTF-8
2,560
2.25
2
[]
no_license
package net.ion.radon.impl.let.sample; import java.sql.SQLException; import java.util.Map; import net.ion.framework.db.IDBController; import net.ion.framework.db.Rows; import net.ion.framework.db.bean.handlers.BeanHandler; import net.ion.framework.db.procedure.IQueryable; import net.ion.framework.db.procedure.IUserProcedure; import net.ion.radon.core.let.AbstractServerResource; import net.ion.radon.param.MyParameter; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.Put; import org.restlet.resource.ResourceException; public class EmployeeLet extends AbstractServerResource { @Get public Employee getEmployee() throws SQLException{ int empno = Integer.parseInt(getInnerRequest().getAttribute("empno")); IDBController dc = getDBController(); Rows rows = dc.createUserProcedure("emp@viewEmp(:empno)").addParam("empno", empno).execQuery() ; return (Employee)rows.toHandle(new BeanHandler(Employee.class)) ; } @Put protected Employee insEmployee() throws SQLException{ Employee emp = getEmployeeBean(); IDBController dc = getDBController(); IUserProcedure upt = dc.createUserProcedure("emp@addEmp(:empno,:ename,:desc)"); upt.addParam("empno", emp.getEmpNo()).addParam("ename", emp.getEname()).addParam("desc", emp.getDesc()) ; upt.execUpdate() ; return emp ; } @Delete protected int delEmployee() throws SQLException { int empno = Integer.parseInt(getInnerRequest().getAttribute("empno")); IDBController dc = getDBController(); IQueryable upt = dc.createUserProcedure("emp@delEmp(:empno)").addParam("empno", empno); upt.execUpdate() ; return empno ; } @Post protected Employee modEmployee() throws ResourceException, SQLException { Employee emp = getEmployeeBean(); IDBController dc = getDBController(); IUserProcedure upt = dc.createUserProcedure("emp@modEmp(:empno,:ename,:desc)"); upt.addParam("empno", emp.getEmpNo()).addParam("ename", emp.getEname()).addParam("desc", emp.getDesc()).execUpdate() ; return emp ; } private Employee getEmployeeBean() { Map<String, Object> params = getInnerRequest().getGeneralParameter() ; return MyParameter.create(params).toBean(Employee.class) ; } private IDBController getDBController() { return getContext().getAttributeObject(H2DB.class.getCanonicalName(), H2DB.class).getIDBController(); } public String toString() { return this.getClass().getCanonicalName(); } }
Swift
UTF-8
1,537
3.125
3
[ "MIT" ]
permissive
// // SCNVector3 + Extension.swift // 3.ARRuler // // Created by wz on 2017/10/11. // Copyright © 2017年 cc.onezen. All rights reserved. // import UIKit import SceneKit extension SCNVector3 { /**get the camera vector*/ static func positionTransform(transform: matrix_float4x4) -> SCNVector3{ return SCNVector3(transform.columns.3.x, transform.columns.3.y, transform.columns.3.z) } /**calculate the distance with two vector*/ func distance(to vector: SCNVector3) -> Float{ let distanceX = self.x - vector.x let distanceY = self.y - vector.y let distanceZ = self.z - vector.z return sqrt(distanceX*distanceX + distanceY*distanceY + distanceZ*distanceZ) } /**two vector draw a line*/ func drawLine(to vector: SCNVector3, color: UIColor) -> SCNNode{ let indices: [UInt32] = [0, 1] //create a geometry container let source = SCNGeometrySource(vertices: [self, vector]) //create a geometry element let element = SCNGeometryElement(indices: indices, primitiveType: .line) let geometry = SCNGeometry(sources: [source], elements: [element]) geometry.firstMaterial?.diffuse.contents = color let node = SCNNode(geometry: geometry) return node } } extension SCNVector3: Equatable { public static func ==(lhs: SCNVector3, rhs: SCNVector3) -> Bool { return lhs.x==rhs.x && lhs.y==rhs.y && lhs.z==rhs.z } }
C
UTF-8
780
2.796875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "Funciones.h" #include "sectores.h" void harcodeoSector(eSectores* list) { eSectores x[]= { {001,"Recursos Humanos",0}, {002,"IT",0}, {003,"Finanzas",0}, {004,"Auditoria",0}, {005,"Facility",0}, }; for(int i = 0; i< 5; i++) { list[i] = x[i]; } }; void viewSector(eSectores aSectores) { printf(" \nID:%d - Descripcion:%s\n ",aSectores.id,aSectores.descripcion); }; void viewSectores(eSectores list[], int len) { system("cls"); for(int i=0; i < len; i++) { if( list[i].isEmpty == 0) { viewSector(list[i]); } } };
Java
UTF-8
2,166
2.234375
2
[]
no_license
package com.niit.Ques3SpringMVC.Model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity public class Weather { @Id int id; @Temporal(TemporalType.DATE) Date datetime_utc; String conds; String dewptm; String fog; String hail; String hum; String pressurem; String rain; String snow; String tempm; String thunder; String tornado; String wdire; String city; public Date getDatetime_utc() { return datetime_utc; } public void setDatetime_utc(Date datetime_utc) { this.datetime_utc = datetime_utc; } public String getConds() { return conds; } public void setConds(String conds) { this.conds = conds; } public String getDewptm() { return dewptm; } public void setDewptm(String dewptm) { this.dewptm = dewptm; } public String getFog() { return fog; } public void setFog(String fog) { this.fog = fog; } public String getHail() { return hail; } public void setHail(String hail) { this.hail = hail; } public String getHum() { return hum; } public void setHum(String hum) { this.hum = hum; } public String getPressurem() { return pressurem; } public void setPressurem(String pressurem) { this.pressurem = pressurem; } public String getRain() { return rain; } public void setRain(String rain) { this.rain = rain; } public String getSnow() { return snow; } public void setSnow(String snow) { this.snow = snow; } public String getTempm() { return tempm; } public void setTempm(String tempm) { this.tempm = tempm; } public String getThunder() { return thunder; } public void setThunder(String thunder) { this.thunder = thunder; } public String getTornado() { return tornado; } public void setTornado(String tornado) { this.tornado = tornado; } public String getWdire() { return wdire; } public void setWdire(String wdire) { this.wdire = wdire; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
C++
UTF-8
3,099
2.625
3
[ "Apache-2.0" ]
permissive
#include "xo/system/assert.h" #include "log.h" #include "log_sink.h" #include <stdarg.h> #include <vector> #include <iostream> #include <algorithm> namespace xo { namespace log { void std_cout_log( level l, const std::string& msg ) { std::cout << msg << std::endl; } level lowest_log_level = level::never_log_level; std::vector< sink* > global_sinks; void log_string( level l, const string& str ) { // no need to do additional test_log_level(), no performance gain for ( auto s : global_sinks ) s->try_send_log_message( l, str ); } void log_vstring( level l, const char* format, va_list list ) { if ( test_log_level( l ) ) // check for global log level first { char buf[ 1024 ]; vsnprintf( buf, sizeof( buf ), format, list ); log_string( l, string( buf ) ); // #todo: use string_view } } void add_sink( sink* s ) { xo_assert( s != nullptr ); if ( std::find( global_sinks.begin(), global_sinks.end(), s ) == global_sinks.end() ) { global_sinks.push_back( s ); get_global_log_level(); } } void remove_sink( sink* s ) { auto it = std::find( global_sinks.begin(), global_sinks.end(), s ); if ( it != global_sinks.end() ) global_sinks.erase( it ); get_global_log_level(); } void set_global_log_level( level l ) { for ( auto s : global_sinks ) s->set_log_level( l ); lowest_log_level = l; } level get_global_log_level() { lowest_log_level = critical_level; for ( auto s : global_sinks ) if ( s->get_log_level() < lowest_log_level ) lowest_log_level = s->get_log_level(); return lowest_log_level; } bool test_log_level( level l ) { return l >= lowest_log_level; } void messagef( level l, const char* format, ... ) { va_list va; va_start( va, format ); log_vstring( l, format, va ); va_end( va ); } void tracef( const char* format, ... ) { if constexpr ( XO_STATIC_LOG_LEVEL <= trace_level ) { va_list va; va_start( va, format ); log_vstring( trace_level, format, va ); va_end( va ); } } void debugf( const char* format, ... ) { if constexpr ( XO_STATIC_LOG_LEVEL <= debug_level ) { va_list va; va_start( va, format ); log_vstring( debug_level, format, va ); va_end( va ); } } void infof( const char* format, ... ) { if constexpr ( XO_STATIC_LOG_LEVEL <= info_level ) { va_list va; va_start( va, format ); log_vstring( info_level, format, va ); va_end( va ); } } void warningf( const char* format, ... ) { if constexpr ( XO_STATIC_LOG_LEVEL <= warning_level ) { va_list va; va_start( va, format ); log_vstring( warning_level, format, va ); va_end( va ); } } void errorf( const char* format, ... ) { if constexpr ( XO_STATIC_LOG_LEVEL <= error_level ) { va_list va; va_start( va, format ); log_vstring( error_level, format, va ); va_end( va ); } } void criticalf( const char* format, ... ) { if constexpr ( XO_STATIC_LOG_LEVEL <= critical_level ) { va_list va; va_start( va, format ); log_vstring( critical_level, format, va ); va_end( va ); } } } }
Ruby
UTF-8
247
2.734375
3
[]
no_license
# frozen_string_literal:true # User class represents a single player class User attr_reader :x_or_o def initialize(x_or_o, name = x_or_o) @name = name == '' ? x_or_o : name @x_or_o = x_or_o end def to_s @name.to_s end end
PHP
UTF-8
89
2.53125
3
[]
no_license
<?php $a["a"] = "Cat"; $a["b"] = "Dog"; print_r($a); echo "<br />"; echo $a["C言"]; ?>
Java
UTF-8
1,805
1.984375
2
[]
no_license
package ins.sino.claimcar.regist.vo; /** * Custom VO class of PO VprppheadId */ public class PrppMainVo implements java.io.Serializable { private static final long serialVersionUID = 1L; private String endorseNo; private String policyNo; private String classCode; private String riskCode; private String printNo; private String language; private String policyType; private String insuredCode; private String insuredName; private Long chgAmount; public String getEndorseNo() { return endorseNo; } public void setEndorseNo(String endorseNo) { this.endorseNo = endorseNo; } public String getPolicyNo() { return policyNo; } public void setPolicyNo(String policyNo) { this.policyNo = policyNo; } public String getClassCode() { return classCode; } public void setClassCode(String classCode) { this.classCode = classCode; } public String getRiskCode() { return riskCode; } public void setRiskCode(String riskCode) { this.riskCode = riskCode; } public String getPrintNo() { return printNo; } public void setPrintNo(String printNo) { this.printNo = printNo; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getPolicyType() { return policyType; } public void setPolicyType(String policyType) { this.policyType = policyType; } public String getInsuredCode() { return insuredCode; } public void setInsuredCode(String insuredCode) { this.insuredCode = insuredCode; } public String getInsuredName() { return insuredName; } public void setInsuredName(String insuredName) { this.insuredName = insuredName; } public Long getChgAmount() { return chgAmount; } public void setChgAmount(Long chgAmount) { this.chgAmount = chgAmount; } }
Java
UTF-8
883
2.359375
2
[]
no_license
/** * */ package com.example.demo.contoller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.example.demo.negocio.IDescuento; /** * @author 201905 * */ @org.springframework.stereotype.Controller public class ControladorDescuento { @Autowired IDescuento descuento; @RequestMapping("descuento") public String CalculaDescuento(@RequestParam("nombre")String n, ModelMap model) { // el container nos genera la inyección de dependencias para poder // utilizar el objeto tal cual, al que le llamamos al metodo calcular ddescuento Integer descuentoTotal = descuento.calculaDescuento(n); model.addAttribute("d",descuentoTotal); return "descuento"; } }
TypeScript
UTF-8
1,767
2.953125
3
[]
no_license
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { AppThunk, RootState } from '../../app/store'; type TodoType = { todoInfo: { userId: number, id: number, title: string, completed: boolean, } } const initialState: TodoType = { todoInfo: { userId: 0, id: 0, title: 'init', completed: false, } } export const todoSlice = createSlice({ name: 'todo', initialState, reducers: { show(state) { return { ...state.todoInfo, todoInfo: { userId: 2, id: 3, title: 'show', completed: true, } } }, getTodo(state, action: PayloadAction<TodoType>) { const todoInfo = action.payload.todoInfo return { ...state.todoInfo, todoInfo: { userId: todoInfo.userId, id: todoInfo.id, title: todoInfo.title, completed: todoInfo.completed, } } } } }) export const { show, getTodo } = todoSlice.actions; export const getTodoAsync = (id: number): AppThunk => dispatch => { fetch(`https://jsonplaceholder.typicode.com/todos/${id}`) .then(res => res.json()) .then(data => { const todo: TodoType = { todoInfo: { userId: data.userId, id: data.id, title: data.title, completed: data.completed, } } dispatch(getTodo(todo)) }) .catch(error => console.log(error)) } export const selectTodo = (state: RootState) => state.todo.todoInfo export default todoSlice.reducer
PHP
UTF-8
1,201
2.53125
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateResultsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('results', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('student_id')->default(0); $table->integer('season_id')->default(0); $table->integer('class_id')->default(0); $table->integer('teacher_id')->default(0); $table->integer('subject_id')->default(0); $table->integer('assessment')->default(0); $table->integer('exam_score')->default(0); $table->integer('total')->default(0); $table->tinyInteger('approved')->default(0); $table->tinyInteger('processed')->default(0); $table->integer('times_uploaded')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('results'); } }
Java
UTF-8
599
2.09375
2
[]
no_license
package com.chen.springboot.service; import com.chen.springboot.po.User; public interface UserService { User findUserId(int id); /** * 登录 * @param username 用户名 * @param psaaword 密码 * @return */ String findUserAndPw(String username,String psaaword); /** * 删除用户 * @param id 用户id */ String deletUser(int id); /** * 添加用户 * @param user */ String addUser(User user); /** * 更新用户 * @param user * @return */ String updateUser(User user); }
JavaScript
UTF-8
7,445
2.6875
3
[ "MIT" ]
permissive
// =================================================================== // COUNT TASKS // =================================================================== function countTasks() { $('.tasks_counter').each(function() { var counter = $(this), currentLi = counter.closest('.whole_column').find('li'), numberOfTasks = currentLi.length; counter.text(numberOfTasks); }); } // =================================================================== // MAKE HEIGHTS 0F BODY, #tasks_div AND WINDOW EQUAL // =================================================================== function setHeight() { var windowHeight = $(window).innerHeight(); $('body').css('min-height', windowHeight); $('#tasks_div').css('min-height', windowHeight); }; // =================================================================== // CALL FUNCTIONS ON RESIZE // =================================================================== $(window).resize(function() { setHeight(); }); // =================================================================== // CREATE addNewTask() WITH FOCUSED INPUT // =================================================================== function addNewTask(inputParam) { var newTask = inputParam.val(), person = inputParam.closest('.column_info_container').find('input[name=person]:checked').val(); if (newTask.length > 0) { var currentColumn = inputParam.closest('.column_info_container').find('.columns-ul'); if (person != undefined) { currentColumn.append( "<li>" + "<a href='#' class='task_link'>" + newTask + "</a>" + "<span class='pic_span'><img src=images/"+person+".png></span>" + "</li>" ); } else { currentColumn.append( "<li>" + "<a href='#' class='task_link'>" + newTask + "</a>" + "<span class='pic_span'><img src=images/not_asigned.png></span>" + "</li>" ); } inputParam.val(""); } } // =================================================================== // CREATE addBtnClick() WITH FOCUSED INPUT // CALL addNewTask(inputParam) AND countTasks(); // =================================================================== function addBtnClick(inputParam) { var currentAddBtnSmall = inputParam.closest('.column_info_container').find('.addBtnSmall'); currentAddBtnSmall.on('click', function(e) { e.preventDefault(); addNewTask(inputParam); countTasks(); currentAddBtnSmall.off('click'); }); } // =================================================================== // =================================================================== // DOCUMENT READY // =================================================================== // =================================================================== $(document).ready(function() { // ================================================================ // HEADER ACTIVE LINK // ================================================================ var activeLink = 'header ul li a.header_a'; $(activeLink).on('click', function() { $(activeLink).removeClass('active_nav'); $(this).addClass('active_nav'); }); // ================================================================ // HANDLEBARS SCRIPT // ================================================================ /* globals document, Handlebars */ var waitingList, waitingListTemplateHtml, waitingListTemplate, progressList, progressListTemplateHtml, progressListTemplate, reviewList, reviewListTemplateHtml, reviewListTemplate; // WAITING LIST waitingList = [{ task: 'Waiting Task 01Waiting Task 01Waiting Task 01Waiting Task 0101Waiting Task 01', asigned: 'images/pesho.png' }, { task: 'Waiting Task 02', asigned: 'images/pesho.png' }, { task: 'Waiting Task 03', asigned: 'images/pesho.png' }, { task: 'Waiting Task 04', asigned: 'images/pesho.png', }, { task: 'Waiting Task 05', asigned: 'images/gosho.png' }, { task: 'Waiting Task 06', asigned: 'images/gosho.png' }, { task: 'Waiting Task 07', asigned: 'images/gosho.png', }, { task: 'Waiting Task 08', asigned: 'images/spas.png' }, { task: 'Waiting Task 09', asigned: 'images/gosho.png' }, { task: 'Waiting Task 10', asigned: 'images/mimi.png' }]; waitingListTemplateHtml = document.getElementById('waiting-list-template').innerHTML; waitingListTemplate = Handlebars.compile(waitingListTemplateHtml); document.getElementById('column_1').innerHTML = waitingListTemplate({waitingList: waitingList}); // PROGRESS LIST progressList = [{ task: 'In Progress Task 01', asigned: 'images/mimi.png' }, { task: 'In Progress Task 02', asigned: 'images/mimi.png' }, { task: 'In Progress Task 03', asigned: 'images/gosho.png' }, { task: 'In Progress Task 04', asigned: 'images/gosho.png', }, { task: 'In Progress Task 05', asigned: 'images/spas.png' }, { task: 'In Progress Task 06', asigned: 'images/spas.png' }]; progressListTemplateHtml = document.getElementById('progress-list-template').innerHTML; progressListTemplate = Handlebars.compile(progressListTemplateHtml); document.getElementById('column_2').innerHTML = progressListTemplate({progressList: progressList}); // REVIEW LIST reviewList = [{ task: 'Review/Confirm Task 01', asigned: 'images/spas.png' }, { task: 'Review/Confirm Task 02', asigned: 'images/spas.png' }, { task: 'Review/Confirm Task 03', asigned: 'images/spas.png' }, { task: 'Review/Confirm Task 04', asigned: 'images/gosho.png', }, { task: 'Review/Confirm Task 05', asigned: 'images/gosho.png' }, { task: 'Review/Confirm Task 06', asigned: 'images/mimi.png', }, { task: 'Review/Confirm Task 08', asigned: 'images/mimi.png' }, { task: 'Review/Confirm Task 09', asigned: 'images/mimi.png' }, { task: 'Review/Confirm Task 10', asigned: 'images/pesho.png', }, { task: 'Review/Confirm Task 11', asigned: 'images/pesho.png', }, { task: 'Review/Confirm Task 12', asigned: 'images/pesho.png' }]; reviewListTemplateHtml = document.getElementById('review-list-template').innerHTML; reviewListTemplate = Handlebars.compile(reviewListTemplateHtml); document.getElementById('column_3').innerHTML = reviewListTemplate({reviewList: reviewList}); // ================================================================ // SHOW ADD INPUT // ================================================================ $('.addBtn').on('click', function() { $(this).closest('.add_container').find('.add_div').toggle(); }); // ================================================================ // GET FOCUSED INPUT // CALL addBtnClick() // ================================================================ $('.add_input').on('focus',function() { var currentInput = $(this); addBtnClick(currentInput); }); // CALL FUNCTIONS countTasks(); setHeight(); });
Markdown
UTF-8
663
2.71875
3
[]
no_license
# 为什么会废弃 componentwillMount Fiber之后,由于任务可中断, willMount可能被执行多次(fiber算法是异步渲染,异步渲染 可能因为高优先级任务的出现被打断现有的任务导致willMount被多次执行) 首先这个函数的功能完全可以使用componentDidMount和constructor来代替,异步获取的数据的情况上面已经说明了,而如果抛去异步获取数据,其余的即是初始化而已,这些功能都可以在constructor中执行,除此之外,如果我们在willMount中订阅事件,但在服务端这并不会执行willUnMount事件,也就是说服务端会导致内存泄漏
Java
UTF-8
6,262
2.265625
2
[]
no_license
package cl.project.myapplication; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.PolylineOptions; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import cz.msebera.android.httpclient.Header; public class MainActivity extends AppCompatActivity { EditText lcorreo, lpass; private AsyncHttpClient client = new AsyncHttpClient(); private static final String TAG = "MainActivity"; private static final int ERROR_DIALOG_REQUEST = 9001; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lcorreo = (EditText) findViewById(R.id.loginCorreo); lpass = (EditText) findViewById(R.id.loginPass); } public boolean isServicesOK() { Log.d(TAG, "isServicesOK: checking google services version"); int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MainActivity.this); if (available == ConnectionResult.SUCCESS) { //everything is fine and the user can make map requests Log.d(TAG, "isServicesOK: Google Play Services is working"); return true; } else if (GoogleApiAvailability.getInstance().isUserResolvableError(available)) { //an error occured but we can resolve it Log.d(TAG, "isServicesOK: an error occured but we can fix it"); Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(MainActivity.this, available, ERROR_DIALOG_REQUEST); dialog.show(); } else { Toast.makeText(this, "You can't make map requests", Toast.LENGTH_SHORT).show(); } return false; } public void buttonLogin(View view) { if (lcorreo.getText().toString().isEmpty() || lpass.getText().toString().isEmpty()) { Toast.makeText(this, "Debe llenar todos los campos", Toast.LENGTH_SHORT).show(); } else { procesaSesion(); } } public void procesaSesion() { String url = "https://www.rendicionsostenedor.cl/iniciarsesion"; RequestParams params = new RequestParams(); params.add("mail", lcorreo.getText().toString()); params.add("pass", lpass.getText().toString()); client.post(url, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { if (statusCode == 200) { String respuesta = new String(responseBody); String b = respuesta.toString().replace("{", ""); String c = b.toString().replace("}", ""); String d = c.toString().replace("\"", ""); String valido = "result:Usuario valido"; if (d.equals(valido)) { if (isServicesOK()) { Intent intent = new Intent(MainActivity.this, MapsActivity.class); intent.putExtra("a", "c"); startActivity(intent); finish(); } } else { printToast("Correo o contraseña invalida"); } /** try { JSONArray json = new JSONArray(respuesta); String result = json.getJSONObject(0).getString("result:"); printToast(result); finish(); /* JSONArray json = new JSONArray(respuesta); if (isServicesOK()){ Button btnLogin = (Button) findViewById(R.id.btnLogin); Intent intent = new Intent(MainActivity.this, MapsActivity.class); startActivity(intent); } } catch (JSONException e) { e.printStackTrace(); printToast("Usuario incorrecto"); }*/ } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Salir") .setMessage("Estás seguro?") .setNegativeButton(android.R.string.cancel, null)// sin listener .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {// un listener que al pulsar, cierre la aplicacion @Override public void onClick(DialogInterface dialog, int which) { // Salir MainActivity.this.finish(); } }) .show(); // Si el listener devuelve true, significa que el evento esta procesado, y nadie debe hacer nada mas return true; } // para las demas cosas, se reenvia el evento al listener habitual return super.onKeyDown(keyCode, event); } public void printToast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } public void btnregisterr(View view) { Intent intent = new Intent(MainActivity.this, RegistrarActivity.class); startActivity(intent); } }
PHP
UTF-8
12,674
2.671875
3
[]
no_license
<?php require_once("ShipClasses.php"); class FighterFlight extends BaseShip{ public $shipSizeClass = -1; //0:Light, 1:Medium, 2:Heavy, 3:Capital, 4:Enormous public $imagePath = "img/ships/null.png"; public $iconPath, $shipClass; public $systems = array(); public $agile = true; public $turncost; public $turndelaycost = 0; public $accelcost = 1; public $rollcost = 1; public $pivotcost = 1; public $currentturndelay = 0; public $iniative = "N/A"; public $iniativebonus = 0; public $gravitic = false; public $phpclass; public $forwardDefense, $sideDefense; public $destroyed = false; public $pointCost = 0; public $faction = null; public $flight = true; public $hasNavigator = false; public $superheavy = false; public $flightSize = 1; protected $flightLeader = null; public $offensivebonus, $freethrust; public $jinkinglimit = 0; public $canvasSize = 200; public $fireOrders = array(); //following values from DB public $id, $userid, $name, $campaignX, $campaignY; public $rolled = false; public $rolling = false; public $team; protected $dropOutBonus = 0; public $movement = array(); function __construct($id, $userid, $name, $slot){ $this->id = (int)$id; $this->userid = (int)$userid; $this->name = $name; $this->slot = $slot; } private $autoid = 1; public function getInitiativebonus($gamedata){ $initiativeBonusRet = parent::getInitiativebonus($gamedata); if($this->hasNavigator){ $initiativeBonusRet += 5; } return $initiativeBonusRet; } public function getDropOutBonus(){ return $this->dropOutBonus; } public function getSystemById($id){ foreach ($this->systems as $system){ if ($system->id == $id){ return $system; } foreach ($system->systems as $fs){ if ($fs->id == $id){ return $fs; } } } return null; } /*returns a sample fighter, if one needs to review example of what's in flight*/ public function getSampleFighter(){ return $this->systems[1]; } /*returns number of still active craft in flight*/ public function countActiveCraft($turn){ $countActive = 0; foreach($this->systems as $ftr){ if(!$ftr->isDestroyed($turn)) $countActive++; } return $countActive; }//endof function countActiveCraft /*redefinition - as defensive systems will be on actual fighters*/ /*assuming all fighters are equal, it's enough to get system from first fighter, whether it's alive or not!*/ public function getDamageMod($shooter, $pos, $turn, $weapon){ $affectingSystems = array(); $fighter = $this->systems[1]; foreach($fighter->systems as $system){ if (!$this->checkIsValidAffectingSystem($system, $shooter, $pos, $turn, $weapon)) continue; $mod = $system->getDefensiveDamageMod($this, $shooter, $pos, $turn, $weapon); if ( !isset($affectingSystems[$system->getDefensiveType()]) || $affectingSystems[$system->getDefensiveType()] < $mod){ $affectingSystems[$system->getDefensiveType()] = $mod; } } return array_sum($affectingSystems); } /*redefinition - as defensive systems will be on actual fighters*/ /*assuming all fighters are equal, it's enough to get system from first fighter, whether it's alive or not!*/ public function getHitChanceMod($shooter, $pos, $turn, $weapon){ $affectingSystems = array(); $fighter = $this->systems[1]; foreach($fighter->systems as $system){ if (!$this->checkIsValidAffectingSystem($system, $shooter, $pos, $turn, $weapon)) continue; $mod = $system->getDefensiveHitChangeMod($this, $shooter, $pos, $turn, $weapon); if ( !isset($affectingSystems[$system->getDefensiveType()]) //no system of this kind is taken into account yet, or it is but it's weaker || $affectingSystems[$system->getDefensiveType()] < $mod){ $affectingSystems[$system->getDefensiveType()] = $mod; } } return (-array_sum($affectingSystems)); } /*redefinition; for fighter, don't check whether system is destroyed - it doesn't matter as long as entire flight isn't!*/ /*also, fighter systems don't get disabled :)*/ private function checkIsValidAffectingSystem($system, $shooter, $pos, $turn, $weapon){ if (!($system instanceof DefensiveSystem)) return false; //this isn't a defensive system at all //if the system has arcs, check that the position is on arc if(is_int($system->startArc) && is_int($system->endArc)){ //get bearing on incoming fire... if($weapon->ballistic){ $relativeBearing = $this->getBearingOnPos($pos); }else{ //direct fire weapon - check from shooter... $relativeBearing = $this->getBearingOnUnit($shooter); } //if not on arc, continue! if (!mathlib::isInArc($relativeBearing, $system->startArc, $system->endArc)){ return false; } } return true; }//endof function checkIsValidAffectingSystem public function getSystemByName($name){ foreach ($this->systems as $fighter){ foreach ($fighter->systems as $fs){ if ($fs->name == $name) return $fs; } } } public function getFighterBySystem($id){ foreach ($this->systems as $fighter){ foreach ($fighter->systems as $fs){ if ($fs->id == $id) return $fighter; } } } protected function addSystem($fighter, $loc = null){ $fighter->setUnit($this); $fighter->id = $this->autoid; $fighter->location = sizeof($this->systems); $this->autoid++; $fighterSys = array(); //add ramming attack //check whether game id is safe (can be safely be deleted lin May 2018) or so) ///already safe enough, commenting out! //if ((TacGamedata::$currentGameID >= TacGamedata::$safeGameID) || (TacGamedata::$currentGameID < 1)){ //check if ramming attack is already added $alreadyRamming = false; foreach ($fighter->systems as $system){ if ($system instanceof RammingAttack) $alreadyRamming = true; } if(!$alreadyRamming){ $fighter->addAftSystem(new RammingAttack(0, 0, 360, 0, 0)); } //} foreach ($fighter->systems as $system){ $system->setUnit($this); $system->id = $this->autoid; $this->autoid++; $fighterSys[$system->id] = $system; } $fighter->systems = $fighterSys; $this->systems[$fighter->id] = $fighter; } //endof function addSystem public function getPreviousCoPos(){ $pos = $this->getCoPos(); for ($i = sizeof($this->movement)-1; $i>=0; $i--){ $move = $this->movement[$i]; $pPos = $move->getCoPos(); if ( $pPos["x"] != $pos["x"] || $pPos["y"] != $pos["y"]) return $pPos; } return $pos; } public function getDEW($turn){ foreach ($this->EW as $EW){ if ($EW->type == "DEW" && $EW->turn == $turn) return $EW->amount; } return 0; } public function getOEW($target, $turn){ foreach ($this->EW as $EW){ if ($EW->type == "OEW" && $EW->targetid == $target->id && $EW->turn == $turn) return $EW->amount; } return 0; } public function getFacingAngle(){ $movement = null; foreach ($this->movement as $move){ $movement = $move; } return $movement->getFacingAngle(); } public function getLocations(){ $locs = array(); foreach ($this->systems as $fighter){ $exampleFtr = $fighter; //whether still alive or not; any fighter in flight will do, as they're all the same! } $health = $exampleFtr->maxhealth; $locs[] = array("loc" => 0, "min" => 330, "max" => 30, "profile" => $this->forwardDefense, "remHealth"=>$health,"armour"=> $exampleFtr->armour[0]); $locs[] = array("loc" => 0, "min" => 30, "max" => 150, "profile" => $this->sideDefense, "remHealth"=>$health,"armour"=> $exampleFtr->armour[3]); $locs[] = array("loc" => 0, "min" => 150, "max" => 210, "profile" => $this->forwardDefense, "remHealth"=>$health,"armour"=> $exampleFtr->armour[1]); $locs[] = array("loc" => 0, "min" => 210, "max" => 330, "profile" => $this->sideDefense, "remHealth"=>$health,"armour"=> $exampleFtr->armour[2]); return $locs; } public function fillLocations($locs){ //for fighters, armour and health are already defined by getLocations return $locs; } public function getStructureSystem($location){ return null; } public function getFireControlIndex(){ return 0; } public function isDestroyed($turn = false){ foreach($this->systems as $system){ if (!$system->isDestroyed($turn) && !$system->isDisengaged($turn)){ return false; } } return true; } public function isPowerless(){ return false; } public function getHitSystem($shooter, $fire, $weapon, $location = null){ $skipStandard=false; $systems = array(); if ($fire->calledid != -1){ $system = $this->getSystemById($fire->calledid); if (!$system->isDestroyed()){ //called shot at particular fighter, which is still living $systems[] = $system; $skipStandard=true; } } if(!$skipStandard){ foreach ($this->systems as $system){ if (!$system->isDestroyed()){ $systems[] = $system; } } } if (sizeof($systems) == 0) return null; return $systems[(Dice::d(sizeof($systems)) -1)]; } public function getAllFireOrders($turn = -1) { $orders = array(); foreach ($this->systems as $fighter) { foreach ($fighter->systems as $system) { $orders = array_merge($orders, $system->getFireOrders($turn)); //$orders = array_merge($orders, $system->fireOrders); //old version } } return $orders; } /*always nothing to do for fighters*/ public function setExpectedDamage($hitLoc, $hitChance, $weapon){ return; } /*returns calculated ramming factor for fighter (so will never use explosive charge if, say, Delegor or HK is rammed instead of ramming itself!*/ /*approximate raming factor as Structure + all Armors of example fighter (so always full ramming factor is used, not reduced by damage received) */ public function getRammingFactor(){ $dmg = 0; $ftr = $this->getSampleFighter(); $dmg += $ftr->maxhealth; foreach($ftr->armour as $armorvalue){ $dmg+=$armorvalue; } return $dmg; } //endof function getRammingFactor }//endof class FighterFlight class SuperHeavyFighter extends FighterFlight{ public $superheavy = true; function __construct($id, $userid, $name, $slot){ parent::__construct($id, $userid, $name, $slot); } } ?>
Markdown
UTF-8
2,887
3.140625
3
[]
no_license
# Unofficial Cambridge Pseudocode Language Plugin for Notepad ++ ### Cambridge Pseudocode Cambridge International offers their students the opportunity to course the subject Computer Science in the following key stages: * 0478 Computer Science in Key Stage 4 (IGCSE) * 9618 Computer Science in Key Stage 5 (A Level) Writing pseudocode is one of the most important parts of these syllabuses and Cambridge offers a specific syntax. Since I have not found any text editor with this syntax, I have created an **user-defined language (UDL)** to share it with my students and with all people studying this subject. In this repository you can find two files: * the last version of Notepad++ (at the moment of writing this document) * the user-defined language xml file ### Installation To install the program and the udl file, please follow the next steps: #### 1. **Installation of Notepad++** You can download the file I have provided to you or go to [Notepad++](https://notepad-plus-plus.org/downloads/) to download the last version * download the file * click on Install * finish the installation by clicking Ok or Next in all the windows of the setup wizard * launch the program #### 2. **Configuration of Notepad++** In order to use Notepad++ with the UDL that you are going to install, please, do the following ammendments: * Open **Notepad++** * In the window it will appear, go to *Editing* and make sure that in the section *Line Wrap* the radio button *Aligned* is selected * Go to *Language* and, in the section *Tab Size*, please change 4 by 2 and make sure that the option *Replace by space* is selected * Go to *Print* and select *Print line number* * Click *Close* to exit. Until now, Notepad++ has been installed and configured and you can use it to write something, but it remains to install the UDL file. #### 3. **UDL Configuration** Follow the next steps: * Download the file *PseudocodeByJoseVteEsteve.xml* you can find in this repository * Open Notepad++ * Go to *Language* --> *User Defined Language* -->*Define your language* * In the new window (**Language Editor**) it appears, click on *Import...* * Browse the **xml** file you have downloaded in step 1 and upload it. When done, a little window should appear informing you that the importing has been successful * Close the Language Editor by clicking on the cross button at the top right of the window * Close Notepad++ Now, you should check if the installation has been successful and all is done. Do the following: * Launch Notepad++ * Go to *Language*, and, if the language called **_PseudocodeByJosEsteve_** appears, the installation has been succesfully done. * Select **PseudocodeByJosEsteve** ### Writing pseudocode Now, you can begin writing pseudocode programs using this hightlighting syntax. # Improvements for newer versions - Make <-- (assignment operator) using only one character
Java
UTF-8
505
2.28125
2
[]
no_license
package com.example.mbg; import java.io.Serializable; public class SyncObject implements Serializable { private String tag; private byte[] bytes; public SyncObject(String string, byte[] serialize) { // TODO Auto-generated constructor stub this.tag=string; bytes = serialize; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } }
C#
UTF-8
2,842
2.75
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Media3D; namespace WWCrossFeed { class WWVirtualTrackball { Point mPressPosXY; public double SphereRadius { get; set; } public Size ScreenWH { get; set; } Quaternion mRotationAnchor = new Quaternion(); Quaternion mRotationCurrent = new Quaternion(); public void Reset() { mRotationAnchor = new Quaternion(); mRotationCurrent = new Quaternion(); } /// <summary> /// ボタンがMouseDownしたら呼ぶ。 /// </summary> /// <param name="xy">スクリーン座標系</param> public void Down(Point xy) { mPressPosXY = xy; } private bool PosOnScreenToPosOnSphere(Point xyScreen, out Vector3D xyz) { var xy = new Vector(-xyScreen.X + ScreenWH.Width/2, -xyScreen.Y + ScreenWH.Height/2); if (SphereRadius <= xy.Length) { xyz = new Vector3D(xy.X * SphereRadius / xy.Length, xy.Y * SphereRadius / xy.Length, 0); } else { double z = Math.Sqrt(SphereRadius * SphereRadius - xy.LengthSquared); xyz = new Vector3D(xy.X, xy.Y, z); } xyz.Normalize(); return true; } /// <summary> /// ボタンが押されつつMouseMoveしたら呼ぶ。 /// </summary> /// <param name="xy">スクリーン座標系</param> public void Move(Point xy) { var delta = new Vector(xy.X - mPressPosXY.X, xy.Y - mPressPosXY.Y); if (delta.LengthSquared < float.Epsilon) { return; } Vector3D xyzFrom; Vector3D xyzTo; if (!PosOnScreenToPosOnSphere(mPressPosXY, out xyzFrom) || !PosOnScreenToPosOnSphere(xy, out xyzTo)) { return; } Vector3D axis = Vector3D.CrossProduct(xyzFrom, xyzTo); double angle = Math.Acos(Vector3D.DotProduct(xyzFrom, xyzTo)); var q = new Quaternion(axis, angle * 180.0 / Math.PI); mRotationCurrent = mRotationAnchor * q; } /// <summary> /// ボタンが離されたら呼ぶ。 /// </summary> public void Up() { mRotationAnchor = mRotationCurrent; } /// <summary> /// 回転行列を取得。 /// </summary> /// <returns></returns> public Matrix3D RotationMatrix() { var mat = new Matrix3D(); mat.Rotate(mRotationCurrent); return mat; } } }
Markdown
UTF-8
2,337
2.671875
3
[]
no_license
# CSE 110 W20 Team 35 Meeting Minutes ## Meeting Objective: Brainstorm Part 2 **Date: Thursday 1/28/2021** **Start Time: Zoom 4 pm PT** **End Time: 5 pm PT** **Attendees (Name, Role):** 1. Nidhi Giridhar 2. Sydney Wong 3. Jasmine Chen 4. Alejandro Malanche 5. Alejandro Marquez 6. Ian Rebmann 7. Zachary Chan 8. Samuel Burkholder **Absent (Name, Role)**: 1. ## Agenda: 1. Discuss research on other pomodoro timers 2. Narrow down list of features 3. Decide on MVP 4. Research how we should (technically) implement features 5. Reminder: look ahead at assignments for next week ## Completed Tasks (from previous meeting): ## Pending Business (from previous meeting): ## Notes, Decisions, Issues: * Notes from research * some apps have default number of pomos * austomatically roll into pomo then break then pomo etc. * MVP Features * timer aspects * reset = restarts the current pomo * stop = stops timer and all future pomos planned for the session * start * notfications * 2 tones (one for pomo end, one for break end) * banner notifications * default number of pomos for the day * visual counter for pomos completed so far (for the day) * static explanation of pomodoro * We are putting user profile idea on hold * Stretch features * High * task input: ability to hit 'finished' after a task is done and pick next task to do, user can finish early * progress bar showing how long you have until long break (reset once long break is hit) * put main task on the screen * make instructions non-static * Medium * keyboard controls (start, stop, reset, finished) * different colors for pomo and break * customizable time limits * reminder to walk around during break * Low * incentives: earn points for every pomo completed (store data on local browser) * points unlock certain features * daily/weekly progress * API research * everyone will posts research/links/resources in #resources channel on Slack ## TODOs: * Add roles to rules * Sydney * Figure out standup meeting time * Nidhi * Make separate repo for standup/daily progress log * Nidhi * Upload Miro images to repo * Nidhi * Read material/links on Cavnas brainstorming assignment * Everyone ## To discuss at next meeting:
Markdown
UTF-8
6,741
2.921875
3
[ "MIT" ]
permissive
### Installing Repertoire Faceting N.B. Repertoire Faceting requires Postgres 9.3+, Rails 3.2+, Ruby 2.0.0+, and JQuery 1.3.2+. #### Short version. You need a working Rails app, with a model, controller, and a partial to show the model 1. in Gemfile `gem 'repertoire-faceting'` 2. install native bitset extensions `$ bundle install` `$ rake db:faceting:extensions:install` # (provide sudo your password) 3. in `./app/models/some_model.rb` ```ruby class SomeModel include Repertoire::Faceting::Model facet :some_column end ``` 5. in `./app/controllers/some_controller` ```ruby class SomeController include Repertoire::Faceting::Controller def base; return SomeModel; end end ``` 6. in `./config/routes.rb` ```ruby SomeApp::Application.routes.draw do faceting_for :some_model end ``` 7. in `./app/assets/javascripts/application.js` ```js //= require rep.faceting ``` 8. in `./app/assets/stylesheets/application.css` ```css /* *=... *= require rep.faceting *=... ```*/ ``` in `./app/views/some_controller/index.html.erb` ```html <script language="javascript"> $().ready(function() { $('#paintings').facet_context(); $('.facet').facet(); $('#results').results(); }); </script> <div id='paintings'> <div id='genre' class='facet'></div> <div id='results'></div> </div> ``` __That's a complete faceted browser in only 14 new lines of code in your app!__ Additionally, you may wish to index the facets. At the console or in a migration: ```ruby SomeModel.index_facets([:some_column]) ``` The faceting subsystem automatically detects available facet indices and uses them when appropriate. #### Detailed version. Start with a working Rails application with a PostgreSQL database. > Note that the canonical resource for using Repertoire Faceting is the > Repertoire Faceting Example application. If you have questions, you are > best served by getting it running and exploring further there. ** * Require repertoire-faceting in Gemfile. `gem 'repertoire-faceting'` * At the command line, bundle everything into your application: `$ bundle install` * From your application root, build and install the repertoire-faceting native extensions to PostgreSQL. These provide a bitwise signature type used to index and count facets. `$ rake db:faceting:extensions:install { sudo will prompt you for your password }` * Load the extension into your local application database. This ensures the plpgsql language is installed, and loads (or re-loads) the new bitset signature type. `$ psql -c "CREATE EXTENSION faceting;" -U<username> <database>` Or, if you prefer to use migrations create one with the following contents: ```ruby def self.change reversible do |dir dir.up { execute('CREATE EXTENSION faceting') } dir.down { execute('DROP EXTENSION faceting CASCADE') } end end ``` Before proceeding, you can confirm the module is installed as follows. `$ psql -c "SELECT facet.count('101010101'::facet.signature);" -U<username> <database>` * Install the faceting mixin in your Rails model and declare a facet on an existing database column. (See the README for complete configuration options for facets.) In `./app/models/painting.rb` ```ruby class Painting include Repertoire::Faceting::Model facet :genre end ``` * Test doing facet count and result queries: ```shell $ rails c > Painting.count(:genre) => {"Impressionist"=>2, "Medieval"=>2} > Painting.refine(:genre => 'Impressionist') => [#<Painting id: 1, title: "Moonlight Shimmers", painter: "Monet", genre: "Impressionist">, #<Painting id: 2, title: "Nude Lunch in Garden", painter: "Manet", genre: "Impressionist">] ``` Or, with a base query as well: ```shell > Painting.where(["title like ?", 'Moon%']).count(:genre) => {"Impressionist"=>1} ``` * Add faceting webservices to your controller and define base() to indicate which model to base queries on In `./app/controllers/paintings_controller` ```ruby class PaintingsController include Repertoire::Faceting::Controller def base search = "%#{params[:search]}%" Painting.where(["title like ?", search]) end end ``` * Add faceting routes to your application. In `./config/routes.rb` ```ruby PaintingsApp::Application.routes.draw do faceting_for :paintings # NB must be BEFORE any resources! ... end ``` Confirm they load: `$ rake routes` ```ruby paintings_counts /paintings/counts/:facet(.:format) {:controller=>"paintings", :action=>"counts"} paintings_results /paintings/results(.:format) {:controller=>"paintings", :action=>"results"} ``` * Add facet count and result widgets to your HTML page. The facet context div collects widgets that affect the same query together. (For complete options, see the README ) In `./app/views/paintings/index.html.erb` ```html <script language="javascript"> $().ready(function() { $('#paintings').facet_context(); $('.facet').facet(); $('#results').results(); }); </script> <div id='paintings'> <div id='genre' class='facet'></div> <div id='results'></div> </div> ``` If you don't already have one, create a partial for displaying your model in results lists. In `./app/views/paintings/_painting.html.erb` ```html <div class='painting' style='width:235px; margin-bottom:5px; padding:2px; border:dotted 1px;'> <div>Title: <%= painting.title %></div> <div>Painter: <%= painting.painter %></div> <div>Genre: <%= painting.genre %></div> </div> ``` [Optional] Add bitset indexes to some facets on your model. The module will automatically use facet indexes when they are available. Facet indexes scale out of the box to over a million model items, and requires no additional configuration. `$ rails generate migration AddFacetIndex` In `./db/migrate/<your date>add_facet_index.rb` ```ruby class AddFacetIndex < ActiveRecord::Migration def self.up Painting.index_facets([:genre]) end def self.down Painting.index_facets end end ``` [Optional] Periodically update indexes via a crontab task. In `./lib/tasks/update_facets.rake` ```ruby task :reindex => :environment do Painting.index_facets # NB this updates whatever indexes already exist end ``` And then configure crontab to execute 'rake reindex' at appropriate intervals.
C++
UTF-8
3,605
2.90625
3
[]
no_license
#pragma once #include "stdafx.h" #include "Pz13BorodinApi.hpp" template<typename T> class Set { public: Set(); Set(int capacity); Set(const Set<T>& other); ~Set(); Set& operator=(const Set<T>& other); Set operator+(Set<T>& other); Set operator*(Set<T>& other); Set operator-(Set<T>& other); T& operator[](int index); bool Find(const T& data); void Push(const T& data); void Delete(T data); int Capacity(); int Size(); template<typename T1,typename T2> T FindCriterion(T2 value,T1 functor); T Top(); template<typename T> friend std::ostream& operator<<(std::ostream& stream, Set<T>& other); private: T* _data; int _capacity; int _size; }; template<typename T> Set<T>::Set() :_capacity(0), _size(0), _data(nullptr) {} template<typename T> Set<T>::Set(int capacity) : _capacity(capacity), _size(0) { _data = new T[_capacity]; } template<typename T> Set<T>::Set(const Set<T>& other) :_size(other._size), _capacity(other._capacity) { _data = new T[_capacity]; for (int i = 0; i < _size; ++i) { _data[i] = other._data[i]; } } template<typename T> Set<T>::~Set() { delete[] _data; } template<typename T> Set<T>& Set<T>::operator=(const Set& other) { if (this == &other) return *this; if (_data != nullptr) delete[] _data; _data = new T[_capacity]; _size = other._size; _capacity = other._capacity; for (int i = 0; i < _size; ++i) { _data[i] = other._data[i]; } } template<typename T> template<typename T1, typename T2> T Set<T>::FindCriterion(T2 value, T1 functor) { for (int i = 0; i < _size; ++i) { if (functor(_data[i], value)) return _data[i]; } throw std::domain_error("Return nothing"); } template<typename T> Set<T> Set<T>::operator+(Set<T>& other) { if (this == &other) return *this; Set<T> sum(_size + other._size); for (int i = 0; i < _size; ++i) { sum.Push(_data[i]); } for (int i = 0; i < other._size; ++i) { sum.Push(other._data[i]); } return sum; } template<typename T> Set<T> Set<T>::operator*(Set<T>& other) { if (this == &other) return *this; Set<T> cross(_size); for (int i = 0; i < _size; ++i) { for (int j = 0; j < other._size; ++j) { if (_data[i] == other._data[j]) cross.Push(_data[i]); } } return cross; } template<typename T> Set<T> Set<T>::operator-(Set<T>& other) { Set<T> cross(*this); for (int i = 0; i < cross._size; ++i) { for (int j = 0; j < other._size; ++j) { if (cross._data[i] == other._data[j]) cross.Delete(cross._data[i]); } } return cross; } template<typename T> inline T& Set<T>::operator[](int index) { return _data[index]; } template<typename T> bool Set<T>::Find(const T& data) { for (int i = 0; i < _size; ++i) { if (data == _data[i]) return true; } return false; } template<typename T> void Set<T>::Push(const T& data) { if (_size == _capacity) throw std::range_error("Stack is Full"); if (Find(data) == 0) _data[_size++] = data; } template<typename T> void Set<T>::Delete(T data) { if (_size == 0) throw std::underflow_error("Stack is Empty"); if (Find(data) != 0) { for (int i = 0; i < _size; ++i) { if (_data[i] == data) _data[i] = _data[_size - 1]; } --_size; } else throw std::domain_error("Delete nothing"); } template<typename T> int Set<T>::Capacity() { return _capacity; } template<typename T> int Set<T>::Size() { return _size; } template<typename T> T Set<T>::Top() { return _data[_size - 1]; } template<typename T> std::ostream& operator<<(std::ostream& stream, Set<T>& other) { for (size_t i = 0; i < other._size; ++i) { stream << other._data[i] <<" "; } return stream; }
PHP
UTF-8
4,069
2.734375
3
[ "MIT" ]
permissive
<?php class Stocks extends Application { var $token; //agent token var $site = 'http://bsx.jlparry.com/'; //server url var $team = 'B01'; //team number function __construct() { parent::__construct(); } function index() { } /*Purchases a stock from the BSX and updates the users cash accordingly.*/ function buy() { $this->load->dbforge(); //load library if ($this->website->getState() != 3) { //if the market is closed echo '<script>alert("Market is currently closed."); window.location.href="/";</script>'; } else { $this->registerAgent(); //register the agent $stuff = array( 'server' => $this->site, 'team' => $this->team, 'token' => $this->token, 'player' => $this->session->userdata['userName'], 'stock' => $this->input->post('stock'), 'quantity' => $this->input->post('number') ); $this->rest->initialize($stuff); $data = $this->rest->post('/buy', $stuff); //move this code into the model $text = $data['token'] . " " . $data['stock'] . " " . $data['amount'] . " " . $data['datetime'] . " "; //combine the pieces we need into a string $currentStocks = $this->db->query('SELECT stocks FROM users WHERE username = \''.$this->session->userdata['userName'].'\'')->row(); //get the stocks the player currently owns $combined = $currentStocks->stocks.$text; //combine the two strings $price = $this->website->getStockPrice($this->input->post('stock'), $this->input->post('number')); //get the price of the stocks $cash = $this->users->getCash($this->session->userdata['userName']); $this->db->query('UPDATE users SET cash = '.($cash->cash-$price).' WHERE username = \''.$this->session->userdata['userName'].'\''); //update the players cash $this->db->query('UPDATE users SET stocks = \''.$combined.'\' WHERE username = \''.$this->session->userdata['userName'].'\''); //update the players stocks redirect("/"); } } /*Sells a stock on the BSX, not currrently implemented.*/ function sell() { $stuff = array( 'server' => $this->site, 'team' => $this->team, 'token' => $this->session->userdata['token'], 'player' => $this->session->userdata['userName'], 'stock' => $this->input->post('stock'), 'quantity' => $this->input->post('number'), 'certificate' => '0' ); $this->rest->initialize($stuff); $data = $this->rest->post('/sell', $stuff); } /*Returns a stock from the given code. */ function getStock($code) { $this->data = $this->website->readCSV(); $this->data['stocks'] = $this->data; $record = $this->get($code); $this->data = array_merge($this->data, $record); $this->data['pagebody'] = 'history'; $this->data['transactions'] = $this->website->getRecentStocks(20); $this->data['price'] = $this->website->getStockPrice($code, 1); $this->render(); } /*Returns all stocks read in from site. */ function getAllStocks() { $data = $this->website->readCSV(); return $data; } /*Returns a specific stock from a given code. */ function get($code) { foreach ($this->data as $record) { if ($record['code'] == $code) { return $record; } } return null; } /*Registers the agent with the BSX.*/ function registerAgent() { $stuff = array( 'server' => $this->site, 'team' => $this->team, 'name' => 'InsertNameHere', 'password' => 'tuesday' ); $this->rest->initialize($stuff); $data = $this->rest->post('/register', $stuff); $this->token = $data['token']; } }
Java
UTF-8
2,808
2
2
[]
no_license
package com.tangmiyi.future.exampleorder.controller; import com.tangmiyi.future.core.annotation.ServiceLogAop; import com.tangmiyi.future.core.bean.ResultBean; import com.tangmiyi.future.exampleorder.pojo.param.TestValidParam; import com.tangmiyi.future.exampleorder.service.PropertiesService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; @RestController @ServiceLogAop @Slf4j public class PropertiesController { @Autowired private PropertiesService propertiesService; /** * 参数校验案例 * @param testValidParam * @return */ @GetMapping("/v1/properties/testValid") public ResultBean<String> testValid(@Valid TestValidParam testValidParam) { ResultBean<String> resultBean = ResultBean.success(); propertiesService.testExceptionReturn(); resultBean.setData(testValidParam.getInputString()); return resultBean; } /** * 参数校验案例,如果是post需要加@RequestBody * @param testValidParam * @return */ @PostMapping("/v1/properties/testValid") @ServiceLogAop(logInfoOutput = false) public ResultBean<String> testPostValid(@Valid @RequestBody TestValidParam testValidParam) { ResultBean<String> resultBean = ResultBean.success(); resultBean.setData(testValidParam.getInputString()); return resultBean; } /** * testRedisLock案例 * @return */ @GetMapping("/v1/properties/testRedisLock") public ResultBean<Boolean> testRedisLock() { ResultBean<Boolean> resultBean = ResultBean.success(); TestValidParam testValidParam = new TestValidParam(); testValidParam.setInputFalse(true); testValidParam.setInputString("QQ"); propertiesService.testRedisLock(1003L,"redisLock",testValidParam); resultBean.setData(true); return resultBean; } /** * testJetCacheApi案例 * @return */ @GetMapping("/v1/properties/testJetCache") public ResultBean<Boolean> testJetCache() { ResultBean<Boolean> resultBean = ResultBean.success(); propertiesService.testJetCache(); resultBean.setData(true); return resultBean; } /** * stream测试 */ @GetMapping("/v1/properties/testStream") public ResultBean testStream() { ResultBean resultBean = ResultBean.success(); propertiesService.testStream(); resultBean.setData(true); return resultBean; } }
Markdown
UTF-8
47,933
3.078125
3
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-proprietary-license", "ISC", "Apache-2.0" ]
permissive
--- layout: docs title: Tab description: Documentazione ed esempi sull'utilizzo del componente Tab. group: componenti toc: true --- L'interfaccia a tab (o schede) di Bootstrap si basa sull'utilizzo del layout di navigazione, con l'aggiunta della classe `.nav-tabs`. Per ottenere una versione con sfondo scuro e testo chiaro bisognerà aggiungere un'ulteriore classe: `.nav-dark`. {% capture callout %} #### Accessibilità Le interfacce a tab, come descritto nelle [pratiche di implementazione WAI ARIA](https://www.w3.org/TR/wai-aria-practices/#tabpanel), richiedono l'utilizzo di attributi `role="tablist"`, `role="tab"`, `role="tabpanel"`, e ulteriori attributi `aria-`, al fine di trasmettere la loro struttura, funzionalità e stato attuale agli utenti delle tecnologie assistive (come i lettori di schermo). Nota che le interfacce dinamiche a tab **non devono** contenere menu a discesa, poiché ciò causa problemi di usabilità e accessibilità. Dal punto di vista dell'usabilità, il fatto che l'elemento trigger del tab attualmente visualizzato non sia immediatamente visibile (dato che si trova all'interno del menu a discesa chiuso) può causare confusione. {% endcapture %}{% include callout.html content=callout type="accessibility" %} ## Tab orizzontali a tutta larghezza Aggiungendo la classe `.auto` al contenitore `.nav-tabs` i tab occupano automaticamente l'intera larghezza disponibile. Se su schermi particolarme piccoli (es: smartphone) le dimensioni dei tab dovessero superare quelle dello schermo, verrà attivato lo scrolling orizzontale dei tab stessi. ### Tab testuale Lo stato dei tab può essere attivo, non attivo e disabilitato. Utilizzare la classe `.active` sul link del tab attivo per default. Utilizzare la classe `.disabled` sul link dei tab da disabilitare, aggiungendo la proprietà `tabindex="-1"` per eliminarlo dalla sequenza di navigazione via tab. {% comment %}Example name: Orizzontali a tutta larghezza, testuali{% endcomment %} {% capture example %} <ul class="nav nav-tabs auto"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Attivo</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabilitato</a> </li> </ul> {% endcapture %}{% include example.html content=example %} ### Tab con icona Le label dei tab possono essere sostituite da icone con classi che ne indicano il tipo, avendo cura di includere all'interno del link un elemento `<span>` con classe `.visually-hidden` contenente la descrizione dedicata agli screen reader. La classe `.visually-hidden` impedisce la visualizzazione del testo sui browser visuali. {% comment %}Example name: Orizzontali a tutta larghezza, con icona{% endcomment %} {% capture example %} <ul class="nav nav-tabs auto"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> <span class="visually-hidden">Tab titolo 1</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-calendar"></use> </svg> <span class="visually-hidden">Tab titolo 2</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-comment"></use> </svg> <span class="visually-hidden">Tab titolo 3</span> </a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-close"></use> </svg> <span class="visually-hidden">Tab titolo 4</span> </a> </li> </ul> {% endcapture %}{% include example.html content=example %} ### Tab con icona grande Per ottenere icone più grandi utilizzare la classe `.icon-lg` alle icone. Aggiungere la classe `.nav-tabs-icon-lg` al contenitore `.nav-tabs` per ottimizzare i margini fra tab. {% comment %}Example name: Orizzontali a tutta larghezza, con icona grande{% endcomment %} {% capture example %} <ul class="nav nav-tabs nav-tabs-icon-lg auto"> <li class="nav-item"> <a class="nav-link active" href="#" aria-current="page"> <svg class="icon icon-lg"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> <span class="visually-hidden">Tab titolo 1</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon icon-lg"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-calendar"></use> </svg> <span class="visually-hidden">Tab titolo 2</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon icon-lg"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-comment"></use> </svg> <span class="visually-hidden">Tab titolo 3</span> </a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1"> <svg class="icon icon-lg"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-close"></use> </svg> <span class="visually-hidden">Tab titolo 4</span> </a> </li> </ul> {% endcapture %}{% include example.html content=example %} ### Tab con testo e icona Icone e testi possono convivere all'interno dei tab, l'allineamento verticale dei due elementi è automatico. Per ottenere il corretto margine fra testo e icona nei tab a sviluppo orizzontale è necessario aggiungere la classe `.nav-tabs-icon-text` al contenitore `.nav-tabs`. {% comment %}Example name: Orizzontali a tutta larghezza, con testo e icona{% endcomment %} {% capture example %} <ul class="nav nav-tabs nav-tabs-icon-text auto"> <li class="nav-item"> <a class="nav-link active" href="#" aria-current="page"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> Tab 1 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-calendar"></use> </svg> Tab 2 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-comment"></use> </svg> Tab 3 </a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-close"></use> </svg> Tab 4 </a> </li> </ul> {% endcapture %}{% include example.html content=example %} ## Tab orizzontali In assenza della classe `.auto` i tab vengono dimensionati in base al contenuto. ### Tab testuale {% comment %}Example name: Orizzontali, testuali{% endcomment %} {% capture example %} <ul class="nav nav-tabs"> <li class="nav-item"><a class="nav-link active" href="#" aria-current="page">Tab 1 Attivo</a></li> <li class="nav-item"><a class="nav-link" href="#">Tab 2</a></li> <li class="nav-item"><a class="nav-link" href="#">Tab 3</a></li> <li class="nav-item"><a class="nav-link disabled" href="#" tabindex="-1">Tab 4 Disabilitato</a></li> </ul> {% endcapture %}{% include example.html content=example %} ### Tab con icona {% comment %}Example name: Orizzontali, con icona{% endcomment %} {% capture example %} <ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link active" href="#" aria-current="page"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> <span class="visually-hidden">Tab titolo 1</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-calendar"></use> </svg> <span class="visually-hidden">Tab titolo 2</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-comment"></use> </svg> <span class="visually-hidden">Tab titolo 3</span> </a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-close"></use> </svg> <span class="visually-hidden">Tab titolo 4</span> </a> </li> </ul> {% endcapture %}{% include example.html content=example %} ### Tab con icona grande {% comment %}Example name: Orizzontali, con icona grande{% endcomment %} {% capture example %} <ul class="nav nav-tabs nav-tabs-icon-lg"> <li class="nav-item"> <a class="nav-link active" href="#" aria-current="page"> <svg class="icon icon-lg"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> <span class="visually-hidden">Tab titolo 1</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon icon-lg"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-calendar"></use> </svg> <span class="visually-hidden">Tab titolo 2</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon icon-lg"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-comment"></use> </svg> <span class="visually-hidden">Tab titolo 3</span> </a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1"> <svg class="icon icon-lg"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-close"></use> </svg> <span class="visually-hidden">Tab titolo 4</span> </a> </li> </ul> {% endcapture %}{% include example.html content=example %} ### Tab con testo e icona {% comment %}Example name: Orizzontali, con testo e icona{% endcomment %} {% capture example %} <ul class="nav nav-tabs nav-tabs-icon-text"> <li class="nav-item"> <a class="nav-link active" href="#" aria-current="page"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> Tab 1 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-calendar"></use> </svg> Tab 2 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-comment"></use> </svg> Tab 3 </a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-close"></use> </svg> Tab 4 </a> </li> </ul> {% endcapture %}{% include example.html content=example %} ## Rimozione delle scrollbar su dispositivi touch Se per motivi estetici si volessero nascondere le scrollbar che appaiono sui dispositivi touch quando vengono scrollati orizzontalmente i tab sarà necessario inserire l'html dei tab all'interno di un wrapper con classe `.nav-tabs-hidescroll`. ```html <div class="nav-tabs-hidescroll"> <!-- HTML dei tab --> </div> ``` Se i tab contengono icone è necessario aggiungere un'ulteriore classe al wrapper: - `.hidescroll-ico` nel caso di icone normali - `.hidescroll-ico-lg` nel caso di icone piccole ### Esempio rimozione scrollbar su dispositivi touch {% comment %}Example name: Senza scrollbar su mobile{% endcomment %} {% capture example %} <div class="nav-tabs-hidescroll hidescroll-ico"> <ul class="nav nav-tabs nav-tabs-icon-text"> <li class="nav-item"> <a class="nav-link active" href="#" aria-current="page"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> Tab 1 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> Tab 2 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> Tab 3 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> Tab 4 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> Tab 5 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> Tab 6 </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <svg class="icon"> <use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use> </svg> Tab 7 </a> </li> </ul> </div> {% endcapture %}{% include example.html content=example %} ## Controllo dei pannelli associati Gli esempi sopra riportati non hanno molto senso senza un contenuto che cambi al di sotto di essi; per rendere tali interfacce navigabili è necessario collegare Tab e Pannelli collegando il tag `<a>` dei primi all'attributo `id` dei secondi, come mostrato di seguito: ### Tab testuale {% comment %}Example name: Con controllo pannelli, testuali{% endcomment %} {% capture example %} <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"><a class="nav-link active" id="tab1-tab" data-bs-toggle="tab" href="#tab1" role="tab" aria-controls="tab1" aria-selected="true">Tab 1</a></li> <li class="nav-item"><a class="nav-link" id="tab2-tab" data-bs-toggle="tab" href="#tab2" role="tab" aria-controls="tab2" aria-selected="false">Tab 2</a></li> <li class="nav-item"><a class="nav-link" id="tab3-tab" data-bs-toggle="tab" href="#tab3" role="tab" aria-controls="tab3" aria-selected="false">Tab 3</a></li> <li class="nav-item"><a class="nav-link disabled" id="tab4-tab" data-bs-toggle="tab" href="#tab4" role="tab" aria-controls="tab4" aria-selected="false" aria-disabled="true" tabindex="-1">Tab 4 Disabilitato</a></li> </ul> <div class="tab-content" id="myTabContent"> <div class="tab-pane p-4 fade show active" id="tab1" role="tabpanel" aria-labelledby="tab1-tab">Contenuto 1</div> <div class="tab-pane p-4 fade" id="tab2" role="tabpanel" aria-labelledby="tab2-tab">Contenuto 2</div> <div class="tab-pane p-4 fade" id="tab3" role="tabpanel" aria-labelledby="tab3-tab">Contenuto 3</div> <div class="tab-pane p-4 fade" id="tab4" role="tabpanel" aria-labelledby="tab3-tab">Contenuto 4 (non raggiungibile, il tab relativo è disabilitato)</div> </div> {% endcapture %}{% include example.html content=example %} ### Tab con icona grande {% comment %}Example name: Con controllo pannelli, icona grande{% endcomment %} {% capture example %} <ul class="nav nav-tabs nav-tabs-icon-lg" id="myTab2" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="tab1a-tab" data-bs-toggle="tab" href="#tab1a" role="tab" aria-controls="tab1a" aria-selected="true"> <svg class="icon icon-lg"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> <span class="visually-hidden"> Tab titolo 1</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="tab2a-tab" data-bs-toggle="tab" href="#tab2a" role="tab" aria-controls="tab2a" aria-selected="false"> <svg class="icon icon-lg"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> <span class="visually-hidden"> Tab titolo 2</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="tab3a-tab" data-bs-toggle="tab" href="#tab3a" role="tab" aria-controls="tab3a" aria-selected="false"> <svg class="icon icon-lg"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> <span class="visually-hidden"> Tab titolo 3</span> </a> </li> <li class="nav-item"> <a class="nav-link disabled" id="tab4a-tab" data-bs-toggle="tab" href="#tab4a" role="tab" aria-controls="tab4a" aria-selected="false" aria-disabled="true" tabindex="-1"> <svg class="icon icon-lg"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> <span class="visually-hidden"> Tab titolo 4</span> </a> </li> </ul> <div class="tab-content" id="myTab2Content"> <div class="tab-pane p-4 fade show active" id="tab1a" role="tabpanel" aria-labelledby="tab1a-tab"><p>Contenuto 1</p></div> <div class="tab-pane p-4 fade" id="tab2a" role="tabpanel" aria-labelledby="tab2a-tab"><p>Contenuto 2</p></div> <div class="tab-pane p-4 fade" id="tab3a" role="tabpanel" aria-labelledby="tab3a-tab"><p>Contenuto 3</p></div> <div class="tab-pane p-4 fade" id="tab4a" role="tabpanel" aria-labelledby="tab4a-tab">Contenuto 4 (non raggiungibile, il tab relativo è disabilitato)</div> </div> {% endcapture %}{% include example.html content=example %} ### Tab con testo e icona {% comment %}Example name: Con controllo pannelli, testo e icona{% endcomment %} {% capture example %} <ul class="nav nav-tabs nav-tabs-icon-text" id="myTab3" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="tab1c-tab" data-bs-toggle="tab" href="#tab1b" role="tab" aria-controls="tab1b" aria-selected="true"> <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 1 </a> </li> <li class="nav-item"> <a class="nav-link" id="tab2b-tab" data-bs-toggle="tab" href="#tab2b" role="tab" aria-controls="tab2b" aria-selected="false"> <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 2 </a> </li> <li class="nav-item"> <a class="nav-link" id="tab3b-tab" data-bs-toggle="tab" href="#tab3b" role="tab" aria-controls="tab3b" aria-selected="false"> <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 3 </a> </li> <li class="nav-item"> <a class="nav-link disabled" id="tab4b-tab" data-bs-toggle="tab" href="#tab4b" role="tab" aria-controls="tab3b" aria-selected="false" aria-disabled="true" tabindex="-1"> <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 4 </a> </li> </ul> <div class="tab-content" id="myTab3Content"> <div class="tab-pane p-4 fade show active" id="tab1b" role="tabpanel" aria-labelledby="tab1c-tab"><p>Contenuto 1</p></div> <div class="tab-pane p-4 fade" id="tab2b" role="tabpanel" aria-labelledby="tab2b-tab"><p>Contenuto 2</p></div> <div class="tab-pane p-4 fade" id="tab3b" role="tabpanel" aria-labelledby="tab3b-tab"><p>Contenuto 3</p></div> <div class="tab-pane p-4 fade" id="tab4b" role="tabpanel" aria-labelledby="tab4b-tab">Contenuto 4 (non raggiungibile, il tab relativo è disabilitato)</div> </div> {% endcapture %}{% include example.html content=example %} Allo stesso modo di quanto avviene con i normali `.nav`, a seconda delle tue necessità, è possibile modificare tale codice con un markup diverso, diverso dalla classica lista basata su `<ul>`. È importante notare però, che nel caso si desideri usare l'elemento `<nav>`, l'attributo `role="tablist"` non deve essere applicato direttamente su di esso, in quanto sovrascriverebbe il ruolo dell'elemento stesso per la navigazione. Si può, alternativamente, usare un diverso elemento (nell'esempio seguente un semplice `<div>`) e racchiuderlo con `<nav>`: {% comment %}Example name: Con controllo pannelli, markup alternativo{% endcomment %} {% capture example %} <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="nav-tab1-tab" data-bs-toggle="tab" href="#nav-tab1" role="tab" aria-controls="nav-tab1" aria-selected="true">Tab 1</a> <a class="nav-item nav-link" id="nav-tab2-tab" data-bs-toggle="tab" href="#nav-tab2" role="tab" aria-controls="nav-tab2" aria-selected="false">Tab 2</a> <a class="nav-item nav-link" id="nav-tab3-tab" data-bs-toggle="tab" href="#nav-tab3" role="tab" aria-controls="nav-tab3" aria-selected="false">Tab 3</a> </div> </nav> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane p-4 fade show active" id="nav-tab1" role="tabpanel" aria-labelledby="nav-tab1-tab">Contenuto 1</div> <div class="tab-pane p-4 fade" id="nav-tab2" role="tabpanel" aria-labelledby="nav-tab2-tab">Contenuto 2</div> <div class="tab-pane p-4 fade" id="nav-tab3" role="tabpanel" aria-labelledby="nav-tab3-tab">Contenuto 3</div> </div> {% endcapture %}{% include example.html content=example %} ## Tab verticali Utilizzando gli strumenti di layout di Bootstrap 5 è possibile realizzare tab a orientamento verticale. Al `<div>` contenitore dei link dei tab va aggiunta la classe `.nav-tabs-vertical`. ### Tab testuale {% comment %}Example name: Con controllo pannelli, verticale, testuale{% endcomment %} {% capture example %} <div class="bd-example-tabs"> <div class="row"> <div class="col-4 col-md-3"> <div class="nav nav-tabs nav-tabs-vertical" id="nav-vertical-tab" role="tablist" aria-orientation="vertical"> <a class="nav-link active" id="nav-vertical-tab1-tab" data-bs-toggle="tab" href="#nav-vertical-tab1" role="tab" aria-controls="nav-vertical-tab1" aria-selected="true">Tab 1</a> <a class="nav-link" id="nav-vertical-tab2-tab" data-bs-toggle="tab" href="#nav-vertical-tab2" role="tab" aria-controls="nav-vertical-tab2" aria-selected="false">Tab 2</a> <a class="nav-link" id="nav-vertical-tab3-tab" data-bs-toggle="tab" href="#nav-vertical-tab3" role="tab" aria-controls="nav-vertical-tab3" aria-selected="false">Tab 3</a> <a class="nav-link">...</a> </div> </div> <div class="col-8 col-md-9"> <div class="tab-content" id="nav-vertical-tabContent"> <div class="tab-pane p-3 fade show active" id="nav-vertical-tab1" role="tabpanel" aria-labelledby="nav-vertical-tab1-tab">Contenuto 1</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab2" role="tabpanel" aria-labelledby="nav-vertical-tab2-tab">Contenuto 2</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab3" role="tabpanel" aria-labelledby="nav-vertical-tab3-tab">Contenuto 3</div> </div> </div> </div> </div> {% endcapture %}{% include example.html content=example %} ### Tab testuale con colore di sfondo Aggiungendo la classe `.nav-tabs-vertical-background` al `<div>` contenitore dei link i tab selezionati avranno un colore di sfondo. {% comment %}Example name: Con controllo pannelli, verticale, colore di sfondo{% endcomment %} {% capture example %} <div class="bd-example-tabs"> <div class="row"> <div class="col-4 col-md-3"> <div class="nav nav-tabs nav-tabs-vertical nav-tabs-vertical-background" id="nav-vertical-tab-bg" role="tablist" aria-orientation="vertical"> <a class="nav-link active" id="nav-vertical-tab-bg1-tab" data-bs-toggle="tab" href="#nav-vertical-tab-bg1" role="tab" aria-controls="nav-vertical-tab-bg1" aria-selected="true">Tab 1</a> <a class="nav-link" id="nav-vertical-tab-bg2-tab" data-bs-toggle="tab" href="#nav-vertical-tab-bg2" role="tab" aria-controls="nav-vertical-tab-bg2" aria-selected="false">Tab 2</a> <a class="nav-link" id="nav-vertical-tab-bg3-tab" data-bs-toggle="tab" href="#nav-vertical-tab-bg3" role="tab" aria-controls="nav-vertical-tab-bg3" aria-selected="false">Tab 3</a> <a class="nav-link">...</a> </div> </div> <div class="col-8 col-md-9"> <div class="tab-content" id="nav-vertical-tab-bgContent"> <div class="tab-pane p-3 fade show active" id="nav-vertical-tab-bg1" role="tabpanel" aria-labelledby="nav-vertical-tab-bg1-tab">Contenuto 1</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-bg2" role="tabpanel" aria-labelledby="nav-vertical-tab-bg2-tab">Contenuto 2</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-bg3" role="tabpanel" aria-labelledby="nav-vertical-tab-bg3-tab">Contenuto 3</div> </div> </div> </div> </div> {% endcapture %}{% include example.html content=example %} ### Tab con testo e icona {% comment %}Example name: Con controllo pannelli, verticale, testo e icona{% endcomment %} {% capture example %} <div class="bd-example-tabs"> <div class="row"> <div class="col-5 col-md-4 col-lg-3"> <div class="nav nav-tabs nav-tabs-vertical" id="nav-vertical-tab-ico" role="tablist" aria-orientation="vertical"> <a class="nav-link active" id="nav-vertical-tab-ico1-tab" data-bs-toggle="tab" href="#nav-vertical-tab-ico1" role="tab" aria-controls="nav-vertical-tab-ico1" aria-selected="true">Tab 1 <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg></a> <a class="nav-link" id="nav-vertical-tab-ico2-tab" data-bs-toggle="tab" href="#nav-vertical-tab-ico2" role="tab" aria-controls="nav-vertical-tab-ico2" aria-selected="false">Tab 2 <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg></a> <a class="nav-link" id="nav-vertical-tab-ico3-tab" data-bs-toggle="tab" href="#nav-vertical-tab-ico3" role="tab" aria-controls="nav-vertical-tab-ico3" aria-selected="false">Tab 3 <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg></a> <a class="nav-link">...</a> </div> </div> <div class="col-7 col-md-8 col-lg-9"> <div class="tab-content" id="nav-vertical-tab-icoContent"> <div class="tab-pane p-3 fade show active" id="nav-vertical-tab-ico1" role="tabpanel" aria-labelledby="nav-vertical-tab-ico1-tab">Contenuto 1</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-ico2" role="tabpanel" aria-labelledby="nav-vertical-tab-ico2-tab">Contenuto 2</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-ico3" role="tabpanel" aria-labelledby="nav-vertical-tab-ico3-tab">Contenuto 3</div> </div> </div> </div> </div> {% endcapture %}{% include example.html content=example %} ### Tab con icona Le label dei Tab possono essere sostituite da icone, avendo cura di includere all'interno del link un elemento `<span>` contenente la descrizione per non gli screen reader del tab con classe `.visually-hidden` per nascondere la descrizione agli altri browser. Al tag `<a>` contenente l'icona va aggiunta la classe `.justify-content-end` per allineare l'icona a destra. {% comment %}Example name: Con controllo pannelli, verticale, icona{% endcomment %} {% capture example %} <div class="bd-example-tabs"> <div class="row"> <div class="col-3"> <div class="nav nav-tabs nav-tabs-vertical" id="nav-vertical-tab-ico-only" role="tablist" aria-orientation="vertical"> <a class="nav-link justify-content-end active" id="nav-vertical-tab-ico-only1-tab" data-bs-toggle="tab" href="#nav-vertical-tab-ico-only1" role="tab" aria-controls="nav-vertical-tab-ico-only1" aria-selected="true"><span class="visually-hidden">Tab titolo 1</span> <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg></a> <a class="nav-link justify-content-end" id="nav-vertical-tab-ico-only2-tab" data-bs-toggle="tab" href="#nav-vertical-tab-ico-only2" role="tab" aria-controls="nav-vertical-tab-ico-only2" aria-selected="false"><span class="visually-hidden">Tab titolo 2</span> <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-calendar"></use></svg></a> <a class="nav-link justify-content-end" id="nav-vertical-tab-ico-only3-tab" data-bs-toggle="tab" href="#nav-vertical-tab-ico-only3" role="tab" aria-controls="nav-vertical-tab-ico-only3" aria-selected="false"><span class="visually-hidden">Tab titolo 3</span> <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-comment"></use></svg></a> <a class="nav-link justify-content-end">...</a> </div> </div> <div class="col-9"> <div class="tab-content" id="nav-vertical-tab-ico-onlyContent"> <div class="tab-pane p-3 fade show active" id="nav-vertical-tab-ico-only1" role="tabpanel" aria-labelledby="nav-vertical-tab-ico-only1-tab">Contenuto 1</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-ico-only2" role="tabpanel" aria-labelledby="nav-vertical-tab-ico-only2-tab">Contenuto 2</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-ico-only3" role="tabpanel" aria-labelledby="nav-vertical-tab-ico-only3-tab">Contenuto 3</div> </div> </div> </div> </div> {% endcapture %}{% include example.html content=example %} ## Posizione dei Tab Per questioni di accessibilità è preferibile utilizzare le proprietà Flex di CSS a un cambio di posizione dei Tab nell'HTML. Per garantiore un flusso di lettura naturale della pagina i tab di navigazione devono precedere il contenuto a loro associato. ### Orizzontale in fondo Per posizionare i tab al di sotto del contenuto è necessario utilizzare un elemento contenitore (ad esempio un <div>) con classi `.d-flex` e `.flex-column-reverse`. {% comment %}Example name: Con controllo pannelli, orizzontale in basso{% endcomment %} {% capture example %} <div class="d-flex flex-column-reverse"> <ul class="nav nav-tabs" id="pos-hr" role="tablist"> <li class="nav-item"><a class="nav-link active" id="pos-hr1-tab" data-bs-toggle="tab" href="#pos-hrtab1" role="tab" aria-controls="pos-hrtab1" aria-selected="true">Tab 1</a></li> <li class="nav-item"><a class="nav-link" id="pos-hr2-tab" data-bs-toggle="tab" href="#pos-hrtab2" role="tab" aria-controls="pos-hrtab2" aria-selected="false">Tab 2</a></li> <li class="nav-item"><a class="nav-link" id="pos-hr3-tab" data-bs-toggle="tab" href="#pos-hrtab3" role="tab" aria-controls="pos-hrtab3" aria-selected="false">Tab 3</a></li> <li class="nav-item"><a class="nav-link disabled" id="pos-hr4-tab" data-bs-toggle="tab" href="#pos-hrtab4" role="tab" aria-controls="pos-hrtab4" aria-selected="false" aria-disabled="true" tabindex="-1">Tab 4 Disabilitato</a></li> </ul> <div class="tab-content" id="pos-hrContent"> <div class="tab-pane p-4 fade show active" id="pos-hrtab1" role="tabpanel" aria-labelledby="pos-hr1-tab">Contenuto 1</div> <div class="tab-pane p-4 fade" id="pos-hrtab2" role="tabpanel" aria-labelledby="pos-hr2-tab">Contenuto 2</div> <div class="tab-pane p-4 fade" id="pos-hrtab3" role="tabpanel" aria-labelledby="pos-hr3-tab">Contenuto 3</div> <div class="tab-pane p-4 fade" id="pos-hrtab4" role="tabpanel" aria-labelledby="pos-hr3-tab">Contenuto 4 (non raggiungibile, il tab relativo è disabilitato)</div> </div> </div> {% endcapture %}{% include example.html content=example %} ### Verticale a destra Per posizionare i tab verticali a destra contenuto è necessario applicare la classe `.flex-row-reverse` all'elemento con classe `.row` che li contiene. {% comment %}Example name: Con controllo pannelli, verticale a destra{% endcomment %} {% capture example %} <div class="bd-example-tabs"> <div class="row flex-row-reverse"> <div class="col-5 col-md-4 col-lg-3"> <div class="nav nav-tabs nav-tabs-vertical" id="pos-vr" role="tablist" aria-orientation="vertical"> <a class="nav-link active" id="pos-vr1-tab" data-bs-toggle="tab" href="#pos-vr1" role="tab" aria-controls="pos-vr1" aria-selected="true"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 1</a> <a class="nav-link" id="pos-vr2-tab" data-bs-toggle="tab" href="#pos-vr2" role="tab" aria-controls="pos-vr2" aria-selected="false"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 2</a> <a class="nav-link" id="pos-vr3-tab" data-bs-toggle="tab" href="#pos-vr3" role="tab" aria-controls="pos-vr3" aria-selected="false"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 3</a> <a class="nav-link">...</a> </div> </div> <div class="col-7 col-md-8 col-lg-9"> <div class="tab-content" id="pos-vrContent"> <div class="tab-pane p-3 fade show active" id="pos-vr1" role="tabpanel" aria-labelledby="pos-vr1-tab">Contenuto 1</div> <div class="tab-pane p-3 fade" id="pos-vr2" role="tabpanel" aria-labelledby="pos-vr2-tab">Contenuto 2</div> <div class="tab-pane p-3 fade" id="pos-vr3" role="tabpanel" aria-labelledby="pos-vr3-tab">Contenuto 3</div> </div> </div> </div> </div> {% endcapture %}{% include example.html content=example %} ## Tab con sfondo scuro ### Tab orizzontali a tutta larghezza {% comment %}Example name: Con controllo pannelli, sfondo scuro, orizzontale a tutta larghezza{% endcomment %} {% capture example %} <ul class="nav nav-tabs auto nav-dark"> <li class="nav-item"><a class="nav-link active" href="#">Tab 1 Attivo</a></li> <li class="nav-item"><a class="nav-link" href="#">Tab 2</a></li> <li class="nav-item"><a class="nav-link" href="#">Tab 3</a></li> <li class="nav-item"><a class="nav-link disabled" href="#" tabindex="-1">Tab 4 Disabilitato</a></li> </ul> {% endcapture %}{% include example.html content=example %} ### Tab con testo e icona {% comment %}Example name: Con controllo pannelli, sfondo scuro, orizzontale a tutta larghezza, testo e icona{% endcomment %} {% capture example %} <ul class="nav nav-tabs nav-tabs-icon-text nav-dark"> <li class="nav-item"><a class="nav-link active" href="#"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 1</a></li> <li class="nav-item"><a class="nav-link" href="#"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 2</a></li> <li class="nav-item"><a class="nav-link" href="#"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 3</a></li> <li class="nav-item"><a class="nav-link disabled" href="#" tabindex="-1"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 4</a></li> </ul> {% endcapture %}{% include example.html content=example %} ### Tab verticali {% comment %}Example name: Con controllo pannelli, sfondo scuro, verticale a sinistra{% endcomment %} {% capture example %} <div class="bd-example-tabs"> <div class="row"> <div class="col-5 col-md-4 col-lg-3"> <div class="nav nav-tabs nav-tabs-vertical nav-dark" id="nav-vertical-tab-ico-dark" role="tablist" aria-orientation="vertical"> <a class="nav-link active" id="nav-vertical-tab-dark1-tab" data-bs-toggle="tab" href="#nav-vertical-tab-ico-dark1" role="tab" aria-controls="nav-vertical-tab-dark1" aria-selected="true">Tab 1 <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg></a> <a class="nav-link" id="nav-vertical-tab-ico-dark2-tab" data-bs-toggle="tab" href="#nav-vertical-tab-ico-dark2" role="tab" aria-controls="nav-vertical-tab-ico-dark2" aria-selected="false">Tab 2 <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg></a> <a class="nav-link" id="nav-vertical-tab-ico-dark3-tab" data-bs-toggle="tab" href="#nav-vertical-tab-ico-dark3" role="tab" aria-controls="nav-vertical-tab-ico-dark3" aria-selected="false">Tab 3 <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg></a> <a class="nav-link disabled" id="nav-vertical-tab-ico-dark4-tab" data-bs-toggle="tab" href="#nav-vertical-tab-ico-dark4" role="tab" aria-controls="nav-vertical-tab-ico-dark4" aria-selected="false">Tab 4 <svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg></a> </div> </div> <div class="col-7 col-md-8 col-lg-9 p-4"> <div class="tab-content" id="nav-vertical-tab-ico-darkContent"> <div class="tab-pane p-3 fade show active" id="nav-vertical-tab-ico-dark1" role="tabpanel" aria-labelledby="nav-vertical-tab-ico-dark1-tab">Contenuto 1</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-ico-dark2" role="tabpanel" aria-labelledby="nav-vertical-tab-ico-dark2-tab">Contenuto 2</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-ico-dark3" role="tabpanel" aria-labelledby="nav-vertical-tab-ico-dark3-tab">Contenuto 3</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-ico-dark4" role="tabpanel" aria-labelledby="nav-vertical-tab-ico-dark4-tab">Contenuto 4</div> </div> </div> </div> </div> {% endcapture %}{% include example.html content=example %} {% comment %}Example name: Con controllo pannelli, sfondo scuro, verticale a destra{% endcomment %} {% capture example %} <div class="bd-example-tabs"> <div class="row flex-row-reverse"> <div class="col-5 col-md-4 col-lg-3"> <div class="nav nav-tabs nav-tabs-vertical nav-dark" id="nav-vertical-tab-ico-dark-rev" role="tablist" aria-orientation="vertical"> <a class="nav-link active" id="nav-vertical-tab-dark1-tab-rev" data-bs-toggle="tab" href="#nav-vertical-tab-ico-dark1-rev" role="tab" aria-controls="nav-vertical-tab-dark1-rev" aria-selected="true"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 1</a> <a class="nav-link" id="nav-vertical-tab-ico-dark2-tab-rev" data-bs-toggle="tab" href="#nav-vertical-tab-ico-dark2-rev" role="tab" aria-controls="nav-vertical-tab-ico-dark2-rev" aria-selected="false"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 2</a> <a class="nav-link" id="nav-vertical-tab-ico-dark3-tab-rev" data-bs-toggle="tab" href="#nav-vertical-tab-ico-dark3-rev" role="tab" aria-controls="nav-vertical-tab-ico-dark3-rev" aria-selected="false"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 3</a> <a class="nav-link disabled" id="nav-vertical-tab-ico-dark4-tab-rev" data-bs-toggle="tab" href="#nav-vertical-tab-ico-dark4-rev" role="tab" aria-controls="nav-vertical-tab-ico-dark4-rev" aria-selected="false"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-link"></use></svg> Tab 4</a> </div> </div> <div class="col-7 col-md-8 col-lg-9 p-4"> <div class="tab-content" id="nav-vertical-tab-ico-darkContent-rev"> <div class="tab-pane p-3 fade show active" id="nav-vertical-tab-ico-dark1-rev" role="tabpanel" aria-labelledby="nav-vertical-tab-ico-dark1-tab-rev">Contenuto 1</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-ico-dark2-rev" role="tabpanel" aria-labelledby="nav-vertical-tab-ico-dark2-tab-rev">Contenuto 2</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-ico-dark3-rev" role="tabpanel" aria-labelledby="nav-vertical-tab-ico-dark3-tab-rev">Contenuto 3</div> <div class="tab-pane p-3 fade" id="nav-vertical-tab-ico-dark4-rev" role="tabpanel" aria-labelledby="nav-vertical-tab-ico-dark4-tab-rev">Contenuto 4</div> </div> </div> </div> </div> {% endcapture %}{% include example.html content=example %} ## Tab tipo Card Aggiungere la classe `.nav-tabs-cards` al tag `ul` per ottenere un design tipo card. {% comment %}Example name: Con controllo pannelli, tipo card{% endcomment %} {% capture example %} <ul class="nav nav-tabs nav-tabs-cards" id="card-simple" role="tablist"> <li class="nav-item"><a class="nav-link active" id="card-simple1-tab" data-bs-toggle="tab" href="#card-simpletab1" role="tab" aria-controls="card-simpletab1" aria-selected="true">Tab 1</a></li> <li class="nav-item"><a class="nav-link" id="card-simple2-tab" data-bs-toggle="tab" href="#card-simpletab2" role="tab" aria-controls="card-simpletab2" aria-selected="false">Tab 2</a></li> <li class="nav-item"><a class="nav-link" id="card-simple3-tab" data-bs-toggle="tab" href="#card-simpletab3" role="tab" aria-controls="card-simpletab3" aria-selected="false">Tab 3</a></li> <li class="nav-item"><a class="nav-link disabled" id="card-simple4-tab" data-bs-toggle="tab" href="#card-simpletab4" role="tab" aria-controls="card-simpletab4" aria-selected="false" aria-disabled="true" tabindex="-1">Tab 4 Disabilitato</a></li> <li class="nav-item-filler"></li> </ul> <div class="tab-content" id="card-simpleContent"> <div class="tab-pane p-4 fade show active" id="card-simpletab1" role="tabpanel" aria-labelledby="card-simple1-tab">Contenuto 1</div> <div class="tab-pane p-4 fade" id="card-simpletab2" role="tabpanel" aria-labelledby="card-simple2-tab">Contenuto 2</div> <div class="tab-pane p-4 fade" id="card-simpletab3" role="tabpanel" aria-labelledby="card-simple3-tab">Contenuto 3</div> <div class="tab-pane p-4 fade" id="card-simpletab4" role="tabpanel" aria-labelledby="card-simple4-tab">Contenuto 4 (non raggiungibile, il tab relativo è disabilitato)</div> </div> {% endcapture %}{% include example.html content=example %} ### Tab tipo Card con pulsanti aggiungi/elimina Aggiungere le classi `.nav-tabs-editable` e `.nav-tabs-cards` al tag `ul` per ottenere un design tipo card editabili. Includere l'hmtl degli ulteriori elementi di interfaccia come da esempio. {% comment %}Example name: Con controllo pannelli, tipo card con pulsanti aggiungi/elimina{% endcomment %} {% capture example %} <div class="nav-tabs-wrapper"> <ul class="nav nav-tabs nav-tabs-cards nav-tabs-editable" id="card-simple-btn" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="card-simple-btn1-tab" data-bs-toggle="tab" href="#card-simple-btntab1" role="tab" aria-controls="card-simple-btntab1" aria-selected="true">Tab 1 </a> <a href="#" class="nav-link-close"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-close"></use></svg><span class="visually-hidden"> Chiudi tab 1</span></a> </li> <li class="nav-item"> <a class="nav-link" id="card-simple-btn2-tab" data-bs-toggle="tab" href="#card-simple-btntab2" role="tab" aria-controls="card-simple-btntab2" aria-selected="false">Tab 2</a> <a href="#" class="nav-link-close"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-close"></use></svg><span class="visually-hidden"> Chiudi tab 2</span></a> </li> <li class="nav-item"> <a class="nav-link" id="card-simple-btn3-tab" data-bs-toggle="tab" href="#card-simple-btntab3" role="tab" aria-controls="card-simple-btntab3" aria-selected="false">Tab 3</a> <a href="#" class="nav-link-close"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-close"></use></svg><span class="visually-hidden"> Chiudi tab 3</span></a> </li> <li class="nav-item"> <a class="nav-link disabled" id="card-simple-btn4-tab" data-bs-toggle="tab" href="#card-simple-btntab4" role="tab" aria-controls="card-simple-btntab4" aria-selected="false" aria-disabled="true" tabindex="-1">Tab 4 Disabilitato</a> <a href="#" class="nav-link-close disabled"><svg class="icon"><use href="{{ site.baseurl }}/dist/svg/sprites.svg#it-close"></use></svg><span class="visually-hidden"> Chiudi tab 4</span></a> </li> <li class="nav-item-filler"></li> <li class="nav-item"> <a href="#" class="nav-tab-add"><span class="visually-hidden"> Aggiungi un tab</span></a> </li> </ul> </div> <div class="tab-content" id="card-simple-btnContent"> <div class="tab-pane p-4 fade show active" id="card-simple-btntab1" role="tabpanel" aria-labelledby="card-simple-btn1-tab">Contenuto 1</div> <div class="tab-pane p-4 fade" id="card-simple-btntab2" role="tabpanel" aria-labelledby="card-simple-btn2-tab">Contenuto 2</div> <div class="tab-pane p-4 fade" id="card-simple-btntab3" role="tabpanel" aria-labelledby="card-simple-btn3-tab">Contenuto 3</div> <div class="tab-pane p-4 fade" id="card-simple-btntab4" role="tabpanel" aria-labelledby="card-simple-btn3-tab">Contenuto 4 (non raggiungibile, il tab relativo è disabilitato)</div> </div> {% endcapture %}{% include example.html content=example %} ### Effetto "a comparsa" Per fare in modo che i tab appaiano con un'animazione "a comparsa" (fade in), è sufficiente aggiungere la classe `.fade` ad ogni `.tab-pane`. Il primo `.tab-pane` dovrà anche avere la classe `.show` per rendere il contenuto iniziale visibile. ```html <div class="tab-content"> <div class="tab-pane fade show active" id="tab1" role="tabpanel" aria-labelledby="content-tab-tab">...</div> <div class="tab-pane fade" id="tab2" role="tabpanel" aria-labelledby="tab2-tab">...</div> <div class="tab-pane fade" id="tab3" role="tabpanel" aria-labelledby="tab3-tab">...</div> <div class="tab-pane fade" id="tab4" role="tabpanel" aria-labelledby="tab4-tab">...</div> </div> ``` Si possono trovare dettagli aggiuntivi sulla gestione attraverso JavaScript di metodi ed eventi sui tab alla [pagina corrispondente](https://getbootstrap.com/docs/{{ site.bootstrap_minor }}/components/navs-tabs/#methods) sul sito di Bootstrap. ## Implementazione ### Tramite data attributes Puoi attivare una navigazione a tab senza scrivere JavaScript, semplicemente utilizzando la proprietà `data-bs-toggle="tab"` nel link all'interno di liste di tipo `.nav-tabs`: ```html <!-- Nav tabs --> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="data-ex-tab1-tab" data-bs-toggle="tab" href="#tab1" role="tab" aria-controls="tab1" aria-selected="true">Tab 1</a> </li> <li class="nav-item"> <a class="nav-link" id="data-ex-tab2-tab" data-bs-toggle="tab" href="#tab2" role="tab" aria-controls="tab2" aria-selected="false">Tab 2</a> </li> <li class="nav-item"> <a class="nav-link" id="data-ex-tab3-tab" data-bs-toggle="tab" href="#tab3" role="tab" aria-controls="tab3" aria-selected="false">Tab 3</a> </li> <li class="nav-item"> <a class="nav-link" id="data-ex-tab4-tab" data-bs-toggle="tab" href="#tab4" role="tab" aria-controls="tab4" aria-selected="false">Tab 4</a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane active" id="data-ex-tab1" role="tabpanel" aria-labelledby="data-ex-tab1-tab">...</div> <div class="tab-pane" id="data-ex-tab2" role="tabpanel" aria-labelledby="data-ex-tab2-tab">...</div> <div class="tab-pane" id="data-ex-tab3" role="tabpanel" aria-labelledby="data-ex-tab3-tab">...</div> <div class="tab-pane" id="data-ex-tab4" role="tabpanel" aria-labelledby="data-ex-tab4-tab">...</div> </div> ``` ### Tramite JavaScript Alternativamente, è possibile attivare i tab utilizzando JavaScript: ```js var triggerTabList = [].slice.call(document.querySelectorAll('#myTab a')) triggerTabList.forEach(function (triggerEl) { var tabTrigger = new bootstrap.Tab(triggerEl) triggerEl.addEventListener('click', function (event) { event.preventDefault() tabTrigger.show() }) }) ``` È possibile attivare tab individualmente in diversi modi: ```js var triggerEl = document.querySelector('#myTab a[href="#profile"]') bootstrap.Tab.getInstance(triggerEl).show() // Select tab by name var triggerFirstTabEl = document.querySelector('#myTab li:first-child a') bootstrap.Tab.getInstance(triggerFirstTabEl).show() // Select first tab ```
Markdown
UTF-8
3,154
2.578125
3
[]
no_license
--- description: "Steps to Prepare Award-winning Pea and Ham Soup" title: "Steps to Prepare Award-winning Pea and Ham Soup" slug: 1033-steps-to-prepare-award-winning-pea-and-ham-soup date: 2021-03-28T13:47:40.190Z image: https://img-global.cpcdn.com/recipes/173924bacd685b24/680x482cq70/pea-and-ham-soup-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/173924bacd685b24/680x482cq70/pea-and-ham-soup-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/173924bacd685b24/680x482cq70/pea-and-ham-soup-recipe-main-photo.jpg author: Emily Gordon ratingvalue: 4.2 reviewcount: 18041 recipeingredient: - "2 Ham Hocks" - "1-2 Litres Water cover food" - "2 Carrots roughly chopped" - "2 Celery Stalks roughly chopped" - "1 Onion roughly chopped" - "500 grams Split Green Peas" - "2 tablespoons Minced Garlic" - " Salt Pepper and Herbs to taste" - "2 teaspoons MSG" recipeinstructions: - "Add all the ingredients to slow cooker. Cook on low for 7 hours" - "Remove Ham and pull meat from the bone." - "Blend soup together" - "Add ham back into blended soup and cook for a further hour on low" categories: - Recipe tags: - pea - and - ham katakunci: pea and ham nutrition: 225 calories recipecuisine: American preptime: "PT22M" cooktime: "PT35M" recipeyield: "1" recipecategory: Dinner --- ![Pea and Ham Soup](https://img-global.cpcdn.com/recipes/173924bacd685b24/680x482cq70/pea-and-ham-soup-recipe-main-photo.jpg) Hello everybody, it's me again, Dan, welcome to my recipe page. Today, we're going to prepare a distinctive dish, pea and ham soup. One of my favorites food recipes. For mine, I will make it a little bit tasty. This is gonna smell and look delicious. Pea and Ham Soup is one of the most well liked of recent trending foods in the world. It's enjoyed by millions every day. It's easy, it's fast, it tastes yummy. Pea and Ham Soup is something that I've loved my whole life. They are fine and they look fantastic. To begin with this particular recipe, we have to first prepare a few components. You can cook pea and ham soup using 9 ingredients and 4 steps. Here is how you can achieve that. <!--inarticleads1--> ##### The ingredients needed to make Pea and Ham Soup: 1. Make ready 2 Ham Hocks 1. Get 1-2 Litres Water (cover food) 1. Prepare 2 Carrots roughly chopped 1. Get 2 Celery Stalks roughly chopped 1. Prepare 1 Onion roughly chopped 1. Get 500 grams Split Green Peas 1. Make ready 2 tablespoons Minced Garlic 1. Take Salt, Pepper and Herbs to taste 1. Prepare 2 teaspoons MSG <!--inarticleads2--> ##### Steps to make Pea and Ham Soup: 1. Add all the ingredients to slow cooker. Cook on low for 7 hours 1. Remove Ham and pull meat from the bone. 1. Blend soup together 1. Add ham back into blended soup and cook for a further hour on low So that's going to wrap it up for this exceptional food pea and ham soup recipe. Thanks so much for reading. I am sure you can make this at home. There's gonna be more interesting food in home recipes coming up. Remember to save this page on your browser, and share it to your family, colleague and friends. Thanks again for reading. Go on get cooking!
Python
UTF-8
230
3.46875
3
[]
no_license
min = input('Informe minutos usando: ') if min < 200: preco = 0.20 else: if min <= 400: preco = 0.18 else: if min <= 800: preco = 0.15 else: preco = 0.08 print ('O preco dos minutos usando: R$ %.2f' %(min * preco))
Ruby
UTF-8
1,873
2.96875
3
[]
no_license
require './lib/atm.rb' describe Atm do let(:account) { instance_double('Account', pin: 1234, exp_date: '04/17', account_status: :active) } before do #add atrribute of balance and set it to 100 allow(account).to receive(:balance).and_return(100) #allow account to receive new balance using setter method allow(account).to receive(:balance=) end it 'has 1000$ on initialize' do expect(subject.funds).to eq 1000 end it 'funds are reduced at a withdrawal' do subject.withdraw(50,1234, account) expect(subject.funds).to eq 950 end it 'allows withdrawal if bank has enough funds' do expected_output ={ status: true, message: 'Success!!', date: Date.today, amount: 45, bills:[20,20,5] } expect(subject.withdraw(45,1234, account)).to eq(expected_output) end it "rejects withdrawal if bank has insufficient funds" do expected_output = { status: false, message: 'You have insufficient funds!!', date: Date.today } expect(subject.withdraw(105, 1234, account)).to eq(expected_output) end it "rejects withdrawal if ATM has insufficient funds" do subject.funds = 50 expected_output = { status: false, message: 'Insufficient funds in ATM', date: Date.today } expect(subject.withdraw(100, 1234, account)).to eq(expected_output) end it 'rejects withdrawal if Atm is expired' do allow(account).to receive(:exp_date).and_return('12/15') expected_output = { status: false, message: 'ATM Card Expired!!', date: Date.today } expect(subject.withdraw(6, 1234, account)).to eq(expected_output) end it 'rejects withdrawal if account is :disabled' do allow(account).to receive(:account_status).and_return(:disabled) expected_output = { status: false, message: 'Your account is disabled!!', date: Date.today } expect(subject.withdraw(5, 1234, account)).to eq(expected_output) end end
SQL
UTF-8
922
2.75
3
[ "MIT" ]
permissive
-- View: public."V_Activity_Linestring" -- DROP VIEW public."V_Activity_Linestring"; CREATE OR REPLACE VIEW public."V_Activity_Linestring_Public" AS SELECT "Activity".act_type, "Activity".act_dist, "Activity"."act_totalElevGain", "Activity".act_avg_speed, "Activity".act_elapsed_time, "Activity".act_kilojoules, "Activity".act_max_speed, st_linefromencodedpolyline("Activity".polyline) AS linestring FROM "Activity" WHERE "Activity".polyline IS NOT NULL UNION ALL SELECT "Activty_Archive".act_type, "Activty_Archive".act_dist, "Activty_Archive"."act_totalElevGain", "Activty_Archive".act_avg_speed, "Activty_Archive".act_elapsed_time, "Activty_Archive".act_kilojoules, "Activty_Archive".act_max_speed, st_linefromencodedpolyline("Activty_Archive".polyline) AS linestring FROM "Activty_Archive" WHERE "Activty_Archive".polyline IS NOT NULL;
C
UTF-8
335
3.5
4
[]
no_license
#include <stdio.h> int main() { int n = 20, i, j, k; for (i = 1; i <= n; i++) { //print space for (j = 1; j < i; j++) { printf(" "); } //printf * for (k = 0; k <= n - i; k++) { printf("*"); } printf("\n"); } return 0; }
C++
UTF-8
394
3.5625
4
[]
no_license
#include "pch.h" #include <iostream> #include <string> namespace { using std::cout; using std::string; } int length(char s[]); int main() { char arr[] = "computer"; int wordLen = length(arr); cout << wordLen; } int length(char s[]) { char *ptr = s; // Point to first element int count = 0; while (*ptr != '\0') // Counts chars in array { count++; ptr++; } return count; }
C++
UTF-8
1,501
3.34375
3
[]
no_license
#include <iostream> #include <memory.h> #pragma warning(disable:4996) using namespace std; char tree[31]; int t_cnt; class Trie { private: Trie* ascii[128]; int cnt; public: Trie() :cnt(0) { memset(ascii, 0, sizeof(ascii)); } void insert(const char* key) { if (*key == '\0') { // 문자열 끝 cnt++; // 해당 나무 개수 카운트 t_cnt++; // 전체 나무 개수 카운트 return; } int nxt = *key; if (!ascii[nxt]) ascii[nxt] = new Trie(); ascii[nxt]->insert(key + 1); } void print(int idx = 0) { if (cnt) { tree[idx] = '\0'; // 저장된 문자열만 출력하기 위해서 널('\0') 삽입 cout << tree << ' ' << 100.0 * cnt / t_cnt << '\n'; } for (int i = 0; i < 128; ++i) { if (ascii[i]) { tree[idx] = i; // 순서대로 문자열 저장 ascii[i]->print(idx + 1); } } } }; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); //freopen("inp.inp", "r", stdin); //freopen("out.out", "w", stdout); cout << fixed; cout.precision(4); Trie* root = new Trie(); while (cin.getline(tree, 31)) root->insert(tree); root->print(); return 0; } #include <map> #include <string> void solve_2() { map<string, int> tree; string str; int t = 0; while (getline(cin, str)) { tree[str]++; // 해당 나무 개수 (key 값에 str이 없더라도 자동으로 insert 됨) t++; // 전체 나무 개수 } cout << fixed; cout.precision(4); for (auto e : tree) cout << e.first << ' ' << 100.0 * e.second / t << '\n'; }
Java
UTF-8
3,212
2.25
2
[]
no_license
package com.example.krishna.badgecountapp.test; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.example.krishna.badgecountapp.R; import java.io.File; /** * Created by krishna on 29/5/15. */ public class CaptureActivity extends Activity { private String photoFileName="abc.png"; private Uri imageUrl; private ImageView mImageView; private Bitmap mBitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.capture_layout); Button capture= (Button) findViewById(R.id.btn_capture); mImageView = (ImageView) findViewById(R.id.iv_capture); capture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); if (intent.resolveActivity(getPackageManager()) != null) { intent.putExtra(MediaStore.EXTRA_OUTPUT, getPhotoFileUri(photoFileName)); startActivityForResult(intent, 1001); } } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1001) { if (resultCode == RESULT_OK) { imageUrl = getPhotoFileUri(photoFileName); mBitmap = BitmapFactory.decodeFile(imageUrl.getPath()); Log.d("TestTag", "ImageUrl:" + imageUrl.getPath()); galleryAddPic() ; mImageView.setImageBitmap(mBitmap); } else { Toast.makeText(this, "Picture wasn't taken!", Toast.LENGTH_SHORT).show(); } } } private void galleryAddPic() { Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); mediaScanIntent.setData(imageUrl); this.sendBroadcast(mediaScanIntent); } public Uri getPhotoFileUri(String fileName) { /*File mediaStorageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Images");*/ File mediaStorageDir=null; if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Images"); else mediaStorageDir=getApplicationContext().getCacheDir(); if(!mediaStorageDir.exists()&& !mediaStorageDir.mkdirs()) mediaStorageDir.mkdirs(); // return mediaStorageDir; /*if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){ }*/ return Uri.fromFile(new File(mediaStorageDir.getPath() + File.separator + fileName)); } }
Python
UTF-8
672
4.4375
4
[]
no_license
# Дана строка текста. # Напишите программу для подсчета стоимости строки, исходя из того, # что один любой символ (в том числе пробел) стоит 6060 копеек. Ответ дайте в рублях и копейках. # Sample Input 1: # # Привет, как дела?! # Sample Output 1: # # 10 р. 80 коп. def line_cost(string): characters = len(string) cost_one_symbol = 60 total = characters * cost_one_symbol rub = total // 100 kop = total % 100 print(f"{rub} р. {kop} коп.") line_cost('Привет, как дела?!')
C++
UTF-8
969
2.625
3
[]
no_license
/* Platform :- Codeforces Contest :- Codeforces Round 702 Div 3 Problem :- E - Accidental Victory */ #include<bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; long int A[n]; vector<long int>B; for(int i=0;i<n;++i){ cin>>A[i]; B.push_back(A[i]); } sort(B.begin(),B.end()); vector<long long>pref(n); pref[0]=B[0]; long int mx=-1; for(int i=1;i<n;++i){ if(B[i]>pref[i-1]){ mx=B[i-1]; } pref[i]=pref[i-1]+B[i]; } int c=0; for(int i=0;i<n;++i){ if(mx<A[i]){ c++; } } cout<<c<<endl; for(int i=0;i<n;++i){ if(mx<A[i]){ cout<<(i+1)<<" "; } } cout<<endl; } }
Java
UTF-8
2,663
3.390625
3
[]
no_license
public class Bl { private static int DEFAULT_SIZE = 1 << 28; public static final int ELEM_NUM = 50 * 10000; // 欲容纳的元素个数 public static final double PERCENTAGE = 0.001; // 希望的误差率 byte[] LowBitSet; byte[] HighBitSet; private static final boolean HIGH = false; private static final boolean LOW = true; Bl() { DEFAULT_SIZE = (int) Math.abs(ELEM_NUM * Math.log(PERCENTAGE) / (Math.log(2) * Math.log(2))) + 1; LowBitSet = new byte[DEFAULT_SIZE]; HighBitSet = new byte[DEFAULT_SIZE]; } int AddWithoutArithmetic(int num1,int num2) { if(num2==0) return num1;//没有进位的时候完成运算 int sum,carry; sum=num1^num2;//完成第一步没有进位的加法运算 carry=(num1&num2)<<1;//完成第二步进位并且左移运算 return AddWithoutArithmetic(sum,carry);//进行递归,相加 } public void add(int n) { if (content(HIGH, n)) { if (content(LOW, n)) { // 11 } else { // 10 del(HIGH, n); add(LOW, n); } } else { if (content(LOW, n)) { // 01 del(LOW, n); add(HIGH, n); } else { // 00 add(LOW, n); } } } public void add(final boolean bit, final int n) { //(byte) (1 << (n & 7)) 跟8取模,然后转换成要设置的bit。 if (bit) { LowBitSet[n >> 3 % DEFAULT_SIZE] |= (byte) (1 << (n & 7)); } else { HighBitSet[n >> 3 % DEFAULT_SIZE] |= (byte) (1 << (n & 7)); } } public void del(final int n) { if (content(HIGH, n) && !content(LOW, n)) { // 10 del(HIGH,n); add(LOW,n); } else{ //00,01,11 del(LOW, n); } } public void del(final boolean bit, final int n) { if (bit) { LowBitSet[n >> 3 % DEFAULT_SIZE] &= (byte) (1 << (n & 7)^255); } else { HighBitSet[n >> 3 % DEFAULT_SIZE] &= (byte) (1 << (n & 7)^255); } } public boolean content(int n) { return (content(LOW, n) || content(HIGH, n)); } public boolean content(final boolean bit, int n) { if (bit) { return ((LowBitSet[n >> 3 % DEFAULT_SIZE] & (byte) 1 << (n & 7)) == 1 << (n & 7)); } else { return ((HighBitSet[n >> 3 % DEFAULT_SIZE] & (byte) 1 << (n & 7)) == 1 << (n & 7)); } } public static void main(String[] args) { Bl bl = new Bl(); bl.add(1000); bl.add(1008); bl.add(1008); bl.del(1008); for (int i = 1000; i <= 1010; i++) { System.out.println("i:" + i + "," + bl.content(i)); } bl.del(1008); System.out.println("i:" + 1008 + "," + bl.content(1008)); System.out.println((1 << (11 & 7))^255); } }
Rust
UTF-8
5,232
2.828125
3
[]
no_license
use super::udp_socket; use crate::ethernet; use crate::ipv4::*; use crate::net_util; #[derive(Clone, Debug)] pub struct UDP { header: UdpHeader, pub payload: Vec<u8>, } #[derive(Copy, Clone, Debug)] pub struct UdpHeader { src_port: u16, dst_port: u16, length: u16, chksm: u16, } pub const UDP_PROTO: u8 = 17; impl UdpHeader { pub fn src_port(&self) -> u16 { self.src_port } pub fn dst_port(&self) -> u16 { self.dst_port } pub fn length(&self) -> u16 { self.length } pub fn chksm(&self) -> u16 { self.chksm } pub fn set_chksm(&mut self, value: u16) { self.chksm = value; } } impl UDP { pub fn process_packet(frame: ethernet::EthernetFrame, layer_3_writer: &IPstackWriter) { let ipv4_packet = ipv4::IPv4::packet_from_net_bytes(frame.payload()); let ip_header = ipv4_packet.ip_header(); match Self::packet_from_bytes(ipv4_packet) { Some(mut datagram) => { let identifier = net_util::addr_identifier(ethernet::IP_ADDR, datagram.dst_port()); match udp_socket::get_sock(&identifier) { Some(mut_wrapped_sock) => { let (lock, cond_var) = &*mut_wrapped_sock; let mut sock = lock.lock().unwrap(); sock.sock.write_to_sockbuff(datagram, ip_header); sock.buff_empty = false; cond_var.notify_all(); } None => { // println!("UDP Port not open"); // Port not open, send icmp error } } } None => { // Send icmp error // Checksum mismatch } } } pub fn header(&self) -> UdpHeader { self.header } pub fn src_port(&self) -> u16 { self.header.src_port } pub fn dst_port(&self) -> u16 { self.header.dst_port } pub fn length(&self) -> u16 { self.header.length } pub fn chksm(&self) -> u16 { self.header.chksm } pub fn set_chksm(&mut self, value: u16) { self.header.chksm = value; } pub fn create_packet( payload: &[u8], src_port: u16, dst_port: u16, src_ip: ethernet::ProtocolAddr, dst_ip: ethernet::ProtocolAddr, ) -> (UDP, Vec<u8>) { let mut packet = UDP { header: UdpHeader { src_port: src_port, dst_port: dst_port, // Header length(8 bytes) + the payload length length: (8 + payload.len()) as u16, chksm: 0u16, }, payload: payload.to_owned(), }; let packet_bytes = packet.packet_to_bytes(); let pseudo_header = Self::create_pseudo_header(&packet_bytes, &src_ip, &dst_ip); let (cmpted_chksum, _) = net_util::compute_ip_checksum(&pseudo_header, 18..20); packet.set_chksm(cmpted_chksum); (packet, packet_bytes) } pub fn packet_from_bytes(ipv4_packet: ipv4::IPv4) -> Option<UDP> { let pseudo_header = Self::create_pseudo_header( ipv4_packet.payload_bytes(), &ipv4_packet.src, &ipv4_packet.dst, ); let (cmpted_chksum, received_chksm) = net_util::compute_ip_checksum(&pseudo_header, 18..20); // If checksum is zero, skip checksum validation if (cmpted_chksum != received_chksm) && (received_chksm != 0) { None } else { let udp_bytes = ipv4_packet.payload_bytes(); let udp_datagram = UDP { header: UdpHeader { src_port: net_util::ntohs(&udp_bytes[0..2]), dst_port: net_util::ntohs(&udp_bytes[2..4]), length: net_util::ntohs(&udp_bytes[4..6]), chksm: net_util::ntohs(&udp_bytes[6..8]), }, payload: udp_bytes[8..].to_owned(), }; Some(udp_datagram) } } // https://en.wikipedia.org/wiki/User_Datagram_Protocol#IPv4_pseudo_header fn create_pseudo_header(udp_packet_bytes: &[u8], src_ip: &[u8], dst_ip: &[u8]) -> Vec<u8> { let mut pseudo_header = Vec::new(); pseudo_header.extend_from_slice(src_ip); pseudo_header.extend_from_slice(dst_ip); pseudo_header.push(0u8); pseudo_header.push(UDP_PROTO); pseudo_header.extend_from_slice((udp_packet_bytes.len() as u16).to_be_bytes().as_ref()); pseudo_header.extend_from_slice(udp_packet_bytes); pseudo_header } pub fn packet_to_bytes(&self) -> Vec<u8> { let mut packet_bytes = Vec::new(); packet_bytes.extend_from_slice(self.src_port().to_be_bytes().as_ref()); packet_bytes.extend_from_slice(self.dst_port().to_be_bytes().as_ref()); packet_bytes.extend_from_slice(self.length().to_be_bytes().as_ref()); packet_bytes.extend_from_slice(self.chksm().to_be_bytes().as_ref()); packet_bytes.extend_from_slice(&self.payload); packet_bytes } }
C#
UTF-8
1,614
2.546875
3
[]
no_license
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; namespace Chat_Server { public partial class Register : Form { public Register() { InitializeComponent(); password.PasswordChar = '\u25CF'; psw.PasswordChar = '\u25CF'; } private void register_but_Click(object sender, EventArgs e) { //Console.WriteLine("Enter your name"); //string name = Console.ReadLine(); string name = username.Text; //Console.WriteLine("Enter your password"); //string psw = Console.ReadLine(); string psws = password.Text; string pswconfirm = psw.Text; if (psws == pswconfirm) { Client client = new Client(name, psws); //Clients clients = Clients.deserialize(); Clients clients = new Clients(); Clients toser = clients.deserialize(); toser._clients.Add(client); toser.serialize(toser); this.Dispose(); } //if (password.StringValue == passwordcheck.StringValue) { // Clients addlcient = new Clients(); // addlcient._clients.Add(new Client(username.StringValue, null)); // addlcient.serialize(addlcient); //} } } }
Java
UTF-8
2,971
2.671875
3
[]
no_license
package icms_controller; import icms_ejb.*; import java.util.List; import javax.ejb.Stateful; import javax.persistence.*; @Stateful public class GestionnaireUsersBean implements GestionnaireUsersLocal { @PersistenceContext private EntityManager em; public void creerAdmin() { em.persist(new User("admin", "admin", 99)); } public void create(String login, String password, int permission) { em.persist(new User(login, password, permission)); } public void update(int id, String login, String password, int permission) { User u = find(id); u.update(login, password, permission); em.merge(u); } public void save(int id) { em.merge(find(id)); } public void destroy(int id) { em.remove(em.merge(find(id))); } /** * Find all users * @return */ public List<User> all() { return em.createNamedQuery("Users.findAll").getResultList(); } /** * Find all users with admin level (99) * @return */ public List<User> findAdmins() { return em.createNamedQuery("Users.findAdmins").getResultList(); } /** * Find a user by his id * @param id * @return */ public User find(int id) { Query queryUserById = em.createNamedQuery("Users.findById"); queryUserById.setParameter("id", id); List<User> users = queryUserById.getResultList(); if (users.size() == 1) { return users.get(0); } else { return null; } } /** * Find user by his login and password * @param login * @param password * @return User instance or null if not found */ public User findUserByLoginAndPassword(String login, String password) { Query queryUserByLoginAndPassword = em.createNamedQuery("Users.findByLoginAndPassword"); queryUserByLoginAndPassword.setParameter("login", login); queryUserByLoginAndPassword.setParameter("password", User.encryptPassword(password)); try { return (User) queryUserByLoginAndPassword.getSingleResult(); } catch (Exception e) { return null; } } /** * Find admin user by his login and password * @param login * @param password * @return User instance or null if not found */ public User findAdminByLoginAndPassword(String login, String password) { Query queryUserByLoginAndPassword = em.createNamedQuery( "Users.findByLoginAndPasswordAndPermission"); queryUserByLoginAndPassword.setParameter("login", login); queryUserByLoginAndPassword.setParameter("password", User.encryptPassword(password)); queryUserByLoginAndPassword.setParameter("permission", 99); try { return (User) queryUserByLoginAndPassword.getSingleResult(); } catch (Exception e) { return null; } } }
Shell
UTF-8
1,979
3.109375
3
[]
no_license
#!/bin/bash ##Created by @CrazyHer echo '继续进行安装...' &&\ cd ~ &&\ apt update && apt install wget curl dialog clang gcc g++ net-tools python -y &&\ curl -sL https://deb.nodesource.com/setup_12.x | bash - &&\ apt-get install -y nodejs &&\ npm install -g yarn &&\ curl -fOL https://github.com/cdr/code-server/releases/download/v3.4.1/code-server_3.4.1_arm64.deb &&\ dpkg -i code-server_3.4.1_arm64.deb ||(echo '继续安装失败!你可以输入./continue.sh重新继续安装' && exit 0) rm -rf ~/.config/code-server mkdir ~/.config/code-server echo '请设置code-server的访问密码,回车确认:' read code_password echo "设置成功,你的访问密码是 $code_password " &&\ echo 'bind-addr: 127.0.0.1:2333' >> ~/.config/code-server/config.yaml &&\ echo 'auth: password' >>~/.config/code-server/config.yaml &&\ echo "password: $code_password" >>~/.config/code-server/config.yaml &&\ echo 'cert: false'>>~/.config/code-server/config.yaml &&\ apt install nginx -y &&\ rm /etc/nginx/sites-enabled/default &&\ echo ' server { ##外网访问端口 listen 8080; ##服务器域名,在没有域名、只在局域网内访问的情况下,就填_就行了 server_name _; ##地址,如果需要重定向请自己配置,这里直接以根目录开始 location / { ##本地code-server的端口 proxy_pass http://localhost:2333/; ##必要的头设置 proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection upgrade; proxy_set_header Accept-Encoding gzip; } }'>> /etc/nginx/sites-available/code-server &&\ ln -s /etc/nginx/sites-available/code-server /etc/nginx/sites-enabled/ &&\ echo 'code-server &;nginx'>>~/startcode.sh &&\ chmod 777 ~/startcode.sh &&\ echo '全部安装完成!以后进入ubuntu输入./startcode.sh就可以启动code-server服务器啦!' ||echo '继续安装失败!' rm -f ~/continue.sh ~/.bashrc mv ~/.bashrcbak ~/.bashrc
SQL
UTF-8
1,173
3.40625
3
[ "MIT" ]
permissive
-- For Section 3.1 -- this is to create an Athena table for Zipcode to City mapping -- drop table quicksightdemo.usa_zipcode_list; create external table quicksightdemo.usa_zipcode_list ( RecordNumber INT, Zipcode STRING, City STRING, State STRING, Lat STRING, Long STRING, Locationtext STRING, Locationhierarchy STRING) ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION 's3://quicksight-demo2/usa-zipcode-list' TBLPROPERTIES ("skip.header.line.count"="1"); -- this is to create a table for Census stats by Zip -- datafile is in S3 csv format create external table quicksightdemo.usacensus_by_zip ( ZIPCODE STRING, MEDIANINCOME INT, MEANINCOME INT, POPULATIONCOUNT INT ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION 's3://quicksight-demo2/USACensus' TBLPROPERTIES ("skip.header.line.count"="1");
Java
UTF-8
10,838
2.84375
3
[]
no_license
package com.android.util.file; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.channels.FileChannel; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.widget.ImageView; /** * 文件工具类 * * @author 张全 */ public final class FileUtil { private FileUtil() { } /** * 将bitmap保存为jpg图片 * * @param bitmap * @param context * @param phone * @param fileName * @return */ public static String outBitmapToFile(Bitmap bitmap, Context context, String fileName) { File imageFile = createFile(context, fileName); if (imageFile == null) { return null; } outBitmapToFile(bitmap, imageFile); return imageFile.getAbsolutePath(); } /** * 创建图片文件 * * @param context * @param fileName * @return */ public static File createFile(Context context, String fileName) { try { if (TextUtils.isEmpty(fileName)) { fileName = System.currentTimeMillis() + ".jpg"; } File targetFile = new File(context.getCacheDir(), fileName); if (!targetFile.createNewFile()) { return null; } else { return targetFile; } } catch (IOException e) { e.printStackTrace(); return null; } } /** * 创建一个目录 * * @return */ public static boolean createDir(File dirPath) { if (dirPath == null) { return false; } if (!dirPath.exists()) { return dirPath.mkdirs(); } return false; } /** * 创建一个.nomedia文件 * * @param targetDir * @return * @throws IOException */ public static boolean createNoMediaFile(File targetDir) throws IOException { if (targetDir == null) { return false; } else { if (!targetDir.exists()) { targetDir.mkdirs(); } } return new File(targetDir, ".nomedia").createNewFile(); } /** * 删除目录及其子文件. * * @param file * 文件夹 */ public static void delFile(File file) { if (null == file) return; if (file.isDirectory()) { File[] listFiles = file.listFiles(); if (null == listFiles || listFiles.length == 0) { file.delete(); } else { for (File item : listFiles) { delFile(item); item.delete(); } } } else file.delete(); file.delete(); } /** * 获得文件目录大小 * * @param dir * 文件 * @return 文件目录大小 */ public static long getFileSize(File file) { long length = 0; if (file.isDirectory()) { String[] children = file.list(); for (int i = 0; i < children.length; i++) { File dir = new File(file, children[i]); length += getFileSize(dir); } } else length = file.length(); return length; } /** * 获取文件的扩展名. * * @param fileName * 文件名 比如 java.txt * @return 该文件的扩展名 比如txt */ @SuppressLint("DefaultLocale") public static String getExtension(String fileName) { String mExt = ""; if (!TextUtils.isEmpty(fileName)) { final int index = fileName.lastIndexOf('.'); mExt = (index != -1) ? fileName.substring(index + 1).toLowerCase().intern() : ""; } return mExt; } /** * 获取文件名(不带扩展名). * * @param fileName * 文件名 比如java.txt * @return 文件名 比如java */ public static String getFileName(String fileName) { if (!TextUtils.isEmpty(fileName)) { int index = fileName.lastIndexOf('.'); return index == -1 ? null : fileName.substring(0, index); } return null; } /** * 缩短显示指定的文件路径 * * @param path * 当前目录 * @param dim * 层级 * @return 返回最后dim层目录 比如/a/b/c/d.txt dim=2 则返回 /c/d.txt */ public static String getFileShortPath(String path, int dim) { int index = path.lastIndexOf("/"); String shortPath = null; if (index == -1) { shortPath = "/" + path; } else if (index > 0) { for (int i = 1; i < dim; i++) { int subIndex = path.lastIndexOf("/", index - 1); if (subIndex == -1) { break; } else { index = subIndex; } } shortPath = path.substring(index); } return shortPath; } /** * 获取当前目录的父级目录. * * @param mCurrentPath * 当前目录 * @return 上级目录 比如当前目录为/a/b/c.txt 则返回/a/b */ public static String getParentFilePath(String mCurrentPath) { int indexLastSlash = mCurrentPath.lastIndexOf("/"); return -1 == indexLastSlash ? null : mCurrentPath.substring(0, indexLastSlash); } /** * 拷贝文件。 * * @param context * @param srcFile * 源文件 * @param fileName * 目标文件名 * @return boolean true拷贝成功 */ public static String copyFile(Context context, File srcFile, String fileName) { if (null == srcFile || !srcFile.exists()) { return null; } FileChannel fcIn = null; FileChannel fcOut = null; File targetFile = createFile(context, fileName); if (targetFile == null || !targetFile.exists()) { return null; } try { fcIn = new FileInputStream(srcFile).getChannel(); fcOut = new FileOutputStream(targetFile).getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); return targetFile.getAbsolutePath(); } catch (Exception e) { e.printStackTrace(); } finally { if (null != fcIn) { try { fcIn.close(); } catch (Exception e) { } } if (null != fcOut) { try { fcOut.close(); } catch (Exception e) { } } } return null; } /** * 拷贝文件。 * * @param srcFile * 源文件 * @param targetFile * 目标文件 * @return boolean true拷贝成功 */ public static boolean copyFile(File srcFile, File targetFile) { if (null == srcFile || !srcFile.exists()) { return false; } FileChannel fcIn = null; FileChannel fcOut = null; try { if (null == targetFile || !targetFile.exists()) { targetFile.getParentFile().mkdirs(); targetFile.createNewFile(); } fcIn = new FileInputStream(srcFile).getChannel(); fcOut = new FileOutputStream(targetFile).getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); return true; } catch (Exception e) { e.printStackTrace(); } finally { if (null != fcIn) { try { fcIn.close(); } catch (Exception e) { } } if (null != fcOut) { try { fcOut.close(); } catch (Exception e) { } } } return false; } /** * 检查目录是否存在,并且为目录文件。 * * @param dir * 要检查的目录文件 * @return boolean */ public static boolean isDirExist(File dir) { return isFileExist(dir) && dir.isDirectory(); } /** * 检查文件是否存在,已做非空检查,file为null时认为文件不存在。 * * @param file * 要检查的文件 * @return boolean */ public static boolean isFileExist(File file) { if (null == file) { return false; } return file.exists(); } /** * 写文件,如果文件存在 则覆盖 * * @param from * 数据流 * @param to * 目标文件 */ public static void outStreamToFile(InputStream from, File to) { FileOutputStream os = null; try { if (to.exists()) to.delete(); to.getParentFile().mkdirs(); to.createNewFile(); os = new FileOutputStream(to); byte[] buf = new byte[1024]; int len = 0; while ((len = from.read(buf)) > 0) { os.write(buf, 0, len); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (from != null) try { from.close(); } catch (IOException e) { } if (os != null) try { os.close(); } catch (IOException e) { } } } /** * 将bitmap保存为jpg图片 * * @param bitmap * @param file */ public static void outBitmapToFile(Bitmap bitmap, File file) { if (null == bitmap || null == file) return; FileOutputStream fos = null; try { fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); if (null != file) file.delete(); } finally { if (null != fos) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static File saveResToFile(Context context, int imgId, File imgFile) { try { Drawable iconDrawable = context.getResources().getDrawable(imgId); if (iconDrawable instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable) iconDrawable).getBitmap(); if (bitmap != null) { // File imgFile = createImageFile(context, SHARE_IMG); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.JPEG, 100, bos); byte[] bitmapdata = bos.toByteArray(); // write the bytes in file FileOutputStream fos = new FileOutputStream(imgFile); fos.write(bitmapdata); fos.close(); return imgFile; } } } catch (Exception e) { e.printStackTrace(); } return null; } public static void saveImage(ImageView appIcon, Context context, File imgFile) { try { Drawable iconDrawable = appIcon.getDrawable(); if (iconDrawable instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable) iconDrawable).getBitmap(); if (bitmap != null) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.JPEG, 100, bos); byte[] bitmapdata = bos.toByteArray(); FileOutputStream fos = new FileOutputStream(imgFile); fos.write(bitmapdata); fos.close(); } } } catch (Exception e) { e.printStackTrace(); } } public static void saveImage(Bitmap bitmap, Context context, File imgFile) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 100, bos); byte[] bitmapdata = bos.toByteArray(); FileOutputStream fos = new FileOutputStream(imgFile); fos.write(bitmapdata); fos.close(); } catch (Exception e) { e.printStackTrace(); } } public static void saveImage(Bitmap bitmap, CompressFormat format, Context context, File imgFile) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(format, 100, bos); byte[] bitmapdata = bos.toByteArray(); FileOutputStream fos = new FileOutputStream(imgFile); fos.write(bitmapdata); fos.close(); } catch (Exception e) { e.printStackTrace(); } } }
C++
UTF-8
831
3.109375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> int * newarray(int n) { int size = sizeof(int) * (n + 1); int *p = (int *)malloc(size); return (int *)memset(p, 0, size); } int max(int v1, int v2) { if (v1 > v2) { return v1; } else { return v2; } } int main(void) { int n; scanf("%d", &n); int *a = newarray(n); for (int i = 1; i <= n; i ++) { scanf("%d", &a[i]); } int *s = newarray(n); for (int i = 1; i <= n; i ++) { s[i] = 1; for (int k = 1; k < i; k ++) { if (a[i] > a[k]) { s[i] = max(s[i], 1 + s[k]); } } } int mlen = 0; for (int i = 1; i <= n; i ++) { mlen = max(mlen, s[i]); } printf("%d\n", mlen); free(s); free(a); return 0; }
Markdown
UTF-8
1,210
2.640625
3
[]
no_license
--- id: error-errors title: Error Codes sidebar_label: Error Codes --- <div id="docBody"> <p>When issues arise, Diffbot APIs return the following fields in a JSON response:</p> <table class="controls table table-bordered" border="0" cellpadding="5"> <thead><tr> <th>Field</th> <th>Response</th> </tr></thead> <tbody> <tr> <td><code>error</code></td> <td>Description of the error</td> </tr> <tr> <td><code>errorCode</code></td> <td>Error code per the chart below</td> </tr> </tbody> </table> ```text { "error": "Could not download page (404)", "errorCode": 404 } ``` <h3>Possible errors returned:</h3> <table class="controls table table-bordered" border="0" cellpadding="5"> <thead><tr> <th>Code</th> <th>Description</th> </tr></thead> <tbody> <tr> <td><code>401</code></td> <td>Unauthorized token</td> </tr> <tr> <td><code>404</code></td> <td>Requested page not found</td> </tr> <tr> <td><code>429</code></td> <td>Your token has exceeded the allowed number of calls, or has otherwise been throttled for API abuse.</td> </tr> <tr> <td><code>500</code></td> <td>Error processing the page. Specific information will be returned in the JSON response.</td> </tr> </tbody> </table> </div>
Java
UTF-8
839
2.859375
3
[]
no_license
package com.sise.pet.utils; public enum CaptchaType { UPDATE_PASSWORD(1,"captcha:updatePassword:"), REGISTER(2,"captcha:register:"); Integer code; String value; CaptchaType(Integer code, String value) { this.code = code; this.value = value; } public static String getValue(Integer code) { CaptchaType[] values = values(); for (CaptchaType captchaType : values) { if (captchaType.code.equals(code)) { return captchaType.value; } } return null; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
TypeScript
UTF-8
902
2.5625
3
[]
no_license
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext' import File from 'App/Models/File' import Application from '@ioc:Adonis/Core/Application' export default class FilesController { public async store({ request }: HttpContextContract) { if (!request.file('file')) return const upload = request.file('file', { size: '2mb' })! const fileName = `${Date.now()}.${upload.subtype}` await upload.move(Application.tmpPath('uploads'), { name: fileName, }) const file = await File.create({ file: fileName, name: upload.clientName, type: upload.type, subtype: upload.subtype, }) return file } public async show({ request, response }: HttpContextContract) { const { id } = request.params() const file = await File.findByOrFail('id', id) return response.download(Application.tmpPath(`uploads/${file.file}`)) } }
Python
UTF-8
189
3.390625
3
[]
no_license
file_path = input().split("\\") tokens = file_path[-1].split(".") file_name = tokens[0] extension = tokens[1] print(f"File name: {file_name}") print(f"File extension: {extension}")
Python
UTF-8
774
3.390625
3
[]
no_license
from tkinter import * root = Tk() root.title("han GUI") listbox = Listbox(root, selectmod = "extended", height= 0) listbox.insert(0, "사과") listbox.insert(1, "딸기") listbox.insert(2, "바나나") listbox.insert(END, "수박") listbox.insert(END, "포도") listbox.pack() def btncmd(): #listbox.delete(0)#END면 맨뒤에 항목 삭제 0이면 맨 앞항목 #갯수 확인 #print("리스트에는", listbox.size(), "개가 있어요") #항목 확인(시작 idx, 끝 idx) #print("1번째부터 3까지의 항목: ", listbox.get(0,2)) #선택된 항목 확인( 위치로 반환(순서)) print("선택된 항목: ", listbox.curselection()) btn = Button(root, text= "클릭", command = btncmd) btn.pack() root.mainloop()
Python
UTF-8
1,677
2.703125
3
[ "MIT" ]
permissive
from flask import Flask, render_template, request from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) user = '' password = '' host = '' database = '' app.config['SQLALCHEMY_DATABASE_URI'] = f'postgresql://{user}:{password}@{host}/{database}' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = "" db = SQLAlchemy(app) class Filmes(db.Model): id = db.Column(db.Integer, primary_key=True) nome = db.Column(db.String(255), nullable=False) imagem_url = db.Column(db.String(255), nullable=False) def __init__(self, nome, imagem_url): self.nome = nome self.imagem_url = imagem_url @staticmethod def read_all(): return Filmes.query.order_by(Filmes.id.asc()).all() @staticmethod def read_single(id_registro): return Filmes.query.get(id_registro) def save(self): db.session.add(self) db.session.commit() @app.route("/") def index(): return render_template("index.html") @app.route("/read") def read_all(): registros = Filmes.read_all() return render_template("read_all.html", registros=registros) @app.route("/read/<id_registro>") def read_id(id_registro): registro = Filmes.read_single(id_registro) return render_template("read_single.html", registro=registro) @app.route("/create", methods=('GET', 'POST')) def create(): novo_id = None if request.method == 'POST': form = request.form registro = Filmes(form['nome'], form['imagem_url']) registro.save() novo_id = registro.id return render_template("create.html", novo_id=novo_id) if (__name__ == "__main__"): app.run(debug=True)
Swift
UTF-8
2,033
2.6875
3
[ "Apache-2.0" ]
permissive
// // CodeSystems.swift // HealthRecords // // Generated from FHIR 4.0.1-9346c8cc45 // Copyright 2022 Apple Inc. // // 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. import FMCore /** Preferred value set for Condition Clinical Status. URL: http://terminology.hl7.org/CodeSystem/condition-clinical ValueSet: http://hl7.org/fhir/ValueSet/condition-clinical */ public enum ConditionClinicalStatusCodes: String, FHIRPrimitiveType { /// The subject is currently experiencing the symptoms of the condition or there is evidence of the condition. case active /// The subject is experiencing a re-occurence or repeating of a previously resolved condition, e.g. urinary tract /// infection, pancreatitis, cholangitis, conjunctivitis. case recurrence /// The subject is experiencing a return of a condition, or signs and symptoms after a period of improvement or /// remission, e.g. relapse of cancer, multiple sclerosis, rheumatoid arthritis, systemic lupus erythematosus, /// bipolar disorder, [psychotic relapse of] schizophrenia, etc. case relapse /// The subject is no longer experiencing the symptoms of the condition or there is no longer evidence of the /// condition. case inactive /// The subject is no longer experiencing the symptoms of the condition, but there is a risk of the symptoms /// returning. case remission /// The subject is no longer experiencing the symptoms of the condition and there is a negligible perceived risk of /// the symptoms returning. case resolved }
Markdown
UTF-8
743
2.796875
3
[]
no_license
``` var data = $('body').data(), // data has properties house and mouse house = data.house, mouse = data.mouse ``` Một ví dụ khác của phép gán destructuring (từ Node.js): ``` var jsonMiddleware = require('body-parser').json var body = req.body, // body has username and password username = body.username, password = body.password ``` Trong ES6, chúng ta có thể thay thế code ES5 với các câu lệnh: ``` var {house, mouse} = $('body').data() // we'll get house and mouse variables var {jsonMiddleware} = require('body-parser') var {username, password} = req.body ``` Điều này cũng làm việc với mảng: ``` var [col1, col2] = $('.column'), [line1, line2, line3, , line5] = file.split('\n') ```
Markdown
UTF-8
1,520
2.796875
3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
--- date: 2009-09-29 22:11:42 slug: talking-about-data-races title: Talking about data races categories: [ "code" ] --- My countryman [Bartosz Milewski](http://bartoszmilewski.wordpress.com/) - the author of one of the best C++ introductory books - the [C++ In Action](http://www.relisoft.com/book/) posted video with very interesting talk about [Ownership Systems against Data Races](http://bartoszmilewski.wordpress.com/2009/09/22/ownership-systems-against-data-races/trackback/) (video is [here](http://www.vimeo.com/6689999)). Interestingly, Bartosz proposes to understand the battle with **data races** as a discipline-driven programming that helps, mostly C+ programmers, to _avoid all this horrible pitfalls_. Moreover, Bartosz presents programmers with a well-designed methodology _based on types system_ as a tool that may guard programs against injury from data races problem and with success. Basically (and not surprisingly) Bartosz recommends _think first, act later_ kind of approach based on detailed analysis of _what might be causing data races in your program_, on identification of potential sources of data race problems. This approach is a contrary to spending hours searching for data races conditions using debugger. The data race problem is a complex subject, but - in my opinion - Bartosz explains it in a very accessible step-by-step form. Three words summary of Bartosz' lecture and the presented methodology is: **sharing** + **mutability** + **no synchronisation** = **data race**
Java
UTF-8
5,120
2.34375
2
[]
no_license
package web.action; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import web.Intermediate.CartItems; import web.Intermediate.RecordPriceAndNum; import web.Intermediate.ShowPage; import web.entity.Cart; import web.entity.User; import web.servicce.CartService; /** * @author 黄信胜 * @date 2018年11月20日下午8:35:06 * @version 版本号 */ @SuppressWarnings("all") public class CartAction extends ActionSupport implements ModelDriven<Cart>{ private Cart cart = new Cart(); private ActionContext con = ActionContext.getContext(); private CartService cartService; private String[] gidlist; private String smallcounter; private boolean numcondition = true; private ShowPage showPage; public Cart getModel() { return cart; } public CartService getCartService() { return cartService; } public void setCartService(CartService cartService) { this.cartService = cartService; } public void setGidlist(String[] gidlist) { this.gidlist = gidlist; } public void setSmallcounter(String smallcounter) { this.smallcounter = smallcounter; } public String execute() throws Exception { return super.execute(); } public void setShowPage(ShowPage showPage) { this.showPage = showPage; } public ShowPage getShowPage() { return showPage; } /** * 查询购物车商品中是否存在该商品,有数量加+1,无添加该对象, * @param uid 用户id * @param gid 商品id * @return true:说明表中该记录已存在;false:该记录不存在 */ public boolean checkExistItems(Integer uid, Integer gid) { List<Cart> list = cartService.checkExistItems(uid, gid); if (list != null&&list.size() > 0) { Cart listCart = list.get(0); if (numcondition) { listCart.setGnum(listCart.getGnum() + cart.getGnum()); } else { if (listCart.getGnum() - cart.getGnum() <= 0) { listCart.setGnum(1); } else { listCart.setGnum(listCart.getGnum() - cart.getGnum()); } } cartService.saveCart(listCart); return true; } else { return false; } } /** * * @param c1 需要保存的商品类 */ public void saveCart(Cart c1) { cartService.saveCart(c1); } /** * 添加商品 * @return 返回一个字符串“addCart" * @throws ParseException 日期格式化异常 */ public String addCart() throws ParseException { if (this.checkExistItems(((User)con.getSession().get("user")).getUid(), cart.getGid())){}//购物车存在该商品添加数量 else { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 cart.setDate(df.parse(df.format(new Date()))); cartService.addCart(cart); } return "addCart"; } /** * 查看购物车 * @return 返回一个字符串 ”lookCart" */ public String lookCart() { System.out.println("showpage:\t"+showPage.getCurrentpage()); this.PagingProcess(cartService.statisticalCarts(((User)con.getSession().get("user")).getUid()).intValue());//总记录数 List<CartItems> cartlist = cartService.lookCart((User)con.getSession().get("user"), showPage.getCurrentpage(), showPage.getPageSize());//购物表 con.getSession().put("cartlist", cartlist); return "lookCart"; } /** * 统计用户购物车总数 * @return 返回 ”success" */ public String countAllCartItems(){ if (cartService.countAllCartItems(((User) con.getSession().get("user")).getUid()) != null) con.getSession().put("countAllCartItems", cartService.countAllCartItems(((User) con.getSession().get("user")).getUid())); else con.getSession().put("countAllCartItems", 0); return "loadHome"; } /** * 分页处理 * @param totalRecords 传入总页数 */ public void PagingProcess(Integer totalRecords) { showPage.setTotalpages((totalRecords % showPage.getPageSize() == 0) ? (totalRecords / showPage.getPageSize()) : ((totalRecords / showPage.getPageSize()) + 1)); if (showPage.getCurrentpage() == 0) showPage.setCurrentpage(1); if (showPage.getCurrentpage() >= showPage.getTotalpages()) showPage.setCurrentpage(showPage.getTotalpages()); con.getSession().put("showPage", showPage); } /** * 删除商品 * @return 返回一个字符串 ”lookCart" */ public String deleCart() { for (String gid : gidlist) {cartService.deleCart(((User)con.getSession().get("user")).getUid(), Integer.parseInt(gid));} this.lookCart(); return "lookCart"; } //添加数量或者减少数量时,默认回到最后一页? /** * 添加商品数量 * @return 返回一个字符串 ”lookCart" */ public String addCartNum() { this.checkExistItems(cart.getUid(), cart.getGid()); this.lookCart(); return "lookCart"; } /** * 减少商品数量 * @return 返回一个字符串 ”lookCart" */ public String decCartNum() { numcondition = false; this.checkExistItems(cart.getUid(), cart.getGid()); numcondition = true; this.lookCart(); return "lookCart"; } }
Python
UTF-8
3,298
2.90625
3
[]
no_license
# -*- coding: utf-8 -*- import jieba import re import jieba.posseg as pseg from sklearn import feature_extraction from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer from sklearn.cross_validation import train_test_split from sklearn import ensemble from sklearn.metrics import confusion_matrix from sklearn.linear_model import SGDClassifier from sklearn.metrics import roc_curve, auc from sklearn import svm from sklearn.linear_model import LogisticRegression from sklearn import tree from sklearn.ensemble import RandomForestClassifier import sklearn.naive_bayes as nb from tkinter import Tk,Label,Entry,StringVar,Button from tkinter import BOTTOM from tkinter import messagebox # 点击button时对应的操作 def on_hello(): print('hello') def on_click(count_v1, model): title_str = title_text.get() popular_prob = predict(title_str, count_v1, model) string = str("新闻标题:%s,其流行概率为%s" %(title_str,popular_prob)) messagebox.showinfo(title='预测结果', message = string) def predict(title_str, count_v1, model): test_title_token=[] token=jieba.cut_for_search(title_str) test_title_token.append(', '.join(token)) count_v2 = CountVectorizer(vocabulary=count_v1.vocabulary_) counts_test = count_v2.fit_transform(test_title_token) tfidf_test = tfidftransformer.fit(counts_test).transform(counts_test) pred=model.predict_proba(tfidf_test) return pred[:,1] # 次级窗口 ############model title=[] label=[] #load training data data=open('','r',encoding='utf-8',errors='ignore') for line in data: line=re.sub(' ','',line) line=re.sub(',',',',line) line=line.strip().split('&#') # split the tokens title_text=line[0] title_text=re.sub('[0-9A-Za-z]','', title_text) uv=float(line[1]) if uv<=100 and uv>=10: label.append(0) title.append(title_text) elif uv>=1000: label.append(1) title.append(title_text) else: continue data.close() ##tokenize title_token=[] for line in title: token=jieba.cut_for_search(line) title_token.append(', '.join(token)) x_train, x_test, y_train, y_test = train_test_split(title_token, label, test_size=0.2) tfidftransformer = TfidfTransformer() count_v1= CountVectorizer() counts_train = count_v1.fit_transform(x_train) print("the shape of train is "+repr(counts_train.shape)) tfidf_train = tfidftransformer.fit(counts_train).transform(counts_train) ## word = count_v1.get_feature_names() #print(word) model=LogisticRegression() #model=nb.MultinomialNB(alpha = 0.01) #model=SGDClassifier(loss='log') model.fit(tfidf_train, y_train) #事件循环 # 根窗口 root = Tk() root.title('window with command') #主窗口标题 root.geometry('400x200') #主窗口大小,中间的为英文字母x # l1 = Label(root, text="新闻标题:") l1.pack() #这里的side可以赋值为LEFT RTGHT TOP BOTTOM title_text = StringVar() title_entry = Entry(root, textvariable = title_text) title_text.set(" ") title_entry.pack() com = Button(root,text = '预测', command = lambda : on_click(count_v1, model)) com.pack(side = BOTTOM) # 次级窗口的位置摆放位置 root.mainloop() ##