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
Markdown
UTF-8
9,051
2.90625
3
[]
no_license
> ##guide-demo - [x] sys-on-emit(系统事件) > ###事件机制说明:<br > > 一句话,事件机制可以解决这种需求:`某个条件达成才做某事` <br > > node.on('eventName',callback,target);<br > > 参数一:eventName 事件名 用于区别监听的事件类型<br > > 参数二: callback 回调函数 当事件名所描述的条件发生时,触发该函数<br > > 参数三:target 调用者, 指定调用该回调函数的调用者,通常是回调函数所处的这个对象(this),也可以动态指定别的对象来调用回调函数。<br > > ###鼠标事件 > #####'mousedown' > `当鼠标按下时触发一次` <br > ```javascript this.node.on('mousedown',function(event){ this.node.runAction(cc.scaleTo(0.1, 0.8));//尺寸缩小为原来80% },this); ``` > #####'mouseenter' > `当鼠标移入目标节点区域时触发,不论是否按下` <br > ```javascript this.node.on('mouseenter',function(event){ this.node.runAction(cc.rotateTo(0.1,180));//旋转180度 },this); ``` > #####'mousemove' > `当鼠标在目标节点在目标节点区域中移动时触发,不论是否按下` <br > ```javascript this.node.on('mousemove',function(event){ //this.node.runAction(cc.rotateBy(0.1,30));//旋转30度 },this); ``` > #####'mouseleave' > `当鼠标移出目标节点区域时触发,不论是否按下` <br > ```javascript this.node.on('mouseleave',function(event){ this.node.runAction(cc.rotateTo(0.1,0));//旋转180度复原 },this); ``` > #####'mouseup' > `当鼠标从按下状态松开时触发一次` <br > ```javascript this.node.on('mouseup',function(event){ this.node.runAction(cc.scaleTo(0.1, 1));//尺寸放大为100% },this); ``` > #####'mousewheel' > `当鼠标滚轮滚动时触发` <br > ```javascript this.node.on('mousewheel',function(event){ this.node.runAction(cc.scaleTo(0.1,event.getScrollY()/120));//获取滚动值来设置大小 },this); ``` > ###鼠标事件的回调参数`event` > #####'event.type' > `事件类型` eg: 'mouseup', 'mousemove' ```javascript this.node.on('mouseup',function(event){ let type = event.type;// 'mouseup' },this); ``` > #####'event.getDelta()' > `返回和上一次触发时鼠标位置的差值`<br> > 返回值类型: cc.Vec2()<br> > eg: event.getDelta().x;event.getDelta().y;<br> ```javascript this.node.on('mouseup',function(event){ let delta = event.getDelta();// cc.Vec2(); let deltaX = delta.x; let deltaY = delta.y; },this); ``` > #####'event.getDeltaX()' > `返回和上一次触发时鼠标位置X方向上的差值` ```javascript this.node.on('mouseup',function(event){ let deltaX = event.getDeltaX(); },this); ``` > #####'event.getDeltaY()' > `返回和上一次触发时鼠标位置Y方向上的差值` ```javascript this.node.on('mouseup',function(event){ let deltaY = event.getDeltaY(); },this); ``` > #####'event.getLocation()' > `返回以当前节点的锚点为坐标原点的鼠标坐标`<br> > 返回值类型: cc.Vec2()<br> > eg: event.getLocation().x;event.getLocation().y;<br> ```javascript this.node.on('mouseup',function(event){ let location = event.getLocation(); let locationX = location.x; let locationY = location.y; },this); ``` > #####'event.getLocationX()' > `返回以当前节点的锚点为坐标原点X方向上的鼠标坐标` ```javascript this.node.on('mouseup',function(event){ let locationX = event.getLocationX(); },this); ``` > #####'event.getLocationY()' > `返回以当前节点的锚点为坐标原点Y方向上的鼠标坐标` ```javascript this.node.on('mouseup',function(event){ let locationY = event.getLocationY(); },this); ``` > #####'event.getLocationInView()' > `返回以手机屏幕左上(左下?)为坐标原点的鼠标坐标`<br> > 返回值类型: cc.Vec2() <br> > eg: event.getLocationInView().x;event.getLocationInView().y; <br> ```javascript this.node.on('mouseup',function(event){ let locationInView = event.getLocationInView(); let locationInViewX = locationInView.x; let locationInViewY = locationInView.y; },this); ``` > #####'event.getScrollX()' > `用于'mousewheel'事件 获取鼠标滚轮滚动X差值?鼠标滚轮只能上下滚,也不知道这个怎么用 默认为0` ```javascript this.node.on('mouseup',function(event){ let scrollX = event.getScrollX(); },this); ``` > #####'event.scrollY()' > `用于'mousewheel'事件 获取鼠标滚轮滚动Y差值?我的鼠标上滚动值为120,下滚动值为-120` ```javascript this.node.on('mouseup',function(event){ let scrollY = event.getScrollY(); //0(不动滚轮) 或 -120(下滚滚轮) 或 120(上滚滚轮) },this); ``` > ###触摸事件 > #####'touchstart' > `当手指触摸到屏幕时(节点范围内)` <br > ```javascript this.node.on('touchstart',function(event){ this.node.runAction(cc.rotateTo(0.1,180));//旋转180度 this.node.runAction(cc.scaleTo(0.1, 0.8));//尺寸缩小为原来80% },this); ``` > #####'touchmove' > `当手指在屏幕上目标节点区域内移动时` <br > ```javascript this.node.on('touchmove',function(event){ //nothing to do },this); ``` > #####'touchend' > `当手指在目标节点区域内离开屏幕时` <br > ```javascript this.node.on('touchend',function(event){ this.node.runAction(cc.rotateTo(0.1,0));//旋转180度复原 this.node.runAction(cc.scaleTo(0.1, 1));//尺寸放大为100% },this); ``` > #####'touchcancel' > `当手指在目标节点区域外离开屏幕时` <br > ```javascript this.node.on('touchcancel',function(event){ this.node.runAction(cc.rotateTo(0.1,0));//旋转180度复原 this.node.runAction(cc.scaleTo(0.1, 1));//尺寸放大为100% },this); ``` > ###触摸事件的回调参数`event` > #####'event.type' > `事件类型` eg: 'touchmove', 'touchend' ```javascript this.node.on('touchmove',function(event){ let type = event.type;// 'touchmove' },this); ``` > #####'event.touch.getDelta()' > `两次触发该事件触摸点的差值` ```javascript this.node.on('touchmove',function(event){ let delta = event.touch.getDelta();// cc.Vec2() let deltaX = delta.x; let deltaY = delta.y; },this); ``` > #####'event.touch.getLocation()' > `触摸点位置` ```javascript this.node.on('touchmove',function(event){ let location = event.touch.getLocation();// cc.Vec2() let locationX = location.x; let locationY = location.y; },this); ``` > #####'event.touch.getLocationX()' > `触摸点在X方向的位置` ```javascript this.node.on('touchmove',function(event){ let locationX = event.touch.getLocationX(); },this); ``` > #####'event.touch.getLocationY()' > `触摸点在Y方向的位置` ```javascript this.node.on('touchmove',function(event){ let locationY = event.touch.getLocationY(); },this); ``` > #####'event.touch.getLocationInView()' > `触摸点在屏幕坐标的位置` ```javascript this.node.on('touchmove',function(event){ let locationInView = event.touch.getLocationInView(); let locationInViewX = locationInView.x; let locationInViewY = locationInView.y; },this); ``` > #####'event.touch.getPreviousLocation()' > `和上面一样?` ```javascript this.node.on('touchmove',function(event){ let previousLocation = event.touch.getPreviousLocation(); let previousLocationX = previousLocation.x; let previousLocationY = previousLocation.y; },this); ``` > #####'event.touch.getPreviousLocationInView()' > `和上面一样?用的屏幕坐标?` ```javascript this.node.on('touchmove',function(event){ let previousLocationInView = event.touch.getPreviousLocationInView(); let previousLocationInViewX = previousLocationInView.x; let previousLocationInViewY = previousLocationInView.y; },this); ``` > #####'event.touch.getStartLocation()' > `触摸点最开始触摸的位置(移动触摸点该值不变)` ```javascript this.node.on('touchmove',function(event){ let startLocation = event.touch.getStartLocation(); let startLocationX = startLocation.x; let startLocationY = startLocation.y; },this); ``` > #####'event.touch.getStartLocationInView()' > `触摸点最开始触摸的位置(移动触摸点该值不变) 用的屏幕坐标?` ```javascript this.node.on('touchmove',function(event){ let startLocationInView = event.touch.getStartLocationInView(); let startLocationInViewX = startLocationInView.x; let startLocationInViewY = startLocationInView.y; },this); ```
C++
UTF-8
534
2.890625
3
[]
no_license
#include <iostream> #include <string> using namespace std; class studentStats { public: string getFName() const; string getLName() const; int getTScore() const; int getPScore() const; double getGPA() const; char getGrade() const; void setFName(string first = ""); void setLName(string last = ""); void setTScore(int); void setPScore(int); void setGPA(double); void setGrade(char); private: string studentFName; string studentLName; int testScore; int programmingScore; double studentGPA; char grade; };
Shell
UTF-8
1,336
3.609375
4
[]
no_license
#!/bin/bash # # Dump OpenVPN Client configs # if [[ "${DEBUG}" == "true" ]]; then set -x fi display_info() { echo -e "\033[1;32mInfo: $1\033[0m" } display_error() { echo -e "\033[1;31mError: $1\033[0m" } export OVPN_ENV_FILE="${OVPN_DIR}/ovpn_env.sh" if [[ ! -f "${OVPN_ENV_FILE}" ]]; then display_error "The [${OVPN_ENV_FILE}] file does not exist!" exit 1 else source ${OVPN_ENV_FILE} fi if [[ ! -f "${OVPN_PKI_DIR}/issued/${OVPN_SERVER_CN}.crt" ]]; then display_error "The EasyRSA PKI [${OVPN_PKI_DIR}/issued/${OVPN_SERVER_CN}.crt] does not exists." exit 1 fi echo "client" echo "nobind" echo "dev ${OVPN_DEVICEN}" echo "proto ${OVPN_PROTOCOL}" echo "remote ${OVPN_SERVER_CN} ${OVPN_PORT}" echo "" echo "persist-key" echo "persist-tun" echo "key-direction 1" echo "" echo "auth SHA512" echo "cipher ${OVPN_CIPHERS}" echo "remote-cert-tls server" if [ "${OVPN_ENABLE_LDAP}" == "true" ] ; then echo "auth-user-pass" fi echo "" echo "verb 3" echo "" echo "<ca>" cat ${OVPN_PKI_DIR}/ca.crt echo "</ca>" echo "" echo "<tls-auth>" cat ${OVPN_PKI_DIR}/ta.key echo "</tls-auth>" if [ "${OVPN_ENABLE_LDAP}" == "false" ] ; then echo "" echo "<cert>" cat ${OVPN_PKI_DIR}/issued/client.crt echo "</cert>" echo "<key>" cat ${OVPN_PKI_DIR}/private/client.key echo "</key>" fi
Markdown
UTF-8
474
2.78125
3
[]
no_license
# Pong_Remastered Author: Koustabh Das mail: keddy8218@gmail.com Originally programmed by Atari in 1972. Features two paddles, controlled by players, with the goal of getting the ball past your opponent's edge.First to 10 points wins. This version is built to more closely resemble the NES than the original Pong machines or the Atari 2600 in terms of resolution, though in widescreen (16:9) so it looks nicer on modern systems. This is an updated version where player 2 is CPU or AI
Java
UTF-8
993
2.375
2
[]
no_license
package com.progerslifes.diplom.facades.converters.user; import com.progerslifes.diplom.entity.UserProfile; import com.progerslifes.diplom.facades.converters.GenericConverter; import com.progerslifes.diplom.facades.dto.UserProfileDTO; import org.springframework.stereotype.Component; @Component public class UserProfileDTOConverter implements GenericConverter<UserProfileDTO, UserProfile> { @Override public UserProfile apply(UserProfileDTO userProfileDTO) { UserProfile userProfile = new UserProfile(); userProfile.setId(userProfileDTO.getId()); userProfile.setName(userProfileDTO.getName()); userProfile.setSurname(userProfileDTO.getSurname()); userProfile.setDescription(userProfileDTO.getDescription()); userProfile.setProfilePicture(userProfileDTO.getProfilePicture()); userProfile.setBirthDate(userProfileDTO.getBirthDate()); userProfile.setGithub(userProfileDTO.getGithub()); return userProfile; } }
Java
UTF-8
1,249
1.921875
2
[]
no_license
package com.ecust.touhouairline.repository; import com.ecust.touhouairline.entity.OrderDetailEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface OrderDetailRepository extends JpaRepository<OrderDetailEntity,String> { OrderDetailEntity findByDetailNo(Integer detailNo); @Query(value = "SELECT od.detailNo FROM flight f,ordermaster om,orderdetail od " + "where f.flightNo=?1 and om.flightNo =f.flightNo and om.orderNo = od.orderNo and od.passport=?2", nativeQuery = true) Integer findByPassport(String flightNo, String passport); @Query(value = "SELECT od.detailNo FROM flight f,ordermaster om,orderdetail od " + "where f.flightNo=?1 and om.flightNo =f.flightNo and om.orderNo = od.orderNo and od.identity=?2", nativeQuery = true) Integer findByIdentity(String flightNo, String passport); @Query(value = "SELECT count(*) FROM flight f,ordermaster om,orderdetail od " + "where f.flightNo=?1 and om.flightNo =f.flightNo and om.orderNo = od.orderNo and od.seat>0", nativeQuery = true) Integer countAllByFlightno(String flightNo); }
PHP
UTF-8
1,096
2.578125
3
[ "MIT" ]
permissive
<?php namespace Helix\Shopify; use Helix\Shopify\Base\AbstractEntity; use Helix\Shopify\Base\AbstractEntity\CrudTrait; /** * A carrier service. * * @see https://shopify.dev/docs/admin-api/rest/reference/shipping-and-fulfillment/carrierservice * * @method bool isActive () * @method string getCallbackUrl () * @method string getCarrierServiceType () * @method string getFormat () * @method string getName () * @method bool hasServiceDiscovery () * * @method $this setActive (bool $active) * @method $this setCallbackUrl (string $url) * @method $this setCarrierServiceType (string $type) * @method $this setFormat (string $format) * @method $this setName (string $name) * @method $this setServiceDiscovery (bool $discovery) */ class Carrier extends AbstractEntity { use CrudTrait; const TYPE = 'carrier_service'; const DIR = 'carrier_services'; const FORMAT_JSON = 'json'; const FORMAT_XML = 'xml'; }
Go
UTF-8
545
2.890625
3
[ "Apache-2.0" ]
permissive
package check import ( "reflect" ) func IsValueNilOrEmpty(c interface{}) bool { if c == nil { return true } value := reflect.ValueOf(c) switch value.Kind() { case reflect.Ptr: return value.IsNil() case reflect.Slice, reflect.Array, reflect.String: return value.Len() == 0 } return false } func IsValueNilOrBlank(c interface{}) bool { if c == nil { return true } value := reflect.ValueOf(c) switch value.Kind() { case reflect.Ptr: return value.IsNil() case reflect.String: return value.Len() == 0 } return false }
C#
UTF-8
1,006
2.5625
3
[ "Apache-2.0" ]
permissive
using Microsoft.SPOT.Hardware; using System; using GTM = Gadgeteer.Modules; namespace Gadgeteer.Modules.GHIElectronics { /// <summary> /// A OneWire X1 module for Microsoft .NET Gadgeteer /// </summary> [Obsolete] public class OneWireX1 : GTM.Module { private OneWire oneWire; private OutputPort port; /// <summary>Constructs a new OneWireX1 module.</summary> /// <param name="socketNumber">The socket that this module is plugged in to.</param> public OneWireX1(int socketNumber) { Socket socket = Socket.GetSocket(socketNumber, true, this, null); socket.EnsureTypeIsSupported(new char[] { 'X', 'Y' }, this); socket.ReservePin(Socket.Pin.Three, this); this.port = new OutputPort(socket.CpuPins[(int)Socket.Pin.Three], false); this.oneWire = new Microsoft.SPOT.Hardware.OneWire(this.port); } /// <summary> /// Returns the native NETMF OneWire interface object. /// </summary> public OneWire Interface { get { return this.oneWire; } } } }
C#
UTF-8
2,727
3.34375
3
[]
no_license
using System; using System.Linq; namespace _1QuickStartEntityFramework { class Program { static void Main(string[] args) { //Ctrate a DB Connections with using block using (var dbContext = new NorthwindSlimEntities()) { //Lecture-1 or Day-1 //Show all sql in console display //dbContext.Database.Log = Console.Write; //Get & Display products var products = from p in dbContext.Products where p.CategoryId == 1 orderby p.ProductName ascending select p; foreach (Product product in products) { Console.WriteLine("ID-{0} Name-{1} Price-{2}", product.ProductId, product.ProductName, product.UnitPrice.GetValueOrDefault().ToString("C")); } //Update Product Price in Single Product Console.WriteLine("Do you want to update Price? \nPlease Enter your product Id below:"); int id = Convert.ToInt32(Console.ReadLine()); var chai = dbContext.Products.Single(a => a.ProductId == id); chai.UnitPrice++; dbContext.SaveChanges(); //Dislay Update Price Console.WriteLine("ID-{0} Name-{1} Price-{2}", chai.ProductId, chai.ProductName, chai.UnitPrice.GetValueOrDefault().ToString("C")); //Create a New Products Console.WriteLine("Create a New Products"); var chocolato = new Product() { ProductName = "Orio", CategoryId = 1, UnitPrice = 15, }; dbContext.Products.Add(chocolato); dbContext.SaveChanges(); //Display New Product Console.WriteLine("ID-{0} Name-{1} Price-{2}", chocolato.ProductId, chocolato.ProductName, chocolato.UnitPrice.GetValueOrDefault().ToString("C")); //Delete a Product Console.WriteLine("Enter your deleting product ID:"); int deleteId = Convert.ToInt32(Console.ReadLine()); var delete = dbContext.Products.Single(b => b.ProductId == deleteId); dbContext.Products.Remove(delete); dbContext.SaveChanges(); //Display Deleting Product Console.WriteLine("ID-{0} Name-{1} Price-{2}", delete.ProductId, delete.ProductName, delete.UnitPrice.GetValueOrDefault().ToString("C")); } Console.ReadKey(); } } }
C++
UTF-8
1,790
3.46875
3
[]
no_license
/* * Progetto di Physics Programming * Fabio Cogliati, Manuele Nerucci */ #pragma once #include "Collider.h" namespace PhysicEngine { //Forward declarations struct Collision; /*Classe che rappresenta un plane collider con funzione Ax + By + Cz = 0*/ class PlaneCollider : public Collider { public: /*Enum che rappresenta il verso del piano, MajorLookDirection : il piano guarda per funzione piano > 0 MinorLookDirection : il piano guarda per funzione pinao < 0*/ enum lookDirections { MajorLookDirection = 0, MinorLookDirection }; /*Costruttore di base*/ PlaneCollider(); /*Costruttore che vuole i parametri della funzione di piano e la direzione di sguardo*/ PlaneCollider(float A, float B, float C, float D, lookDirections lookDirection); /*Funzione che clona l'oggetto tramite una new */ PlaneCollider* clone() const; /*Ritorna il tipo di collider secondo l'enum ColliderType contenuto nella classe Collider */ ColliderType getColliderType() const; /*Ritorna il coefficiente A della funzione di piano*/ float getAFunctionCoefficient() const; /*Ritorna il coefficiente B della funzione di piano*/ float getBFunctionCoefficient() const; /*Ritorna il coefficiente C della funzione di piano*/ float getCFunctionCoefficient() const; /*Ritorna il coefficiente D della funzione di piano*/ float getDFunctionCoefficient() const; /*Ritorna il verso di sguardo*/ lookDirections getLookingDirection() const; private: /*coefficiente A della funzione di piano*/ float A; /*coefficiente B della funzione di piano*/ float B; /*coefficiente C della funzione di piano*/ float C; /*coefficiente D della funzione di piano*/ float D; /*direzione di sguardo della funzione di piano*/ lookDirections lookDirection; }; }
Markdown
UTF-8
11,928
3.4375
3
[ "CC0-1.0" ]
permissive
--- layout: post title: "Topology, Part I: Topological Spaces" author: "Jay Havaldar" date: 2017-08-04 mathjax: true category: [math] download: true category: notes --- ## Definition of a Topology **Definition:** Let $X$ be a set. We define a **topology** $\mathcal{T}$ on $X$ to be a collection of sets (called **open sets**) so that: - $\emptyset \in \mathcal{T}$ - $X \in \mathcal{T}$ - $\mathcal{T}$ is closed under unions and finite intersections. We name some examples: - If $X$ is a nonempty set, we can define $T$ to be every subset of $X$. This is called the **discrete topology** on $X$. **Definition:** Let $X$ be a set with two topologies $\mathcal{T}_1, \mathcal{T}_2$. If $\mathcal{T}_1 \subset \mathcal{T}_2$ or $\mathcal{T}_2 \subset \mathcal{T}_1$, we say that they are **comparable**. If $\mathcal{T}_1 \subset \mathcal{T}_2$ it is **finer** than $\mathcal{T}_2$; if $\mathcal{T}_1 \supset \mathcal{T}_2$ we say it is **coarser**. **Definition:** Let $X$ be a topological space and $x\in X$. An open set containing $x$ is called a **neighborhood** of $x$. We now come to a familiar definition of open sets. ##### Theorem >Let $X$ be a topological space and $A \subset X$. Then $A$ is open in $X$ iff for every $x \in A$, there is a neighborhood $U$ of $x$ so that $U\subset A$. We prove the theorem as follows. Suppose that $A$ is open and $x \in A$. Then we have found a neighborhood of $X$ contained in $A$; namely, $A$ itself. Now conversely, suppose that for every $x\in A$, there is a neighborhood $U_x \subset A$ so that $x\in U_x$. Then, $A = \bigcup\limits_{x\in A} U_x$; since each $U_x$ is open, $A$ is as well. ## Bases **Definition:** Let $X$ be a topological space. We say that a collection of subsets $\mathcal{B}$ of $X$ is a **basis** if: - For every $x\in X$, $x \in B$ for some $B \in \mathcal{B}$; the collection $\mathcal{B}$ covers $X$. - For every $x\in X$, if $x\in B_1 \cap B_2$ for $B_1, B_2 \in \mathcal{B}$, then there is a set $B_3 \in \mathcal{B}$ so that $x\in B_3 \subset B_1 \cap B_2$. We get a topology out of a basis: **Definition:** Let $\mathcal{B}$ be a basis for a set $X$. Then we define the **topology generated by ** $\mathcal{B}$ as follows: the open sets consist of the empty set and every union of basis elements. In particular, each basis element is an open set in the topology generated by the basis. We still have to prove that the topology generated by $\mathcal{B}$ is indeed a topology. We begin with a lemma. ##### Lemma > Let $\mathcal{B}$ be a basis. Then if $B_1, B_2, \dots ,B_n \in \mathcal{B}$, and $x\in \bigcap\limits_{i=1}^{n} B_i$, there exists a basis element $B'$ so that $x \in B' \in \bigcap\limits_{i=1}^{n} B_i$ The $n=2$ case follows from the definition of a basis. The other cases follow by induction. ##### Theorem > Let $\mathcal{B}$ be a basis for a set $X$. Then the topology generated by $\mathcal{B}$ is a topology. We check the four properties of a topology. By definition, the empty set is indeed open. Furthermore, since every point $x\in X$ is contained in some basis element, $X$ is the union of all the basis elements. Since the open sets are unions of basis elements, unions of open sets are also unions of basis elements, and hence open. We are left to show that finite intersections are open. Let $V = \bigcap\limits_{i=1}^n U_i$, where each $U_i$ is open and nonempty. For each $x\in V$, $x\in U_i$ for all $i$. Since each $U_i$ is a union of basis elements, in particular we can find a basis element $B_i$ so that $x \in B_i \subset U_i$ for each $U_i$. Therefore, we can write $x\in \bigcap\limits_{i=1}^n B_i \subset V$. By the definition of a basis and our earlier lemma, $x\in B_x$ for some $B_x \subset V$. Therefore, $V = \bigcap\limits_{x\in V} B_x$; since $V$ is a union of basis elements, it is open as well. --- We name some examples of bases and the topologies they generate: - On the real line, the open intervals $(a,b)$ form a basis. This basis generates the **standard topology** on $\mathbb{R}$, where the open sets are unions of intervals. - Let $X$ be a set. Then the singleton sets form a basis. This basis generates the discrete topology on $X$. - On $\mathbb{R^2}$, we define a basis as open balls of radius $\epsilon > 0$. This basis generates the topology for which the open sets are unions of open balls; we can generate this same topology with open intervals of the form $(a,b)\times (c,d)$. This is called the **standard topology** on $\mathbb{R}^n$. ##### Theorem > Let $X$ be a set and $\mathcal{B}$ a basis for a topology on $X$. Then $U$ is open in the topology generated by $\mathcal{B}$ iff for each $x\in U$, there is a basis element $B_x$ so that $x \in B_x \subset U$. The forward direction follows from the fact that open sets are unions of basis elements. To prove the converse, we assume that for each $x\in U$, there is a basis element $B_x$ so that $x \in B_x \subset U$. Then $U = \bigcup\limits_{x \in U}B_x$, so indeed $U$ is open. --- We now give a way to construct a basis for a topology. ##### Theorem > Let $X$ be a set with a topology $\mathcal{T}$, and let $\mathcal{C}$ be a collection of open sets in $X$. Suppose that for each open set $U$ and each point $x\in U$, there is an open set $V\in \mathcal{C}$ so that $x\in V \subset U$. Then $C$ is a basis that generates the topology $\mathcal{T}$. ## Special Kinds of Topologies We discuss two kinds of standard topologies we can create from spaces. ### The Product Topology **Definition:** Suppose we have two topological spaces $X,Y$. Then we define the **product topology** on $X \times Y$ as the topology generated by the basis $\\{ U \times V\\}$, where $U$ is open in $X$ and $V$ is open in $Y$. We can define this topology equivalently with the following theorem. ##### Theorem > If $\mathcal{B}, \mathcal{C}$ are bases for $X,Y$, respectively, then the collection: ><p> $$ \mathcal{D} = \{ B \times C \vert B \in \mathcal{B}, C\in \mathcal{C} \} $$ ></p> >Is a basis for the product topology on $X\times Y$. ### The Subspace Topology **Definition:** Let $X$ be a topological space with topology $\mathcal{T}$. If $Y \subset X$, then the collection: <p> $$ \mathcal{T}_Y = \{ Y \cap U \vert U \in \mathcal{T} \} $$ </p> Is a topology on $Y$, called the **subspace topology**. ##### Lemma >If $\mathcal{B}$ is a basis for a topology on $X$, then we can construct a basis for the subspace topology on $Y$ by taking: ><p> $$ \mathcal{B}_Y = \{ Y \cap B \vert B \in \mathcal{B} \} $$ ></p> Under special conditions, open sets in $Y$ can also be open in $X$: ##### Lemma > Let $Y$ be a subspace of $X$. If $U$ is open in $Y$, and $Y$ is open in $X$, then $U$ is open in $X$. Since $U$ is open in $Y$, $U = Y \cap V$ for some open set $V \in X$. But $Y$ is open, so that means the intersection $Y \cap V$ is open as well. We can connect the subspace topology and the product topology in the way you might expect: ##### Theorem > Let $A \subset X, B \subset Y$. Suppose we take the product topology on $X \times Y$, and use this to construct the subspace topology on $A \times B$. Then this is exactly the product topology of $A\times B$. In other words, this theorem tells us that the subspace of a product is indeed the product of subspaces, considered as topologies. Indeed the bases of both constructions are exactly the same. ## Closed Sets, Interior, Closure, Boundary **Definition:** A subset $A \subset X$ is called **closed** if its complement $X - A$ is open. For example, $\emptyset, X$ are both closed and open, or clopen. Rectangles and circles in the plane with borders are also closed. We have some analogous properties to open sets: ##### Theorem Let $X$ be a topological space. Then the closed sets satisfy: - $\emptyset$ is closed. - $X$ is closed. - Intersections and finite unions of closed sets are closed. The following property guarantees that every singleton set is closed, as is true on the plane with the standard topology. **Definition:** A topological space $X$ is called **Hausdorff** if for every pair fo distinct points $x,y \in X$, there are disjoint neighborhoods $U,V$ of $x$ and $y$ respectively. Examples include: - The real line with the standard topology is Hausdorff. - Any set with the discrete topology is Hausdorff. ##### Theorem > If $X$ is Hausdorff, then every singleton set is closed. Pick an arbitrary element $y\in X - \\{ x \\}$. Since $X$ is Hausdorff, there are open sets $U, V$ containing $x,y$ respectively. So every $y\in X - \\{ x \\}$ is contained in an open set; therefore $X- \\{x \\}$ is open. Finally, we give a criteria for closed sets in the subspace topology. ##### Theorem > Let $Y$ be a subspace in $X$. Then a set $A$ is closed in $Y$ iff it is the intersection of $Y$ and a closed set in $X$. We now define the smallest closed set containing an open set, with the following set of definitions. **Definition:** The interior of $A$ is the union of all open sets containing $A$. Evidently, if $A$ is open, its interior is itself. **Definition:** The closure of $\bar{A}$ is the intersection of all closed sets containing $A$. So we have: <p> $$ \text{Int}(A) \subset A \subset \bar{A} $$ </p> We can define the following equivalent definitions, which are perhaps more useful. ##### Theorem > Let $A$ be a subspace of a topological space $X$, which has a basis $\mathcal{B}$. Then: > - $x \in \bar{A}$ if every open set $U$ in $A$ intersects $A$. > - $x \in \bar{A}$ iff every basis element containing $x$ intersects $A$. ### Limit Points An alternate construction of closed sets comes from the concept of a limit point. **Definition:** $x$ is a **limit point** of $A$ if every neighborhood of $x$ intersects $A$ in some point other than $x$ itself. Equivalently, using our prior theorem, $x \in \overline{A - \\{ x \\}}$ iff it is a limit point. ##### Theorem > A set in a topological space is closed iff it contains all its limit points. ##### Proof We consider $A'$ to be the set of limit points of $A$. We already know that, by definition, $A \cup A' \subset \bar{A}$, since a neighborhood of a limit point intersects $A$. We want to show that indeed the opposite inclusion is true, meaning that $A \cup A' = \bar{A}$. Conversely, we assume that $x\in \bar{A}$. Then, there are two cases. If $x\in A$, then we are done. If $x \notin A$, then by definition, any neighborhood $x$ intersects $A$ in some point other than $x$ itself. Indeed, that means $x \in A'$. Now we can prove our theorem. A set $A$ is closed iff $\bar{A} = A$. But then, we have $A' \subset A$; so all the limit points of $A$ are indeed in $A$. So, a closed set guarantees the existence of limit points. The Hausdorff condition, in a way, guarantees the uniqueness of limit points. ##### Theorem > If $X$ is Hausdorff, then $x$ is a limit point of a set $A$ iff every neighborhood of $x$ contains infinitely many points of $A$. One direction is evident. We seek to prove that if $x$ is a limit point, then any neighborhood contains infinitely many points. Suppose to the contrary that a neighborhood intersects $A$ in finitely many points; then we can successively subtract these points from $X$ and maintain open sets, since any finite set of points is closed. We are left with a neighborhood of $x$ which intersects $A$ in only $x$. ##### Corollary > If $X$ is Hausdorff, then a sequence of points converges to at most one point in $X$. This follows from the above fact that a neighborhood of a limit point in a Hausdorff space indeed contains infinitely many points of the sequence. Suppose that we have two distinct limit points. Then they have two distinct neighborhoods. One neighborhood contains all points of the sequence except finitely many; so the other neighborhood cannot have infinitely many points. **Definition:** A boundary point is in both $\bar{A}$ and $\overline{X-A}$.
Java
UTF-8
4,241
1.84375
2
[ "Apache-2.0" ]
permissive
package com.feng.project.sales.quote.controller; import com.feng.common.utils.DateUtils; import com.feng.common.utils.security.ShiroUtils; import com.feng.framework.aspectj.lang.annotation.Log; import com.feng.framework.web.controller.BaseController; import com.feng.framework.web.domain.JSON; import com.feng.framework.web.page.TableDataInfo; import com.feng.project.sales.customer.dao.ICustomerDao; import com.feng.project.sales.customer.domain.Customer; import com.feng.project.sales.quote.domain.Quote; import com.feng.project.sales.quote.domain.QuoteBody; import com.feng.project.sales.quote.service.IQuoteBodyService; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import com.feng.project.sales.quote.service.IQuoteService; import java.util.List; @Controller @RequestMapping("/sales/quote") public class QuoteController extends BaseController { private String prefix = "/sales/quote"; @Autowired private IQuoteService quoteService; @Autowired private IQuoteBodyService quoteBodyService; // @Autowired // private ICustomerDao customerDao; @RequiresPermissions("sales:quote:view") @GetMapping() public String quote(){ if(ShiroUtils.ROLE_KEY == null) { String result = quoteService.initRole(); if (result == null) return "error"; } return prefix +"/quote"; } /** * get quote list * @param quote * @return */ @RequiresPermissions("sales:quote:list") @GetMapping("/list") @ResponseBody public TableDataInfo list(Quote quote) { setPageInfo(quote); List<Quote> list = quoteService.selectQuoteList(quote); return getDataTable(list); } /** * * @param model * @return */ @RequiresPermissions("sales:quote:add") @GetMapping("/add") public String add(Model model) { String date_today = DateUtils.dateTimeStr().substring(0,10); model.addAttribute("today", date_today); return prefix + "/add"; } @Log(title = "sale Management", action = "Quote Management - save Quote") @RequiresPermissions("sales:quote:save") @PostMapping("/save") @ResponseBody public JSON save(Quote quote) { int rows = quoteService.insertQuote(quote); if( rows>0){ return JSON.ok(); } if(rows<0){ return JSON.error("Item code not exist!"); } return JSON.error(); } @Log(title = "Sales Management", action = "Quote - remove Quote") @RequiresPermissions("sales:quote:remove") @RequestMapping("/remove/{quoteBodyId}/{quoteId}") @ResponseBody public JSON remove(@PathVariable("quoteBodyId") Long quoteBodyId,@PathVariable("quoteId") Long quoteId ){ if ( quoteBodyService.deleteQuoteBodyById(quoteBodyId, quoteId) > 0) { return JSON.ok(); } return JSON.error(); } @RequiresPermissions("sales:quote:batchRemove") @Log(title = "Sales Management", action = "Quote - batchRemoveQuote") @PostMapping("/batchRemove") @ResponseBody public JSON batchRemove(@RequestParam("quoteBodyId[]")Long[] quoteBodyId,@RequestParam("quoteId[]")Long[] quoteId){ int rows = quoteBodyService.batchDeleteQuote(quoteBodyId,quoteId); if(rows>0){ return JSON.ok(); } return JSON.error(); } @Log(title = "Sales Management", action = "Quote - edit") @RequiresPermissions("sales:quote:edit") @GetMapping("/edit/{quoteId}") public String edit(@PathVariable("quoteId") Long quoteId, Model model) { Quote quote = quoteService.selectQuoteById(quoteId); List<QuoteBody> quoteBodies= quoteBodyService.selectBodyByQuoteId(quoteId); for (int i=0;i<quoteBodies.size();i++) model.addAttribute("quoteBodies", quoteBodies); model.addAttribute("quote", quote); return prefix + "/edit"; } }
C++
UTF-8
2,042
2.625
3
[]
no_license
// hw511_CInstrument.cpp #ifndef HW511_CINSTRUMENT_H_ #include "hw511_CInstrument.h" #endif // additional constructor CInstrument::CInstrument(uint32_t beginTm, uint32_t endTm, int noteOffset, int chan, int patch, int vol, int pan, int startNote, int measNum) : CMidiTrack(beginTm, endTm, noteOffset, chan, patch, vol, pan), start_note{startNote}, meas_num{measNum} { } // This is a pure virtual function in CInstrument and we need to implement it // here. This CInstrument function does not implement write_one_measure() and // instead calls the functions implemented in sax, piano, and bass CInstrument // subclasses. void CInstrument::write_track() { vtrk.clear(); push_patch(0, get_channel(), get_patch()); push_volume(0, get_channel(), get_volume()); push_pan(0, get_channel(), get_pan()); // Calls write_one_measure(), however because it is a pure virtual function // it will be implemented in each of the Sax, Piano, and Bass subclasses // according to the needs of that subclass for (int ix = 0; ix < kTOTAL_MEASURES; ++ix) write_one_measure(ix, get_channel()); } // changes the note offset based on which measure // of the blues form is being written // measure numbers are zero based; measure 1 == 0, measure 12 == 11 // Return the scale note offset for meas_num // A 12 bar blues with 4 repeats means you have to account for measures 13-48 int CInstrument::get_note_offset(int meas, int note_offset) { uint16_t offset; switch (meas % 12) { case 0: case 1: case 2: case 3: case 6: case 7: case 10: offset = note_offset; break; case 4: case 5: case 9: offset = note_offset + 5; break; case 8: offset = note_offset + 7; break; case 11: offset = note_offset - 5; break; default: offset = note_offset; break; } return offset; } // returns the timestamp at the start of the measure // measure numbers are zero based // there are 4 beats in a measure, each beat == 1000ms uint32_t CInstrument::get_measure_start_time(int meas) { return meas * 4000; }
C
UTF-8
2,374
3.703125
4
[ "MIT" ]
permissive
#include <stdlib.h> #include <stdio.h> #include "list.h" node* newNode(int value) { node* elem = (node*) malloc(sizeof(node)); elem->next = NULL; elem->data = value; return elem; } node* initialize(node* list, int n) { while(n) { node* elem = newNode(n); elem->next = list; list = elem; --n; } return list; } void print(node* list) { if(NULL == list) { printf("\nList is empty\n\n"); return; } while(NULL != list) { printf("%p:%d%s", list, list->data, (NULL == list->next) ? " -> NULL \n" : " -> "); list = list->next; } } node* reverse(node* list) { node* prev = NULL; node* next = NULL; while(NULL != list) { next = list->next; list->next = prev; prev = list; list = next; } return prev; } node* reverseN(node* list, int n) { if(n < 2 || NULL == list) { return list; } node* prevTail = NULL; node* tail = NULL; node* head = NULL; node* firstHead = NULL; node* prev = NULL; node* next = NULL; int i = 1; int isFirstHead = 1; for(; NULL != list; ++i) { if(1 == i) { prevTail = tail; tail = list; prev = list; list = list->next; } else { if(i == n) { if(isFirstHead) { firstHead = list; isFirstHead = 0; } head = list; if(NULL != prevTail) { prevTail->next = head; } i = 0; } next = list->next; list->next = prev; prev = list; list = next; } } if(i != 1) { if(NULL == prevTail) { firstHead = prev; } else { prevTail->next = prev; } } tail->next = NULL; return firstHead; } node* shuffle(node* list) { return shuffleN(list, 2); } node* shuffleN(node* list, int n) { if(n < 2 || NULL == list) { return list; } node** heads = (node**) malloc(sizeof(node) * n); node** tails = (node**) malloc(sizeof(node) * n); int i = 0; int isHead = 1; for(; NULL != list; list = list->next, ++i) { if(isHead) { *(heads + i) = list; *(tails + i) = list; if(i == n - 1) { isHead = 0; } continue; } if(i == n) { i = 0; } (*(tails + i))->next = list; *(tails + i) = list; } for(i = 0; i < n - 1; ++i) { (*(tails + i))->next = *(heads + i + 1); } (*(tails + n - 1))->next = NULL; return *heads; }
Java
UTF-8
1,417
2.53125
3
[]
no_license
package com.example.movieapplication.session; import android.text.TextUtils; import com.google.gson.Gson; import java.util.Map; public class SharedPreferences { protected android.content.SharedPreferences sharedPreferences; public SharedPreferences(android.content.SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } protected String putObject(String key, Object object) { String json = objectToJson(object); putObjectInSharedPreferences(key, json); return json; } private String objectToJson(Object object) { return new Gson().toJson(object); } private void putObjectInSharedPreferences(String key, String jsonObject) { android.content.SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(key, jsonObject); editor.apply(); } protected Map<String, ?> getAll(){ return sharedPreferences.getAll(); } protected <T> T getObject(String key, Class targetClass) { String jsonObject = sharedPreferences.getString(key, ""); if (TextUtils.isEmpty(jsonObject)) { return null; } return (T) new Gson().fromJson(jsonObject, targetClass); } public void clear() { android.content.SharedPreferences.Editor editor = sharedPreferences.edit().clear(); editor.apply(); } }
TypeScript
UTF-8
1,204
2.96875
3
[ "MIT" ]
permissive
import { DviCommand, merge } from '../parser'; import { Machine } from '../machine'; class Papersize extends DviCommand { width: number; height: number; constructor(width : number, height : number) { super({}); this.width = width; this.height = height; } execute(machine : Machine) { machine.setPapersize( this.width, this.height ); } toString() : string { return `Papersize { width: ${this.width}, height: ${this.height} }`; } } export default function*(commands) { for (const command of commands) { if (! command.special) { yield command; } else { if (! command.x.startsWith('papersize=')) { yield command; } else { let sizes = command.x.replace(/^papersize=/, '').split(','); if (sizes.length != 2) throw Error('Papersize special requires two arguments.'); if (! sizes[0].endsWith('pt')) throw Error('Papersize special width must be in points.'); if (! sizes[1].endsWith('pt')) throw Error('Papersize special height must be in points.'); let width = parseFloat(sizes[0].replace(/pt$/,'')); let height = parseFloat(sizes[1].replace(/pt$/,'')); yield new Papersize(width, height); } } } }
Markdown
UTF-8
3,933
2.78125
3
[ "MIT", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
dOmega Library ===================================== This code implements an efficient algorithm for the maximum clique problem that runs in time polynomial in the graph's size, but exponential in the clique-core gap g:=(d+1)-omega (where d denotes the graph's degeneracy and omega the size of the largest clique). When this gap $g$ can be treated as a constant, as is often the case for real-life graphs, the proposed algorithm runs in time $O(dm)=O(m^{1.5})$. Key subroutines in our approach include existing kernelization and fixed-parameter tractable algorithms for vertex cover. Please cite the following paper if used: Jose L. Walteros and Austin L. Buchanan. Why is maximum clique often easy in practice? The code implements the following modules: * **Degeneracy:** Given a simple undirected graph G, the code outputs the graph's degeneracy an a valid degeneracy ordering. * **Maximum clique:** Given a simple undirected graph G, the code finds the size of the largest clique. The code includes two implementations of the algorithm (LS and BS(. The main difference between both implementations is the way in which the algorithm performs the search (see Jose L. Walteros and Austin L. Buchanan. Why is maximum clique often easy in practice? for further details). Usage --------- ### Compiling the code The library provides a simple makefile to compile the library. The library has been tested on Linux (Ubuntu and CentOS), macOS X (Mavericks-Sierra), and Windows (Cygwin and VS) * **For the LS version:** $ cd path/dOmega/LS $ make * **For the BS version:** $ cd path/dOmega/BS $ make ### Input file format The code can receive as input adjacency lists and edge list files. See the dat folder for a few examples: * **Adjacency lists** The first line of the file must include the number vertices and edges. The vertices must be labeled from 1 to n. %% Adjacency lists of a 6-vertex, 6-edge graph 6 6 2 3 4 1 3 5 1 2 6 1 2 3 * **Edge list** The first line of the file must include the number vertices and edges. The vertices must be labeled from 0 to n-1. %% Edge list of a 6-vertex, 6-edge graph 6 6 0 1 0 2 0 3 1 2 1 4 2 5 ### Running the code * **Degeneracy*** To find the degeneracy ordering of a graph use: ./dOmega [file type] [filename] -d # Finds the degeneracy ordering of the graph described by edge list file testEdge.txt ./dOmega -e ../dat/testEdge.txt -d # Finds the degeneracy ordering of the graph described by adjacency list file testAdj.txt ./dOmega -a ../dat/testAdj.txt -d * **Maximum Clique*** To find the size of the maximum clique of a graph use: ./dOmega [file type] [filename] -m [optional: num. processors to use] # Finds the size of the maximum clique of the graph described by # edge list file testEdge.txt 3 processors ./dOmega -e ../dat/testEdge.txt -m 3 Terms and conditions -------------------- Please feel free to use these codes. We only ask that you cite: Jose L. Walteros and Austin L. Buchanan. Why is maximum clique often easy in practice? _This library was implemented for academic purposes. You may use the library with no limitation for academic, commercial, and/or leisure applications without the need an explicit permission, other than the one granted by the MIT type license included in the library. We kindly ask you to aknowledge the library by citing the above paper in any publication that uses this resources._ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Copyright (C) 2017 Jose L. Walteros. All rights reserved.
Swift
UTF-8
1,512
3.546875
4
[]
no_license
// // QuizModel.swift // Quiz Fun // // Created by Gina Sprint on 9/20/18. // Copyright © 2018 Gina Sprint. All rights reserved. // import Foundation struct QuizModel { // use parallel arrays for our questions and their answers private let questions: [String] private let answers: [String] private var currentQuestionIndex: Int init() { questions = ["What is our mascot?", "Where is GU?", "What room are we in?"] answers = ["Spike", "Spokane", "223"] currentQuestionIndex = -1 } // MARK: - Access Modifiers // control access to state and behavior // internal: accessible anywhere in this app or framework // private: only accessible within this object // private(set): accessible (view only) anywhere in the app or framework but only writable within this object // fileprivate: accessible only within this source file // public: used by frameworks // open: used by frameworks // API: application programming interface // expose limited state and functionality // "encapsulate" things that the outside world shouldn't see mutating func getNextQuestion() -> String { currentQuestionIndex += 1 // what if now currentQuestionIndex is beyond the last valid index of questions and answers? currentQuestionIndex %= questions.count return questions[currentQuestionIndex] } func getCurrentAnswer() -> String { return answers[currentQuestionIndex] } }
SQL
UTF-8
522
2.90625
3
[]
no_license
-- golang_dbという名前のデータベースを作成 CREATE DATABASE golang_db; -- golang_dbをアクティブ use golang_db; -- usersテーブルを作成。名前とパスワード CREATE TABLE users ( id INT(11) AUTO_INCREMENT NOT NULL, name VARCHAR(64) NOT NULL, password CHAR(30) NOT NULL, PRIMARY KEY (id) ); -- usersテーブルに2つレコードを追加 INSERT INTO users (name, password) VALUES ("gophar", "5555"); INSERT INTO users (name, password) VALUES ("octcat", "0000");
Python
UTF-8
7,628
2.921875
3
[]
no_license
from collections import Counter import numpy as np trainingDataFilePath = 'training-100000.txt' modelFilePath = 'model-10000000.model' testDataFilePath = 'test_1000.txt' resultFilePath = '2016081111_侯海洋.result' ''' function:cut the string parameter: 1.string:the input string return: 1.type:list,mean:a list include the cutted string ''' def extractFeatures(string): return string.split(' ') ''' function:save the model parameter: 1.goodModel:the good model dict,form is word-count like key-value 2.badModel:the bad model dict,form is word-count like key-value 3.goodCount:the good words' number,include the repeat words 4.badCount:the bad words' number,include the repeat words 5.V:the number of words,no repeat return: 1.type:bool,mean:save model success or fail ''' def saveModel(goodModel, badModel, goodCount, badCount, V): try: global modelFilePath with open(modelFilePath, 'w', encoding='UTF-8-sig') as f: for key, value in goodModel.items(): line = '好评_%s\t%s\r\n' % (key, value) f.write(line) for key, value in badModel.items(): line = '差评_%s\t%s\r\n' % (key, value) f.write(line) line = '好评\t%s\r\n差评\t%s\r\nV\t%s' % (goodCount, badCount, V) f.write(line) f.close() return True except: return False ''' function:load the model parameter:None return:list,mean:the model,include good words model,bad words model,goodCount,badCount and V ''' def loadModel(): try: model, goodModel, badModel, count = {}, {}, {}, {} words = set() global modelFilePath with open(modelFilePath, "r", encoding='UTF-8-sig') as f: for line in f: line = line.replace('\r\n', '') if line[0:3] == '好评_': goodModel[line.split('\t')[0].split( '_')[1]] = float(line.split('\t')[1]) words.add(line.split('\t')[0].split('_')[1]) elif line[0:3] == '差评_': badModel[line.split('\t')[0].split( '_')[1]] = float(line.split('\t')[1]) words.add(line.split('\t')[0].split('_')[1]) elif line[0:2] == '好评': count['goodCount'] = float(line.split('\t')[1]) elif line[0:2] == '差评': count['badCount'] = float(line.split('\t')[1]) count['V'] = len(words) print(count['goodCount'] + count['badCount']) model['goodModel'] = goodModel model['badModel'] = badModel model['count'] = count print('load model success') f.close() return model except: print('load model fail') ''' function:read all the lines of test data parameter:None return:list,mean:the test data list,it's item is a string ''' def readAllLines(): test = [] global testDataFilePath with open(testDataFilePath, 'r', encoding='UTF-8-sig') as f: line = f.readline().replace('\n', '') while line: test.append(line) line = f.readline().replace('\n', '') return test ''' function:save the predict result parameter: 1.result:the predict result return:bool ''' def saveResult(result): global resultFilePath try: with open(resultFilePath, 'w') as f: for item in result: f.write(item + '\n') return True except: return False ''' function:train the model parameter:None return:None ''' def train(): # mapper goodWords, badWords = [], [] global trainingDataFilePath with open(trainingDataFilePath, 'r', encoding='UTF-8-sig') as f: for line in f: line = line.replace('\n', '') if line[0:2] == '好评': goodWords.extend(line[2:].strip('\t').split(' ')) else: badWords.extend(line[2:].strip('\t').split(' ')) # reducer goodModel = dict(Counter(goodWords)) badModel = dict(Counter(badWords)) V = len(set(goodWords + badWords)) print(V) goodCount, badCount = len(goodWords), len(badWords) # save model if saveModel(goodModel, badModel, goodCount, badCount, V): print('store model success') else: print('store model fail') ''' function:predict one parameter: 1.comment:one comment 2.model:the model return:string,mean:'好评' or '差评' ''' def predict(comment, model): if model: comment = extractFeatures(comment) V = model['count']['V'] print(V) # print(V, model['count']['goodCount'], model['count']['badCount']) p_good_before = np.log(model['count'][ 'goodCount'] / (model['count']['goodCount'] + model['count']['badCount'])) p_bad_before = np.log(model['count'][ 'badCount'] / (model['count']['goodCount'] + model['count']['badCount'])) p_good_word, p_bad_word = 0, 0 for word in comment: if word in model['goodModel'].keys(): p_good_word += np.log((model['goodModel'][word] + 1.0) / (model['count']['goodCount'] + V)) else: p_good_word += np.log(1.0 / (model['count']['goodCount'] + V)) if word in model['badModel'].keys(): p_bad_word += np.log((model['badModel'][word] + 1.0) / (model['count']['badCount'] + V)) else: p_bad_word += np.log(1.0 / (model['count']['badCount'] + V)) p_good_after = p_good_before + p_good_word p_bad_after = p_bad_before + p_bad_word if p_good_after > p_bad_after: return '好评' else: return '差评' ''' function:predict all parameter:model return:None ''' def predictAll(model): result = [] accuracy, amount = 0, 0 test = readAllLines() for line in test: gold = line[0:2] prediction = predict(line[2:].strip('\t').strip('\n'), model) # print((amount + 1), # 'Gold={0}\tPrediction={1}'.format(gold, prediction)) if gold == prediction: accuracy += 1 print(amount + 1, 'Gold={0}\tPrediction={1}'.format(gold, prediction)) amount += 1 result.append(prediction) print("Accuracy = {0}%".format(str(round((accuracy / amount) * 100, 5)))) print('正确=', accuracy, '错误=', amount) result.append("Accuracy = {0}%".format( str(round((accuracy / amount) * 100, 5)))) if saveResult(result): print("save result success") else: print("save result fail") ''' function:main function parameter:None return:None ''' def main(): # train() model = loadModel() if model: # print(model['count']['V']) # print(model) # comment = '几乎 凌晨 才 到 包头 包头 没有 什么 特别 好 酒店 每次 来 就是 住 这家 所以 没有 忒 多 对比 感觉 行 下次 还是 得到 这里 来 住' # print(predict(comment, model)) predictAll(model) else: print('load model fail') if __name__ == '__main__': main()
Ruby
UTF-8
722
2.671875
3
[]
no_license
class WeatherAPI require 'Unirest' # def new # WeatherAPI.new[:location] # end def self.get_weather(location) response = Unirest.get "https://george-vustrey-weather.p.mashape.com/api.php?location=#{location}", headers:{ "X-Mashape-Key" => "N4oUSJBSeymsh73eOWuHWwHSyjB7p1UmqkzjsnXCc7UMI3jnzD", "Accept" => "application/json" } location_weather = response.body end def self.get_weather2(location2) response2 = Unirest.get "https://george-vustrey-weather.p.mashape.com/api.php?location=#{location2}", headers:{ "X-Mashape-Key" => "N4oUSJBSeymsh73eOWuHWwHSyjB7p1UmqkzjsnXCc7UMI3jnzD", "Accept" => "application/json" } location2_weather = response2.body end # def show # WeatherAPI.new # end end # WeatherAPI.get_weather
C#
UTF-8
2,960
2.53125
3
[ "MIT" ]
permissive
using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using OniTemplate.Model; using Xunit; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; namespace OniTemplate.Test { public class YamlTests { [Fact] [Trait("Category", "Integration")] public void DeserializeExistingFileTest() { var distinctElements = new List<string>(); var distinctOEids = new List<string>(); var baseDir = @"F:\Steam\steamapps\common\OxygenNotIncluded\OxygenNotIncluded_Data\StreamingAssets\templates\poi"; var yamlFiles = Directory.GetFiles(baseDir); foreach (var filePath in yamlFiles) { var reader = new StreamReader(filePath); var yamlString = reader.ReadToEnd(); var deserializer = new DeserializerBuilder() .WithNamingConvention(new CamelCaseNamingConvention()) .Build(); // assertion provided by no exception var strongGraph = deserializer.Deserialize<Template>(yamlString); foreach (var item in strongGraph.Cells) { if (!distinctElements.Contains(item.Element)) { distinctElements.Add(item.Element); } } foreach (var item in strongGraph.Buildings) { if (!distinctElements.Contains(item.Element)) { distinctElements.Add(item.Element); } } foreach (var item in strongGraph.ElementalOres) { if (!distinctElements.Contains(item.Element)) { distinctElements.Add(item.Element); } } foreach (var item in strongGraph.OtherEntities) { if (!distinctElements.Contains(item.Element)) { distinctElements.Add(item.Element); } if (!distinctOEids.Contains(item.Id)) { distinctOEids.Add(item.Id); } } } var builder = new StringBuilder(); foreach (var element in distinctElements.OrderBy(x=>x)) { builder.AppendLine(element); } File.WriteAllText(@"c:\temp\elements.txt",builder.ToString()); builder = new StringBuilder(); foreach (var element in distinctOEids.OrderBy(x => x)) { builder.AppendLine(element); } File.WriteAllText(@"c:\temp\otherentities.txt", builder.ToString()); } } }
PHP
UTF-8
9,035
2.796875
3
[]
no_license
<?php /** * Simplified JS munger. * * @package munger-silverstripe-module * @author Darren Inwood <darren.inwood@chrometoaster.com> */ class JS_Munger { /** * Default options */ public static $default_options = array( // Header 'client' => false, 'project' => false, 'author' => false, // Blacklist 'blacklist' => false, 'blacklist_min_versions' => array( 'ie' => 6, 'safari' => 3, 'ff' => 3, 'opera' => 9.5, 'netscape' => 8 ), // Cache 'cache' => true, 'cache_dir' => false, // JSmin compression 'jsmin' => true, 'jsmin_opts' => array(), // Combine files 'combine' => false, 'combined_filename' => false // output filename - will invent one if nothing is supplied // note - ignores any directory info, just uses the filename ); /** * Instance options */ public $options; /** * An array of the included files. */ private $files = array( ); public function __construct($options=array()) { $this->options = array_merge(self::$default_options, $options); if ( ! $this->options['cache_dir'] ) { $this->options['cache_dir'] = dirname(__FILE__); } } /** * Enables setting 'Dev mode', where caching, file combining and * minification are disabled regardless of options. */ public function setDev($isDev) { if ( $isDev !== true ) return; $this->options['cache'] = false; $this->options['minify'] = false; $this->options['combine'] = false; } public function addFile($file) { $this->files[] = $file; } public function addFiles($files) { foreach( $files as $file ) { $this->addFile($file); } } public function getMungedFiles() { if ( $this->options['blacklist'] && $this->isBlacklisted() ) { // Blacklisted browsers do not get any javascript. return array(); } $output_files = array(); foreach( $this->files as $file ) { $real_filename = $this->getRealFilename($file); if ( ! $real_filename || ! file_exists($real_filename) ) continue; // File doesn't exist! $cache_filename = $this->options['cache_dir'] . '/' . md5(serialize($this->options)) . str_replace('/', '_', $file); $output_files[] = $cache_filename; if ( $this->options['cache'] && file_exists($cache_filename) && filemtime($cache_filename) > filemtime($real_filename) ) { // File is cached, no need to regenerate continue; } $js = file_get_contents($real_filename); // JSMin if ( $this->options['jsmin'] ) { /* // seems to spit the dummy... require_once( dirname(__FILE__).'/jsmin/JSMinPlus.php' ); $js = JSMinPlus::minify($js); */ require_once( dirname(__FILE__).'/jsmin/jsmin.php' ); $js = JSMin::minify($js); } if ( ! $this->options['combine'] ) { $js = $this->file_header($file) . $js; } // Write cache file file_put_contents($cache_filename, $js); } // If we're not combining, just return the bare files if ( ! $this->options['combine'] ) { return $output_files; } // Combine files $latest_modification_time = false; foreach( $output_files as $file ) { $latest_modification_time = max(filemtime($file), $latest_modification_time); } if ( $this->options['combined_filename'] ) { $cache_filename = $this->options['cache_dir'] . '/' . md5(serialize($this->options)) . '_' . basename($this->options['combined_filename']); } else { $cache_filename = $this->options['cache_dir'] . '/' . 'combined_' . md5(implode('-',$output_files).serialize($this->options)).'.js'; } if ( $this->options['cache'] && file_exists($cache_filename) && filemtime($cache_filename) > $latest_modification_time ) { return array($cache_filename); // This file is cached } // Cache combined file $fh = fopen($cache_filename, 'w'); fwrite($fh, $this->file_header($output_files)); foreach( $output_files as $file ) { fwrite($fh, file_get_contents($file).";\n"); } fclose($fh); return array($cache_filename); } /** * Returns HTML tags for inclusion into your page, outputting the files we * added using addFile() and addFiles(). */ public function toHTML() { $files = $this->getMungedFiles(); $out = ''; foreach( $files as $file ) { if ( strpos($file, $_SERVER['DOCUMENT_ROOT']) !== false ) { $file = str_replace($_SERVER['DOCUMENT_ROOT'], '', $file); } $out .= '<script type="text/javascript" src="'.$file.'"></script>'."\n"; } return $out; } /** * File header * Generate a short file header to supplement the non human-readable filename * Requires preserve_comments to be enabled, else file header will be added but stripped by compressor * * @access private * @return String A header describing the output */ private function file_header($files) { if ( ! is_array($files) ) $files = array($files); $client = $this->options['client']; $project = $this->options['project']; $author = $this->options['author']; $header = ""; $header .= "/*!\n"; $header .= " * Description: JavaScript functions\n"; if ( $client && $project ) { $header .= " * For: $client / $project\n"; } else if ( $client && !$project ) { $header .= " * For: $client\n"; } else if ( !$client && $project ) { $header .= " * For: $project\n"; } if ( $author ) { $header .= " * Author: $author\n"; } $header .= ' * Cache: '.($this->options['cache']?'On':'Off')."\n"; $header .= ' * Minification: '.($this->options['jsmin']?'On':'Off')."\n"; $header .= ' * File Combining: '.($this->options['combine']?'On':'Off')."\n"; if ( count($files) == 0 ) { $header .= ' * No source files specified.'."\n"; } else if ( count($files) == 1 ) { $header .= ' * Source file: '.basename($files[0])."\n"; } else { $header .= ' * Source files:'."\n"; foreach( $files as $file ) { $header .= ' * - '.basename($file)."\n"; } } $header .= " * Generated: ".date('Y-m-d g:i:sa')."\n"; $header .= " */\n\n"; return $header; } /** * DS, 14.03.2011 * Withhold munged assets from C-grade browsers as per Yahoo! graded best practice * This is separate from the sniffing functions, as we need to be able to withhold assets when the optional munger CSS conditionals are not in use. * Reference: http://developer.yahoo.com/yui/articles/gbs/, http://monospaced.co.uk/labs/gbs/ * Note that the C-grade browser list is independent of the versioning system used by Yahoo! for the A-grade browser list. */ private function isBlacklisted() { require_once( dirname(__FILE__).'/useragent/Useragent.php' ); $ua = Useragent::current(); // if the current browser matches any array entries, then it's on the blacklist foreach( $this->options['blacklist_min_versions'] as $browser => $version ) { if ( $ua->browser_short == $browser && (float)$ua->version < (float)$version ) { return true; } } return false; } /** * Converts a relative or absolute URL to a file into a full filesystem path * * @param $filename String The URL to the file to find. Can be relative to * the current request, or absolute to the document root. * @return String A full filesystem path to the file. */ private function getRealFilename($filename) { if ( substr($filename, 0, 1) == '/' ) { // Absolute path return $_SERVER['DOCUMENT_ROOT'] . $filename; } if ( file_exists($_SERVER['DOCUMENT_ROOT'].'/'.dirname($_SERVER['REQUEST_URI']).'/'.$filename) ) { // Relative to current request return $_SERVER['DOCUMENT_ROOT'].'/'.dirname($_SERVER['REQUEST_URI']).'/'.$filename; } return $_SERVER['DOCUMENT_ROOT'] . '/' . $filename; } }
C++
GB18030
3,003
4.0625
4
[]
no_license
#include<iostream> using namespace std; const int MaxSize=100;//Ԫظ class Set{//Set int *data;//żеԪ int n;//Ԫظ public: Set(){//캯 data=new int [MaxSize];//̬ռ n=0; } ~Set(){// delete []data; } bool IsIn(int e){//жeǷڼ int i; for(int i=0;i<n;i++) if(data[i]==e) return true;//dataҵԪetrue return false; //dataûҵefalse } bool Insert(int e){//Ԫe뵽ϵȥ if(IsIn(e)) //ҪeѾڼϵдڣfalseʧ return false; else{//вe±Ϊnλã鳤++true data[n]=e; n++; return true; } } bool Remove(int e){//ԪeӼɾ int i=0,j; while(i<n&&data[i]!=e){//Ҽeڵ± i++; } if(i>=n) return false;//ʧ for(j=i+1;j<n;j++) data[j-1]=data[j];//ɾԪغԪǰƶһλ n--;//ɹɾ鳤-- return true;//true } void display(){//еԪ int i; for(i=0;i<n;i++){ cout<<data[i]<<" "; } cout<<endl; } Set &operator=(Set &s1){//=سԱ int i; for(i=0;i<s1.n;i++){ data[i]=s1.data[i]; } n=s1.n; return *this; } friend Set&operator+(Set &s1,Set &s2){//󲢼 int i; static Set s3; for(i=0;i<s1.n;i++)//s1ԪظƵs3 s3.Insert(s1.data[i]); for(i=0;i<s2.n;i++){//s2s1вڵԪظƵs3 if(!(s1.IsIn(s2.data[i]))) s3.Insert(s2.data[i]); } return s3;//غϲļ } friend Set &operator*(Set &s1,Set &s2){//󽻼 int i; static Set s3; for(i=0;i<s1.n;i++)//s1гs2ԪظƵs3 if(s2.IsIn(s1.data[i])) s3.Insert(s1.data[i]); return s3;//ؽ } friend Set&operator-(Set &s1,Set &s2){// int i; static Set s3; for(int i=0;i<s1.n;i++)//s1s2еԪظƵs3 if(!s2.IsIn(s1.data[i])) s3.Insert(s1.data[i]); return s3;//ز } }; int main(){ Set s1,s2,s3,s4,s5;//Set s1.Insert(1); s1.Insert(2); s1.Insert(4); s1.Insert(6); s1.Insert(8); cout<<"s1:";//s1в 1 2 4 6 8 s1.display();//ӡs1 s2.Insert(2); s2.Insert(3); s2.Insert(5); s2.Insert(6); cout<<"s2:";//s2в2 3 5 6 s2.display();//ӡs2 cout<<"󼯺s1s2IJs3:"<<" "; s3=s1+s2; s3.display(); cout<<"󼯺s1s2Ľs4:"<<" "; s4=s1*s2; s4.display(); cout<<"󼯺s1s2IJs5:"<<" "; s5=s1-s2; s5.display(); return 0; }
SQL
UTF-8
6,306
3.515625
4
[]
no_license
-- MySQL Script generated by MySQL Workbench -- Sun Dec 6 13:44:41 2020 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'; -- ----------------------------------------------------- -- Schema Tech4Kek -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema Tech4Kek -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `Tech4Kek` DEFAULT CHARACTER SET utf8 ; USE `Tech4Kek` ; -- ----------------------------------------------------- -- Table `Tech4Kek`.`Address` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `Tech4Kek`.`Address` ( `addressId` INT NOT NULL AUTO_INCREMENT, `CreatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `UpdatedAt` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `Country` VARCHAR(45) NOT NULL, `Zipcode` VARCHAR(12) NOT NULL, `City` VARCHAR(45) NOT NULL, `Street` VARCHAR(45) NOT NULL, `Number` VARCHAR(10) NOT NULL, PRIMARY KEY (`addressId`)); -- ----------------------------------------------------- -- Table `Tech4Kek`.`Account` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `Tech4Kek`.`Account` ( `accountId` INT NOT NULL AUTO_INCREMENT, `CreatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `UpdatedAt` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `FirstName` VARCHAR(50) NOT NULL, `LastName` VARCHAR(30) NOT NULL, `Email` VARCHAR(255) UNIQUE NOT NULL, `Password` VARCHAR(100) NOT NULL, `Role` INT NOT NULL DEFAULT 0, `addressId` INT NULL, PRIMARY KEY (`accountId`), UNIQUE INDEX `Email_UNIQUE` (`Email` ASC), INDEX `fk_Account_Address1_idx` (`addressId` ASC), CONSTRAINT `fk_Account_Address1` FOREIGN KEY (`addressId`) REFERENCES `Tech4Kek`.`Address` (`addressId`) ON DELETE NO ACTION ON UPDATE NO ACTION); -- ----------------------------------------------------- -- Table `Tech4Kek`.`Orders` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `Tech4Kek`.`Orders` ( `orderId` INT NOT NULL AUTO_INCREMENT, `CreatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `UpdatedAt` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `Status` INT NOT NULL DEFAULT 0, `accountId` INT NOT NULL, `addressId` INT NULL, `FirstName` VARCHAR(50) NULL, `LastName` VARCHAR(30) NULL, PRIMARY KEY (`orderId`), INDEX `fk_Orders_Account1_idx` (`accountId` ASC), INDEX `fk_Orders_Address1_idx` (`addressId` ASC), CONSTRAINT `fk_Orders_Account1` FOREIGN KEY (`accountId`) REFERENCES `Tech4Kek`.`Account` (`accountId`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_Orders_Address1` FOREIGN KEY (`addressId`) REFERENCES `Tech4Kek`.`Address` (`addressId`) ON DELETE NO ACTION ON UPDATE NO ACTION); -- ----------------------------------------------------- -- Table `Tech4Kek`.`Product` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `Tech4Kek`.`Product` ( `productId` INT NOT NULL AUTO_INCREMENT, `CreatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `UpdatedAt` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `ProdName` VARCHAR(100) NOT NULL, `Price` DECIMAL(10,2) NOT NULL, `ProdType` INT NOT NULL, `OnStock` INT NOT NULL, PRIMARY KEY (`productId`), UNIQUE INDEX `ProdName_UNIQUE` (`ProdName` ASC)); -- ----------------------------------------------------- -- Table `Tech4Kek`.`Product_to_Order` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `Tech4Kek`.`Product_to_Order` ( `PtoID` INT NOT NULL AUTO_INCREMENT, `CreatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `UpdatedAt` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `ProductCount` INT NOT NULL, `orderId` INT NOT NULL, `productId` INT NOT NULL, PRIMARY KEY (`PtoID`), INDEX `fk_Product_to_Order_Orders1_idx` (`orderId` ASC), INDEX `fk_Product_to_Order_Product1_idx` (`productId` ASC), CONSTRAINT `fk_Product_to_Order_Orders1` FOREIGN KEY (`orderId`) REFERENCES `Tech4Kek`.`Orders` (`orderId`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_Product_to_Order_Product1` FOREIGN KEY (`productId`) REFERENCES `Tech4Kek`.`Product` (`productId`) ON DELETE NO ACTION ON UPDATE NO ACTION); -- ----------------------------------------------------- -- Table `Tech4Kek`.`Property` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `Tech4Kek`.`Property` ( `propertyId` INT NOT NULL AUTO_INCREMENT, `CreatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `UpdatedAt` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `Type` VARCHAR(45) NOT NULL, `Name` VARCHAR(45) NOT NULL, `Value` VARCHAR(60) NOT NULL, PRIMARY KEY (`propertyId`)); -- ----------------------------------------------------- -- Table `Tech4Kek`.`Product_has_Property` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `Tech4Kek`.`Product_has_Property` ( `PhpID` INT NOT NULL AUTO_INCREMENT, `CreatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `UpdatedAt` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `productId` INT NOT NULL, `propertyId` INT NOT NULL, PRIMARY KEY (`PhpID`), INDEX `fk_Product_has_Property_Product1_idx` (`productId` ASC), INDEX `fk_Product_has_Property_Property1_idx` (`propertyId` ASC), CONSTRAINT `fk_Product_has_Property_Product1` FOREIGN KEY (`productId`) REFERENCES `Tech4Kek`.`Product` (`productId`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_Product_has_Property_Property1` FOREIGN KEY (`propertyId`) REFERENCES `Tech4Kek`.`Property` (`propertyId`) ON DELETE NO ACTION ON UPDATE NO ACTION); SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
SQL
UHC
9,623
4.25
4
[]
no_license
[92] last_name߿ B, M, A ۵Ǵ ϼ. select * from employees where last_name like 'B%' or last_name like 'M%' or last_name like 'A%'; select * from employees where instr(last_name,'B') = 1 or instr(last_name,'M') = 1 or instr(last_name,'A') = 1; select * from employees where substr(last_name,1,1) in ('B','M','A'); [93] first_name 'Steven','Stephen' ϼ. select * from employees where first_name in ('Steven','Stephen'); [94] job_id߿ _MAN, _MGR ڰ ִ ϼ. select * from employees where job_id like '%_MAN' or job_id like '%_MGR'; select * from employees where job_id like '%\_MAN' escape '\' or job_id like '%\_MGR' escape '\'; [95] ĺ ҹ ʰ ġ ֵ o ִ last_name ϼ. select last_name from employees where instr(last_name,'o')>0 or instr(last_name,'O')>0; [96] ӵǴ oִ last_name ˻ ִ last_name ϼ. -- ÷ (Ǵ ҹ) ٲ index ĵ (substr, instr εĵ ) select last_name from employees where last_name like '%oo%' or last_name like '%OO%' or last_name like '%Oo%' or last_name like '%oO%'; select last_name, instr(last_name,'o'), instr(last_name,'o',1,2) from employees where instr(last_name,'o',1,2)-instr(last_name,'o') = 1; ================================================================================ Oracle Regular Expression(ǥ) -- regexp_like(index scan ) : ڰ˻ Լ [92] last_name߿ B, M, A ۵Ǵ ϼ. select * from employees where regexp_like(last_name,'^(B|M|A)'); /* Ÿ ^ : , ^(A) A ۵Ǵ ã | : or */ [93] first_name 'Steven','Stephen' ϼ. select * from employees where regexp_like(first_name, '^Ste(v|ph)en$'); /* ^Ste : Ste (v|ph) : v or ph ( κ) en$ : en */ [94] job_id߿ _MAN, _MGR ڰ ִ ϼ. select * from employees where regexp_like(job_id, '(_m(an|gr))','i'); /* i : ҹ ʰ ˻ c : Է ˻(⺻) */ select * from employees where regexp_like(job_id, '[a-z]{2}_m[an|gr]','i'); /* [a-z]{2} : a ~ z 2ڸ */ [95] ĺ ҹ ʰ ġ ֵ o ִ last_name ϼ. select * from employees where regexp_like(last_name, '(o)', 'i'); [96] ӵǴ oִ last_name ˻ ִ last_name ϼ. select * from employees where regexp_like(last_name, '(oo)', 'i'); select * from employees where regexp_like(last_name, '(o)\1', 'i'); /* \1 : , (o)\1 = (oo) */ -------------------------------------------------------------------------------- create table cust(name varchar2(30)); insert into cust(name) values('oracle'); insert into cust(name) values('ORACLE'); insert into cust(name) values('Ŭ'); insert into cust(name) values('0racle'); insert into cust(name) values(''); insert into cust(name) values('׳'); insert into cust(name) values('볪'); insert into cust(name) values('racle'); insert into cust(name) values('5racle'); commit; select * from cust; ĺ ҹ ʰ ̸ ˻ select * from cust where regexp_like(name, '^[a-z]','i'); /* [a-z] : a ~ z */ ĺ ҹ ؼ ̸ ˻ select * from cust where regexp_like(name, '^[A-Z]','c'); /* [A-Z] : A ~ Z */ ڷ ۴ ̸ ˻ select * from cust where regexp_like(name, '^[0-9]'); /* [0-9] : 0 ~ 9 */ ѱ ִ ̸ ˻ select * from cust where regexp_like(name, '^[-]','i'); /* [-] : ~ */ select * from cust where regexp_like(name, '^(||)$'); -------------------------------------------------------------------------------- select postal_code from locations; /* 빮 ˻*/ select postal_code from locations where regexp_like(postal_code,'[[:upper:]]'); /* ҹ ˻ */ select postal_code from locations where regexp_like(postal_code,'[[:lower:]]'); /* ˻ */ select postal_code from locations where regexp_like(postal_code,'[[:digit:]]'); /*  ˻*/ select postal_code from locations where regexp_like(postal_code,'[[:blank:]]'); select postal_code from locations where regexp_like(postal_code,'[[:space:]]'); /* Ư ˻ */ select street_address from locations where regexp_like(street_address,'[[:punct:]]'); ================================================================================ [97] ̺ phone_number ȭ ȣ ˻(35 ) < ȭ > 011.44.1344.429268 select phone_number from employees; select phone_number from employees where regexp_like(phone_number, '[0-9]{3}.(4)\1.[0-9]{4}.[0-9]{6}'); select phone_number from employees where regexp_like(phone_number, '\d{3}.\d{2}.\d{4}.\d{6}'); select phone_number from employees where regexp_like(phone_number, '^\d{3}.\d{3,4}.\d{4}$'); [98] locations ̺ postal_code ڷ ϼ. select postal_code from locations; select * from locations where regexp_like(postal_code, '[a-z]$','i'); ================================================================================ -- regexp_substr select REGEXP_SUBSTR('abc@dream.com', '[^@]+',1,1) from dual; /* [^ : not ǹ + : ù° (abc), ǥ ϸ ùڸ */ SELECT REGEXP_INSTR ('0123456789', '(123)(4(56)(78))', 1, 1, 0, 'i', 1) "Position" FROM dual; /* (123)(4(56)(78)) : 123, 45678, 56, 78() / 4 1 ù° (123) '0123456789' ? (1, n, 0,... : ó n° (0 ǹ̾) ..., n) : n° Ͻ ãƶ */ select regexp_instr('78123456789', '(4(56)(78))', 1, 1, 0, 'i', 3) "position" from dual; /* 9 */ select regexp_instr('45678123456789', '(4(56)(78))', 1, 1, 0, 'i', 3) "position" from dual; /* 4 */ select regexp_instr('45678456789', '(4(56)(78))', 1, 2, 0, 'i', 3) "position" from dual; /* 9 */ /* DNA */ SELECT REGEXP_INSTR('ccacctttccctccactcctcacgttctcacctgtaaagcgtccctc cctcatccccatgcccccttaccctgcagggtagagtaggctagaaaccagagagctccaagc tccatctgtggagaggtgccatccttgggctgcagagagaggagaatttgccccaaagctgcc tgcagagcttcaccacccttagtctcacaaagccttgagttcatagcatttcttgagttttca ccctgcccagcaggacactgcagcacccaaagggcttcccaggagtagggttgccctcaagag gctcttgggtctgatggccacatcctggaattgttttcaagttgatggtcacagccctgaggc atgtaggggcgtggggatgcgctctgctctgctctcctctcctgaacccctgaaccctctggc taccccagagcacttagagccag', '(gtc(tcac)(aaag))', 1, 1, 0, 'i',1) "Position" FROM dual; SELECT REGEXP_COUNT( 'ccacctttccctccactcctcacgttctcacctgtaaagcgtccctccctcatccccatgcccccttaccctgcag ggtagagtaggctagaaaccagagagctccaagctccatctgtggagaggtgccatccttgggctgcagagagaggag aatttgccccaaagctgcctgcagagcttcaccacccttagtctcacaaagccttgagttcatagcatttcttgagtt ttcaccctgcccagcaggacactgcagcacccaaagggcttcccaggagtagggttgccctcaagaggctcttgggtc tgatggccacatcctggaattgttttcaagttgatggtcacagccctgaggcatgtaggggcgtggggatgcgctctg ctctgctctcctctcctgaacccctgaaccctctggctaccccagagcacttagagccag', 'gtc') AS Count FROM dual; /* 'gtc' ڰ */ [] phone_number ù° . , տ ִ ڴ? select phone_number from employees; select regexp_substr(phone_number, '[^.]+', 1, 1) f_num, count(*) cnt from employees group by regexp_substr(phone_number, '[^.]+', 1, 1); ================================================================================ [99] '010-1234-5678', '010-123-5678' ȣ չȣ 010 ߰ȣ 1234 ȣ 5678 иؼ ϼ.( substr ̿) select substr('010-1234-5678', 1, 3) f_num, substr('010-1234-5678', 5, 4) m_num, substr('010-1234-5678', 10, 4) l_num, substr('010-123-5678', 1, 3) f_num, substr('010-123-5678', 5, 3) m_num, substr('010-123-5678', 10, 4) l_num from dual; select substr('010-1234-5678', 1, instr('010-1234-5678','-')-1) f_num, substr('010-1234-5678', instr('010-1234-5678','-')+1, instr('010-1234-5678','-',1,2)-instr('010-1234-5678','-')-1) m_num, substr('010-1234-5678', instr('010-1234-5678','-',1,2)+1) l_num from dual; select substr('010-123-5678', 1, instr('010-123-5678','-')-1) f_num, substr('010-123-5678', instr('010-123-5678','-')+1, instr('010-123-5678','-',1,2)-instr('010-123-5678','-')-1) m_num, substr('010-123-5678', instr('010-123-5678','-',1,2)+1) l_num from dual; [100] '010-1234-5678' ȣ չȣ 010 ߰ȣ 1234 ȣ 5678 иؼ ϼ.( regexp_substr ̿) select regexp_substr('010-1234-5678', '[^-]+', 1, 1) f_num, regexp_substr('010-1234-5678', '[^-]+', 1, 2) m_num, regexp_substr('010-1234-5678', '[^-]+', 1, 3) l_num from dual; ================================================================================ -- Ʃ /* ocp Ŭ (Ͼ) ̼ / ʿ ( ó縦 ) */
Java
UTF-8
1,459
2.25
2
[]
no_license
package online.ors.oldraddisold.activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import java.util.Locale; /** * Activity for reaching out to ORS */ @SuppressWarnings("ConstantConditions") public class ContactUsActivity extends ORSActivity implements View.OnClickListener { /** * Recover Habitat Geo location constance */ private static final double ORS_LATITUDE = 13.0206016; private static final double ORS_LONGITUDE = 77.6566887; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(online.ors.oldraddisold.R.layout.activity_contact_us); Toolbar toolbar = (Toolbar) findViewById(online.ors.oldraddisold.R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeAsUpIndicator(online.ors.oldraddisold.R.drawable.ic_back_white_18dp); findViewById(online.ors.oldraddisold.R.id.tv_address).setOnClickListener(this); } @Override public void onClick(View v) { // open google map to show the Recover Habitat premises location String uri = String.format( Locale.ENGLISH, "geo:%f,%f?q=%f,%f(Recover Habitat)", ORS_LATITUDE, ORS_LONGITUDE, ORS_LATITUDE, ORS_LONGITUDE ); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); startActivity(intent); } }
Python
UTF-8
266
3.125
3
[]
no_license
# 5/10/2020 # Select the first 1000 respondents brfss = brfss[:1000] # Extract age and weight age = brfss['AGE'] weight = brfss['WTKG3'] # Make a scatter plot plt.plot(age, weight,'o', alpha = 0.1) plt.xlabel('Age in years') plt.ylabel('Weight in kg') plt.show()
Markdown
UTF-8
1,656
3
3
[ "MIT" ]
permissive
# Responsive Storefront ### Question Using HTML, CSS and the supplied media, recreate the screens below in a responsive manner. * The storefront consists of three main screens: a category list page, a product details page, and a cart page. * None of the pages require any behaviour; they are completely static. * You are free to create 3 separate static HTML files, or to use any tools/methods you deem appropriate to reduce code duplication. * You are free to use whatever frameworks you deem appropriate, but you should justify your choice in the application's README. * You are free to use any CSS pre/post processors, build tools or methodologies (SASS, LESS, Autoprefixer, PostCSS). * You are free to nominate the breakpoint at which the page transitions from mobile to desktop layouts. Please justify your choices for each breakpoint in your code comments. * Your assignment will be judged on structure, clarity of code, reusability and extensibility, accessibility, etc. ### Sample Screens #### Category List page: ![](./screens/desktop/category-page.png) ![](./screens/mobile/category-page.png) #### Product details page: ![](./screens/desktop/product-details.png) ![](./screens/mobile/product-details.png) #### Cart page: ![](./screens/desktop/cart.png) ![](./screens/mobile/cart.png) ### Candidate Notes You should * Submit your assignment as a Git repository hosted on either GitHub or BitBucket. * Take the full window of time; there are no bonuses for early submission. * Include a README explaining how to install dependencies (if any) and build your site. * Explain any compromises/shortcuts you made due to time considerations.
Java
UTF-8
2,873
3.328125
3
[]
no_license
/** * Tests for Library assignment. * Submitted By * Ying Chen * Chaitali Gondhalekar */ package library; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * @author David Matuszek */ public class PatronTest { private Patron dave; private Patron paula; private Book book,book1,book2,book3; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { dave = new Patron("Dave", null); paula = new Patron("Paula", null); book = new Book("Disappearing Nightly", "Laura Resnick"); book1 = new Book("Pride and Prejudice", "Jane Austen"); book2 = new Book("Paths of Glory", "Jeffery Archer"); //delete if unused book3 = new Book("Deception Point", "Dan Brown"); } /** * Test method for {@link library.Patron#Patron(java.lang.String, library.Library)}. * test if object of Patron class is created */ @Test public void testPatron() { Patron paula = new Patron("Paula", null); assertTrue(paula instanceof Patron); } /** * Test method for {@link library.Patron#getName()}. * test if correct name is returned for this patron */ @Test public void testGetName() { assertEquals("Dave", dave.getName()); assertEquals("Paula", paula.getName()); } /** * Test method for {@link library.Patron#take(library.Book)}. * test if this patron can take the books */ @Test public void testTake() { paula.take(book); assertTrue(paula.getBooks().contains(book)); assertFalse(dave.getBooks().contains(book)); dave.take(book1); assertFalse(dave.getBooks().isEmpty()); } /** * Test method for {@link library.Patron#giveBack(library.Book)}. * test if book is returned */ @Test(expected=RuntimeException.class) public void testGiveBack() { paula.take(book); assertTrue(paula.getBooks().contains(book)); paula.giveBack(book); //check if returned book is removed from the list of books checked out by patron assertFalse(paula.getBooks().contains(book)); } /** * Test method for {@link library.Patron#getBooks()}. */ @Test(expected=RuntimeException.class) public void testGetBooks() { dave.take(book); assertTrue(dave.getBooks().contains(book)); assertEquals(1, dave.getBooks().size()); dave.giveBack(book); dave.take(book1); assertFalse(dave.getBooks().isEmpty()); } /** * Test method for {@link library.Patron#toString()}. * test if name of this patron is printed correctly */ @Test public void testToString() { assertEquals("Dave", dave.toString()); assertEquals("Paula", paula.toString()); } }
JavaScript
UTF-8
12,872
2.515625
3
[ "MIT" ]
permissive
import React, { useState, useEffect} from 'react'; import { Link } from 'react-router-dom'; import "./StoreTwoDBsTwoTables.css"; import { useStorageSQLite } from 'react-data-storage-sqlite-hook/dist'; const StoreTwoDBsTwoTables = () => { const [log, setLog] = useState([]); const {openStore, getItem, setItem, getAllKeys, getAllValues, getAllKeysValues, isKey, setTable, removeItem, clear} = useStorageSQLite(); useEffect(() => { const keyList1 = ["app","user","state"]; const keyList2 = ["key1","key2"]; const keyList3 = ["session","contact","state"]; const keyList4 = ["comment1","comment2","comment3"]; async function setFirstDBFirstTable() { var firstTable = false; try { // open a named store setLog((log) => log.concat("**** Test Two DBs Two Tables Store ****\n")); await openStore({database:"myStore",table:"saveData"}); // clear the store table "saveData" for successive test runs await clear(); // store a string await setItem("app","App Opened"); await getItem('app'); // store a JSON Object in the default store const data = {'age':40,'name':'jeep','email':'jeep@example.com'} await setItem("user",JSON.stringify(data)); await getItem("user"); // Get All Keys const keys = await getAllKeys(); if(keys && keys.length === 2 && keyList1.includes(keys[0]) && keyList1.includes(keys[1])) { firstTable = true; setLog((log) => log.concat("*** Set First Table Store was successfull ***\n")); } else { setLog((log) => log.concat("*** Set First Table Store was not successfull ***\n")); } } catch(err) { setLog((log) => log.concat(`>>> ${err}\n`)); setLog((log) => log.concat("*** Set First Table Store was not successfull ***\n")); } return firstTable; } async function setFirstDBSecondTable() { var secondTable = false; try { setLog((log) => log.concat("**** Test First Store Second Table ****\n")); await openStore({database:"myStore",table:"otherData"}); // clear the store table "otherData" for successive test runs await clear(); // store data in the new table await setItem("key1", "Hello World!"); await getItem("key1"); const data1 = {'a':60,'pi':'3.141516','b':'cool'} await setItem("key2",JSON.stringify(data1)); await getItem("key2"); const keys = await getAllKeys(); if(keys && keys.length === 2 && keyList2.includes(keys[0]) && keyList2.includes(keys[1])) { secondTable = true; setLog((log) => log.concat("*** Set First Store Second Table was successfull ***\n")); } else { setLog((log) => log.concat("*** Set First Store Second Table was not successfull ***\n")); } } catch(err) { setLog((log) => log.concat(`>>> ${err}\n`)); setLog((log) => log.concat("*** Set First Store Second Table was not successfull ***\n")); } return secondTable; } async function updateFirstDBFirstTable() { var firstTable = false; try { setLog((log) => log.concat("**** Test First Store First Table ****\n")); await setTable("saveData"); await setItem("state",JSON.stringify({'color':"#ff235a",'opacity':0.75})); // read app from the store await getItem("state"); // Get All Keys const keys = await getAllKeys(); if(keys && keys.length === 3 && keyList1.includes(keys[0]) && keyList1.includes(keys[1]) && keyList1.includes(keys[2])) { firstTable = true; setLog((log) => log.concat("*** Update First Store First Table was successfull ***\n")); } else { setLog((log) => log.concat("*** Update First Store First Table was not successfull ***\n")); } } catch(err) { setLog((log) => log.concat(`>>> ${err}\n`)); setLog((log) => log.concat("*** Update First Store First Table was not successfull ***\n")); } return firstTable; } async function getKeysValuesFromFirstDBSecondTable() { var secondTable = false; try { setLog((log) => log.concat("**** Test First Store Second Table ****\n")); await setTable("otherData"); const keysvalues = await getAllKeysValues(); if(keysvalues && keysvalues.length === 2 && keyList2.includes(keysvalues[0].key) && keyList2.includes(keysvalues[1].key)) { secondTable = true; setLog((log) => log.concat("*** KeysValues from First Store Second Table was successfull ***\n")); } else { setLog((log) => log.concat("*** KeysValues from First Store Second Table was not successfull ***\n")); } } catch(err) { setLog((log) => log.concat(`>>> ${err}\n`)); setLog((log) => log.concat("*** KeysValues from First Store Second Table was not successfull ***\n")); } return secondTable; } async function setSecondDBFirstTable() { var firstTable = false; try { // open a named store setLog((log) => log.concat("**** Test Second Store First Table ****\n")); await openStore({database:"secondStore",table:"saveData"}); // clear the store table "saveData" for successive test runs await clear(); // store a string await setItem("session","Session Opened"); await getItem('session'); // store a JSON Object in the default store const data = {'age':30,'name':'White','email':'white@example.com'} await setItem("contact",JSON.stringify(data)); await getItem("contact"); // Get All Keys const keys = await getAllKeys(); if(keys && keys.length === 2 && keyList3.includes(keys[0]) && keyList3.includes(keys[1])) { firstTable = true; setLog((log) => log.concat("*** Set Second Store First Table was successfull ***\n")); } else { setLog((log) => log.concat("*** Set Second Store First Table was not successfull ***\n")); } } catch(err) { setLog((log) => log.concat(`>>> ${err}\n`)); setLog((log) => log.concat("*** Set Second Store First Table was not successfull ***\n")); } return firstTable; } async function setSecondDBSecondTable() { var secondTable = false; try { setLog((log) => log.concat("**** Test Second Store First Table ****\n")); await openStore({database:"secondStore",table:"comments"}); // clear the store table "saveData" for successive test runs await clear(); // store data in the new table await setItem("comment1", "Lorem ipsum dolor sit amet"); await getItem("comment1"); await setItem("comment2", "Nam pretium risus velit"); await getItem("comment2"); // Get All Keys const keys = await getAllKeys(); if(keys && keys.length === 2 && keyList4.includes(keys[0]) && keyList4.includes(keys[1])) { secondTable = true; setLog((log) => log.concat("*** Set Second Store Second Table was successfull ***\n")); } else { setLog((log) => log.concat("*** Set Second Store Second Table was not successfull ***\n")); } } catch(err) { setLog((log) => log.concat(`>>> ${err}\n`)); setLog((log) => log.concat("*** Set Second Store Second Table was not successfull ***\n")); } return secondTable; } async function updateSecondDBFirstTable() { var firstTable = false; try { setLog((log) => log.concat("**** Test Second Store First Table ****\n")); await setTable("saveData"); await setItem("state",JSON.stringify({platform: ['ios','android','web']})); await getItem("state"); // Get All Keys const keys = await getAllKeys(); if(keys && keys.length === 3 && keyList3.includes(keys[0]) && keyList3.includes(keys[1]) && keyList3.includes(keys[2])) { firstTable = true; setLog((log) => log.concat("*** Update Second Store First Table was successfull ***\n")); } else { setLog((log) => log.concat("*** Update Second Store First Table was not successfull ***\n")); } } catch(err) { setLog((log) => log.concat(`>>> ${err}\n`)); setLog((log) => log.concat("*** Update Second Store First Table was not successfull ***\n")); } return firstTable; } async function getKeysValuesFromSecondDBSecondTable() { var secondTable = false; try { setLog((log) => log.concat("**** Test Second Store Second Table ****\n")); await setTable("comments"); await setItem("comment3", "Suspendisse lobortis volutpat elit ac mattis"); await getItem("comment3"); // Get All Keys const keys = await getAllKeys(); if(keys && keys.length === 3 && keyList4.includes(keys[0]) && keyList4.includes(keys[1]) && keyList4.includes(keys[2])) { secondTable = true; setLog((log) => log.concat("*** Update Second Store Second Table was successfull ***\n")); } else { setLog((log) => log.concat("*** Update Second Store Second Table was not successfull ***\n")); } } catch(err) { setLog((log) => log.concat(`>>> ${err}\n`)); setLog((log) => log.concat("*** Update Second Store Second Table was not successfull ***\n")); } return secondTable; } async function testStoreTwoDBsTwoTables() { // create the first table in the first store const fStore_fTable = await setFirstDBFirstTable(); if(!fStore_fTable) { document.querySelector('.failure').classList.remove('display'); return; } // create the first table in the second store const sStore_fTable = await setSecondDBFirstTable(); if(!sStore_fTable) { document.querySelector('.failure').classList.remove('display'); return; } // create the second table in the first store const fStore_sTable = await setFirstDBSecondTable(); if(!fStore_sTable) { document.querySelector('.failure').classList.remove('display'); return; } // update first table in the first store const fStore_fTable1 = await updateFirstDBFirstTable(); if(!fStore_fTable1) { document.querySelector('.failure').classList.remove('display'); return; } // reopen the second table in the first store and read all keys-values const fStore_sTable1 = await getKeysValuesFromFirstDBSecondTable(); if(!fStore_sTable1) { document.querySelector('.failure').classList.remove('display'); } else { document.querySelector('.success').classList.remove('display'); } // open second table in second store const sStore_sTable = await setSecondDBSecondTable(); if(!sStore_sTable) { document.querySelector('.failure').classList.remove('display'); return; } // update first table in the second store const sStore_fTable1 = await updateSecondDBFirstTable(); if(!sStore_fTable1) { document.querySelector('.failure').classList.remove('display'); return; } // reopen the second table in the second store and read all keys-values const sStore_sTable1 = await getKeysValuesFromSecondDBSecondTable(); if(!sStore_sTable1) { document.querySelector('.failure').classList.remove('display'); } else { document.querySelector('.success').classList.remove('display'); } return; } testStoreTwoDBsTwoTables(); }, [ openStore, getItem, setItem, getAllKeys, getAllValues, getAllKeysValues, isKey, setTable, removeItem, clear]); return ( <React.Fragment> <div className="StoreOneDBTwoTables"> <div id="header"> <Link to="/"> <button> Home </button> </Link> <p id="title">Test Store Two DBs Two Tables</p> </div> <div id="content"> <pre> <p>{log}</p> </pre> <p className="success display"> The set of tests was successful </p> <p className="failure display"> The set of tests failed </p> </div> </div> </React.Fragment> ); } export default StoreTwoDBsTwoTables;
Java
UTF-8
1,067
2.78125
3
[]
no_license
public class testRemontService { public static void main(String[] args) { RemontService remontService = new RemontService(); Notebook myNotebook1 = new Notebook("ASUS TUF Gaming FX705", 6, "AMD Ryzen 7", 2020); remontService.addComputer(myNotebook1); remontService.addComputer(new Notebook("MSI Prestige 14", 4, "Intel Core i5 10210U", 2020)); Smartphone mySmartphone = new Smartphone("Iphone X", 6, "iOS", 64); remontService.addComputer(mySmartphone); remontService.printRemontService(); System.out.println("Количество ноутбуков в сервисном центре: " + remontService.getNotebooksCount()); System.out.println("Количество смартфонов в сервисном центре: " + remontService.getSmartphonesCount()); if (remontService.findComputer(myNotebook1)) { System.out.println("Да"); } else { System.out.println("Нет"); } remontService.removeComputer(myNotebook1); } }
Go
UTF-8
5,485
2.890625
3
[ "ISC" ]
permissive
/* * Copyright (c) 2017-2020 The qitmeer developers */ package discover import ( "context" "time" "github.com/Qitmeer/qitmeer/p2p/qnode" ) const ( MinTableNodes = 5 PollingPeriod = 6 * time.Second ) // lookup performs a network search for nodes close to the given target. It approaches the // target by querying nodes that are closer to it on each iteration. The given target does // not need to be an actual node identifier. type lookup struct { tab *Table queryfunc func(*node) ([]*node, error) replyCh chan []*node cancelCh <-chan struct{} asked, seen map[qnode.ID]bool result nodesByDistance replyBuffer []*node queries int } type queryFunc func(*node) ([]*node, error) func newLookup(ctx context.Context, tab *Table, target qnode.ID, q queryFunc) *lookup { it := &lookup{ tab: tab, queryfunc: q, asked: make(map[qnode.ID]bool), seen: make(map[qnode.ID]bool), result: nodesByDistance{target: target}, replyCh: make(chan []*node, alpha), cancelCh: ctx.Done(), queries: -1, } // Don't query further if we hit ourself. // Unlikely to happen often in practice. it.asked[tab.self().ID()] = true return it } // run runs the lookup to completion and returns the closest nodes found. func (it *lookup) run() []*qnode.Node { for it.advance() { } return unwrapNodes(it.result.entries) } // advance advances the lookup until any new nodes have been found. // It returns false when the lookup has ended. func (it *lookup) advance() bool { for it.startQueries() { select { case nodes := <-it.replyCh: it.replyBuffer = it.replyBuffer[:0] for _, n := range nodes { if n != nil && !it.seen[n.ID()] { it.seen[n.ID()] = true it.result.push(n, bucketSize) it.replyBuffer = append(it.replyBuffer, n) } } it.queries-- if len(it.replyBuffer) > 0 { return true } case <-it.cancelCh: it.shutdown() } time.Sleep(PollingPeriod) } return false } func (it *lookup) shutdown() { for it.queries > 0 { <-it.replyCh it.queries-- } it.queryfunc = nil it.replyBuffer = nil } func (it *lookup) startQueries() bool { if it.queryfunc == nil { return false } // The first query returns nodes from the local table. if it.queries == -1 { it.tab.mutex.Lock() closest := it.tab.closest(it.result.target, bucketSize, false) it.tab.mutex.Unlock() // Avoid finishing the lookup too quickly if table is empty. It'd be better to wait // for the table to fill in this case, but there is no good mechanism for that // yet. if len(closest.entries) == 0 { it.slowdown() } it.queries = 1 it.replyCh <- closest.entries return true } // Ask the closest nodes that we haven't asked yet. for i := 0; i < len(it.result.entries) && it.queries < alpha; i++ { n := it.result.entries[i] if !it.asked[n.ID()] { it.asked[n.ID()] = true it.queries++ go it.query(n, it.replyCh) } } // The lookup ends when no more nodes can be asked. return it.queries > 0 } func (it *lookup) slowdown() { sleep := time.NewTimer(1 * time.Second) defer sleep.Stop() select { case <-sleep.C: case <-it.tab.closeReq: } } func (it *lookup) query(n *node, reply chan<- []*node) { if len(n.ID()) == 0 || n.IP().To16() == nil { return } fails := it.tab.db.FindFails(n.ID(), n.IP()) r, err := it.queryfunc(n) if err == errClosed { // Avoid recording failures on shutdown. reply <- nil return } else if len(r) == 0 { if len(it.tab.allNodes()) > MinTableNodes { fails++ it.tab.db.UpdateFindFails(n.ID(), n.IP(), fails) log.Trace("Findnode failed", "id", n.ID(), "failcount", fails, "results", len(r), "err", err) if fails >= maxFindnodeFailures { log.Trace("Too many findnode failures, dropping", "id", n.ID(), "failcount", fails) it.tab.delete(n) } } } else if fails > 0 { // Reset failure counter because it counts _consecutive_ failures. it.tab.db.UpdateFindFails(n.ID(), n.IP(), 0) } // Grab as many nodes as possible. Some of them might not be alive anymore, but we'll // just remove those again during revalidation. for _, n := range r { it.tab.addSeenNode(n) } reply <- r } // lookupIterator performs lookup operations and iterates over all seen nodes. // When a lookup finishes, a new one is created through nextLookup. type lookupIterator struct { buffer []*node nextLookup lookupFunc ctx context.Context cancel func() lookup *lookup } type lookupFunc func(ctx context.Context) *lookup func newLookupIterator(ctx context.Context, next lookupFunc) *lookupIterator { ctx, cancel := context.WithCancel(ctx) return &lookupIterator{ctx: ctx, cancel: cancel, nextLookup: next} } // Node returns the current node. func (it *lookupIterator) Node() *qnode.Node { if len(it.buffer) == 0 { return nil } return unwrapNode(it.buffer[0]) } // Next moves to the next node. func (it *lookupIterator) Next() bool { // Consume next node in buffer. if len(it.buffer) > 0 { it.buffer = it.buffer[1:] } // Advance the lookup to refill the buffer. for len(it.buffer) == 0 { if it.ctx.Err() != nil { it.lookup = nil it.buffer = nil return false } if it.lookup == nil { it.lookup = it.nextLookup(it.ctx) continue } if !it.lookup.advance() { it.lookup.shutdown() it.lookup = nil continue } it.buffer = it.lookup.replyBuffer } return true } // Close ends the iterator. func (it *lookupIterator) Close() { it.cancel() }
Python
UTF-8
228
3.078125
3
[]
no_license
import json import sys def show_data(data, type='json'): try: data_to_be_shown = json.dumps(data, indent=4) except RuntimeError: print "Invalid data type." sys.exit(0) print data_to_be_shown
Python
UTF-8
1,599
3.15625
3
[]
no_license
# # @lc app=leetcode id=126 lang=python # # [126] Word Ladder II # # @lc code=start class Solution(object): def backtrack(self, result, trace, path, word): if not trace[word]: result.append([word] + path) else: for prev in trace[word]: self.backtrack(result, trace, [word] + path, prev) def findLadders(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[List[str]] """ wordSet = set(wordList) wordSet.add(beginWord) wordSet.add(endWord) result = [] cur = [beginWord] visited = set([endWord]) found = False trace = {word: [] for word in wordList} while cur and not found: for word in cur: visited.add(word) next = set() for word in cur: for i in xrange(len(word)): for j in 'abcdefghijklmnopqrstuvwxyz': candidate = word[:i] + j + word[i + 1:] if candidate not in visited and candidate in wordSet: if candidate == endWord: found = True next.add(candidate) trace[candidate].append(word) cur = next if found: self.backtrack(result, trace, [], endWord) return result # @lc code=end
Python
UTF-8
770
3.953125
4
[]
no_license
'给定一个整型列表,如:lst =[1,5,2,7,4,9],指定的目标值为11,可以从中找出 2和9之和为11 ' import datetime from functools import wraps def logger(fn): @wraps(fn) def wrapper(*args, **kwargs): start = datetime.datetime.now() ret = fn(*args, **kwargs) delta = (datetime.datetime.now() - start).total_seconds() print('{} tooks {}s'.format(fn.__name__,delta)) return ret return wrapper @logger def sum_townums(src:list, target:int): length = len(src) flag = [False] * length ret = [] for i in range(length): if flag[i]: continue for j in range(i,length): if src[i] + src[j] == target: flag[i], flag[j] = True , True ret.append((src[i],src[j])) break return ret print(sum_townums([1, 5, 2, 7, 4, 9],11))
Python
UTF-8
1,013
3.453125
3
[]
no_license
def sanitize(time_string): """用.替换时间当中的- :""" if '-' in time_string: splitter = '-' elif ':' in time_string: splitter = ':' else: return(time_string) (mins, secs) = time_string.split(splitter) return(mins + '.' + secs) """定义函数读取数据""" def get_coach_data(file_name): try: with open (file_name) as f: data= f.readline() return (data.strip().split(',')) except IOError as ioerr: print("File error:" + str(ioerr)) return(None) james = get_coach_data('james.txt') julie = get_coach_data('julie.txt') mikey = get_coach_data('mikey.txt') sarah = get_coach_data('sarah.txt') """use set to unique the data""" print(sorted(set([sanitize(each_c) for each_c in james]))[0:3]) print(sorted(set([sanitize(each_c) for each_c in julie]))[0:3]) print(sorted(set([sanitize(each_c) for each_c in mikey]))[0:3]) print(sorted(set([sanitize(each_c) for each_c in sarah]))[0:3])
Markdown
UTF-8
455
2.75
3
[ "Apache-2.0" ]
permissive
--- layout: feature title: 'Gender' shortdef: 'gender' udver: '2' --- `Gender` in Erzya is a peripheral phenomenon attested only occasionally/archaically in the [proper nouns](myv-pos/PROPN), where a woman is given the name of her husband with the -низэ `wife` suffix attached. #### Examples * [myv] _Иван ды <b>Иваннызе</b>_ "Ivan and <b>Ivan's wife</b>" * [myv] _Гава ды <b>Гаванизе</b>_ "Gava and <b>Gava's wife</b>"
Java
UTF-8
1,158
2.796875
3
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2017 xiaoniu, Inc. All rights reserved. * * @author chunlin.li * */ package netty.authority.ch02.bio; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * 功能描述: 同步阻塞I/O (BIO) * <p/> * 创建人: chunlin.li * <p/> * 创建时间: 2018/06/23. * <p/> * Copyright (c) 凌霄阁工作室-版权所有 */ public class TimeServer { public static void main(String[] args) throws IOException { int prot = 8080; if (args != null && args.length > 0) { try { prot = Integer.valueOf(args[0]); } catch (NumberFormatException e) { e.printStackTrace(); } } ServerSocket server = null; try { server = new ServerSocket(prot); System.out.println("The time server start in port:"+ prot); Socket socket = null; while (true) { socket = server.accept(); new Thread(new TimeServerHandler(socket)).start(); } } catch (Exception e) { e.printStackTrace(); } } }
C
UTF-8
926
2.96875
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <string.h> char* chanbufe_str(char *s1, char *s2) { char *lastP, *p; int k=0; p = strstr(s1, s2); while (p!='\n') { lastP = p++; p = strstr(p, s1); k++; } lastP = p; if (lastP) { strcpy(lastP, lastP + strlen(s2)); } return k; } int main() { char *h; char *buf = NULL; char *h1; char *s2 = NULL; char m; char m1; int n1 = 0; int n = 0; do { scanf("%c", &m); n++; h = (char*)realloc(buf, sizeof(char)*n); if ((h != NULL)) { buf = h; buf[n - 1] = m; } } while (m != '\n'); do { scanf("%c", &m1); n1++; h1 = (char*)realloc(s2, sizeof(char)*n1); if ((h1 != NULL)) { s2 = h1; s2[n1 - 1] = m1; } } while (m1 != '\n'); getchar(); int k = 0; k = chanbufe_str(buf, s2); printf("\n%s", buf-k); getchar(); return 0; }
PHP
UTF-8
3,852
2.578125
3
[]
no_license
<?php //Disk Free $df = disk_free_space("/"); $disk_space_free = get_int_symbol($df); //Disk Total $dt = disk_total_space("/"); $disk_space_total = get_int_symbol($dt); //Disk Progress Bar $get_ds_percent = get_percent($df, $dt); $disk_available = 100 - $get_ds_percent; //Memory $memory_usage = get_server_memory_usage(); $memory_total = get_int_symbol(get_server_memory_total()); $memory_free = get_int_symbol(get_server_memory_free()); $memory_available = 100 - $memory_usage; //CPU $cpu_usage = get_server_cpu_usage_cores(); $cpu_available = 100 - $cpu_usage; ?> <h1 class="page-header">Welcome</h1> <div class="row"> <div class="col-sm-12"> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-sm-9"> <h3 class="panel-title"><span class="glyphicon glyphicon-hdd" aria-hidden="true"></span> Disk Space</h3> </div> <div class="col-sm-3"> <label class="label label-default"><?php echo $disk_available; ?>% Available</label> </div> </div> </div> <div class="panel-body"> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="<?php echo $get_ds_percent; ?>" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $get_ds_percent; ?>%;"> <?php echo $get_ds_percent; ?>% </div> </div> <strong>Free Space:</strong> <?php echo $disk_space_free; ?> <br /> <strong>Total Space:</strong> <?php echo $disk_space_total; ?> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-sm-9"> <h3 class="panel-title"><span class="glyphicon glyphicon-hdd" aria-hidden="true"></span> Memory</h3> </div> <div class="col-sm-3"> <label class="label label-default"><?php echo $memory_available; ?>% Available</label> </div> </div> </div> <div class="panel-body"> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="<?php echo $memory_usage; ?>" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $memory_usage; ?>%;"> <?php echo $memory_usage; ?>% </div> </div> <strong>Free Memory:</strong> <?php echo $memory_free; ?> <br /> <strong>Total Memory:</strong> <?php echo $memory_total; ?> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-sm-9"> <h3 class="panel-title"><span class="glyphicon glyphicon-hdd" aria-hidden="true"></span> CPU</h3> </div> <div class="col-sm-3"> <label class="label label-default"><?php echo $cpu_available; ?>% Available</label> </div> </div> </div> <div class="panel-body"> <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="<?php echo $cpu_usage; ?>" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $cpu_usage; ?>%;"> <?php echo $cpu_usage; ?>% </div> </div> </div> </div> </div> </div>
JavaScript
UTF-8
2,784
2.859375
3
[]
no_license
import React from "react"; import Task from './task'; import { useState } from "react"; import axios from "axios"; const TasksBox = () => { const [newtasks, setnewtasks] = useState([]); const [taskvalue, settaskvalue] = useState(""); function changehandler(event) { settaskvalue(event.target.value); } function addtasks(event) { if(event.key === "Enter" || event.button === 0) { var newtask = document.getElementById('tasker').value; if(newtask !== "") { axios.post('https://djangoapitodo.herokuapp.com/tasks/api/', {'task': newtask,}, {headers: {'content-type': 'application/json'}}).then(res => { setnewtasks((prev) => { return [...prev, { 'key': res.data['id'], 'id': res.data['id'], 'task': res.data['task'], 'isdone': res.data['is_done'], }] }); }); } settaskvalue(""); } } const [tasks, setTasks] = useState([]); React.useEffect(() => { axios .get("https://djangoapitodo.herokuapp.com/tasks/api/") .then((res) => { var t = []; for (var obj in res.data) { t.push({ key: res.data[obj]["id"], id: res.data[obj]["id"], task: res.data[obj]["task"], isdone: res.data[obj]["is_done"], }); } setTasks(t); }); }, []); document.addEventListener('keypress', addtasks); return ( <div> <div className="mt-5 pt-5 pb-5 text-center mr-auto ml-auto taskbox"> <h2>To do List</h2> <div className="mb-5 mt-5"> {tasks.map((task) => { return <Task task={task.task} key={task.id} id={task.id} isdone={task.isdone} /> })} {newtasks.map((task) => { return <Task task={task.task} key={task.id} id={task.id} isdone={task.isdone} /> })} </div> <div className="inliner task-container"> <input type="text" className="task-input mr-auto ml-auto" id="tasker" value={taskvalue} onChange={changehandler} placeholder="New Task..(max 50 chars)"/> <div className="inliner"> <p onClick={addtasks} className="hooki">✔</p> </div> </div> </div> </div> ) } export default TasksBox;
C#
UTF-8
32,712
2.8125
3
[ "MIT" ]
permissive
using System; using OpenCvSharp.Util; namespace OpenCvSharp { /// <summary> /// Matrix expression /// </summary> public sealed partial class MatExpr : DisposableCvObject { #region Init & Disposal /// <summary> /// /// </summary> /// <param name="ptr"></param> internal MatExpr(IntPtr ptr) { this.ptr = ptr; } /// <summary> /// /// </summary> /// <param name="mat"></param> internal MatExpr(Mat mat) { if(mat == null) throw new ArgumentNullException(nameof(mat)); ptr = NativeMethods.core_MatExpr_new2(mat.CvPtr); } /// <summary> /// Releases unmanaged resources /// </summary> protected override void DisposeUnmanaged() { NativeMethods.core_MatExpr_delete(ptr); base.DisposeUnmanaged(); } #endregion #region Cast /// <summary> /// /// </summary> /// <param name="self"></param> /// <returns></returns> public static implicit operator Mat(MatExpr self) { try { var retPtr = NativeMethods.core_MatExpr_toMat(self.ptr); GC.KeepAlive(self); var retVal = new Mat(retPtr); return retVal; } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <returns></returns> public Mat ToMat() { return this; } /// <summary> /// /// </summary> /// <param name="mat"></param> /// <returns></returns> public static implicit operator MatExpr(Mat mat) { return new MatExpr(mat); } /// <summary> /// /// </summary> /// <param name="mat"></param> /// <returns></returns> public static MatExpr FromMat(Mat mat) { return new MatExpr(mat); } #endregion #region Operators #region Unary /// <summary> /// /// </summary> /// <param name="e"></param> /// <returns></returns> public static MatExpr operator +(MatExpr e) { return e; } /// <summary> /// /// </summary> /// <param name="e"></param> /// <returns></returns> public static MatExpr operator -(MatExpr e) { if (e == null) throw new ArgumentNullException(nameof(e)); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorUnaryMinus_MatExpr(e.CvPtr); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="e"></param> /// <returns></returns> public static MatExpr operator ~(MatExpr e) { if (e == null) throw new ArgumentNullException(nameof(e)); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorUnaryNot_MatExpr(e.CvPtr); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } #endregion #region + /// <summary> /// /// </summary> /// <param name="e"></param> /// <param name="m"></param> /// <returns></returns> public static MatExpr operator +(MatExpr e, Mat m) { if (e == null) throw new ArgumentNullException(nameof(e)); if (m == null) throw new ArgumentNullException(nameof(m)); e.ThrowIfDisposed(); m.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorAdd_MatExprMat(e.CvPtr, m.CvPtr); GC.KeepAlive(e); GC.KeepAlive(m); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="m"></param> /// <param name="e"></param> /// <returns></returns> public static MatExpr operator +(Mat m, MatExpr e) { if (m == null) throw new ArgumentNullException(nameof(m)); if (e == null) throw new ArgumentNullException(nameof(e)); m.ThrowIfDisposed(); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorAdd_MatMatExpr(m.CvPtr, e.CvPtr); GC.KeepAlive(m); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="e"></param> /// <param name="s"></param> /// <returns></returns> public static MatExpr operator +(MatExpr e, Scalar s) { if (e == null) throw new ArgumentNullException(nameof(e)); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorAdd_MatExprScalar(e.CvPtr, s); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="e"></param> /// <returns></returns> public static MatExpr operator +(Scalar s, MatExpr e) { if (e == null) throw new ArgumentNullException(nameof(e)); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorAdd_ScalarMatExpr(s, e.CvPtr); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="e1"></param> /// <param name="e2"></param> /// <returns></returns> public static MatExpr operator +(MatExpr e1, MatExpr e2) { if (e1 == null) throw new ArgumentNullException(nameof(e1)); if (e2 == null) throw new ArgumentNullException(nameof(e2)); e1.ThrowIfDisposed(); e2.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorAdd_MatExprMatExpr(e1.CvPtr, e2.CvPtr); GC.KeepAlive(e1); GC.KeepAlive(e2); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } #endregion #region - /// <summary> /// /// </summary> /// <param name="e"></param> /// <param name="m"></param> /// <returns></returns> public static MatExpr operator -(MatExpr e, Mat m) { if (e == null) throw new ArgumentNullException(nameof(e)); if (m == null) throw new ArgumentNullException(nameof(m)); e.ThrowIfDisposed(); m.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorSubtract_MatExprMat(e.CvPtr, m.CvPtr); GC.KeepAlive(e); GC.KeepAlive(m); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="m"></param> /// <param name="e"></param> /// <returns></returns> public static MatExpr operator -(Mat m, MatExpr e) { if (m == null) throw new ArgumentNullException(nameof(m)); if (e == null) throw new ArgumentNullException(nameof(e)); m.ThrowIfDisposed(); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorSubtract_MatMatExpr(m.CvPtr, e.CvPtr); GC.KeepAlive(m); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="e"></param> /// <param name="s"></param> /// <returns></returns> public static MatExpr operator -(MatExpr e, Scalar s) { if (e == null) throw new ArgumentNullException(nameof(e)); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorSubtract_MatExprScalar(e.CvPtr, s); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="e"></param> /// <returns></returns> public static MatExpr operator -(Scalar s, MatExpr e) { if (e == null) throw new ArgumentNullException(nameof(e)); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorSubtract_ScalarMatExpr(s, e.CvPtr); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="e1"></param> /// <param name="e2"></param> /// <returns></returns> public static MatExpr operator -(MatExpr e1, MatExpr e2) { if (e1 == null) throw new ArgumentNullException(nameof(e1)); if (e2 == null) throw new ArgumentNullException(nameof(e2)); e1.ThrowIfDisposed(); e2.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorSubtract_MatExprMatExpr(e1.CvPtr, e2.CvPtr); GC.KeepAlive(e1); GC.KeepAlive(e2); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } #endregion #region * /// <summary> /// /// </summary> /// <param name="e"></param> /// <param name="m"></param> /// <returns></returns> public static MatExpr operator *(MatExpr e, Mat m) { if (e == null) throw new ArgumentNullException(nameof(e)); if (m == null) throw new ArgumentNullException(nameof(m)); e.ThrowIfDisposed(); m.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorMultiply_MatExprMat(e.CvPtr, m.CvPtr); GC.KeepAlive(e); GC.KeepAlive(m); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="m"></param> /// <param name="e"></param> /// <returns></returns> public static MatExpr operator *(Mat m, MatExpr e) { if (m == null) throw new ArgumentNullException(nameof(m)); if (e == null) throw new ArgumentNullException(nameof(e)); m.ThrowIfDisposed(); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorMultiply_MatMatExpr(m.CvPtr, e.CvPtr); GC.KeepAlive(m); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="e"></param> /// <param name="s"></param> /// <returns></returns> public static MatExpr operator *(MatExpr e, double s) { if (e == null) throw new ArgumentNullException(nameof(e)); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorMultiply_MatExprDouble(e.CvPtr, s); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="e"></param> /// <returns></returns> public static MatExpr operator *(double s, MatExpr e) { if (e == null) throw new ArgumentNullException(nameof(e)); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorMultiply_DoubleMatExpr(s, e.CvPtr); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="e1"></param> /// <param name="e2"></param> /// <returns></returns> public static MatExpr operator *(MatExpr e1, MatExpr e2) { if (e1 == null) throw new ArgumentNullException(nameof(e1)); if (e2 == null) throw new ArgumentNullException(nameof(e2)); e1.ThrowIfDisposed(); e2.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorMultiply_MatExprMatExpr(e1.CvPtr, e2.CvPtr); GC.KeepAlive(e1); GC.KeepAlive(e2); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } #endregion #region / /// <summary> /// /// </summary> /// <param name="e"></param> /// <param name="m"></param> /// <returns></returns> public static MatExpr operator /(MatExpr e, Mat m) { if (e == null) throw new ArgumentNullException(nameof(e)); if (m == null) throw new ArgumentNullException(nameof(m)); e.ThrowIfDisposed(); m.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorDivide_MatExprMat(e.CvPtr, m.CvPtr); GC.KeepAlive(e); GC.KeepAlive(m); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="m"></param> /// <param name="e"></param> /// <returns></returns> public static MatExpr operator /(Mat m, MatExpr e) { if (m == null) throw new ArgumentNullException(nameof(m)); if (e == null) throw new ArgumentNullException(nameof(e)); m.ThrowIfDisposed(); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorDivide_MatMatExpr(m.CvPtr, e.CvPtr); GC.KeepAlive(m); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="e"></param> /// <param name="s"></param> /// <returns></returns> public static MatExpr operator /(MatExpr e, double s) { if (e == null) throw new ArgumentNullException(nameof(e)); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorDivide_MatExprDouble(e.CvPtr, s); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="e"></param> /// <returns></returns> public static MatExpr operator /(double s, MatExpr e) { if (e == null) throw new ArgumentNullException(nameof(e)); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorDivide_DoubleMatExpr(s, e.CvPtr); GC.KeepAlive(e); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="e1"></param> /// <param name="e2"></param> /// <returns></returns> public static MatExpr operator /(MatExpr e1, MatExpr e2) { if (e1 == null) throw new ArgumentNullException(nameof(e1)); if (e2 == null) throw new ArgumentNullException(nameof(e2)); e1.ThrowIfDisposed(); e2.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_operatorDivide_MatExprMatExpr(e1.CvPtr, e2.CvPtr); GC.KeepAlive(e1); GC.KeepAlive(e2); return new MatExpr(retPtr); } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } #endregion #endregion #region Methods #region Indexers /// <summary> /// /// </summary> /// <param name="rowStart"></param> /// <param name="rowEnd"></param> /// <param name="colStart"></param> /// <param name="colEnd"></param> /// <returns></returns> public MatExpr this[int rowStart, int rowEnd, int colStart, int colEnd] { get { ThrowIfDisposed(); return SubMat(rowStart, rowEnd, colStart, colEnd); } } /// <summary> /// /// </summary> /// <param name="rowRange"></param> /// <param name="colRange"></param> /// <returns></returns> public MatExpr this[Range rowRange, Range colRange] { get { ThrowIfDisposed(); return SubMat(rowRange, colRange); } set { ThrowIfDisposed(); if (value == null) throw new ArgumentNullException(nameof(value)); var subMatExpr = SubMat(rowRange, colRange); NativeMethods.core_Mat_assignment_FromMatExpr(subMatExpr.CvPtr, value.CvPtr); GC.KeepAlive(subMatExpr); GC.KeepAlive(value); } } /// <summary> /// /// </summary> /// <param name="roi"></param> /// <returns></returns> public MatExpr this[Rect roi] { get { ThrowIfDisposed(); return SubMat(roi); } set { ThrowIfDisposed(); if (value == null) throw new ArgumentNullException(nameof(value)); var subMatExpr = SubMat(roi); NativeMethods.core_Mat_assignment_FromMatExpr(subMatExpr.CvPtr, value.CvPtr); GC.KeepAlive(subMatExpr); GC.KeepAlive(value); } } #endregion #region Col /// <summary> /// /// </summary> public class ColIndexer : MatExprRowColIndexer { /// <summary> /// /// </summary> /// <param name="parent"></param> protected internal ColIndexer(MatExpr parent) : base(parent) { } /// <summary> /// /// </summary> /// <param name="x"></param> /// <returns></returns> public override MatExpr this[int x] { get { Parent.ThrowIfDisposed(); var retPtr = NativeMethods.core_MatExpr_col(Parent.CvPtr, x); GC.KeepAlive(this); return new MatExpr(retPtr); } } } /// <summary> /// /// </summary> public ColIndexer Col { get { return col ??= new ColIndexer(this); } } private ColIndexer? col; #endregion #region Cross /// <summary> /// /// </summary> /// <param name="m"></param> /// <returns></returns> public Mat Cross(Mat m) { ThrowIfDisposed(); m.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_MatExpr_cross(ptr, m.CvPtr); GC.KeepAlive(this); GC.KeepAlive(m); var retVal = new Mat(retPtr); return retVal; } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } #endregion #region Diag /// <summary> /// /// </summary> /// <param name="d"></param> /// <returns></returns> public MatExpr Diag(int d = 0) { ThrowIfDisposed(); try { var retPtr = NativeMethods.core_MatExpr_diag2(ptr, d); GC.KeepAlive(this); var retVal = new MatExpr(retPtr); return retVal; } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } #endregion #region Dot /// <summary> /// /// </summary> /// <param name="m"></param> /// <returns></returns> public double Dot(Mat m) { ThrowIfDisposed(); m.ThrowIfDisposed(); try { var res = NativeMethods.core_MatExpr_dot(ptr, m.CvPtr); GC.KeepAlive(this); GC.KeepAlive(m); return res; } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } #endregion #region Inv /// <summary> /// /// </summary> /// <param name="method"></param> /// <returns></returns> public MatExpr Inv(DecompTypes method = DecompTypes.LU) { ThrowIfDisposed(); try { var retPtr = NativeMethods.core_MatExpr_inv2(ptr, (int)method); GC.KeepAlive(this); var retVal = new MatExpr(retPtr); return retVal; } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } #endregion #region Mul /// <summary> /// /// </summary> /// <param name="e"></param> /// <param name="scale"></param> /// <returns></returns> public MatExpr Mul(MatExpr e, double scale = 1.0) { ThrowIfDisposed(); e.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_MatExpr_mul_toMatExpr(ptr, e.CvPtr, scale); GC.KeepAlive(this); GC.KeepAlive(e); var retVal = new MatExpr(retPtr); return retVal; } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="m"></param> /// <param name="scale"></param> /// <returns></returns> public MatExpr Mul(Mat m, double scale = 1.0) { ThrowIfDisposed(); m.ThrowIfDisposed(); try { var retPtr = NativeMethods.core_MatExpr_mul_toMat(ptr, m.CvPtr, scale); GC.KeepAlive(this); GC.KeepAlive(m); var retVal = new MatExpr(retPtr); return retVal; } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } #endregion #region Row /// <summary> /// /// </summary> public class RowIndexer : MatExprRowColIndexer { /// <summary> /// /// </summary> /// <param name="parent"></param> protected internal RowIndexer(MatExpr parent) : base(parent) { } /// <summary> /// /// </summary> /// <param name="y"></param> /// <returns></returns> public override MatExpr this[int y] { get { Parent.ThrowIfDisposed(); var retPtr = NativeMethods.core_MatExpr_row(Parent.CvPtr, y); GC.KeepAlive(this); return new MatExpr(retPtr); } } } /// <summary> /// /// </summary> public RowIndexer Row { get { return row ??= new RowIndexer(this); } } private RowIndexer? row; #endregion #region /// <summary> /// /// </summary> public Size Size { get { ThrowIfDisposed(); try { var res = NativeMethods.core_MatExpr_size(ptr); GC.KeepAlive(this); return res; } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } } #endregion #region SubMat /// <summary> /// /// </summary> /// <param name="rowStart"></param> /// <param name="rowEnd"></param> /// <param name="colStart"></param> /// <param name="colEnd"></param> /// <returns></returns> public MatExpr SubMat(int rowStart, int rowEnd, int colStart, int colEnd) { ThrowIfDisposed(); try { var retPtr = NativeMethods.core_MatExpr_submat(ptr, rowStart, rowEnd, colStart, colEnd); GC.KeepAlive(this); var retVal = new MatExpr(retPtr); return retVal; } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } /// <summary> /// /// </summary> /// <param name="rowRange"></param> /// <param name="colRange"></param> /// <returns></returns> public MatExpr SubMat(Range rowRange, Range colRange) { return SubMat(rowRange.Start, rowRange.End, colRange.Start, colRange.End); } /// <summary> /// /// </summary> /// <param name="roi"></param> /// <returns></returns> public MatExpr SubMat(Rect roi) { return SubMat(roi.Y, roi.Y + roi.Height, roi.X, roi.X + roi.Width); } #endregion #region T /// <summary> /// /// </summary> /// <returns></returns> public MatExpr T() { ThrowIfDisposed(); try { var retPtr = NativeMethods.core_MatExpr_t(ptr); GC.KeepAlive(this); var retVal = new MatExpr(retPtr); return retVal; } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } #endregion #region Type /// <summary> /// /// </summary> public MatType Type { get { ThrowIfDisposed(); try { var res = (MatType)NativeMethods.core_MatExpr_type(ptr); GC.KeepAlive(this); return res; } catch (BadImageFormatException ex) { throw PInvokeHelper.CreateException(ex); } } } #endregion #endregion } }
Java
UTF-8
4,001
2.265625
2
[]
no_license
package cn.biggar.biggar.helper; import android.support.v4.app.FragmentActivity; import android.text.TextUtils; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.SPUtils; import com.orhanobut.logger.Logger; import cn.biggar.biggar.api.DataApiFactory; import cn.biggar.biggar.app.Constants; import cn.biggar.biggar.bean.ApkInfoBean; import cn.biggar.biggar.fragment.UpdateDialogFragment; import rx.Subscriber; /** * Created by langgu on 16/5/19. */ public class DownloadManager { private static DownloadManager ourInstance = new DownloadManager(); private boolean isRuning; private DownloadManager() { } public static synchronized DownloadManager getInstance() { return ourInstance; } public void checkUpdate(final FragmentActivity context) { context.runOnUiThread(new Runnable() { @Override public void run() { checkAPI(context); } }); } private synchronized void checkAPI(final FragmentActivity context) { if (isRuning) return; isRuning = true; DataApiFactory.getInstance().createICommonAPI(context.getApplication()).checkApkVersion().subscribe(new Subscriber<ApkInfoBean>() { @Override public void onCompleted() { isRuning = false; } @Override public void onError(Throwable e) { isRuning = false; } @Override public void onNext(ApkInfoBean apkInfoBean) { isRuning = false; int versionCode = AppUtils.getAppVersionCode(); Logger.e("versionCode - " + versionCode + "\napkInfoBean.getVersionCode() - " + apkInfoBean.getVersionCode()); if (apkInfoBean.getVersionCode() > versionCode) { UpdateDialogFragment updateDialogFragment = UpdateDialogFragment.newInstance(apkInfoBean); updateDialogFragment.setCancelable(apkInfoBean.isMust().equals("0")); updateDialogFragment.show(context.getSupportFragmentManager(), null); } //缓存的版本号 int cacheVersionCode = SPUtils.getInstance().getInt(Constants.VERSION_CODE, 0); //当前版本号 int curVersionCode = AppUtils.getAppVersionCode(); //如果缓存的版本号为0,则表示app是全新安装的,需要显示礼物的引导 if (cacheVersionCode == 0) { Logger.e("全新安装的..."); SPUtils.getInstance().put(Constants.IS_SHOULD_SHOW_REDPACKET_GUIDE, "1"); SPUtils.getInstance().put(Constants.VERSION_CODE, curVersionCode); return; } //如果当前版本号 > 缓存的版本号,则表示版本更新了,要判断后台配置是否要显示引导 if (curVersionCode > cacheVersionCode) { String isShouldShowGuide = SPUtils.getInstance().getString(Constants.IS_SHOULD_SHOW_REDPACKET_GUIDE); //如果是否引导表示为空,则表示从来没有进入过引导,或者引导步骤没有走完,要显示引导 if (TextUtils.isEmpty(isShouldShowGuide)){ Logger.e("没有进过引导或者引导并没有完成..."); SPUtils.getInstance().put(Constants.IS_SHOULD_SHOW_REDPACKET_GUIDE, "1"); } //判断后台配置是否要显示引导 else { Logger.e("判断后台配置是否要显示引导..."); SPUtils.getInstance().put(Constants.IS_SHOULD_SHOW_REDPACKET_GUIDE, apkInfoBean.isLoad); } SPUtils.getInstance().put(Constants.VERSION_CODE, curVersionCode); } } }); } }
PHP
UTF-8
1,231
2.75
3
[]
no_license
<?php class Report extends Dbh{ public function displayReports(){ $sql = "SELECT * FROM reports"; $stmt = $this->connect()->query($sql); while ($row = $stmt->fetch()) { echo "<div class='report container'> <h4>Sms id:" .$row['sms_id']. "</h4> <label>Type: Bulk Message</label> <label>Sms delivery Status:".$row['report_sms_status']. "</label> <label>Sms Delivery details:" .$row['report_details']."</label> </div>"; } } public function displaySpecialReports(){ $sql = "SELECT * FROM special_reports"; $stmt = $this->connect()->query($sql); while ($row = $stmt->fetch()) { echo "<div class='report container'> <h4>Sms id:" .$row['sms_id']. "</h4> <label>Type: Special Message</label> <label>Sms delivery Status:".$row['report_sms_status']. "</label> <label>Sms Delivery details:" .$row['report_details']."</label> </div>"; } } }
Python
UTF-8
802
3.328125
3
[]
no_license
#!/usr/bin/env python """ Opens an Apache server error log file and finds the top 25 errors """ # imports import sys from urllib.request import urlopen # URL for testing: "http://icarus.cs.weber.edu/~hvalle/cs3030/data/error.log.test" def help(): print("Usage is: ./riley_curtis_hw6.py <file Input>") def get_errors(url): """ Opens an Apache server error log file and finds the top 25 errors Args: url: url for the log Returns: none """ response = urlopen(url) log = response.read().decode('utf-8').split('\n') i = 0 for line in log: if i < 25: print(line) i += 1 def main(): if len(sys.argv) == 2: get_errors(sys.argv[1]) else: help() if __name__ == '__main__': main() exit(0)
Ruby
UTF-8
1,434
2.515625
3
[]
no_license
class CartsController < ApplicationController def show cart_products = session[:shopping_cart][current_store.id] if cart_products.empty? @shopping_cart = [] else @shopping_cart = cart_products.collect{|k,v| [Product.unscoped.find(k), v]} @order_total = @shopping_cart.reduce(0){|memo,(p,q)|memo+=(p.price*q)} end end def update session[:order_id] = nil product = Product.find(params[:product]) add_to_cart(product.id, params[:quantity]) if params[:quantity] subtract_from_cart(product.id) if params[:subtract] == "1" add_to_cart(product.id) if params[:add] == "1" redirect_to :back, notice: "Cart Updated" end def destroy if params[:remove] product = Product.find(params[:remove]) session[:shopping_cart][current_store.id].delete(product.id) redirect_to carts_path, notice: "Product removed." elsif params[:clear_cart] session[:shopping_cart].delete(current_store.id) redirect_to carts_path, notice: "Cart has been cleared." end end private def subtract_from_cart(id) session[:shopping_cart][current_store.id][id] -= 1 if session[:shopping_cart][current_store.id][id] < 1 session[:shopping_cart][current_store.id].delete(id) end end def add_to_cart(id, quantity="1") session[:shopping_cart][current_store.id][id] += quantity.to_i end end
Java
UTF-8
978
2.375
2
[]
no_license
package com.boa.cashfilm.item.dto; public class Item { private int myItemCode; private String myItemName; private int myItemAmount; private String myItemExpiration; public int getMyItemCode() { return myItemCode; } public void setMyItemCode(int myItemCode) { this.myItemCode = myItemCode; } public String getMyItemName() { return myItemName; } public void setMyItemName(String myItemName) { this.myItemName = myItemName; } public int getMyItemAmount() { return myItemAmount; } public void setMyItemAmount(int myItemAmount) { this.myItemAmount = myItemAmount; } public String getMyItemExpiration() { return myItemExpiration; } public void setMyItemExpiration(String myItemExpiration) { this.myItemExpiration = myItemExpiration; } @Override public String toString() { return "Item [myItemCode=" + myItemCode + ", myItemName=" + myItemName + ", myItemAmount=" + myItemAmount + ", myItemExpiration=" + myItemExpiration + "]"; } }
Markdown
UTF-8
635
2.625
3
[]
no_license
# RiotEfficiencyTester A program for calculating the most efficient spell in the game League of Legends, created by Riot Games. Currently being refactored for style and general improvements due to putting this together in a weekend. In the future, I plan to make this more usable for everyone instead of just my own devices. I plan to use my recent internship at SAS to incorporate this into a Command Line Interface using their more formal REST API Standards. UPDATE 02/2017: Currently attempting to translate this to golang, but since the Riot API is still somewhat primitively broken in some cases, may have to put this on hold.
C#
UTF-8
298
2.9375
3
[]
no_license
public static string GetGeneratedQuery(this SqlCommand dbCommand) { var query = dbCommand.CommandTex; foreach (var parameter in dbCommand.Parameters) { query = query.Replace(parameter.ParameterName, parameter.Value.ToString()); } return query; }
Markdown
UTF-8
3,506
2.859375
3
[]
no_license
--- id: hubs-cloud-aws-quick-start title: AWS Quick Start sidebar_label: AWS Quick Start --- ## Before creating the Hubs Cloud Stack 1. Create an account on AWS and log into the console. 2. Register or setup any domains in AWS Route 53, you'll need at least 2 domains. For example: `myhub.com` and `myhub.link`. See [Domain Recipes](./hubs-cloud-aws-domain-recipes.md) for more info. 3. Review relevant docs: - [Why use Hubs Cloud vs. hubs.mozilla.com?](./hubs-cloud-faq.md#why-use-hubs-cloud-vs-hubsmozillacom) - [Personal vs. Enterprise](./hubs-cloud-faq.md#personal-vs-enterprise) - [Cost Information](./hubs-cloud-aws-costs.md) 4. Create an SSH keypair to access your servers - [Follow AWS guide to create the SSH keypair in your deployment region](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#having-ec2-create-your-key-pair) - Deployment region is in the upper right corner with your username and support - Save the private key using preferred format ## Deploy your Hubs Cloud Stack If you'd prefer a video tutorial, follow along to [Setting Up Hubs Cloud](https://www.youtube.com/watch?v=MyGJ0s4XjTA) deploying your stack. 1. Go to https://hubs.mozilla.com/cloud and choose which Hubs Cloud product to deploy 2. Click **"Continue to Subscribe"** on Hubs Cloud Personal AWS Marketplace page 3. Click **"Continue to Configuration"** 4. Select your desired **"Region"** - For Enterprise select your desired **"Delivery Method"**: - **"Multi-server"** - **"Single Server"** - Then your desired **"Region"** 5. Click **"Continue to Launch"** 6. Change **"Select a launch action"** dropdown to **"Launch CloudFormation"** then click **"Launch"** 7. Select **"Next"** in bottom right corner of the **"Create stack"** or **"Specify template"** page 8. In specify stack details: - Name your stack, something like: **"your-hub-name-1"** - Account Configuration Administrator Email Address - NO CAPITALIZED LETTERS - The admin for your hub - For these parameters use [Domain Recipes](./hubs-cloud-aws-domain-recipes.md) for guidance: `Site Domain Name`, `Site is Set Up On Route 53`, `Internal Domain`, `Short Link Domain`, `Outgoing Email Domain`, and `Outgoing Email Subdomain Prefix` - Double check for no typos! - Choose your `KeyPair` from Before Creating the Stack: Step 4 - If you are using an existing domain not on AWS Route 53, you'll need to perform a few extra steps - See [Using an existing domain](./hubs-cloud-aws-existing-domain.md) - Choose a setting for `Restrict SSH Access` - Review the other options, or keep the defaults. You can update most of these later via a [Stack Update](./hubs-cloud-aws-updating-the-stack.md) 9. Select **"Next"** 10. Agree to Terms of Service checkboxes 11. Wait 20-30 minutes for the stack to complete deploying - Any issues? Check out [AWS Troubleshooting](./hubs-cloud-aws-troubleshooting.md) for solutions to common problems. 12. Confirm your `Administrator Email Address` in your inbox, it will be confirming your email in **N. Virginia** 13. After stack is created, hit your site at your primary domain, wait 20 to 30 seconds 14. Login with your `Administrator Email Address` 15. Proceed with the setup process. Documentation can be found in the [Getting Started with Hubs Cloud](./hubs-cloud-getting-started.md) guide. **Any issues deploying?** Check out [AWS Troubleshooting](./hubs-cloud-aws-troubleshooting.md) for solutions to common problems.
Java
UTF-8
1,851
2.375
2
[]
no_license
package example.jianghao.mvp.model; import android.util.Log; import java.util.ArrayList; import java.util.List; import example.jianghao.mvp.R; import example.jianghao.mvp.bean.GirlBean; /** * girl model implementation v2. * Created by jianghao on 2017/7/29. */ public class GirlModelImplV2 implements IGirlModel { @Override public void loadGirl(OnLoadListener listener) { //模拟从网络加载 Log.d("mvp", "load from internet"); List<GirlBean> data = new ArrayList<>(); data.add(new GirlBean(R.mipmap.girl_1, "美女一号", "这是第一个美女--这是第一个美女--这是第一个美女")); data.add(new GirlBean(R.mipmap.girl_2, "美女二号", "这是第二个美女--这是第二个美女--这是第二个美女")); data.add(new GirlBean(R.mipmap.girl_3, "美女三号", "这是第三个美女--这是第三个美女--这是第三个美女")); data.add(new GirlBean(R.mipmap.girl_1, "美女一号", "这是第一个美女--这是第一个美女--这是第一个美女")); data.add(new GirlBean(R.mipmap.girl_2, "美女二号", "这是第二个美女--这是第二个美女--这是第二个美女")); data.add(new GirlBean(R.mipmap.girl_3, "美女三号", "这是第三个美女--这是第三个美女--这是第三个美女")); data.add(new GirlBean(R.mipmap.girl_1, "美女一号", "这是第一个美女--这是第一个美女--这是第一个美女")); data.add(new GirlBean(R.mipmap.girl_2, "美女二号", "这是第二个美女--这是第二个美女--这是第二个美女")); data.add(new GirlBean(R.mipmap.girl_3, "美女三号", "这是第三个美女--这是第三个美女--这是第三个美女")); listener.onComplete(data); } @Override public void run(OnRunListener listener) { } }
PHP
UTF-8
3,242
2.828125
3
[]
no_license
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Filter * @subpackage Zend_Filter_Builder * @copyright 2007 Bryce Lohr (blohr@gearheadsoftware.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * Zend Filter Builder FluentAdder * * Special-purpose class that facilitates adding Filters through the fluent * Facade. */ class Zend_Filter_Builder_FluentAdder { /** * The Builder object being facaded * * @var Zend_Filter_Builder */ protected $_builder; /** * Factory object to use to create filter instances * * @var Zend_Filter_Builder_FilterFactory_Interface */ protected $_factory; /** * The field or fields we're adding Filters to * * @var string|array */ protected $_fieldSpec; /** * Field flags to set on each added filter * * @var int */ protected $_flags; /** * List of the filter indexes in the Builder that were added by this * FluentAdder. Useful if we needed to go back and set flags for any of the * added fields. * * @var array */ protected $_rowIds; /** * Constructor * * @param Zend_Filter_Builder * @param Zend_Filter_Builder_FilterFactory_Interface Factory object * that can create filters * @param string|array Field name(s) * @param int Field flags, defaults to none * @returns void * @throws Zend_Filter_Exception */ public function __construct(Zend_Filter_Builder $builder, Zend_Filter_Builder_FilterFactory_Interface $factory, $fieldSpec, $flags = 0) { if (empty($fieldSpec)) { require_once 'Zend/Filter/Exception.php'; throw new Zend_Filter_Exception('The field specification parameter is required'); } $this->_builder = $builder; $this->_factory = $factory; $this->_fieldSpec = $fieldSpec; $this->_flags = $flags; $this->_rowIds = array(); } /** * Call magic method * * Maps the method call to a filter name and adds that filter to the * Builder object. * * @param string Base name of the filter * @param array Constructor arguments * @returns Zend_Filter_Builder_FluentAdder * @throws none */ public function __call($name, $args) { $this->_rowIds[] = $this->_builder->add( $this->_factory->create($name, $args), $this->_fieldSpec, $this->_flags ); return $this; } }
PHP
UTF-8
767
2.546875
3
[]
no_license
<?php namespace Admin\Model; use Think\Model; class UserModel extends Model{ protected $tableName = "admin_user"; public function getUser($data){ $where['uname']=$data; $user = $this->where($where)->find(); if($user){ return $user; }else{ return false; } } public function setUser($w,$d){ $where['uname']=$w; $data['upwd']=md5(md5($d)); $result = $this->where($where)->save($data); if($result){ return true; }else{ return false; } } public function createUser($d){ $result = $this->add($d); if($result){ return true; }else{ return false; } } }
Markdown
UTF-8
19,396
3.5
4
[]
no_license
# javascript ### js能干什么(生机活力、强大) 1、进行数据验证(是否符合格式) 2、操作dom元素:内容、样式、属性 3、动态的创建、删除元素 4、动画 5、cookie()、本地存储 6、ajax(动态获取数据) .... # js组成 ### ECMAScript > 基础语法:变量、数据类型、运算符、代码执行流程、函数、对象 ### BOM(browser object model) > 地址(url)、历史记录、DOM、屏幕、 ### DOM(document object model) > 节点、 ## 引入方式 1、嵌入式:通过script标签写到任意位置 ​ 弹出警示窗口:alert(1);/alert(‘张三’);/alert(“a”); ​ 控制台输出:console.log(1);/console.log('张三');/console.log(“a”); ​ 写在页面:document.write(1);/document.write('张三');(括号里面写文字字母都行)/document.write(“a”);(括号里面写文字字母都行) ```HTML <script> // alert(1); // alert('张三'); // alert("a"); // console.log(1); // console.log('张三'); document.write('张三'); </script> ``` 2、通过外部js文件引入 //index.html ```HTML <script src='index.js'></script> ``` //index.js #### 注意事项 1、可以引入多个JS文件、js文件整体,相互联系相互影响相互作用 ```HTML <script src='index.js'></script> <script> alert(1); </script> ``` 2、外部js文件中不允许写script标签对 3、如果引入外部js文件script标签对中间不允许出现js代码 ```HTML <script src='index.js'> alert(1); </script>× ``` ## 调试工具 alert(); console.log(); document.write(); ## js特点 基于对象和事件驱动的松散型解释性语言。 松散型(弱类型):没有规矩、不严谨 > 变量声明(var)、加不加分号都行、 基于对象:一切对象; ## 变量 存储数据的一个容器 ### 变量声明 > var 变量的名 > > > 由数字、字母、下划线、$符号组成;单独的数字不行,数字不能开头;不能用关键字声明变量;保留字不用;区分大小写;有意义;遵循规则:首字母大写、驼峰命名; ```HTML 先声明后赋值 <secript> var a=1; alert(1); </secript> ``` ```HTML 声明的同时进行赋值 <secript> var a; a=1; alert(1); </secript> ``` 一次性声明多个变量,然后再赋值 ```HTML var zhangsan lisi wangwu zhangsan=1; lisi=3; wangwu=5; ``` 一次性声明多个变量,同时进行赋值 ```HTML var a=1;b=3;c=5; ``` ##### 变量注意事项 1、变量值修改; 2、变量允许重复声明同一个变量; > 如果不给新的变量赋值,用的还是原来的值;若给新的变量赋值,新值会覆盖旧值。 3、声明变量需要var去修饰; > 如果没用var修饰并且也没有赋值,会**报错**; > > 如果没用var修饰并且赋值,变成全局变量(不推荐); 4、变量声明没有赋值,默认值undefined。赋值之前调用默认值undefined. ### 数据类型 根据在内存中存储的位置 ##### 初始数据类型(栈区:数据简单,读取快,信息少) 1、undefined 2、number 3、string 4、null 5、boolean ##### 复合数据类型(堆区:数据复杂,读取慢,信息多) object #### 检测数据类型 typeof(variable) typeof variable | 数据类型 | 值 | typeof | | :-------: | :---------------------------: | :-------: | | undefined | undefined | undefined | | boolean | true/false | boolean | | null | null(空 什么都没有) | object | | number | 数字、十进制、十六进制、二进制、八进制、特殊值 | number | | string | 通过‘单引号’“双引号”包裹起来就是字符串(数字、字符、) | string | | object | 属性和方法的无序集合 | object | 二进制:0b; 八进制:0o; 十六进制:0x; 最大值:number.MAX-VALUE; 最小值:number.MIN-VALUE; **如何操作数据** #### **运算符** **1、算术运算符**:+(1、加法运算两边都是数字 2、拼接如果有字符串(括号可以改变优先级))、—、×、÷ 、%(取余数,得到某一范围之内的数)、++(1、var++先运算后自增 2、++var先自增后参与运算 3、undefined+数字=NAN(NOT A NUMBER)4、常量不能进行++ )、——、 在字符串中\为转义字符 | 代码 | 输出 | 代码 | 输出 | | ---- | :--- | ---- | ---- | | \' | 单引号 | ... | 拆分元素 | | \" | 双引号 | | | | \& | 和号 | | | | \\ | 反斜杠 | | | | \n | 换行符 | | | | \r | 回车符 | | | | \t | 制表符 | | | | \b | 退格符 | | | | \f | 换页符 | | | **注**:其中反双点:不需要拼接,数字加字符中间加上${数字} **2、赋值运算符:**=、+=、-=、*=、/=、%=、 > **a=a+5 相当于 a+=5** > > **给定 *x=10* 和 *y=5*,下面的表格解释了赋值运算符:** | 运算符 | 例子 | 等价于 | 结果 | | :--- | :--- | :---- | :--- | | = | x=y | | x=5 | | += | x+=y | x=x+y | x=15 | | -= | x-=y | x=x-y | x=5 | | *= | x*=y | x=x*y | x=50 | | /= | x/=y | x=x/y | x=2 | | %= | x%=y | x=x%y | x=0 | **3、关系(比较)运算符**:>、<、>=、<=、==(等于)、===(全等)、!=(不等)、!==(完全不等于) 关系运算符运算结果是boolean **注意**:1、一个等于号相当于赋值,两个等于号是等于; ​ 2、两个等于号比较的是数值; ​ 3、三个等于号比较的是数值和数据类型; ​ 4、字符串(其中只有数字)与数字比较时,字符串当数字,然后进行比较大小; 5、字符串中要是有字母不能转换成数字,不能与数字进行比较大小,返回NAN,整个表达式返回false, ‘ture’字符串不能转化; 6、两个字符串比较,比较字符串首字符的ASCLL码值,ASCLL码值大的所在字符串就大;若第一个相等,需比较第二个字符串;以此类推,依次比较; ​ 7、数字和布尔值,true>=1,fales<=0; ​ 8、undefined与null相等,但不完全相等; **4、逻辑运算符:**&&(与)、||(或)、!(非) 假值:false、0、null、undefined、NAN &&(与逻辑):全部为真,返回值则为真;反之则为假; ||(或逻辑):有一个为真,返回值则为真;全部为假,返回值为假; 注意:1、逻辑运算值返回值并不一定是boolean; ​ 2、a、当console.log(num>10 && num1),如果两个都是真的值时,返回值为后边值(最后一个)num1 ​ b、当console.log(num>10 && num1),如果两个中有一个假的值时,返回值为假的值 ​ 如果两个值都是假的,返回值为前边(第一个)的值 ​ 3、当console.log(undefined && num++);如果假值在前面时,后面是真值时,后边num++不执行 ​ console.log(num); //num=num ​ 当console.log(num++&& undefined );如果假值在后面时,前面是真值时,前边num++执行 ​ console.log(num) ;//num=(num++) ​ 4、a、当console.log(num || num1),如果两个都是假的值时,返回值为前边值(第一个)num ​ b、当console.log(num || num1),如果两个中有一个真的值时,返回值为真的值 ​ 如果两个值都是真的,返回值为前边(第一个)的值 ​ 5、当console.log(undefined || num++);如果假值在前面时,后边是真值,后边num++执行 ​ console.log(num); //num=(num++) ​ 当console.log(num1|| num++ );如果两个都为真值,后边真值不执行,返回值为第一个值 ​ console.log(num); //num=num 三元表达式 #### 一些关键词 > new用来创建对象; > delete用来删除对象的属性和方法; > ±10加减号代表正负号表示; > ()调用函数; >,逗号一次声明多个变量的时候分隔; > ...[] ### 执行流程 #### 顺序结构 #### 分支结构(选择结构)(不要有重复) ##### 单路分支: ```HTML var num=10; if(num>0){ alert(1); } ``` ##### 双路分支: if(条件){ //条件成立执行的代码 }else{ //条件不成立执行的代码 } ```HTML var num=10; if(num>0){ alert(true); }else{ alert(false); } ``` ##### 多路分支: if(条件){ }else if(条件){ }else if(条件){ }else{ //上述条件都不满足,执行 } ```HTML var score=prompt('请输入你的成绩',90); if(score>=90 && score<=100){ alert('优秀') }else if(score>=80 && score<90){ alert('良好') }else if(score>=70 && score<80){ alert('中等') }else if(score>=60 && score<70){ alert('及格') }else if(score>=0 && score<60){ alert('不及格') }else{ alert('输入错误') } ``` ##### 嵌套分支(在一个支路中嵌套一个分支) > **条件是一个范围(if)。条件是定值,情况可数,优先考虑switch** ##### switch用法 switch(值){ case 情况1: 代码; break; case 情况2: 代码; break; case 情况3: 代码; break; default; } break来阻止代码自动地向下一个case运行 ```HTML var week=prompt('请输入你的星期')*1; switch(week){ case 1: alert('一组'); break; case 2: alert('二组'); break; case 3: alert('三组'); break; case 4: alert('四组'); break; case 5: alert('五组'); break; case 6: alert('六组'); break; case 7: alert('七组'); break; default: alert('输入错误'); } ``` #### 循环结构 ##### 在满足条件的情况下,不停的执行某一段代码。 ```HTML for(var i=1;i<11;i++){ alert(1); } ``` ##### 求和 ```HTML var sum=0; for(var i=1;i<11;i++){ sum+=i; } alert(sum); ``` 表格拼接法: ```HTML var table='<table>'; table+='<table>'; for(var i=1;i<=10;i++){ table+='<tr>'; for(var j=1;j<=10;j++){ table+='<td>'+j+'-'+i+'</td>'; } table+='</tr>'; } table+='</table>'; document.write(table); ``` #### 数组: > 存储一系列相同相关的数据的容器 > > **优点**:1、方便管理数据 > > ​ 2、逻辑清晰,代码方便管理维护 > > **创建数组**:var=[]; > > ​ var arrl=new Array[] > > **赋值**:1、声明的同时赋值; > > ```HTML > var arr=[1,2,3,4,5] > ``` > > ​ 2、声明之后赋值 > > ```HTML > var arr=[]; > arr[0]=1,arr[3]=5; > ``` > > **遍历**:for > > ```HTML > for(var i=0;i<arr.length;i++){ > arr[i] > } > ``` > > **通过下标访问:** > > ​ var arr=[1,2,3,4,5]; > > ​ arr[0],arr[1],arr[2] > > > 下标从**0**开始, 最大:arr.length-1 > > 二维最大值 > > ```HTML > var classes=[ > [85,90,70], > [85,92,70], > [85,95,70] > ] > var max=classes[0][0]; > for(var i=1;i<classes.length;i++){ > for(var j=1;j<classes[i].length;j++){ > if(max>classes[i][j]){ > max=classes[i][j]; > } > } > } > console.log(max); > ``` > > 二维数组 > > ```HTML > var classes[ > [85,90,70], > [85,90,70], > [85,90,70] > ] > for(var i=1;i<classes.length;i++){ > for(var j=1;j<classes.length;j++){ > console.log(classes[i][j]); > } > } > ``` > > 去空格案例: > > ```HTML > 第一种方法 > var arr=[1,2,3,,4,5,6,,7,8,9],newarr=[]; > for(var i=0;i<arr.length;i++){ > if(arr[i]!=undefined){ > console.log(newarr[newarr.length]=arr[i]) > } > } > 第二种方法 > var arr=[1,2,3,,4,5,6,,7,8,9],newarr=[]; > for(var i=0;i<arr.length;i++){ > if((typeof arr[i])!='undefined'){ > console.log(newarr[newarr.length]=arr[i]) > } > } > ``` > > **注意**:1、数组元素默认undefined > > ​ 2、数组长度可变 > > ​ 3、数组元素可以任意的数据类型 #### for for(条件初始化;终止条件;变化量){ //循环体 } for(var i=0;i<10;i++){ console.log(i) } #### while(先判断后执行)(如果初始值不满足条件,一次都不执行) ​ while(循环条件){ ​ //循环体 ​ 变化量 ​ } ```HTML var i=1; while(i<=10){ console.log(i); i++; } ``` #### do-while(先执行一次循环体,然后判断条件,如果条件超能力,会继续执行循环体,直到条件不成立,推出循环)(如果初始值不满足条件,执行一次) ​ do{ ​ //循环体; }while(条件) ```HTML do{ sum+=i; i++; }while(i<=10) console.log(sum); ``` **注:**知道循环次数,优先考虑for。知道循环条件,考虑while、do while; #### 跳转 1、continue跳过当前这次循环,如果条件成立,继续执行循环; 2、break终止整个循环; ## 函数(打包、封装、重复调用) 将实现某一个特定功能的代码段封装,能够重复调用 > 优点:1、重复调用new Array > > ​ 2、逻辑结构、清晰 > > ​ 3、维护、开发 ### 1、基本语法声明 #### 格式: 函数名(10,10)(调用函数) 函数体变量->形参(rows,cols)->实参 函数名()(重复几次就调用几次) function 函数名(rows,cols){ ​ 功能代码段 } ```HTML function fnName([形参1],[形参2]){ //函数体 [return] } ``` 可在声明前后调用函数 ### 2、字面量声明 #### 格式: var fn(自变量)=function()(字面量){ ​ alert(1); } ​ fn(); #### 注意: 只能在声明后调用函数 ```HTML var fn=function(){ } ``` ### 3、面向对象 ```HTML new ``` ### 4、调用函数 1、函数名()自变量() 2、事件后面 3、自调用函数 ```HTML (function fn(){ alert(1)' })(); 用括号将自己本身括起来 ``` 注意: *函数名相同,后面的函数覆盖掉原来的函数 *基本语法声明的函数在声明的前后都可调用,以字面量声明的函数只能在赋值之后调用 ### 参数: 动态的去改变函数体内部的变量,函数灵活强大。 #### 形参: 函数定义时,小括号里面的值,形参没有实际的值,接受实参的值。 #### 实参: 函数调用,小括号里面的值,实参给形参传递值。 注意: 1、实参给形参传递值按照先后顺序传递; 2、当形参值比实参多时,多出来的形参值显示undefined; 3、当实参值比形参值多时,多出来的实参值不显示 ```HTML var arr=[1,2,3,4,5,6,7,8]; function fn(arr){ for(var i=1;i<arguments.length;i++){ arr[arr.length]=arguments[i]; } console.log(arr); } fn(arr,'a','b'); ``` ```HTML arr=[13,24,36,47,52,64,75,86,9] function sort(arr,type){ 默认升序:第一种:if(type=undefined){ type='<'; } 第二种:type=type==undefined? '<':type; 第三种:type=type||'<'; if(type=='<'){ sortUP(arr); }else if(type=='>'){ sortDown(arr); } } function sortUp(arr){ for(var i=0;i<arr.length;i++){ for(var j=i+1;j<arr.length;j++){ if(arr[i>arr[j]){ var temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } } function sortDown(arr){ for(var i=0;i<arr.length;i++){ for(var j=i+1;j<arr.length;j++){ if(arr[i>arr[j]){ var temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } } ``` #### arguments 接受所有的实参,是一个对象object,用法和数组差不多,但不是数组,只能在函数内部调用 函数内部自动生成对象,只能函数内部调用,保存了函数调用时实参的信息 默认参数: 参数:传值,传进来的值。不传默认值; 分支 #### 三元表达式 ```HTML ···js type=type==undefined?默认值:type ``` #### 逻辑|| ```HTML ​```js type=type||默认值 ``` #### ES6 ```HTML ··· function fn(type=默认值) ``` #### rest参数 1、剩余参数,(没有形参对应的实参),是一个数组 2、没有剩余参数,空数组 3、rest参数必须在最后 ```HTML fn(arr,a,b,c) function fn(arr,...rest(名字)){ //rest } ``` ```HTML arr=[13,24,36,47,52,64,75,86,9] fn(arr,a,b,c) function fun(arr,...rest){ for(var i=1;i<arr.length;i++){ arr[arr.length]=rest[i] } console.log(arr); } ``` #### 返回值 return(返回、终止函数) 在函数调用地方返回一个值; 终止函数执行,return后面的代码不会执行; 函数的返回值可以是任意的数据类型; 一个函数只有一个返回值,允许写多个return,但只执行一个; 函数返回值只能返回一个; ```HTML arr=[31,22,3,4,15,56,73,82] var ex=exist(arr,5); alert(ex); function exist(arr,value){ for(var i=0;i<arr.length;i++){ if(arr[i]=value){ return true; } } return false; } ``` ## 作用域 变量的作用范围 1、全局作用域(任意):定义在函数最外层;变量不用var去声明; 2、局部作用域(某一个函数):定义在函数内部 #### 环境 *宿主 *执行 *预编译 按照从上到下,script var function 变量名和函数名预先放置内存,记录声明环境 ```HTML var num=20; function aa(){ var num=10; alert(num);//10 function bb(){ alert(num);//10 var num=15; alert(num);//15 } } alert(num);//20 ``` ```HTML function aa(num1,num2){ return num1*num2/num2; } function bb(num1,num2){ return num1*num2-num2; } function cc(num1,num2){ return num1*num2+num2; } function math(num1,num2,fn){ return fn(num1,num2); } var result=math(2,3,bb); console.log(result); ``` ## 回调函数 map:映射 ```HTML arr=[1,2,3,4,5,6,7] var result=map(arr,function(value){ return value*2 }) console.log(result); function map(arr,fn){ var newarr=[]; for(var i=0;i<arr.length;i++){ newarr[newarr.length]=fn(arr[i]) } return newarr; } ``` filter:过滤 ```HTML arr=[1,2,3,4,5,6,7] ar result=filter(arr,function(value){ return value%2==1 }) console.log(result); function map(arr,fn){ var newarr=[]; for(var i=0;i<arr.length;i++){ if(fn(arr[i])){ newarr[newarr.length]=arr[i]; } } return newarr; } ``` some:一些 ```HTML var arr=[1,2,-3,4,5,-6] var result=some(arr,function(value){ return value>0; }) console.log(result) function some(arr,fn){ for(var i=0;i<arr.length;i++){ if(fn(arr[i])){ return true; } } return false; } ``` every:每一个 ```html var arr=[1,4,3,5,-2] var result=every(arr,function(value){ return value>0; }) console.log(result) function every(arr,fn){ for(var i=0;i<arr.length;i++){ if(!fn(arr[i])){ return false; } } return ture; } ``` ## 递归函数 不是循环, 函数自己调用自己本身,必须有临界条件,输出是从下往上, ```HTML fn(1) function fn(num){ if(num<5){ fn(+num) } alert(num); } ``` 地址:浅拷贝 ```HTML var arr=[1,23,4,5] var arr1=arr; arr1[1]='a'; arr[3]='x' console.loge(arr1) console.loge(arr) ``` 传值:深拷贝 ```HTML var arr1=[] for(var i=0;i<rr.lenghht;i++){ arr1[i]=arr[i] } arr[1]='a'; arr[3]='x' console.log(arr1) console.log(arr) ``` # github new responsitory
Python
UTF-8
2,218
2.5625
3
[]
no_license
#!/usr/bin/env python # # This is a script testing all APIs of oandapy # import oandapy import ConfigParser from pprint import pprint from datetime import datetime, timedelta class Trade(): def __init__(self): Config = ConfigParser.ConfigParser() Config.read("./account.txt") self.id = Config.get("account", "id") self.token = Config.get("account", "token") self.instruments = Config.get("forex", "instrument") self.api = oandapy.API(access_token=self.token) def showAccount(self): print "id: " + self.id print "token: " + self.token print "url: " + self.api.api_url def get_accounts(self): all_accounts = self.api.get_accounts() for i in all_accounts["accounts"]: pprint(self.api.get_account(i["accountId"])) def get_instruments(self): print "Available instruments:" pprint(self.api.get_instruments(account_id=self.id)) def get_orders(self): pprint(self.api.get_orders(account_id=self.id)) def get_positions(self): pprint(self.api.get_positions(account_id=self.id)) def get_prices(self): pprint(self.api.get_prices(instruments=self.instruments)) def get_orders(self): pprint(self.api.get_orders(account_id=self.id)) def open_order(self): trade_expire = datetime.utcnow() + timedelta(days=1) trade_expire = trade_expire.isoformat("T") + "Z" self.buy_response = self.api.create_order(self.id, instrument=self.instruments, unit=1, side='buy', type='limit', price=1.15, expiry=trade_expire ) pprint(buy_response) def close_order(self): pprint(self.api.close_order(account_id=self.id, self.buy_response["orderOpened"]["id"])) def get_transactions(self): pprint(self.api.get_transaction_history(account_id=self.id) trade = Trade() #trade.showAccount() #trade.get_accounts() #trade.get_instruments() #trade.get_orders() #trade.get_positions() #trade.get_prices() #trade.get_orders() #trade.open_order() #trade.close_order() #trade.get_transactions()
Java
UTF-8
1,776
2.34375
2
[]
no_license
package com.otta.eventall.Utils; import android.content.Context; import android.content.SharedPreferences; public class ConfidentialDB { static SharedPreferences sharedPreferences; static SharedPreferences.Editor editor; static void Init(Context context) { if (sharedPreferences == null) { sharedPreferences = context.getSharedPreferences("EventAllAppSettings", Context.MODE_PRIVATE); editor = sharedPreferences.edit(); } } public static void save_AccessToken(Context context, String VeryLongToken) { Init(context); editor.putString("AccessToken", VeryLongToken).apply(); } public static String get_AccessToken(Context context) { Init(context); return sharedPreferences.getString("AccessToken" , null); } public static void save_Email(Context context , String EmailAddress){ Init(context); editor.putString("ConfigEmail", EmailAddress).apply(); } public static void save_Password(Context context , String Password){ Init(context); editor.putString("ConfigPassword", Password).apply(); } public static String get_Email(Context context) { Init(context); return sharedPreferences.getString("ConfigEmail" , null); } public static String get_Password(Context context) { Init(context); return sharedPreferences.getString("ConfigPassword" , null); } public static void save_logStatus(Context context , boolean isLoggedIn){ Init(context); editor.putBoolean("loggedIn" , isLoggedIn).apply(); } public static boolean get_logStatus(Context context){ Init(context); return sharedPreferences.getBoolean("loggedIn",false); } }
C#
UTF-8
4,296
3
3
[ "MIT" ]
permissive
using EuclideanGeometryLib.BasicMath.Tuples.Immutable; using EuclideanGeometryLib.BasicMath.Tuples.Mutable; using MeshComposerLib.Geometry.PathsMesh.Space3D; using MeshComposerLib.Geometry.PointsPath.Space3D; namespace MeshComposerLib.Composers { public sealed class YzGridComposer { /// <summary> /// The center point of the grid /// </summary> public MutableTuple3D Center { get; } = new MutableTuple3D(0, 0, 0); /// <summary> /// The size of each grid unit in the Y direction /// </summary> public double YUnitSize { get; set; } = 1.0d; /// <summary> /// The size of each grid unit in the Z direction /// </summary> public double ZUnitSize { get; set; } = 1.0d; /// <summary> /// The number of grid units in the Y direction on each side /// </summary> public int YUnitsCount { get; set; } = 10; /// <summary> /// The number of grid units in the Z direction on each side /// </summary> public int ZUnitsCount { get; set; } = 10; /// <summary> /// The number of grid units in the Y direction on both side /// </summary> public int YUnitTotalCount => 2 * YUnitsCount; /// <summary> /// The number of grid units in the Z direction on both side /// </summary> public int ZUnitTotalCount => 2 * ZUnitsCount; /// <summary> /// The smallest Y coordinate of the grid /// </summary> public double YMin => Center.Y - YUnitSize * YUnitsCount; /// <summary> /// The largest Y coordinate of the grid /// </summary> public double YMax => Center.Y + YUnitSize * YUnitsCount; /// <summary> /// The smallest Z coordinate of the grid /// </summary> public double ZMin => Center.Z - ZUnitSize * ZUnitsCount; /// <summary> /// The largest Z coordinate of the grid /// </summary> public double ZMax => Center.Z + ZUnitSize * ZUnitsCount; /// <summary> /// The lower left corner point of the grid /// </summary> public Tuple3D CornerLowerLeft => new Tuple3D(Center.X, YMin, ZMin); /// <summary> /// The lower right corner point of the grid /// </summary> public Tuple3D CornerLowerRight => new Tuple3D(Center.X, YMax, ZMin); /// <summary> /// The upper left corner point of the grid /// </summary> public Tuple3D CornerUpperLeft => new Tuple3D(Center.X, YMin, ZMax); /// <summary> /// The upper right corner point of the grid /// </summary> public Tuple3D CornerUpperRight => new Tuple3D(Center.X, YMax, ZMax); /// <summary> /// The total length of the grid in the Y direction /// </summary> public double YSize => YUnitTotalCount * YUnitSize; /// <summary> /// The total length of the grid in the Z direction /// </summary> public double ZSize => ZUnitTotalCount * ZUnitSize; /// <summary> /// Create a path mesh from the specs of this grid composer /// </summary> /// <returns></returns> public ListPathsMesh3D ComposeMesh() { var path1 = new ArrayPointsPath3D( CornerLowerLeft, CornerLowerRight ); var path2 = new ArrayPointsPath3D( CornerUpperLeft, CornerUpperRight ); return new ListPathsMesh3D(2, path1, path2); } /// <summary> /// Compose path mesh patch from the specs of this grid composer /// </summary> /// <returns></returns> public TexturedPathsMesh3D ComposeTexturedMesh() { return new TexturedPathsMesh3D( ComposeMesh(), YMin, YMax, ZMin, ZMax ); } } }
JavaScript
UTF-8
8,213
2.953125
3
[]
no_license
//Magic Trie Tree!! class TrieNode { constructor() { this.children = new Map(); this.index = -1; } }; class Trie { constructor() { this.root = new TrieNode(); this.curNode = this.root; this.size = 0; } addWord(word, index) { this.curNode = this.root; for (let i = 0; i < word.length; ++i) { if (!this.curNode.children.has(word[i])) this.curNode.children.set(word[i], new TrieNode()) this.curNode = this.curNode.children.get(word[i]); } this.curNode.index = index; this.size++; } //-1 doesnt exist //0 partial word //1 complete word findWord(word) { this.curNode = this.root; for (let i = 0; i < word.length; ++i) { if (!this.curNode.children.has(word[i])) return -1; this.curNode = this.curNode.children.get(word[i]); } return this.curNode.index >= 0 ? 1 : 0; } getCurIndex() { return this.curNode.index; } getAllPossibleIndex() { let indexList = []; function recursive(curNode) { //Short-curciut if list size is 3 if (indexList.length >= 3) return; if (curNode.index > -1) indexList.push(curNode.index); curNode.children.forEach(recursive); } recursive(this.curNode); return indexList; } } //DOM Objects const pendReqContainer = document.getElementById("pend_req_container"); const allReqContainer = document.getElementById("all_req_container"); const allReimSearch = document.getElementById("all_reim_search"); allReimSearch.addEventListener("input", updateAllReimQuery); const pendReimSearch = document.getElementById("pend_reim_search"); pendReimSearch.addEventListener("input", updatePendReimQuery); //Globals let allReqTrie = new Trie(); let pendReqTrie = new Trie(); let prevPendSearchString = ""; let idToResponse = new Map(); let pendingReims; let allReims; //Helper Functions function getReimInnerHtml(reim, dom_id) { textColor = "u-color-yellow"; statusText = "Pending"; if (reim.status > 0) { textColor = "u-color-green"; statusText = "Approved"; } else if (reim.status < 0) { textColor = "u-color-red"; statusText = "Denied"; } return ` <div id="${dom_id}"> <h2 class="u-margin-bottom-small">Request #${reim.id}</h2> <h3>Amount: ${reim.amount}</h3> <p>${reim.reason}</p> <p class="${textColor}">${statusText}</p> <p class="u-margin-bottom-small">${reim.response}</p> </div> `; } function getPendReimInnerHtml(reim, dom_id) { return ` <div id="pend_reim_child_${dom_id}"> <h2 class="u-margin-bottom-small">Request #${reim.id}</h2> <h3>Amount: ${reim.amount}</h3> <p>${reim.reason}</p> <textarea id="reim_reason_${dom_id}" class="form__textarea" oninput="setResponse(${dom_id})"></textarea> <div class="row"> <div class="col-1-of-2 u-center-text"> <button id="cur_reim_deny_btn_${dom_id}" type="button" onclick="updatePendingReim(${dom_id}, -1)" class="btn btn--red_small">Deny</button> </div> <div class="col-1-of-2 u-center-text"> <button id="cur_reim_approve_btn_${dom_id}" type="button" onclick="updatePendingReim(${dom_id}, 1)" class="btn btn--green_small">Approve</button> </div> </div> </div> `; } function getAllReimInnerHtml(reimRequests, reimHtmlFunc, dom_id) { let finalInnerHTML = ``; let numDisplay = 0; for (let i = 0; i < reimRequests.length; ++i) { //Limit Display to 3 previous requests if (numDisplay >= 3) break; finalInnerHTML += reimHtmlFunc(reimRequests[i], dom_id + i); ++numDisplay; } return finalInnerHTML; } function setDefaultDisplay(containerDOM, reimList, func, dom_id) { let finalInnerHTML = getAllReimInnerHtml(reimList, func, dom_id) if (finalInnerHTML !== "") containerDOM.innerHTML = finalInnerHTML; else containerDOM.innerHTML = `<h3>There are no requests</h3>` } function updateQuery(stringID, reimRequests, domID, trie, reimSearchDOM, reimContainerDOM, getReimFunc) { //Empty Search Query prevPendSearchString = stringID; if (stringID === "") { setDefaultDisplay(reimContainerDOM, reimRequests, getReimFunc, domID); return; } let searchResult = trie.findWord(stringID); //Successful + Partial Trie search if (searchResult >= 0) { let finalInnerHTML = ""; let indices = trie.getAllPossibleIndex(); for (let i = 0; i < indices.length; ++i) { finalInnerHTML += getReimFunc(reimRequests[indices[i]], domID + indices[i]); } reimContainerDOM.innerHTML = finalInnerHTML; if (searchResult === 1) reimSearchDOM.className = "form__input form__input--found" else reimSearchDOM.className = "form__input"; } //Failed Trie search else { reimContainerDOM.innerHTML = `<h3>No requests match your search query</h3>`; reimSearchDOM.className = "form__input form__input--invalid" } } function updateAllReimQuery(e) { updateQuery(`${e.target.value}`, allReims, "all_reim_child_", allReqTrie, allReimSearch, allReqContainer, getReimInnerHtml); } function updatePendReimQuery(e) { updateQuery(`${e.target.value}`, pendingReims, "", pendReqTrie, pendReimSearch, pendReqContainer, getPendReimInnerHtml); } function setResponse(id) { let value = document.getElementById("reim_reason_" + id).value; idToResponse.set(id, value); } //API Calls async function getAllPendingReim() { const response = await fetch(`http://127.0.0.1:5000/reimbursements/pending`, { method: 'GET', mode: 'cors', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'username': localStorage.getItem("username") }, referrerPolicy: 'no-referrer', }); //Update our page if (response.ok) { pendingReims = await response.json(); for (let i = 0; i < pendingReims.length; ++i) pendReqTrie.addWord(`${pendingReims[i].id}`, i); setDefaultDisplay(pendReqContainer, pendingReims, getPendReimInnerHtml, ""); } } async function getAllReim() { const response = await fetch(`http://127.0.0.1:5000/reimbursements`, { method: 'GET', mode: 'cors', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'username': localStorage.getItem("username") }, referrerPolicy: 'no-referrer', }); //Update our page if (response.ok) { allReims = await response.json(); for (let i = 0; i < allReims.length; ++i) allReqTrie.addWord(`${allReims[i].id}`, i); setDefaultDisplay(allReqContainer, allReims, getReimInnerHtml, "all_reim_child_"); } } async function updatePendingReim(index, status) { reim = pendingReims[index]; res = idToResponse.has(index) ? idToResponse.get(index) : ""; const response = await fetch(`http://127.0.0.1:5000/reimbursements/update/${reim.id}`, { method: 'PUT', mode: 'cors', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'username': localStorage.getItem("username") }, referrerPolicy: 'no-referrer', body: JSON.stringify({ 'amount': reim.amount, 'reason': reim.reason, 'owner': reim.owner, 'status': status, 'response': res }) }); //Update our page if (response.ok) { pendingReims.splice(index, 1); idToResponse.set(index, ""); //console.log("Update display", pendingReims); updateQuery(prevPendSearchString, pendingReims, "", pendReqTrie, pendReimSearch, pendReqContainer, getPendReimInnerHtml); //BUG - All reims also needs to be updated } } getAllPendingReim(); getAllReim();
PHP
UTF-8
22,070
2.578125
3
[]
no_license
<?php function buscarTipoContrato($frmBuscar) { $objResponse = new xajaxResponse(); $valBusq = sprintf("%s|%s", $frmBuscar['lstEmpresaBuscar'], $frmBuscar['txtCriterio']); $objResponse->loadCommands(listaTipoContrato(0, "id_tipo_contrato", "ASC", $valBusq)); return $objResponse; } function cargarLstClaveMovimiento($modoFactura, $idClaveMovimiento = NULL, $idClaveMovimientoDev = NULL){ $objResponse = new xajaxResponse(); if($modoFactura == 1){//FACTURA $filtroTipo = "1"; $filtroTipoDev = "3"; }elseif($modoFactura == 2){//VALE SALIDA $filtroTipo = "5"; $filtroTipoDev = "6"; }else{//ninguno $filtroTipo = "1,5";//que muestre todos los de ingreso $filtroTipoDev = "3,6";//que muestre todos los de devolucion } $sqlClave = sprintf("SELECT id_clave_movimiento, CONCAT_WS(') ', clave, descripcion) AS descripcion FROM pg_clave_movimiento WHERE id_modulo = 4 AND documento_genera IN(%s)", $filtroTipo); $rsClave = mysql_query($sqlClave); if(!$rsClave){ return $objResponse->alert(mysql_error()."\n\nLine:".__LINE__); } while ($row = mysql_fetch_assoc($rsClave)){ $arrayClaveMov[$row['id_clave_movimiento']] = $row['descripcion']; } $sqlClaveDev = sprintf("SELECT id_clave_movimiento, CONCAT_WS(') ', clave, descripcion) AS descripcion FROM pg_clave_movimiento WHERE id_modulo = 4 AND documento_genera IN(%s)", $filtroTipoDev); $rsClaveDev = mysql_query($sqlClaveDev); if(!$rsClaveDev) { return $objResponse->alert(mysql_error()."\n\nLine:".__LINE__); } while ($row2 = mysql_fetch_assoc($rsClaveDev)){ $arrayClaveMovDev[$row2['id_clave_movimiento']] = $row2['descripcion']; } //compruebo que la guardada este en el listado, sino es porque se encuentra mal asignada y debo mostrar completo el listado para que se vea if($idClaveMovimiento != NULL && $idClaveMovimientoDev != NULL){ if(!array_key_exists($idClaveMovimiento, $arrayClaveMov) || !array_key_exists($idClaveMovimientoDev, $arrayClaveMovDev)){ $objResponse->alert("Este tipo de contrato tiene una clave de movimiento que no pertene al modo de factura asigando"); $objResponse->script("xajax_cargarClaveMovimiento('OTROS',".$idClaveMovimiento.",".$idClaveMovimientoDev.");"); return $objResponse; } } $htmlClave .= "<select id=\"lstClaveMovimiento\" name=\"lstClaveMovimiento\" class=\"inputHabilitado\">"; $htmlClave .= "<option value=\"-1\">[ Seleccione ]</option>"; foreach($arrayClaveMov as $idClave => $descripcionClave){ $htmlClave .= "<option value=\"".$idClave."\">".utf8_encode($descripcionClave)."</option>"; } $htmlClave .= "</select>"; $htmlClaveDev .= "<select id=\"lstClaveMovimientoDev\" name=\"lstClaveMovimientoDev\" class=\"inputHabilitado\">"; $htmlClaveDev .= "<option value=\"-1\">[ Seleccione ]</option>"; foreach($arrayClaveMovDev as $idClaveDev => $descripcionClaveDev){ $htmlClaveDev .= "<option value=\"".$idClaveDev."\">".utf8_encode($descripcionClaveDev)."</option>"; } $htmlClaveDev .= "</select>"; $objResponse->assign("tdClaveMovimiento","innerHTML",$htmlClave); $objResponse->assign("tdClaveMovimientoDev","innerHTML",$htmlClaveDev); $objResponse->assign('lstClaveMovimiento','value',$idClaveMovimiento); $objResponse->assign('lstClaveMovimientoDev','value',$idClaveMovimientoDev); return $objResponse; } function cargarLstClaveMovimientoSalidaEntrada($idClaveMovimientoSalida = NULL, $idClaveMovimientoEntrada = NULL){ $objResponse = new xajaxResponse(); $filtroTipoSalida = "4";//que muestre todos los de ingreso $filtroTipoEntrada = "2";//que muestre todos los de devolucion $sqlClaveSalida = sprintf("SELECT id_clave_movimiento, CONCAT_WS(') ', clave, descripcion) AS descripcion FROM pg_clave_movimiento WHERE id_modulo = 4 AND documento_genera = 0 AND tipo IN(%s)", $filtroTipoSalida); $rsClaveSalida = mysql_query($sqlClaveSalida); if(!$rsClaveSalida){ return $objResponse->alert(mysql_error()."\n\nLine:".__LINE__); } while ($row = mysql_fetch_assoc($rsClaveSalida)){ $arrayClaveMovSalida[$row['id_clave_movimiento']] = $row['descripcion']; } $sqlClaveEntrada = sprintf("SELECT id_clave_movimiento, CONCAT_WS(') ', clave, descripcion) AS descripcion FROM pg_clave_movimiento WHERE id_modulo = 4 AND documento_genera = 0 AND tipo IN(%s)", $filtroTipoEntrada); $rsClaveEntrada = mysql_query($sqlClaveEntrada); if(!$rsClaveEntrada) { return $objResponse->alert(mysql_error()."\n\nLine:".__LINE__); } while ($row2 = mysql_fetch_assoc($rsClaveEntrada)){ $arrayClaveMovEntrada[$row2['id_clave_movimiento']] = $row2['descripcion']; } $htmlClaveSalida .= "<select id=\"lstClaveMovimientoSalida\" name=\"lstClaveMovimientoSalida\" class=\"inputHabilitado\">"; $htmlClaveSalida .= "<option value=\"-1\">[ Seleccione ]</option>"; foreach($arrayClaveMovSalida as $id => $descripcion){ $htmlClaveSalida .= "<option value=\"".$id."\">".utf8_encode($descripcion)."</option>"; } $htmlClaveSalida .= "</select>"; $htmlClaveEntrada .= "<select id=\"lstClaveMovimientoEntrada\" name=\"lstClaveMovimientoEntrada\" class=\"inputHabilitado\">"; $htmlClaveEntrada .= "<option value=\"-1\">[ Seleccione ]</option>"; foreach($arrayClaveMovEntrada as $id => $descripcion){ $htmlClaveEntrada .= "<option value=\"".$id."\">".utf8_encode($descripcion)."</option>"; } $htmlClaveEntrada .= "</select>"; $objResponse->assign("tdClaveMovimientoSalida","innerHTML",$htmlClaveSalida); $objResponse->assign("tdClaveMovimientoEntrada","innerHTML",$htmlClaveEntrada); $objResponse->assign('lstClaveMovimientoSalida','value',$idClaveMovimientoSalida); $objResponse->assign('lstClaveMovimientoEntrada','value',$idClaveMovimientoEntrada); return $objResponse; } function cargarListFiltroContrato($idFiltroContrato){ $objResponse = new xajaxResponse(); $sql = sprintf("SELECT id_filtro_contrato, CONCAT_WS('.- ', id_filtro_contrato, descripcion) as descripcion FROM al_filtro_contrato"); $rs = mysql_query($sql); if(!$rs){ return $objResponse->alert(mysql_error()."\n\nLine:".__LINE__); } $html.= "<select id=\"lstFiltroContrato\" name=\"lstFiltroContrato\" class=\"inputHabilitado\">"; $html.= "<option value=\"-1\">[ Seleccione ]</option>"; while($row = mysql_fetch_assoc($rs)){ $selected = ""; if($idFiltroContrato == $row["id_filtro_contrato"]){ $selected = "selected = \"selected\""; } $html.= "<option value=\"".$row["id_filtro_contrato"]."\" ".$selected.">".utf8_encode($row["descripcion"])."</option>"; } $html.= "</select>"; $objResponse->assign("tdListFiltroContrato","innerHTML",$html); return $objResponse; } function eliminarPrecio($idTipoContrato) { $objResponse = new xajaxResponse(); if (!xvalidaAcceso($objResponse,"al_tipos_contrato_list","eliminar")) { return $objResponse; } mysql_query("START TRANSACTION;"); $deleteSQL = sprintf("DELETE FROM al_tipo_contrato WHERE id_tipo_contrato = %s", valTpDato($idTipoContrato, "int")); $Result1 = mysql_query($deleteSQL); if(mysql_errno() == 1451){ return $objResponse->alert("No se puede eliminar porque ya esta en uso"); } if (!$Result1) return $objResponse->alert(mysql_error()."\nError Nro: ".mysql_errno()."\nLine: ".__LINE__); mysql_query("COMMIT;"); $objResponse->script("byId('btnBuscar').click();"); $objResponse->alert("Eliminado Correctamente"); return $objResponse; } function frmTipoContrato($idTipoContrato) { $objResponse = new xajaxResponse(); if ($idTipoContrato > 0) { if (!xvalidaAcceso($objResponse,"al_tipos_contrato_list","editar")) { usleep(0.5 * 1000000); $objResponse->script("byId('btnCancelarTipoContrato').click();"); return $objResponse; } $query = sprintf("SELECT * FROM al_tipo_contrato WHERE id_tipo_contrato = %s;", valTpDato($idTipoContrato, "int")); $rs = mysql_query($query); if (!$rs) return $objResponse->alert(mysql_error()."\nError Nro: ".mysql_errno()."\nLine: ".__LINE__); $row = mysql_fetch_assoc($rs); $objResponse->assign("hddIdTipoContrato","value",$idTipoContrato); $objResponse->assign("txtNombre","value",utf8_encode($row['nombre_tipo_contrato'])); $objResponse->assign("lstModoFactura","value",$row['modo_factura']); $objResponse->loadCommands(cargaLstEmpresaFinal($row["id_empresa"],"","lstEmpresa")); $objResponse->loadCommands(cargarListFiltroContrato($row["id_filtro_contrato"])); $objResponse->loadCommands(cargarLstClaveMovimiento($row["modo_factura"],$row["id_clave_movimiento"],$row["id_clave_movimiento_dev"])); $objResponse->loadCommands(cargarLstClaveMovimientoSalidaEntrada($row["id_clave_movimiento_salida"],$row["id_clave_movimiento_entrada"])); } else { if (!xvalidaAcceso($objResponse,"al_tipos_contrato_list","insertar")) { usleep(0.5 * 1000000); $objResponse->script("byId('btnCancelarTipoContrato').click();"); return $objResponse; } $objResponse->loadCommands(cargaLstEmpresaFinal($_SESSION["idEmpresaUsuarioSysGts"],"","lstEmpresa")); $objResponse->loadCommands(cargarListFiltroContrato()); $objResponse->loadCommands(cargarLstClaveMovimiento()); $objResponse->loadCommands(cargarLstClaveMovimientoSalidaEntrada()); } return $objResponse; } function guardarTipoContrato($frmTipoContrato) { $objResponse = new xajaxResponse(); mysql_query("START TRANSACTION;"); $idTipoContrato = $frmTipoContrato['hddIdTipoContrato']; if ($idTipoContrato > 0) { if (!xvalidaAcceso($objResponse,"al_tipos_contrato_list","editar")) { return $objResponse; } $updateSQL = sprintf("UPDATE al_tipo_contrato SET nombre_tipo_contrato = %s, id_filtro_contrato = %s, id_clave_movimiento = %s, id_clave_movimiento_dev = %s, id_clave_movimiento_salida = %s, id_clave_movimiento_entrada = %s, modo_factura = %s, id_empresa = %s WHERE id_tipo_contrato = %s;", valTpDato($frmTipoContrato['txtNombre'], "text"), valTpDato($frmTipoContrato['lstFiltroContrato'], "int"), valTpDato($frmTipoContrato['lstClaveMovimiento'], "int"), valTpDato($frmTipoContrato['lstClaveMovimientoDev'], "int"), valTpDato($frmTipoContrato['lstClaveMovimientoSalida'], "int"), valTpDato($frmTipoContrato['lstClaveMovimientoEntrada'], "int"), valTpDato($frmTipoContrato['lstModoFactura'], "int"), valTpDato($frmTipoContrato['lstEmpresa'], "int"), valTpDato($idTipoContrato, "int")); mysql_query("SET NAMES 'utf8'"); $Result1 = mysql_query($updateSQL); if (!$Result1) return $objResponse->alert(mysql_error()."\nError Nro: ".mysql_errno()."\nLine: ".__LINE__); mysql_query("SET NAMES 'latin1';"); } else { if (!xvalidaAcceso($objResponse,"al_tipos_contrato_list","insertar")) { return $objResponse; } $insertSQL = sprintf("INSERT INTO al_tipo_contrato (nombre_tipo_contrato, id_filtro_contrato, id_clave_movimiento, id_clave_movimiento_dev, id_clave_movimiento_salida, id_clave_movimiento_entrada, modo_factura, id_empresa) VALUE (%s, %s, %s, %s, %s, %s, %s, %s);", valTpDato($frmTipoContrato['txtNombre'], "text"), valTpDato($frmTipoContrato['lstFiltroContrato'], "int"), valTpDato($frmTipoContrato['lstClaveMovimiento'], "int"), valTpDato($frmTipoContrato['lstClaveMovimientoDev'], "int"), valTpDato($frmTipoContrato['lstClaveMovimientoSalida'], "int"), valTpDato($frmTipoContrato['lstClaveMovimientoEntrada'], "int"), valTpDato($frmTipoContrato['lstModoFactura'], "int"), valTpDato($frmTipoContrato['lstEmpresa'], "int")); mysql_query("SET NAMES 'utf8'"); $Result1 = mysql_query($insertSQL); if (!$Result1) return $objResponse->alert(mysql_error()."\nError Nro: ".mysql_errno()."\nLine: ".__LINE__); $idTipoContrato = mysql_insert_id(); mysql_query("SET NAMES 'latin1';"); } mysql_query("COMMIT;"); $objResponse->alert("Guardado correctamente."); $objResponse->script(" byId('btnCancelarTipoContrato').click(); byId('btnBuscar').click();"); return $objResponse; } function listaTipoContrato($pageNum = 0, $campOrd = "id_tipo_contrato", $tpOrd = "ASC", $valBusq = "", $maxRows = 20, $totalRows = NULL) { $objResponse = new xajaxResponse(); $valCadBusq = explode("|", $valBusq); $startRow = $pageNum * $maxRows; if ($valCadBusq[0] != "-1" && $valCadBusq[0] != "") { $cond = (strlen($sqlBusq) > 0) ? " AND " : " WHERE "; $sqlBusq .= $cond.sprintf("tipo_contrato.id_empresa = %s", valTpDato($valCadBusq[0], "int")); } if ($valCadBusq[1] != "-1" && $valCadBusq[1] != "") { $cond = (strlen($sqlBusq) > 0) ? " AND " : " WHERE "; $sqlBusq .= $cond.sprintf("(nombre_tipo_contrato LIKE %s)", valTpDato("%".$valCadBusq[1]."%", "text")); } $query = sprintf("SELECT tipo_contrato.id_tipo_contrato, tipo_contrato.id_empresa, tipo_contrato.nombre_tipo_contrato, tipo_contrato.id_filtro_contrato, tipo_contrato.id_clave_movimiento, tipo_contrato.id_clave_movimiento_dev, (CASE tipo_contrato.modo_factura WHEN 1 THEN 'FACTURA' WHEN 2 THEN 'VALE SALIDA' END) AS descripcion_modo_factura, empresa.nombre_empresa, CONCAT_WS(') ', clave_mov.clave, clave_mov.descripcion) AS descripcion_clave_mov, CONCAT_WS(') ', clave_mov_dev.clave, clave_mov_dev.descripcion) AS descripcion_clave_mov_dev, CONCAT_WS(') ', clave_mov_salida.clave, clave_mov_salida.descripcion) AS descripcion_clave_mov_salida, CONCAT_WS(') ', clave_mov_entrada.clave, clave_mov_entrada.descripcion) AS descripcion_clave_mov_entrada, CONCAT_WS('.- ', filtro_contrato.id_filtro_contrato, filtro_contrato.descripcion) AS descripcion_filtro FROM al_tipo_contrato tipo_contrato INNER JOIN pg_empresa empresa ON tipo_contrato.id_empresa = empresa.id_empresa LEFT JOIN al_filtro_contrato filtro_contrato ON filtro_contrato.id_filtro_contrato = tipo_contrato.id_filtro_contrato LEFT JOIN pg_clave_movimiento clave_mov ON tipo_contrato.id_clave_movimiento = clave_mov.id_clave_movimiento LEFT JOIN pg_clave_movimiento clave_mov_dev ON tipo_contrato.id_clave_movimiento_dev = clave_mov_dev.id_clave_movimiento LEFT JOIN pg_clave_movimiento clave_mov_salida ON tipo_contrato.id_clave_movimiento_salida = clave_mov_salida.id_clave_movimiento LEFT JOIN pg_clave_movimiento clave_mov_entrada ON tipo_contrato.id_clave_movimiento_entrada = clave_mov_entrada.id_clave_movimiento %s", $sqlBusq); $sqlOrd = ($campOrd != "") ? sprintf(" ORDER BY %s %s", $campOrd, $tpOrd) : ""; $queryLimit = sprintf("%s %s LIMIT %d OFFSET %d", $query, $sqlOrd, $maxRows, $startRow); $rsLimit = mysql_query($queryLimit); if (!$rsLimit) return $objResponse->alert(mysql_error()."\nError Nro: ".mysql_errno()."\nLine: ".__LINE__); if ($totalRows == NULL) { $rs = mysql_query($query); if (!$rs) return $objResponse->alert(mysql_error()."\nError Nro: ".mysql_errno()."\nLine: ".__LINE__); $totalRows = mysql_num_rows($rs); } $totalPages = ceil($totalRows/$maxRows)-1; $htmlTblIni = "<table border=\"0\" width=\"100%\">"; $htmlTh .= "<tr class=\"tituloColumna\">"; $htmlTh .= ordenarCampo("xajax_listaTipoContrato", "1%", $pageNum, "id_tipo_contrato", $campOrd, $tpOrd, $valBusq, $maxRows, "id"); $htmlTh .= ordenarCampo("xajax_listaTipoContrato", "10%", $pageNum, "nombre_empresa", $campOrd, $tpOrd, $valBusq, $maxRows, "Empresa"); $htmlTh .= ordenarCampo("xajax_listaTipoContrato", "10%", $pageNum, "nombre_tipo_contrato", $campOrd, $tpOrd, $valBusq, $maxRows, "Nombre"); $htmlTh .= ordenarCampo("xajax_listaTipoContrato", "5%", $pageNum, "descripcion_modo_factura", $campOrd, $tpOrd, $valBusq, $maxRows, "Modo Factura"); $htmlTh .= ordenarCampo("xajax_listaTipoContrato", "15%", $pageNum, "descripcion_clave_mov", $campOrd, $tpOrd, $valBusq, $maxRows, "Clave Mov"); $htmlTh .= ordenarCampo("xajax_listaTipoContrato", "15%", $pageNum, "descripcion_clave_mov_dev", $campOrd, $tpOrd, $valBusq, $maxRows, "Clave Mov Dev"); $htmlTh .= ordenarCampo("xajax_listaTipoContrato", "15%", $pageNum, "descripcion_clave_mov_salida", $campOrd, $tpOrd, $valBusq, $maxRows, "Clave Mov Salida"); $htmlTh .= ordenarCampo("xajax_listaTipoContrato", "15%", $pageNum, "descripcion_clave_mov_entrada", $campOrd, $tpOrd, $valBusq, $maxRows, "Clave Mov Entrada"); $htmlTh .= ordenarCampo("xajax_listaTipoContrato", "10%", $pageNum, "descripcion_filtro", $campOrd, $tpOrd, $valBusq, $maxRows, "Filtro"); $htmlTh .= "<td colspan=\"2\" width=\"1%\"></td>"; $htmlTh .= "</tr>"; while ($row = mysql_fetch_assoc($rsLimit)) { $clase = (fmod($contFila, 2) == 0) ? "trResaltar4" : "trResaltar5"; $contFila ++; $htmlTb .= "<tr align=\"left\" class=\"".$clase."\" height=\"24\">"; $htmlTb .= "<td align=\"center\">".$row['id_tipo_contrato']."</td>"; $htmlTb .= "<td>".utf8_encode($row['nombre_empresa'])."</td>"; $htmlTb .= "<td align=\"center\">".utf8_encode($row['nombre_tipo_contrato'])."</td>"; $htmlTb .= "<td align=\"center\">".utf8_encode($row['descripcion_modo_factura'])."</td>"; $htmlTb .= "<td>".utf8_encode($row['descripcion_clave_mov'])."</td>"; $htmlTb .= "<td>".utf8_encode($row['descripcion_clave_mov_dev'])."</td>"; $htmlTb .= "<td>".utf8_encode($row['descripcion_clave_mov_salida'])."</td>"; $htmlTb .= "<td>".utf8_encode($row['descripcion_clave_mov_entrada'])."</td>"; $htmlTb .= "<td align=\"center\">".utf8_encode($row['descripcion_filtro'])."</td>"; $htmlTb .= "<td>"; $htmlTb .= sprintf("<a class=\"modalImg\" id=\"aEditar%s\" rel=\"#divFlotante1\" onclick=\"abrirDivFlotante1(this, 'tblTipoContrato', '%s');\"><img class=\"puntero\" src=\"../img/iconos/pencil.png\" title=\"Editar\"/></a>", $contFila, $row['id_tipo_contrato']); $htmlTb .= "</td>"; $htmlTb .= "<td>"; $htmlTb .= sprintf("<a onclick=\"validarEliminar('%s');\"><img class=\"puntero\" src=\"../img/iconos/cross.png\" title=\"Eliminar\"/></a>", $row['id_tipo_contrato']); $htmlTb .= "</td>"; $htmlTb .= "</tr>"; } $htmlTf = "<tr>"; $htmlTf .= "<td align=\"center\" colspan=\"30\">"; $htmlTf .= "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">"; $htmlTf .= "<tr class=\"tituloCampo\">"; $htmlTf .= "<td align=\"right\" class=\"textoNegrita_10px\">"; $htmlTf .= sprintf("Mostrando %s de %s Registros&nbsp;", $contFila, $totalRows); $htmlTf .= "<input name=\"valBusq\" id=\"valBusq\" type=\"hidden\" value=\"".$valBusq."\"/>"; $htmlTf .= "<input name=\"campOrd\" id=\"campOrd\" type=\"hidden\" value=\"".$campOrd."\"/>"; $htmlTf .= "<input name=\"tpOrd\" id=\"tpOrd\" type=\"hidden\" value=\"".$tpOrd."\"/>"; $htmlTf .= "</td>"; $htmlTf .= "<td align=\"center\" class=\"tituloColumna\" width=\"210\">"; $htmlTf .= "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"; $htmlTf .= "<tr align=\"center\">"; $htmlTf .= "<td width=\"25\">"; if ($pageNum > 0) { $htmlTf .= sprintf("<a class=\"puntero\" onclick=\"xajax_listaTipoContrato(%s,'%s','%s','%s',%s);\">%s</a>", 0, $campOrd, $tpOrd, $valBusq, $maxRows, "<img src=\"../img/iconos/ico_reg_pri_al.gif\"/>"); } $htmlTf .= "</td>"; $htmlTf .= "<td width=\"25\">"; if ($pageNum > 0) { $htmlTf .= sprintf("<a class=\"puntero\" onclick=\"xajax_listaTipoContrato(%s,'%s','%s','%s',%s);\">%s</a>", max(0, $pageNum - 1), $campOrd, $tpOrd, $valBusq, $maxRows, "<img src=\"../img/iconos/ico_reg_ant_al.gif\"/>"); } $htmlTf .= "</td>"; $htmlTf .= "<td width=\"100\">"; $htmlTf .= sprintf("<select id=\"pageNum\" name=\"pageNum\" onchange=\"xajax_listaTipoContrato(%s,'%s','%s','%s',%s)\">", "this.value", $campOrd, $tpOrd, $valBusq, $maxRows); for ($nroPag = 0; $nroPag <= $totalPages; $nroPag++) { $htmlTf .= "<option value=\"".$nroPag."\"".(($pageNum == $nroPag) ? "selected=\"selected\"" : "").">".($nroPag + 1)." / ".($totalPages + 1)."</option>"; } $htmlTf .= "</select>"; $htmlTf .= "</td>"; $htmlTf .= "<td width=\"25\">"; if ($pageNum < $totalPages) { $htmlTf .= sprintf("<a class=\"puntero\" onclick=\"xajax_listaTipoContrato(%s,'%s','%s','%s',%s);\">%s</a>", min($totalPages, $pageNum + 1), $campOrd, $tpOrd, $valBusq, $maxRows, "<img src=\"../img/iconos/ico_reg_sig_al.gif\"/>"); } $htmlTf .= "</td>"; $htmlTf .= "<td width=\"25\">"; if ($pageNum < $totalPages) { $htmlTf .= sprintf("<a class=\"puntero\" onclick=\"xajax_listaTipoContrato(%s,'%s','%s','%s',%s);\">%s</a>", $totalPages, $campOrd, $tpOrd, $valBusq, $maxRows, "<img src=\"../img/iconos/ico_reg_ult_al.gif\"/>"); } $htmlTf .= "</td>"; $htmlTf .= "</tr>"; $htmlTf .= "</table>"; $htmlTf .= "</td>"; $htmlTf .= "</tr>"; $htmlTf .= "</table>"; $htmlTf .= "</td>"; $htmlTf .= "</tr>"; $htmlTblFin = "</table>"; if (!($totalRows > 0)) { $htmlTb .= "<td colspan=\"30\">"; $htmlTb .= "<table cellpadding=\"0\" cellspacing=\"0\" class=\"divMsjError\" width=\"100%\">"; $htmlTb .= "<tr>"; $htmlTb .= "<td width=\"25\"><img src=\"../img/iconos/ico_fallido.gif\" width=\"25\"/></td>"; $htmlTb .= "<td align=\"center\">No se encontraron registros</td>"; $htmlTb .= "</tr>"; $htmlTb .= "</table>"; $htmlTb .= "</td>"; } $objResponse->assign("divListaTipoContrato","innerHTML",$htmlTblIni.$htmlTf.$htmlTh.$htmlTb.$htmlTf.$htmlTblFin); return $objResponse; } $xajax->register(XAJAX_FUNCTION,"buscarTipoContrato"); $xajax->register(XAJAX_FUNCTION,"cargarLstClaveMovimiento"); $xajax->register(XAJAX_FUNCTION,"cargarLstClaveMovimientoSalidaEntrada"); $xajax->register(XAJAX_FUNCTION,"cargarListFiltroContrato"); $xajax->register(XAJAX_FUNCTION,"eliminarPrecio"); $xajax->register(XAJAX_FUNCTION,"frmTipoContrato"); $xajax->register(XAJAX_FUNCTION,"guardarTipoContrato"); $xajax->register(XAJAX_FUNCTION,"listaTipoContrato"); ?>
Markdown
UTF-8
7,036
2.765625
3
[]
no_license
## DOM (돔) ### 정의 - Document Object Model 그리고 문서 객체 모델이며 HTML 및 XML 문서를 위한 API이다. - 이 DOM이란 트리 구조로 되어있는 객체 모델로써, Javascript가 getElementbyid()를 같은 함수를 이용하여 HTML문서의 각 요소(li, head같은 태그들)들을 접근하고 사용할 수 있도록 하는 객체 모델이다. 브라우저마다 DOM을 구현하는 방식은 다르기에 DOM이라는 것이 구체적으로 정해저 있는 언어나 모델과 같은 것은 아니다. 다만 웹페이지를 객체로 표현한 모델을 의미할 뿐이다. #### DOM 의 트리구조 예시 ![enter image description here](https://miro.medium.com/max/486/1*LA6AXbzvC0IQ_d2H8v3NCw.gif) #### 브라우저가 돔을 이용해서 화면을 렌더링 하는 방법 예시 ![enter image description here](https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&fname=https://blog.kakaocdn.net/dn/cLx0Fj/btqzEC7eCe7/pOWQArZDNwHiQrvrdTDqdk/img.png) **첫째,** 브라우저는 html태그를 파싱 하여 **돔 트리를** 구성한다. **동시에** 브라우저는 스타일시트에서 css를 파싱 하여 **스타일 규칙**들을 만들어낸다. **둘째,** 위에서 언급한 돔 트리와 스타일 규칙 두 가지가 합쳐져서 **렌더 트리를** 만들어낸다. ## VIRTUAL DOM (가상 돔) ## 정의 > A virtual DOM is a lightweight JavaScript representation of the DOM used in declarative web frameworks such as React, Vue.js, and Elm. Updating the virtual DOM is comparatively faster than updating the actual DOM, since nothing has to be rendered onto the screen. *- Wikipedia -* > > 가상돔이란 돔을 가볍게 만든 자바스크립트 표현이라고 할 수 있고 주로 React, Vue.js 그리고 Elm에 사용된다. 가상돔은 실제로 스크린에 랜더링을 하는것이 아니기에 돔을 직접 업데이트 하는것보다 상대적으로 빠르다. ## 필요성및 차이점 ### 돔의 문제 > SPA (Single Page Application)의 출현으로 가상 돔이 매우 필요해졌다. DOM은 트리구조로 되어있어서 이해하기 쉽다는 장점은 있으나, 이 구조는 거대해 질때 속도가 느려지고, DOM 업데이트에 잦은 오류를 야기한다. DOM을 분석하는데에도 힘든 단점이 있다. 그런데 최근 모던 웹은 SPA(Single Page Application) 을 사용한다. 하나의 웹 페이지를 어플리케이션 처럼 구성하는 SPA에서는 HTML 문서 자체가 하나이며, Application이라 칭 할 만큼 여러 동적인 기능(실시간 기능)들이 들어가기 때문에 안그래도 리소스가 모두 합쳐진 HTML 문서를 지속적으로 재 렌더링 해주어야 하는 문제점이 발생하게 되었다. 기존에는 화면의 변경사항을 돔을 직접 조작하여 브라우저에 반영하였다. 하지만, 이 방법의 가장 큰 단점은 돔 트리가 수정될 때마다 렌더 트리가 계속해서 실시간으로 갱신된다는 점이었다. 즉, 화면에서 10개의 수정사항이 발생하면 수정할 때마다 새로운 랜더 트리가 10번 수정되면서 새롭게 만들어지게 되는 것이다. ### 그래서 가상 돔이 출현 - 가상돔(Virtual DOM)은 실제 DOM 문서를 추상화한 개념으로, 변화가 많은 View를 실제 DOM에서 직접 처리하는 방식이 아닌 Virtual Dom과 메모리에서 미리 처리하고 저장한 후 실제 DOM과 동기화 하는 프로그래밍 개념입니다. - 해당 DOM을 컴포넌트 단위로 쪼개어 HTML 컴포넌트 조립품 처럼 다루는 개념이다. 이 조립품들이 VirtualDOM이라 할 수 있다. - Vue, React는 가상 돔 방식을 채택했다. |돔|가상돔| |--|--| |업데이트가 느리다.|업데이트가 빠르다.| |HTML을 직접적으로 업데이트 한다.| HTML을 직접적으로 업데이트 하지 않는다.| |새로운 element가 업데이트 된 경우 새로운 DOM을 생성한다.|새로운 element가 업데이트 된 경우 새로운 가상돔 생성한 후 이전 돔과 비교하여 차이를 계산 이후 돔을 업데이트한다.| |메모리 낭비가 심하다.|메모리 낭비가 덜하다.| **업데이트가 빠른것은 가상돔이 돔보다 빠르다는 표현과는 다르다.* *VDOM의 주목적은 DOM의 직접적 변화의 수를 줄이는데 있고 이 변화가 느린것이다.* ### 아래와 같은 코드 돔은 브라우저가 핸들하여 생성한다. ``` html <ul class="fruits"> <li>Apple</li> <li>Orange</li> <li>Banana</li> </ul> ``` ### Virtual DOM 식으로 표현된 코드 React, Vue 등의 모던 프레임워크가 실제 돔과 비슷한 가상돔을 메모리에 생성한다. ```javascript // Virtual DOM representation { type: "ul", props: { "class": "fruits" }, children: [ { type: "li", props: null, children: [ "Apple" ] }, { type: "li", props: null, children: [ "Orange" ] }, { type: "li", props: null, children: [ "Banana" ] } ] } ``` [출처](https://dev.to/karthikraja34/what-is-virtual-dom-and-why-is-it-faster-14p9) ## 가상돔의 Three Steps 1. 어떠한 데이터의 변화가 일어났을때, 전체 UI가 가상 돔에서 재 랜더링이 된다. ![enter image description here](https://www.edureka.co/blog/wp-content/uploads/2017/08/1dom.png) 2. 이전 돔과 새로운 가상돔의 차이가 계산된다. ![enter image description here](https://www.edureka.co/blog/wp-content/uploads/2017/08/2dom.png) 3. 계산이 끝난 후, 돔은 변경된 부분만을 변화시킨다. ![enter image description here](https://www.edureka.co/blog/wp-content/uploads/2017/08/3dom.png) ### REACT/Vue.js/Angular/Elm 가 사용하는 가상 돔 첫 번째로 가상 돔은 리액트에서 나온 개념이 아니다. 하지만 리액트는 무료로 이 개념을 사용하고 사용자들에게 제공한다. 퍼포먼스와 메모리 관리가 효율적으로 가능하게 되었다. 가상 돔을 활용하면 이러한 불필요한 렌더링 횟수를 줄일 수 있다. 가상 돔을 활용한 대표적인 프런트 앤드 프레임워크가 리액트, 뷰, 앵귤러이다. 이러한 프레임워크들은 화면에 변화가 있을 때마다 실시간으로 돔 트리를 수정하지 않고 변경사항이 모두 반영된 가상 돔을 만들어낸다. 그 후 가상 돔을 이용해 **한 번만 돔수정을 하게 되고 이는 한 번만 렌더 트리를 만들어**내게 된다. 결과적으로 브라우저는 한번만 렌더링을 하게 됨으로써 **불필요한 렌더링 횟수**를 줄일 수 있게 되는 것이다. ![enter image description here](https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&fname=https://blog.kakaocdn.net/dn/bgW4xU/btqzFeLIjMG/yGgjkkr7mnMX9pyVRowywK/img.png) < 추가 링크 > https://bitsofco.de/understanding-the-virtual-dom/
Java
UTF-8
1,125
3.0625
3
[]
no_license
import org.json.JSONObject; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class AccountService { private Map<Integer, Account> accountMap; Integer counter = 1; public AccountService() { counter = 1; accountMap = new HashMap<Integer, Account>(); } public void addAccountToMap(String firstName, String lastName, int accountNumber) { Account newAccount = new Account(firstName, lastName, accountNumber); accountMap.put(counter, newAccount); counter++; } public Account getAccountFromMap(Integer accountToGet) { return accountMap.get(accountToGet); } public JSONObject convertMapToJSON() { return new JSONObject(accountMap); } public int numberOfAccounts(String firstName) { int instances = 0; for(int i=1; i <= accountMap.size(); i++) { String fName = accountMap.get(i).getFirstName(); if(fName.equals(firstName)) { instances++; } } return instances; } }
C++
UTF-8
2,266
3.734375
4
[]
no_license
//including libraries #include<iostream> #include<fstream> #include <stdio.h> #include <string> #include <ctype.h> using namespace std; int sum[10][10]; // result of sum int matrixC[10][10]; // result of multiplication // this function add two matrices if their order are same and stores the result in a global 2D array void sumofmatrix(int first[10][10], int second[10][10], int row1, int col1, int row2, int col2){ int count1 = 0; int count2 = 0; int j = 0; int c1 = 0; int d = 0; if ((row1 == row2) && (col1 == col2)){ for (c1 = 0; c1 <= row1; c1++){ for (d = 0; d <= col1; d++){ sum[c1][d] = first[c1][d] + second[c1][d]; } } cout << "Sum of entered matrices:-\n"; for (c1 = 0; c1 <= row1; c1++) { for (d = 0; d <= col1; d++) cout << sum[c1][d] << "\t"; cout << endl; } } else { cout << "addition is not possible because matrix are not of the same order\n"; } } //This function subtracts two matrices if their order are same void Subofmatrix(int first[10][10], int second[10][10], int row1, int col1, int row2, int col2){ int c1 = 0; int d = 0; int sub[2][2]; if ((row1 == row2) && (col1 == col2)){ for (c1 = 0; c1 < 2; c1++){ for (d = 0; d < 2; d++){ sub[c1][d] = first[c1][d] - second[c1][d]; } } cout << "Sum of entered matrices:-\n"; for (c1 = 0; c1 < 2; c1++) { for (d = 0; d < 2; d++) cout << sub[c1][d] << "\t"; cout << endl; } } else { cout << "addition is not possible because matrices are not of the same order\n"; } } //this function multiply two matrcies if column of first matrix is equal to rows of the second matrix and stores the result in global 2D array void MatrixMultiply(int first[10][10], int second[10][10], int row1, int col1, int row2, int col2) { if (col1 == row2){ for (int i = 0; i <= row1; i++){ for (int j = 0; j <= col2; j++){ matrixC[i][j] = 0; for (int k = 0; k <= col1; k++){ matrixC[i][j] = matrixC[i][j] + (first[i][k] * second[k][j]); } } } cout << "result of matrix multiplication\n"; for (int i = 0; i <= row1; i++){ for (int j = 0; j <= col2; j++){ cout << matrixC[i][j] << " "; } cout << "\n"; } } else cout << "Matrix Multiplication is not possible\n"; }
Java
UTF-8
8,678
1.992188
2
[]
no_license
package jp.co.inte.attendance.controller; import java.text.MessageFormat; import java.util.List; import javax.servlet.http.HttpServletRequest; import jp.co.inte.attendance.common.util.SystemConstant; import jp.co.inte.attendance.entity.EmployGrade; import jp.co.inte.attendance.entity.Useraccount; import jp.co.inte.attendance.exception.MyUniqueConstraintException; import jp.co.inte.attendance.exception.MyValidationException; import jp.co.inte.attendance.service.GradeService; import org.apache.log4j.Logger; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @Controller public class EmployGradeController { @Autowired GradeService gradeServ; private static final Logger logger = Logger.getLogger(EmployGradeController.class); @RequestMapping(value = "/grade", method = RequestMethod.GET) public ModelAndView indexForm(HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView("admin/grade"); String uname = null; try { Useraccount user = (Useraccount) request.getSession().getAttribute("user"); uname = user.getUsername(); List<EmployGrade> gradeList = this.gradeServ.getAllGrades(); logger.info(MessageFormat.format("GRADE | LIST[{0}]: Get all of grades, size = {1}", uname, gradeList.size())); modelAndView.addObject("gradeList", gradeList); modelAndView.addObject("menu", "grade"); } catch (Exception e) { logger.info(MessageFormat.format("GRADE | LIST[{0}]: {1}", uname, e.getMessage())); } return modelAndView; } @RequestMapping(value = "/grade", method = RequestMethod.POST, params = "action_name=search") public ModelAndView searchForm(HttpServletRequest request, @RequestParam("grade_name") String name) { ModelAndView modelAndView = new ModelAndView("admin/grade"); String uname = null; try { Useraccount user = (Useraccount) request.getSession().getAttribute("user"); uname = user.getUsername(); List<EmployGrade> gradeList = this.gradeServ.getGradesByName(name); logger.info(MessageFormat.format("GRADE | SEARCH[{0}]: Search GRADE by name = {1}, size = {2}", uname, name, gradeList.size())); modelAndView.addObject("gradeList", gradeList); modelAndView.addObject("menu", "grade"); modelAndView.addObject("name", name); } catch (Exception e) { logger.info(MessageFormat.format("GRADE | SEARCH[{0}]: {1}", uname, e.getMessage())); } return modelAndView; } @RequestMapping(value = "/grade", method = RequestMethod.POST, params = "action_name=edit_index") public ModelAndView editForm(HttpServletRequest request, @RequestParam("id") int id, @RequestParam("mode") int mode) { ModelAndView modelAndView = new ModelAndView("admin/grade_edit"); String uname = null; try { Useraccount user = (Useraccount) request.getSession().getAttribute("user"); uname = user.getUsername(); EmployGrade employGrade = null; if (SystemConstant.INSERT == mode) { employGrade = new EmployGrade(); employGrade.setDeleted(false); } else { employGrade = this.gradeServ.getGradeById(id); } logger.info(MessageFormat.format("GRADE | EDIT[{0}]: Edit GRADE id = {1}, mode = {2}", uname, id, mode)); modelAndView.addObject("employGrade", employGrade); modelAndView.addObject("mode", mode); } catch (Exception e) { logger.info(MessageFormat.format("GRADE | EDIT[{0}]: {1}", uname, e.getMessage())); } return modelAndView; } @RequestMapping(value = "/grade", method = RequestMethod.POST, params = "action_name=delete") public ModelAndView deleteForm(HttpServletRequest request, @RequestParam("grade_id") int id) { ModelAndView modelAndView = new ModelAndView("redirect:/grade"); String uname = null; try { Useraccount user = (Useraccount) request.getSession().getAttribute("user"); uname = user.getUsername(); EmployGrade employGrade = this.gradeServ.getGradeById(id); logger.info(MessageFormat.format("GRADE | DELETE[{0}]: Get GRADE = {1} by id = {2}", uname, employGrade, id)); boolean errorFlg = false; Integer ret = new Integer(0); if (employGrade != null) { employGrade.setDeleted(true); ret = this.gradeServ.saveOrUpdate(employGrade, SystemConstant.UPDATE); if (ret == null) { errorFlg = true; } } else { errorFlg = true; } if (errorFlg) { modelAndView.addObject("error", "Unable to delele employee grade."); logger.info(MessageFormat.format("GRADE | DELETE[{0}]: Unable to delete grade.", uname)); } else { modelAndView.addObject("message", "Delete employee grade successful."); logger.info(MessageFormat.format("GRADE | DELETE[{0}]: Delete grade successful: {1} record", uname, ret.intValue())); } List<EmployGrade> gradeList = this.gradeServ.getAllGrades(); modelAndView.addObject("gradeList", gradeList); } catch (Exception e) { logger.info(MessageFormat.format("GRADE | DELETE[{0}]: {1}", uname, e.getMessage())); } return modelAndView; } @SuppressWarnings("unchecked") @RequestMapping(value = "/savegrade", method = RequestMethod.POST, params = "action_name=save") @ResponseBody public JSONObject saveForm(HttpServletRequest request, @RequestParam("id") Integer id, @RequestParam("code") String code, @RequestParam("name") String name, @RequestParam("description") String description, @RequestParam("mode") Integer mode) { JSONObject jsonReponse = new JSONObject(); jsonReponse.put("mode", mode); String uname = null; try { Useraccount user = (Useraccount) request.getSession().getAttribute("user"); uname = user.getUsername(); EmployGrade employGrade = new EmployGrade(); employGrade.setCode(code); employGrade.setName(name); employGrade.setDescription(description); logger.info(MessageFormat.format("GRADE | SAVE[{0}]: Get GRADE = {1} by name = {2}", uname, employGrade, name)); if (SystemConstant.UPDATE == mode) { employGrade.setId(id); } Integer ret = this.gradeServ.saveOrUpdate(employGrade, mode); if (ret == null) { jsonReponse.put("error", SystemConstant.ERROR_1); jsonReponse.put("message", "Unable to save employee grade."); logger.info(MessageFormat.format("GRADE | SAVE[{0}]: Unable to save GRADE.", uname)); } else { jsonReponse.put("error", SystemConstant.ERROR_0); jsonReponse.put("message", "Save employee grade successful."); logger.info(MessageFormat.format("GRADE | SAVE[{0}]: Save GRADE successful: {1} record.", uname, ret.intValue())); } } catch (Exception e) { jsonReponse.put("error", SystemConstant.ERROR_1); if (e instanceof MyUniqueConstraintException) { String template = "Grade with Code=%s and/or Name=%s existed already. Please choose other value(s)"; Object[] args = { code, name }; jsonReponse.put("message", String.format(template, args)); } else if (e instanceof MyValidationException) { jsonReponse.put("message", "Unable to save Grade."); } else { logger.error(MessageFormat.format("GRADE | SAVE[{0}]: {1}", uname, e.getMessage())); } } return jsonReponse; } }
Java
UTF-8
1,074
3.828125
4
[]
no_license
package model; import java.util.Random; /** * A random generator that picks items based on percent chance. */ public class RandomGenerator { // EFFECTS: cannot be instantiated, as this is used for static method utilities private RandomGenerator() { } // EFFECTS: returns a random index that is more biased towards higher probabilities // if probabilities is empty, throws IllegalArgumentException public static int chooseFromProbabilities(double[] probabilities) { Random random = new Random(); double chance = random.nextDouble(); double sumSoFar = 0; for (int i = 0; i < probabilities.length; i++) { if (chance < sumSoFar + probabilities[i]) { return i; } sumSoFar += probabilities[i]; } if (probabilities.length == 0) { throw new IllegalArgumentException("Cannot choose from empty list."); } else { throw new IllegalArgumentException("Sum of probabilities do not add up to 1."); } } }
C++
UTF-8
1,871
2.78125
3
[]
no_license
#include "src/GameEngine/hpp/MusicManager.hpp" #include <iostream> //definitions here, not in DEFINE.hpp #define GAME_MUSIC_FILEPATH "" namespace hgw { void MusicManager::LoopPlay(sf::Music &music, float soundVolume) { if (!muted) { if (music.getStatus() == music.Playing) { std::cout << "Music already playing" << std::endl; } else { if (!music.openFromFile(GAME_MUSIC_FILEPATH)) { std::cout << "Error occured when opening music file" << std::endl; } else { if (music.getVolume() != musicVolume) { music.setVolume(musicVolume); } music.setLoop(true); music.play(); loaded = true; } } } else { std::cout << "Music Muted" << std::endl; } } void MusicManager::Play(sf::Music &music, float soundVolume) { if (!muted) { if (music.getStatus() == music.Playing) { std::cout << "Music already playing" << std::endl; } else { if (!music.openFromFile(GAME_MUSIC_FILEPATH)) { std::cout << "Error occured when opening music file" << std::endl; } else { if (music.getVolume() != musicVolume) { music.setVolume(musicVolume); } music.play(); loaded = true; } } } else { std::cout << "Music Muted" << std::endl; } } void MusicManager::Mute() { if (muted) { std::cout << "Music already muted" << std::endl; } else { muted = true; } } void MusicManager::UnMute() { if (!muted) { std::cout << "Music already unmuted" << std::endl; } else { muted = false; } } bool MusicManager::IsMuted() { return muted; } bool MusicManager::IsLoaded() { return loaded; } void MusicManager::SetVolume(float volume) { musicVolume = volume; gameMusic.setVolume(volume); } float MusicManager::GetVolume() { return musicVolume; } }
Python
UTF-8
2,159
3.765625
4
[]
no_license
# Universidad del Valle de Guatemala # Cifrado de informacion # Hugo Roman 19199 # Laurelinda Gomez 19501 # Juan Pablo Pineda 19087 # counter para contar las letras del texto plano from collections import Counter import matplotlib.pylab as plt import numpy as np # abecedario 27 letras abc = 'ABCDEFGHIJKLMNÑOPQRSTUVWXYZ' # Cifrado caesar def cifrar(cadena, clave): texto_cifrado = '' for letra in cadena: suma = abc.find(letra) + clave modulo = int(suma) % len(abc) texto_cifrado = texto_cifrado + str(abc[modulo]) return texto_cifrado # Descifrado caesar def decifrar(cadena, clave): texto_cifrado = '' for letra in cadena: suma = abc.find(letra) - clave modulo = int(suma) % len(abc) texto_cifrado = texto_cifrado + str(abc[modulo]) return texto_cifrado def BruteForce(): cryptic_text = "WDSFSDALALIHKXKWUNWFUASLISKSVWLUAXKSKUKAIMHYKSESLLWTSLSWFWLMNVASKDSXKWUNWFUASUHFDSJNWSISKWUWFDHLVALMAFMHLLAETHDHLWFNFDWFYNSBWVWMWKEAFSVHQDNWYHWLMNVASKDSXKWUNWFUASUHFDSJNWSISKWUWFWFDHLUKAIMHYKSESLQVWWLMSESFWKSWLMSTDWUWKNFSKWDSUAHFQHTMWFWKWDMWPMHIDSFHDSAVWSXNFVSEWFMSDWLJNWFHMHVSLDSLDWMKSLSISKWUWFUHFDSEALESXKWUNWFUASWFDHLMWPMHLLAFHJNWSDYNFSLSISKWUWFESLSEWFNVHJNWHMKSLUHFMSFVHDSLLAYFHLVWDMWPMHUAXKSVHQHKVWFSFVHDHLVWESQHKSEWFHKXKWUNWFUASIHVWEHLWLMSTDWUWKUHFBWMNKSLSUWKUSVWJNWDWMKSUHKKWLIHFVWSUSVSLAYFHWDSFSDALALLWUHEIDWMSUHFDSTNLJNWVSVWISDSTKSLXKWUNWFMWLUHEHSKMAUNDHLQIKWIHLAUAHFWLLASVWESLUHFHUWEHLHLHLIWUZSEHLVWSDYNFSISDSTKSJNWVWTSSISKWUWKWFWDEWFLSBWEWBHKJNWEWBHKWDKWLMHWLUNWLMAHFVWAFMNAUAHFLWYNFNFWLMNVAHLHTKWMWPMHLVWDVASKAHWDISALVWWFKAJNWXHFMSFADDHDSENWLMKSMHESVSVLHFDHLWBWEIDSKWLVWVAUZHVASKAHINTDAUSVHLVNKSFMWNFSLWESFSUAFUNWFMSQVHLEADLWALUAWFMHLVAWUAFNWÑWDWMKSLWFMHMSDDSXKWUNWFUASVWDSLDWMKSLWFUSLMWDDSFHWLSIKHPAESVSEWFMWDSJNWLAYNW" for i in range(0, 27): plain_text = decifrar(cryptic_text, i) print("Para la llave {}, el texto decifrado: {}".format(i, plain_text)) # Distribucion de probabilidad a = len(cryptic_text) c = Counter(cryptic_text) w = c.get("W") print("***Distribucion probabilidad del texto cifrado***") def frecuency(text): text = text.upper() letterF = {} for letter in abc: letterF[letter] = 0 for letter in text: if letter in abc: letterF[letter] += 1 return letterF def caesar(Ctext): prob = 0 frec = frecuency(Ctext) for letra, valor in frec.items(): prob = (valor/a)*100 print(letra, ":", prob, "%") ypos = range(len(abc)) plt.xticks(ypos, abc) plt.bar(ypos, frec.values()) caesar(cryptic_text) # Frecuencias Teoricas Frec = [13.65, 11.79, 9.195, 7.983, 6.696, 6.69, 6.86, 5.27, 5.19, 4.919, 4.802, 3.445, 3.996, 2.925, 1.0, 0.953, 0.693, 0.875, 1.043, 0.585, 0.272, 0.074, 0.022, 0.019, 0.183, 0.523, 0.291] Char = ['E', 'A', 'O', 'S', 'R', 'N', 'I', 'L', 'D', 'C', 'T', 'P', 'U', 'M', 'B', 'F', 'V', 'Q', 'G', 'H', 'J', 'Ñ', 'K', 'W', 'X', 'Y', 'Z']
C++
UTF-8
5,428
2.984375
3
[]
no_license
#include "PC.h" #include "Floor.h" #include "Object.h" #include "IOhandler.h" #include "Dungeon.h" #include <cstdlib> #include <cmath> #include <algorithm> #include <climits> //intialize instance pointer PC *PC::s_instance = 0; PC * PC::instance() { if (!s_instance) { s_instance = new PC(); } return s_instance; } void PC::reset() { if (s_instance) { delete s_instance; } } unsigned int PC::roll_damage() { if (god_mode) { return INT_MAX - 1; } unsigned int dmg_total = this->damage.roll(); for (unsigned int i = 0; i < equipment.size(); i++) { if (equipment[i]) { dmg_total += equipment[i]->roll_damage(); } } return dmg_total; } void PC::take_damage(int amount) { if (god_mode) { return; } int resistance = 0; for (unsigned int i = 0; i < equipment.size(); i++) { if (equipment[i]) { resistance += equipment[i]->defense; } } this->hp -= (amount - resistance); } unsigned int PC::get_speed() { unsigned int speed = this->spd; for (unsigned int i = 0; i < equipment.size(); i++) { if (equipment[i]) { speed += equipment[i]->speed; } } if (speed < 1) { speed = 1; } return speed; } void PC::do_turn() { } bool PC::pick_up_object(Object * obj) { for (unsigned int i = 0; i < inventory.size(); i++) { if (!inventory[i]) { inventory[i] = obj; std::string pickup_message = "You picked up "; pickup_message += obj->name; IO_handler::queue_message(pickup_message); return true; } } //full inventory std::string full_message = "Your inventory was too full for "; full_message += obj->name; IO_handler::queue_message(full_message); return false; } bool PC::equip_object(int slot) { if (!inventory.at(slot)) { return false; } for (int t = 1; t < (int)SCROLL; t++) { if ((int)inventory.at(slot)->type == t) { if (t == (int)RING && (equipment.at(RING_SLOT_A) && !equipment.at(RING_SLOT_B))) { t++; } Object * temp = equipment.at(t-1); equipment.at(t-1) = inventory.at(slot); std::string equip_message = "You equip "; equip_message += inventory.at(slot)->name; IO_handler::queue_message(equip_message); inventory.at(slot) = temp; return true; } } return false; } bool PC::unequip_object(equipment_slots slot) { if (!equipment.at(slot)) { return false; } for (int s = 0; s < 10; s++) { if (!inventory.at(s)) { inventory.at(s) = equipment.at(slot); equipment.at(slot) = NULL; return true; } } Object *temp = inventory.at(0); inventory.at(0) = equipment.at(slot); drop_item(0); inventory.at(0) = temp; return true; } bool PC::drop_item(int slot) { if (!inventory.at(slot)) { return false; } if (!Dungeon::instance()->place_object(position.x, position.y, inventory.at(slot))) { IO_handler::queue_message("There is no space to drop that item"); return false; } std::string drop_message = "You dropped "; drop_message += inventory.at(slot)->name; IO_handler::queue_message(drop_message); inventory.at(slot) = NULL; return true; } void PC::expunge_item(int slot) { std::string message = "You destroyed "; message += inventory.at(slot)->name; IO_handler::queue_message(message); inventory.at(slot) = NULL; } Object * PC::inventory_object(int slot) { return inventory.at(slot); } Object * PC::equipped_item(equipment_slots slot) { return equipment.at(slot); } void PC::tgm() { god_mode = !god_mode; } //helper function for update_vision int square_dist(int x1, int y1, int x2, int y2) { int dx = x2 - x1; int dy = y2 - y1; return (dx * dx) + (dy * dy); } void PC::update_vision(Floor *f) { int vbox_left = this->x_pos() - vision_range; if (vbox_left < 0) { vbox_left = 0; } int vbox_right = this->x_pos() + vision_range; if (vbox_right >= FWIDTH) { vbox_right = FWIDTH-1; } int vbox_top = this->y_pos() - vision_range; if (vbox_top < 0) { vbox_top = 0; } int vbox_bottom = this->y_pos() + vision_range; if (vbox_bottom >= FHEIGHT) { vbox_bottom = FHEIGHT - 1; } f->reset_current_vision(); std::array<int, 8> n = f->get_neighbors(x_pos(), y_pos()); for (int i : n) { cellType c = f->get_type(linearX(i), linearY(i)); //check for any cell that blocks the sight line if (c != rock_c && c != immutable_c) { f->view_cell(i); } } std::vector<int> sight_line; //iterate over a box that contains the entire visual range of the NPC for (int row = vbox_top; row <= vbox_bottom; row++) { for (int col = vbox_left; col <= vbox_right; col++) { //use manhattan distance to get the edge of a diamond if (std::abs(square_dist(x_pos(), y_pos(), col, row) - vision_range) <= 2 * vision_range) { //draw a line to each point on the diamond sight_line = f->bresenham_line(x_pos(), y_pos(), col, row); //Since my bresenham algorithm can return a reversed line, check whether the //sight line vector is reversed and flip it back if (sight_line.front() == index2d(col, row)) { std::reverse(sight_line.begin(), sight_line.end()); } //iterate over the sight line from what should now be the PC's location //if a single opaque cell is encountered, skip the rest of the iteration for (int i : sight_line) { cellType c = f->get_type(linearX(i), linearY(i)); //check for any cell that blocks the sight line if (c == rock_c || c == immutable_c) { break; } //since we have unobstructed view, set PC vision to true f->view_cell(i); } } } } }
Java
UTF-8
261
1.734375
2
[]
no_license
package junitTest; import org.junit.Test; /********************* * *@Author: Jian Zhang *@Date: 2017-07-17 16:39 * *********************/ public class B_ModelTest { @Test public void _test(){ System.out.println("testing B model..."); } }
Java
UTF-8
2,023
3.8125
4
[]
no_license
/********** NAME: Shoaib Khan STUDENT NUMBER: 507285 ICS4U0-A, Sep-Jan 2016 THIS FILE IS PART OF THE PROGRAM: Stacks Assignment (The "LAN" class), uses Computer.java Purpose: This class is used to set up and add attributes to the LAN stack. Includes methods to alter or display the stack. **********/ import hsa.Console; //Imports the console class which allows the program to create a new display console. public class LAN //Stack class with attributes listed below { Console c = new Console (); private Computer firstComputer; private String nameLAN; private int numComputers; public LAN (String nameLAN, int numComputers) //Constructor which creates the LAN stack { this.nameLAN = nameLAN; this.numComputers = numComputers; } public int isEmpty () { if (numComputers == 0) c.println ("The Stack is Empty."); else c.println ("The Stack is NOT Empty."); return numComputers; } public Computer peek () { if (numComputers != 0) c.println ("The object at the top of the stack is: " + firstComputer.getCompany ()); return firstComputer; } public void push (Computer newComputer) { newComputer.setNext (firstComputer); firstComputer = newComputer; numComputers++; } public Computer pop () { if (numComputers != 0) { firstComputer.setPrevious (firstComputer); firstComputer = firstComputer.getNext (); numComputers--; } else c.println (nameLAN + " is Empty."); return firstComputer; } public void size () { c.println ("There are " + numComputers + " Computers in the LAN."); } public void display (Computer newComputer) { newComputer = firstComputer; c.println ("Name of the LAN: " + nameLAN); while (newComputer != null) { c.print (newComputer.getCompany (), 10); c.print (newComputer.getHDDSize (), 10); c.println (newComputer.getRam (), 10); newComputer = newComputer.getNext (); } } }
Shell
UTF-8
580
3.40625
3
[]
no_license
# !/bin/sh read -p 'Song: ' song read -p 'Format(Press a for audio and v for video): ' song_type read -p 'Location: ' location if [ ${song_type:-a} == 'v' ] then song_type=video a_or_v=-v else song_type=audio a_or_v=-a fi if [ "${location:-0}" == 0 ];then location=$HOME/Downloads/ fi # Cannot download song without phrase. while [ "${song:-0}" == 0 ] do read -p 'Phrase of song not given try again: ' song done source ~/youtubeDownloader/youtubeDownloader_env/bin/activate python ~/youtubeDownloader/mp3-mp4-downloader/downloader.py $song $a_or_v $location deactivate
C++
UTF-8
1,631
3.171875
3
[]
no_license
#include<iostream> using namespace std; //#define POINTERS_BASICS //#define POINTERS_AND_ARRAYS #define POINTER_2_POINTER void main() { setlocale(LC_ALL, ""); #ifdef POINTERS_BASICS int a = 2; int* pa = &a; cout << a << endl; //Вывод значения переменной 'a' на экран. cout << &a << endl; //Взятие адреса переменной 'a' прямо при выводе. cout << pa << endl; //Вывод адреса переменной 'a' хранящегося в указателе 'pa'. cout << *pa << endl;//Разыменование указателя 'pa', и получение значения по адресу. int* pb; //Объявляем указатель 'pb', не зная что мы в него положим int b = 3; //l-value = r-value; pb = &b; //(int) = (int*) cout << b << endl; cout << pb << endl; cout << *pb << endl; //int - int //int* - Указатель на int //double - double //double* - Указатель на double #endif // POINTERS_BASICS #ifdef POINTERS_AND_ARRAYS const int n = 5; int arr[n] = { 3,5,8,13,21 }; cout << arr << endl; cout << *arr << endl; for (int i = 0; i < n; i++) { cout << *(arr + i) << "\t"; } cout << endl; #endif // POINTERS_AND_ARRAYS int a = 2; int* pa = &a; int** ppa = &pa; } /* ---------------------------------- & - Address-of operator (Оператор взятия адреса). * - Dereference operator (Оператор разыменования). ---------------------------------- */ /* ---------------------------------- + - ++ -- ---------------------------------- */
C++
UTF-8
604
3.03125
3
[]
no_license
#ifndef CONTAINER_H #define CONTAINER_H #pragma once #include <vector> #include <unordered_map> #include <queue> #include <stack> #include <iostream> using namespace std; template <class T> class Container { private: vector<T*> m_Arr; queue<T*> m_DeletionList; unordered_map<int, int> m_IdMap; int m_Size; Container() = delete; Container(const Container& other) = delete; Container& operator=(const Container& rhs) = delete; public: Container(int size); ~Container(); int size() const; void add(T& obj, int id); T& get(int id) const; void erase(int id); void cleanUp(); }; #endif
SQL
UTF-8
811
3.328125
3
[]
no_license
--***************************************************************************** -- SQL SERVER --***************************************************************************** select d.*, DD.DESCRICAO from dbo.Dados d , dadosdet DD where (D.status & 4) = DD.CODIGO /* update dbo.Dados set status = status + 16 where codigo in (select d.codigo from dbo.Dados d , dadosdet DD where (D.status & 8) = DD.CODIGO) */ --***************************************************************************** -- ORACLE --***************************************************************************** SELECT D.*, C.DESCRICAO FROM IFRDBA.DADOS D , IFRDBA.CODIGOS C WHERE BITAND(STATUS, 4) = C.CODIGO --DECODE(BITAND(TBL_TEMP.VALUE,2), 2, 2, -1) <> -1;
Go
UTF-8
922
2.84375
3
[]
no_license
package api import ( "net/http" "../controller" "encoding/json" "../models" ) func GetAllData(w http.ResponseWriter, r *http.Request) { visas := controller.GetAllData() w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) err := json.NewEncoder(w).Encode(visas); if err != nil { println(err.Error()) } } func CreateData(w http.ResponseWriter, r *http.Request){ decoder := json.NewDecoder(r.Body) var visa models.Visa err := decoder.Decode(&visa) if err != nil{ println(err.Error()) } controller.CreateData(visa) } func DeleteData(w http.ResponseWriter, r *http.Request){ id := r.URL.Query().Get("visaID") controller.DeteleData(id) } func UpdateData(w http.ResponseWriter, r *http.Request){ decoder := json.NewDecoder(r.Body) var visa models.Visa err := decoder.Decode(&visa) if err != nil{ println(err.Error()) } controller.UpdateData(visa) }
Java
UTF-8
2,562
3.421875
3
[]
no_license
// ATMThread.java package cscie55.hw6; import java.util.ArrayList; /** * This class is responsible for executing the requests in a request queue through ATMRunnable objects. * * @author Antonio Recalde Russo * @version 11/23/2013 * */ public class ATMThread extends Thread { private ArrayList<ATMRunnable> request_queue; private static int thread_counter = 0; // this variable will be used to determine the id number private int thread_id; public ATMThread(ArrayList<ATMRunnable> request_queue) { this.request_queue = request_queue; thread_id = ++thread_counter; } @Override public void run() { while (true) { synchronized (request_queue) { /******************************************************************************** * * If the queue is empty, it calls the wait() method of the request queue, * thereby waiting to be notified when another thread puts a request on the queue. * ********************************************************************************/ if (request_queue.isEmpty()) { // System.out.println("WAIT: " + this); try { request_queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } /********************************************************************************* * * When notified, this Thread begins its second and primary responsibility: * It retrieves the ATMRunnable from the list and executes the request contained in it. * *********************************************************************************/ else { ATMRunnable temp = request_queue.get(0); request_queue.remove(0); // remove it from the list. If list is empty again, other threads will call wait. System.out.println("Running request in thread: " + this); new Thread(temp).start(); // starts the ATMRunnable, so it executes the request contained in it. /***************************************************************************** * * Finally, when the request has been executed, this Thread once again calls wait() * on the request queue, ready to be notified of additional incoming requests. * ******************************************************************************/ try { request_queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // end else } // end synchronized } // end while } // end run public String toString() { return String.format("Thread-%d", thread_id); } }
Java
UTF-8
835
1.851563
2
[]
no_license
package com.restAssured; import io.restassured.RestAssured; import io.restassured.RestAssured; import io.restassured.path.json.JsonPath; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; import files.Payload; public class AddAssertion { public static void main(String[] args) { //for encapsulation body in seperate payload class //interested on scope RestAssured.baseURI = "https://rahulshettyacademy.com"; given().log().all().queryParam("key", "qaclick123") .headers("Content-Type", "application/json").body(Payload.AddPlace()).when() .post("maps/api/place/add/json") .then().log().all().assertThat().statusCode(200).body("scope", equalTo("APP")) //assertion on body(see respone) .header("Server", "Apache/2.4.18 (Ubuntu)");//assertion on header } }
Java
UTF-8
1,202
2.375
2
[]
no_license
package dressing.asi.insarouen.fr.dressing.data.model; import dressing.asi.insarouen.fr.dressing.data.model.contenu.Vetement; import dressing.asi.insarouen.fr.dressing.elements.Couleur; /** * Created by julie on 22/10/16. */ public class Contenu { private Couleur couleur; private String image; private int idObjet; private int idDressing; public Contenu() { } public Contenu(Couleur couleur, String image, int idDressing, int idObjet) { this.idObjet = idObjet; this.couleur = couleur; this.image = image; this.idDressing = idDressing; } public Couleur getCouleur() { return couleur; } public int getIdObjet() { return idObjet; } public int getIdDressing() { return idDressing; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public void setCouleur(Couleur couleur) { this.couleur = couleur; } public void setIdObjet(int idObjet) { this.idObjet = idObjet; } public void setIdDressing(int idDressing) { this.idDressing = idDressing; } }
Python
UTF-8
889
3.90625
4
[]
no_license
def grades(): sum=0 g=eval(input("Enter a grade:")) while g>=0 and g<=100: sum=sum+g g=eval(input("enter next grade:")) print("The sum of the grades is:",sum) def number(): n=eval(input("enter a number:")) if n==1: n=eval(input("enter another number")) while n!=1: if n%2==0: n=n/2 else: n=(3*n)+1 print("the value is",n) def eat(): persons=["John","Marissa","Pete","Dayton"] restaurants=["Japanese","American","Mexican","French"] for i in range(len(persons)): for j in range(len(restaurants)): if i == j: print(persons[i],"loves to eat",restaurants[j]) file=open(listfile.txt,'w') for i in range(1,5): file.write(str(i)+"\n") file.close()
JavaScript
UTF-8
2,120
2.96875
3
[]
no_license
// Get dependencies const express = require('express'); const path = require('path'); const http = require('http'); const bodyParser = require('body-parser'); // Get our API routes const api = require(path.join(__dirname, 'api', 'api.js')); const app = express(); app.use(bodyParser.json()); /** * Get port from environment and store in Express. */ const port = process.env.PORT || '3000'; app.set('port', port); let isDevMode = false; process.argv.forEach(function (val) { if (/DEVELOP/.test(val)) { isDevMode = true; } }); if (isDevMode) { console.log('RUNNING IN DEVELOPMENT MODE'); // Add headers app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Pass to next layer of middleware next(); }); } const frontendFolder = path.join(__dirname, 'static', 'templyte', 'dist', 'templyte'); // Point static path to frontend folder app.use(express.static(frontendFolder)); console.log("Serving static from " + frontendFolder); // Set our api routes app.use('/api', api); console.log("Setting api routes"); // Catch all other routes and return the index file app.get('*', (req, res) => { res.sendFile(path.join(frontendFolder, 'index.html')); }); console.log("Catching all other routes and returning the index file"); /** * Create HTTP server. */ const server = http.createServer(app); console.log("Created Server"); /** * Listen on provided port, on all network interfaces. */ server.listen(port, () => { if (isDevMode) { console.log('\nPlease use \'npm run development-gui\' to start a development gui and navigate to localhost:4200'); console.log('Node that the api is still running on port ' + port.toString()) } else { console.log(`\nServer running on port: ${port}`); } });
Swift
UTF-8
717
2.734375
3
[]
no_license
// // RandomFall.swift // GiocoChimica // // Created by Antonio Mennillo on 20/11/2019. // Copyright © 2019 Antonio Mennillo. All rights reserved. // import Foundation import SpriteKit extension SKSpriteNode { func startFallingFromRandomPosition() { //let random01 = CGFloat(Float(arc4random()) / Float(UINT32_MAX)) let randomx = CGFloat.random(min: 40, max: 350) self.position.x = randomx self.position.y = self.scene!.frame.height let randomDuration = TimeInterval(arc4random_uniform(3) + 2) let fallAction = SKAction.moveTo(y: -500, duration: randomDuration) self.run(fallAction) { [weak self] in self?.removeFromParent() } } }
Java
UTF-8
1,092
3.203125
3
[]
no_license
import java.util.Scanner; public class zigzag{ public static void main(String[] args){ Scanner scan; scan = new Scanner(System.in); String yes = "y"; int nStars = 0; while(yes.equals("y") || yes.equals("Y")){ while (nStars<3||nStars>33){ Scanner myScanner; myScanner = new Scanner(System.in); System.out.print("Enter the number for nStars"); nStars=myScanner.nextInt(); if(nStars<=1){ System.out.println("Number not valid."); } } String star = "*"; for(int i=0; i<nStars; i++){ System.out.print(star); } for(int j=0; j<nStars-1; j++){ for(int k=0; k<j; k++){ System.out.print(" "); } System.out.print(star); System.out.println(""); } for(int i=0; i<nStars; i++){ System.out.print(star); } System.out.println("Enter Y or y to continue anything else to quit"); yes=scan.nextLine(); nStars=0; } } }
Go
UTF-8
728
2.65625
3
[ "MIT" ]
permissive
package telegraph_test import ( "testing" "github.com/stretchr/testify/assert" "gitlab.com/toby3d/telegraph" ) func TestCreateAccount(t *testing.T) { t.Run("invalid", func(t *testing.T) { t.Run("nil", func(t *testing.T) { _, err := telegraph.CreateAccount(telegraph.Account{}) assert.Error(t, err) }) t.Run("without shortname", func(t *testing.T) { _, err := telegraph.CreateAccount(telegraph.Account{ ShortName: "", AuthorName: "Anonymous", }) assert.Error(t, err) }) }) t.Run("valid", func(t *testing.T) { account, err := telegraph.CreateAccount(telegraph.Account{ ShortName: "Sandbox", AuthorName: "Anonymous", }) assert.NoError(t, err) assert.NotNil(t, account) }) }
PHP
UTF-8
1,311
2.546875
3
[]
no_license
<?php /** * productoCategoriaEshopTable * * This class has been auto-generated by the Doctrine ORM Framework */ class productoCategoriaEshopTable extends Doctrine_Table { /** * Returns an instance of this class. * * @return object productoCategoriaEshopTable */ public static function getInstance() { return Doctrine_Core::getTable('productoCategoriaEshop'); } /** * Elimina todas posiciones ordenables de categorias para un eShop en particular * * @param integer $idEshop * */ public function deleteByIdEshop( $idEshop ) { $this->createQuery('pce') ->delete() ->addWhere('pce.id_eshop= ?', array( $idEshop ) ) ->execute(); } /** * Retorna el productoCategoriaEshop que coincide con la clave compuesta * * @param integer $idEshop * @param integer $idProductoCategoria * * @return productoCategoriaEshop */ public function getByCompoundKey( $idEshop, $idProductoCategoria ) { $query = $this->createQuery('pce') ->addWhere('pce.id_producto_categoria = ?', $idProductoCategoria ) ->addWhere('pce.id_eshop = ?', $idEshop ); $query->useResultCache(true, null, 'productoCategoriaEshop_getByCompoundKey_' . $idEshop . '_' . $idProductoCategoria ); return $query->fetchOne(); } }
C#
UTF-8
1,565
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using WebApi.Service.Interface.Table; using WebApi.Models.Repository.EDI.Interface; using WebApi.Models; namespace WebApi.Service.Implement.Table { public class Budget_DepartmentReportService : IBudget_DepartmentReportService { private IRepository<Budget_DepartmentReport> _repository; public Budget_DepartmentReportService(IRepository<Budget_DepartmentReport> repository) { this._repository = repository; } public string Create(Budget_DepartmentReport instance) { if (instance == null) { throw new ArgumentNullException(); } return this._repository.Create(instance); } public void Update(Budget_DepartmentReport instance) { if (instance == null) { throw new ArgumentNullException(); } this._repository.Update(instance); } public void Delete(int Id) { var instance = this.GetByID(Id); this._repository.Delete(instance); } public bool IsExists(int Id) { return this._repository.GetAll().Any(x => x.Id == Id); } public Budget_DepartmentReport GetByID(int Id) { return this._repository.Get(x => x.Id == Id); } public IEnumerable<Budget_DepartmentReport> GetAll() { return this._repository.GetAll(); } } }
Markdown
UTF-8
2,993
2.796875
3
[ "MIT" ]
permissive
--- layout: about title: H.J.Chang permalink: / description: Associate Professor @ <a href="https://www.ed.ac.uk" target="_blank">University of Birmingham</a> profile: align: right image: team/HJ.jpg address: <!-- > <p>Informatics Forum</p> <p>10 Crichton Street</p> <p>Edinburgh, EH8 9AB</p> --> news: false # includes a list of news items selected_papers: true # includes a list of papers marked as "selected={true}" social: true # includes social icons at the bottom of the page twitter: true # show twitter navigation_weight: 10 --- ### **Biography** I am a Associate Professor of the School of Computer Science at the University of Birmingham and a ***Turing Fellow of the Alan Turing Institute***. My research interests are focused on human-centred visual learning, especially in application to human-robot interaction. Computer vision and machine learning including deep learning are my expertise research area. **I am always looking for fully motivated & talented PhD students!** ### **Contact Me** - Office: Room 107, School of Computer Science - E-mail: H.J.Chang@bham.ac.uk - Phone: +44(0)121 414 7264 ### **News** - **<font color=grey>Jun 2022</font>** **-** I will co-organise Eye Gaze workshop ***[“GAZE2022: The 4th International Workshop on Gaze Estimation and Prediction in the Wild”](https://gazeworkshop.github.io/2022/)*** at **<font color=red>CVPR 2022</font>**. - **<font color=grey>Mar 2022</font>** **-** **One paper** is accepted to **<font color=red>CVPR 2022</font>**. - **<font color=grey>Feb 2022</font>** **-** **One paper** is accepted to **<font color=red>Pattern Recognition</font>**. - **<font color=grey>Feb 2022</font>** **-** **One paper** is accepted to **<font color=red>ICRA 2022</font>**. - **<font color=grey>Oct 2021</font>** **-** I am appointed as **<font color=purple>Turing Fellow</font>** of the **<font color=green>Alan Turing Institute</font>**. - **<font color=grey>Oct 2021</font>** **-** **One paper** is accepted to **<font color=red>WACV 2022</font>**. - **<font color=grey>May 2021 </font>** **-** **One paper** is accepted to **<font color=red>MICCAI 2021</font>**. - **<font color=grey>Mar 2021 </font>** **-** **Four papers** is accepted to **<font color=red>CVPR 2021</font>** (1 Oral + 3 Poster). - **<font color=grey>Mar 2021</font>** **-** I will co-organise Eye Gaze workshop ***[“VOT2021 Challenge”](https://www.votchallenge.net/vot2021/)*** at **<font color=red>ICCV 2021</font>**. - **<font color=grey>Dec 2020</font>** **-** I will co-organise Eye Gaze workshop ***[GAZE 2021: The 3rd International Workshop on Gaze Estimation and Prediction in the Wild ](https://gazeworkshop.github.io/2021/)*** at **<font color=red>CVPR 2021</font>**. - **<font color=grey>Dec 2020 </font>** **-** **Two papers** is accepted to **<font color=red>AAAI 2021</font>**. - **<font color=grey>Dec 2020 </font>** **-** I will be serving as **Senior Program Chair (Area Chair)** for **<font color=red>AAAI 2021</font>**.
C#
UTF-8
1,441
3.5
4
[ "MIT" ]
permissive
using System; class Trip { static void Main() { double number = double.Parse(Console.ReadLine()); string season = Console.ReadLine(); if (number <= 100) { if (season == "summer") { number = (number * 30) / 100; Console.WriteLine("Somewhere in Bulgaria"); Console.WriteLine("Camp - {0:f2}", number); } else if (season == "winter") { number = (number * 70) / 100; Console.WriteLine("Somewhere in Bulgaria"); Console.WriteLine("Hotel - {0:f2}", number); } } else if (number > 100 && number <= 1000) { if (season == "summer") { number = (number * 40) / 100; Console.WriteLine("Somewhere in Balkans"); Console.WriteLine("Camp - {0:f2}", number); } else if (season == "winter") { number = (number * 80) / 100; Console.WriteLine("Somewhere in Balkans"); Console.WriteLine("Hotel - {0:f2}", number); } } else if (number >1000 && number <= 5000) { number = (number * 90) / 100; Console.WriteLine("Somewhere in Europe"); Console.WriteLine("Hotel - {0:f2}", number); } } }
PHP
UTF-8
1,666
2.59375
3
[ "MIT" ]
permissive
<?php namespace Despark\Cms\Console\Commands\User; use Illuminate\Console\Command; use Illuminate\Support\Facades\Storage; /** * Class CleanUserExports */ class CleanUserExports extends Command { /** * The console command signature. * * @var string */ protected $signature = 'igni:user:exports:clean'; /** * The console command description. * * @var string */ protected $description = 'Delete user exports older than 48 hours.'; /** * Create a new command instance. */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $storageDisk = Storage::disk('public'); $storagePrefix = $storageDisk->getDriver()->getAdapter()->getPathPrefix(); $files = $storageDisk->files('user-exports'); $filesToDelete = []; $maxLifetimeInMinutes = 2880; foreach ($files as $file) { if (file_exists($storagePrefix . $file)) { $minutesPassedSinceCreated = date('i', filectime($storagePrefix . $file)); if ($minutesPassedSinceCreated >= $maxLifetimeInMinutes) { $filesToDelete[] = $file; } } } $count = count($filesToDelete); $bar = $this->output->createProgressBar($count); foreach ($filesToDelete as $file) { $storageDisk->delete($file); $bar->advance(); } $bar->finish(); $this->info(PHP_EOL . 'User exports were deleted successfully'); } }
Java
UTF-8
1,881
2.625
3
[ "Apache-2.0" ]
permissive
package com.popupmc.soloexperience.events; import com.popupmc.soloexperience.SoloExperience; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.scheduler.BukkitRunnable; public class JoinEvent implements Listener { private final SoloExperience plugin; public JoinEvent(SoloExperience plugin){ this.plugin = plugin; } /** * Logs an executed command to console. * @param cmd The command being executed. */ private void logCommand(String cmd){ Bukkit.getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("prefix")+" &eExecuting cmd: &f"+cmd)); } @EventHandler public void onJoin(PlayerJoinEvent event){ if(!event.getPlayer().hasPlayedBefore()) { // New player incoming FileConfiguration config = plugin.getConfig(); Player player = event.getPlayer(); boolean logCommands = config.getBoolean("log commands to console"); for(String command : config.getStringList("join commands")){ command = command.replace("%player%", player.getName()).replace("%world%", player.getWorld().getName()); if(logCommands) logCommand(command); Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); } int delay = config.getInt("chest spawn delay"); if(delay > 0){ new BukkitRunnable(){ public void run(){ plugin.spawnChest(player); } }.runTaskLater(plugin, delay); } } } }
Java
UTF-8
547
3.1875
3
[]
no_license
package interfac_e; /** * 接口中可以定义“成员变量”,但是必须使用public static final 三个关键字修饰 * <p> * <p> * 接口中的常量遵循以下要求: * 1. public static final 可以省略 * 2.接口的常量必须赋值 * 3.接口中的常量名必须全部大写,单词之间使用下划线隔开 * 4.通过 接口名 . 常量名来使用 * <p> * <p> * 接口不能有静态代码块 和构造方法 */ public class InterfaceTest05 { } interface Person { public static final int NUM = 10; }
Java
UTF-8
1,862
3.453125
3
[]
no_license
public class Problem17 { public static void main( String[] args ) { long startTime = System.nanoTime(); String[] nums = new String[40]; nums[1] = "one"; nums[2] = "two"; nums[3] = "three"; nums[4] = "four"; nums[5] = "five"; nums[6] = "six"; nums[7] = "seven"; nums[8] = "eight"; nums[9] = "nine"; nums[10] = "ten"; nums[11] = "eleven"; nums[12] = "twelve"; nums[13] = "thirteen"; nums[14] = "fourteen"; nums[15] = "fifteen"; nums[16] = "sixteen"; nums[17] = "seventeen"; nums[18] = "eighteen"; nums[19] = "nineteen"; nums[20] = "twenty"; nums[21] = "thirty"; nums[22] = "forty"; nums[23] = "fifty"; nums[24] = "sixty"; nums[25] = "seventy"; nums[26] = "eigthy"; nums[27] = "ninety"; nums[28] = "hundred"; nums[29] = "thousand"; long letters = 0; for( int i = 1; i < 1000; i++ ) { String numStr = ""; if( i >= 100 ) { numStr += nums[i/100] + nums[28]; if( (i % 100) != 0 ) { numStr += "and"; } } if( (i % 100) < 20 && (i % 100) != 0 ) { numStr += nums[i%100]; } if( (i % 100) >= 20 ) { if( (i % 10) == 0 ) { numStr += nums[18 + ((i % 100) / 10)]; } else { numStr += nums[18 + ((i % 100) / 10)] + nums[i % 10]; } } System.out.println(numStr); letters += numStr.length(); } letters += nums[1].length() + nums[29].length(); // for one thousand System.out.println(nums[1] + nums[29]); System.out.println("Letters: " + letters); System.out.println( "- - - - - - - - - - - - - - - - - - - " ); long endTime = System.nanoTime(); long duration = (endTime - startTime); System.out.println("Execution time: " + duration / (Math.pow(10, 9)) + " s"); } }
Python
UTF-8
3,057
3.046875
3
[]
no_license
import codecademylib import pandas as pd ad_clicks = pd.read_csv('ad_clicks.csv') # Examine the first 10 rows of ad_clicks print(ad_clicks.head(10)) # Variable views_from_utm_source to hold the total number of views from each utm_source views_from_utm_source = ad_clicks.groupby('utm_source').user_id.count().reset_index() # Display views_from_utm_source print(views_from_utm_source) # A new column called is_click, which is True if ad_click_timestamp is not null and False otherwise ad_clicks['is_click'] = ~ad_clicks.ad_click_timestamp.isnull() # Get the percent of people who clicked on ads from each utm_source and assign it to the variable clicks_by_source clicks_by_source = ad_clicks.groupby(['utm_source', 'is_click']).user_id.count().reset_index() # Display clicks_by_source print(clicks_by_source) # Pivot the data so that the columns are is_click (either True or False), the index is utm_source, and the values are user_id and assign it to the variable clicks_pivot clicks_pivot = clicks_by_source.pivot( columns = 'is_click', index = 'utm_source', values = 'user_id' ).reset_index() # Examine clicks_pivot print(clicks_pivot) # Create a new column in clicks_pivot called percent_clicked which is equal to the percent of users who clicked on the ad from each utm_source clicks_pivot['percent_clicked'] = clicks_pivot[True] / (clicks_pivot[True] + clicks_pivot[False]) # Examine clicks_pivot print(clicks_pivot) # Group experimental_group and count the number users print(ad_clicks.groupby('experimental_group').user_id.count().reset_index()) # Group both experimental_group and is_click and count the number of user_id's, and create a pivoton the data print( ad_clicks.groupby(['experimental_group', 'is_click']).user_id.count().reset_index()\ .pivot( columns = 'is_click', index = 'experimental_group', values = 'user_id' ).reset_index() ) # Variable a_clicks to hold the results for A group a_clicks = ad_clicks[ad_clicks.experimental_group == 'A'] # Variable b_clicks to hold the results for B group b_clicks = ad_clicks[ad_clicks.experimental_group == 'B'] # Create a pivot data for a_clicks and assign it to a_clicks_pivot a_clicks_pivot = a_clicks.groupby(['is_click', 'day']).user_id.count().reset_index()\ .pivot( columns = 'is_click', index = 'day', values = 'user_id' ).reset_index() # Calculate the percent of users who clicked on the ad by day for a_clicks a_clicks_pivot['percentage_clicked'] = a_clicks_pivot[True] / (a_clicks_pivot[True] + a_clicks_pivot[False]) # Examine a_clicks_pivot print(a_clicks_pivot) # Create a pivot data for b_clicks and assign it to b_clicks_pivot b_clicks_pivot = b_clicks.groupby(['is_click', 'day']).user_id.count().reset_index()\ .pivot( columns = 'is_click', index = 'day', values = 'user_id' ).reset_index() # Calculate the percent of users who clicked on the ad by day for b_clicks b_clicks_pivot['percentage_clicked'] = b_clicks_pivot[True] / (b_clicks_pivot[True] + b_clicks_pivot[False]) # Examine b_clicks_pivot print(b_clicks_pivot)
Markdown
UTF-8
197
2.96875
3
[]
no_license
# Final: Accumulator Pattern Given a string input by a user (like "hello"), return an object that counts the letters and then display the content within the HTML page. ```{h:1, e:1, l:2, o:1}```
PHP
UTF-8
297
2.765625
3
[ "Apache-2.0" ]
permissive
<?php try { // buat koneksi dengan database $pdo = new PDO('mysql:host=localhost;dbname=electrical', 'root', ''); } catch (PDOException $e) { // tampilkan pesan kesalahan jika koneksi gagal print "Koneksi atau query bermasalah: " . $e->getMessage() . "<br/>"; die(); } ?>
Java
UTF-8
331
2.03125
2
[]
no_license
/** * */ package socket; import java.io.IOException; /** * @author ZHU Yuting * */ public class Main { /** * @param args */ public static void main(String[] args) throws IOException { System.out.println("Begin..."); MultiServer server = new MultiServer(); server.server(); } }
JavaScript
UTF-8
1,085
3.25
3
[]
no_license
document.getElementById('page-loaded').innerHTML = (new Date()).toLocaleTimeString(); document.querySelector('button').addEventListener('click', getData); document.querySelector('#get-html').addEventListener('click', getHtmlData); function getData() { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { const client = JSON.parse(xhr.responseText); document.getElementById('client-name').innerHTML = client.name; document.getElementById('client-address').innerHTML = client.address; document.getElementById('client-age').innerHTML = client.age; } } xhr.open('GET', 'client.json', true); xhr.send(); } function getHtmlData() { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById('info-html').innerHTML = xhr.responseText; } } xhr.open('GET', 'client.html', true); xhr.send(); }
JavaScript
UTF-8
1,588
3.25
3
[]
no_license
// target all panel elements const panels = document.querySelectorAll('.panel'); // detail the maximum rotation assumed by the cards const maxRotation = 45; // retrieve the number of panels // the idea is to use the index of each panel vis-a-vis this integer to rotate the cards in an arc const { length } = panels; // when clicking on a panel, loop through the list of elements function handleClick() { panels.forEach((panel) => { // add the prescribed class increasing the flex-grow value (among many other values) // ! only to the selected item and only if the selected item doesn't already have the prescribed class if (panel === this && !panel.classList.contains('hover')) { panel.classList.add('hover'); } else { panel.classList.remove('hover'); } }); } // loop through the list // attach the click event listener on each panel and rotate each item based on its index panels.forEach((panel, index) => { panel.addEventListener('click', handleClick); // consider the distance between the index and the center of the list // this value starts out negative (-3, -2) and proceeds positive const fromHalf = index - (length - 1) / 2; // give the consideration of the halfway point, be sure to double the total rotation, or to halve the length integer // this because fromHalf will be at most equal to half the length of the list panel.style.transform = `rotate(${maxRotation * 2 / length * fromHalf}deg)`; // give a higher z-index value to those elements more distant from the center panel.style.zIndex = Math.abs(fromHalf); });
Markdown
UTF-8
5,267
2.828125
3
[]
no_license
--- author: name: shawkash picture: 110759 body: "While I was suerfing, I found this strange site. And I thought you may like to discuss this new way.\r\nhttp://www.dontclick.it\r\n\r\nDo you think that one day we will surf the internet without useing our hands at all?" comments: - author: name: Eric_West picture: 109470 body: I think there is a lot of potential for something like this. Of course, the current set of interface design theory would have to morph. 2 thumbs up. Thoroughly enjoyable. created: '2005-07-23 03:30:12' - author: name: nepenthe picture: 109675 body: What about right clicking to bring up menus? What about click and drag for selections? Within the context of this site, which requires only simple navigation, no clicking is ok. But I think that so long as we have to drag mice about rather than do everything through the keyboard (like in the old days) because it adds functionality which reduces the amount of stressful wrist movements with the mouse that can make carpal tunnel problems happen. This is why I personally prefer the greater comfort of my tablet, despite the fact that it takes up most of my desk! created: '2005-07-23 05:33:49' - author: name: shawkash picture: 110759 body: I am useing tablet also, it is better in navgiation created: '2005-07-23 12:30:31' - author: name: locus picture: 110840 body: "Great site, a very interesting concept.\r\n\r\n2Nepenthe: dragging can be easily reilzed within the idea (e.g. you hold cursor over the obejct you've got to drag for 5 secs, then it sticks to the cursor and moves till you cursor remains still for 5 secs). The major issue here is usability.\r\n\r\nSpeaking of tablets, do you use the tablet's pen for plain surfing and navigation through software windows? I prefer the tablet's mouse with mine, using pen only in Photoshop." created: '2005-07-24 10:40:59' - author: name: Chris Rugen picture: 110153 body: "It's a very interesting concept, but it's all Flash and there are no unique URLs per page or area, which runs counter to many of the underlying concepts of the web and accessibility in the first place.\r\n\r\nBut judged as an interactive concept alone, it's intriguing. I find all of the movement and reconfiguration to be a bit much, and the information density would require a lot of handling and segmenting so an errant mouse hit wouldn't send the user flying through the site.\r\n\r\nThis all sounds negative, but I do like it." created: '2005-07-24 16:22:59' - author: name: TBiddy picture: 110666 body: It's a nice idea. I agree with Chris...too much Flash. Too many websites do this and make it difficult to navigate their site. Like Chris was saying, with no unique URLs you can't hit the back button and go to information that you were just looking at. As a guy who gets "mouse cramps" on his hand pretty frequently, I'd love to see an interface that just used keyboard commands. Sometimes I hate "meeces to pieces." created: '2005-07-25 18:11:07' - author: name: shawkash picture: 110759 body: "There is some opinions as I see, let's speak about the line which say the site is full of flash: no unique URL. I think this opinion is true. But I think if we think of future of web to make it like a huge multimedia web.. then this site will be a good move. \r\nThe site was speaking about to use click or not to use click, it looks like how scientists think in planes, that they try these days to make the driver of the plane drive it with his head only, I saw a documentary in Discovery Science about that case, which reflects that they are moving forward in this technology in solid steps. Let me say this site is very good as a source for designer who work on flash as web or as CD that it is not necessary to make all your buttons click able! What if you made a button some place in an interactive CD or site working by rolling over your courser on it? It may do a strange effect.\r\nSorry for speaking a lot, but let me declare things by graphics. I made here a small experiment to describe what I mean, this may be used as a surprise for the person who suppose to click.\r\nhttp://www.deviantart.com/view/20981312/\r\nSurprised ?\r\nI saw a file like that in past, by someone I know in channel flash I guess while I was learning Macromedia Flash in 1999, I just made something like it to show you.\r\n\r\n" created: '2005-07-26 00:20:56' - author: name: Chris Rugen picture: 110153 body: "\"<em>But I think if we think of future of web to make it like a huge multimedia web.. </em>\"\r\n\r\nCan you say more about what this means?" created: '2005-07-26 17:05:12' - author: name: shawkash picture: 110759 body: "I think like any complex thing the man is trying to make it more simpler, like every machine has developing every day.. I think one day the web will be all some kind of haveing multimedia like the CDs to be more fun.\r\n\r\n" created: '2005-07-28 16:25:38' date: '2005-07-23 02:48:19' node_type: forum title: You may navigate this site without clicking! ---
Markdown
UTF-8
930
3.375
3
[]
no_license
# Path Finding Visualizer This is visualization tool to visualize various path finding algorithms. There are various options to choose, like create a randomized maze, choose an algorithim to visualize and choose the heuristic to calculate. On pressing ```SPACE```, the code starts running. ## Algorithms <ul> <li> A* Search </li> <li> Breadth First Search</li> <li> Depth First Search</li> <li> Greedy Search </li> <li> Uniform Cost Search </li> </ul> ## Requirements <ol> <li> Python 3 </li> <li> TKinter </li> <li> Pygame </li> </ol> ## Installation To run the app in a windows environment 1. Install python 3.8 2. Run ```pip install pygame```,```pip install tkinter``` 3. Clone/Download the files 4. Run ```python path.py``` to start the application ## Output ![ezgif com-gif-maker](https://user-images.githubusercontent.com/68152189/121096182-4f928880-c80f-11eb-84ce-966796293391.gif)