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
Java
UTF-8
6,196
1.695313
2
[]
no_license
package org.qcri.micromappers.config; import javax.inject.Inject; import javax.sql.DataSource; import org.qcri.micromappers.config.social.CustomConnectController; import org.qcri.micromappers.service.FacebookConnectInterceptor; import org.qcri.micromappers.service.TwitterConnectInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.core.env.Environment; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.encrypt.Encryptors; import org.springframework.social.UserIdSource; import org.springframework.social.config.annotation.ConnectionFactoryConfigurer; import org.springframework.social.config.annotation.EnableSocial; import org.springframework.social.config.annotation.SocialConfigurerAdapter; import org.springframework.social.connect.Connection; import org.springframework.social.connect.ConnectionFactory; import org.springframework.social.connect.ConnectionFactoryLocator; import org.springframework.social.connect.ConnectionRepository; import org.springframework.social.connect.UsersConnectionRepository; import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository; import org.springframework.social.connect.web.ConnectController; import org.springframework.social.connect.web.ReconnectFilter; import org.springframework.social.facebook.api.Facebook; import org.springframework.social.facebook.connect.FacebookConnectionFactory; import org.springframework.social.google.api.Google; import org.springframework.social.google.connect.GoogleConnectionFactory; import org.springframework.social.twitter.api.Twitter; import org.springframework.social.twitter.connect.TwitterConnectionFactory; //import qa.qcri.mm.controller.FacebookConnectInterceptor; //import qa.qcri.mm.controller.TwitterConnectInterceptor; @Configuration @EnableSocial @PropertySource("config.properties") public class SocialConfig extends SocialConfigurerAdapter { @Value("${FACEBOOK_APP_KEY}") private String facebookAppKey; @Value("${FACEBOOK_APP_SECRET}") private String facebookAppSecret; @Value("${TWITTER_APP_KEY}") private String twitterAppKey; @Value("${TWITTER_APP_SECRET}") private String twitterAppSecret; @Value("${GOOGLE_APP_KEY}") private String googleAppKey; @Value("${GOOGLE_APP_SECRET}") private String googleAppSecret; @Value("${application.url}") private String applicationURL; @Inject private DataSource dataSource; @Autowired UserConnectionSignUp userConnectionSignUp; public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) { cfConfig.addConnectionFactory(facebookConnectionFactory()); cfConfig.addConnectionFactory(twitterConnectionFactory()); cfConfig.addConnectionFactory(googleConnectionFactory()); } @Override @Bean public UserIdSource getUserIdSource() { return new UserIdSource() { @Override public String getUserId() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in"); } return authentication.getName(); } }; } @Override public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) { JdbcUsersConnectionRepository jdbcUsersConnectionRepository = new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText()); jdbcUsersConnectionRepository.setConnectionSignUp(userConnectionSignUp); return jdbcUsersConnectionRepository; } @Bean public ReconnectFilter apiExceptionHandler(UsersConnectionRepository usersConnectionRepository, UserIdSource userIdSource) { return new ReconnectFilter(usersConnectionRepository, userIdSource); } private ConnectionFactory<Facebook> facebookConnectionFactory() { FacebookConnectionFactory facebookConnectionFactory = new FacebookConnectionFactory(facebookAppKey, facebookAppSecret); return facebookConnectionFactory; } private ConnectionFactory<Twitter> twitterConnectionFactory() { TwitterConnectionFactory twitterConnectionFactory = new TwitterConnectionFactory(twitterAppKey, twitterAppSecret); return twitterConnectionFactory; } private ConnectionFactory<Google> googleConnectionFactory() { GoogleConnectionFactory googleConnectionFactory = new GoogleConnectionFactory(googleAppKey, googleAppSecret); return googleConnectionFactory; } @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public Facebook facebook(ConnectionRepository repository) { Connection<Facebook> connection = repository.findPrimaryConnection(Facebook.class); return connection != null ? connection.getApi() : null; } @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public Twitter twitter(ConnectionRepository repository) { Connection<Twitter> connection = repository.findPrimaryConnection(Twitter.class); return connection != null ? connection.getApi() : null; } @Bean public TwitterConnectInterceptor twitterConnectInterceptor(){ return new TwitterConnectInterceptor(); } @Bean public FacebookConnectInterceptor facebookConnectInterceptor(){ return new FacebookConnectInterceptor(); } @Bean public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) { ConnectController connectController = new CustomConnectController(connectionFactoryLocator, connectionRepository); connectController.setApplicationUrl(applicationURL); connectController.addInterceptor(facebookConnectInterceptor()); connectController.addInterceptor(twitterConnectInterceptor()); return connectController; } }
TypeScript
UTF-8
1,056
3.125
3
[]
no_license
import { Point } from './point'; import { taxiDiff } from './taxi-diff'; import { Grid } from './grid'; export function findLargestArea(points: Point[]) { const grid = new Grid(points); const numRows = grid.numRows; const numCols = grid.numCols; for (let row = 0; row < numRows; row++) { for (let col = 0; col < numCols; col++) { if (grid.pointExists(row, col)) { continue; } const currentPoint = { x: col, y: row }; const sortedPoints = points .map(p => ({ point: p, distance: taxiDiff(p, currentPoint) })) .sort((a, b) => a.distance - b.distance); if (sortedPoints[0].distance === sortedPoints[1].distance) { continue; } const closestPoint = sortedPoints[0]; if (row === 0 || row === numRows - 1 || col === 0 || col === numCols - 1) { closestPoint.point.infinite = true; } closestPoint.point.area += 1; } } const largestPoint = points.filter(p => !p.infinite).sort((a, b) => b.area - a.area)[0]; return largestPoint.area; }
C
UTF-8
3,517
2.5625
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <sstream> #include <iomanip> #include <vector> #include <deque> #include <list> #include <set> #include <map> #include <stack> #include <queue> #include <bitset> #include <string> #include <numeric> #include <functional> #include <iterator> #include <typeinfo> #include <utility> #include <memory> #include <cmath> #include <cstdlib> #include <cctype> #include <cstddef> #include <complex> #include <ctime> #include <cassert> using namespace std; typedef long long int64; const int inf = 2000000000; static inline int Rint() { struct X{ int dig[256]; X(){ for(int i = '0'; i <= '9'; ++i) dig[i] = 1; dig['-'] = 1; }}; static X fuck;int s = 1, v = 0, c; for (;!fuck.dig[c = getchar()];); if (c == '-') s = 0; else if (fuck.dig[c]) v = c ^ 48; for (;fuck.dig[c = getchar()]; v = v * 10 + (c ^ 48)); return s ? v : -v; } typedef vector<int> vi; typedef vi::iterator ivi; typedef map<int, int> mii; typedef mii::iterator imii; typedef set<int> si; typedef si::iterator isi; #define all(x) (x).begin(), (x).end() #define pb push_back #define mp make_pair #define sz(x) ((int)(x).size()) #define rep(i, s, e) for (int i = (s); i < (e); ++i) #define foreach(itr, c) for(__typeof((c).begin()) itr = (c).begin(); itr != (c).end(); ++itr) template<typename T> static inline void cmax(T& a, const T& b){if(b>a)a=b;} template<typename T> static inline void cmin(T& a, const T& b){if(b<a)a=b;} const int64 mod = 1000002013; struct Pt { int s, t, c; int operator < (const Pt& o) const { if (s != o.s) return s < o.s; return t > o.t; } }; Pt data[1024]; vector<Pt> compose(const vector<Pt>& in) { map<pair<int, int>, int64> t; rep(i, 0, in.size()) if(in[i].c) t[mp(in[i].s, in[i].t)] += in[i].c; vector<Pt> ret; foreach(iter, t) { Pt temp; temp.s = iter->first.first; temp.t = iter->first.second; temp.c = iter->second; ret.pb(temp); } return ret; } int main() { int T = Rint(); for (int cid = 1; cid <= T; ++cid) { int n = Rint(); int m = Rint(); rep(j, 0, m) data[j].s = Rint(), data[j].t = Rint(), data[j].c = Rint(); int64 ans0 = 0; rep(i, 0, m) { int64 diff = data[i].t - data[i].s; int64 x = diff * (diff - 1) / 2 % mod; ans0 = (ans0 + x * data[i].c % mod) % mod; } sort(data, data+m); vector<Pt> u; rep(i, 0, m) u.pb(data[i]); for (;;) { vector<Pt> v; const int size = sz(u); int flag = 0; for (int i = 0; i < size; ++i) if (u[i].c) for (int j = i+1; j < size; ++j) if (u[j].c) { if (i == j) continue; if (u[j].s <= u[i].s) continue; if (u[j].s > u[i].t) break; if (u[j].t <= u[i].t) continue; int64 how = min(u[i].c, u[j].c); if (!how) continue; u[i].c -= how, u[j].c -= how; Pt temp; temp.s = u[i].s; temp.t = u[j].t; temp.c = how; v.pb(temp); temp.s = u[j].s; temp.t = u[i].t; v.pb(temp); flag = 1; } for (int i = 0; i < size; ++i) if (u[i].c) v.pb(u[i]); sort(v.begin(), v.end()); u = compose(v); if (!flag) break; } int64 ans1 = 0; rep(i, 0, u.size()) { int64 diff = u[i].t - u[i].s; int64 x = diff * (diff - 1) / 2 % mod; ans1 = (ans1 + x * u[i].c % mod) % mod; } int64 ans = ans1 - ans0; if (ans < 0) ans += mod; printf("Case #%d: ", cid); printf("%lld\n", ans); } return 0; }
C
UTF-8
605
3.734375
4
[]
no_license
/* * #include <sys/types.h> * #include <unistd.h> * uid_t getuid(void); * gid_t getgid(void); * char *getlogin(void); * * getuid 返回程序关联的UID,通常是启动程序的用户的UID, uid_t 是一个小整数。 * * getgid 返回程序关联的GID 。 * * getlogin 返回用户的名字。 */ #include <sys/types.h> #include <unistd.h> #include <stdio.h> int main() { uid_t uid; gid_t gid; char* user_name; uid = getuid(); gid = getgid(); user_name = getlogin(); printf("uid: %d\n", uid); printf("gid: %d\n", gid); printf("user_name: %s\n", user_name); return 0; }
C++
UTF-8
669
2.75
3
[]
no_license
#include<iostream> #include<string> using namespace std; int main(){ int n,a,b,index1=0,index2=0; cin>>n; int d[100],e[100],out[200],carry=0; for(int i=0;i<n;i++){ cin>>a>>b; index1 = 0; while(a!=0){ d[index1] = a%10; a = a/10; index1++; } index2 = 0; while(b!=0){ e[index2] = b%10; b = b/10; index2++; } for(int j=0;j<index1+index2;j++){ out[j] = 0; for(int k=0;k<=j;k++){ if((j-k)<index2 && k<index1) out[j] = out[j] + d[k]*e[j-k]; } out[j] = out[j] + carry; carry = out[j]/10; out[j] = out[j]%10; } for(int j=index1+index2-1;j>=0;j--){ if(out[j]!=0){ cout<<out[j]; } } } }
C++
UTF-8
1,044
3.5
4
[]
no_license
// Question Link: https://leetcode.com/problems/evaluate-reverse-polish-notation/submissions/ class Solution { public: int evalRPN(vector<string>& tokens) { unordered_set<string> operands = {"+", "-", "*", "/"}; stack<int> s; for (string token : tokens) { // We have a number if (operands.find(token) == operands.end()) { s.push(stoi(token)); } else { // We have an operand int b = s.top(); s.pop(); int a = s.top(); s.pop(); if (token == "+") { s.push(a + b); } else if (token == "-") { s.push(a - b); } else if (token == "*") { s.push(a * b); } else if (token == "/") { s.push(a / b); } } } return s.top(); } };
Python
UTF-8
309
2.96875
3
[]
no_license
# This is my second program in the python.. # I am trying to learn python in the easy way: and I am beginer on the GitHUb .. # Please help and guided me to improve myself and so i will conribute on the Open Source project:: # This program works for if-else condition x=int(input("Enter the value of X:"))
Java
UTF-8
5,184
1.820313
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.graph.impl.facade.bek; import com.intellij.openapi.util.Condition; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcs.log.graph.GraphColorManager; import com.intellij.vcs.log.graph.GraphCommit; import com.intellij.vcs.log.graph.api.GraphLayout; import com.intellij.vcs.log.graph.api.LinearGraph; import com.intellij.vcs.log.graph.api.permanent.PermanentCommitsInfo; import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; public class DelegatedPermanentGraphInfo<CommitId> implements PermanentGraphInfo<CommitId> { @NotNull private final PermanentGraphInfo<CommitId> myDelegateInfo; @NotNull private final BekIntMap myBekIntMap; public DelegatedPermanentGraphInfo(@NotNull PermanentGraphInfo<CommitId> delegateInfo, @NotNull BekIntMap bekIntMap) { myDelegateInfo = delegateInfo; myBekIntMap = bekIntMap; } @NotNull @Override public PermanentCommitsInfo<CommitId> getPermanentCommitsInfo() { final PermanentCommitsInfo<CommitId> commitsInfo = myDelegateInfo.getPermanentCommitsInfo(); return new PermanentCommitsInfo<CommitId>() { @NotNull @Override public CommitId getCommitId(int permanentNodeIndex) { return commitsInfo.getCommitId(myBekIntMap.getUsualIndex(permanentNodeIndex)); } @Override public long getTimestamp(int permanentNodeIndex) { return commitsInfo.getTimestamp(myBekIntMap.getUsualIndex(permanentNodeIndex)); } @Override public int getPermanentNodeIndex(@NotNull CommitId commitId) { int usualIndex = commitsInfo.getPermanentNodeIndex(commitId); return myBekIntMap.getBekIndex(usualIndex); } @NotNull @Override public Set<Integer> convertToCommitIndexes(Collection<CommitId> heads) { Set<Integer> usualIndexes = commitsInfo.convertToCommitIndexes(heads); return ContainerUtil.map2Set(usualIndexes, new Function<Integer, Integer>() { @Override public Integer fun(Integer integer) { return myBekIntMap.getBekIndex(integer); } }); } }; } @NotNull @Override public LinearGraph getPermanentLinearGraph() { final LinearGraph linearGraph = myDelegateInfo.getPermanentLinearGraph(); return new LinearGraph() { @Override public int nodesCount() { return linearGraph.nodesCount(); } @NotNull private List<Integer> convertToBekIndexes(@NotNull List<Integer> usualIndexes) { return ContainerUtil.map(usualIndexes, new Function<Integer, Integer>() { @Override public Integer fun(Integer integer) { return myBekIntMap.getBekIndex(integer); } }); } @NotNull @Override public List<Integer> getUpNodes(int nodeIndex) { return convertToBekIndexes(linearGraph.getUpNodes(myBekIntMap.getUsualIndex(nodeIndex))); } @NotNull @Override public List<Integer> getDownNodes(int nodeIndex) { return convertToBekIndexes(linearGraph.getDownNodes(myBekIntMap.getUsualIndex(nodeIndex))); } }; } @NotNull @Override public GraphLayout getPermanentGraphLayout() { final GraphLayout graphLayout = myDelegateInfo.getPermanentGraphLayout(); return new GraphLayout() { @Override public int getLayoutIndex(int nodeIndex) { return graphLayout.getLayoutIndex(myBekIntMap.getUsualIndex(nodeIndex)); } @Override public int getOneOfHeadNodeIndex(int nodeIndex) { int usualIndex = graphLayout.getOneOfHeadNodeIndex(myBekIntMap.getUsualIndex(nodeIndex)); return myBekIntMap.getBekIndex(usualIndex); } }; } @NotNull @Override public Condition<Integer> getNotCollapsedNodes() { final Condition<Integer> notCollapsedNodes = myDelegateInfo.getNotCollapsedNodes(); return new Condition<Integer>() { @Override public boolean value(Integer bekIndex) { return notCollapsedNodes.value(myBekIntMap.getUsualIndex(bekIndex)); } }; } @NotNull @Override public GraphColorManager<CommitId> getGraphColorManager() { return myDelegateInfo.getGraphColorManager(); } @NotNull @Override public Map<CommitId, GraphCommit<CommitId>> getCommitsWithNotLoadParent() { return myDelegateInfo.getCommitsWithNotLoadParent(); } }
Markdown
UTF-8
14,812
3.109375
3
[]
no_license
# 循序渐进理解CNI机制与Flannel工作原理 CNI,它的全称是 Container Network Interface,即容器网络的 API 接口。kubernetes 网络的发展方向是希望通过插件的方式来集成不同的网络方案, CNI 就是这一努力的结果。CNI 只专注解决容器网络连接和容器销毁时的资源释放,提供一套框架,所以 CNI 可以支持大量不同的网络模式,并且容易实现。 ## 从网络模型到 CNI 在理解 CNI 机制以及 Flannel 等具体实现方案之前,首先要理解问题的背景,这里从 kubernetes 网络模型开始回顾。 从底层网络来看,kubernetes 的网络通信可以分为三层去看待: - Pod 内部容器通信; - 同主机 Pod 间容器通信; - 跨主机 Pod 间容器通信; 对于前两点,其网络通信原理其实不难理解。 1. **对于 Pod 内部容器通信,由于 Pod 内部的容器处于同一个 Network Namespace 下(通过 Pause 容器实现),即共享同一网卡,因此可以直接通信。** 2. **对于同主机 Pod 间容器通信,Docker 会在每个主机上创建一个 Docker0 网桥,主机上面所有 Pod 内的容器全部接到网桥上,因此可以互通。** 而对于第三点,跨主机 Pod 间容器通信,Docker 并没有给出很好的解决方案,而对于 Kubernetes 而言,跨主机 Pod 间容器通信是非常重要的一项工作,但是有意思的是,Kubernetes 并没有自己去解决这个问题,而是专注于容器编排问题,对于跨主机的容器通信则是交给了第三方实现,这就是 CNI 机制。 CNI,它的全称是 Container Network Interface,即容器网络的 API 接口。kubernetes 网络的发展方向是希望通过插件的方式来集成不同的网络方案, CNI 就是这一努力的结果。CNI 只专注解决容器网络连接和容器销毁时的资源释放,提供一套框架,所以 CNI 可以支持大量不同的网络模式,并且容易实现。平时比较常用的 CNI 实现有 Flannel、Calico、Weave 等。 CNI 插件通常有三种实现模式: - **Overlay:靠隧道打通,不依赖底层网络;** - 路由:靠路由打通,部分依赖底层网络; - Underlay:靠底层网络打通,强依赖底层网络; 在选择 CNI 插件时是要根据自己实际的需求进行考量,比如考虑 NetworkPolicy 是否要支持 Pod 网络间的访问策略,可以考虑 Calico、Weave;Pod 的创建速度,Overlay 或路由模式的 CNI 插件在创建 Pod 时比较快,Underlay 较慢;网络性能,Overlay 性能相对较差,Underlay 及路由模式相对较快。 ## Flannel 工作原理 CNI 中经常见到的解决方案是 Flannel,由CoreOS推出,Flannel 采用的便是上面讲到的 Overlay 网络模式。 ### Overlay 网络简介 Overlay 网络 (overlay network) 属于应用层网络,它是面向应用层的,不考虑网络层,物理层的问题。 具体而言, Overlay 网络是指建立在另一个网络上的网络。该网络中的结点可以看作通过虚拟或逻辑链路而连接起来的。虽然在底层有很多条物理链路,但是这些虚拟或逻辑链路都与路径一一对应。例如:许多P2P网络就是 Overlay 网络,因为它运行在互连网的上层。 Overlay 网络允许对没有IP地址标识的目的主机路由信息,例如:Freenet 和DHT(分布式哈希表)可以路由信息到一个存储特定文件的结点,而这个结点的IP地址事先并不知道。 Overlay 网络被认为是一条用来改善互连网路由的途径,让二层网络在三层网络中传递,既解决了二层的缺点,又解决了三层的不灵活。 ### Flannel的工作原理 Flannel 实质上就是一种 Overlay 网络,也就是将 TCP 数据包装在另一种网络包里面进行路由转发和通信,目前已经支持 UDP、VxLAN、AWS VPC 和 GCE 路由等数据转发方式。 **Flannel会在每一个宿主机上运行名为 flanneld 代理,其负责为宿主机预先分配一个子网,并为 Pod 分配IP地址**。Flannel 使用Kubernetes 或 etcd 来存储网络配置、分配的子网和主机公共IP等信息。数据包则通过 VXLAN、UDP 或 host-gw 这些类型的后端机制进行转发。 **Flannel 规定宿主机下各个Pod属于同一个子网,不同宿主机下的Pod属于不同的子网。** ### Flannel 工作模式 支持3种实现:UDP、VxLAN、host-gw, - UDP 模式:使用设备 flannel.0 进行封包解包,不是内核原生支持,**频繁地内核态用户态切换**,性能非常差; - VxLAN 模式:**使用 flannel.1 进行封包解包**,内核原生支持,性能较强; - host-gw 模式:无需 flannel.1 这样的中间设备,直接宿主机当作子网的下一跳地址,性能最强; host-gw的性能损失大约在10%左右,而其他所有基于VxLAN“隧道”机制的网络方案,性能损失在20%~30%左右。 #### UDP 模式 官方已经不推荐使用 UDP 模式,性能相对较差。 UDP 模式的核心就是通过 TUN 设备 flannel0 实现。TUN设备是工作在三层的虚拟网络设备,功能是:在操作系统内核和用户应用程序之间传递IP包。 相比两台宿主机直接通信,多出了 flanneld 的处理过程,这个过程,使用了 flannel0 这个TUN设备,仅在发出 IP包的过程中经过多次用户态到内核态的数据拷贝(linux的上下文切换代价比较大),所以性能非常差 原理如下:![img](https://blog.yingchi.io/posts/2020/8/k8s-flannel/662544-20191022103006305-198547277.png) 以flannel0为例,操作系统将一个IP包发给flannel0,flannel0把IP包发给创建这个设备的应用程序:flannel进程(内核态->用户态) 相反,flannel进程向flannel0发送一个IP包,IP包会出现在宿主机的网络栈中,然后根据宿主机的路由表进行下一步处理(用户态->内核态) 当IP包从容器经过docker0出现在宿主机,又根据路由表进入flannel0设备后,宿主机上的flanneld进程就会收到这个IP包 flannel管理的容器网络里,一台宿主机上的所有容器,都属于该宿主机被分配的“子网”,子网与宿主机的对应关系,存在Etcd中(例如Node1的子网是100.96.1.0/24,container-1的IP地址是100.96.1.2) 当flanneld进程处理flannel0传入的IP包时,就可以根据目的IP地址(如100.96.2.3),匹配到对应的子网(比如100.96.2.0/24),从Etcd中找到这个子网对应的宿主机的IP地址(10.168.0.3) 然后 flanneld 在收到container-1给container-2的包后,把这个包直接封装在UDP包里,发送给Node2(UDP包的源地址,就是Node1,目的地址是Node2) 每台宿主机的flanneld都监听着8285端口,所以flanneld只要把UDP发给Node2的8285端口就行了。然后Node2的flanneld再把IP包发送给它所管理的TUN设备flannel0,flannel0设备再发给docker0 #### VxLAN模式 VxLAN,即Virtual Extensible LAN(虚拟可扩展局域网),是Linux本身支持的一网种网络虚拟化技术。VxLAN可以完全在内核态实现封装和解封装工作,从而通过“隧道”机制,构建出 Overlay 网络(Overlay Network) VxLAN的设计思想是: 在现有的三层网络之上,“覆盖”一层虚拟的、由内核VxLAN模块负责维护的二层网络,使得连接在这个VxLAN二层网络上的“主机”(虚拟机或容器都可以),可以像在同一个局域网(LAN)里那样自由通信。 为了能够在二层网络上打通“隧道”,VxLAN会在宿主机上设置一个特殊的网络设备作为“隧道”的两端,叫VTEP:VxLAN Tunnel End Point(虚拟隧道端点) 原理如下: ![img](https://blog.yingchi.io/posts/2020/8/k8s-flannel/662544-20191022103037567-147724494.png) flannel.1设备,就是VxLAN的VTEP,即有IP地址,也有MAC地址 与UDP模式类似,当container-发出请求后,上的地址10.1.16.3的IP包,会先出现在docker网桥,再路由到本机的flannel.1设备进行处理(进站),为了能够将“原始IP包”封装并发送到正常的主机,VxLAN需要找到隧道的出口:宿主机的VTEP设备,这个设备信息,由宿主机的flanneld进程维护 VTEP设备之间通过二层数据桢进行通信 源VTEP设备收到原始IP包后,在上面加上一个目的MAC地址,封装成一个导去数据桢,发送给目的VTEP设备(获取 MAC地址需要通过三层IP地址查询,这是ARP表的功能)![img](https://blog.yingchi.io/posts/2020/8/k8s-flannel/662544-20191022103148437-452134686.png) 封装过程只是加了一个二层头,不会改变“原始IP包”的内容 这些VTEP设备的MAC地址,对宿主机网络来说没什么实际意义,称为内部数据桢,并不能在宿主机的二层网络传输,Linux内核还需要把它进一步封装成为宿主机的一个普通的数据桢,好让它带着“内部数据桢”通过宿主机的eth0进行传输,Linux会在内部数据桢前面,加上一个我死的VxLAN头,VxLAN头里有一个重要的标志叫VNI,它是VTEP识别某个数据桢是不是应该归自己处理的重要标识。 在Flannel中,VNI的默认值是1,这也是为什么宿主机的VTEP设备都叫flannel.1的原因 一个flannel.1设备只知道另一端flannel.1设备的MAC地址,却不知道对应的宿主机地址是什么。 在linux内核里面,网络设备进行转发的依据,来自FDB的转发数据库,这个flannel.1网桥对应的FDB信息,是由flanneld进程维护的 linux内核再在IP包前面加上二层数据桢头,把Node2的MAC地址填进去。这个MAC地址本身,是Node1的ARP表要学习的,需 Flannel维护,这时候Linux封装的“外部数据桢”的格式如下![img](https://blog.yingchi.io/posts/2020/8/k8s-flannel/662544-20191022103125394-40388131.png) 然后Node1的flannel.1设备就可以把这个数据桢从eth0发出去,再经过宿主机网络来到Node2的eth0 Node2的内核网络栈会发现这个数据桢有VxLAN Header,并且VNI为1,Linux内核会对它进行拆包,拿到内部数据桢,根据VNI的值,所它交给Node2的flannel.1设备 #### host-gw模式 Flannel 第三种协议叫 host-gw (host gateway),这是一种纯三层网络的方案,性能最高,即 Node 节点把自己的网络接口当做 pod 的网关使用,从而使不同节点上的 node 进行通信,这个性能比 VxLAN 高,因为它没有额外开销。**不过他有个缺点, 就是各 node 节点必须在同一个网段中 。** ![img](https://blog.yingchi.io/posts/2020/8/k8s-flannel/662544-20191022103224393-1472403318.png) howt-gw 模式的工作原理,就是将每个Flannel子网的下一跳,设置成了该子网对应的宿主机的 IP 地址,也就是说,宿主机(host)充当了这条容器通信路径的“网关”(Gateway),这正是 host-gw 的含义 所有的子网和主机的信息,都保存在 Etcd 中,flanneld 只需要 watch 这些数据的变化 ,实时更新路由表就行了。 核心是IP包在封装成桢的时候,使用路由表的“下一跳”设置上的MAC地址,这样可以经过二层网络到达目的宿主机。 另外,如果两个 pod 所在节点在同一个网段中 ,可以让 VxLAN 也支持 host-gw 的功能, 即直接通过物理网卡的网关路由转发,而不用隧道 flannel 叠加,从而提高了 VxLAN 的性能,这种 flannel 的功能叫 directrouting。 ### Flannel 通信过程描述 以 UDP 模式为例,跨主机容器间通信过程如下图所示: ![img](https://blog.yingchi.io/posts/2020/8/k8s-flannel/1178573-20191101152442306-2133215750.png) 上图是 Flannel 官网提供的在 UDP 模式下一个数据包经过封包、传输以及拆包的示意图,从这个图片中可以看出两台机器的 docker0 分别处于不同的段:`10.1.20.1/24 `和` 10.1.15.1/24 `,如果从 Web App Frontend1 pod(10.1.15.2)去连接另一台主机上的 Backend Service2 pod(10.1.20.3),网络包从宿主机 192.168.0.100 发往 192.168.0.200,内层容器的数据包被封装到宿主机的 UDP 里面,并且在外层包装了宿主机的 IP 和 mac 地址。这就是一个经典的 overlay 网络,因为容器的 IP 是一个内部 IP,无法从跨宿主机通信,所以容器的网络互通,需要承载到宿主机的网络之上。 以 **VxLAN** 模式为例。 在源容器宿主机中的数据传递过程: 1)**源容器向目标容器发送数据,数据首先发送给 docker0 网桥** 在源容器内容查看路由信息: ``` $ kubectl exec -it -p {Podid} -c {ContainerId} -- ip route ``` 2)**docker0 网桥接受到数据后,将其转交给flannel.1虚拟网卡处理** docker0 收到数据包后,docker0 的内核栈处理程序会读取这个数据包的目标地址,根据目标地址将数据包发送给下一个路由节点: 查看源容器所在Node的路由信息: ``` $ ip route ``` 3)**flannel.1 接受到数据后,对数据进行封装,并发给宿主机的eth0** flannel.1收到数据后,flannelid会将数据包封装成二层以太包。 Ethernet Header的信息: - From:{源容器flannel.1虚拟网卡的MAC地址} - To:{目录容器flannel.1虚拟网卡的MAC地址} 4)**对在flannel路由节点封装后的数据,进行再封装后,转发给目标容器Node的eth0;** 由于目前的数据包只是vxlan tunnel上的数据包,因此还不能在物理网络上进行传输。因此,需要将上述数据包再次进行封装,才能源容器节点传输到目标容器节点,这项工作在由linux内核来完成。 Ethernet Header的信息: - From:{源容器Node节点网卡的MAC地址} - To:{目录容器Node节点网卡的MAC地址} IP Header的信息: - From:{源容器Node节点网卡的IP地址} - To:{目录容器Node节点网卡的IP地址} 通过此次封装,就可以通过物理网络发送数据包。 在目标容器宿主机中的数据传递过程: 5)目标容器宿主机的eth0接收到数据后,对数据包进行拆封,并转发给flannel.1虚拟网卡; 6)flannel.1 虚拟网卡接受到数据,将数据发送给docker0网桥; 7)最后,数据到达目标容器,完成容器之间的数据通信。 ## 参考 - https://blog.csdn.net/alauda_andy/article/details/80132922 - https://blog.csdn.net/liukuan73/article/details/78883847 - https://www.kubernetes.org.cn/6908.html - https://www.cnblogs.com/chenqionghe/p/11718365.html - https://zhuanlan.zhihu.com/p/105942115 - https://www.jianshu.com/p/165a256fb1da - https://www.cnblogs.com/ssgeek/p/11492150.html - https://www.cnblogs.com/sandshell/p/11777312.html
Java
UTF-8
4,766
1.828125
2
[]
no_license
package com.svmuu.ui.activity.settings; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.view.View; import android.widget.TextView; import com.sp.lib.common.support.net.client.SRequest; import com.sp.lib.common.util.ContextUtil; import com.sp.lib.common.util.FileUtil; import com.svmuu.AppDelegate; import com.svmuu.R; import com.svmuu.common.config.Preference; import com.svmuu.common.http.HttpHandler; import com.svmuu.common.http.HttpManager; import com.svmuu.common.http.Response; import com.svmuu.common.receiver.UserChangeReceiver; import com.svmuu.ui.activity.SecondActivity; import com.svmuu.ui.pop.YAlertDialog; import org.apache.http.Header; import org.json.JSONException; import java.io.File; public class SettingActivity extends SecondActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); TextView tv = (TextView) findViewById(R.id.tv_version); PackageInfo packageInfo = ContextUtil.getPackageInfo(); if (packageInfo == null) { tv.setText(getString(R.string.version_s, "0")); } else { tv.setText(getString(R.string.version_s, packageInfo.versionName)); } findViewById(R.id.aboutUs).setOnClickListener(this); findViewById(R.id.suggestion).setOnClickListener(this); findViewById(R.id.clear).setOnClickListener(this); findViewById(R.id.logout).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.aboutUs: { startActivity(new Intent(this, AboutActivity.class)); break; } case R.id.suggestion: { startActivity(new Intent(this, SuggestionActivity.class)); break; } case R.id.clear: { File cacheDir = getCacheDir(); FileUtil.delete(cacheDir); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.warn); builder.setMessage(R.string.cache_clear_ok); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); break; } case R.id.logout: { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.warn); builder.setMessage(R.string.confirm_logout); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SRequest request = new SRequest("logout"); HttpManager.getInstance().postMobileApi(SettingActivity.this, request, new HttpHandler() { @Override public void onResultOk(int statusCode, Header[] headers, Response response) throws JSONException { AppDelegate.getInstance().setUser(null); //如果要清除密码,就启用下面这段代码 // SharedPreferences sp = Preference.get(getApplicationContext(), Preference.USER.class); // sp.edit() // .putString(Preference.USER.USER_PASSWORD, "") // .putBoolean(Preference.USER.IS_SAVE_PASSWORD, false) // .apply(); Intent useChanged = new Intent(UserChangeReceiver.ACTION_USER_CHANGED); sendBroadcast(useChanged); finish(); } }); } }); builder.show(); break; } } super.onClick(v); } }
Python
UTF-8
935
3.734375
4
[]
no_license
# Python program to demonstrate # KNN classification algorithm # on IRIS dataset from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier import numpy as np from sklearn.model_selection import train_test_split # Loads the IRIS dataset iris_dataset=load_iris() X_train, X_test, y_train, y_test = train_test_split(iris_dataset["data"], iris_dataset["target"], random_state=0) # Initialzes KNN classification instance kn = KNeighborsClassifier(n_neighbors=1) kn.fit(X_train, y_train) # Creates a numpy Array x_new = np.array([[5, 2.9, 1, 0.2]]) prediction = kn.predict(x_new) # prints the prediction for the target value print("Predicted target value: {}\n".format(prediction)) # prints the feature name print("Predicted feature name: {}\n".format (iris_dataset["target_names"][prediction])) #prints The test score print("Test score: {:.2f}".format(kn.score(X_test, y_test)))
JavaScript
UTF-8
323
3.78125
4
[]
no_license
'use strict'; // rewrite for loop using map let arr = ["Есть", "жизнь", "на", "Марсе"]; // var arrLength = []; // for (var i = 0; i < arr.length; i++) { // arrLength[i] = arr[i].length; // } arrLength = arr.map(function(value, index, array) { return value.length; }); alert( arrLength ); // 4,5,2,5
C++
UTF-8
402
2.875
3
[]
no_license
#include <iostream> #include <math.h> using namespace std; int main(){ int k = 10; bool star = false; for(int i = 0; i < k; i++){ for(int j = 0; j < k; j++){ if(star){ cout << "*"; } else { cout << "_"; } star = !star; } cout << endl; star = !star; } }
JavaScript
UTF-8
1,937
2.8125
3
[]
no_license
import React from "react"; import { useHistory } from "react-router-dom"; import styles from './home.module.css'; import titleImage from "../../images/X0_Red.png"; import example from "../../images/Example.png"; export function Home() { const history = useHistory(); const goToLogin = () => { history.push("/login"); }; const goToRegister = () => { history.push("/register"); }; return ( <> <h1>Tic-tac-toe</h1> <img src={titleImage} className={styles.topImg} alt="topImg"></img> <h2>Gameplay</h2> <p>In order to win the game, a player must place three of their marks in a horizontal, vertical, or diagonal row. The following example game is won by the first player, X:</p> <img src={example} className={styles.example} alt="example"></img> <p>Players soon discover that the best play from both parties leads to a draw. Hence, tic-tac-toe is most often played by young children, who often have not yet discovered the optimal strategy.</p> <p>Because of the simplicity of tic-tac-toe, it is often used as a pedagogical tool for teaching the concepts of good sportsmanship and the branch of artificial intelligence that deals with the searching of game trees. It is straightforward to write a computer program to play tic-tac-toe perfectly or to enumerate the 765 essentially different positions (the state space complexity) or the 26,830 possible games up to rotations and reflections (the game tree complexity) on this space. If played optimally by both players, the game always ends in a draw, making tic-tac-toe a futile game.</p> <h3>Login or register in order to start playing</h3> <div className={styles.flexBox}> <button className="btn btn-dark" onClick={goToLogin}> Login </button> <button className="btn btn-dark" onClick={goToRegister}> Register </button> </div> </> ); }
C
UTF-8
4,230
2.75
3
[]
no_license
#include <dirent.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/dir.h> #include <sys/types.h> #include <sys/wait.h> extern int ppid; extern int back_size ; extern int back_order[4000]; extern char back_process[400000+1][300]; extern void redirection(char* arg[],int n); extern void chandler(int signum); extern void push(int sig); extern int flagz; extern int flagc; int exec(char * arg[],int n) { pid_t pid; int status ; int background = 0; // printf("%c\n",arg[n-1][0] ); if(arg[n-1][0] == '&') { background = 1; arg[n-1] = NULL; } if((pid = fork())<0) { printf("forking failed\n"); return 0; } if(pid ==0) { if(execvp(arg[0],arg)<0) { printf("Enter a proper command\n"); exit(0); } } else { if(background) { setpgid(pid,pid); signal(SIGCHLD,SIG_IGN); int i; strcpy(back_process[pid],arg[0]); for (i = 0; i < back_size; ++i) { if(back_process[back_order[i]][0]=='\0') { back_order[i] = pid; break; } } if(i == back_size) back_order[back_size++] = pid; printf("[%d] %d\n",i+1, pid); signal(SIGCHLD, SIG_IGN); } else { flagz = 0; flagc = 0; signal(SIGTSTP, push); signal(SIGINT, chandler); while(flagc==0 && flagz==0 && pid != waitpid(pid,&status,WNOHANG) ); if(flagc){ kill(pid,9); wait(NULL); } if(flagz){ setpgid(pid,pid); kill(pid,SIGSTOP); int i; strcpy(back_process[pid],arg[0]); for (i = 0; i < back_size; ++i) { if(back_process[back_order[i]][0]=='\0') { back_order[i] = pid; break; } } if(i == back_size) back_order[back_size++] = pid; printf("[%d] %d\n",i+1, pid); signal(SIGCHLD, SIG_IGN); } flagc = 0; flagz =0; } } } int checkpipes(char* arg[],int p) { // printf("%s-=-\n", arg[p]); for(int i=0; i < strlen(arg[p]) ; i++) { // printf("%c\n", arg[p][i]); if (arg[p][i] == '|') return 1; } return 0; } char ** getargs(char * cmd) { // assumes that cmd ends with NULL char** argsarray; int nargs = 0; int nlen = strlen(cmd); int i = 0; argsarray = (char**) malloc(sizeof(char*) * 256); argsarray[0] = strtok(cmd," "); i = 0; while (argsarray[i] != NULL){ i++; argsarray[i] = strtok(NULL," "); } return argsarray; } void execute_with_pipes(char * arg[], int n) { int fd[256][2]; char * sepCmd[256]; char * pch; int itr =0; int in = 0,out = 0; while(arg[n][itr]!='\0') { if(arg[n][itr]=='<') in =1; if(arg[n][itr]=='>') out =1; itr++; } pch = strtok (arg[n], "|"); int count = 0; while (pch != NULL) { // printf("%s\n", pch); sepCmd[count] = pch; // printf("The value in this array value is: %s\n", sepCmd[count]); pch = strtok (NULL, "|"); count++; } char ** argue; int k; k = 0; pipe(fd[k]); pid_t pid = fork(); if(pid<0) { perror("fork error"); exit(0); } else if(pid==0) { dup2(fd[k][1], STDOUT_FILENO); close(fd[k][0]); argue = getargs(sepCmd[k]); if(in){ redirection(argue,5); } else{ execvp(argue[0], argue); perror(argue[0]); } exit(0); } else if(pid>0) { waitpid(pid,0,0); for(k = 1; k < count - 1; k++) { close(fd[k-1][1]); pipe(fd[k]); if(!fork()) { close(fd[k][0]); dup2(fd[k-1][0], STDIN_FILENO); dup2(fd[k][1], STDOUT_FILENO); argue = getargs(sepCmd[k]); execvp(argue[0], argue); perror(argue[0]); exit(0); } else { while(waitpid(-1, NULL, 0) != -1); } } close(fd[k-1][1]); if(!fork()) { close(fd[k][0]); dup2(fd[k-1][0], STDIN_FILENO); argue = getargs(sepCmd[k]); if(out){ redirection(argue,5); } else{ execvp(argue[0], argue); perror(argue[0]); } exit(0); } else { while(waitpid(-1, NULL, 0) != -1); } } }
Java
UTF-8
304
1.71875
2
[ "Apache-2.0" ]
permissive
package com.bgh.myopeninvoice.api.domain.dto; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) @Data public class RoleDTO implements Serializable { private Integer roleId; private String roleName; }
C
UTF-8
6,909
3.09375
3
[]
no_license
/* * hash_table.c * * Created on: 2012-5-8 * Author: hujin */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <assert.h> #include "clib/hash_table.h" static inline ulong hash_func(string key, uint key_len) { ulong hash = 31; int i; for(i=0;key[i] != 0; i ++) { hash = hash + key[i] * 33; } return hash; } static inline uint get_table_size(uint size) { uint i = 3; uint ret; if (size >= 0x80000000) { /* prevent overflow */ ret = 0x80000000; } else { while ((1U << i) < size) { i++; } ret = 1 << i; } return ret; } hash_table_t * hash_table_new(uint size, hash_table_dtor_func_t dtor) { hash_table_t * ht = malloc(sizeof(hash_table_t)); if(!ht) return NULL; ht->dtor = dtor; ht->size = 0; ht->bucket_size = get_table_size(size); ht->table_mask = ht->bucket_size - 1; ht->curr = NULL; ht->head = NULL; ht->tail = NULL; ht->buckets = calloc(sizeof(hash_bucket_t *), ht->bucket_size); return ht; } hash_table_t * hash_table_init(hash_table_t * ht, uint size, hash_table_dtor_func_t dtor) { ht->dtor = dtor; ht->size = 0; ht->bucket_size = get_table_size(size); ht->table_mask = ht->bucket_size - 1; ht->curr = NULL; ht->head = NULL; ht->tail = NULL; ht->buckets = calloc(sizeof(hash_table_t *), ht->bucket_size); return ht; } void hash_table_rehash(hash_table_t * ht) { ht->bucket_size += ht->bucket_size; ht->table_mask = ht->bucket_size - 1; ht->buckets = realloc(ht->buckets, ht->bucket_size); memset(ht->buckets, 0, ht->bucket_size * sizeof(hash_bucket_t *)); hash_bucket_t * bucket = ht->head; hash_bucket_t ** buckets = ht->buckets; hash_bucket_t * tmp; ulong bidx; while(bucket) { bidx = bucket->idx & ht->table_mask; if(buckets[bidx]) { tmp = buckets[bidx]; while(tmp->next) { tmp = tmp->next; } tmp->next = bucket; }else { buckets[bidx] = bucket; } bucket = bucket->elem_next; } } bool hash_table_sized_insert(hash_table_t * ht, string key, int key_size, pointer data){ ulong idx = hash_func(key, key_size); ulong bidx = idx & ht->table_mask; hash_bucket_t * nb = malloc(sizeof(hash_bucket_t) + key_size); if(!nb) return false; nb->data = data; nb->key_size = key_size; nb->next = NULL; nb->elem_next = NULL; nb->elem_prev = ht->tail; nb->idx = idx; if(ht->size == 0) { ht->head = ht->tail = nb; }else { ht->tail->elem_next = nb; ht->tail = nb; } memcpy(nb->key, key, key_size); hash_bucket_t * bucket = ht->buckets[bidx]; if(!bucket) { ht->buckets[bidx] = nb; }else{// 冲突解决 while(bucket->next) { bucket = bucket->next; } bucket->next = nb; } /* make ht->curr point to the first element of hash table, for iterator use . */ if(ht->size == 0) { ht->curr = nb; } ht->size ++; /* rehash the table when necessary */ if(ht->size >= ht->bucket_size) { hash_table_rehash(ht); } return true; } pointer hash_table_sized_quick_find(hash_table_t * ht, string key, size_t key_size, ulong idx) { ulong bidx = idx & ht->table_mask; hash_bucket_t * bucket = ht->buckets[bidx]; while(bucket) { printf("key:%s\n", bucket->key); if(strcmp(bucket->key, key) == 0) { return bucket->data; } bucket = bucket->next; } return NULL; } bool hash_table_sized_quick_remove(hash_table_t * ht, string key, size_t key_size, ulong idx) { ulong bidx = idx & ht->table_mask; hash_bucket_t * bucket = ht->buckets[bidx], *tmp; if(!bucket) { return false; } while(bucket) { if(strcmp(bucket->key, key) == 0) { goto found; } } return false; found: if(ht->head == bucket) {//found bucket is the head of the doubly linked list . ht->head = bucket->elem_next; }else if(ht->tail == bucket){ ht->tail = bucket->elem_prev; }else { tmp = bucket; bucket->elem_prev->elem_next = tmp->elem_next; bucket->elem_next->elem_prev = tmp->elem_prev; } // remove the bucket from conflict list . if(ht->buckets[bidx] == bucket) { ht->buckets[bidx] = bucket->next; }else { tmp = ht->buckets[bidx]; while(tmp->next && tmp->next != bucket) { break; tmp = tmp->next; } tmp->next = bucket->next; } /* if the deleting bucket is ht->curr, move the ht->curr forward . */ if(ht->curr == bucket) { ht->curr = ht->curr->elem_next; } free(bucket); return true; } bool hash_table_sized_remove(hash_table_t *ht, string key, size_t key_size) { ulong idx = hash_func(key, key_size); return hash_table_sized_quick_remove(ht, key, key_size, idx); } bool hash_table_sized_quick_key_exist(hash_table_t * ht, string key, size_t key_size, ulong idx) { ulong bidx = idx & ht->table_mask; hash_bucket_t * bucket = ht->buckets[bidx]; if(!bucket) { return false; } while(bucket) { if(strcmp(bucket->key, key) == 0) { return true; } bucket = bucket->next; } return false; } bool hash_table_sized_key_exist(hash_table_t *ht, string key, size_t key_size) { ulong idx = hash_func(key, key_size); return hash_table_sized_quick_key_exist(ht, key, key_size, idx); } pointer hash_table_sized_find(hash_table_t * ht, string key, size_t key_size) { ulong idx = hash_func(key, key_size); return hash_table_sized_quick_find(ht, key, key_size, idx); } void hash_table_apply(hash_table_t * ht, hash_table_apply_func_t func, bool reverse) { hash_bucket_t * bucket = reverse ? ht->tail : ht->head; while(bucket) { if(func) { func(bucket->data); } bucket = reverse ? bucket->elem_prev : bucket->elem_next; } } void hash_table_clear(hash_table_t * ht) { hash_bucket_t * bucket = ht->head, *tmp; ulong idx; while(bucket) { if(ht->dtor) { ht->dtor(bucket->data); } idx = bucket->idx; tmp = bucket->elem_next; free(bucket); ht->buckets[idx & ht->table_mask] = NULL; bucket = tmp; } ht->head = ht->tail = NULL; ht->curr = NULL; ht->size = 0; } void hash_table_free(hash_table_t * ht) { assert(ht != NULL); hash_table_clear(ht); free(ht->buckets); free(ht); } void hash_table_destroy(hash_table_t *ht) { assert(ht != NULL); hash_table_clear(ht); free(ht->buckets); } /*****************************************/ /* iterator APIs for hash table */ /*****************************************/ /** * reset internal current pointer . */ inline void hash_table_rewind(hash_table_t *ht) { ht->curr = ht->head; } /** * whether has current data */ inline bool hash_table_current(hash_table_t * ht) { return ht->curr ? true : false; } inline char * hash_table_current_key(hash_table_t * ht) { return ht->curr->key; } inline pointer hash_table_current_data(hash_table_t * ht) { return ht->curr->data; } /** * move internal pointer forward */ inline void hash_table_next(hash_table_t * ht) { if(ht->curr) { ht->curr = ht->curr->elem_next; } } /** * move internal pointer backword. */ inline void hash_table_prev(hash_table_t * ht) { if(ht->curr) { ht->curr = ht->curr->elem_prev; } }
Java
UTF-8
907
3.46875
3
[]
no_license
package com.mrma.t5; import java.util.concurrent.TimeUnit; /** * 一个同步方法可以使用另一个同步方法,一个线程已经拥有了某个对象的锁,再次申请的时候仍然会得到该对象的锁 * 也就是说synchronized获得的锁是可重入的 * @program: thread * @description: * @author: zt648 * @create: 2019-07-15 12:33 **/ public class T { synchronized void m1(){ System.out.println("m1 start"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } m2(); } synchronized void m2(){ try{ TimeUnit.SECONDS.sleep(2); }catch (Exception e){ e.printStackTrace(); } System.out.println(" m2 "); } public static void main(String[] args) { new Thread(()->new T().m1(), "T1 ").start(); } }
PHP
UTF-8
2,904
2.578125
3
[]
no_license
<?php if(!isset($_SESSION)) { session_start(); } $SERVER_PATH = "http://127.0.0.1/bgfhomes/"; $currency = "Euro"; $currency_symbol = "&#8364;"; ##Function for generating the dynamic options ####### function get_new_optionlist($table,$id_col,$value_col,$selected=0, $cond = 1) { global $con; $SQL="SELECT * FROM $table WHERE $cond ORDER BY $value_col"; $rs=mysqli_query($con,$SQL); $option_list="<option value=''>Please Select</option>"; while($data=mysqli_fetch_assoc($rs)) { if($selected==$data[$id_col]){ $option_list.="<option value='$data[$id_col]' selected>$data[$value_col]</option>"; }else{ $option_list.="<option value='$data[$id_col]'>$data[$value_col]</option>"; } } return $option_list; } function get_new_optionlist1($table,$id_col,$value_col,$selected=0, $cond = 1) { global $con; $SQL="SELECT * FROM $table WHERE $cond ORDER BY $value_col"; print_r($SQL);die; $rs=mysqli_query($con,$SQL); $option_list="<option value=''>Please Select</option>"; while($data=mysqli_fetch_assoc($rs)) { if($selected==$data[$id_col]){ $option_list.="<option value='$data[$id_col]' selected>$data[$value_col]</option>"; }else{ $option_list.="<option value='$data[$id_col]'>$data[$value_col]</option>"; } } return $option_list; } ##Function for generating the dynamic options ####### function get_checkbox($name,$table,$id_col,$value_col,$selected=0) { global $con; $selected_array=explode(",",$selected); $SQL="SELECT * FROM $table ORDER BY $value_col"; $rs=mysqli_query($con,$SQL); $option_list=""; while($data=mysqli_fetch_assoc($rs)) { if(in_array($data[$id_col],$selected_array)) { $option_list.="<input type='checkbox' value='$data[$id_col]' name='".$name."[]' id='$name' checked>$data[$value_col]<br>"; } else { $option_list.="<input type='checkbox' value='$data[$id_col]' name='".$name."[]' id='$name'>$data[$value_col]<br>"; } } return $option_list; } #### Function for get Balance Amount #### function getBalance($userID) { global $con; //// Get all Credit Amount ///// $SQL = "SELECT SUM(transaction_amount) as total_credit FROM `transaction` WHERE transaction_type_id = 1 AND transaction_user_id = $userID"; $rs=mysqli_query($con,$SQL); $credit = mysqli_fetch_assoc($rs); //// Get all Credit Amount ///// $SQL = "SELECT SUM(transaction_amount) as total_debit FROM `transaction` WHERE transaction_type_id = 2 AND transaction_user_id = $userID"; $rs=mysqli_query($con,$SQL); $debit = mysqli_fetch_assoc($rs); //// Remaining Balance ////// $remainingBalance = $credit['total_credit'] - $debit['total_debit']; return $remainingBalance; } function getUserBalance($userID) { global $con; //// Get all Credit Amount ///// $SQL = "SELECT balance_amount FROM `user` WHERE user_id = $userID"; $rs=mysqli_query($con,$SQL); $balance_amount = mysqli_fetch_assoc($rs); return $balance_amount['balance_amount']; } ?>
JavaScript
UTF-8
2,398
2.84375
3
[]
no_license
import { Platform } from "react-native"; const fonts = ["Comfortaa", "Roboto_Condensed", "Staatliches", "Circe"]; const defaultFont = fonts[0]; function getFontIndex(fontName) { return fonts.findIndex(font => fontName == font); } const fontStyles = (function(fonts) { if (Platform.OS === "web") { return fonts.map(font => ({ fontFamily: font })); } if (Platform.OS === "android") { return { regular: [ { fontFamily: "Comfortaa-Regular" }, { fontFamily: "RobotoCondensed-Regular" }, // не проверял { fontFamily: "Staatliches-Regular" }, // не проверял { fontFamily: "Circe-Regular" } ], bold: [ { fontFamily: "Comfortaa-Bold" }, { fontFamily: "RobotoCondensed-Bold" }, // не проверял { fontWeight: "bold" }, // не проверял, как default { fontFamily: "Circe-Bold" } ], italic: [ { fontStyle: "italic" }, // как default { fontFamily: "RobotoCondensed-Italic" }, // не проверял { fontStyle: "italic" }, // как default { fontStyle: "italic" } // как default ] }; } if (Platform.OS === "ios") { return false; // пока не знаю } })(fonts); //console.log('fontStyles=', fontStyles); function getKindStyle(kind) { switch (kind) { case "bold": return { fontWeight: "bold" }; case "italic": return { fontStyle: "italic" }; case "default": case "regular": default: return {}; } } function getFontStyle(family, kind = "regular") { let fontIndex = -1; if (family) { fontIndex = getFontIndex(family); } const kindStyle = getKindStyle(kind); if (fontIndex == -1) { return kindStyle; } else { if (Platform.OS === "web") { return { ...fontStyles[fontIndex], ...kindStyle }; } if (Platform.OS === "android") { if (fontStyles.hasOwnProperty(kind)) { return fontStyles[kind][fontIndex]; } else { //console.warn("getFontStyle() Invalid kind=", kind); return kindStyle; } } } } //console.log("Testing fonts:"); [false, "", "default", "regular", "bold", "italic"].forEach(kind => { fonts.forEach(font => { let style = getFontStyle(font, kind); //console.log(font+" "+kind+" -> ", style); }); }); export { fonts, defaultFont, getFontStyle };
C++
UTF-8
614
3.0625
3
[]
no_license
#include <disk_driver.h> DiskDriver::DiskDriver(char *fileName) { this->fileName = fileName; } DiskDriver::~DiskDriver() { this->close(); } bool DiskDriver::open() { this->hd = fopen(this->fileName, "r+"); return hd != NULL; } void DiskDriver::close() { fclose(this->hd); } bool DiskDriver::writeSector(uint8_t *data) { return fwrite(data, 1, 512, this->hd) == 512; } uint8_t* DiskDriver::readSector() { uint8_t* data = (uint8_t*)malloc(512); fread(data, 1, 512, this->hd); return data; } void DiskDriver::seek(uint32_t offset) { fseek(this->hd, offset, SEEK_SET); }
TypeScript
UTF-8
4,235
2.953125
3
[]
no_license
import IDocumentLike from '../NodeLike/ParentNodeLike/DocumentLike/IDocumentLike'; import IRecurser from '../Recurser/IRecurser'; import ITask from './ITask'; import ITaskFunctionMap from './ITaskFunctionMap'; import Recurser from '../Recurser/Recurser'; import TIndexableObject from '../TypeAliases/TIndexableObject'; abstract class AbstractTask implements ITask { /* Allow user-driven tasks to collect results. */ accumulator: TIndexableObject | Array<any> = {}; /* Provides four types of recursion: (left|right)-(top|bottom) */ recurser: IRecurser = new Recurser(); execute: Function = ( document: IDocumentLike, format: string, version: string, options?: TIndexableObject, ): void => { const node = document.documentElement; if (!node) { throw new Error('The node has no root element.'); } const opts = options || {}; let recursionMode = 'left-top'; if (opts.recursionMode && typeof opts.recursionMode === 'string') { recursionMode = opts.recursionMode; } const callback = this.executeMicrotask; if (/left-?top/i.test(recursionMode)) { this.recurser.leftTopRecurse(node, format, version, callback, opts); } else if (/left-?bottom/i.test(recursionMode)) { this.recurser.leftBottomRecurse(node, format, version, callback, opts); } else if (/right-?top/i.test(recursionMode)) { this.recurser.rightTopRecurse(node, format, version, callback, opts); } else if (/right-?bottom/i.test(recursionMode)) { this.recurser.rightBottomRecurse(node, format, version, callback, opts); } else { throw new Error('Unrecognized recursionMode value.'); } } /* Initialize functions as no-ops to prevent from having to sniff their * existence in run(). */ readonly preSetup: Function = () => { return; }; readonly setup: Function = () => { return; }; readonly postSetup: Function = () => { return; }; readonly preExecute: Function = () => { return; }; abstract readonly executeMicrotask: Function; readonly postExecute: Function = () => { return; }; readonly preComplete: Function = () => { return; }; readonly complete: Function = () => { return; }; readonly postComplete: Function = () => { return; }; constructor(functionOrFunctionMap?: Function | ITaskFunctionMap) { /* If the function map is provided, assign the existing properties to * the object. */ if (typeof functionOrFunctionMap === 'function') { this.executeMicrotask = <Function>functionOrFunctionMap; } else if (typeof functionOrFunctionMap !== 'undefined') { const functionMap = <ITaskFunctionMap>functionOrFunctionMap; if (typeof functionMap.preSetup === 'function') { this.preSetup = functionMap.preSetup.bind(this); } if (typeof functionMap.setup === 'function') { this.setup = functionMap.setup.bind(this); } if (typeof functionMap.postSetup === 'function') { this.postSetup = functionMap.postSetup.bind(this); } if (typeof functionMap.preExecute === 'function') { this.preExecute = functionMap.preExecute.bind(this); } if (typeof functionMap.execute === 'function') { this.execute = functionMap.execute.bind(this); } if (typeof functionMap.executeMicrotask !== 'function') { throw new Error('The executeMicrotask function was not ' + 'provided.'); } this.executeMicrotask = functionMap.executeMicrotask; if (typeof functionMap.postExecute === 'function') { this.postExecute = functionMap.postExecute.bind(this); } if (typeof functionMap.preComplete === 'function') { this.preComplete = functionMap.preComplete.bind(this); } if (typeof functionMap.complete === 'function') { this.complete = functionMap.complete.bind(this); } if (typeof functionMap.postComplete === 'function') { this.postComplete = functionMap.postComplete.bind(this); } } } } export default AbstractTask;
Java
UTF-8
286
1.664063
2
[ "Apache-2.0" ]
permissive
package org.folio.dao.export; import io.vertx.core.Future; import org.folio.rest.jaxrs.model.ExportHistory; import org.folio.rest.persist.DBClient; public interface ExportHistoryRepository { Future<ExportHistory> createExportHistory(ExportHistory exportHistory, DBClient client); }
Java
UTF-8
389
2.6875
3
[]
no_license
package pe.egcc.app.prueba; /** * * @author Eric Gustavo Coronel Castillo * @blog gcoronelc.blogspot.com */ public class Prueba01 { public static void main(String[] args) { String[] ciudades = { "Lima","Londres","Paris", "New York","Roma","Berlín" }; for (int i = 0; i < ciudades.length; i++) { String ciudad = ciudades[i]; System.out.println(ciudad); } } }
Python
UTF-8
1,835
3.453125
3
[]
no_license
#!/usr/bin/env python3 import re sub = { 'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e', 'e': 'f', 'f': 'g', 'g': 'h', 'h': 'i', 'i': 'j', 'j': 'k', 'k': 'l', 'l': 'm', 'm': 'n', 'n': 'o', 'o': 'p', 'p': 'q', 'q': 'r', 'r': 's', 's': 't', 't': 'u', 'u': 'v', 'v': 'w', 'w': 'x', 'x': 'y', 'y': 'z' } def has_straight(password): for i in range(len(password)-2): if (password[i] in sub and password[i+1] in sub and sub[password[i]] == password[i+1] and sub[password[i+1]] == password[i+2]): return True return False def has_no_bad_chars(password): return bool(re.search(r'[iol]', password)) == False def has_pairs(password): return bool(re.search(r'([a-z])\1.*([a-z])\2', password)) == True def is_valid_password(password): return (has_straight(password) and has_no_bad_chars(password) and has_pairs(password)) def increment_password(old_password): letters = list(old_password) for i in range(len(letters)-1, -1, -1): if letters[i] != 'z': letters[i] = sub[letters[i]] break letters[i] = 'a' return ''.join(letters) def next_password(old_password): next = old_password while True: next = increment_password(next) if is_valid_password(next): return next return None def run_tests(): assert(is_valid_password('ghjaabcc')) assert(is_valid_password('abcdffaa')) assert(not is_valid_password('hijklmmn')) assert(not is_valid_password('abbceffg')) assert(not is_valid_password('abbcegjk')) assert(next_password('abcdefgh') == 'abcdffaa') assert(next_password('ghijklmn') == 'ghjaabcc') # run_tests() first = next_password('vzbxkghb') print(first) print(next_password(first))
JavaScript
UTF-8
1,510
3.546875
4
[]
no_license
// var element = document.getElementById("app") // console.log(element); // // // element.innerHTML = "Howdy"; (function(exports) { function NoteController(notesList = new NotesList()) { this.notesList = notesList this.notesList.createAndStoreNote("Favourite drink: Ribena") this.notesListView = new NotesListView(notesList) } NoteController.prototype.insertNoteIntoHTML = function () { var element = document.getElementById('app') return element.innerHTML = this.notesListView.htmlReturn(); }; NoteController.prototype.makeURLChangeShowNoteForCurrentPage = function () { var boundShowNoteForCurrentPage = this.showNoteForCurrentPage.bind(this); window.addEventListener("hashchange", boundShowNoteForCurrentPage); }; NoteController.prototype.showNoteForCurrentPage = function () { var noteId = this.getNoteFromURL(window.location) var notes = this.notesList.returnNotes() var note = notes.find(function(element) { return element.id === parseInt(noteId); }) this.showNote(note); }; NoteController.prototype.getNoteFromURL = function (location) { return location.hash.split("#")[1]; }; NoteController.prototype.showNote = function (note) { var notes = new SingleNoteView(note) document .getElementById('app') .innerHTML = notes.returnNote(); }; exports.NoteController = NoteController; })(this) var ayo = new NoteController() ayo.insertNoteIntoHTML() ayo.makeURLChangeShowNoteForCurrentPage();
C#
UTF-8
3,255
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Timataka.Core.Models.Entities; using Timataka.Core.Models.ViewModels.CategoryViewModels; namespace Timataka.Core.Data.Repositories { public class CategoryRepository : ICategoryRepository { private readonly ApplicationDbContext _db; private bool _disposed; public CategoryRepository(ApplicationDbContext db) { _db = db; } public void Insert(Category c) { _db.Categories.Add(c); _db.SaveChanges(); } public async Task InsertAsync(Category c) { await _db.Categories.AddAsync(c); await _db.SaveChangesAsync(); } public IEnumerable<Category> Get() { return _db.Categories.ToList(); } public Category GetById(int id) { return _db.Categories.SingleOrDefault(x => x.Id == id); } public Task<Category> GetByIdAsync(int id) { return _db.Categories.SingleOrDefaultAsync(x => x.Id == id); } public void Edit(Category c) { _db.Categories.Update(c); _db.SaveChanges(); } public async Task EditAsync(Category c) { _db.Categories.Update(c); await _db.SaveChangesAsync(); } public void Remove(Category c) { _db.Categories.Remove(c); _db.SaveChanges(); } public async Task<int> RemoveAsync(Category c) { _db.Categories.Remove(c); await _db.SaveChangesAsync(); return 1; } public Task<Category> GetCategoryByNameAsync(string cName) { return _db.Categories.SingleOrDefaultAsync(x => x.Name == cName); } public IEnumerable<CategoryViewModel> GetListOfCategoriesForEvent(int eventId) { var categories = (from c in _db.Categories join e in _db.Events on c.EventId equals e.Id join country in _db.Countries on c.CountryId equals country.Id into cc from country in cc.DefaultIfEmpty() where c.EventId == eventId select new CategoryViewModel { EventId = e.Id, Id = c.Id, AgeFrom = c.AgeFrom, AgeTo = c.AgeTo, CountryId = c.CountryId.GetValueOrDefault(0), CountryName = country.Name ?? "All", Name = c.Name, EventName = e.Name, Gender = c.Gender }).ToList(); return categories; } protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { _db.Dispose(); } } this._disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
Python
UTF-8
3,323
2.84375
3
[]
no_license
import os import hashlib import sys MAX_BLOCK_SIZE = 1024 * 1024 def load_snapshot_folder(PROJECT_FOLDER): snapshot_folder = '{0}/.snapshot'.format(PROJECT_FOLDER) if not os.path.exists(snapshot_folder): print('Snapshot does not exists') return -1 return snapshot_folder def init(PROJECT_FOLDER): snapshot_folder = load_snapshot_folder(PROJECT_FOLDER) if (snapshot_folder == -1): snapshot_folder = '{0}/.snapshot'.format(PROJECT_FOLDER) print('Initializing snapshot...') os.mkdir(snapshot_folder) print('Snapshot initialized') return snapshot_folder def snap(PROJECT_FOLDER): print('Snapping...') snapshot_folder = load_snapshot_folder(PROJECT_FOLDER) if (snapshot_folder == -1): print('Please init snapshot') exit(3) dirs = os.listdir(PROJECT_FOLDER) if '.snapshot' not in dirs: print('No snapshot found. Please initialize snapshot') exit(4) dirs.remove('.snapshot') copy_project_to_snapshot(PROJECT_FOLDER, snapshot_folder) def copy_project_to_snapshot(source, destination): dirs = os.listdir(source) if '.snapshot' in dirs: dirs.remove('.snapshot') for blob in dirs: source_blob_dir = '{0}/{1}'.format(source, blob) if os.path.isfile(source_blob_dir): transfer_file(source_blob_dir, destination, blob) continue destination_blob_dir = '{0}/{1}'.format(destination, blob) if not os.path.exists(destination_blob_dir): os.mkdir(destination_blob_dir) copy_project_to_snapshot(source_blob_dir, destination_blob_dir) def transfer_file(source_blob_dir, destination, blob): destination_blob_dir = '{0}/{1}'.format(destination, blob) if (os.path.exists(destination_blob_dir)): source_file_hash = compute_file_hash(source_blob_dir) destination_file_hash = compute_file_hash(destination_blob_dir) if source_file_hash == destination_file_hash: print('{0} is not changed.'.format(source_blob_dir)) return source_blob = open(source_blob_dir, 'rb') destination_blob = open(destination_blob_dir, 'w+b') while True: blob_data = source_blob.read(MAX_BLOCK_SIZE) if not blob_data: break destination_blob.write(blob_data) source_blob.close() destination_blob.close() def compute_file_hash(file_src): source_file = open(file_src, 'rb') sha256 = hashlib.sha256() while True: source_data = source_file.read(MAX_BLOCK_SIZE) if not source_data: break sha256.update(source_data) return sha256.hexdigest() def help(): help = open('./help', 'r') print(help.read()) help.close() def intro(): intro = open('./intro', 'r') print(intro.read()) intro.close() def main(): args = sys.argv if (len(args) <= 1): intro() help() return command = args[1] if (command == 'init'): if (len(args) < 3): print('Please specify project folder') help() return PROJECT_FOLDER = args[2] init(PROJECT_FOLDER) return if (command == 'snap'): if (len(args) < 3): print('Please specify project folder') help() return PROJECT_FOLDER = args[2] snap(PROJECT_FOLDER) return if (command == '-v'): intro() return print('Invalid command') intro() help() return if __name__ == '__main__': main()
Java
UTF-8
503
2.546875
3
[]
no_license
package com.steam.common; /** * @author : JOSE 2019/3/11 10:01 PM */ public class SteamException extends RuntimeException { /** 返回code */ private int code; /** 返回信息 */ private String message; public SteamException(int code, String message) { super(message); this.code = code; this.message = message; } public int getCode() { return code; } @Override public String getMessage() { return message; } }
Java
UTF-8
1,828
2.421875
2
[]
no_license
package za.co.devj.projectsv2.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import za.co.devj.projectsv2.R; import za.co.devj.projectsv2.pojo.feedClass.Feeds; /** * Created by Codetribe on 3/20/2017. */ public class FeedsAdapter extends RecyclerView.Adapter<FeedsAdapter.MyViewHolder> { ArrayList<Feeds> feed_list; Context c; @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_cards,parent,false); c = v.getContext(); return new MyViewHolder(v); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { Feeds feeds = feed_list.get(position); holder.tv_desc.setText(feeds.getDesc()); holder.tv_title.setText(feeds.getTitle()); Picasso.with(c).load(feeds.getImgUrl()).into(holder.img); } @Override public int getItemCount() { return feed_list.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { ImageView img; TextView tv_title, tv_desc; public MyViewHolder(View itemView) { super(itemView); img = (ImageView) itemView.findViewById(R.id.feed_image); tv_title = (TextView) itemView.findViewById(R.id.tv_feed_title); tv_desc = (TextView) itemView.findViewById(R.id.tv_feed_desc); } } public FeedsAdapter(ArrayList<Feeds> feed_list) { this.feed_list = feed_list; } }
PHP
UTF-8
291
2.875
3
[]
no_license
<?php /** Log class * * Is under development. Is intended to write log to a file... :) * */ class Log extends CI_Model { function __construct() { parent::__construct(); } public function message($level, $message) { $level = strtoupper($level); echo "$level: $message"; } }
Java
UTF-8
568
3.28125
3
[]
no_license
package java8; import java.util.ArrayList; import java.util.List; public class MethodReference { public static void main(String[] args) { objectinstanceMethodreference(); } private static void objectinstanceMethodreference() { List<String> namelist = new ArrayList<String>(); namelist.add("Aravind"); namelist.add("Geetha"); namelist.add("Purvi"); namelist.forEach(item -> System.out.println(item)); namelist.forEach(System.out::println); namelist.forEach(item ->{ if(item.length()>5) System.out.println("Condition:" +item);}); } }
Java
UTF-8
1,816
2.109375
2
[]
no_license
package com.spring.ot.dao; import java.sql.SQLException; import java.util.List; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import com.spring.command.SearchCriteria; import com.spring.dto.AdminVO; import com.spring.ot.dto.OtVO; public class OtDAOImpl implements OtDAO{ private SqlSession session; public void setSqlSession(SqlSession session) { this.session = session; } @Override public List<OtVO> selectOtList(SearchCriteria cri) throws SQLException { int offset = cri.getStartRowNum(); int limit = cri.getPerPageNum(); RowBounds rowBounds = new RowBounds(offset, limit); List<OtVO> otList = session.selectList("OtBoard-Mapper.selectOtList", cri, rowBounds); return otList; } @Override public OtVO selectOtByOtNo(int otNo) throws SQLException { OtVO ot = session.selectOne("OtBoard-Mapper.selectOtByOtNo", otNo); return ot; } @Override public int selectOtListCount(SearchCriteria cri) throws SQLException { int count = session.selectOne("OtBoard-Mapper.selectOtListCount", cri); return count; } @Override public void insertOtBoard(OtVO ot) throws SQLException { session.update("OtBoard-Mapper.insertOtBoard", ot); } @Override public void updateOtBoard(OtVO ot) throws SQLException { session.update("OtBoard-Mapper.updateOtBoard", ot); } @Override public void deleteOtBoard(int otNo) throws SQLException { session.update("OtBoard-Mapper.deleteOtBoard", otNo); } @Override public int checkExistByEmpNo(String empNo) throws SQLException { int chk = session.selectOne("OtBoard-Mapper.checkExistByEmpNo", empNo); return chk; } @Override public AdminVO getAdminByEmpNo(String empNo) throws SQLException { AdminVO admin = session.selectOne("OtBoard-Mapper.getAdminByEmpNo", empNo); return admin; } }
Markdown
UTF-8
558
3.34375
3
[]
no_license
## Snake A browser version of Snake. Game logic is written in Javascript, while HTML canvas draws the images. A live version can be found [here](https://philnachumsnake.firebaseapp.com/) Use the arrow keys to move, and P to pause/unpause. ### Rules The aim of the game is to eat as much food as possible. Eating one piece of food earns one point. When the snake eats a piece of food, it grows in length, and another piece of food is randomly placed on the screen. The game ends when the snake either collides with the edge of the screen, or with itself.
Java
UTF-8
3,383
2.515625
3
[]
no_license
package com.jinqiu.zombieattack.view.attached; import android.graphics.PointF; import com.jinqiu.zombieattack.model.GameModel; /** The transformation between view, model and screen */ public class ModelViewScreenTrans { /** The view frame width */ private static final int VIEW_FRAME_WIDTH = 854; /** The view frame height */ private static final int VIEW_FRAME_HEIGHT = 480; /** The game frame width */ private static final int GAME_FRAME_WIDTH = GameModel.getGameFrameWidth(); /** The game frame height */ private static final int GAME_FRAME_HEIGHT = GameModel.getGameFrameHeight(); /** The width of the game in the view */ private static final int GAME_IN_VIEW_WIDTH = 760; /** The height of the game in the view */ private static final int GAME_IN_VIEW_HEIGHT = GAME_FRAME_HEIGHT; /** The left top position of the game in the view */ private static final PointF GAME_IN_VIEW_SHIFT = new PointF(60, 0); /** Model to screen transformation */ private static FrameTransformation modelToScreenTransformation; /** View to screen transformation */ private static FrameTransformation viewToScreenTransformation; /** Screen to model transformation */ private static FrameTransformation screenToModelTransformation; /** Screen to view transformation */ private static FrameTransformation screenToViewTransformation; /** Whether the transformation is initialized */ private static boolean initialized = false; /** * Initialize the transformation * * @param screenWidth * The screen width * @param screenHeight * The screen height */ public static void initialize(int screenWidth, int screenHeight) { if (!initialized) { // Log.d("screen size", screenWidth + " " + screenHeight); viewToScreenTransformation = new FrameTransformation( VIEW_FRAME_WIDTH, VIEW_FRAME_HEIGHT, screenWidth, screenHeight, new PointF(0, 0)); // Log.d("view to screen scale", viewToScreenTransformation.getScale() // + ""); modelToScreenTransformation = new FrameTransformation( GAME_FRAME_WIDTH, GAME_FRAME_HEIGHT, GAME_IN_VIEW_WIDTH, GAME_IN_VIEW_HEIGHT, GAME_IN_VIEW_SHIFT); modelToScreenTransformation = modelToScreenTransformation .addFrameTransformation(viewToScreenTransformation); // Log.d("model to screen scale", // modelToScreenTransformation.getScale() + ""); screenToModelTransformation = modelToScreenTransformation .getBackwardTransformation(); screenToViewTransformation = viewToScreenTransformation .getBackwardTransformation(); initialized = true; } } /** * Get the model to screen transformation * * @return The transformation */ public static FrameTransformation getModelToScreenTransformation() { return modelToScreenTransformation; } /** * Get the screen to model transformation * * @return The transformation */ public static FrameTransformation getScreenToModelTransformation() { return screenToModelTransformation; } /** * Get the view to screen transformation * * @return The transformation */ public static FrameTransformation getViewToScreenTransformation() { return viewToScreenTransformation; } /** * Get the screen to view transformation * * @return The transformation */ public static FrameTransformation getScreenToViewTransformation() { return screenToViewTransformation; } }
Python
UTF-8
1,362
3.171875
3
[]
no_license
import pygame pygame.init() screen = pygame.display.set_mode((800, 600)) done = False color1 = (0, 128, 255) color2 = (255, 0, 0) is_color1 = True x = 30 y = 30 # playerImage = pygame.image.load("pygame_idle.png") # def player(x, y): # screen.blit(playerImage, (x, y)) while not done: for event in pygame.event.get(): # event on quit if event.type == pygame.QUIT: # event.type == pygame.KEYDOWN done = True # Change color on press space key if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: is_color1 = not is_color1 # Move # if event.type == pygame.KEYDOWN: # if event.key == pygame.K_UP: # y -= 3 # if event.key == pygame.K_DOWN: # y += 3 # if event.key == pygame.K_LEFT: # x -= 3 # if event.key == pygame.K_RIGHT: # x += 3 pressed = pygame.key.get_pressed() if pressed[pygame.K_UP]: y -= 1 if pressed[pygame.K_DOWN]: y += 1 if pressed[pygame.K_LEFT]: x -= 1 if pressed[pygame.K_RIGHT]: x += 1 if is_color1: color = color1 else: color = color2 screen.fill((0, 0, 0)) pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60)) pygame.display.flip() pygame.quit()
JavaScript
UTF-8
3,006
2.515625
3
[]
no_license
import { sendUpdate, delay, either, getInput } from './loop'; import {call} from 'redux-saga/effects'; import {countdown} from './utils'; import {CODE_NAMES, RESET_GAME_INPUT, YOUR_CODENAME_PHASE, PARTNER_CODENAME_PHASE, INPUT_PASSWORDS_PHASE, ROUND_END_PHASE, GAME_END_PHASE, LOBBY_PHASE, GUESS_PASSWORD_INPUT, ADD_PLAYER_INPUT, START_GAME_INPUT} from '../common/constants'; const shuffle = require('shuffle-array'); const _ = require('lodash'); import {runRound, isPlayerFinished} from './round'; const ROUNDS = 3; const MIN_NUM_PLAYERS = 2; const GAME_EXPIRY_MS = 60000; const GAME_END_EXPIRY_MS = 120000; const INPUT_PASSWORDS_TIMEOUT_MS = 30000; const BETWEEN_ROUNDS_DELAY = 10000; const SCORES = [3,2,1]; export function* lobby() { let players = {}; yield sendUpdate({ scores: {}, players: players, phase: LOBBY_PHASE }); let gameStarted = false; let expired = false; while (!gameStarted && !expired) { yield either( call(getPlayer), call(startGame), call(function *() { yield* countdown(GAME_EXPIRY_MS); expired = true; }) ); } return yield sendUpdate({ expired, players }); function* startGame() { yield getInput(START_GAME_INPUT); const canStartGame = Object.keys(players).length >= MIN_NUM_PLAYERS; if (canStartGame) { gameStarted = true; } } function* getPlayer() { const { clientId, data } = yield getInput(ADD_PLAYER_INPUT); players = { ...players, [clientId]: { playerId: clientId, name: data.name } }; yield sendUpdate({players}); } } export function* runGame() { let expired = false; while (!expired) { let game = yield* lobby(); if (game.expired) { console.log('GAME EXPIRED'); return; } const players = _.values(game.players).map(player => player.playerId); yield sendUpdate({ phase: ROUND_END_PHASE }); yield* countdown(BETWEEN_ROUNDS_DELAY); for (let round = 0; round < ROUNDS; round++) { yield sendUpdate({round}); game = yield* runRound(players, round); if (round === ROUNDS - 1) { continue; } yield sendUpdate({ phase: ROUND_END_PHASE, scores: getUpdatedScores(game) }); yield* countdown(BETWEEN_ROUNDS_DELAY); } yield sendUpdate({ phase: GAME_END_PHASE, scores: getUpdatedScores(game)}); yield either( getInput(RESET_GAME_INPUT), call(function *() { yield* countdown(GAME_END_EXPIRY_MS); expired = true; }) ); } } function getUpdatedScores(game) { let scores = game.scores; _.values(game.round.players).forEach(player => { if (!isPlayerFinished(player)) { return; } const playerId = player.playerId; scores = { ...scores, [playerId]: (scores[playerId] || 0) + 1 }; }); return scores; }
Python
UTF-8
555
4.71875
5
[]
no_license
#Parametros y argumentos #Funcion Sumar def sumar(a, b, c): return a + b + c resultado = sumar(4,5,6) print("La suma es: ", resultado) #Funcion Restar def restar (a, b): return a - b resultado = restar(b= 100, a=10) print("La resta es: ", resultado) #Guardar una funcion en una variable valor = restar print(valor(20,30)) def multiples_valores(): return "String", 12, True string, entero, bol = multiples_valores() print(string, entero, bol) def nueva_funcion(funcion): print(funcion(50,30)) resta = restar nueva_funcion(resta)
Java
UTF-8
2,641
2.46875
2
[]
no_license
/** * Copyright 2014 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common.detector; import org.junit.Assert; import org.junit.Test; /** * Tests {@link MathUtils}. */ public final class MathUtilsTestCase extends Assert { private static final float EPSILON = 1.0E-8F; @Test public void testRound() { Assert.assertEquals((-1), MathUtils.round((-1.0F))); Assert.assertEquals(0, MathUtils.round(0.0F)); Assert.assertEquals(1, MathUtils.round(1.0F)); Assert.assertEquals(2, MathUtils.round(1.9F)); Assert.assertEquals(2, MathUtils.round(2.1F)); Assert.assertEquals(3, MathUtils.round(2.5F)); Assert.assertEquals((-2), MathUtils.round((-1.9F))); Assert.assertEquals((-2), MathUtils.round((-2.1F))); Assert.assertEquals((-3), MathUtils.round((-2.5F)));// This differs from Math.round() Assert.assertEquals(Integer.MAX_VALUE, MathUtils.round(Integer.MAX_VALUE)); Assert.assertEquals(Integer.MIN_VALUE, MathUtils.round(Integer.MIN_VALUE)); Assert.assertEquals(Integer.MAX_VALUE, MathUtils.round(Float.POSITIVE_INFINITY)); Assert.assertEquals(Integer.MIN_VALUE, MathUtils.round(Float.NEGATIVE_INFINITY)); Assert.assertEquals(0, MathUtils.round(Float.NaN)); } @Test public void testDistance() { Assert.assertEquals(((float) (Math.sqrt(8.0))), MathUtils.distance(1.0F, 2.0F, 3.0F, 4.0F), MathUtilsTestCase.EPSILON); Assert.assertEquals(0.0F, MathUtils.distance(1.0F, 2.0F, 1.0F, 2.0F), MathUtilsTestCase.EPSILON); Assert.assertEquals(((float) (Math.sqrt(8.0))), MathUtils.distance(1, 2, 3, 4), MathUtilsTestCase.EPSILON); Assert.assertEquals(0.0F, MathUtils.distance(1, 2, 1, 2), MathUtilsTestCase.EPSILON); } @Test public void testSum() { Assert.assertEquals(0, MathUtils.sum(new int[]{ })); Assert.assertEquals(1, MathUtils.sum(new int[]{ 1 })); Assert.assertEquals(4, MathUtils.sum(new int[]{ 1, 3 })); Assert.assertEquals(0, MathUtils.sum(new int[]{ -1, 1 })); } }
C++
UTF-8
4,555
2.5625
3
[]
no_license
#ifndef __LUP__ #define __LUP__ #include <vector> #include <cmath> #include <fstream> #include <iostream> #include "matrix.hpp" #include "vector.hpp" using namespace std; int m_detSign = 1; void m_frontSub(Matrix &mat, vector <double> &vec, vector <double> &vecP, vector <double> &vecZ) { int n = mat.getSize(); for (int i = 0; i < n; ++i) { double sum = 0.0; for (int j = 0; j < i; ++j) { sum += mat.get(i, j) * vecZ[j]; } vecZ[i] = vec[(int)vecP[i]] - sum; } } void m_backSub(Matrix &mat, vector <double> &vec, vector <double> &vecX) { int n = mat.getSize(); for (int i = n - 1; i >= 0; --i) { double sum = 0.0; for (int j = i + 1; j < n; ++j) { sum += mat.get(i, j) * vecX[j]; } vecX[i] = (vec[i] - sum) / mat.get(i, i); } } bool m_lup(Matrix &mat, Matrix &matL, Matrix &matU, vector <double> &vecP) { int n = mat.getSize(); m_detSign = 1; matU.copy(mat); for (int i = 0; i < n; ++i) { vecP[i] = i; } for (int j = 0; j < n; ++j) { int row = -1; double max = 0.0; for (int i = j; i < n; ++i) { double element = abs(matU.get(i, j)); if (element > max) { max = element; row = i; } } if (row == -1) { return false; } if (row != j) { m_detSign *= -1; } matU.swapRows(j, row); matL.swapRows(j, row); matL.set(j, j, 1); swap(vecP[j], vecP[row]); for (int i = j + 1; i < n; ++i) { double ratio = matU.get(i, j) / matU.get(j, j); for (int k = j; k < n; ++k) { matU.set(i, k, matU.get(i, k) - matU.get(j, k) * ratio); } matL.set(i, j, ratio); } } return true; } void matInverse(Matrix &mat, Matrix &matInv) { int n = mat.getSize(); vector <double> vec1(n); vector <double> vec2(n); vector <double> vecP(n); vector <double> vecX(n); Matrix matL(n); Matrix matU(n); Matrix matE(n); m_lup(mat, matL, matU, vecP); matE.identity(); for (int j = 0; j < n; ++j) { for (int i = 0; i < n; ++i) { vec1[i] = matE.get(i, j); } m_frontSub(matL, vec1, vecP, vec2); m_backSub(matU, vec2, vecX); for (int i = 0; i < n; ++i) { matInv.set(i, j, vecX[i]); } } } double matDet(Matrix &mat) { int n = mat.getSize(); double res = 1.0; Matrix matL(n); Matrix matU(n); vector <double> vecP(n); m_lup(mat, matL, matU, vecP); for (int i = 0; i < n; ++i) { res *= matU.get(i, i); } return res * m_detSign; } bool lup(Matrix &mat, vector <double> &vec, vector <double> &vecX) { int n = mat.getSize(); Matrix matL(n); Matrix matU(n); vector <double> vecP(n); vector <double> vecZ(n); if (!m_lup(mat, matL, matU, vecP)) { return false; } m_frontSub(matL, vec, vecP, vecZ); m_backSub(matU, vecZ, vecX); return true; } void method1() { ifstream fin("../data/in1.txt"); ofstream fout("../data/out1.txt"); int n, tmp; fin >> n;//int n; Matrix mat(n, n); vector <double> vec(n); vector <double> vecX(n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { fin >> tmp; mat.set(i, j, tmp); } } for (int i = 0; i < n; ++i) { fin >> vec[i]; } Matrix matInv(n); if (!lup(mat, vec, vecX)) { fout << "Degenerate matrix\n"; } else { matInverse(mat, matInv); fout << "Answer (vector):\n"; for (int i = 0; i < n; ++i) { fout << vecX[i] << " "; } fout << "\nInverse matrix:\n"; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { fout << matInv.get(i, j) << " "; } fout << "\n"; } fout << "Determinant: " << matDet(mat) << "\n"; } } #endif
Java
UTF-8
11,365
2.1875
2
[]
no_license
/* * An XML document type. * Localname: Text * Namespace: http://api.callfire.com/data * Java type: com.callfire.api.data.TextDocument * * Automatically generated - do not modify. */ package com.callfire.api.data; /** * A document containing one Text(@http://api.callfire.com/data) element. * * This is a complex type. */ public interface TextDocument extends org.apache.xmlbeans.XmlObject { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(TextDocument.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.sF5862003E60B0EFBE9BF7C4370E02CB6").resolveHandle("text7da6doctype"); /** * Gets the "Text" element */ com.callfire.api.data.TextDocument.Text getText(); /** * Sets the "Text" element */ void setText(com.callfire.api.data.TextDocument.Text text); /** * Appends and returns a new empty "Text" element */ com.callfire.api.data.TextDocument.Text addNewText(); /** * An XML Text(@http://api.callfire.com/data). * * This is a complex type. */ public interface Text extends com.callfire.api.data.Action { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(Text.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.sF5862003E60B0EFBE9BF7C4370E02CB6").resolveHandle("text330felemtype"); /** * Gets the "Message" element */ java.lang.String getMessage(); /** * Gets (as xml) the "Message" element */ org.apache.xmlbeans.XmlString xgetMessage(); /** * True if has "Message" element */ boolean isSetMessage(); /** * Sets the "Message" element */ void setMessage(java.lang.String message); /** * Sets (as xml) the "Message" element */ void xsetMessage(org.apache.xmlbeans.XmlString message); /** * Unsets the "Message" element */ void unsetMessage(); /** * Gets array of all "TextRecord" elements */ com.callfire.api.data.TextRecordDocument.TextRecord[] getTextRecordArray(); /** * Gets ith "TextRecord" element */ com.callfire.api.data.TextRecordDocument.TextRecord getTextRecordArray(int i); /** * Returns number of "TextRecord" element */ int sizeOfTextRecordArray(); /** * Sets array of all "TextRecord" element */ void setTextRecordArray(com.callfire.api.data.TextRecordDocument.TextRecord[] textRecordArray); /** * Sets ith "TextRecord" element */ void setTextRecordArray(int i, com.callfire.api.data.TextRecordDocument.TextRecord textRecord); /** * Inserts and returns a new empty value (as xml) as the ith "TextRecord" element */ com.callfire.api.data.TextRecordDocument.TextRecord insertNewTextRecord(int i); /** * Appends and returns a new empty value (as xml) as the last "TextRecord" element */ com.callfire.api.data.TextRecordDocument.TextRecord addNewTextRecord(); /** * Removes the ith "TextRecord" element */ void removeTextRecord(int i); /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static com.callfire.api.data.TextDocument.Text newInstance() { return (com.callfire.api.data.TextDocument.Text) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static com.callfire.api.data.TextDocument.Text newInstance(org.apache.xmlbeans.XmlOptions options) { return (com.callfire.api.data.TextDocument.Text) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } private Factory() { } // No instance of this class allowed } } /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static com.callfire.api.data.TextDocument newInstance() { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static com.callfire.api.data.TextDocument newInstance(org.apache.xmlbeans.XmlOptions options) { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } /** @param xmlAsString the string value to parse */ public static com.callfire.api.data.TextDocument parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); } public static com.callfire.api.data.TextDocument parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); } /** @param file the file from which to load an xml document */ public static com.callfire.api.data.TextDocument parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); } public static com.callfire.api.data.TextDocument parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); } public static com.callfire.api.data.TextDocument parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); } public static com.callfire.api.data.TextDocument parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); } public static com.callfire.api.data.TextDocument parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); } public static com.callfire.api.data.TextDocument parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); } public static com.callfire.api.data.TextDocument parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); } public static com.callfire.api.data.TextDocument parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); } public static com.callfire.api.data.TextDocument parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); } public static com.callfire.api.data.TextDocument parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); } public static com.callfire.api.data.TextDocument parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); } public static com.callfire.api.data.TextDocument parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static com.callfire.api.data.TextDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static com.callfire.api.data.TextDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (com.callfire.api.data.TextDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } private Factory() { } // No instance of this class allowed } }
PHP
UTF-8
922
2.6875
3
[]
no_license
<?php namespace App\Entity; use App\Repository\StatusCodesRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=StatusCodesRepository::class) * @ORM\Table(name="status_codes") */ class StatusCodes { /** * @var string * * @ORM\Column(name="scode", type="string", length=5, nullable=false) * @ORM\Id */ private $scode; /** * @var string|null * * @ORM\Column(name="title", type="string", length=30, nullable=true) */ private $title; public function getScode(): ?string { return $this->scode; } public function setScode(string $code): self { $this->scode = $code; return $this; } public function getTitle(): ?string { return $this->title; } public function setTitle(?string $title): self { $this->title = $title; return $this; } }
PHP
UTF-8
637
3.3125
3
[ "MIT" ]
permissive
<?php namespace thorin; /** * Extract the url's from the passed string. Return the result in array format * * @param {String} $string The string to extract the url's from * @return {Array} The array of url's extracted * * @example php * $string = 'Hello https://google.com, this is the universe talking'; * Thorin::extract_urls_from_str($string); * // ['https://google.com'] * * @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io) */ function extract_urls_from_str($string) { $urls = \Purl\Url::extract($string); $urls = array_map(function($url) { return (string) $url; }, $urls); return $urls; }
Java
UTF-8
3,063
1.78125
2
[]
no_license
package com.xiaojing.shop.mode; import com.wuzhanglong.library.mode.BaseVO; import java.util.List; /** * Created by ${Wuzhanglong} on 2017/6/2. */ public class GameVO extends BaseVO { private String game_banner; private GameVO datas; private List<GameVO> list; private String game_id; private String game_name; private String game_star; private String game_logo; private String game_card_price; private GameVO merchant; private String game_desc; private String game_ios_download_url; private String game_android_download_url; private List<String> imgs; private String game_banner_url; public String getGame_banner() { return game_banner; } public void setGame_banner(String game_banner) { this.game_banner = game_banner; } public GameVO getDatas() { return datas; } public void setDatas(GameVO datas) { this.datas = datas; } public List<GameVO> getList() { return list; } public void setList(List<GameVO> list) { this.list = list; } public String getGame_id() { return game_id; } public void setGame_id(String game_id) { this.game_id = game_id; } public String getGame_name() { return game_name; } public void setGame_name(String game_name) { this.game_name = game_name; } public String getGame_star() { return game_star; } public void setGame_star(String game_star) { this.game_star = game_star; } public String getGame_logo() { return game_logo; } public void setGame_logo(String game_logo) { this.game_logo = game_logo; } public String getGame_card_price() { return game_card_price; } public void setGame_card_price(String game_card_price) { this.game_card_price = game_card_price; } public GameVO getMerchant() { return merchant; } public void setMerchant(GameVO merchant) { this.merchant = merchant; } public String getGame_desc() { return game_desc; } public void setGame_desc(String game_desc) { this.game_desc = game_desc; } public String getGame_ios_download_url() { return game_ios_download_url; } public void setGame_ios_download_url(String game_ios_download_url) { this.game_ios_download_url = game_ios_download_url; } public String getGame_android_download_url() { return game_android_download_url; } public void setGame_android_download_url(String game_android_download_url) { this.game_android_download_url = game_android_download_url; } public List<String> getImgs() { return imgs; } public void setImgs(List<String> imgs) { this.imgs = imgs; } public String getGame_banner_url() { return game_banner_url; } public void setGame_banner_url(String game_banner_url) { this.game_banner_url = game_banner_url; } }
TypeScript
UTF-8
1,187
2.515625
3
[]
no_license
import {UserActions} from '../redux/actions/UserActions'; import {Api} from './Api'; import {AsyncStorageService} from './AsyncStorage'; import {User} from '../models/user'; export class AuthRepositry { static login(data: { email: string; password: string; returnSecureToken: boolean; }) { return async dispatch => { try { dispatch(UserActions.LoginRequestAction()); const user: User = await Api.login(data); dispatch(UserActions.LoginRequestSuccessAction(user)); await AsyncStorageService.setUser({ email: user.email, idToken: user.idToken, }); return user; } catch (e) { console.log(e); dispatch(UserActions.UserErrorOccurred()); return Promise.reject(e); } }; } static updateUser(user) { return async dispatch => { try { dispatch(UserActions.UserUpdateAction(user)); return; } catch (e) { return Promise.reject(e); } }; } static logout() { return async dispatch => { await AsyncStorageService.clearUser(); dispatch(UserActions.UserLogoutAction()); return; }; } }
JavaScript
UTF-8
7,156
2.515625
3
[]
no_license
var wz, wizard = { settings: { start: $('.btn.open-wizard'), heroLayouts: $('.layout.hero.style-cards'), question: $('.layout.wizard .question'), answers: $('.answer'), result: $('.results .layout'), nextQuestionID: '', backQuestionID: '', buttonControls: $('.layout.wizard .controls .btn'), buttonNext: $('.layout.wizard .controls .btn.next'), buttonBack: $('.layout.wizard .controls .btn.back'), customMsg: $('#custom-message'), wizardOpen: false, }, init: function() { wz = this.settings; this.bindUIActions(); console.log('wizard loaded!'); }, bindUIActions: function() { // Initialize the fancybox $(wz.start).click( function(evt) { evt.preventDefault(); $.fancybox.open({ // Options will go here src : '#wizard', type : 'inline', opts : { afterShow : function( instance, current ) { wz.wizardOpen = true; // console.info( 'Wizard is open! ' + wz.wizardOpen); }, afterClose : function( instance, current ) { wz.wizardOpen = false; // console.info( 'Wizard is closed! ' + wz.wizardOpen); } } }); }); // Closing the fancybox $('.wizard-close-btn').click( function() { $.fancybox.close(); console.log('Close the wizard!'); }); // Selecting an answer wz.answers.click( function(evt) { evt.preventDefault(); wz.nextQuestionID = $(this).attr('href').substr(1); wizard.selectAnswer($(this)); }); // Selecting the next button wz.buttonNext.click( function(evt) { // Check to make sure an answer was selected // If no answer was chosen, display an error message var target = $(this).data('target-question'); // console.log('Target question: ' + target); if (target == 0) { console.log('Target equals 0.'); // Display the custom message if an answer is already selected (from navigating with back and next buttons) if ( $('.question.active .answer').hasClass('selected') ) { console.log('An answer has the selected class.'); wz.customMsg.html( $('.question.active .answer.selected').data('message') ); } else { wz.customMsg.html('Please select an answer.'); } } else { console.log('Target equals ' + target + '.'); // Set the data attribute on the back button wz.backQuestionID = $(this).parents('.wizard').find('.question.active').attr('id'); wz.buttonBack.data('target-question', wz.backQuestionID); wizard.goToQuestion(target); $(this).data('target-question', 0) } }); // Selecting the back button wz.buttonBack.click( function(evt) { window.history.back(); // console.log(window.history); // var target = $(this).data('target-question'); // wizard.goToQuestion(target); }); window.addEventListener('popstate', function(e) { // console.log('Popstate event is happening.'); // call goToQuestion and pass the variable window.location.hash var popstate = window.location.hash.replace('#', ''); // console.log(popstate); // wizard.goToQuestion(popstate); // Remove active class from all questions wz.question.removeClass('active'); // If popstate == empty, go to q1 if (popstate == '') { // console.log('Popstate is empty.'); // Set target question to active $('.wizard .question').first().addClass('active'); } else { if (popstate.length > 3) { // console.log('Popstate length is > 3.'); // This is a result wz.result.removeClass('active'); // Take the popstate value, convert it to an array by exploding the string by comma popstate = popstate.split(','); $.each(popstate, function( index, value) { $('#' + value).addClass('active'); }); // Close the lightbox if (wz.wizardOpen == true) { $.fancybox.close(); } } else { // console.log('Popstate is not empty, but not > 3.'); // This is a question // Set target question to active $('.wizard #' + popstate).addClass('active'); // Open the lightbox if (wz.wizardOpen == false) { $.fancybox.open(); } // $.fancybox.open( $('#wizard') ); } } // Then clear the custom message wz.customMsg.html(''); // Replicating a click of the selected answer var selectedAnswer = $('.question.active .answer.selected'); wz.nextQuestionID = selectedAnswer.attr('id'); wizard.selectAnswer(selectedAnswer); }); // ** // On page load, check for a hashtag in the url and display a result // ** var pageUrl = window.location.hash.replace('#', ''); // console.log('The page url is: ' + pageUrl); if (pageUrl.length > 3) { // This is a result // Remove active class from all results wz.result.removeClass('active'); wz.heroLayouts.removeClass('active'); // Take the hash value, convert it to an array by exploding the string by comma pageUrl = pageUrl.split(',%20'); // console.log('The page url is: ' + pageUrl); $.each(pageUrl, function( index, value) { $('.results #' + value).addClass('active'); }); // Reveal the results content $('.layout.hero.style-cards.results-content').addClass('active'); // Close the lightbox $.fancybox.close(); // Scroll to results // $('html, body').animate({ // scrollTop: $('#results').offset().top - 160 // }, 1500); } else if (pageUrl.length > 0 && pageUrl.length < 3) { // This is a question // Remove active class from all questions wz.question.removeClass('active'); // Set target question to active $('.wizard #' + pageUrl).addClass('active'); // Open the lightbox $.fancybox.open( $('#wizard') ); } }, selectAnswer: function($answer) { // Clear the selected class (from all selected answers) $answer.parents('.wizard').find('.question.active .answer').removeClass('selected'); // Add the selected class $answer.addClass('selected'); // Set the data attribute on the next button wz.buttonNext.data('target-question', wz.nextQuestionID); // Change the custom message according to answer selection wz.customMsg.html( $answer.data('message') ); }, goToQuestion: function($targetQuestion) { // Set a new pushstate history.pushState('Next Question', 'New Page', '#' + $targetQuestion); if ($targetQuestion.length > 3) { // This is a result wz.result.removeClass('active'); wz.heroLayouts.removeClass('active'); // Take the popstate value, convert it to an array by exploding the string by comma // console.log($targetQuestion); $targetQuestion = $targetQuestion.split(', '); $.each($targetQuestion, function( index, value) { $('.results #' + value).addClass('active'); }); $('.layout.hero.style-cards.results-content').addClass('active'); // Close the lightbox $.fancybox.close(); } else { // This is a question // Remove active class from all questions wz.question.removeClass('active'); // Set target question to active $('.wizard #' + $targetQuestion).addClass('active'); } // Then clear the custom message wz.customMsg.html(''); }, // Add a function for changing the pushstate changeUrl: function() { } };
Markdown
UTF-8
4,953
2.578125
3
[ "MIT" ]
permissive
# 浏览器 等待资源加载时间和大部分情况下的浏览器单线程执行是影响Web性能的两大主要原因 #### 浏览器渲染流程 #### 浏览器垃圾回收 标记清除法 - 假定存在一个根对象垃圾回收期将定期从根对象开始查找,凡事从根部出发能到的都会保留,扫描不到的将被回收 - 一组基本的无法删除的根元素 - 全局变量 - 本地函数的局部变量和参数 - 当前嵌套调用链上的其他函数的变量和参数 - 如果引用或者引用链可以从根访问任何其他值,则认为该值是可访问的 - 如果不可访问就是垃圾,会被回收 - https://segmentfault.com/a/1190000018605776 - https://segmentfault.com/a/1190000037588250 几种常见的内存泄露 - 去哪及变量 - 未移除的时间绑定 - 无效的DOM - 定时器setTimeout/setInterval #### 优化 CRP 提升页面加载速度需要通过被加载资源的优先级、控制它们加载的顺序和减小这些资源的体积。性能提示包含 1)通过异步重要资源的下载来减小请求数量,2)优化必须的请求数量和每个请求的文件体积,3)通过区分关键资源的优先级来优化被加载关键资源的顺序,来缩短关键路径长度。 #### 参考资料 - https://juejin.im/post/6844903873887338510 - https://developer.mozilla.org/zh-CN/docs/Web/Performance/%E6%B5%8F%E8%A7%88%E5%99%A8%E6%B8%B2%E6%9F%93%E9%A1%B5%E9%9D%A2%E7%9A%84%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86 - https://developer.mozilla.org/zh-CN/docs/Web/Performance - [读懂浏览器渲染流程](https://www.sohu.com/a/223805109_820120) #### 浏览器的加载流程 - 服务端请求和响应 - 通过域名查找DNS(如果之前没有访问过)获取ip地址 - 获得了IP地址通过TCP与服务器建立连接 - 响应请求 - 加载过程 - 解析html文档,浏览器通过网络接收的数据转换为DOM和CSSOM的步骤,通过渲染器把DOM和CSSOM在屏幕上绘制成页面 - 构建DOM树 - 执行脚本 - JavaScript被解释、编译、解析和执行。脚本被解析为抽象语法树。一些浏览器引擎使用”Abstract Syntax Tree“并将其传递到解释器中,输出在主线程上执行的字节码。这就是所谓的JavaScript编译 - 渲染 - 渲染步骤包括样式、布局、绘制,在某些情况下还包括合成。在解析步骤中创建的CSSOM树和DOM树组合成一个Render树,然后用于计算每个可见元素的布局,然后将其绘制到屏幕上。在某些情况下,可以将内容提升到它们自己的层并进行合成,通过在GPU而不是CPU上绘制屏幕的一部分来提高性能,从而释放主线程 - 样式 - - 布局 - 绘制 #### 建立链接 - 输入域名,通过DNS(域名服务器)查找服务器对应的IP地址 - 浏览器用过TCP三次握手与服务器建立连接 ``` DNS查找域名耗时间所以最好资源的域名要相同,特别是移动网络用户 每一个DNS查找必须从手机发送到信号塔,然后到达一个认证DNS服务器 ``` #### 加载文件 - http1.0 每个文件都要建立一个tcp连接 - http1.1 相同域名可以建立持久连接、支持断点续传、新增了24个错误状态响应码,但是并行请求的连接数只能是4-6个,会阻塞资源的请求 - http1.2 相同域名下只建立一个请求连接通过增加包分帧层将多个资源分成更小的包进行传输,通过不同的头部字段进行区分不同的资源文件 #### 加载解析过程 输入url,加载html. 解析html 构建DOM( document object model)和CSSOM. 构建DOM过程中如果遇到css文件或者js文件就会阻塞DOM的构建, 直到请求回来js并解析执行后才会继续构建。js文件可以会用async和defer来消除js阻塞, 区别在于async会时DOM继续解析 并且加快js并行请求 但是js加载回来还是会阻塞DOM的解析的。 如果用的是defer js则会等到DOM解析完成后再执行。 #### 渲染过程 DOM树和CSSOM树加载完成后构建一棵渲染树,并计算每个可见元素的布局 然后将其绘制到屏幕上。 - 样式是将DOM和CSSOM组合成一个Render树,计算样式树或渲染树从DOM树的根开始构建,遍历每个可见节点。 - 布局是确定呈现树中所有节点的宽度、高度和位置,以及确定页面上每个对象的大小和位置的过程 - 浏览器将在布局阶段计算的每个框转换为屏幕上的实际像素。绘画包括将元素的每个可视部分绘制到屏幕上 - 合成是当文档的各个部分以不同的层绘制,相互重叠时,必须进行合成,以确保它们以正确的顺序绘制到屏幕上,并正确显示内容 - 交互是一旦主线程绘制页面完成,如果加载包含JavaScript(并且延迟到onload事件激发后执行),则主线程可能很忙,无法用于滚动、触摸和其他交互。
Python
UTF-8
399
2.71875
3
[]
no_license
def algorithms(module): """ Retrieves algorithm functions from a module. Raises AssertionError if no functions are provided. :param module: :return: """ blacklist = ['deque', 'defaultdict', 'namedtuple', 'OrderedDict'] l = [getattr(module, attr) for attr in filter(lambda x: x not in blacklist, dir(module)) if callable(getattr(module, attr))] assert l return l
Go
UTF-8
833
2.765625
3
[]
no_license
func abs(a int) int { if a >= 0 { return a } return -a } func minimumEffortPath(heights [][]int) int { m, n := len(heights), len(heights[0]) var l, r, mi int = 0, 2e6, 0 var v [][]bool var cal func(int, int) bool cal = func(i, j int) bool { if i == m-1 && j == n-1 { return true } v[i][j] = true h := heights[i][j] return (i > 0 && !v[i-1][j] && abs(h-heights[i-1][j]) <= mi && cal(i-1, j)) || (j > 0 && !v[i][j-1] && abs(h-heights[i][j-1]) <= mi && cal(i, j-1)) || (i < m-1 && !v[i+1][j] && abs(h-heights[i+1][j]) <= mi && cal(i+1, j)) || (j < n-1 && !v[i][j+1] && abs(h-heights[i][j+1]) <= mi && cal(i, j+1)) } for l < r { mi = l + (r-l)>>1 v = make([][]bool, m) for i := 0; i < m; i++ { v[i] = make([]bool, n) } if cal(0, 0) { r = mi } else { l = mi + 1 } } return l }
Markdown
UTF-8
612
2.78125
3
[]
no_license
# specialcharacter python script to generate special character images This program helps in generating training images for special characters. These images can be used to train the system using ML algorithms To run the program 1. Ensure you have python installed 2. Import PIL and other required modules 3. Download the support files provided here - font.txt contains the fonts we need to style and char.txt contains the chars we need 4. The O/P path where image is stored can be changed to your directory. Images will be generated into the O/P directory. output file is at www.androidfloor.com/spimages.zip
Java
UTF-8
11,839
1.734375
2
[]
no_license
/** * @FileName: MsgBaseServiceImpl.java * @Package com.ziroom.minsu.services.message.service * * @author yd * @created 2016年4月18日 下午2:28:18 * * Copyright 2011-2015 asura */ package com.ziroom.minsu.services.message.service; import com.asura.framework.base.paging.PagingResult; import com.asura.framework.base.util.Check; import com.asura.framework.dao.mybatis.paginator.domain.PageBounds; import com.asura.framework.utils.LogUtil; import com.ziroom.minsu.entity.message.HuanxinImRecordEntity; import com.ziroom.minsu.entity.message.MsgBaseEntity; import com.ziroom.minsu.entity.message.MsgBaseErrorEntity; import com.ziroom.minsu.entity.message.MsgHouseEntity; import com.ziroom.minsu.services.common.dto.PageRequest; import com.ziroom.minsu.services.message.dao.HuanxinImRecordDao; import com.ziroom.minsu.services.message.dao.MsgBaseDao; import com.ziroom.minsu.services.message.dao.MsgBaseErrorDao; import com.ziroom.minsu.services.message.dto.ImMsgListDto; import com.ziroom.minsu.services.message.dto.MsgBaseRequest; import com.ziroom.minsu.services.message.dto.MsgCountRequest; import com.ziroom.minsu.services.message.dto.MsgHouseRequest; import com.ziroom.minsu.services.message.dto.MsgReplyStaticsData; import com.ziroom.minsu.services.message.dto.MsgReplyStaticsRequest; import com.ziroom.minsu.services.message.dto.MsgStaticsRequest; import com.ziroom.minsu.services.message.dto.MsgSyncRequest; import com.ziroom.minsu.services.message.dto.PeriodHuanxinRecordRequest; import com.ziroom.minsu.services.message.entity.AppMsgBaseVo; import com.ziroom.minsu.services.message.entity.ImMsgListVo; import com.ziroom.minsu.services.message.entity.ImMsgSyncVo; import com.ziroom.minsu.services.message.entity.MsgAdvisoryChatVo; import com.ziroom.minsu.services.message.entity.MsgChatVo; import com.ziroom.minsu.services.message.entity.MsgNotReplyVo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * <p>基本消息的服务层</p> * * <PRE> * <BR> 修改记录 * <BR>----------------------------------------------- * <BR> 修改日期 修改人 修改内容 * </PRE> * * @author yd * @since 1.0 * @version 1.0 */ @Service("message.msgBaseServiceImpl") public class MsgBaseServiceImpl { /** * 日志对象 */ private static Logger logger = LoggerFactory.getLogger(MsgBaseServiceImpl.class); @Resource(name = "message.msgBaseDao") private MsgBaseDao msgBaseDao; @Resource(name = "message.msgBaseErrorDao") private MsgBaseErrorDao msgBaseErrorDao; @Resource(name = "message.huanxinImRecordDao") private HuanxinImRecordDao huanxinImRecordDao; /** * * 条件分页查询留言房源关系实体 (房源留言fid必须要有) * * @author yd * @created 2016年4月16日 下午3:41:14 * * @param msgHouseRequest * @return */ public PagingResult<MsgBaseEntity> queryByPage(MsgBaseRequest msgBaseRequest){ if(Check.NuNObj(msgBaseRequest)||Check.NuNStr(msgBaseRequest.getMsgHouseFid())){ LogUtil.error(logger, "msgBaseRequest or msgHouseFid is null"); } LogUtil.info(logger, "当前查询条件msgBaseRequest={}", msgBaseRequest); return msgBaseDao.queryByPage(msgBaseRequest); } /** * * 条件查询 * * @author yd * @created 2016年4月19日 下午8:26:18 * * @param msgBaseRequest * @return */ public List<MsgBaseEntity> queryByCondition(MsgBaseRequest msgBaseRequest){ return msgBaseDao.queryByCondition(msgBaseRequest); } /** * * 保存实体 * * @author yd * @created 2016年4月16日 下午4:49:05 * * @param msgBaseEntity * @return */ public int save(MsgBaseEntity msgBaseEntity){ return this.msgBaseDao.save(msgBaseEntity); } /** * * 根据msgHouseFid 修改留言状态is_del * * @author yd * @created 2016年4月18日 下午1:51:40 * * @param msgHouseFid * @return */ public int updateByMsgHouseFid(String msgHouseFid){ return this.msgBaseDao.updateByMsgHouseFid(msgHouseFid); } /** * * 更新消息为已读状态 * * @author jixd * @created 2016年4月21日 下午9:48:22 * * @param msgHouseFid * @return */ public int updateByMsgHouseReadFid(MsgBaseRequest request){ return this.msgBaseDao.updateByMsgHouseReadFid(request); } /** * * 查询一个对话的未读数量 * * @author jixd * @created 2016年7月5日 下午2:50:11 * * @param msgBaseRequest * @return */ public long queryMsgCountByItem(MsgBaseRequest msgBaseRequest){ return msgBaseDao.queryMsgCountByItem(msgBaseRequest); } /** * * 查询一个房客或者房东消息未读数量 * * @author jixd * @created 2016年7月5日 下午2:50:32 * * @param request * @return */ public long queryMsgCountByUid(MsgCountRequest request){ return msgBaseDao.queryMsgCountByUid(request); } /** * 统计 2小时内 房东回复在30min内回复的新增会话人数 * @author liyingjie * @created 2016年7月5日 下午2:50:32 * @param request * @return */ public Long staticsCountLanImReplyNum(MsgStaticsRequest request){ Long result = msgBaseDao.staticsCountLanImReplyNum(request); return result; } /** * 统计 2小时内 房东回复在30min内的时间和 * @author liyingjie * @created 2016年7月5日 下午2:50:32 * @param request * @return */ public Long staticsCountLanImReplySumTime(MsgStaticsRequest request){ Long result = msgBaseDao.staticsCountLanImReplySumTime(request); return result; } /** * troy查询房东未回复的IM记录(1小时以内) * @author lishaochuan * @create 2016年8月4日下午2:28:03 * @param pageRequest * @return */ public PagingResult<MsgNotReplyVo> getNotReplyList(PageRequest pageRequest){ return msgBaseDao.getNotReplyList(pageRequest); } /** * 条件更新 * @param msgBaseRequest * @return */ public int updateByCondition(MsgBaseEntity msgBaseEntity){ return this.msgBaseDao.updateByCondition(msgBaseEntity); } /** * 根据主记录fid 查询当前最近的咨询信息 * @param msgHouseFid * @return */ public MsgBaseEntity queryCurrMsgBook(String msgHouseFid){ if(Check.NuNStr(msgHouseFid)){ return null; } return msgBaseDao.queryCurrMsgBook(msgHouseFid); } /** * * 房东或房客 条件查询IM聊天历史数据( 数据是当前俩人的聊天数据) * * @author yd * @created 2016年9月14日 上午10:28:13 * * @param msgHouseRequest * @return */ public PagingResult<MsgBaseEntity> queryTwoChatRecord(MsgHouseRequest msgHouseRequest){ return this.msgBaseDao.queryTwoChatRecord(msgHouseRequest); } /** * * 分页 查询当前一个用户 所有的聊天记录 * * @author yd * @created 2016年9月14日 上午10:28:13 * * @param msgHouseRequest * @return */ public PagingResult<AppMsgBaseVo> queryOneChatRecord(MsgHouseRequest msgHouseRequest){ return this.msgBaseDao.queryOneChatRecord(msgHouseRequest); } /** * * IM记录查询 : 分页 查询当前一个用户 所有的聊天记录 * * @author yd * @created 2016年9月14日 上午10:28:13 * * @param msgHouseRequest * @return */ public PagingResult<AppMsgBaseVo> findIMChatRecord(MsgHouseRequest msgHouseRequest){ return this.msgBaseDao.findIMChatRecord(msgHouseRequest); } /** * * 分页 查询当前一个用户 所有的聊天记录 * * @author yd * @created 2016年9月14日 上午10:28:13 * * @param msgHouseRequest * @return */ public List<AppMsgBaseVo> queryOneChatAllRecord(MsgHouseRequest msgHouseRequest){ return this.msgBaseDao.queryOneChatAllRecord(msgHouseRequest); } /** * 查询房东回复时长 * @param request * @return */ public MsgReplyStaticsData queryLanReplyTime(MsgReplyStaticsRequest request){ return msgBaseDao.queryLanReplyTime(request); } /** * * 保存错误消息实体 * * @author yd * @created 2016年11月11日 上午11:49:36 * * @param msgBaseError * @return */ public int saveMsgBaseError(MsgBaseErrorEntity msgBaseError){ return msgBaseErrorDao.saveMsgBaseError(msgBaseError); } /** * * 查询im聊天列表 * * @author yd * @created 2016年4月16日 下午3:41:14 * * @param msgHouseRequest * @return */ public List<ImMsgListVo> queryImMsgList(ImMsgListDto imMsgListDto){ return msgBaseDao.queryImMsgList(imMsgListDto); } /** * 同步消息记录 * @author jixd * @created 2017年04月07日 14:56:35 * @param * @return */ public PagingResult<ImMsgSyncVo> listImMsgSyncList(MsgSyncRequest msgSyncRequest){ return this.msgBaseDao.listImMsgSyncList(msgSyncRequest); } /** * 查询双方的聊天内容 * @author jixd * @created 2017年04月12日 11:00:23 * @param msgFid 消息主表fid * @return */ public List<MsgChatVo> listChatBoth(String msgFid){ return this.msgBaseDao.listChatBoth(msgFid); } /** * house_fid,msg_advisory_fid 维度的消息聊天列表 * @author wangwentao * @created 2017/5/27 15:50 * * @param * @return */ public List<MsgAdvisoryChatVo> listChatOnAdvisory(String msgBaseFid, String fisrtAdvisoryFollowStartTime){ return this.msgBaseDao.listChatOnAdvisory(msgBaseFid, fisrtAdvisoryFollowStartTime); } /** * * 分页查询 聊天信息 * * @author yd * @created 2017年8月2日 下午2:13:30 * * @param msgSyncRequest * @return */ public PagingResult<HuanxinImRecordEntity> queryHuanxinImRecordByPage(MsgSyncRequest msgSyncRequest){ return huanxinImRecordDao.queryHuanxinImRecordByPage(msgSyncRequest); } /** * 获取用户24小时内聊天记录(t_huanxin_im_record表) * * @author loushuai * @created 2017年9月5日 下午2:20:46 * * @param object2Json * @return */ public PagingResult<HuanxinImRecordEntity> queryUserChatInTwentyFour(PeriodHuanxinRecordRequest msgSyncRequest) { return huanxinImRecordDao.queryUserChatInTwentyFour(msgSyncRequest); } /** * t_msg_house查询所有记录 * * @author loushuai * @created 2017年9月26日 下午4:34:38 * * @param msgHouseRe * @return */ public List<MsgHouseEntity> getAllMsgHouseFid(MsgHouseRequest msgHouseRe) { return msgBaseDao.getAllMsgHouseFid(msgHouseRe); } /** * 查询t_msg_base表,填充所有需要的字段 * * @author loushuai * @created 2017年9月26日 下午4:55:30 * * @param fid * @return */ public List<AppMsgBaseVo> fillMsgBaseByMsgHouse(String msgHouseFid) { return msgBaseDao.fillMsgBaseByMsgHouse(msgHouseFid); } /** * t_msg_house查询所有记录(im聊天) * * @author loushuai * @created 2017年10月24日 下午3:56:55 * * @param msgHouseRe * @return */ public List<MsgHouseEntity> getAllMsgHouseFidByIMChatRecord(MsgHouseRequest msgHouseRe) { return msgBaseDao.getAllMsgHouseFidByIMChatRecord(msgHouseRe); } /** * 查询t_msg_base表,填充所有需要的字段 * * @author loushuai * @created 2017年10月24日 下午3:42:38 * * @param fid * @return */ public List<AppMsgBaseVo> getMsgBaseByMsgHouse(String msgHouseFid) { return msgBaseDao.getMsgBaseByMsgHouse(msgHouseFid); } /** * 根据msgBaseFid获取对象 * * @author loushuai * @created 2017年11月6日 下午4:35:31 * * @param msgBaseFid * @return */ public MsgBaseEntity findMsgBaseByFid(String msgBaseFid) { return msgBaseDao.findMsgBaseByFid(msgBaseFid); } /** * 根据param获取两个人所有回话的集合 * * @author loushuai * @created 2017年11月6日 下午4:35:31 * * @param msgBaseFid * @return */ public List<MsgBaseEntity> findAllImByParam(Map<String, Object> param) { return msgBaseDao.findAllImByParam(param); } }
Markdown
UTF-8
5,645
2.9375
3
[ "MIT" ]
permissive
--- layout: post title: A Clean Architecture web API - part two subtitle: An easy to follow structure comments: true published: true --- ## Introduction As mentioned in part one, each service is designed with Clean Architecture principles. Clean Architecture is a smart way of structuring an application, and thrives on some of the principles of good Object Oriented Principles such as SOLID and DRY. But also some design principles as Domain-Driven Design. Domain-Driven Design is first introduced by Eric Evans in his book *"Domain-Driven design"*. Domain-Driven design places the domain rather than the data such as models in the center of an application. The domain means you need to have a great understanding of what kind of problem the software is going to solve. Imagine making a banking system, without knowing what banking really is? To create a system in this way the final product will often not meet the criteria/requirements of the company itself. However, Clean Architecture is embracing this idea of putting the domain in the center, and uses a strict codex for how dependencies should be in your program. ![Onion Architecture](https://paulovich.net/img/CleanArchitecture-Uncle-Bob.jpg) Here is the black arrows the dependencies meaning that the must vulnerable layers, the domain/application is in the middle, and the more non-vulnerable layers are the most outer layers. By vulnerable layers I mean the most often to change. ### The application structure The application structure is fairly organized and therefore easy to setup. Here you can see my solution structure, which gives a clear hint of the dependencies in th program. ![Picture Of Structure](https://i.imgur.com/qiF25Ty.png) The API gateway has no dependencies what so ever to any of the services. The API gateway functions as a kind of proxy redirecting requests to the specific service. The CrossCuttingConcerns project is a project consisting of different options / setup functions for services. This is so I don't have to keep repeating the same code over and over again, essentially following the DRY principle (Don't Repeat Yourself) making my code less prone to bugs. If we look at RequestService structure we will see clear indicators of Clean Architecture. ![Picture Of Service](https://i.imgur.com/zP8I4yX.png) As we can see, we have 5 different projects essentially mirroring the naming from Clean Architecture. Let's try open the projects. ![OpenService](https://i.imgur.com/XsALLWD.png) ## General As we see on the picture above, I split up the infrastructure layer into two separated projects. One dealing with the more generalized Infrastructure such as NotificationService (which can be used with a messagebroker) and a Persistence project using a Code-first Entity Framework Core approach. A SharedKernel/SeedWork is essential a concept from DDD. Reusable code which may not be changed without consulting DevOps or a another team working on the same project. This could be moved to CrossCuttingConcerns, however I haven't got around to do it. ### The domain layer The domain layer consists of our domain models, entities, the data which is saved in the database and mapped to DTO's to be presented. I tried to implement interfaces, and using the repository pattern. However, the Entity Framework Core already is a repository pattern, and there another abstraction would just leave me more confused and would be unnecessary code. Therefore I went with no repository using Entity Framework Cores DbSets instead. ### The application layer / use case layer. This is where the core business logic is handled. I chose the CQRS pattern essentially splitting my application into two different flows/models (Commands and queries). Commands changes the state of the program - writes to the program. Queries reads from a database, and presents it. So essentially the flow would be like this: ![Flow of application](https://i.imgur.com/uq42cuG.png) In an ideal world, the Query would read from a cache to make small less stress on the database. Commands will then report to the cache to change state, whenever a command is successfully executed. The validation is made with use of the library [FluentValidation](https://github.com/JeremySkinner/FluentValidation) which gives the possibility to make use of ValidationFailure exception. An easy way of making custom validation errors and returning BadRequest status code if a command/query is not validated. The whole handler pattern is made with Mediator pattern by using the [Mediatr](https://github.com/jbogard/MediatR) library. The smart thing about an easy structure like this, is that it is easy for new developers to figure out how to implement new functionality to the application. However it can easy be over engineering, if the domain is not complex enough. I made this as a proof of concept, since this could easy be made using a normal CRUD model. ### Infrastructure layer The infrastructure layer is fairly simple. I used FluentAPI to configure my entities, rather than Data annotations, since I didn't want to have that logic in my domain layer (remember to keep dependencies in the domain layer at a minimum to none). The application layer needed to know about the different DbSets to execute handler logic. To do this, I made an interface in the application layer essentially mirroring the DbContext and implemented this in the persistence layer. Because of this, I inverted the dependency, essentially achieving the right dependencies. ### Next part In the next part we will see how I made the two services communicate together via. RestEase HTTP Clients.
Markdown
UTF-8
1,262
3.40625
3
[]
no_license
## RESTful API with NodeJS and MongoDB *** Basic NodeJS and MongoDB RESTful API. This project allows to create, get, update and delete users (with email and password attributes). If you want to test the code you need to follow this steps: * Clone this repository. * Install and setup MongoDB and NodeJS. * Open a terminal at the project folder and do a ``npm install``. * Execute ``npm start``. Now, using [Postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop) or your favorite REST simulator, you can work with the following requests: * **GET** *[localhost:3000/users](localhost:3000/users)*: get all users. * **POST** *[localhost:3000/users](localhost:3000/users)*: create a new user passing *"email"* and *"password"* attributes in JSON format. * **GET** *[localhost:3000/users/:id](localhost:3000/users/:id)*: get an user by its identifier. * **PUT** *[localhost:3000/users/:id](localhost:3000/users/:id)*: update an existing user passing the new *"email"* and *"password"* attributes in JSON format. * **DELETE** *[localhost:3000/users/:id](localhost:3000/users/:id)*: delete an user by its identifier. *** *This code was created following [this post](https://codeforgeek.com/2015/08/restful-api-node-mongodb/).*
Markdown
UTF-8
5,517
2.953125
3
[ "MIT" ]
permissive
json-silo ========= Installation ------------ npm install json-silo Hello json-silo! ---------------- npm start Browse to [localhost:3000/json-silo/](http://localhost:3000/json-silo/) for the story creation page. REST API -------- ### GET /stories/{id} Retrieve the story with the given _id_. #### Example request | Method | Route | Content-Type | |:-------|:-----------------|:-----------------| | GET | /stories/barnowl | application/json | #### Example response { "_meta": { "message": "ok", "statusCode": 200 }, "_links": { "self": { "href": "http://localhost:3000/stories/barnowl" } }, "stories": { "barnowl": { "@context": { "schema": "https://schema.org/" }, "@graph": [ { "@id": "person", "@type": "schema:Person", "schema:givenName": "barnowl" } ] } } } ### POST /stories Create a story. #### Example request | Method | Route | Content-Type | |:-------|:---------|:-----------------| | POST | /stories | application/json | { "@context": { "schema": "https://schema.org/" }, "@graph": [ { "@id": "person", "@type": "schema:Person", "schema:givenName": "barnowl" } ] } #### Example response { "_meta": { "message": "ok", "statusCode": 200 }, "_links": { "self": { "href": "http://localhost:3000/stories" } }, "stories": { "barnowl": { "@context": { "schema": "https://schema.org/" }, "@graph": [ { "@id": "person", "@type": "schema:Person", "schema:givenName": "barnowl" } ] } } } What's in a name? ----------------- The __json-silo__ is exactly that: a data silo for [JSON](https://en.wikipedia.org/wiki/JSON)! Simple enough, right? So why does it have a grain silo with a hockey mask for a mascot? At reelyActive we've always been outspoken about the need for an open Internet of Things as opposed to a bunch of siloed applications. In 2013, on social media we recycled the ["More cowbell" meme](https://en.wikipedia.org/wiki/More_cowbell) with an image of Will Ferrell banging on a grain silo with the caption ["The Internet of Things does not need More Silo"](https://reelyactive.github.io/images/moreSilo.jpg). When it came time to create a mascot for the __json-silo__, we decided to start with that grain silo. Now, how do you visually represent JSON in association with a grain silo? Sure, we could have slapped the official JSON logo on that silo, but where's the fun in that? Instead, for those of us who grew up in the eighties, hearing "JSON" out of context (pun intended) evokes the image of [Jason Voorhees](https://en.wikipedia.org/wiki/Jason_Voorhees) from the Friday the 13th series of films, specifically the iconic hockey goaltender mask he wore. Not only does that "Jason" mask make for a silly visual pun, it also gives a nod to our hometown heritage, where [Jacques Plante](https://en.wikipedia.org/wiki/Jacques_Plante) of the Montreal Canadiens was the first goaltender to wear such a mask full-time, which would later become standard practice. We'd be pleased to see the use of personal data lockers become standard practice too. ![json-silo logo](https://reelyactive.github.io/json-silo/images/json-silo-bubble.png) What's next? ------------ __json-silo__ v1.0.0 was released in August 2019, superseding all earlier versions, the latest of which remains available in the [release-0.5 branch](https://github.com/reelyactive/json-silo/tree/release-0.5) and as [json-silo@0.5.2 on npm](https://www.npmjs.com/package/json-silo/v/0.5.2). This is an active work in progress. Expect regular changes and updates, as well as improved documentation! If you're developing with __json-silo__ check out: * [diyActive](https://reelyactive.github.io/) our developer page * our [node-style-guide](https://github.com/reelyactive/node-style-guide) for development * our [contact information](https://www.reelyactive.com/contact/) to get in touch if you'd like to contribute License ------- MIT License Copyright (c) 2014-2020 [reelyActive](https://www.reelyactive.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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.
Java
UTF-8
432
1.921875
2
[]
no_license
package de.springframework.monitoring.backend.repository; import de.springframework.monitoring.backend.entity.Speciality; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface SpecialityRepository extends PagingAndSortingRepository<Speciality, Long> { Optional<Speciality> findByName(String name); }
Java
GB18030
47,112
1.695313
2
[]
no_license
package nc.bs.scm.pub; import java.rmi.RemoteException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Random; import java.util.Vector; import javax.naming.NamingException; import nc.bs.ml.NCLangResOnserver; import nc.bs.pub.SystemException; import nc.bs.pub.para.SysInitBO; import nc.bs.scm.pub.bill.SQLUtil; import nc.bs.scm.pub.smart.SmartDMO; import nc.vo.bd.access.AccessorManager; import nc.vo.bd.access.BddataVO; import nc.vo.bd.access.IBDAccessor; import nc.vo.pub.AggregatedValueObject; import nc.vo.pub.BusinessException; import nc.vo.pub.VOStatus; import nc.vo.pub.lang.UFBoolean; import nc.vo.pub.lang.UFDouble; import nc.vo.scm.bd.InvVO; import nc.vo.scm.ic.bill.FreeVO; import nc.vo.scm.pu.PuPubVO; import nc.vo.scm.pub.IFreeField; import nc.vo.scm.pub.IMeasDownConv; import nc.vo.scm.pub.IMeasField; import nc.vo.scm.pub.SCMEnv; import nc.vo.scm.pub.smart.SmartVO; /** * ܣDMO * * ԼҪ̨Ĺ * * * ߣ */ public class ScmPubDMO extends nc.bs.pub.DataManageObject { public static final String DEPTDOC = "00010000000000000002"; public static final String AREACL = "00010000000000000012"; public static final String SALESTRU = "00010000000000000020";// ֯v5.02 // by ų /** * ScmPubDMO ע⡣ * * @exception javax.naming.NamingException * 쳣˵ * @exception nc.bs.pub.SystemException * 쳣˵ */ public ScmPubDMO() throws javax.naming.NamingException, nc.bs.pub.SystemException { super(); } /** * ScmPubDMO ע⡣ * * @param dbName * java.lang.String * @exception javax.naming.NamingException * 쳣˵ * @exception nc.bs.pub.SystemException * 쳣˵ */ public ScmPubDMO(String dbName) throws javax.naming.NamingException, nc.bs.pub.SystemException { super(dbName); } /** * ߣӡ ܣ׳RemoteExceptionBO Exception e 쳣 أ * ⣺RemoteException ڣ(2003-03-25 11:39:42) ޸ڣ޸ˣ޸ԭעͱ־ */ public static void throwRemoteException(Exception e) throws java.rmi.RemoteException { if (e instanceof RemoteException) throw (RemoteException) e; else { throw new RemoteException("Remote Call", e); } } /** * V5׳쳣1-쳣 * <p> * <b>examples:</b> * <p> * ʹʾ * <p> * <b>˵</b> * * @param e * @throws BusinessException * <p> * @author czp * @time 2007-3-6 11:12:11 */ public static void throwBusinessException(Exception e) throws BusinessException { if (e instanceof BusinessException) throw (BusinessException) e; else { SCMEnv.out(e); throw new BusinessException(e.getMessage()); } } /** * ߣӡ ܣݴķּ־PKõPKPK String sPkBdInfo * Ϊbd_bdinfopk_bdinfoº壺 pk_bdinfo bdcode bdname 00010000000000000002 * 2 ŵ 00010000000000000012 12 String sCurP ǰPK統ǰĵID * String[] saPk_corp й˾ أString[] PKPK * ⣺пڲѯ¼ʱ׳쳣ӦΪϵͳ쳣 ڣ(2003-4-15 11:39:21) ޸ڣ޸ˣ޸ԭעͱ־ */ private static ArrayList getTotalSubPkAndNames(String sPkBdInfo, String sCurPk, String sCurName, String[] saPk_corp) throws Exception { ArrayList resultArray = new ArrayList(); // ȷԼ if (sPkBdInfo == null) { return null; } int iPk_corpCount = 1; if (saPk_corp != null) { iPk_corpCount = saPk_corp.length; } // IBDAccessor[] ibdaAcc = new IBDAccessor[iPk_corpCount] ; Vector vecPk = new Vector(10); vecPk.addElement(sCurPk); Vector vecName = new Vector(10); vecName.addElement(sCurName); for (int i = 0; i < iPk_corpCount; i++) { IBDAccessor ibdaAcc = null; if (saPk_corp == null) { ibdaAcc = AccessorManager.getAccessor(sPkBdInfo); } else { ibdaAcc = AccessorManager.getAccessor(sPkBdInfo, saPk_corp[i]); } // ԭȵibdaAcc.getChildDocsByHierarchy(sCurPk)ΪibdaAcc.getChildDocs(sCurPk); // ԭgetChildDocsByHierarchyΪҶӽڵǷDzνṹ // ԶsCurPkӦĵıΪǰ׺رǰ׺еӦǷnullɡby zhangcheng // 07-9-18 BddataVO[] voaBdData = ibdaAcc.getChildDocs(sCurPk); if (voaBdData != null) { int iRetLen = voaBdData.length; for (int j = 0; j < iRetLen; j++) { vecPk.addElement(voaBdData[j].getPk()); vecName.addElement(voaBdData[j].getName()); } } } int iSize = vecPk.size(); resultArray.add((String[]) (vecPk.toArray(new String[iSize]))); resultArray.add((String[]) (vecName.toArray(new String[iSize]))); return resultArray; } /** * ߣӡ ܣݴķּ־PKõPKPK String sPkBdInfo * Ϊbd_bdinfopk_bdinfoº壺 pk_bdinfo bdcode bdname 00010000000000000002 * 2 ŵ 00010000000000000012 12 String sCurP ǰPK統ǰĵID * String[] saPk_corp й˾ أString[] PKPK * ⣺пڲѯ¼ʱ׳쳣ӦΪϵͳ쳣 ڣ(2003-4-15 11:39:21) ޸ڣ޸ˣ޸ԭעͱ־ */ public static String[] getTotalSubPks(String sPkBdInfo, String sCurPk, String[] saPk_corp) throws Exception { // ȷԼ if (sPkBdInfo == null) { return null; } int iPk_corpCount = 1; if (saPk_corp != null) { iPk_corpCount = saPk_corp.length; } // IBDAccessor[] ibdaAcc = new IBDAccessor[iPk_corpCount] ; Vector vecPk = new Vector(10); vecPk.addElement(sCurPk); for (int i = 0; i < iPk_corpCount; i++) { IBDAccessor ibdaAcc = null; if (saPk_corp == null) { ibdaAcc = AccessorManager.getAccessor(sPkBdInfo); } else { ibdaAcc = AccessorManager.getAccessor(sPkBdInfo, saPk_corp[i]); } BddataVO[] voaBdData = ibdaAcc.getChildDocs(sCurPk); if (voaBdData != null) { int iRetLen = voaBdData.length; for (int j = 0; j < iRetLen; j++) { vecPk.addElement(voaBdData[j].getPk()); } } } int iSize = vecPk.size(); return (String[]) (vecPk.toArray(new String[iSize])); } /** * ߣά ܣ IDλ ĻϢ ǵһΣвѯHashtableлȡ * ϢڹϣУϣṹ KEY: IDλ VALUE: Object[] [0] UFDouble [1] * Ƿ̶ UFBoolean λĻΪ1.00Ϊ̶ String[] saBaseId ID[] * String]] saAssistUnit λID[] أ ⣺ ڣ(2003-11-13 11:39:21) * ޸ڣ޸ˣ޸ԭעͱ־ */ public HashMap loadBatchInvConvRateInfo(String[] saBaseId, String[] saAssistUnit) throws Exception { HashMap hInvConvRate = new HashMap(); // ȷ if (saBaseId == null || saAssistUnit == null || saBaseId.length == 0) { return hInvConvRate; } int iLen = saBaseId.length; // ʱ ArrayList listTempTableValue = new ArrayList(); for (int i = 0; i < iLen; i++) { if (PuPubVO.getString_TrimZeroLenAsNull(saBaseId[i]) == null || PuPubVO.getString_TrimZeroLenAsNull(saAssistUnit[i]) == null) { continue; } ArrayList listElement = new ArrayList(); listElement.add(saBaseId[i]); listElement.add(saAssistUnit[i]); listTempTableValue.add(listElement); } try { // ʱ String sTempTableName = new nc.bs.scm.pub.TempTableDMO().getTempStringTable( nc.vo.scm.pub.TempTableVO.PU_CLMS_PUB01, new String[] { "cbaseid", "cassistunit" }, new String[] { "char(20) not null ", "char(20) not null " }, null, listTempTableValue); // ѯ Object[][] ob = null; ob = queryResultsFromAnyTable(sTempTableName + " JOIN bd_convert ON " + sTempTableName + ".cbaseid=bd_convert.pk_invbasdoc" + " AND pk_measdoc=" + sTempTableName + ".cassistunit", new String[] { "pk_invbasdoc", "pk_measdoc", "mainmeasrate", "fixedflag" }, null); if (ob != null) { // ǷKEY iLen = ob.length; for (int i = 0; i < iLen; i++) { String sTempKey = (String) ob[i][0] + (String) ob[i][1]; hInvConvRate.put(sTempKey, new Object[] { ob[i][2] == null ? null : new UFDouble(ob[i][2].toString()), new UFBoolean(ob[i][3] == null ? "N" : ob[i][3].toString()) }); } } } catch (Exception e) { reportException(e); throw e; } return hInvConvRate; } /** * ߣӡ ܣݱѯֶΡѯõĽ صĽظ String sTable * SQLFROMַ String[] saFields ѯSQLSELECTַ String sWhere * SQLWHEREַ,ɼORDER BY أObject[][] ṹ£ = * ÿ[]еԪΪfieldk˳еֶεֵ fields[] = * {"d1","d2","d3"}ѯм¼򷵻Object[2][3] [0] һvalue(d1,d2,d3) [1] * ڶvalue(d1,d2,d3) ⣺SQLException SQL쳣 ڣ(2001-08-04 11:39:21) * ޸ڣ޸ˣ޸ԭעͱ־ 2003-03-04 wyf ֶμDISTINCT */ public Object[][] queryResultsFromAnyTable(String sTable, String[] saFields, String sWhere) throws SQLException { // ȷ if (sTable == null || sTable.trim().length() < 1 || saFields == null || saFields.length < 1) { System.out .println("nc.bs.pu.pub.PubBO.queryResultsFromAnyTable(String, String [], String)"); return null; } // Ԫȷ int iLen = saFields.length; for (int i = 0; i < iLen; i++) { if (saFields[i] == null || saFields[i].trim().length() < 1) { System.out .println("nc.bs.pu.pub.PubBO.queryResultsFromAnyTable(String, String [], String)"); return null; } } // SQL StringBuffer sbufSql = new StringBuffer("SELECT DISTINCT "); sbufSql.append(saFields[0]); // + for (int i = 1; i < saFields.length; i++) { sbufSql.append(","); sbufSql.append(saFields[i]); } sbufSql.append(" FROM "); sbufSql.append(sTable); if (PuPubVO.getString_TrimZeroLenAsNull(sWhere) != null) { sbufSql.append(" WHERE "); sbufSql.append(sWhere); } Object[][] rets = null; Vector vec = new Vector(); Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = getConnection(); stmt = con.createStatement(); rs = stmt.executeQuery(sbufSql.toString()); // boolean flag = false; Object o = null; while (rs.next()) { Object[] ob = new Object[saFields.length]; for (int i = 0; i < saFields.length; i++) { o = rs.getObject(i + 1); if (o != null && o.toString().trim().length() > 0) { ob[i] = o; flag = true; } } if (flag) { vec.addElement(ob); } flag = false; } } finally { // رսʱͷԴ try { if (rs != null) rs.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } try { if (con != null) con.close(); } catch (Exception e) { } } if (vec.size() > 0) { rets = new Object[vec.size()][]; for (int i = 0; i < vec.size(); i++) { rets[i] = (Object[]) vec.elementAt(i); } } return rets; } /** * ߣӡ ܣݱѯֶΡѯõĽ String sTable SQLFROMַ * Ϊջմ String sIdName ֶ"corderid" Ϊջմ String[] saFields * ѯ Ϊ,ԪزΪջմ String[] saId ѯID Ϊ,ԪزΪջմ String * sWhere Ϊ أObject[][] ΪջsaIdȡṹ£ fields[] = * {"d1","d2","d3"}=(56,"dge",2002-03-12) ΪձʾδнڣԪΪձIDӦֵڡ * ԪؾΪյؽΪգΪ1 ⣺SQLException SQL쳣 ڣ(2002-04-22 * 11:39:21) ޸ڣ޸ˣ޸ԭעͱ־ */ public Object[][] queryArrayValue(String sTable, String sIdName, String[] saFields, String[] saId, String sWhere) throws Exception { // SQL StringBuffer sbufSql = new StringBuffer("select "); sbufSql.append(sIdName); sbufSql.append(","); sbufSql.append(saFields[0]); int iLen = saFields.length; for (int i = 1; i < iLen; i++) { sbufSql.append(","); sbufSql.append(saFields[i]); } sbufSql.append(" from "); sbufSql.append(sTable); sbufSql.append(" where "); sbufSql.append(sIdName + " in "); String strIdSet = ""; try { nc.bs.scm.pub.TempTableDMO dmoTmpTbl = new nc.bs.scm.pub.TempTableDMO(); strIdSet = dmoTmpTbl.insertTempTable(saId, nc.vo.scm.pub.TempTableVO.TEMPTABLE_PU14, nc.vo.scm.pub.TempTableVO.TEMPPKFIELD_PU); if (strIdSet == null || strIdSet.trim().length() == 0) strIdSet = "('TempTableDMOError')"; } catch (Exception e) { nc.vo.scm.pub.SCMEnv.out(e); throw e; } sbufSql.append(strIdSet + " "); if (sWhere != null && sWhere.trim().length() > 1) { sbufSql.append("and "); sbufSql.append(sWhere); } Hashtable hashRet = new Hashtable(); Vector vec = new Vector(); Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = getConnection(); stmt = con.createStatement(); rs = stmt.executeQuery(sbufSql.toString()); // while (rs.next()) { String sId = rs.getString(1); Object[] ob = new Object[saFields.length]; for (int i = 1; i < saFields.length + 1; i++) { ob[i - 1] = rs.getObject(i + 1); } hashRet.put(sId, ob); } } finally { // رսʱͷԴ try { if (rs != null) rs.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } try { if (con != null) con.close(); } catch (Exception e) { } } Object[][] oRet = null; if (hashRet.size() > 0) { iLen = saId.length; oRet = new Object[iLen][saFields.length]; for (int i = 0; i < iLen; i++) { oRet[i] = (Object[]) hashRet.get(saId[i]); } } return oRet; } /** * ˴뷽˵ : Զŵɰ¼ ߼ 1- ConditionVOа * ""򡰲ŵҴPKֵ ֵ: VO 쳣: : 2003-09-05 л : * * @param condvo * nc.vo.pub.query.ConditionVO[] * @param String[] * saPk_corp й˾ ߼ 1.ȷҪ 2.ȻÿӦҪ滻VOб * 3.滻ԭӦ * * ޸ʱ䣺2007-8-21 ޸ˣų ޸ݣӶ֯ͽṹ֧-Զ֯ɰ¼֯ */ public nc.vo.pub.query.ConditionVO[] getTotalSubPkVO(nc.vo.pub.query.ConditionVO[] condvo, String[] saPk_corp) throws Exception { int lenold; int lennew; lenold = condvo.length; if (lenold <= 0) { return condvo; } // Ƿв String sCurPk = null; boolean flag = false; ArrayList rowdept = new ArrayList(); Integer newint; for (int i = 0; i < lenold; i++) { if ((condvo[i].getFieldName() != null) && (condvo[i].getFieldName().equals("") || condvo[i].getFieldName().equals("ŵ") || condvo[i].getFieldName().equals("֯") // v5.02 // by // zhangcheng || condvo[i].getFieldName().indexOf("") >= 0 // v5.02 // by // zhangcheng ) && (("=".equals(condvo[i].getOperaCode())) || ("like".equals(condvo[i].getOperaCode())) || ("LIKE" .equals(condvo[i].getOperaCode())))) { sCurPk = condvo[i].getValue(); if (sCurPk != null && sCurPk.length() > 0) { newint = new Integer(i); rowdept.add(newint); flag = true; } } } if (!flag) { return condvo; } String[] sRetPk; // List ArrayList arAll = new ArrayList(); for (int j = 0; j < rowdept.size(); j++) { // List ArrayList arPer = new ArrayList(); // ȡ¼ŵID int rowindex = ((Integer) rowdept.get(j)).intValue(); // sCurPk = condvo[rowindex].getValue(); //ж ָ쳣 if(null != condvo[rowindex].getRefResult()) sCurPk = condvo[rowindex].getRefResult().getRefPK(); else sCurPk = NCLangResOnserver.getInstance().getStrByID("scmpub", "UPPscmpub-000054")/* * @res * "Ч룡" */; String sCurName; if (condvo[rowindex].getRefResult() != null) // жϣ״ wj sCurName = condvo[rowindex].getRefResult().getRefName(); else sCurName = NCLangResOnserver.getInstance().getStrByID("scmpub", "UPPscmpub-000054")/* * @res * "Ч룡" */; String sRetName[] = null; // modify by zxj // v5.02޸ģӶ֯Ĵ//////////////////// try { ArrayList retArray = null; if (("ŵ".equals(condvo[rowindex].getFieldName())) || ("".equals(condvo[rowindex].getFieldName()))) { retArray = getTotalSubPkAndNames(DEPTDOC, sCurPk, sCurName, saPk_corp); } else if (("֯".equals(condvo[rowindex].getFieldName()))) { retArray = getTotalSubPkAndNames(SALESTRU, sCurPk, sCurName, saPk_corp); } else if (null != condvo[rowindex].getFieldName()&& condvo[rowindex].getFieldName().indexOf("") >= 0 ) { retArray = getTotalSubPkAndNames(AREACL, sCurPk, sCurName, saPk_corp); } sRetPk = (String[]) retArray.get(0); sRetName = (String[]) retArray.get(1); } catch (Exception e) { nc.vo.scm.pub.SCMEnv.out(e); /** <needn't ??> */ sRetPk = null; } // v5.02޸//////////////////////////////////////// // ֻԭһֵ򲻽滻 if (sRetPk == null || sRetPk.length <= 1) { arAll.add(null); continue; } nc.vo.pub.query.ConditionVO vo; for (int i = 0; i < sRetPk.length; i++) { vo = new nc.vo.pub.query.ConditionVO(); vo.setDataType(condvo[rowindex].getDataType()); vo.setDirty(condvo[rowindex].isDirty()); vo.setFieldCode(condvo[rowindex].getFieldCode()); vo.setFieldName(condvo[rowindex].getFieldName()); vo.setOperaCode(condvo[rowindex].getOperaCode()); vo.setOperaName(condvo[rowindex].getOperaName()); vo.setTableCode(condvo[rowindex].getTableCodeForMultiTable()); vo.setTableName(condvo[rowindex].getTableNameForMultiTable()); vo.setValue(sRetPk[i]); // modify by zxj nc.vo.pub.query.RefResultVO refresultvo = new nc.vo.pub.query.RefResultVO(); refresultvo.setRefPK(sRetPk[i]); refresultvo.setRefName(sRetName[i]); vo.setRefResult(refresultvo); // // ϵλor vo.setLogic(false); // һ,һ if (i == 0) { vo.setNoLeft(false); // ԭţΪand if (!condvo[rowindex].getNoLeft()) { vo.setLogic(true); } else { vo.setLogic(condvo[rowindex].getLogic()); } } else if (i == sRetPk.length - 1) { vo.setNoRight(false); } arPer.add(vo); } // ԭ if (!condvo[rowindex].getNoLeft()) { vo = new nc.vo.pub.query.ConditionVO(); // vo.setDataType(condvo[rowindex].getDataType()); // Ϊ,ϳΪ1=1 ַϳ1='1'ݿΪǷ vo.setDataType(1); vo.setFieldCode("1"); vo.setOperaCode("="); vo.setValue("1"); vo.setLogic(condvo[rowindex].getLogic()); vo.setNoLeft(false); arPer.add(0, vo); } // ԭ if (!condvo[rowindex].getNoRight()) { vo = new nc.vo.pub.query.ConditionVO(); // vo.setDataType(condvo[rowindex].getDataType()); vo.setDataType(1); vo.setFieldCode("1"); vo.setOperaCode("="); vo.setValue("1"); vo.setLogic(true); vo.setNoRight(false); arPer.add(vo); } arAll.add(arPer); } // ϳList ArrayList arRes = new ArrayList(); // ȸԭ鵽list for (int i = 0; i < lenold; i++) { arRes.add(condvo[i]); } // Ӻǰ for (int j = rowdept.size() - 1; j >= 0; j--) { int rowindex = ((Integer) rowdept.get(j)).intValue(); ArrayList arPer = (ArrayList) arAll.get(j); if (arPer == null) { continue; } arRes.remove(rowindex); if (rowindex >= arRes.size()) { // ˳ for (int k = 0; k < arPer.size(); k++) { arRes.add(arPer.get(k)); } } else { // Ŵм for (int k = arPer.size() - 1; k >= 0; k--) { arRes.add(rowindex, arPer.get(k)); } } } int iSize = arRes.size(); return (nc.vo.pub.query.ConditionVO[]) (arRes .toArray(new nc.vo.pub.query.ConditionVO[iSize])); } /** * ֿƥԼ:ǹ̶ʲһʲ(Ӧ˰ͼ۸ۿԵĴ) * <p> * <b>examples:</b> * <p> * ʹʾ * <p> * <b>˵</b> * * @param billVO:ݾۺVO * @param strBillType: * @throws BusinessException * <p> * @author lixiaodong * @time 2007-5-30 01:54:12 */ public void checkStorAndInvIsCapital(AggregatedValueObject billVO, String strBillType) throws BusinessException { try { if (billVO == null || PuPubVO.getString_TrimZeroLenAsNull(strBillType) == null) { SCMEnv.out("ȷֱӷ"); return; } Vector<String> vctBaseID = new Vector<String>(); // ID Vector<String> vctWarehouseID = new Vector<String>(); // ջֿID Object objInvBaseID = null; Object objWarehouseID = null; if (strBillType == nc.vo.scm.pu.BillTypeConst.PO_ORDER // ɹ || strBillType == nc.vo.scm.pu.BillTypeConst.PO_PRAY // ɹ빺 || strBillType == nc.vo.scm.pu.BillTypeConst.PO_ARRIVE) { // ɹ for (int i = 0; i < billVO.getChildrenVO().length; i++) { if (billVO.getChildrenVO()[i] != null) { objInvBaseID = billVO.getChildrenVO()[i].getAttributeValue("cbaseid"); objWarehouseID = billVO.getChildrenVO()[i] .getAttributeValue("cwarehouseid"); if (PuPubVO.getString_TrimZeroLenAsNull(objInvBaseID) != null && PuPubVO.getString_TrimZeroLenAsNull(objWarehouseID) != null) { vctBaseID.add(objInvBaseID.toString()); vctWarehouseID.add(objWarehouseID.toString()); } } } } else if (strBillType == nc.vo.scm.pu.BillTypeConst.STORE_PO) { // ɹⵥ for (int i = 0; i < billVO.getChildrenVO().length; i++) { if (billVO.getChildrenVO()[i] != null && billVO.getParentVO() != null) { objInvBaseID = billVO.getParentVO().getAttributeValue("cinvbasid"); objWarehouseID = billVO.getChildrenVO()[i] .getAttributeValue("cwarehouseid"); if (PuPubVO.getString_TrimZeroLenAsNull(objInvBaseID) != null && PuPubVO.getString_TrimZeroLenAsNull(objWarehouseID) != null) { vctBaseID.add(objInvBaseID.toString()); vctWarehouseID.add(objWarehouseID.toString()); } } } } if (vctBaseID == null || vctWarehouseID == null || vctBaseID.size() < 1 || vctWarehouseID.size() < 1 || vctBaseID.size() != vctWarehouseID.size()) { return; } String[] arrInvBaseID = new String[vctBaseID.size()]; String[] arrWarehouseID = new String[vctWarehouseID.size()]; vctBaseID.copyInto(arrInvBaseID); vctWarehouseID.copyInto(arrWarehouseID); Object[][] oaRetWarehouseID = null;// Ƿʲ Object[][] oaRetInvBaseID = null;// Ƿ̶ʲ oaRetWarehouseID = queryArrayValue("bd_stordoc", "pk_stordoc", new String[] { "iscapitalstor" }, arrWarehouseID, null); oaRetInvBaseID = queryArrayValue("bd_invbasdoc", "pk_invbasdoc", new String[] { "pk_assetscategory", "laborflag", "discountflag" }, arrInvBaseID, null);// pk_assetscategory:̶ʲID // discountflag:۸ۿ // laborflag:Ӧ˰ if (oaRetWarehouseID == null || oaRetInvBaseID == null || oaRetWarehouseID.length < 1 || oaRetInvBaseID.length < 1) { return; } else { for (int i = 0; i < oaRetWarehouseID.length; i++) { UFBoolean bRet = new UFBoolean((String) oaRetWarehouseID[i][0]); UFBoolean bRet2 = new UFBoolean((String) oaRetInvBaseID[i][0]); if ("Y".equalsIgnoreCase(oaRetInvBaseID[i][1].toString()) && "n".equalsIgnoreCase(oaRetInvBaseID[i][2].toString()))// Ӧ˰ͼ۸ۿԵĴ if (PuPubVO.getString_TrimZeroLenAsNull(bRet2) != null && !bRet.booleanValue()) {// ǹ̶ʲ(pk_assetscategoryΪ)һʲ throw new BusinessException("̶ʲֻܶӦ̶ʲ"); } } } } catch (Exception e) { // ־쳣 nc.vo.scm.pub.SCMEnv.out(e); // 淶׳쳣 throw new BusinessException(e); } } public static void convertFreeValue(String pk_corp, IFreeField[] voItems) throws BusinessException { if (voItems == null || voItems.length == 0) return; HashMap<String, String> hmInv = new HashMap<String, String>(); for (int i = 0; i < voItems.length; i++) { String invid = voItems[i].getInvBasID(); hmInv.put(invid, invid); } String[] invids = new String[hmInv.size()]; hmInv.keySet().toArray(invids); String sql = " select pk_invbasdoc,bas.free1,bas.free2,bas.free3,bas.free4,bas.free5 from bd_invbasdoc bas where coalesce(bas.free1,bas.free2,bas.free3,bas.free4,bas.free5,'ZZ') !='ZZ' "; sql = sql + SQLUtil.formInSQL("pk_invbasdoc", invids); Object[] values = null; try { values = new SmartDMO().selectBy2(sql); } catch (Exception e) { SCMEnv.out(e); throw new BusinessException(e.getMessage()); } FreeVO voFree = null; HashMap<String, FreeVO> hmFree = new HashMap<String, FreeVO>(); if (values != null) { for (int i = 0; i < values.length; i++) { Object[] itemValues = (Object[]) values[i]; voFree = new FreeVO(); voFree.setPk_invbasdoc((String) itemValues[0]); voFree.setVfreeid1((String) itemValues[1]); voFree.setVfreeid2((String) itemValues[2]); voFree.setVfreeid3((String) itemValues[3]); voFree.setVfreeid4((String) itemValues[4]); voFree.setVfreeid5((String) itemValues[5]); hmFree.put(voFree.getPk_invbasdoc(), voFree); } } HashMap hmPara = getParaFreeAndPosMap(pk_corp); for (int i = 0; i < voItems.length; i++) { String invid = voItems[i].getInvBasID(); Object[] ncvalues = new Object[5]; Object[] retailvalues = voItems[i].getRetailFreeValue(); if (hmFree.containsKey(invid)) { voFree = (FreeVO) hmFree.get(invid); int count = 0; for (int j = 0; j < 5; j++) { String key = (String) voFree.getAttributeValue("vfreeid" + String.valueOf(j + 1)); if (key != null) count = count + 1; if (hmPara.containsKey(key)) { ncvalues[j] = retailvalues[((Integer) hmPara.get(key)).intValue() - 1]; } else ncvalues[j] = null; if (ncvalues[j] != null) count = count - 1; } voItems[i].setNCFreeValue(ncvalues); if (count != 0) throw new BusinessException("ֵȷԣ"); } else voItems[i].setNCFreeValue(null); } } public static void convertRetailMeas(IMeasField[] voItems) throws BusinessException { if (voItems == null || voItems.length == 0) return; java.util.HashSet<String> hm = new java.util.HashSet<String>(); for (int i = 0; i < voItems.length; i++) { hm.add(voItems[i].getInvbas()); } String[] invids = new String[hm.size()]; hm.toArray(invids); HashMap hmData = queryInvVos(invids); UFDouble udTmpNum = null; String sTmp = null; UFDouble one = new UFDouble(1); ArrayList alinv = null; // ޴ϢĴID ArrayList<String> noInv = new ArrayList<String>(); // λ͸λһ ArrayList<String> errMeas = new ArrayList<String>(); for (int i = 0; i < voItems.length; i++) { alinv = (ArrayList) hmData.get(voItems[i].getInvbas()); if (alinv == null || alinv.size() == 0) { noInv.add(((InvVO) alinv.get(0)).getInvcode()); continue; } udTmpNum = voItems[i].getRetailNum(); sTmp = voItems[i].getRetailMeas(); for (int j = 0; j < alinv.size(); j++) { InvVO voInv = (InvVO) alinv.get(j); // ۵λ, ۵λλһ λ if (sTmp == null || sTmp.equals(voInv.getPk_measdoc())) { // Ǹλ if (voInv.getAssistunit() == null || !(voInv.getAssistunit().booleanValue())) { voItems[i].setMainMeas(voInv.getPk_measdoc()); voItems[i].setMainNum(udTmpNum); break; } else { voItems[i].setMainMeas(voInv.getPk_measdoc()); voItems[i].setMainNum(udTmpNum); voItems[i].setAstMeas(voInv.getPk_measdoc()); voItems[i].setAstNum(udTmpNum); voItems[i].setHsl(one); break; } } else { // Ǹλ,۵λλڴ if (voInv.getAssistunit() == null || !(voInv.getAssistunit().booleanValue())) { errMeas.add(voInv.getInvcode()); continue; }// λ۵λһ£λͻ else if (voInv.getCassistunitid().equals(sTmp)) { voItems[i].setMainMeas(voInv.getPk_measdoc()); voItems[i].setMainNum(udTmpNum.multiply(voInv.getMainmeasrate())); voItems[i].setAstMeas(sTmp); voItems[i].setAstNum(udTmpNum); voItems[i].setHsl(voInv.getMainmeasrate()); break; } } } } // 쳣 if (noInv.size() > 0 || errMeas.size() > 0) { String err = ""; if (noInv.size() > 0) { err = "IDĴڣ" + noInv.toString() + "\r\n"; } if (errMeas.size() > 0) { err = err + "ǸλĴ۵λλһ£" + errMeas.toString() + "\r\n"; } throw new BusinessException(err); } } /** * ӵݻȡλۼĿѯ۵λӴѯλ if ۵λ==λ = if * ۵λ==λ = else ۵λλ Ļ =/ * * @param voItems * @throws BusinessException */ public static void convertToRetailMeas(IMeasDownConv[] voItems, String pk_corp) throws BusinessException { if (voItems == null || voItems.length == 0) return; HashMap hm = new HashMap(); for (int i = 0; i < voItems.length; i++) { hm.put(voItems[i].getInvbas(), voItems[i].getInvbas()); } String[] invids = new String[hm.size()]; hm.keySet().toArray(invids); HashMap hmData = queryInvVos(invids); HashMap hmMeas = queryRetailMeas(invids, pk_corp); String sMainMeas = null; ArrayList alinv = null; String sRetailMeas = null; // δѯϢ ArrayList<String> noInv = new ArrayList<String>(); // δѯ۵λ ArrayList<String> noMeas = new ArrayList<String>(); // δѯ ArrayList<String> noHsl = new ArrayList<String>(); for (int i = 0; i < voItems.length; i++) { alinv = (ArrayList) hmData.get(voItems[i].getInvbas()); if (alinv == null || alinv.size() == 0 || alinv.get(0) == null) { noInv.add(voItems[i].getInvbas()); continue; } sRetailMeas = (String) hmMeas.get(voItems[i].getInvbas()); if (sRetailMeas == null) { noMeas.add(((InvVO) alinv.get(0)).getInvcode()); continue; } // λ sMainMeas = ((InvVO) alinv.get(0)).getPk_measdoc(); if (sRetailMeas.equals(sMainMeas)) { voItems[i].setRetailNum(voItems[i].getMainNum()); } else if (sRetailMeas.equals(voItems[i].getAstMeas())) { voItems[i].setRetailNum(voItems[i].getAstNum()); } else { boolean isfind = false; for (int j = 0; j < alinv.size(); j++) { InvVO voInv = (InvVO) alinv.get(j); if (voInv.getCassistunitid() != null && voInv.getCassistunitid().equals(sRetailMeas)) { voItems[i].setRetailNum(voItems[i].getMainNum() .div(voInv.getMainmeasrate())); isfind = true; break; } } if (!isfind) { noHsl.add(((InvVO) alinv.get(0)).getInvcode()); continue; } } voItems[i].setRetailMeas(sRetailMeas); } // 쳣 if (noInv.size() > 0 || noMeas.size() > 0 || noHsl.size() > 0) { String err = ""; if (noInv.size() > 0) { err = "IDĴڣ" + noInv.toString() + "\r\n"; } if (noMeas.size() > 0) { err = err + "´۵λȷ(ۼĿܴ)" + noMeas.toString() + "\r\n"; } if (noHsl.size() > 0) { err = err + "´λ۵λ֮ûж廻ϵ" + noHsl.toString() + "\r\n"; } throw new BusinessException(err); } } /** * õеID˳ĶӦϵ * <p> * <b>examples:</b> * <p> * ʹʾ * <p> * <b>˵</b> * * @param pk_corp * ˾ * @return HASHMAPΪ * @throws Exception * <p> * @author wangyf * @time 2007-6-15 11:23:59 */ public static HashMap<String, Integer> getParaFreeAndPosMap(String pk_corp) throws BusinessException { // TODO ˿Ծ̬һ // U8RM0401 String[] saParaCode = new String[] { "U8RM0401", "U8RM0402", "U8RM0403", "U8RM0404", "U8RM0405", "U8RM0406", "U8RM0407", "U8RM0408", "U8RM0409", "U8RM0410" }; Hashtable<String, String> htPara = new nc.bs.pub.para.SysInitBO().queryBatchParaValues( pk_corp, saParaCode); // õһIDĸŵHASH String sTempParaValue = null; int iFreeLen = saParaCode.length; HashMap<String, Integer> hmapParaFreeAndPos = new HashMap<String, Integer>(iFreeLen); for (int i = 0; i < iFreeLen; i++) { sTempParaValue = htPara.get(saParaCode[i]); if (sTempParaValue != null) { hmapParaFreeAndPos.put(sTempParaValue, new Integer(i + 1)); } } return hmapParaFreeAndPos; } private static HashMap queryInvVos(String[] invids) throws BusinessException { StringBuffer sql = new StringBuffer( "select bas.pk_invbasdoc as cinvbasid, bas.invcode ,bas.pk_measdoc as pk_measdoc,assistunit,con.pk_measdoc as cassistunitid ,con.mainmeasrate "); sql.append(" from bd_invbasdoc bas "); sql.append(" left outer join bd_convert con on bas.pk_invbasdoc=con.pk_invbasdoc "); sql.append(" where 1=1 " + SQLUtil.formInSQL("bas.pk_invbasdoc", invids)); HashMap hmData = new HashMap(); ArrayList alinv = null; try { InvVO[] voInvs = (InvVO[]) new SmartDMO().selectBySql(sql.toString(), InvVO.class); if (voInvs != null && voInvs.length > 0) { for (int i = 0; i < voInvs.length; i++) { if (hmData.containsKey(voInvs[i].getCinvbasid())) { alinv = (ArrayList) hmData.get(voInvs[i].getCinvbasid()); } else { alinv = new ArrayList(); hmData.put(voInvs[i].getCinvbasid(), alinv); } alinv.add(voInvs[i]); } } } catch (Exception e) { throw new BusinessException(); } return hmData; } private static HashMap queryRetailMeas(String[] invids, String pk_corp) throws BusinessException { String currency = new SysInitBO().getPkValue(pk_corp, "BD301"); StringBuffer sql = new StringBuffer( "select distinct cinvbasdocid as cinvbasid ,cmeasdocid as pk_measdoc "); sql.append(" from prm_tariffcurlist prm , bd_invmandoc man "); // sql.append(" left outer join bd_convert con on // bas.pk_invbasdoc=con.pk_invbasdoc "); sql.append(" where prm.cinventoryid=man.pk_invmandoc and man.pk_corp='" + pk_corp + "' and prm.ccurrencyid='" + currency + "'" + SQLUtil.formInSQL("man.pk_invbasdoc", invids)); HashMap hmData = new HashMap(); ArrayList alinv = null; try { InvVO[] voInvs = (InvVO[]) new SmartDMO().selectBySql(sql.toString(), InvVO.class); if (voInvs != null && voInvs.length > 0) { for (int i = 0; i < voInvs.length; i++) { if (!hmData.containsKey(voInvs[i].getCinvbasid())) { hmData.put(voInvs[i].getCinvbasid(), voInvs[i].getPk_measdoc()); } } } } catch (Exception e) { throw new BusinessException(); } return hmData; } HashMap<String, Integer> indexMap = new HashMap<String, Integer>(); String rootCode=null; /** * ڵʾλdispcode * * @param nodeCodeģڵ * @param posڵλλñ * @throws Exception */ public void updateNodeDispCode(String nodeCode, String pos) throws Exception { int nodeLen = nodeCode.length(); String superDispCode = null; String subDispCode = null; String superCode = nodeCode.substring(0, nodeLen - 2); String funid = null; String sqlfunid = "select cfunid from sm_funcregister where fun_code = '" + nodeCode + "'"; String sqlDisp = "select disp_code from sm_funcregister where fun_code =?"; String dispCode = null; Connection con = null; PreparedStatement stmt = null; ArrayList<String> subCodeList = new ArrayList<String>(); try { con = getConnection(); stmt = con.prepareStatement(sqlfunid.toString()); ResultSet result = stmt.executeQuery(); if (result.next()) { funid = result.getString("cfunid"); String sqlSubcode = "select fun_code from sm_funcregister where parent_id = '" + funid + "' order by fun_code asc"; stmt = con.prepareStatement(sqlSubcode.toString()); result = stmt.executeQuery(); while (result.next()) { subCodeList.add(result.getString("fun_code")); } } if(nodeLen>2){ stmt = con.prepareStatement(sqlDisp.toString()); stmt.setString(1, superCode); result = stmt.executeQuery(); if (result.next()) { dispCode = result.getString("disp_code"); superDispCode = dispCode; } stmt.setString(1, nodeCode); result = stmt.executeQuery(); if (result.next()) { subDispCode = result.getString("disp_code"); } boolean isrePeated=false; if(rootCode==null){ String doubleDispcodeCheckSql="select disp_code from sm_funcregister where disp_code='"+subDispCode+"'"; stmt = con.prepareStatement(doubleDispcodeCheckSql); result = stmt.executeQuery(); int i=0; while(result.next()){ i++; } if(i>1){ isrePeated=true; } rootCode=nodeCode; } if ((dispCode != null && subDispCode != null && !subDispCode.substring(0, subDispCode.length() - 2).equals(superDispCode))||isrePeated) { dispCode = dispCode + pos; for (int i = 0; i < 20; i++) { String isUsedSql = "select fun_code from sm_funcregister where disp_code = '" + dispCode + "'"; stmt = con.prepareStatement(isUsedSql); result = stmt.executeQuery(); if (result.next()) { dispCode = getIncreaseCode(dispCode); } else { break; } } String sqlUpdate = "update sm_funcregister set disp_code='" + dispCode + "' where fun_code='" + nodeCode + "'"; stmt = con.prepareStatement(sqlUpdate.toString()); stmt.executeUpdate(); } } } finally { try { if (stmt != null) { stmt.close(); } } catch (Exception e) { } try { if (con != null) { con.close(); } } catch (Exception e) { SCMEnv.error(e); throw new Exception(e); } } int index = 50; if(indexMap.get(subDispCode)!=null){ index=indexMap.get(subDispCode).intValue(); } for (String nodecode : subCodeList) { String indexString = String.valueOf(index); if (indexString.length() > 2) { indexString=String.valueOf(50+new Random().nextInt(50)); } else if (indexString.length() == 1) { indexString = "0" + indexString; } updateNodeDispCode(nodecode, indexString); index += 2; indexMap.put(superCode, new Integer(index)); } rootCode=null; } public String getIncreaseCode(String code) throws Exception { String indexString = String.valueOf(Integer.parseInt(code.substring(code.length() - 2, code .length())) + 1); if (indexString.length() > 2) { return String.valueOf(50+new Random().nextInt(50)); } else if (indexString.length() == 1) { indexString = "0" + indexString; } return code.substring(0, code.length() - 2) + indexString; } public String[] querySingleValuesBySql(String sql)throws Exception { String[] results=null; Connection con = null; PreparedStatement stmt = null; List<String> resultList=new ArrayList<String>(); try { con = getConnection(); stmt = con.prepareStatement(sql); ResultSet result = stmt.executeQuery(); if (result.next()) { resultList.add(result.getString(1)); } results=resultList.toArray(new String[0]); } finally { try { if (stmt != null) { stmt.close(); } } catch (Exception e) { } try { if (con != null) { con.close(); } } catch (Exception e) { } } return results; } /** * */ public String queryColumn(String tabName, String fieldName, String whereFilter) throws Exception { String queryColumn = null; Connection con = null; PreparedStatement stmt = null; String sql = "select " + fieldName + " from " + tabName + " where " + whereFilter; try { con = getConnection(); stmt = con.prepareStatement(sql); ResultSet result = stmt.executeQuery(); if (result.next()) { queryColumn = result.getString(fieldName); } } finally { try { if (stmt != null) { stmt.close(); } } catch (Exception e) { } try { if (con != null) { con.close(); } } catch (Exception e) { } } return queryColumn; } /** * @function SmartVO * * @author QuSida * * @param vos * @throws SystemException * @throws NamingException * @throws SQLException * * @return void * * @date 2010-8-12 10:43:36 */ public void insertSmartVOs(SmartVO[] vos) throws SystemException, NamingException, SQLException{ SmartDMO dmo = new SmartDMO(); for (int i = 0; i < vos.length; i++) { vos[i].setPrimaryKey(dmo.getOID()); vos[i].setAttributeValue("dr", 0); vos[i].setStatus(VOStatus.NEW); } dmo.maintain(vos); } /** * @function ѯSmartVO * * @author QuSida * * @param voClass * @param names * @param where * * @throws SystemException * @throws NamingException * @throws SQLException * * @return SmartVO[] * * @date 2010-9-11 02:24:50 */ public SmartVO[] querySmartVOs(Class voClass, String[] names, String where) throws SystemException, NamingException, SQLException{ SmartDMO dmo = new SmartDMO(); SmartVO[] smartVOs = dmo.selectBy(voClass,names,where); return smartVOs; } /** * @function ɾSmartVO * * @author QuSida * * @param vos * @throws SystemException * @throws NamingException * @throws SQLException * * @return void * * @date 2010-9-11 02:25:17 */ public void deleteSmartVOs(SmartVO[] vos) throws SystemException, NamingException, SQLException{ SmartDMO dmo = new SmartDMO(); for (int i = 0; i < vos.length; i++) { vos[i].setStatus( VOStatus.DELETED); } dmo.maintain(vos); } /** * @function ޸SmartVO * * @author QuSida * * @param vos * @throws SystemException * @throws NamingException * @throws SQLException * * @return void * * @date 2010-9-11 02:25:30 */ public void updateSmartVOs(SmartVO[] vos,String cbillid) throws SystemException, NamingException, SQLException{ SmartDMO dmo = new SmartDMO(); String preparedUpdateSql = "delete from jj_scm_informationcost where cbillid = '"+cbillid+"'"; dmo.executeUpdate(preparedUpdateSql); if(vos.length == 0 || vos == null) return; insertSmartVOs(vos); } }
Java
UTF-8
2,321
2.15625
2
[]
no_license
/* * 工具自动生成:VIEW条件实体类 * 生成时间 : 2016/05/16 18:54:36 */ package com.icomp.entity.base; import com.icomp.common.entity.BaseEntity; import java.io.Serializable; /** * VIEW条件实体类 * @author 工具自动生成 * 创建时间:2016/05/16 18:54:36 * 创建者 :工具自动生成 * */ public class VapplyuserWhere extends BaseEntity implements Serializable { // 序列化接口属性 private static final long serialVersionUID = 1L; /* 用户ID[自动生成20位字符串] */ private String customerIDWhere; /** * 用户ID[自动生成20位字符串]取得 * @return customerIDWhere */ public String getCustomerIDWhere () { return customerIDWhere; } /** * 用户ID[自动生成20位字符串]设定 * @param customerIDWhere */ public void setCustomerIDWhere (String customerIDWhere) { this.customerIDWhere = customerIDWhere; } /* 姓名 */ private String userNameWhere; /** * 姓名取得 * @return userNameWhere */ public String getUserNameWhere () { return userNameWhere; } /** * 姓名设定 * @param userNameWhere */ public void setUserNameWhere (String userNameWhere) { this.userNameWhere = userNameWhere; } /* 身份证号 */ private String userCardIDWhere; /** * 身份证号取得 * @return userCardIDWhere */ public String getUserCardIDWhere () { return userCardIDWhere; } /** * 身份证号设定 * @param userCardIDWhere */ public void setUserCardIDWhere (String userCardIDWhere) { this.userCardIDWhere = userCardIDWhere; } /* 部门名称 */ private String departmentNameWhere; /** * 部门名称取得 * @return departmentNameWhere */ public String getDepartmentNameWhere () { return departmentNameWhere; } /** * 部门名称设定 * @param departmentNameWhere */ public void setDepartmentNameWhere (String departmentNameWhere) { this.departmentNameWhere = departmentNameWhere; } /* 部门ID */ private String departmentIDWhere; /** * 部门ID取得 * @return departmentIDWhere */ public String getDepartmentIDWhere () { return departmentIDWhere; } /** * 部门ID设定 * @param departmentIDWhere */ public void setDepartmentIDWhere (String departmentIDWhere) { this.departmentIDWhere = departmentIDWhere; } }
Java
UTF-8
3,735
2.046875
2
[ "BSD-3-Clause" ]
permissive
/* * Copyright (C) 2019 Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ package com.intel.mtwilson.audit.data; import com.intel.mtwilson.audit.converter.AuditDataConverter; import java.io.Serializable; import java.util.Date; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; /** * * @author dsmagadx */ @Entity @Table(name = "mw_audit_log_entry") @XmlRootElement @NamedQueries({ @NamedQuery(name = "AuditLogEntry.findAll", query = "SELECT a FROM AuditLogEntry a"), @NamedQuery(name = "AuditLogEntry.findById", query = "SELECT a FROM AuditLogEntry a WHERE a.id = :id"), @NamedQuery(name = "AuditLogEntry.findByEntityId", query = "SELECT a FROM AuditLogEntry a WHERE a.entityId = :entityId"), @NamedQuery(name = "AuditLogEntry.findByEntityType", query = "SELECT a FROM AuditLogEntry a WHERE a.entityType = :entityType"), @NamedQuery(name = "AuditLogEntry.findByCreateDt", query = "SELECT a FROM AuditLogEntry a WHERE a.created = :created"), @NamedQuery(name = "AuditLogEntry.findByAction", query = "SELECT a FROM AuditLogEntry a WHERE a.action = :action")}) public class AuditLogEntry implements Serializable { @Column(name = "entity_id") private String entityId; @Basic(optional = false) @Column(name = "created") @Temporal(TemporalType.TIMESTAMP) private Date created; private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "id") private String id; @Basic(optional = false) @Column(name = "entity_type") private String entityType; @Basic(optional = false) @Column(name = "action") private String action; @Basic(optional = false) @Lob @Column(name = "data", columnDefinition = "json") @Convert(converter = AuditDataConverter.class) private AuditTableData data; public AuditLogEntry() { } public AuditLogEntry(String id) { this.id = id; } public AuditLogEntry(String id, String entityId, String entityType, Date created, String action) { this.id = id; this.entityId = entityId; this.entityType = entityType; this.created = created; this.action = action; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getEntityId() { return entityId; } public void setEntityId(String entityId) { this.entityId = entityId; } public String getEntityType() { return entityType; } public void setEntityType(String entityType) { this.entityType = entityType; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public AuditTableData getData() { return data; } public void setData(AuditTableData data) { this.data = data; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof AuditLogEntry)) { return false; } AuditLogEntry other = (AuditLogEntry) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.intel.mtwilson.audit.data.AuditLogEntry[ id=" + id + " ]"; } }
Java
UTF-8
714
2.34375
2
[]
no_license
package com.example.spring_test.service; import com.example.spring_test.domain.Board; import com.example.spring_test.repository.BoardRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service //해당 클래스는 서비스로 동작 public class BoardServiceImpl implements BoardService{ @Autowired BoardRepository boardRepository; //레포지포리 빈 연결 @Override public List<Board> selectBoardList() throws Exception { return boardRepository.findAll(); } @Override public void insertBoard(Board board) throws Exception { boardRepository.insert(board); } }
JavaScript
UTF-8
13,575
3
3
[]
no_license
/* */ var cont = 0; var cont2 = 0; var Pp;//variable para almacenar la potencia del primario var Ps; //variable para almacenar la potencia del secundario var S; // almacena la sección transversal del núcleo var AWG =[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40]; var diametro =[4.115,3.665,3.264,2.906,2.588,2.304,2.052,1.829,1.628,1.450,1.290,1.151,1.024,0.912,0.813,0.724,0.643,0.574,0.511,0.455,0.404,0.361,0.320,0.287,0.254,0.226,0.203,0.180,0.160,0.142,0.127,0.114,0.102,0.089,0.079]; var diametro_sen=["-","-","-","-","-","-","-","-",1.692,1.509,1.349,1.207,1.077,0.963,0.864,0.770,0.686,0.617,0.551,0.493,0.439,0.396,0.356,0.320,0.284,0.254,0.231,0.206,0.183,0.163,0.147,0.135,0.119,0.104,0.094]; var diametro_doble=[4.244,3.787,3.383,3.023,2.703,2.416,2.159,1.935,1.732,1.549,1.384,1.240,1.110,0.993,0.892,0.800,0.714,0.643,0.577,0.516,0.462,0.419,0.373,0.338,0.302,0.274,0.249,0.224,0.198,0.178,0.160,0.145,0.130,0.114,0.102]; function potencia (){ var voltaje= document.getElementById("Vs").value;//obtenemos el valor del voltaje digitado por el usuario var corr = document.getElementById("Is").value;//obtenemos el valor de la corriente digitado por el usuario if (voltaje > 0 && corr > 0){ //se crea la condición para evaluar si el usuario digito valores en los campos Ps = voltaje * corr; //se calcula la potencia del secundario document.getElementById("Ps").value = Ps;// se pasa el valor calculado al campo de texto de potencia } else { alert("Debe ingresar el valor del voltaje y la corriente en el secundario ") } return Ps; } function pot_primario (){ if (Ps > 0){ // obtenemos el valor seleccionado y lo guardamos en una variable var lista = document.getElementById("rendimiento").value; var Ppri= (Ps/lista); // calculamos la potencia del primario Pp=Math.round(Ppri); // redondeamos al número entero más próximo document.getElementById("Pp").value = Pp; //asignamos el valor obtenido al campo de texto Pp return Pp; } else { alert("Por favor realice el paso 1, calcule la potencia del secundario." ); } } function seccion_nucleo(){ if (Pp > 0){ coef=document.getElementById("coeficiente").value;//se obtiene el valor seleccionado del formulario S=coef*Math.sqrt(Pp); //se calcula el valor de la sección del núcleo S = Math.round(S*100)/100; //con este procediento obtenemos el resultado con 2 decimales document.getElementById("S").value=S;// se pasa el valor al campo de texto S var a= Math.sqrt(S); //se saca la raiz cuadrada al valor de S para obtener la dimesión (a) a=Math.round(a*10)/10;//redondeamos el número a un decimal. var b = a/2; // se obtiene la dimesión (b) b=Math.round(b*10)/10;//redondeamos el número a un decimal. var c = b; // b,c y f tienen el mismo valor por tanto se asigna el valor de (b) var f = b; var e = 3*b; // se obtiene la dimesión (e) e=Math.round(e*10)/10;//redondeamos el número a un decimal. var sup = b*e;// se obtiene el valor de la superficie de ventana. sup=Math.round(sup*10)/10;//redondeamos el número a un decimal. document.getElementById("cel1").innerHTML=a; // se envía el valor a cada celda de la tabla. document.getElementById("cel2").innerHTML=b; document.getElementById("cel3").innerHTML=b; document.getElementById("cel4").innerHTML=e; document.getElementById("cel5").innerHTML=b; document.getElementById("cel6").innerHTML=sup; return S; //se retorna el valor de S para que se conserve como número. } else { alert ("Por favor realice el paso 2, calcule la potencia del primario. "); } } function paso_456(){ if (S>0 && document.getElementById("Vp").value >0){ var volt = document.getElementById("Vp").value; var frec = document.getElementById("frecuencia").value; var vuel_voltios = 1/(4.44*0.0001*S*frec); vuel_voltios = Math.round(vuel_voltios*100)/100; var Np = volt * vuel_voltios; Np = Math.round(Np); var Ns = document.getElementById("Vs").value * vuel_voltios; Ns = Math.round(Ns); var Ip = Pp/volt; Ip = Math.round(Ip); document.getElementById("cel7").innerHTML= vuel_voltios; document.getElementById("cel8").innerHTML= Np; document.getElementById("cel9").innerHTML= Ns; document.getElementById("cel10").innerHTML= Ip; document.getElementById("cel11").innerHTML= document.getElementById("Is").value; } else { alert ("Por favor realice el paso 3, determine la sección del núcleo y/o Digite el voltaje del primario "); } } function diametro_con(){ if ((document.getElementById("Is").value > 0) && (parseFloat(document.getElementById("cel10").textContent) > 0)){ var den = document.getElementById("densidad").value; var Ip = parseFloat(document.getElementById("cel10").textContent); var Is = document.getElementById("Is").value; var sup_p = Ip/den; sup_p = Math.round(sup_p*1000)/1000; var sup_s = Is/den; sup_s = Math.round(sup_s*1000)/1000; var dia_p = Math.sqrt(4*sup_p/Math.PI); dia_p = Math.round(dia_p*1000)/1000; var dia_s = Math.sqrt(4*sup_s/Math.PI); dia_s = Math.round(dia_s*1000)/1000; document.getElementById("diametro_p").value = dia_p; document.getElementById("diametro_s").value = dia_s; //alert("la cantidad de datos es"+diametro_doble.length) var cal = Math.round(-8.623*Math.log(dia_p)+18.203); var pos_p = AWG.indexOf(cal); var cal2 = Math.round(-8.623*Math.log(dia_s)+18.203); var pos_s = AWG.indexOf(cal2);; document.getElementById("cel12").innerHTML= AWG[pos_p-1]; document.getElementById("cel16").innerHTML= AWG[pos_p]; document.getElementById("cel20").innerHTML= AWG[pos_p+1]; document.getElementById("cel24").innerHTML= AWG[pos_p+2]; document.getElementById("cel13").innerHTML= diametro[pos_p-1]; document.getElementById("cel17").innerHTML= diametro[pos_p]; document.getElementById("cel21").innerHTML= diametro[pos_p+1]; document.getElementById("cel25").innerHTML= diametro[pos_p+2]; document.getElementById("cel14").innerHTML= diametro_sen[pos_p-1]; document.getElementById("cel18").innerHTML= diametro_sen[pos_p]; document.getElementById("cel22").innerHTML= diametro_sen[pos_p+1]; document.getElementById("cel26").innerHTML= diametro_sen[pos_p+2]; document.getElementById("cel15").innerHTML= diametro_doble[pos_p-1]; document.getElementById("cel19").innerHTML= diametro_doble[pos_p]; document.getElementById("cel23").innerHTML= diametro_doble[pos_p+1]; document.getElementById("cel27").innerHTML= diametro_doble[pos_p+2]; document.getElementById("cel28").innerHTML= AWG[pos_s-1]; document.getElementById("cel32").innerHTML= AWG[pos_s]; document.getElementById("cel36").innerHTML= AWG[pos_s+1]; document.getElementById("cel40").innerHTML= AWG[pos_s+2]; document.getElementById("cel29").innerHTML= diametro[pos_s-1]; document.getElementById("cel33").innerHTML= diametro[pos_s]; document.getElementById("cel37").innerHTML= diametro[pos_s+1]; document.getElementById("cel41").innerHTML= diametro[pos_s+2]; document.getElementById("cel30").innerHTML= diametro_sen[pos_s-1]; document.getElementById("cel34").innerHTML= diametro_sen[pos_s]; document.getElementById("cel38").innerHTML= diametro_sen[pos_s+1]; document.getElementById("cel42").innerHTML= diametro_sen[pos_s+2]; document.getElementById("cel31").innerHTML= diametro_doble[pos_s-1]; document.getElementById("cel35").innerHTML= diametro_doble[pos_s]; document.getElementById("cel39").innerHTML= diametro_doble[pos_s+1]; document.getElementById("cel43").innerHTML= diametro_doble[pos_s+2]; } else { alert ("Por favor realice el paso 4, 5 y 6, se requiere la corriente del primario y del secundario. "); } } function paso_8910(){ if (S>0 && document.getElementById("Vp").value >0){ var diam_sel_pri=document.getElementById("diametro_sp").value;//se obtiene el valor del diámetro del primario var diam_sel_sec=document.getElementById("diametro_ss").value;//se obtiene el valor del diámetro del secundario var Scu_p = (Math.PI/4)*Math.pow(diam_sel_pri,2); //se calcula la sección del cobre del primario Scu_p = Math.round(Scu_p*100)/100; // se rendoea el valor a 2 decimales var Scu_s = (Math.PI/4)*Math.pow(diam_sel_sec,2); //se calcula la sección del cobre del secundario Scu_s = Math.round(Scu_s*100)/100; // se rendoea el valor a 2 decimales // alert ("la superficie del primario es: "+Scu_p); // alert ("la superficie del secundario es: "+Scu_s); // se calcula la sección total del cobre var STcu = (parseFloat(document.getElementById("cel8").textContent)*Scu_p)+ (parseFloat(document.getElementById("cel9").textContent)*Scu_s); STcu= STcu/100; //pasamos el valor a cm^2 STcu = Math.round(STcu*100)/100; //se calcula el coeficiente de superficie de ventana var coef = STcu/(parseFloat(document.getElementById("cel2").textContent)*parseFloat(document.getElementById("cel4").textContent)); coef= Math.round(coef*100)/100; var Es_pri = Math.round(10/diam_sel_pri);//se calcula el número de espiras por centímetro en el primario var Es_sec = Math.round(10/diam_sel_sec);//se calcula el número de espiras por centímetro en el secundario //se calculan las espiras por capa tanto del primario como del secundario. var EsCa_pri = Es_pri * Math.trunc(parseFloat(document.getElementById("cel4").textContent)); var EsCa_sec = Es_sec * Math.trunc(parseFloat(document.getElementById("cel4").textContent)); //se calcula el número de capas para cada bobinado var No_cap_pri = parseFloat(document.getElementById("cel8").textContent)/EsCa_pri; No_cap_pri = Math.ceil(No_cap_pri); var No_cap_sec = parseFloat(document.getElementById("cel9").textContent)/EsCa_sec; No_cap_sec = Math.ceil(No_cap_sec); //se imprimen los valores en el documento HTML o página principal. document.getElementById("cel44").innerHTML= STcu; document.getElementById("cel45").innerHTML= coef; document.getElementById("cel46").innerHTML= EsCa_pri; document.getElementById("cel47").innerHTML= EsCa_sec; document.getElementById("cel48").innerHTML= No_cap_pri; document.getElementById("cel49").innerHTML= No_cap_sec; } else{ alert("Por favor realice el paso 3, determine la sección del núcleo.") } } function aislamiento(){ var carr = parseFloat(document.getElementById("espe_carr").value); var pri_sec = parseFloat(document.getElementById("ais_pri_sec").value); var cap_pri = parseFloat(document.getElementById("espe_cap_pri").value); var cap_sec = parseFloat(document.getElementById("espe_cap_sec").value); var esp_ext = parseFloat(document.getElementById("espe_ais_ext").value); var ais_total = (carr + pri_sec + cap_pri + cap_sec + esp_ext); if (carr <0 || cap_pri<0 || pri_sec<0 || cap_sec<0 || esp_ext<0){ alert("Debes digitar números positivos, no se aceptan negativos"); document.getElementById("espe_carr").value = 0; document.getElementById("ais_pri_sec").value = 0; document.getElementById("espe_cap_pri").value = 0; document.getElementById("espe_cap_sec").value = 0; document.getElementById("espe_ais_ext").value = 0; }else{ document.getElementById("cel50").innerHTML = ais_total; } } function paso_131415(){ var diametro_primario= parseFloat(document.getElementById("diametro_sp").value); var diametro_secundario= parseFloat(document.getElementById("diametro_ss").value); var capas_primario= parseFloat(document.getElementById("cel48").textContent); var capas_secundario=parseFloat(document.getElementById("cel49").textContent); var esp_total_aisl= parseFloat(document.getElementById("cel50").textContent); var dimension_b=parseFloat(document.getElementById("cel2").textContent); var ETcu = (diametro_primario*capas_primario)+(diametro_secundario*capas_secundario); var ET = ETcu + esp_total_aisl; var ver_esp_vent = ((ET/10)/dimension_b)*100; ver_esp_vent = Math.round(ver_esp_vent*100)/100; if (diametro_primario<=0 || diametro_secundario<=0 || capas_primario<=0 || capas_secundario<=0 || esp_total_aisl<=0 || dimension_b<=0){ alert("Por favor realice el paso 3, determine la sección del núcleo."); } else { document.getElementById("cel51").innerHTML= ETcu; document.getElementById("cel52").innerHTML= ET; document.getElementById("cel53").innerHTML= ver_esp_vent; } }
Python
UTF-8
592
2.796875
3
[]
no_license
import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl # javascript:void(0) ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input("Enter:-") html = urllib.request.urlopen(url, context = ctx).read() soup = BeautifulSoup(html,"html.parser") # print(soup.get_text()) print("..............................") # retrieving tags = soup("a") for tag in tags: if (tag.get("href",None)) == "javascript\:void(0)": tag.contents[0] print("..............................") javascript:void(0)
C
UTF-8
2,520
3.21875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #define MAX_READ 120 int main( int argc, char** argv) { FILE* fd; char* oneLine = NULL; int line = 0; int counter = 0; char buff[MAX_READ]; ssize_t num; int charCounter = 0; char character; int charCounter2 = 0; char character2; char filep[50]; if ((argc ==2 ) && (strcmp(argv[1], "-h") == 0)) { printf("usage: outail [-n N] <file>\n"); exit(-1); } if (argc == 3) { num = read(STDIN_FILENO, buff, MAX_READ); if (num == -1) { fprintf(stderr,"error read only\n"); return EXIT_FAILURE; } buff[num] = '\0'; int templine = 0; int tempCount = 0; while (buff[tempCount] != '\0') //this loops finds the number of line in a file { if (buff[tempCount] =='\n') { templine++; } tempCount++; } while (buff[counter] != '\0') //this loop prints the line to be printed { if (buff[counter] =='\n') { charCounter++; } counter++; if(charCounter >= templine - atoi(argv[2])) { printf("%c", buff[counter]); } } return EXIT_SUCCESS; } if (argc == 2) { fd = fopen(argv[1], "r"); if (fd == NULL) { fprintf(stderr,"error read only\n"); return 0; } character = getc(fd); while(character != EOF) { if (character == '\n') { charCounter = charCounter + 1; } character = getc(fd); } fclose(fd); fd = fopen(argv[1], "r"); if (fd == NULL) { fprintf(stderr,"error read only\n"); return 0; } while( getline(&oneLine, &line, fd) != -1) { counter++; if (counter > charCounter - 10 )//prints default number of lines { printf("%s", oneLine); } } fclose(fd); return EXIT_SUCCESS; } if (argc == 4) { fd = fopen(argv[3], "r"); if (fd == NULL) { fprintf(stderr,"error read only\n"); return 0; } character2 = getc(fd); while(character2 != EOF) { if (character2 == '\n') { charCounter2 = charCounter2 + 1; } character2 = getc(fd); } fclose(fd); fd = fopen(argv[3], "r"); if (fd == NULL) { fprintf(stderr,"error read only\n"); } while( getline(&oneLine, &line, fd) != -1) { counter++; if (counter > charCounter2 - atoi(argv[2]) ) { printf("%s", oneLine); } } fclose(fd); return EXIT_SUCCESS; } return EXIT_SUCCESS; }
Markdown
UTF-8
12,106
2.671875
3
[]
no_license
title=新手引导:利用AWS伸缩到千万级用户 date=2017-08-25 type=post tags=archetecture status=published ~~~~~~ <div id="table-of-contents"> <h2>Table of Contents</h2> <div id="text-table-of-contents"> <ul> <li><a href="#org85a7ed2">1. 新手引导:利用AWS伸缩到千万级用户</a> <ul> <li><a href="#org62393be">1.1. 基础</a></li> <li><a href="#orgcac6e52">1.2. 单用户</a></li> <li><a href="#org6dc4f36">1.3. 垂直伸缩</a></li> <li><a href="#org2120e3c">1.4. 用户量大于10</a></li> <li><a href="#org8ec8903">1.5. 用户量大于100</a></li> <li><a href="#orgd304dc7">1.6. 用户量大于1000</a></li> <li><a href="#org015df2f">1.7. 用户量一万到十万</a></li> <li><a href="#orga52b1fe">1.8. 自动伸缩</a></li> <li><a href="#org7ba5bea">1.9. 用户量大于50万</a></li> <li><a href="#org1c92550">1.10. 自动化</a></li> <li><a href="#org544f2c1">1.11. 解耦架构</a></li> <li><a href="#org0a31f1d">1.12. 不要重复发明轮子</a></li> <li><a href="#org727f571">1.13. 用户量大于一百万</a></li> <li><a href="#orgcf3fe1a">1.14. 用户量大于一千万</a></li> <li><a href="#org4af6b98">1.15. 用户量大于1000万</a></li> <li><a href="#org49c6bf3">1.16. 总结</a></li> </ul> </li> </ul> </div> </div> <a id="org85a7ed2"></a> # 新手引导:利用AWS伸缩到千万级用户 本文翻译自:[HighScalability](http://highscalability.com/blog/2016/1/11/a-beginners-guide-to-scaling-to-11-million-users-on-amazons.html)。 如何将系统从单用户伸缩到千万级的用户量?Joel Williams,亚马逊的Web服务方案架构师,就此话题做了一个不错的演讲:[AWS re:Invent 2015 Scaling Up to Your First 10 Million Users](https://www.youtube.com/watch?v=vg5onp8TU6Q&list=PLhr1KZpdzukdRxs_pGJm-qSy5LayL6W_Y)。 如果你是高级AWS用户,这份演讲可能对你没什么用处。但对于新手来说,这却是一个很好的起点。 这份演讲出自亚马逊,所以演讲中亚马逊的服务是解决所有问题的核心。 下面是一些有趣的总结: - 从SQL开始,只有在必要时才迁移到NOSQL。 - 将系统中的模块分离,使它们可以独立的伸缩并实现差错隔离。 - 将精力投入到你的核心商业业务,不要重新发明轮子。 - 伸缩性和冗余性不是两个分离的概念,你通常能够同时实现二者。 <a id="org62393be"></a> ## 基础 1. AWS在全球有12个区。 (1) 一个区是一个具体的物理位置,其中包含了多个可用域(AZ, Available Zone)。 (2) 一个可用域通常由一个数据中心或者多个数据中心组成。 (3) 各个可用域之间相互独立,具有独立的电力和网络。 (4) 可用域之间用低延迟网络连接,在地理位置上相距5至15英里。由于网络延迟极低,在应用程序看来,所有的可用域就像是一个整体。 (5) 每个区至少有两个可用域。 2. AWS在全球有53个边缘区(Edge Location) (1) 边缘区用于CloudFront,CDN,Route53和Amazon DNS服务 (2) 边缘区使用户可以低延迟的访问数据,无论在什么地理位置. 3. 构建块 (1) AWS提供了众多的构建块服务,这些服务使用可用域作为支撑,具备高可用和容错性。 (2) 你可以付费使用这些服务构建应用,而不是自己构建这些高可用的服务。 (3) 可用域包含的服务有:CloudFront, Route53, S3, DynamoDb, Elastic Load Balancing, EFS, lambda, SQS, SNS, SES, SWF。 (4) 使用单一的可用域也可以构建出高可用的应用程序架构。 <a id="orgcac6e52"></a> ## 单用户 此种情形下,你是唯一的用户,你需要一个可以运行的网站。 你的架构可能是这样的: 1. 应用运行在单一的服务器中。 2. 单一服务器运行整个程序栈:网络层,数据库,管理层.. 3. 使用Amazon Route 53做DNS。 4. 为应用绑定一个[Elastic IP](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)。 5. 应用在一段时间可以工作地很好。 <a id="org6dc4f36"></a> ## 垂直伸缩 1. 你需要一个性能更好的主机。最简单的方案是选择[c4.8xlarge](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/c4-instances.html) 或者[om3.2xlarge](https://aws.amazon.com/ec2/instance-types/)。 2. 垂直伸缩的问题在于:没有差错转移,没有冗余。如果应用出现一个问题,整个服务可能不可用。 <a id="org2120e3c"></a> ## 用户量大于10 1. 单服务器模式切换到多服务器模式。 (1) 一个主机用于web层。 (2) 一个主机用于数据库,或者运行任意多个数据库,这些数据库都由你管理。 (3) 将web主机与数据库主机分离开来可以让它们独立的伸缩。 2. 除了运行自己的数据库,你也可以使用数据库服务。 (1) 你是数据库管理员吗?你想要自己关心数据备份,高可用,打包,操作系统等问题吗? (2) 使用数据库服务的优势在于:你可以一键点击就生成分布在多个可用域的数据服务,而且是高可用,高可靠的。 3. AWS提供了多种数据库服务: (1) Amazon RDS关系数据库服务。 (2) Amazon DynamoDB Nosql数据库服务。 (3) Amazon Redshift 千兆兆级别数据仓库服务。 4. Amazon Aurora (1) 自动伸缩到64tb。不用再关心数据的存储。 (2) 有多达15个读集。 (3) 数据增量备份。 (4) 跨越3个可用域的六路数据备份,这可以帮助解决数据访问失败的问题。 (5) 兼容mysql。 5. 从SQL起步,而不是NOSQL (1) 建议从SQL开始构建数据存储 (2) SQL技术比较成熟 (3) SQL有大量的现存代码,社区,支持组,书籍,以及工具。 (4) SQL足以满足你前1000万用户的需求。 (5) SQL清楚的数据模式便于构建可伸缩的数据服务。 6. 什么时候可以从NOSQL起步? (1) 你首年即需存储5TB以上的数据或者你的应用有极大的数据紧密性任务。 (2) 你的应用有极低延迟的需求。 (3) 你真的需要高吞吐量。你需要优化读写的性能。 (4) 你的应用中没有关系型数据。 <a id="org8ec8903"></a> ## 用户量大于100 1. 使用单独的主机,用于网络层。 2. 将数据存储到Amazon RDS,由它管理一切。 <a id="orgd304dc7"></a> ## 用户量大于1000 1. 在另一个可用域中开启另一个网络层实例,这样可以提高服务可用性,同时,由于可用域之间网络延迟极低,两个网络层实例就好像一个实例一样。 2. 在另一个可用域中开启一个从数据库,在主数据库故障时,应用程序会自动地向从数据库发送请求。 3. 在配置中加入弹性负载均衡(Elastic Load Balancer, ELB), 用于在你的两个网络实例之间进行负载均衡。 (1) ELB是高可用可管理的负载均衡器。在所有的可用域中均可使用,他是你应用程序的唯一DNS端口。 (2) ELB具有健康检测功能,这可以保证请求不会流入故障的主机。 (3) ELB帮助你进行架构伸缩,让你无需操心太多。 <a id="org015df2f"></a> ## 用户量一万到十万 1. 水平伸缩,在ELB之后可以有1000或更多个网络实例。 2. 添加更多的只读数据集。 3. 考虑到网络层的性能,将网络层的一些流量分离到其他模块,将静态内容移动到Amazon S3和Amazon CloudFront。CloudFront将你的数据存储到边缘区(Edge Location)。 4. Amazon S3是一个对象存储。 5. Amazon CloudFront是应用的缓存。 6. 你也可以将回话状态存储到ElasticCache或者DynamoDB,从而减轻网络层的负载。 7. 将数据库的数据缓存到ElastiCache。 <a id="orga52b1fe"></a> ## 自动伸缩 1. 如果你提供足够的资源,能够满足应用高峰时的流量需求,在闲时,你却在浪费资源。 2. 你可以定义最大和最小资源池。 3. CloudWatch是一个嵌入到所有应用的管理服务,提供伸缩性管理。 <a id="org7ba5bea"></a> ## 用户量大于50万 1. 前一节中, 自动伸缩组加入到网络层配置中。自动伸缩组包括两个可用域,可以伸缩到3个或者更多可用域。 2. 在每个可用域中有3个网络实例,其实可以增加到数千个实例。你可以配置最少需要10个实例,最多伸缩到1000个实例。 3. ElastiCache用于缓存热数据,减轻数据库负载。 4. DynamoDB用于管理会话数据。 5. 为应用增加监控,度量,日志功能。 6. 了解用户的体验,是否延迟过高或者遇到什么错误。 7. 通过配置尽量利用系统性能,自动伸缩是很好的解决方案。 <a id="org1c92550"></a> ## 自动化 1. 架构更加复杂,它能伸缩到1000个实例,具有只读数据集,可以水平伸缩。现在我们需要一些自动化管理工具来管理所有的实例。 2. AWS Elastic Beanstalk,自动管理你的应用设施。 <a id="org544f2c1"></a> ## 解耦架构 1. 使用SOA/microservices。将应用组件分离出来,独立成为单独的服务,就好像你分离网络层和数据库一样。 2. 每个服务都可以独立的伸缩,这带给你更多的灵活性和高可用性。 3. SOA是架构的核心组件。 4. 低耦合使你更加灵活: (1) 各组件独立伸缩,差错隔离。 (2) 如果一个工作节点故障,只需启动一个新的节点,这提高了错误处理能力。 (3) 将各个服务设计到独立的黑盒中。 (4) 在服务内部提供伸缩性和冗余性。 <a id="org0a31f1d"></a> ## 不要重复发明轮子 1. 关注你的业务逻辑。 2. Amazon提供了很多高容错的服务。 3. SQS:队列服务。 4. AWS Lambda: 让你无需配置和管理服务器。 <a id="org727f571"></a> ## 用户量大于一百万 1. 用户量达到一百万需要前面提到的所有服务: (1) 多个可用域 (2) Elastic Load Balanceing(ELB)。 (3) Service Oriented Architecture。 (4) 添加缓存。 (5) 将状态从网络层移除。 2. 使用Amazon SES发送邮件。 3. 使用CloudWatch进行监控。 <a id="orgcf3fe1a"></a> ## 用户量大于一千万 1. 随着用户量增大,数据层成了问题所在。写数据库负载过高,成为瓶颈。 2. 如何解决? (1) 联合 (2) 分片 (3) 将部分功能转移到Nosql 3. 联合,基于功能将数据分配到多个数据库。 (1) 例如:论坛数据库,用户数据库,产品数据库等等。 (2) 各个数据库可以独立伸缩。 (3) 缺点:不能跨数据库查询,这引出了下一种策略:分片。 4. 分片:将一个数据集切分到多个主机。 (1) 应用层变复杂,可扩展性没有限制。 (2) 比如:将1/3的用户存入shard1,1/3存入shard2,剩下的存入shard3。 5. 将部分功能转移到NoSql <a id="org4af6b98"></a> ## 用户量大于1000万 1. 伸缩性是一个迭代的过程,随着用户量的增多,你总是可以找到更多的解决方案。 2. 调优应用程序。 3. 更多的SOA。 4. 由多个可用域升级到多个可用区。 5. 开始构建定制的解决方案,专用于解决你遇到的特定问题。 6. 深入分析整个应用栈。 <a id="org49c6bf3"></a> ## 总结 1. 使用多可用域提高可用性。 2. 使用自动伸缩服务。 3. 在应用的各级构建冗余,可伸缩性和冗余性可以同时实现。 4. 有关系性数据库开始构建应用。 5. 缓存数据。 6. 使用自动化管理工具。 7. 保证有较好的测量,监控,日志工具。 8. SOA。 9. 将部分数据迁移到NoSql。
Ruby
UTF-8
384
2.78125
3
[]
no_license
class PC attr_accessor :pantalla def initialize(pantalla) self.pantalla = pantalla end def ppp pantalla.ppp end def consumo_de_pantalla self.pantalla.consumo end def consumo_pc super end def consumo_total self.consumo_de_pantalla + self.consumo_pc end def es_apta_videojuegos? @pantalla.usar_para_videojuegos? && super end end
JavaScript
UTF-8
1,076
2.515625
3
[ "Apache-2.0", "MIT" ]
permissive
//Para inicializar las funciones de mensajería (notificaciones) document.addEventListener('deviceready', function () { //Al recibir la notificación (con aplicación abierta) window.plugins.OneSignal .startInit("6a1e3ec9-5164-4876-8c93-7adcbabfdc70") .handleNotificationReceived(function(jsonData) { //alert("Notification received:\n" + JSON.stringify(jsonData)); //Si es agregar actividades diarias va al if, y si es de invitación va al else if(!jsonData['payload']['additionalData']['noti']=="inv"){ location.href ="actividades.html"; }else{ location.href ="evento.html?inv="+jsonData['payload']['additionalData']['even']; } }) .endInit(); window.plugins.OneSignal .startInit( "6a1e3ec9-5164-4876-8c93-7adcbabfdc70") .handleNotificationOpened(function(jsonData) { if(!jsonData['payload']['additionalData']['noti']=="inv"){ location.href ="actividades.html"; }else{ location.href ="evento.html?inv="+jsonData['payload']['additionalData']['even']; } }) .endInit(); }, false);
PHP
UTF-8
854
2.5625
3
[ "MIT" ]
permissive
<?php namespace SensioLabs\Behat\PageObjectExtension\Context; use SensioLabs\Behat\PageObjectExtension\PageObject\Element; use SensioLabs\Behat\PageObjectExtension\PageObject\InlineElement; use SensioLabs\Behat\PageObjectExtension\PageObject\Page; interface PageFactoryInterface { /** * @param string $name * * @return Page */ public function createPage($name); /** * @param string $name * * @return Element */ public function createElement($name); /** * @param string|array $selector * * @return InlineElement */ public function createInlineElement($selector); /** * @param string $namespace */ public function setPageNamespace($namespace); /** * @param string $namespace */ public function setElementNamespace($namespace); }
Ruby
UTF-8
436
4.09375
4
[]
no_license
def print_welcome puts "welcome to converter" end def convert_to_celsius(degrees_fahrenheit) ((degrees_fahrenheit-32)* 5.0/9.0).round(2) end def print_converted(temperature) converted=convert_to_celsius(temperature) puts "#{temperature} is equal to #{converted} degrees celcius" end def convert(first,second,third) print_welcome print_converted(first) print_converted(second) print_converted(third) end convert(12,34,56)
PHP
UTF-8
3,394
3.140625
3
[]
no_license
<?php require_once "BaseService.php"; /** * Plot related service */ class ChangeProcessService extends BaseService { /** * Constructor */ public function __construct() { $this->tablename = "change_process"; $this->connect(); } public function __destruct() { $this->close(); } /** * Returns all the rows from the table. * * @param int $project_id * @param int $tsa * @param int $plotid * @param int $interpreter * @return array */ public function getProcessForPlot($project_id, $tsa, $plotid, $interpreter) { $sql =<<<DOQ SELECT project_id, tsa, plotid, groups, process, shape, context, trajectory, comments, interpreter, iscomplete, issnow, isphenology, iscloud, ismisregistration, ispartialpatch, iswrongyear FROM change_process WHERE project_id = $project_id AND tsa = $tsa AND plotid = $plotid AND interpreter = $interpreter DOQ; $result = $this->connection->query($sql); $this->throwExceptionOnError(); $rows = array(); while($row = $result->fetch_array(MYSQLI_ASSOC)) { $row['project_id'] = $row['project_id']+0; $row['tsa'] = $row['tsa'] + 0; $row['plotid'] = $row['plotid'] + 0; $row['groups'] = $row['groups'] + 0; $row['interpreter'] = $row['interpreter'] + 0; $row['iscomplete'] = $row['iscomplete'] + 0; $row['issnow'] = $row['issnow'] + 0; $row['isphenology'] = $row['isphenology'] + 0; $row['iscloud'] = $row['iscloud'] + 0; $row['ismisregistration'] = $row['ismisregistration'] + 0; $row['ispartialpatch'] = $row['ispartialpatch'] + 0; $row['iswrongyear'] = $row['iswrongyear'] + 0; $rows[] = $row; } $result->close(); return $rows; } /** * Add change process interpretation to the database. * sicne it is unknow whether vertex exists on existing plot, * the sequence of operation is to first delete all existing vertex * for the given plot interpretation and then add all the new information. * To maintaine database consistencey, a transaction is being used. * * @param int $project_id * @param int $tsa * @param int $plotid * @param int $interpreter * @param string $sqlstr * @return int */ public function updatePlotProcess($project_id, $tsa, $plotid, $interpreter, $sqlstr) { $sql = <<<DOQ INSERT INTO change_process (project_id, tsa, plotid, groups, process, shape, context, trajectory, comments, interpreter, iscomplete, issnow, isphenology, iscloud, ismisregistration, ispartialpatch, iswrongyear) VALUES DOQ; $del = <<<DOQ DELETE FROM change_process WHERE project_id = $project_id AND tsa = $tsa AND plotid = $plotid AND interpreter = $interpreter DOQ; //rough check on the format if (strlen($sqlstr)<34) { return 1; } try { $this->connection->autocommit(false); //remove existing ones $this->connection->query($del); $this->throwExceptionOnError(); //add new ones $insql = $sql . ' ' . $sqlstr; $this->connection->query($insql); $this->throwExceptionOnError(); $this->connection->commit(); return 0; } catch (Exception $e) { $this->connection->rollback(); throw $e; } } }
Java
UTF-8
4,172
2.234375
2
[]
no_license
package fr.wildcodeschool.blablawild.search; import android.app.DatePickerDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Toast; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import fr.wildcodeschool.blablawild.R; import fr.wildcodeschool.blablawild.data.ItineraryData; import fr.wildcodeschool.blablawild.list.ItineraryListActivity; public class ItinerarySearchActivity extends AppCompatActivity implements ItinerarySearchView{ private ItinerarySearchPresenter<ItinerarySearchView> presenter = new ItinerarySearchPresenterImpl<>(); private EditText departure; private EditText destination; private EditText date; private Button searchSend; private Calendar calendar; private DateFormat sdf; public static Intent getStartIntent(Context context) { return new Intent(context, ItinerarySearchActivity.class); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_itinerary_search); departure = findViewById(R.id.itinerary_search_departure_edit); destination = findViewById(R.id.itinerary_search_destination_edit); date = findViewById(R.id.itinerary_search_date_edit); searchSend = findViewById(R.id.itinerary_search_send_button); presenter.attach(this); calendar = Calendar.getInstance(); sdf = SimpleDateFormat.getDateInstance(DateFormat.SHORT); try { if (!date.getHint().toString().isEmpty()) { Date tmp = stringAsDate(date.getHint().toString()); date.setHint(sdf.format(tmp)); } } catch (ParseException e) { e.printStackTrace(); } date.setOnClickListener(onEditDateListener(this)); searchSend.setOnClickListener(onSearchSendListener); } @Override protected void onDestroy() { super.onDestroy(); presenter.detach(); } private DatePickerDialog.OnDateSetListener onDateSetListener() { return new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); date.setText(sdf.format(calendar.getTime())); } }; } private View.OnClickListener onEditDateListener(final Context context) { return new View.OnClickListener() { @Override public void onClick(View v) { new DatePickerDialog(context, onDateSetListener(), calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)) .show(); } }; } private View.OnClickListener onSearchSendListener = new View.OnClickListener() { @Override public void onClick(View v) { presenter.onSearchSend(departure.getText().toString(), destination.getText().toString(), date.getText().toString()); } }; @Override public Date stringAsDate(String date) throws ParseException { if (date.isEmpty()) return null; return sdf.parse(date); } @Override public void searchSend(ItineraryData itineraryData) { Intent intent = ItineraryListActivity.getStartIntent(this, itineraryData); startActivity(intent); } @Override public void showError(int id) { Toast toast = Toast.makeText(this, id, Toast.LENGTH_SHORT); toast.show(); } }
JavaScript
UTF-8
5,014
3.1875
3
[ "MIT" ]
permissive
'use strict' // record start time var dateStartTime; function display() { alert('in display function'); // later record end time var endTime = new Date(); // time difference in ms var timeDiff = endTime - dateStartTime; // strip the miliseconds timeDiff /= 1000; // get seconds var seconds = Math.round(timeDiff % 60); //console.log('seconds ' + seconds); // remove seconds from the date timeDiff = Math.floor(timeDiff / 60); // get minutes var minutes = Math.round(timeDiff % 60); // remove minutes from the date timeDiff = Math.floor(timeDiff / 60); // get hours var hours = Math.round(timeDiff); // the rest of timeDiff is number of days seconds = checkTime(seconds); minutes = checkTime(minutes); hours = checkTime(hours); $("#elapsedTime").text( hours + ":" + minutes + ":" + seconds); setTimeout(display, 1000); } $("input#startElapsedCounter").click(function () { if(OFF === false){ //alert('Stopping current activity'); }else{ OFF = false; //console.log('events[0] = ' + events[0]); //this defines the array events.push(event); // // console.log('events[0] = ' + events[0]); //disable start button //enable stop button stop_start_enable(); events[0].strTask = getTask(); events[0].booActive = true; events[0].notes = 'events[0]'; events[0].startTime = new Date(); console.log('events[0].startTime = ' + events[0].startTime ); //set alarm events[0].alarm.period = 60 * parseInt($('input[name="goalTime"]:checked').val()); events[0].alarm.startTime = events[0].startTime; events[0].alarm.booOn = (events[0].alarm.period != '0'); //events[0].alarm.period = 5; if (events[0].alarm.booOn){ $('#bell-stat').html(' ON' + '<span id="remain" ></span>');}else{ $('#bell-stat').html(' OFF'); } //send events object 0 to consol outputEvent('start elapsed' , events[0]); //save new event data //this is where the active item is saved //alert('about to store current item'); save_to_local_storage('active' , events[0]); //debug get item from ls //worked //alert(localStorage.getItem('active')); setTimeout(displayObj, 1000); } }); function toggleBell(){ // alert("turning alarm off") pauseAlarm(); } $("input#stopElapsedCounter").click(function () { //events[0] = new Object(event); //events[0].strTask = new Date(); events[0].endTime = new Date(); outputEvent('after adding end time' , events[0]); events[0].elapsedSeconds = Math.round((events[0].endTime - new Date(events[0].startTime))/1000 ); /// 1000); console.log('events[0].elapsedSeconds = ' + events[0].elapsedSeconds); events[0].booActive = false; start_stop_enable(); remove_from_local_storage('active'); set_results(); stuffIt2(); }); function getTask(){ var strActivity = $('#inputActivity').val(); if (strActivity == "enter activity") { strActivity = prompt("Enter Activity", "No Activity Entered"); } g_strActivity = strActivity; $('#activity').html(strActivity); return strActivity; } function displayObj() { // later record end time var endTime = new Date(); // time difference in ms var timeDiff = endTime - new Date(events[0].startTime); //alert('endtime = ' + endTime + ' startTime = ' + events[0].startTime); // strip the miliseconds timeDiff /= 1000; // get seconds var seconds = Math.round(timeDiff % 60); //console.log('seconds ' + seconds); // remove seconds from the date timeDiff = Math.floor(timeDiff / 60); // get minutes var minutes = Math.round(timeDiff % 60); // remove minutes from the date timeDiff = Math.floor(timeDiff / 60); // get hours var hours = Math.round(timeDiff); // the rest of timeDiff is number of days seconds = checkTime(seconds); minutes = checkTime(minutes); hours = checkTime(hours); $("#elapsedTime").text( hours + ":" + minutes + ":" + seconds); //check if alarm on if(events[0].alarm.booOn){ //check if time to alarm var t; var left; t = Math.round((Date.parse(new Date()) - events[0].startTime) / 1000); left = events[0].alarm.period - t ; if (left > 60 ){ left = Math.round((left/60) - .5); } if(left<0) left='0'; $('span#remain').html(' [ ' + left + ' ] '); //console.log('-events[0].alarm.period --' + events[0].alarm.period ); if (t > events[0].alarm.period ) { console.log('t.total > period '); if(OFF!= true){ events[0].alarm.booOn=false; //play alarm $('#debug').html('in timeout play'); $('#play').click(); } } } if(!OFF){ setTimeout(displayObj, 1000); } }
Java
UTF-8
1,022
2.203125
2
[]
no_license
package com.events.hanle.events.BroadCast; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.widget.Toast; import com.events.hanle.events.gcm.GcmIntentService; /** * Created by Hanle on 5/30/2017. */ public class Offline extends BroadcastReceiver { public static final int REQUEST_CODE = 131231; @Override public void onReceive(Context context, Intent intent) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""); wl.acquire(); // Put here YOUR code. Intent i = new Intent(context, GcmIntentService.class); i.putExtra(GcmIntentService.KEY, GcmIntentService.OFFLINE); context.startService(i); //Toast.makeText(context, "Alarm from offline !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example wl.release(); } }
PHP
UTF-8
7,007
2.625
3
[]
no_license
<?php $cid=$_GET['cid']; include "conn.php"; ini_set( "display_errors", 0); if(isset($_POST['addpro'])) { echo "addpro"; $pro_name = $_POST['pro_name']; $quantity = $_POST['quantity']; $doo = $_POST['doo']; echo $quantity; echo $pro_name; echo $cid; $pr = "SELECT * FROM product WHERE pid ='$pro_name'"; $price_pro= mysqli_query($conn,$pr); while($data = mysqli_fetch_assoc($price_pro)){ $p_pro= $data['price']; } $limit_qua = "SELECT * FROM product WHERE pid='$pro_name'"; $limit_r = mysqli_query($conn,$limit_qua); /*if (mysqli_query($conn,$limit_qua)){ //echo "successful"; }else{ echo mysqli_error($conn); }*/ while($row= mysqli_fetch_assoc($limit_r)){ $limit = $row['quantity']; $lower_limit = $row['q_lower_limit']; echo "limit is ".$limit; } echo "<br>"; echo $limit." ".$quantity; if($limit<$quantity){ echo "<script>alert('please enter quantity less than $limit ');</script>"; // header("location:add_pro.php?cid=$cid"); } else{ $q = "INSERT INTO `cus_pro`(`cid`, `pid`, `quantity`,`doo`,`price`) VALUES ($cid,'$pro_name','$quantity','$doo','$p_pro')"; if(mysqli_query($conn,$q)){ echo "successful uploaded data in table!\n"; }else{ echo mysqli_error($conn); } $total_q ="UPDATE customer SET total = (SELECT SUM(cus_pro.quantity * cus_pro.price) FROM cus_pro WHERE customer.cid = cus_pro.cid)"; if(mysqli_query($conn,$total_q)){ echo "successful q2!"; }else{ echo mysqli_error($conn); } //} $limit ="UPDATE product SET quantity = quantity-'$quantity' WHERE pid='$pro_name'"; if(mysqli_query($conn,$limit)){ echo "successful limit!"; }else{ echo mysqli_error($conn); } $price_q = "SELECT * FROM product WHERE pid ='$pro_name'"; $price= mysqli_query($conn,$price_q); while($data = mysqli_fetch_assoc($price)){ $quantity_afu= $data['quantity']; echo $quantity_afu; } if($quantity_afu<$lower_limit){ echo "quantity is less than lower limit "; $insert = "INSERT INTO lower_limit values ('$pro_name',$lower_limit,$quantity_afu)"; if(mysqli_query($conn,$insert)){ echo " data inserted in q_lower limit"; }else{ echo mysqli_error($conn); } } } } ?> <?php $q = "SELECT * FROM customer WHERE cid = $cid"; $result = mysqli_query($conn,$q); while($row = mysqli_fetch_assoc($result)) { ?> <div class="container p-3 my-3 bg-dark text-white"> <p><?php echo "NAME : ".$row['name']; ?></p><br> <p><?php echo "EMAIL : ".$row['email']; ?></p><br> <p><?php echo "CONTACT NUMBER : ".$row['phone']; ?></p><br> <p><?php echo "GENDER : ".$row['gender']; ?></p><br> </div> <?php } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>INSERT DATA</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <!-- JS, Popper.js, and jQuery --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> </head> <body> <button class="btn-secondary btn "><a href="index.php" class="text-white text-center">HOME</a></button> <h1 class='text-center'>CUSTOMER DETAILS</h1> <table class="table table-striped table-hover table-border"> <TR> <th>OID</th> <th>PID</th> <th>PNAME</th> <th>QUANTIY</th> <th>DATE OF ORDER</th> <th><button class="btn-primary btn"><a href="sort_by_ordp.php?cid=<?php echo $cid; ?>"class="text-white text-center">SORT PRICE</a></button> </th> <th>UPDATE</th> <th>DELETE</th> </tr> <?php //$show = "SELECT c.*,b.total,p.pname FROM cus_pro as c ,customer as b ,product as p WHERE c.cid=$cid and b.cid=$cid and p.pid=$pro_name"; //$show="SELECT cs.* ,p.pname FROM cus_pro as cs, product as p,customer as c WHERE cs.cid=$cid and p.pid=cs.pid "; $show="SELECT cs.* ,p.pname , (cs.price * cs.quantity)as pro FROM cus_pro as cs, product as p WHERE cs.cid=$cid and p.pid=cs.pid"; $result = mysqli_query($conn,$show); while($row=mysqli_fetch_array($result)){ ?> <tr> <td><?php echo $row['oid']; ?></td> <td><?php echo $row['pid']; ?></td> <td><?php echo $row['pname']; ?></td> <td><?php echo $row['quantity']; ?></td> <td><?php echo $row['doo']; ?></td> <td><?php echo $row['pro']; ?></td> <td><button class="btn-danger btn"><a href="ord_delete.php?oid=<?php echo $row['oid']; ?>&cid=<?php echo $row['cid']; ?>&pid=<?php echo $row['pid']; ?>"class="text-white text-center">DELETE</a></button></td> <td><button class="btn-danger btn"><a href="ord_update.php?oid=<?php echo $row['oid']; ?>&cid=<?php echo $row['cid']; ?>&pid=<?php echo $row['pid']; ?>"class="text-white text-center">UPDATE</a></button></td> </tr> <?php } ?> <form method="post"><button class="btn-primary btn col-sm-4 btn-block" method="post" type="submit" name="plus"> + (add more) </button><br><br> <?php if (isset($_POST['plus'])) { ?> <h1>INSERT CUSTOMER DATA</h1> <label for="pro_name">PRODUCT NAME</label><br><br> <?php // <input type="text" class="pro_name" id="pro_name" name="pro_name" required><br><br> ?> <select name="pro_name" id="pro_name"> <?php $q2 = "SELECT * FROM product "; $result2 = mysqli_query($conn,$q2); while($r = mysqli_fetch_assoc($result2)) { ?> <option value=<?php echo $r['pid']; ?>><?php echo $r['pname']; ?></option> <?php } ?> </select><BR><BR> <label for="quantity">Enter quantity</label><br><br> <input type="number" id="quantity" name="quantity" required><br><br> </select> <label for="doo">DATE OF ORDER:</label> <input type="date" name="doo" id="doo"> <button type="submit" name="addpro" id="addpro">ADD PRODUCT</button><br><br> <?php } ?> </form> </body> <footer> <?php $tt = "SELECT total FROM customer WHERE cid =$cid"; $price_tt= mysqli_query($conn,$tt); while($data = mysqli_fetch_assoc($price_tt)){?> <TH>TOTAL</TH> <tH><?php echo $data['total']; ?></tH> <?php } ?> </footer> </html>
Markdown
UTF-8
8,586
2.625
3
[]
no_license
--- layout: post title: Cómo hice el blog description: Cómo hacer un blog con Jekyll, paso a paso permalink: 2015/01/como-hice-el-blog/ tags: - blog comments: true --- ![Jekyll y GitHub](/public/pictures/jekyll-github.png) En Internet hay un montón de alternativas para crear un blog propio. Cuando me propuse crear una web personal tuve claro desde el principio que los contenidos generados deberían ser míos. Me explico: en ocasiones, al utilizar plataformas como [blogger](http://www.blogger.com) ocurre que los posts quedan alojados en un servidor sobre el que no tienes ningún control. Y así te puedes encontrar con que nuestro amigo Google ha decidido que no estás cumpliendo las *condiciones de uso* y cerrártelo de buenas a primeras. En la misma liga juegan los blogs de [WordPress](https://es.wordpress.com/), por ejemplo. <!--break--> No hablo de primera mano, pero sí que me he encontrado con gente en esta situación leyendo foros y demás. Siempre es posible hacer copias de seguridad, pero en caso de catástrofe recuperar los contenidos de la forma en que se encontraban supondría un esfuerzo que no sé si estaría dispuesto a asumir (y digo esto cuando aún no he publicado la segunda entrada de mi blog :)). Total, que las opciones se iban reduciendo. Durante varias semanas casi llegué a decidirme por contratar un hosting e instalar WordPress ([no es lo mismo Wordpress.org que Wordpress.com](http://www.creartiendavirtual.com.es/diferencias-entre-wordpress-org-y-wordpress-com-y-tu-padre-y-tu-madre-cual-te-conviene-elegir/)), pero, para ser sinceros, no me apetecía demasiado el desembolso inicial, y seguía teniendo la sensación de estar limitado por una plataforma, plataforma que es infinita en cuanto a opciones por otra parte, y permite conseguir resultados tan chulos como [esta web](http://carlosalcaniz.com/). La opción definitiva la descubrí de la mano de [Trisha Gee](http://trishagee.github.io/), referencia de la [London Java Community](https://twitter.com/ljcjug). Descubrí que su blog está alojado en [GitHub Pages](https://pages.github.com/), una especia de servicio de hosting que da GitHub a sus usuarios, ¡de forma gratuita! La idea es que tú generas tu web como quieras y la subes a un repositorio GitHub para finalmente ser publicada en la URL [usuario].github.io. Genial. Profundizando más, existe una plataforma llamada [Jekyll](http://jekyllrb.com/), que es utilizada por GitHub pages para generar webs a partir de contenido estático creado mediante [Markdown](http://es.wikipedia.org/wiki/Markdown). Esta plataforma corre con Ruby, lenguage del que no tengo ni idea, pero del que apenas hay que conocer nada para utilizar Jekyll. En resumen, que me decidí por Jekyll + GitHub pages, y diría que no puedo estar más contento con la decisión. Aparte de permitirme mantener una copia local de mi web puedo jugar todo lo que quiera con estilos, plantillas, etc. Otra ventaja muy interesante es que al subirse como contenidos estáticos, sin bases de datos o plugins respaldando, la seguridad frente a ataques es bastante alta. Reproduciré a continuación, a modo de referencia, los diferentes pasos que llevé a cabo para poner en marcha esta web (y así queda registrado por si tengo que volver a hacerlo algún día): 1. Dar de alta una cuenta en [GitHub](https://github.com/). El nombre de usuario será el que dará nombre a la web una vez publicada (en mi caso raulavila.github.io). 2. Crear el repositorio que alojará el blog, [según se explica aquí](https://pages.github.com/). 3. [Instalar Jekyll](http://www.webhostwhat.com/guide-how-to-host-jekyll-blog-on-github-using-a-mac/). Si no tienes un Mac sería necesario [instalar Ruby primero](http://jekyllrb.com/docs/installation/). 4. Buscar una plantilla de referencia para, a partir de ahí, dar forma al blog. Esta opción es más sencilla que crear la página desde cero, aunque también sería una posibilidad, claro. La plantilla que elegí fue [Poole](http://getpoole.com/), es muy minimalista, e incluye varios archivos útiles como el Feed, 404, config, etc. 5. Añadir la plantilla al repositorio, junto con un fichero .gitignore (para que no se incluyan ciertos archivos en los commits). Si lo subimos a GitHub podremos ver la web publicada por primera vez pasados unos 30 minutos (en posteriores commits los cambios se actualizan automáticamente). 6. Configurar correctamente las variables del fichero _config.yml 7. Tunear los ficheros CSS a mi gusto, así como el layout de las plantillas. 8. Cambiar el idioma de los textos de las plantillas a Castellano. Algún día escribiré un post explicando por qué decidí escribir en Castellano y no en inglés. 9. Añadir una página de [Archivos](/archivos), que recorre todos los posts publicados y los lista por fecha. Para ello utilizo el lenguaje de plantillas [Liquid](http://jekyllrb.com/docs/templates/). También añadí una página [Sobre mí](/sobre-mi), pero tampoco tiene demasiado misterio. 10. Jekyll genera de forma automática los permalinks, pero no me gustaba demasiado la forma en que lo hacía. Existe la opción de asignar el permalink que deseemos mediante la variable permalink [en la cabecera de los posts](http://jekyllrb.com/docs/frontmatter/). 11. Añadir botones de Twitter ([Follow Me](https://dev.twitter.com/web/follow-button) en "Sobre mí", y [Tweet](https://dev.twitter.com/web/tweet-button) en la cabecera de los posts). Es muy sencillo siguiendo las indicaciones de los enlaces. 12. Soporte para añadir tags en los posts, y crear páginas para cada tag específico. Seguí las indicaciones de [este blog](http://charliepark.org/tags-in-jekyll/), no obstante me trajo varios quebraderos de cabeza por motivos que explicaré en el anexo. La verdad es que el soporte para tags es uno de los puntos flacos de Jekyll+GitHub Pages. 13. Truncar posts en la página de inicio, según se explica [aquí](http://mikeygee.com/blog/truncate.html). 14. Para publicar bajo un dominio propio, en lugar de *.github.io, compré el nombre en [NameCheap](https://www.namecheap.com/). Es una opción bastante barata, e incluye el servicio [WhoIs Guard](https://www.namecheap.com/domains/whois.aspx). 15. Configurar las DNS de GitHub pages en NameCheap. [Este blog](http://davidensinger.com/2013/03/setting-the-dns-for-github-pages-on-namecheap/) lo explica perfectamente. 16. Añadir comentarios [Disqus](https://disqus.com/). Tras darme de alta en la web, las indicaciones fueron muy claras y funcionó sin ningún problema. 17. Añadir [Google Analytics](http://www.google.com/analytics/), para así poder saber si me visita alguien de vez en cuando. 16. Tunear detallitos sin importancia aquí y allá. Creo que no me dejo nada. Mención especial para [este post](http://joshualande.com/jekyll-github-pages-poole/), que me sirvió de referencia para muchos de los puntos. De hecho, utilizo la misma plantilla. ### Anexo: GitHub y los plugins Me encontré con un problema inesperado a la hora de añadir el plugin de Ruby que creaba automáticamente las páginas para los tags. Al subirlo a GitHub pages descubrí que dichas páginas ¡no se generaban! Tras investigar un poco, lo que ocurre es que GitHub pages, al generar los sites a partir de las plantillas de Jekyll no ejecuta, por seguridad, los plugins adicionales que pueda haber en la carpeta **_plugins**, y que sí se ejecutan a nivel local. La solución a este dilema no fue nada sencilla. Pensé en descartar el uso de plugins para la web, pero me parecía limitarme demasiado. No solo me llevaba a crear una solución más chapucera para los tags, a medio plazo no podría añadir cualquier otra cosa si lo consideraba necesario. La salida más razonable está explicada en [este post](http://www.sitepoint.com/jekyll-plugins-github/). En lugar de dejar a GitHub la tarea de generar la web la genero yo localmente y la subo al repositorio de GitHub pages. El código fuente está subido en un repositorio diferente. Aunque existe una solución que juega con las ramas dentro del mismo repositorio, me pareció más adecuado así ([Separation of concerns](http://en.wikipedia.org/wiki/Separation_of_concerns) y tal). Por tanto, finalmente mi blog está dividido en dos repositorios: * [Uno con el código fuente](https://github.com/raulavila/blog-source-code) * [Y otro con el site generado en local con Jekyll](https://github.com/raulavila/raulavila.github.io) Es increíble la cantidad de trabajo que puede llevar montar una página tan sencillita, pero estoy bastante orgulloso del resultado.
JavaScript
UTF-8
615
2.75
3
[ "MIT" ]
permissive
class Level { #height #width #mines #size remainder constructor(height, width, mines) { this.#height = height this.#width = width this.#mines = mines this.#size = height * width this.remainder = this.#size - this.#mines } get height() { return this.#height } get width() { return this.#width } get size() { return this.#size } get mines() { return this.#mines } get remainder() { return this.remainder } } export const easy = new Level(10, 10, 10) export const medium = new Level(16, 16, 40) export const hard = new Level(16, 30, 99)
C++
UTF-8
3,382
3.734375
4
[]
no_license
#include <iostream> #include<string> using namespace std; template<typename T> class Node { public: string key; T value; Node<T>*next; Node(string key, T val) { this->key = key; value = val; next = NULL; } ~Node() { if(next!=NULL){ delete next; } } }; template<typename T> class Hashtable{ private: Node<T>** table; int cs; int ts; int hashFn(string key) //Hash Function to convert alphabet*27%tableSize { int idx = 0; int p = 1; for(int j=0;j<key.length();j++) { idx = idx+(key[j]*p)%ts; idx = idx%ts; p = (p*27)%ts; } return idx; } void rehash() { Node<T> **old = table; ts = 2*ts; table = new Node<T>*[ts]; for(int i=0;i<ts;i++){ table[i] = NULL; } cs = 0; for(int i=0;i<(ts/2);i++) { Node<T>*temp = old[i]; while(temp!=NULL) { insert(temp->key,temp->value); temp=temp->next; } if(old[i]!=NULL){ delete old[i]; } } delete [] old; } public: Hashtable(int ts = 7) { this->ts = ts; table = new Node<T>*[ts]; //Allocation of array for hashTable cs = 0; for(int i=0;i<ts;i++) { table[i] = NULL; } } void insert(string key, T value) { int idx = hashFn(key); Node<T>* n = new Node<T>(key,value); n->next = table[idx]; table[idx] = n; cs++; float lf = cs/(1.0*ts); if(lf>0.7) rehash(); } void print() { for(int i=0;i<ts;i++) { cout<<"Bucket "<<i<<" --> "; Node<T> *temp = table[i]; while(temp!=NULL) { cout<<temp->key<<" --> "; temp = temp->next; } cout<<endl; } cout<<endl; } T* search(string key) { int idx = hashFn(key); Node<T> *temp = table[idx]; while(temp!=NULL) { if(temp->key==key) return &temp->value; temp=temp->next; } return NULL; } void erase(string key) { if(search(key)!=NULL) { int idx = hashFn(key); Node<T>* temp = table[idx]; if(temp->key == key) //Erase if node is at head { table[idx] = temp->next; delete temp; cs--; return; } while(temp->next!=NULL) { if(temp->next->key==key) break; temp=temp->next; } if(temp->next == NULL) //Erase node if it is at Tail { Node<T>* prev = temp; prev->next = NULL; temp = temp->next; delete temp; cs--; return; } Node<T>* prev = temp; //Erase for anyother position(nth) temp=temp->next; prev->next = temp->next; delete temp; cs--; return; } } };
C#
UTF-8
4,095
2.65625
3
[ "Apache-2.0" ]
permissive
using System; using System.IO; using Whitelog.Core.Binary.Serializer.MemoryBuffer; namespace Whitelog.Core.Binary.Deserilizer.Reader { public class ExpendableListReader : IListReader { class ExpendableBuffer : IRawData { public int Length { get; set; } public byte[] Buffer { get; set; } public DateTime DateTime { get; set; } } private ExpendableBuffer m_expendableBuffer; private long m_readIndex; private Stream m_stream; public ExpendableListReader(Stream stream):this (stream,stream.Position) { } public ExpendableListReader(Stream stream, long startReadPosition) { m_readIndex = startReadPosition; m_stream = stream; m_expendableBuffer = new ExpendableBuffer() { Buffer = new byte[1024], Length = 0, }; } public bool Read(IBufferConsumer bufferConsumer) { byte[] intSizeBuffer = new byte[sizeof(int)]; if (m_readIndex < m_stream.Length) { m_stream.Position = m_readIndex; m_stream.Read(intSizeBuffer, 0, intSizeBuffer.Length); int sizeBuffer = BitConverter.ToInt32(intSizeBuffer, 0); if (sizeBuffer != -1) { if (m_expendableBuffer.Buffer.Length >= sizeBuffer) { m_expendableBuffer.Buffer = new byte[sizeBuffer]; } if (m_stream.Read(m_expendableBuffer.Buffer, 0, sizeBuffer) != sizeBuffer) { throw new CorruptedDataException(); } else { m_readIndex = m_stream.Position; m_expendableBuffer.Length = sizeBuffer; bufferConsumer.Consume(m_expendableBuffer); return true; } } } return false; } public bool ReadAll(IBufferConsumer bufferConsumer) { var maxRead = m_stream.Length; bool ended = false; if (m_readIndex < maxRead) { m_stream.Position = m_readIndex; } else { ended = true; } byte[] intSizeBuffer = new byte[sizeof(int)]; bool hasAnyRead = false; while (!ended) { if (m_stream.Read(intSizeBuffer, 0, intSizeBuffer.Length) != sizeof (int)) { ended = true; } else { int sizeBuffer = BitConverter.ToInt32(intSizeBuffer, 0); if (sizeBuffer == 0) { // this is for debug only m_stream.Seek(-4, SeekOrigin.Current); ended = true; } else { if (m_expendableBuffer.Buffer.Length < sizeBuffer) { m_expendableBuffer.Buffer = new byte[sizeBuffer]; } if (m_stream.Read(m_expendableBuffer.Buffer, 0, sizeBuffer) != sizeBuffer) { throw new CorruptedDataException(); } else { m_readIndex = m_stream.Position; m_expendableBuffer.Length = sizeBuffer; bufferConsumer.Consume(m_expendableBuffer); hasAnyRead = true; } ended = !(m_readIndex < maxRead); } } } return hasAnyRead; } } }
Markdown
UTF-8
5,830
2.515625
3
[ "MIT" ]
permissive
--- template: PracticePage title: Broken Rib Lawyer status: Published date: 2020-09-04 featuredImage: /images/ribs-injury-lawyer.jpg excerpt: We have 24 ribs, twelve on each side. Both men and women have the same amount of ribs. The ribs are attached to a spine bone in the back. categories: - category: Serious Personal Injury meta: title: Broken Rib Lawyer description: We have 24 ribs, twelve on each side. Both men and women have the same amount of ribs. The ribs are attached to a spine bone in the back. --- <iframe width="560" height="315" src="https://www.youtube.com/embed/Xi7g9BagtmQ" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <!--StartFragment--> The ribs are the long curved bones which form the rib cage, and enclose and protect the internal organs such as the lungs and heart and other organs inside the thoracic cavity. They enable the lungs to expand and facilitate breathing within the chest cavity. As a result, rib injuries can be devastating. An experienced broken rib lawyer can help you recover the full compensation you deserve. <!--EndFragment--> ![](/images/ribs.jpg) <!--StartFragment--> We have 24 ribs, twelve on each side. Both men and women have the same amount of ribs. The ribs are attached to a spine bone in the back. The first seven pairs of ribs join the breastbone in the center of the chest. The front ends of the eight, ninth, and 10th A direct blow to the chest from a [car accident](/practice-areas/car-accident-lawyers/) or a [slip and fall](/practice-areas/slip-and-fall-injury-lawyers/) situation can cause rib injuries such as a [rib fracture](/practice-areas/broken-bone-injury-attorneys/). In a car crash, the ribs can become injured in many ways. A side impact collision could push the door or the center console into the driver or passenger. If the car rolls due to the impact, the occupants will roll with it, exposing the people inside to all kinds of injuries. The force of the impact can also cause objects to fly about the interior, even shearing off bolted car parts. Those objects may strike the ribs or other parts of the body at high speed, causing injury. Another common cause of rib injuries in an accident involve the rapid deployment of airbags which can exert a lot of force on the chest leading to rib injuries. The sudden stop of momentum when the seat-belt arrests a moving body can also cause rib injuries. ## Types of Rib Injuries ### Broken Ribs The high pulling force towards the seat-belts during a rolling action of a car can lead to broken ribs. Some people even develop broken ribs due to the collision which can exert too much pressure on the rib cage area. If you experience broken ribs, it is necessary to seek urgent medical attention. Rib Fractures Force exerted on your chest due to pulling by the seat belt or airbag can expose you to the extreme force which can make you suffer from rib fractures. ### Inflamed Rib Cartilage Trauma to the chest area can lead to inflammation of the rib cartilage. Exposure of the rib to too much force causes muscle injury around the rib cage area. The result will be pain which will be too much for you to bear. ## Symptoms, Complications, and Treatment of Rib Injuries If someone has a fractured rib, breathing will be difficult because all the muscles used for breathing pull on the ribs. Due to the difficulty of breathing deeply, pneumonia is a common secondary affect of rib injuries. It is very important to seek medical attention if you suspect your rib is fractured. An accident that caused an impact that fractured a rib can also cause injury to the lungs, spleen, blood vessels or other parts of the body. A collapsed lung is a common injury when a rib is fractured or punctured. Symptoms that you might experience if you have a fractured rib include, mild to severe pain in the injured area, pain when breathing, pain around the fracture if pressure is applied to the breastbone. You may also feel shortness of breath, anxiousness, restlessness, or you may be scared. You may have a headache, and feel dizzy, tired, or sleepy. The doctor will conduct a physical exam that will include applying pressure to the chest to find out the location of the injury, watch your breathing and make sure your lungs are working properly, listen to your heart, and check head, neck, and spine to make sure that there are no other injuries. Unfortunately, rib fractures do not always show up on imaging or x-rays, so the doctor may treat you for a rib fracture anyway just to be safe. A rib fracture can take up to six weeks to heal. The best treatment is rest, and pain management with aspirin or ibuprofen. It is really important to breath deeply or cough at least once an hour to prevent pneumonia and partial collapse of the lung tissue. Do not tightly wrap the injury because this will prevent deep breaths increasing the risk for the pneumonia. Sleeping on the injured side will also help with taking those deep breaths. This may seem counter intuitive at first, but it will help. Only sleep on the injured side, if you have not [injured your neck](/practice-areas/neck-injuries/) or [injured your back](/practice-areas/austin-back-injury-lawyers/) which may require lying in other positions. Consider contacting an experienced broken rib lawyer if your rib injury was due to the carelessness of someone else. ## Experienced Broken Rib Lawyer If you a rib injury due to a car accident, [motorcycle accident](/practice-areas/motorcycle-accident-attorney/) or slip and fall accident, and want to talk to an experienced broken rib lawyer, please call or text the Traub Law Office at 512-246-9191 or complete the form below for more information. We look forward to helping you. <!--EndFragment-->
C
UTF-8
2,151
2.734375
3
[ "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "Martin-Birgmeier", "dtoa", "MIT", "HPND", "SunPro", "CMU-Mach", "ISC", "Apache-2.0", "BSD-2-Clause", "BSD-4-Clause", "BSD-4.3TAHOE", "LicenseRef-scancode-ibm-dhcp" ]
permissive
/* $OpenBSD: strerror_r.c,v 1.6 2005/08/08 08:05:37 espie Exp $ */ /* Public Domain <marc@snafu.org> */ #include <errno.h> #include <limits.h> #include <signal.h> #include <stdio.h> #include <string.h> #include "private/ErrnoRestorer.h" typedef struct Pair Pair; struct Pair { int code; const char* msg; }; static const char* __code_string_lookup(const Pair* strings, int code) { size_t i; for (i = 0; strings[i].msg != NULL; ++i) { if (strings[i].code == code) { return strings[i].msg; } } return NULL; } static const Pair _sys_error_strings[] = { #define __BIONIC_ERRDEF(x,y,z) { x, z }, #include <sys/_errdefs.h> { 0, NULL } }; __LIBC_HIDDEN__ const char* __strerror_lookup(int error_number) { return __code_string_lookup(_sys_error_strings, error_number); } static const Pair _sys_signal_strings[] = { #define __BIONIC_SIGDEF(x,y,z) { y, z }, #include <sys/_sigdefs.h> { 0, NULL } }; __LIBC_HIDDEN__ const char* __strsignal_lookup(int signal_number) { return __code_string_lookup(_sys_signal_strings, signal_number); } int strerror_r(int error_number, char* buf, size_t buf_len) { ErrnoRestorer errno_restorer; ErrnoRestorer_init(&errno_restorer); size_t length; const char* error_name = __strerror_lookup(error_number); if (error_name != NULL) { length = snprintf(buf, buf_len, "%s", error_name); } else { length = snprintf(buf, buf_len, "Unknown error %d", error_number); } if (length >= buf_len) { ErrnoRestorer_override(&errno_restorer, ERANGE); ErrnoRestorer_fini(&errno_restorer); return -1; } ErrnoRestorer_fini(&errno_restorer); return 0; } __LIBC_HIDDEN__ const char* __strsignal(int signal_number, char* buf, size_t buf_len) { const char* signal_name = __strsignal_lookup(signal_number); if (signal_name != NULL) { return signal_name; } const char* prefix = "Unknown"; if (signal_number >= SIGRTMIN && signal_number <= SIGRTMAX) { prefix = "Real-time"; signal_number -= SIGRTMIN; } size_t length = snprintf(buf, buf_len, "%s signal %d", prefix, signal_number); if (length >= buf_len) { return NULL; } return buf; }
Java
UTF-8
142
1.976563
2
[]
no_license
package vcci.android.consumer.interfaces; public interface CategorySelectionListener { void onCategorySelected(int id, String title); }
Java
UTF-8
5,893
2.25
2
[]
no_license
package controlador; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import modelo.ruta; import modelo.vehiculo; import modeloDAO.rutaDAO; import modeloDAO.vehiculoDAO; @WebServlet(name = "servlet2", urlPatterns = {"/servlet2"}) public class servlet2 extends HttpServlet { vehiculoDAO dao=new vehiculoDAO(); vehiculo p=new vehiculo(); int id; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String accion=request.getParameter("accion"); if(accion.equalsIgnoreCase("Editar")){ try{ id=Integer.parseInt(request.getParameter("id")); } catch (NumberFormatException e){ } request.getRequestDispatcher("/modificarV.jsp").forward(request, response); }else if(accion.equalsIgnoreCase("modify")){ try{ id=Integer.parseInt(request.getParameter("id")); } catch (NumberFormatException e){ } request.getRequestDispatcher("/modificarVin.jsp").forward(request, response); }else if(accion.equalsIgnoreCase("eliminar")){ id=Integer.parseInt(request.getParameter("id")); p.setIdvehiculo(id); dao.eliminar(id); request.getRequestDispatcher("/vehiculo.jsp").forward(request, response); } else if(accion.equalsIgnoreCase("delete")){ id=Integer.parseInt(request.getParameter("id")); p.setIdvehiculo(id); dao.eliminar(id); request.getRequestDispatcher("/vehiculoin.jsp").forward(request, response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ String accion =request.getParameter("accion"); switch (accion) { case "registrar": int idconductor = Integer.parseInt(request.getParameter("idconductor")); String tipo = request.getParameter("tipo"); String modelo = request.getParameter("modelo"); String placa=request.getParameter("placa"); vehiculo vehiculo=new vehiculo(); vehiculoDAO DAO = new vehiculoDAO(); DAO.agendarVehiculo(modelo,placa,tipo,idconductor); request.getRequestDispatcher("/vehiculo.jsp").forward(request, response); break; case "editar": int idvehiculo = Integer.parseInt(request.getParameter("idvehiculo")); int estado = Integer.parseInt(request.getParameter("estado")); int idConductor = Integer.parseInt(request.getParameter("idconductor")); String Placa=request.getParameter("placa"); String Modelo = request.getParameter("modelo"); String Tipo = request.getParameter("tipo"); vehiculo registroin=new vehiculo(idvehiculo,estado,idConductor,Placa,Modelo,Tipo); vehiculoDAO inDAO = new vehiculoDAO(); inDAO.actualizarVehiculo(idvehiculo,estado,idConductor,Placa,Modelo,Tipo); request.getRequestDispatcher("/vehiculo.jsp").forward(request, response); break; case "eliminar": int idVehiculo = Integer.parseInt(request.getParameter("idvehiculo")); vehiculoDAO inDao =new vehiculoDAO(); inDao.eliminar(idVehiculo); request.getRequestDispatcher("/vehiculo.jsp").forward(request, response); break; case "edit": int IDVEHICULO = Integer.parseInt(request.getParameter("idvehiculo")); int ESTADO = Integer.parseInt(request.getParameter("estado")); int IDCONDUCTOR = Integer.parseInt(request.getParameter("idconductor")); String PLACA=request.getParameter("placa"); String MODELO = request.getParameter("modelo"); String TIPO = request.getParameter("tipo"); vehiculoDAO DAo = new vehiculoDAO(); DAo.actualizarVehiculo(IDVEHICULO,ESTADO,IDCONDUCTOR,PLACA,MODELO,TIPO); request.getRequestDispatcher("/vehiculoin.jsp").forward(request, response); break; case "add": int IDCONDUCTOr= Integer.parseInt(request.getParameter("idconductor")); String TIPo = request.getParameter("tipo"); String MODELo = request.getParameter("modelo"); String PLACa=request.getParameter("placa"); vehiculoDAO Dao = new vehiculoDAO(); Dao.agendarVehiculo(MODELo,PLACa,TIPo,IDCONDUCTOr); request.getRequestDispatcher("/vehiculoin.jsp").forward(request, response); break; default: } }catch(Exception e){ } } }
PHP
UTF-8
3,687
2.921875
3
[]
no_license
<?php /* * Following code will create a new product row * All product details are read from HTTP Post Request */ // array for JSON response $response = array(); // check for required fields if (isset($_POST['UserID']) && isset($_POST['NickName']) && isset($_POST['Country']) && isset($_POST['State']) && isset($_POST['GamesPlayed']) && isset($_POST['BestScore']) && isset($_POST['LongestStreak']) && isset($_POST['Wins']) && isset($_POST['LongestWinStreak']) && isset($_POST['MostCardsLeft']) && isset($_POST['WorstScore']) && isset($_POST['BestLoseScore']) && isset($_POST['LongStreakOnLoss']) && isset($_POST['LongestLoseStreak']) && isset($_POST['MostCardsLeftPeak']) && isset($_POST['TotalScore']) && isset($_POST['TotalWinScore']) && isset($_POST['TotalLosingScore']) && isset($_POST['AverageScore']) && isset($_POST['AverageWinScore']) && isset($_POST['AverageLoseScore']) && isset($_POST['WorstWinScore'])) { $userid = $_POST['UserID']; $nickname = $_POST['NickName']; $country = $_POST['Country']; $state = $_POST['State']; $gamesplayed = $_POST['GamesPlayed']; $bestscore = $_POST['BestScore']; $longeststreak = $_POST['LongestStreak']; $wins = $_POST['Wins']; $longestwinstreak = $_POST['LongestWinStreak']; $mostcardsleft = $_POST['MostCardsLeft']; $worstscore = $_POST['WorstScore']; $bestlosescore = $_POST['BestLoseScore']; $longstreakonloss = $_POST['LongStreakOnLoss']; $longestlosestreak = $_POST['LongestLoseStreak']; $mostcardsleftpeak = $_POST['MostCardsLeftPeak']; $totalscore = $_POST['TotalScore']; $totalwinscore = $_POST['TotalWinScore']; $totallosingscore = $_POST['TotalLosingScore']; $averagescore = $_POST['AverageScore']; $averagewinscore = $_POST['AverageWinScore']; $averagelosescore = $_POST['AverageLoseScore']; $worstwinscore = $_POST['WorstWinScore']; // include db connect class require_once __DIR__ . '/db_connect.php'; // connecting to db $db = new DB_CONNECT(); // mysql inserting a new row $result = mysqli_query($db->conn, "INSERT INTO scores (UserID, NickName, Country, State, GamesPlayed, BestScore, LongestStreak, Wins, LongestWinStreak, MostCardsLeft, WorstScore, BestLoseScore, LongStreakOnLoss, LongestLoseStreak, MostCardsLeftPeak, TotalScore, TotalWinScore, TotalLosingScore, AverageScore, AverageWinScore, AverageLoseScore, WorstWinScore) VALUES('$userid', '$nickname', '$country', '$state', '$gamesplayed', '$bestscore', '$longeststreak', '$wins', '$longestwinstreak', '$mostcardsleft', '$worstscore', '$bestlosescore', '$longstreakonloss', '$longestlosestreak', '$mostcardsleftpeak', '$totalscore', '$totalwinscore', '$totallosingscore', '$averagescore', '$averagewinscore', '$averagelosescore', '$worstwinscore')"); //var_dump($userid); //var_dump($nickname); //var_dump($country); /*$result = mysqli_query($db->conn, "INSERT INTO scores (UserID, NickName, Country) VALUES('$userid', '$nickname', '$country')");*/ // check if row inserted or not if ($result) { // successfully inserted into database $response["success"] = 1; $response["message"] = "Score record successfully created."; // echoing JSON response echo json_encode($response); } else { // failed to insert row $response["success"] = 0; $response["message"] = "Oops! An error occurred." . mysqli_error($db->conn); // echoing JSON response echo json_encode($response); } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } ?>
Python
UTF-8
420
3.3125
3
[]
no_license
from threading import Thread, Lock lock1 = Lock() lock2 = Lock() l = [] def value1(): for i in range(65, 91): lock1.acquire() print(chr(i)) lock2.release() def value2(): for i in range(1, 53, 2): lock2.acquire() print(i) print(i+1) lock1.release() t1 = Thread(target=value1) t2 = Thread(target=value2) lock1.acquire() t1.start() t2.start() print(l)
Java
UTF-8
209
1.851563
2
[]
no_license
package com.example.demo.spi; /** * Created by evan.qi on 2017/7/12. * * */ public class FileSearch implements Search{ @Override public void search() { System.out.println("this is file search"); } }
Swift
UTF-8
1,270
2.65625
3
[]
no_license
// // GetLoginInfo.swift // myStepiPhone // // Created by 保立馨 on 2016/11/06. // Copyright © 2016年 Kaoru Hotate. All rights reserved. // import Alamofire import RxAlamofire import RxSwift import SwiftyJSON class GetLoginInfo { let loginVM = LoginViewModel() enum APIError: ErrorType { case CannotParse } func getUserInfo(username: String, password: String) -> Observable<UserResp> { loginVM.requestState.next(.Requesting) let req = UserReq(userName: username, password: password) return request(.POST, req.urlString, parameters: req.parameters, encoding: .URLEncodedInURL) .rx_JSON() .map(JSON.init) .flatMap { json -> Observable<UserResp> in guard let user = UserResp(json: json) else { return Observable.error(APIError.CannotParse) } return Observable.just(user) } /* Alamofire.request(.POST, req.urlString, parameters: req.parameters).responseJSON { response in switch response.result { case .Success: if let value = response.result.value { self.resp = UserResp(json:JSON(value)) self.requestState.next(.Finish) self.err = self.resp!.err! } case .Failure(let error): print(error) self.requestState.next(.Error) self.err = "Connection Error" } } */ } }
JavaScript
UTF-8
1,730
2.53125
3
[]
no_license
import React, { Component } from 'react' export default class reviewInput extends Component { constructor(props) { super() this.state = { review: { title: '', content: '', }, action: "" } } handleChange = event => { const { name, value } = event.target this.setState({ review: { ...this.state.review, [name]: value } }) } onChange = (e) => { e.preventDefault() this.props.setReview(this.state.action, this.props.id, this.state.review) } componentDidMount = () => { if (this.props.id === '') { this.setState({ action: 'create' }) } else { this.setState({ action: 'update', review: { title: this.props.review.title, content: this.props.review.content, } }) } } // setKey = key => this.setState({ week: { ...this.state.week, [key]: true } }); render() { const {title, content} = this.state.review return ( <div > <form className='auth-form' onSubmit={this.onChange}> <h3> { (this.state.action ==='create')? "New Review" : "Edit Review"}</h3> <label htmlFor="name">Title</label> <input required name="title" value={title} type="text" placeholder="title" onChange={this.handleChange} /> <label htmlFor="name">Details</label> <textarea required name="content" value={content} type="text" placeholder="review Details" onChange={this.handleChange} /> <button type="submit">{ (this.state.action ==='create')? "Create" : "Update"}</button> </form> </div> ) } }
C++
UTF-8
1,849
3.671875
4
[]
no_license
// { Driver Code Starts #include <iostream> using namespace std; // } Driver Code Ends class Solution { public: // Function to find equilibrium point in the array. // a: input array // n: size of array int equilibriumPoint(long long a[], int n) { if(n == 1) { return 1; } int mid = n / 2 - 1; int midlast = mid; int endarr, begarr, sumbeg, sumend, maxit, c; endarr = n - 1; begarr = 0; while ((mid < endarr) && (mid > begarr)) { sumbeg = 0; sumend = 0; c = 0; maxit = max(mid, endarr - mid); while (c < maxit) { ++c; if (begarr < mid) { sumbeg += *(a + begarr); ++begarr; } if (endarr > mid) { sumend += *(a + endarr); --endarr; } } // cout << "mid " << mid << " sumbeg " << sumbeg << " sumend " << sumend << endl; if (sumend < sumbeg) { if (mid - 1 == midlast) { break; } midlast = mid; --mid; } else if (sumend > sumbeg) { if (mid + 1 == midlast) { break; } midlast = mid; ++mid; } else { return mid + 1; } endarr = n - 1; begarr = 0; } return -1; } }; int main() { Solution s; int n = 2; long long arr[] = {1,3}; cout << s.equilibriumPoint(arr, n) << endl; }
Python
UTF-8
10,660
2.875
3
[]
no_license
#!/usr/bin/python3 import sys import math import string import glob import numpy as np import scipy as sp from scipy import optimize from scipy.linalg import expm, logm import os.path from os import walk from collections import defaultdict import scipy.integrate as integrate from pandas import * import pandas as pd import os import time from scipy import linalg from random import * from custom_constants import * def writeLineAndDB(db, line, output): #simple function to write out the line of the potential and the detailed balance. #Arguments:# #db - 1Darray which contains values of detailed balance #line - coefficient values which correspond to increasing values of x^n #output - filename for output file #Returns:# #none #TODO: make writing the line into a for loop for variable order polynomials. file = open(output, "a") file.write("#Detailed balance followed by equation of the line\n") for i in db: file.write(str(i)+"\n") z=line file.write("\n") file.write("y=%.6fx^8 + %.6fx^7 + %.6fx^6 + %.6fx^5 + %.6fx^4 + %.6fx^3 + %.6fx^2 + %.6fx + %.6f"%(z[0],z[1],z[2],z[3],z[4],z[5],z[6], z[7], z[8])) file.close() def detailedBalance(mat, ij=True):#input is ETM or EPM #Calculate detailedBalance for Transition Matrix or Generator Matrix. #This is a J->I convention, i.e. P_i,j is the transitions from J to I #arguments:# #mat - input matrix #ij - specifies the matrix represents i->j transitions, false is j->i convention. #Returns:# #FE - 1Darray of free energies as determined through detailed balance. #TODO: Add input arguments for kBT FE = np.zeros(mat.shape[0]) for i in range(mat.shape[0]-1): if(mat[i+1,i]==0 or mat[i,i+1]==0): FE[i] = 0 else: if ij: FE[i] = FE[i-1] - kBT * np.log(mat[i,i+1]/mat[i+1,i]) else: FE[i] = FE[i-1] - kbT * np.log(mat[i+1,i]/mat[i,i+1]) FE = FE + FE.min() return FE #frobenius is a measure of distance between two matrices #this function takes two square matrices (q1, q2) and finds their frobenius distance #find the distance between the two matrices def frobenius(q1, q2): #Arguments:# #q1/2 - input matrices to calculate distance n = q1.shape[0] dist = 0.0 for i in range(n): for j in range(n): dist += (abs(q1[i,j]) - abs(q2[i,j]))**2 return np.sqrt(dist) #Iteratively take the log of a matrix. This is a function which always produces real numbers def isRealLog(matrix, epsilon=eps, maxIterations=maxIters): #Arguments:# #matrix - take the log of this matrix #epsilon - convergenace criterion #maxIterations - maximum iterations until we just say it has converged arbitrarily matrix = normalizeMatrix(matrix) iterations = 1 #print("taking log") ret = np.zeros((matrix.shape)) previousIteration = np.copy(matrix) i=1 ret = ret + float(i)/float(iterations) * (matrix - np.identity(len(matrix[0])))**iterations distance = frobenius(previousIteration, ret) #print(distance) while(distance>epsilon): iterations+=1 i=i*-1 ret = ret + float(i)/float(iterations) * (matrix - np.identity(len(matrix[0])))**iterations distance = frobenius(ret, previousIteration) previousIteration = np.copy(ret) #print(distance) if iterations == maxIterations+1: distance = 0 #print("Log Iterations: %s" %iterations) return ret #iteratively take the exponential of a matrix as per the expansion above. def iterative_expm(matrix, epsilon=eps, maxIterations=maxIters): #see isRealLog #do not normalize first previousIteration = np.copy(matrix) iters=1 ret = np.identity(len(matrix[0])) distance = epsilon + 1 while(distance > epsilon): ret += (matrix**iters)/float(math.factorial(iters)) distance = frobenius(ret, previousIteration) previousIteration = np.copy(ret) if iters == maxIterations: distance = 0 iters += 1 return ret def calcLL(Nij, Rij, t=1):#input is empirical transition matrix #Calculate Log Likelihood #Nij - Empirical Transition Matrix #Rij - Rate Matrix to compare #t - tau/dt (i.e. window size as reported in paper) #Returns:# #Log Likelihood n = Nij.shape[0] logl = 0 tiny = np.zeros((n,n)) tiny.fill(1.e-16) #r = np.maximum(iterative_expm(t*Rij), tiny) r = np.maximum(expm(t*Rij), tiny) for i in range(n): for j in range(n): #if r[i,j]*Nij[i,j]>0: logl+=Nij[i,j]*np.log(r[i,j]) return logl def guessP(N): n = N.shape[0] # initial guess for P P=np.zeros((n)) TotalP=1.0 N = normalizeMatrix(N+0.00000000000001) for i in range(n): if i==0: P[i]=1.0 else: P[i]=N[i-1,i]*P[i-1]/N[i,i-1] #print(i, P[i], "=", N[i,i-1],"/",N[i-1,i],"*",P[i-1]) TotalP+=P[i] for i in range(n): P[i]/=TotalP P = P / P.sum() for i in P: print(i) return P def guessR(N, P): # initial guess for R n = N.shape[0] R=np.zeros((n,n)) for i in range(n): for j in range(n): if i==j+1 or j==i+1: R[i,j]=P[j]*(N[i,j]+N[j,i])/(N[i,i]*P[j]+N[j,j]*P[i]) else: R[i,j]=0 #set diagonals to negative of sum of rest of ####row - Column. for l in range(n): R[l,l]-=R[l].sum() print("R") for i in detailedBalance(R): print(i) return R #Simply read a square matrix, return said matrix as a 2d numpy array def readMatrix(fileName): i=0 file = open(fileName) for line in file: if "," not in line: array = line.split() else: array = line.split(", ") if(i==0): matrix = np.zeros((len(array),len(array))) matrix[i] = array i+=1 if(matrix.shape[0]!=matrix.shape[1]): print("Error: Your Matrix is not square, Exiting!") quit() file.close() return matrix #Simply take a NxN numpy array and write it to a file. def writeMatrix(matrix, fileName): file = open(fileName, "w") for i in range(matrix.shape[0]): for j in range(matrix.shape[0]): file.write("%f\t"%matrix[i,j]) file.write("\n") file.close() #Function to Normalize a square Matrix. #k=0 is row normalization, k=1 is column normalization. #Row Normalization corresponds to i->j #Column Normalization corresponds to j->i def normalizeMatrix(matrix, k=0): normalizedMatrix = np.copy(matrix).astype(float) if (k==0): #by row for i in range(normalizedMatrix.shape[0]): normalizedMatrix[i] = normalizedMatrix[i]/normalizedMatrix[i].sum() return normalizedMatrix else: #by column for i in range(normalizedMatrix.shape[0]): normalizedMatrix[:,i] = normalizedMatrix[:,i]/normalizedMatrix[:,i].sum() return normalizedMatrix def compressMatrix_by2(m): bins = m.shape[0] compressedMatrix = np.zeros((int(bins/2),int(bins/2))) for i in range(0,bins,2): for j in range(0,bins,2): compressedMatrix[int(i/2),int(j/2)] = m[i,j] + m[i+1,j] + m[i,j+1] + m[i+1,j+1] return compressedMatrix #This is a helper function to convert a np Matrix to a pandas data frame def npMatrixToPDdf(matrix): indexList = [] columnsList = [] for i in range(matrix.shape[0]): indexList.append(i) for i in range(matrix.shape[1]): columnsList.append(i) return pd.DataFrame(data=matrix, index=indexList, columns=columnsList) #Calculate D as in Hummer,2005. Both possible methods are included, the 2nd is commented. def calcD(generatormatrix,potentialFunction=0, bins=47, width=4):#,binWidth=0.08695652174): #4/46 D = np.ones(generatormatrix.shape[0]-1) binWidth=width/bins generatormatrix+=1/bins for i in range(len(D)): D[i] = binWidth**2 * np.sqrt(generatormatrix[i+1,i]) * np.sqrt(generatormatrix[i,i+1]) #D[i] = binWidth**2 * generatormatrix[i+1,i] * np.exp(-1 * beta *(potentialFunction((i+1)*binWidth-2)-potentialFunction((i+1)*binWidth-2))) return D #discrete version def MFPT_from_Generator(filename, tau, first=12, second=34, delta=1, bins=47, width=4, createTables=False): a = readMatrix(filename)#read Generator c = detailedBalance((a)) #z = np.polyfit(np.arange(len(c))/len(c)*4-2, c-c.min(), 8) potentialFunction = c #potentialFunction = np.poly1d(z) #wellErr = abs(potentialFunction(-1)-potentialFunction(1)) #34/35, 11/12 D = calcD(a/tau, potentialFunction, bins=bins, width=width)#+1e-6#calculate position dependent diffusion constants dAvg = np.average(D[12:34]) #pylab.plot(np.arange(len(c)),potentialFunction(np.arange(len(c))),"r--") #print(D) def outerSum(lower=first, upper=second, delta=delta, D=D): value = 0 i = lower j=1 while(i<=upper): value += p(i) * innerSum(0, i) /D[j]* (width/bins) j+=1 i+=delta return value def p(x, beta=beta): return np.exp(beta * potentialFunction[x]) def n(x, beta=beta): return np.exp(-1*beta*potentialFunction[x]) def innerSum(lower=first, upper=second, delta=delta): value = 0 i = lower while(i<=upper): value += n(i) * delta * (width/bins) i+=delta return value if createTables==True: err = calcdGError(c) wellErr= abs((c[34]+c[35])/2 - (c[11] + c[12]) / 2) return outerSum(), dAvg, err, wellErr return outerSum(), dAvg #calculate the \Delta G as per the height of the barrier vs the average of the two wells. #Expected values for the project are the defaults. def calcdG(detailedBal, maxRange=[14,29], min1Range=[4,21], min2Range=[21,40], totalRange=[5,41]): #input is a detailed Balance, returns dG detailedBal += 0-(detailedBal[totalRange[0]:totalRange[1]].min()) MAX = max(detailedBal[maxRange[0]:maxRange[1]]) MIN1 = min(detailedBal[min1Range[0]:min1Range[1]]) MIN2 = min(detailedBal[min2Range[0]:min2Range[1]]) return MAX - (MIN1+MIN2)/2 def calcDMinima(detailedBal, min1Range=[4,21], min2Range=[21,40]): #input is a detailed Balance, returns dG of two minima MIN1 = min(detailedBal[min1Range[0]:min1Range[1]]) MIN2 = min(detailedBal[min2Range[0]:min2Range[1]]) return abs(MIN1-MIN2) #input is a detailed Balance and the expected dG, returns dG def calcdGError(detailedBal, expected=2.5): dG = calcdG(detailedBal) return abs(expected - dG) / expected * 100
Shell
UTF-8
3,303
3.0625
3
[ "BSD-3-Clause" ]
permissive
# ------------------ # wxWidgets 2.9 # ------------------ # $Id: wxmac28.sh 1902 2007-02-04 22:27:47Z ippei $ # Copyright (c) 2007-2008, Ippei Ukai # 2009-12-04.0 Remove unneeded arguments to make and make install; made make single threaded # prepare source ../scripts/functions.sh check_SetEnv # ------------------------------- # 20091206.0 sg Script tested and used to build 2009.4.0-RC3 # Works Intel: 10.5, 10.6 & Powerpc 10.4, 10.5 # 20100624.0 hvdw More robust error checking on compilation # ------------------------------- fail() { echo "** Failed at $1 **" exit 1 } # init check_numarchs ENABLE_DEBUG="" if [ $# -eq 1 -a "$1" = "--enable-debug" ]; then ENABLE_DEBUG="--enable-debug --enable-debug_gdb" fi # only for 2.9.3 wx_version="$(basename $(pwd))" if [ "$wx_version" = "wxWidgets-2.9.3" ]; then patch -Np1 < ../scripts/patches/wx-2.9.3-xh_toolb.diff patch -Np1 < ../scripts/patches/wxwidgets-2.9.3-clang.patch fi mkdir -p "$REPOSITORYDIR/bin"; mkdir -p "$REPOSITORYDIR/lib"; mkdir -p "$REPOSITORYDIR/include"; # compile ARCH=$ARCHS mkdir -p "build-$ARCH" cd "build-$ARCH" # wxWidgets needs to be compiled against the 10.6 SDK TARGET=$x64TARGET MACSDKDIR=$MACSDKDIR106 ARCHARGs="$x64ONLYARG" OSVERSION="$x64OSVERSION" CC=$x64CC CXX=$x64CXX ARCHARGs=$(echo $ARCHARGs | sed 's/-ftree-vectorize//;s/-fopenmp//g') env \ CC=$CC CXX=$CXX \ CFLAGS="-isysroot $MACSDKDIR -arch $ARCH $ARCHARGs $OTHERARGs -O2 -g -dead_strip" \ CXXFLAGS="-isysroot $MACSDKDIR -arch $ARCH $ARCHARGs $OTHERARGs -O2 -g -dead_strip" \ CPPFLAGS="-isysroot $MACSDKDIR -arch $ARCH $ARCHARGs $OTHERARGs -O2 -g -dead_strip -I$REPOSITORYDIR/include" \ OBJCFLAGS="-arch $ARCH" \ OBJCXXFLAGS="-arch $ARCH" \ LDFLAGS="-L$REPOSITORYDIR/lib -arch $ARCH -mmacosx-version-min=$OSVERSION -dead_strip -prebind" \ ../configure --prefix="$REPOSITORYDIR" --disable-dependency-tracking \ --host="$TARGET" --with-macosx-sdk=$MACSDKDIR --with-macosx-version-min=$OSVERSION \ --enable-monolithic --enable-unicode --with-opengl --disable-compat26 --enable-graphics_ctx --with-cocoa \ --with-libiconv-prefix=$REPOSITORYDIR --with-libjpeg --with-libtiff --with-libpng --with-zlib \ --without-sdl --disable-sdltest ${ENABLE_DEBUG} \ --enable-shared --disable-static --enable-aui || fail "configure step for $ARCH"; make --jobs=1 || fail "failed at make step of $ARCH"; make install || fail "make install step of $ARCH"; if [ "$wx_version" = "wxWidgets-2.9.3" ]; then ln -sf libwx_osx_cocoau-2.9.3.0.0.dylib $REPOSITORYDIR/lib/libwx_osx_cocoau-2.9.dylib ln -sf libwx_osx_cocoau_gl-2.9.3.0.0.dylib $REPOSITORYDIR/lib/libwx_osx_cocoau_gl-2.9.dylib elif [ "$wx_version" = "wxWidgets-3.0.0" ]; then ln -sf libwx_osx_cocoau-3.0.0.0.0.dylib $REPOSITORYDIR/lib/libwx_osx_cocoau-3.0.dylib ln -sf libwx_osx_cocoau_gl-3.0.0.0.0.dylib $REPOSITORYDIR/lib/libwx_osx_cocoau_gl-3.0.dylib elif [ "$wx_version" = "wxWidgets-3.0.1" ]; then ln -sf libwx_osx_cocoau-3.0.0.1.0.dylib $REPOSITORYDIR/lib/libwx_osx_cocoau-3.0.dylib ln -sf libwx_osx_cocoau_gl-3.0.0.1.0.dylib $REPOSITORYDIR/lib/libwx_osx_cocoau_gl-3.0.dylib fi # no clean (we want to keep object files for debugging purpose) if [ -z "${ENABLE_DEBUG}" ]; then cd .. rm -rf build-$ARCH fi
SQL
UTF-8
17,204
3.265625
3
[]
no_license
# Host: localhost (Version: 5.6.12) # Date: 2014-11-07 01:08:15 # Generator: MySQL-Front 5.3 (Build 4.136) /*!40101 SET NAMES utf8 */; # # Structure for table "banco" # CREATE TABLE `banco` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NRO_CUENTA` varchar(20) NOT NULL, `TIPO_CUENTA` enum('AHORRO','CORRIENTE') NOT NULL, `NOMBRE_BANCO` varchar(20) NOT NULL, `SALDO` decimal(10,2) NOT NULL, `PERSONA_ID` int(11) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; # # Structure for table "curso" # CREATE TABLE `curso` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NOMBRE` varchar(20) NOT NULL, `CONTENIDO` varchar(100) NOT NULL, `PRERREQUISITOS` varchar(100) DEFAULT NULL, `ESPECIALIDAD` varchar(20) DEFAULT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1; # # Structure for table "edicion_curso" # CREATE TABLE `edicion_curso` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `ID_CURSO` int(11) DEFAULT NULL, `NOMBRE` varchar(20) DEFAULT NULL, `CONTENIDO` varchar(100) DEFAULT NULL, `PRERREQUISITOS` varchar(100) DEFAULT NULL, `ESPECIALIDAD` varchar(20) DEFAULT NULL, `ID_EDICION` int(11) DEFAULT NULL, `NRO_EDICION` int(11) DEFAULT NULL, `FECHA_INICIO` date DEFAULT NULL, `FECHA_FINALIZACION` date DEFAULT NULL, `AULA` varchar(20) DEFAULT NULL, `NRO_ESTUDIANTES` int(11) DEFAULT NULL, `HORARIO_ID` int(11) DEFAULT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=81 DEFAULT CHARSET=latin1; # # Structure for table "estadisticas" # CREATE TABLE `estadisticas` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NOMBRE_CURSO` varchar(45) NOT NULL, `NRO_INSTANCIA` int(11) NOT NULL, `NOM_APE_PROFESOR` varchar(100) NOT NULL, `PAGO_A_PROFESOR` decimal(10,2) NOT NULL DEFAULT '0.00', `FECHA_INICIO` date NOT NULL, `FECHA_FIN` date NOT NULL, `NRO_ESTUDIANTES` int(11) NOT NULL, `TOTAL_POR_MATRICULAS` decimal(10,2) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; # # Structure for table "horario" # CREATE TABLE `horario` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `HORA_INICIO` time NOT NULL, `HORA_FIN` time NOT NULL, `NUM_HORAS` int(11) NOT NULL, `DETALLE` enum('LUNES-VIERNES','SABADO-DOMINGO') NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; # # Structure for table "curso_edicion" # CREATE TABLE `curso_edicion` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NRO_EDICION` int(11) NOT NULL, `FECHA_INICIO` date NOT NULL, `FECHA_FINALIZACION` date NOT NULL, `AULA` varchar(20) NOT NULL, `NRO_ESTUDIANTES` int(11) NOT NULL, `CURSO_ID` int(11) NOT NULL, `HORARIO_ID` int(11) NOT NULL, PRIMARY KEY (`ID`), KEY `fk_curso_edicion_horario1_idx` (`HORARIO_ID`), CONSTRAINT `fk_curso_edicion_horario1` FOREIGN KEY (`HORARIO_ID`) REFERENCES `horario` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1; # # Structure for table "formulario" # CREATE TABLE `formulario` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `CONOCIMIENTOS` int(11) DEFAULT NULL, `PUNTUALIDAD` int(11) DEFAULT NULL, `MAT_DIDACTICO` int(11) DEFAULT NULL, `FORMA_ENSENANZA` int(11) DEFAULT NULL, `ESTUDIANTE_ID` int(11) NOT NULL, `INSTRUCTOR_ID` int(11) NOT NULL, `CURSO_EDICION_ID` int(11) NOT NULL, PRIMARY KEY (`ID`), KEY `FK_RELATIONSHIP_20` (`CURSO_EDICION_ID`), CONSTRAINT `FK_RELATIONSHIP_20` FOREIGN KEY (`CURSO_EDICION_ID`) REFERENCES `curso_edicion` (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; # # Structure for table "faltas_estudiante" # CREATE TABLE `faltas_estudiante` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NRO_FALTAS` int(11) NOT NULL, `TOTAL_DIAS_CURSO` int(11) NOT NULL, `PERSONA_ID` int(11) NOT NULL, `CURSO_EDICION_ID` int(11) NOT NULL, PRIMARY KEY (`ID`), KEY `FK_RELATIONSHIP_14` (`CURSO_EDICION_ID`), CONSTRAINT `FK_RELATIONSHIP_14` FOREIGN KEY (`CURSO_EDICION_ID`) REFERENCES `curso_edicion` (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; # # Structure for table "evaluacion_estudiante" # CREATE TABLE `evaluacion_estudiante` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NOTA` int(11) NOT NULL, `PERSONA_ID` int(11) NOT NULL, `CURSO_EDICION_ID` int(11) NOT NULL, PRIMARY KEY (`ID`), KEY `FK_RELATIONSHIP_13` (`CURSO_EDICION_ID`), CONSTRAINT `FK_RELATIONSHIP_13` FOREIGN KEY (`CURSO_EDICION_ID`) REFERENCES `curso_edicion` (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; # # Structure for table "curso_edicion_has_personas" # CREATE TABLE `curso_edicion_has_personas` ( `PERSONA_ID` int(11) NOT NULL, `CURSO_EDICION_ID` int(11) NOT NULL, PRIMARY KEY (`PERSONA_ID`,`CURSO_EDICION_ID`), KEY `FK_CURSO_HAS_PERSONAS2` (`CURSO_EDICION_ID`), CONSTRAINT `FK_CURSO_HAS_PERSONAS2` FOREIGN KEY (`CURSO_EDICION_ID`) REFERENCES `curso_edicion` (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; # # Structure for table "banco_deposito" # CREATE TABLE `banco_deposito` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NRO_COMPROBANTE` varchar(20) NOT NULL, `VALOR` decimal(10,2) NOT NULL, `BANCO_ID` int(11) NOT NULL, `CURSO_EDICION_ID` int(11) NOT NULL, PRIMARY KEY (`ID`), UNIQUE KEY `NRO_COMPROBANTE_UNIQUE` (`NRO_COMPROBANTE`), KEY `FK_RELATIONSHIP_11` (`BANCO_ID`), KEY `fk_banco_deposito_curso_edicion1_idx` (`CURSO_EDICION_ID`), CONSTRAINT `fk_banco_deposito_curso_edicion1` FOREIGN KEY (`CURSO_EDICION_ID`) REFERENCES `curso_edicion` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `FK_RELATIONSHIP_11` FOREIGN KEY (`BANCO_ID`) REFERENCES `banco` (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; # # Structure for table "centro_recaudacion_depositos" # CREATE TABLE `centro_recaudacion_depositos` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NRO_FACTURA` varchar(20) NOT NULL, `VALOR` decimal(10,2) NOT NULL, `PERSONA_ID` int(11) NOT NULL, `CURSO_EDICION_ID` int(11) NOT NULL, PRIMARY KEY (`ID`), KEY `FK_RELATIONSHIP_10` (`CURSO_EDICION_ID`), CONSTRAINT `FK_RELATIONSHIP_10` FOREIGN KEY (`CURSO_EDICION_ID`) REFERENCES `curso_edicion` (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; # # Structure for table "certificado" # CREATE TABLE `certificado` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `ENTREGADO` enum('SI','NO') NOT NULL, `PERSONA_ID` int(11) NOT NULL, `CURSO_EDICION_ID` int(11) NOT NULL, PRIMARY KEY (`ID`), KEY `FK_RELATIONSHIP_19` (`CURSO_EDICION_ID`), CONSTRAINT `FK_RELATIONSHIP_19` FOREIGN KEY (`CURSO_EDICION_ID`) REFERENCES `curso_edicion` (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; # # Structure for table "material_didactico" # CREATE TABLE `material_didactico` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NOMBRE` varchar(20) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; # # Structure for table "curso_has_mat_didactico" # CREATE TABLE `curso_has_mat_didactico` ( `MAT_DIDACTICO_ID` int(11) NOT NULL, `CURSO_EDICION_ID` int(11) NOT NULL, PRIMARY KEY (`MAT_DIDACTICO_ID`,`CURSO_EDICION_ID`), KEY `fk_curso_has_mat_didactico_curso_edicion1_idx` (`CURSO_EDICION_ID`), CONSTRAINT `FK_CURSO_HAS_MAT_DIDACTICO` FOREIGN KEY (`MAT_DIDACTICO_ID`) REFERENCES `material_didactico` (`ID`), CONSTRAINT `fk_curso_has_mat_didactico_curso_edicion1` FOREIGN KEY (`CURSO_EDICION_ID`) REFERENCES `curso_edicion` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1; # # Structure for table "persona" # CREATE TABLE `persona` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `CEDULA` varchar(20) NOT NULL, `RUC` varchar(20) DEFAULT NULL, `NOMBRES` varchar(20) NOT NULL, `APELLIDOS` varchar(20) NOT NULL, `DIRECCION` varchar(100) NOT NULL, `TELEFONO` varchar(20) NOT NULL, `TITULOS_ACADEMICOS` varchar(70) DEFAULT NULL, `LUGAR_TRABAJO` varchar(20) NOT NULL, `TIPO_PERSONA` int(3) NOT NULL, `NRO_CURSOS_APROBADOS` int(11) DEFAULT NULL, `FOTO` mediumblob, PRIMARY KEY (`ID`,`TIPO_PERSONA`) ) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=latin1; # # Structure for table "persona_frg1" # CREATE TABLE `persona_frg1` ( `ID` int(11) NOT NULL, `FOTO` mediumblob, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; # # Structure for table "persona_frg2" # CREATE TABLE `persona_frg2` ( `ID` int(11) NOT NULL, `CEDULA` varchar(20) NOT NULL, `RUC` varchar(20) DEFAULT NULL, `NOMBRES` varchar(20) NOT NULL, `APELLIDOS` varchar(45) NOT NULL, `DIRECCION` varchar(100) NOT NULL, `TELEFONO` varchar(20) NOT NULL, `TITULOS_ACADEMICOS` varchar(70) DEFAULT NULL, `LUGAR_TRABAJO` varchar(20) NOT NULL, `TIPO_PERSONA` int(3) NOT NULL, `NRO_CURSOS_APROBADOS` int(11) DEFAULT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; # # Procedure "pa_detalles_curso_edicion" # CREATE PROCEDURE `pa_detalles_curso_edicion`(codigoCurso int(11), numEdicion int(11)) BEGIN select concat(concat(ho.hora_inicio,' '), ho.hora_fin) as horario, ce.aula, concat(concat(pe.nombres,' '),pe.apellidos) as instructor from curso_edicion ce inner join curso_edicion_has_personas cep on cep.curso_edicion_id=ce.id inner join horario ho on ce.horario_id=ho.id inner join persona pe on cep.persona_id=pe.id where pe.tipo_persona=3 and ce.curso_id=codigoCurso and ce.nro_edicion=numEdicion; END; # # Procedure "pa_detalles_instructor" # CREATE PROCEDURE `pa_detalles_instructor`(cedulaIns varchar(20)) BEGIN select distinct cu.nombre as nombre_curso, ce.nro_edicion as num_edicion, ce.fecha_inicio, ce.fecha_finalizacion, bd.valor from curso_edicion ce inner join curso cu on cu.id=ce.curso_id inner join banco_deposito bd on ce.id=bd.curso_edicion_id inner join banco ba on bd.banco_id=ba.id inner join persona pe on ba.persona_id=pe.id inner join curso_edicion_has_personas cep on cep.curso_edicion_id=ce.id and cep.persona_id=pe.id where pe.cedula=cedulaIns and pe.tipo_persona=3; END; # # Procedure "PA_INSERT_ESTADISTICAS" # CREATE PROCEDURE `PA_INSERT_ESTADISTICAS`() BEGIN INSERT INTO ESTADISTICAS(NOMBRE_CURSO,NRO_INSTANCIA,NOM_APE_PROFESOR,FECHA_INICIO, FECHA_FIN, NRO_ESTUDIANTES,TOTAL_POR_MATRICULAS) SELECT CU.NOMBRE, CE.NRO_EDICION, CONCAT(PE.NOMBRES, CONCAT(" ",PE.APELLIDOS)) AS NOMBRE_APELLIDO ,CE.FECHA_INICIO,CE.FECHA_FINALIZACION,CE.NRO_ESTUDIANTES,CE.NRO_ESTUDIANTES*40 AS VALOR FROM CURSO_EDICION CE INNER JOIN CURSO CU ON CU.ID=CE.CURSO_ID INNER JOIN CURSO_EDICION_HAS_PERSONAS CEP ON CEP.CURSO_EDICION_ID=CE.ID INNER JOIN PERSONA PE ON CEP.PERSONA_ID=PE.ID WHERE PE.TIPO_PERSONA=3; END; # # Procedure "PA_PAGO_PROFESOR" # CREATE PROCEDURE `PA_PAGO_PROFESOR`() BEGIN UPDATE ESTADISTICAS ES SET ES.PAGO_A_PROFESOR= (SELECT BD.VALOR FROM BANCO_DEPOSITO BD INNER JOIN BANCO BA ON BA.ID=BD.BANCO_ID INNER JOIN PERSONA PE ON PE.ID=BA.PERSONA_ID INNER JOIN CURSO_EDICION CE ON CE.ID=BD.CURSO_EDICION_ID INNER JOIN CURSO CU ON CU.ID=CE.CURSO_ID WHERE CU.NOMBRE=ES.NOMBRE_CURSO AND CE.NRO_EDICION=ES.NRO_INSTANCIA) WHERE ES.PAGO_A_PROFESOR=0; END; # # Trigger "control_fecha_matriculas" # CREATE DEFINER='root'@'localhost' TRIGGER `bdd3-project`.`control_fecha_matriculas` BEFORE INSERT ON `bdd3-project`.`curso_edicion_has_personas` FOR EACH ROW begin declare fecha_fin date; select ce.fecha_finalizacion into fecha_fin from curso_edicion ce where ce.id=new.curso_edicion_id; if fecha_fin<now() then SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Fecha de matricula expirada.!!'; end if; end; # # Trigger "control_num_matriculas" # CREATE DEFINER='root'@'localhost' TRIGGER `bdd3-project`.`control_num_matriculas` AFTER INSERT ON `bdd3-project`.`curso_edicion_has_personas` FOR EACH ROW begin DECLARE num_estudiantes int(11); DECLARE condicion varchar(20); -- select num-estudiantes de la edición del curso select NRO_ESTUDIANTES into num_estudiantes from curso_edicion where id=new.curso_edicion_id; -- select de comprobación del tipo de persona registrada select TIPO_PERSONA into condicion from persona where id=new.persona_id; if condicion=1 then if num_estudiantes < 25 then update curso_edicion set NRO_ESTUDIANTES=NRO_ESTUDIANTES+1 where id=new.CURSO_EDICION_ID; else SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'CUPO LLENO!' ; end if; end if; end; # # Trigger "curso_aprobado" # CREATE DEFINER='root'@'localhost' TRIGGER `bdd3-project`.`curso_aprobado` AFTER INSERT ON `bdd3-project`.`evaluacion_estudiante` FOR EACH ROW begin DECLARE num_faltas int(11); DECLARE total_dias int(11); DECLARE porcentaje_faltas decimal(10,2); if new.nota >= 7 then -- num-faltas -- select fe.nro_faltas into num_faltas from faltas_estudiante fe where fe.persona_id=new.persona_id and fe.curso_edicion_id=new.curso_edicion_id; -- total-dias-curso -- select fe.total_dias_curso into total_dias from faltas_estudiante fe where fe.persona_id=new.persona_id and fe.curso_edicion_id=new.curso_edicion_id; -- porcentaje -- set porcentaje_faltas = num_faltas * 100 / total_dias; -- 2da comparacion porcentaje if porcentaje_faltas < 40 then update persona set nro_cursos_aprobados=nro_cursos_aprobados+1 where id=new.persona_id; end if; end if; end; # # Trigger "curso_delete" # CREATE DEFINER='root'@'localhost' TRIGGER `bdd3-project`.`curso_delete` AFTER DELETE ON `bdd3-project`.`curso` FOR EACH ROW begin DELETE FROM Edicion_curso WHERE ID_CURSO=OLD.ID; end; # # Trigger "curso_update" # CREATE DEFINER='root'@'localhost' TRIGGER `bdd3-project`.`curso_update` AFTER UPDATE ON `bdd3-project`.`curso` FOR EACH ROW begin UPDATE Edicion_curso SET ID_CURSO=NEW.ID, NOMBRE=NEW.NOMBRE, CONTENIDO=NEW.CONTENIDO, PRERREQUISITOS=NEW.PRERREQUISITOS, ESPECIALIDAD=NEW.ESPECIALIDAD WHERE ID_CURSO=OLD.ID; end; # # Trigger "edicion_delete" # CREATE DEFINER='root'@'localhost' TRIGGER `bdd3-project`.`edicion_delete` AFTER DELETE ON `bdd3-project`.`curso_edicion` FOR EACH ROW begin DELETE FROM Edicion_curso WHERE ID_EDICION=OLD.ID; end; # # Trigger "edicion_insert" # CREATE DEFINER='root'@'localhost' TRIGGER `bdd3-project`.`edicion_insert` AFTER INSERT ON `bdd3-project`.`curso_edicion` FOR EACH ROW begin DECLARE SWV_FILA_ID INT; DECLARE SWV_FILA_NOMBRE varchar(20); DECLARE SWV_FILA_CONTENIDO varchar(100); DECLARE SWV_FILA_PRERREQUISITOS varchar(100); DECLARE SWV_FILA_ESPECIALIDAD varchar(20); SELECT ID, NOMBRE, CONTENIDO, PRERREQUISITOS, ESPECIALIDAD INTO SWV_FILA_ID,SWV_FILA_NOMBRE, SWV_FILA_CONTENIDO, SWV_FILA_PRERREQUISITOS, SWV_FILA_ESPECIALIDAD FROM curso WHERE ID=NEW.CURSO_ID; INSERT INTO Edicion_curso VALUES(default,SWV_FILA_ID, SWV_FILA_NOMBRE, SWV_FILA_CONTENIDO, SWV_FILA_PRERREQUISITOS, SWV_FILA_ESPECIALIDAD, new.ID, new.NRO_EDICION, new.FECHA_INICIO, new.FECHA_FINALIZACION, new.AULA, new.NRO_ESTUDIANTES, new.HORARIO_ID); end; # # Trigger "edicion_update" # CREATE DEFINER='root'@'localhost' TRIGGER `bdd3-project`.`edicion_update` AFTER UPDATE ON `bdd3-project`.`curso_edicion` FOR EACH ROW begin UPDATE Edicion_curso SET ID_EDICION = NEW.ID, NRO_EDICION=NEW.NRO_EDICION, FECHA_INICIO=NEW.FECHA_INICIO, FECHA_FINALIZACION=NEW.FECHA_FINALIZACION, AULA=NEW.AULA, NRO_ESTUDIANTES=NEW.NRO_ESTUDIANTES, HORARIO_ID=NEW.HORARIO_ID WHERE ID_EDICION=OLD.ID; end; # # Trigger "persona_fragmentacion_delete" # CREATE DEFINER='root'@'localhost' TRIGGER `bdd3-project`.`persona_fragmentacion_delete` AFTER DELETE ON `bdd3-project`.`persona` FOR EACH ROW begin if(old.TIPO_PERSONA=3) then delete from persona_frg1 where id=old.id; delete from persona_frg2 where id=old.id; end if; end; # # Trigger "persona_fragmentacion_insert" # CREATE DEFINER='root'@'localhost' TRIGGER `bdd3-project`.`persona_fragmentacion_insert` AFTER INSERT ON `bdd3-project`.`persona` FOR EACH ROW begin if(new.TIPO_PERSONA=3) then insert into persona_frg1 values(new.ID, new.FOTO); insert into persona_frg2 values(new.ID, new.CEDULA, new.RUC, new.NOMBRES, new.APELLIDOS, new.DIRECCION, new.TELEFONO, new.TITULOS_ACADEMICOS, new.LUGAR_TRABAJO, new.TIPO_PERSONA, new.NRO_CURSOS_APROBADOS); end if; end; # # Trigger "persona_fragmentacion_update" # CREATE DEFINER='root'@'localhost' TRIGGER `bdd3-project`.`persona_fragmentacion_update` AFTER UPDATE ON `bdd3-project`.`persona` FOR EACH ROW begin if(new.TIPO_PERSONA=3) then if(old.tipo_persona!=3) then insert into persona_frg1 values(new.ID, new.FOTO); insert into persona_frg2 values(new.ID, new.CEDULA, new.RUC, new.NOMBRES, new.APELLIDOS, new.DIRECCION, new.TELEFONO, new.TITULOS_ACADEMICOS, new.LUGAR_TRABAJO, new.TIPO_PERSONA, new.NRO_CURSOS_APROBADOS); else update persona_frg1 set foto=new.foto where id=new.id; update persona_frg2 set cedula=new.cedula, ruc=new.ruc, nombres=new.nombres, apellidos=new.apellidos, direccion=new.direccion, telefono=new.telefono, titulos_academicos=new.titulos_academicos, lugar_trabajo=new.lugar_trabajo, tipo_persona=new.tipo_persona, nro_cursos_aprobados=new.nro_cursos_aprobados where id=new.id; end if; end if; end;
Python
UTF-8
1,082
2.71875
3
[]
no_license
#!/usr/bin/env python import sys import numpy as np def shiftPickles(picklesDat, shift): gr = picklesDat[:,8].astype(float) + shift[0] ri = picklesDat[:,9].astype(float) + shift[1] iz = picklesDat[:,10].astype(float) + shift[2] newPickles = picklesDat.copy() newPickles[:,8] = gr newPickles[:,9] = ri newPickles[:,10] = iz return newPickles if __name__ == "__main__": picklesFileName = sys.argv[1] shift = np.fromstring(sys.argv[2], sep=' ') newPicklesFileName = sys.argv[3] pickles = np.loadtxt(picklesFileName, dtype=str) newPickles = shiftPickles(pickles, shift) newPicklesFile = open(newPicklesFileName, 'w') print('# spec MACHO_B MACHO_R DECam_g DECam_r DECam_i DECam_z MACHO_BR DECam_gr DECam_ri DECam_iz', file=newPicklesFile) nPickles = newPickles.shape[0] nCol = newPickles.shape[1] for i in range(nPickles): for n in range(nCol): print(newPickles[i,n], end=' ', file=newPicklesFile) print(' ', file=newPicklesFile) newPicklesFile.close()
Java
UTF-8
214
1.765625
2
[]
no_license
package com.locker.service.exception; public class NamesException extends Exception { private static final long serialVersionUID = -1287766609237779542L; public NamesException(String msg) { super(msg); } }
Python
UTF-8
7,003
2.734375
3
[]
no_license
# Rebuild the UCI network with low accuracy from __future__ import print_function # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) import tensorflow as tf import numpy as np # Training Parameters #learning_rate = 0.1 batch_size = 100 display_step = 1 model_path = "./MNIST/nn/NN" file_ending = ".ckpt" epoch_num = 40 # Network Parameters n_hidden_1 = 300 # 1st layer number of features n_input = 784 # MNIST data input (img shape: 28*28) n_classes = 10 # MNIST total classes (0-9 digits) # Device Parameters #n_bits = 6 # Device resolution--device state--mapping -1.0~1.0 into these states #f_n_bits = 2.0/(2**n_bits) # Gaussian distribution mu = 0 # Mean sigma = 0.0 # Standard deviation num_of_samples = 1 gaussian_matrix = { 'h1': np.random.normal(mu,sigma,epoch_num*n_input*n_hidden_1).\ reshape(epoch_num,n_input,n_hidden_1), 'out': np.random.normal(mu,sigma,epoch_num*n_hidden_1*n_classes).\ reshape(epoch_num,n_hidden_1,n_classes) } # Stores epoch *[dimension,dimension] for each weight matrix # normal sample with mean and var def new_weight(mean, var): return var * np.random.randn()+mean # parse input distribution data # return distribution, max, min distribution = [] distribution_path = "./distribution.txt" distribution_max, distribution_min = None, None distribution_stage = None def read_distribution(path): rtn = [] with open(path) as f: lines = f.readlines() for line in lines[1:]: tmp = line.split() rtn.append([float(tmp[1]), float(tmp[2])]) return rtn, rtn[-1][0], rtn[0][0] distribution, distribution_max, distribution_min = read_distribution(distribution_path) distribution_stage = len(distribution) # find distribution parameter # conductance -1 to 1 value,distribution array, max, min of conductance, total stages # return mean, stdv def check_distribution(c, chi, clo, d, hi, lo, stage): idx = int((c-clo)*stage/(chi-clo)) if idx >= stage-1: m, var = d[-1][0], d[-1][1] else: m, var = (d[idx][0]+d[idx+1][0])/2.0, (d[idx][1]+d[idx+1][1])/2.0 m = new_weight(m, var) return (m-lo)/(hi-lo)*(chi-clo) + clo #u, var = check_distribution(-0.1, 4.5, -4.5, distribution, distribution_max, distribution_min, distribution_stage) # tf Graph input x = tf.placeholder("float", [None, n_input]) y = tf.placeholder("float", [None, n_classes]) # round operation to convert floating point number to fixed point number #def fround(fnum): # return round((fnum+1.0)/f_n_bits)*f_n_bits - 1.0 # for testing fround purpose #for i in np.linspace(-1, 1, num=73): #print(fround(i)) # Create model def multilayer_perceptron(x, weights): # Hidden layer with RELU activation layer_1 = tf.matmul(x, weights['h1']) #layer_1 = tf.nn.relu(layer_1) # Output layer with linear activation out_layer = tf.matmul(layer_1, weights['out']) return out_layer # Store layers weight & bias weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'out': tf.Variable(tf.random_normal([n_hidden_1, n_classes])) } # Construct model pred = multilayer_perceptron(x, weights) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) #optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost) # Initialize the variables (i.e. assign their default value) # init = tf.global_variables_initializer() # 'Saver' op to save and restore all the variables saver = tf.train.Saver(max_to_keep=100) # Running a new session print("Starting 2nd session...") with tf.Session() as sess: # Initialize variables # sess.run(init) tf.initialize_all_variables().run() real_accu = [] ideal_accu = [] for epoch in range(epoch_num): save_path = model_path + str(epoch+1) + file_ending # Restore model weights from previously saved model saver.restore(sess, save_path) print("Model restored from file: %s" % save_path) #print("valofw:", weights['h1'].eval()) #nw = { # 'h1': weights['h1'].eval(), # 'out': weights['out'].eval()} #print(nw) #nw['h1'] = np.zeros((784,300)) #weights['h1'].assign(nw['h1']).eval() #print("afterchange:",weights['h1'].eval()) #print(sess.run(weights)) #print(weights['h1']) #print(weights['h1'].get_shape(),weights['out'].get_shape()) # Ideal accuracy test # Test model correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print("Ideal Accuracy:", accuracy.eval( {x: mnist.test.images, y: mnist.test.labels})) ideal_accu.append(accuracy.eval({x: mnist.test.images, y: mnist.test.labels})) # update weight values newh1 = weights['h1'].eval() newout = weights['out'].eval() saveh1 = np.copy(newh1) # deep copy saveout = np.copy(newout) #newh1 += gaussian_matrix['h1'][epoch] #newout += gaussian_matrix['out'][epoch] #print(newh1) print("weight layer 1 max-min:",newh1.max(),newh1.min()) print("weight layer 2 max-min:",newout.max(),newout.min()) sample_accu = [] # loop for # of normal distribution samples for sample in range(num_of_samples): for i in range(0,n_input): for j in range(0,n_hidden_1): tmp = saveh1[i][j] tmp = check_distribution(tmp, 4.7, -4.7, distribution, distribution_max, distribution_min, distribution_stage) newh1[i][j] = tmp #print("after-----",newh1) for i in range(0,n_hidden_1): for j in range(0,n_classes): tmp = saveout[i][j] tmp = check_distribution(tmp, 4.7, -4.7, distribution, distribution_max, distribution_min, distribution_stage) newout[i][j] = tmp weights['h1'].assign(newh1).eval() weights['out'].assign(newout).eval() # Real accuracy test # Test model correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) #print("Accuracy:", accuracy.eval( #{x: mnist.test.images, y: mnist.test.labels})) sample_accu.append(accuracy.eval({x: mnist.test.images, y: mnist.test.labels})) print("Real sample_accu: ",sample_accu) real_accu.append(sum(sample_accu)/(len(sample_accu))) print("Final ideal accuracies:", ideal_accu) print("Final real accuracies:", real_accu)
Python
UTF-8
1,204
2.8125
3
[]
no_license
# -*- coding: utf-8 -*- from pyvirtualdisplay import Display from selenium import webdriver import time output = open('top_twitch_sully_7dollowup.tsv', 'w+') #textResults = [] with Display(): driver = webdriver.Firefox() driver.get('https://sullygnome.com/channels/watched') time.sleep(15) for i in range(10): results = driver.find_elements_by_xpath('//*[@id="tblControl"]/tbody/tr') if len(results) == 0: time.sleep(15) results = driver.find_elements_by_xpath('//*[@id="tblControl"]/tbody/tr') for result in results: #textResults.append([cell.text for cell in result.find_elements_by_tag_name('td')]) try: output.write('\t'.join([cell.text.encode('utf-8') for cell in result.find_elements_by_tag_name('td')]) + '\n') #print('\t'.join([cell.text.encode('utf-8') for cell in result.find_elements_by_tag_name('td')]) + '\n') except Exception as e: print(e) button = driver.find_elements_by_xpath('//*[@id="tblControl_next"]')[0] button.click() # go to next page time.sleep(5) print("On Page " + str(i)) driver.quit()
Swift
UTF-8
2,050
3.65625
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit var str = "Hello, Ordered Set" public struct OrderedSet<T: Hashable> { private var internalSet = [T]() private var indexOfKey: [T: Int] = [:] public init() {} public var count: Int { return internalSet.count } public mutating func add(_ object: T) { guard indexOfKey[object] == nil else { return } // if not exist, append to the last internalSet.append(object) indexOfKey[object] = internalSet.count - 1 } public mutating func insert(_ object: T, at index: Int) { assert(index < internalSet.count, "Index out of range.") assert(index >= 0, "Index should greater than 0") guard indexOfKey[object] == nil else { return } internalSet.insert(object, at: index) indexOfKey[object] = index for i in (index + 1)..<internalSet.count { indexOfKey[internalSet[i]] = i } } public func object(at index: Int) -> T { assert(index < internalSet.count, "Index out of range.") assert(index >= 0, "Index should greater than 0") return internalSet[index] } public mutating func set(_ object: T, at index: Int) { assert(index < internalSet.count, "Index out of range.") assert(index >= 0, "Index should greater than 0") guard indexOfKey[object] == nil else { return } indexOfKey.removeValue(forKey: internalSet[index]) indexOfKey[object] = index internalSet[index] = object } public mutating func remove(_ object: T) { guard let index = indexOfKey[object] else { return } internalSet.remove(at: index) indexOfKey.removeValue(forKey: object) for i in (index + 1)..<internalSet.count { indexOfKey[internalSet[i]] = i } } }
Python
UTF-8
4,533
2.65625
3
[ "Apache-2.0" ]
permissive
"""Internal utility functions.""" from matplotlib.colors import BoundaryNorm, Normalize from matplotlib.pyplot import gca import numpy as np import matplotlib.cm as cm import matplotlib.collections as collections from .settings import color_missing, im_settings, point_settings from . import mapping def get_extend(norm): if isinstance(norm, BoundaryNorm): # Norm used for a discrete mapping. return "neither" # Determine `extend` argument to `figure.colorbar` that # corresponds to the norm. if norm.vmin is not None and norm.vmax is not None: return "both" elif norm.vmin is not None and norm.vmax is None: return "min" elif norm.vmin is None and norm.vmax is not None: return "max" return "neither" def mask(data): # TODO: pass through if already masked? return np.ma.MaskedArray(data, np.isnan(data) | ~np.isfinite(data)) class DataContainer(object): """Hold the internal representation of the data.""" def __init__(self, data, colormap, norm, ticklabels): self.data = data self.colormap = colormap self.colormap.set_bad(color_missing) self.norm = norm self.ticklabels = ticklabels @classmethod def from_discrete(cls, data, palette): data = np.asanyarray(data) pairs, mock = mapping.create_mapped(data) ticklabels, internal_data = zip(*pairs.items()) norm = mapping.discrete_norm(internal_data) colormap = mapping.discrete_cmap(internal_data, palette) return cls(mock, colormap, norm, ticklabels) @classmethod def from_continuous(cls, data, palette, *, lower=None, upper=None): data = np.asanyarray(data) if not isinstance(data, np.ma.MaskedArray): data = mask(data) norm = Normalize(lower, upper) colormap = cm.get_cmap(palette) return cls(data, colormap, norm, None) class AxesUpdater(object): """Draw on the axes.""" def __init__(self, container, ax, plot_kwds): if ax is None: ax = gca() self.container = container self.ax = ax self.plot_kwds = plot_kwds @classmethod def from_discrete(cls, container, ax=None, **kwds): plot_kwds = { **kwds, "cmap": container.colormap, "norm": container.norm, } return cls(container, ax, plot_kwds) @classmethod def from_continuous(cls, container, ax=None, **kwds): # Some plotting methods (e.g. scatter) will modify # `norm` in-place if either `vmin` or `vmax` are # None. To avoid this, the `vmin` and `vmax` values # are passed to normalize the data, instead of using # `norm`. plot_kwds = { **kwds, "cmap": container.colormap, "vmin": container.norm.vmin, "vmax": container.norm.vmax, } return cls(container, ax, plot_kwds) def add_points(self, xy): kwds = {**point_settings, **self.plot_kwds} # `scatter will filter out any masked values. To ensure # that they're plotted, pass the color mapping information # directly to the collection after calling `scatter` and the # colors will be updated when rendering the figure. collection = self.ax.scatter(*xy.T, c=None, **kwds) collection.set_array(self.container.data) collection.set_cmap(self.container.colormap) collection.set_norm(self.container.norm) return collection def add_polygons(self, verts): # PolyCollection does not allow `vmin`/`vmax`, # and `norm` is already passed. kwds = { k: v for k, v in self.plot_kwds.items() if k not in ("vmin", "vmax", "norm") } p = collections.PolyCollection( verts, array=self.container.data, norm=self.container.norm, **kwds) self.ax.add_collection(p) self.ax.autoscale_view() return p def add_raster(self): kwds = {**im_settings, **self.plot_kwds} return self.ax.imshow(self.container.data, **kwds) def add_colorbar(self, collection): ax = self.ax extend = get_extend(self.container.norm) colorbar = ax.figure.colorbar(collection, ax=ax, extend=extend) ticklabels = self.container.ticklabels if ticklabels is not None: mapping.add_discrete_labels(colorbar, labels=ticklabels) return
Python
UTF-8
5,972
2.546875
3
[ "MIT" ]
permissive
'''Random value-generating utilities. Intended mainly for generating random values for testing purposes (i.e. finding edge cases). ''' import sys from random import randint, random, choice from six import PY2, PY3 if PY3: xrange = range #------------------------------------------------------------------------------- MAX_INT = sys.maxsize MIN_INT = -MAX_INT - 1 MIN_CHR = 0x00 MAX_CHR = 0xff MIN_UNICHR = 0x00 MAX_UNICHR = sys.maxunicode MIN_STRLEN = 0 MAX_STRLEN = 10 MAX_FLOAT = sys.float_info.max MIN_FLOAT = -MAX_FLOAT MIN_SEQLEN = 0 MAX_SEQLEN = 5 MAX_DEPTH = 1 PRIMITIVE_TYPES = [bool, int, float, complex, str, type(None)] if PY2: PRIMITIVE_TYPES += [long, unicode] if PY3: PRIMITIVE_TYPES += [bytes] HASHABLE_TYPES = PRIMITIVE_TYPES + [tuple, frozenset] SEQ_TYPES = PRIMITIVE_TYPES + [list, tuple, dict, set, frozenset] inf = float('inf') #------------------------------------------------------------------------------- # Numeric def rand_bool(thresh=0.5, **kwargs): if random() > thresh: return True return False def rand_int(min_val = MIN_INT, max_val = MAX_INT, **kwargs): return randint(min_val, max_val) def rand_long(min_len=None, max_len=None, **kwargs): if min_len is None: min_len = len(str(MAX_INT)) + 2 if max_len is None: max_len = min_len + 40 s = rand_str(min_char = ord('0'), max_char = ord('9'), min_len = min_len, max_len = max_len) ret = long(s) if rand_bool(): ret = -ret return ret def rand_float(lb = None, ub = None, **kwargs): if lb is not None and ub is not None: return (ub - lb) * random() + lb elif ub is not None: m = ub else: m = MAX_FLOAT sign = 1 if rand_bool() else -1 return sign * m * random() def rand_complex(imag_only=False, **kwargs): real = 0 if not imag_only: real = rand_float() imag = rand_float() return complex(real, imag) #------------------------------------------------------------------------------- # String def rand_str(min_char=MIN_CHR, max_char=MAX_CHR, min_len=MIN_STRLEN, max_len=MAX_STRLEN, func=chr, **kwargs): '''For values in the (extended) ASCII range, regardless of Python version. ''' l = randint(min_len, max_len) ret = '' for k in xrange(l): ret += func(randint(min_char, max_char)) return ret def rand_unicode(min_char=MIN_UNICHR, max_char=MAX_UNICHR, min_len=MIN_STRLEN, max_len=MAX_STRLEN, **kwargs): '''For values in the unicode range, regardless of Python version. ''' from syn.five import unichr return unicode(rand_str(min_char, max_char, min_len, max_len, unichr)) def rand_bytes(**kwargs): kwargs['types'] = [int] kwargs['min_val'] = 0 kwargs['max_val'] = 255 values = rand_list(**kwargs) return bytes(values) #------------------------------------------------------------------------------- # Sequence def rand_list(**kwargs): min_len = kwargs.get('min_len', MIN_SEQLEN) max_len = kwargs.get('max_len', MAX_SEQLEN) types = kwargs.get('types', SEQ_TYPES) depth = kwargs.get('depth', 0) max_depth = kwargs.get('max_depth', MAX_DEPTH) if depth >= max_depth: types = [t for t in types if t in PRIMITIVE_TYPES] ret = [] kwargs['depth'] = depth + 1 N = randint(min_len, max_len) for k in xrange(N): typ = choice(types) ret.append(rand_dispatch(typ, **kwargs)) return ret def rand_tuple(**kwargs): return tuple(rand_list(**kwargs)) #------------------------------------------------------------------------------- # Mapping def rand_dict(**kwargs): key_types = kwargs.get('key_types', HASHABLE_TYPES) key_kwargs = dict(kwargs) key_kwargs['types'] = key_types keys = rand_list(**key_kwargs) values = rand_list(**kwargs) N = min(len(keys), len(values)) return dict(zip(keys[:N], values[:N])) #------------------------------------------------------------------------------- # Set def rand_set(**kwargs): kwargs['types'] = kwargs.get('types', HASHABLE_TYPES) return set(rand_list(**kwargs)) def rand_frozenset(**kwargs): return frozenset(rand_set(**kwargs)) #------------------------------------------------------------------------------- # Misc. def rand_none(**kwargs): return None #------------------------------------------------------------------------------- # Dispatch GENERATORS = {bool: rand_bool, int: rand_int, float: rand_float, complex: rand_complex, str: rand_str, list: rand_list, tuple: rand_tuple, dict: rand_dict, set: rand_set, frozenset: rand_frozenset, type(None): rand_none} if PY2: GENERATORS[long] = rand_long GENERATORS[unicode] = rand_unicode if PY3: GENERATORS[bytes] = rand_bytes def rand_dispatch(typ, **kwargs): from .py import hasmethod if typ in GENERATORS: return GENERATORS[typ](**kwargs) elif hasmethod(typ, '_generate'): return typ._generate(**kwargs) raise TypeError('Cannot dispatch random generator for type: {}'. format(typ)) def rand_primitive(**kwargs): return rand_dispatch(choice(PRIMITIVE_TYPES), **kwargs) def rand_hashable(**kwargs): kwargs['types'] = HASHABLE_TYPES return rand_dispatch(choice(HASHABLE_TYPES), **kwargs) #------------------------------------------------------------------------------- # __all__ __all__ = ('rand_bool', 'rand_int', 'rand_float', 'rand_complex', 'rand_long', 'rand_str', 'rand_unicode', 'rand_bytes', 'rand_list', 'rand_tuple', 'rand_dict', 'rand_set', 'rand_frozenset', 'rand_none', 'rand_dispatch', 'rand_primitive', 'rand_hashable') #-------------------------------------------------------------------------------
C#
UTF-8
272
3.03125
3
[]
no_license
int CalculatePrice(int id) { int price = Items.Where(item => item.Id_Parent == id).Sum(child => CalculatePrice(child.Id)); return price + Items.First(item => item.Id == id).Price; } int total = CalculatePrice(3); // 3 is just an example id
Markdown
UTF-8
14,270
2.546875
3
[]
no_license
# [原创内容] 详细解释为什么Matlab被禁对大学论文发表没有任何实质性影响 > tid: `22134888` 用户ID: `1869831` 发布时间: `2020-06-11 14:42:00` > 联动这两个帖子,我要解释一下为什么Matlab被禁对大学没有实质性影响。因为那俩帖子里外行一本正经的胡说八道危言耸听的实在是太多了。<br/><b>不要自己吓自己,放心大胆该怎么用Matlab就还怎么用</b>。当然,Mathwork这个禁售政策sb没得洗。<br/><br/>[url]https://nga.178.com/read.php?tid=22128769[/url]<br/>[url]https://nga.178.com/read.php?tid=22123587[/url]<br/><br/>首先声明我的身份:高校教师,近些年发表若干SCI论文,担任若干国际会议AE,担任若干SCI期刊审稿人。第一个附件,如果你在Transactions on Automatic Control投过论文,就能知道图片里是什么意思。第二个附件是CASE会议Associate Editor的操作界面,如果你这几年在CASE、SMC Conference投过稿,那有可能会到我手里。第三个附件是TAC发给我的Outstanding Reviewer的证明信。摆出以上证据的意思是我是业内人士,不是一个连论文审稿发表流程都没搞清楚的外行在瞎BB。<br/><br/>言归正传。<span class="red">在Matlab被禁用的情况下,一个哈工大的学生,用Matlab跑了仿真,在论文里堂而皇之的写上了我的单位是HEU/HIT,没有其他单位,我的仿真数据是来自Matlab计算得到的结果,会有什么后果。答案是,没有任何后果。原因如下</span><br/><br/>1、这篇论文投稿之后分配Associate Editor,AE没兴趣关心这个Matlab到底是有没有授权,而关心的是这篇论文能不能赶紧找到合适的审稿人,以及这些审稿人能不能按时给我把评审意见发回来。除了熟人稿子AE可能故意找几个熟人审帮忙潜规则放放水,正常情况下AE在找审稿人是在数据库里通过关键词匹配来选的。一个期刊AE手头同时会有大约10篇在审论文的工作量,每结案一篇之后又会收到新的一篇。AE每天惦记着就是怎么赶紧把这些论文处理掉,否则主编要催了,谁有空仔细看一篇论文里的某个仿真数据是哪做的。<br/><br/>2、AE把论文发给审稿人。审稿人也没兴趣关心这个Matlab到底是有没有授权。他想着我怎么赶快把论文扫一眼看明白之后看看有没有问题,写个意见赶紧在截止时间前发回去,要不然AE该催了。注意一下,审稿是没有报酬的。所以一篇稿子写评审意见愿意上花两三个小时的审稿人已经算是良心的审稿人了。你指望再花几个小时搞清楚这个学生到底Matlab用得是正版还是盗版?Mathwork给他发工资么?<br/><br/>3、审稿人把审稿意见返回给AE之后,AE综合审稿人的意见之后做决策。如果AE决定接收,主编会在系统里收到消息,等主编approve了之后会真的接收。在99.99%的情况下主编不会推翻AE的决策。<br/><br/>4、主编Approve之后,审稿系统会让作者提交最终稿并把相关信息都forward到期刊出版部门。到了这一步,出版部门只会让作者检查一下有没有排版错误之类的问题,刊出已经是板上钉钉了。<br/><br/>5、你应该看明白了,Matlab仿真用的是正版还是盗版跟论文接收没有丝毫关系。至于文章刊出后会不会被撤稿,答案是不会。<br/>撤稿只有两种情况:(1)学术不端,例如伪造数据或者抄袭。(2)作者主动要求撤稿。然而,在matlab常用场合,工程领域很多期刊除非第一种学术不端的情况之外,是不会撤稿的。这一点跟化学生物领域常见的撤稿逻辑完全不同。如果你在TAC或者Automatica上发表的论文数据有误乃至结论全错,也不会撤稿。实际的做法是对此发表一篇勘误或者Comment指出之前那篇论文哪里哪里错了(我知道你们在想什么,没错,这个Comment在统计时会视为你又发了一篇论文!),原始那篇有错的论文仍然会一字不变的保留在原始位置,并且仍然始终处于被检索状态。某些人臆想的某第三方公司比如Mathwork能有权力要求期刊撤稿那是纯yy。<br/><br/>6、作者可以选择公开论文中仿真程序的源代码。但是根据绝大多数期刊的评审规则,源代码不是必须公开的,编辑和审稿人也认可这一点并且绝大多数场合不会要求作者提供源代码。只有很少见的情况下,审稿人对仿真结果存在严重的质疑,认为程序有误,才会要求作者提供源代码来进行code review。我至今只在2019年底遇到过一个审稿人认为我的仿真数据违反直觉,要求我公开代码,其实是他没看到我论文里专门一段解释为什么会出现这个反直觉的现象(最后结果是我把那段解释高亮并把代码po到了github上,然后论文秒接收)。<br/>但是,需要指出的是:审稿人是要求作者提供源代码,而不是要求作者“证明运行源代码的平台是正版”。下面一点解释为什么审稿人不会要求作者证明运行源代码的平台是正版。<br/><br/>7、如果审稿人想要接收一篇论文,那么可以随便夸夸就行了。但是如果想要拒绝一篇论文,他需要解释这篇论文有哪些严重缺陷,因此这个论文应当被拒稿。拒稿的条件(严重缺陷)包括:论文创新性不够、逻辑混乱、关键公式推导错误、等等。但是,“作者使用的软件可能不是正版”并不在拒稿条件之内!<br/>前面说过,AE收到多个审稿人意见之后会综合之后再决策。AE的判断标准就是上面说的创新性、逻辑、技术正确性等方面,并不包括作者使用软件平台的合法性。记住,决定你的论文是接收还是拒绝的不是审稿人,而是AE。审稿人的意见是“建议”,AE的意见是可以override审稿人的意见的——如果遇到sb审稿人写的非常负面但是完全不着边际的话,AE经常是一边骂这个审稿人sb一遍写report解释原因然后给个“minor revision”的决策的。如果审稿人挑不出任何毛病,只有一个攻击点“作者使用的软件可能不是正版”,这样的审稿意见在AE看来等于“this paper is well written”。<br/><br/>当然,如果AE想拒你,即使审稿意见都偏正面,他随便把审稿人的负面意见摘出来综合一下写成report就把你拒了,根本不需要拿Matlab说事。<br/><br/>总之,这种因为政治原因被禁了软件之后不要担心,你正常该怎么搞科研还怎么搞科研就是了。唯一的影响可能就是你没法从学校官网上下个免费的matlab了,得自己想办法(你懂得)。对你的论文发表毫无影响。 ---------- > `1.楼` 用户ID: `1869831` 发布时间: `2020-06-11 14:54:00` > 无聊的挽尊然后继续码论文去 ---------- > `2.楼` 用户ID: `60332398` 发布时间: `2020-06-11 15:31:00` > 为什么感觉这里什么人都有[s:ac:晕] ---------- > `3.楼` 用户ID: `7252630` 发布时间: `2020-06-11 15:32:00` > 什么叫专业啊[img]https://img.nga.178.com/attachments/mon_201209/14/-47218_5052bc587c6f9.png[/img] ---------- > `5.楼` 用户ID: `25597287` 发布时间: `2020-06-11 15:34:00` > 拜见SCI审稿大拿 ---------- > `6.楼` 用户ID: `61431161` 发布时间: `2020-06-11 15:34:00` > 审稿肯定没问题。<br/>问题是,matlab专门指名道姓点了学校了,就不会派个法务部的实习生盯着这两个学校的出版物吗?点开文件(ctrl+f搜一下,一天就能查一年的出版物)<br/>到时候告一波呢? 学校以后申请国际专利呢?<br/><del class='gray'> 我不清楚这次Matlab终止授权是否违法 </del> <br/>自己写个小算法跑跑么也就算了。最蛋疼的是使用其他基于matlab的商业软件,可能会有问题。<br/>matlab提供的一些库可能也没法直接调用了 ---------- > `7.楼` 用户ID: `60231333` 发布时间: `2020-06-11 15:35:00` > 这……真是卧虎藏龙啊 ---------- > `8.楼` 用户ID: `10496830` 发布时间: `2020-06-11 15:35:00` > [s:ac:哭笑]matlab大部分人都用的是盗版吧,无所谓了 ---------- > `9.楼` 用户ID: `25641044` 发布时间: `2020-06-11 15:38:00` > [s:ac:哭笑]别说国内大学了<br/>我在美国大学里如果在私人的电脑上就没见到过有人用正版的 ---------- > `10.楼` 用户ID: `42212677` 发布时间: `2020-06-11 15:38:00` > 反正我觉得无所谓,前年吧,我们学院一教授专门致电邮给Matlab公司,商讨给咱们学院配一批正版的,对面报价以后(好像几十万吧),他反手就让我们把盗版装上了[s:ac:哭笑] ---------- > `11.楼` 用户ID: `42980344` 发布时间: `2020-06-11 15:38:00` > 膜拜[s:ac:羡慕] ---------- > `12.楼` 用户ID: `81341` 发布时间: `2020-06-11 15:39:00` > 但你是基于目前的业内行事手法来判断的吧?后面会不会出幺蛾子呢? ---------- > `13.楼` 用户ID: `43057376` 发布时间: `2020-06-11 15:42:00` > [s:ac:哭笑]我想问一下自控原理应该怎么学,头大 ---------- > `14.楼` 用户ID: `1651623` 发布时间: `2020-06-11 15:43:00` > 你说的现在都对,但是,美国政府既然今天能把学校放上实体名单,明天就可以出命令,要求所有期刊在接受文章时核实所用软件是否有正版授权。想想看对华为步步升级的禁令,这个可能还是存在的吧?所以现在该有所准备的还是要做好准备啊 ---------- > `15.楼` 用户ID: `42072190` 发布时间: `2020-06-11 15:45:00` > 这个问题太简单了<br/><br/>我用matlab跑的程序,用excel、origin画图,你知道我用什么跑的?难道还要在acknowledgement里头标明我是用matlab跑的?<br/><br/>退一步讲,ban了学校的matlab又不代表ban了私人的购买,editor闲的蛋疼也不会去追究你用整版还是盗版matlab,想拒你的稿还不简单?<br/><br/>这本来就是mathwork给美帝政府舔屁股做姿态的事,可以说没有任何实质性影响。<br/><br/>以后就光明正大的用盗版,也不别扭了[s:ac:茶] ---------- > `16.楼` 用户ID: `1070505` 发布时间: `2020-06-11 15:46:00` > [quote][pid=429133662,22134888,1]Reply[/pid] <b>Post by [uid=61431161]黑牛猎[/uid] (2020-06-11 15:34):</b><br/><br/>审稿肯定没问题。<br/>问题是,matlab专门指名道姓点了学校了,就不会派个法务部的实习生盯着这两个学校的出版物吗?点开文件(ctrl+f搜一下,一天就能查一年的出版物)<br/>到时候告一波呢? 学校以后申请国际专利呢?<br/><del class='gray'> 我不清楚这次Matlab终止授权是否违法 </del> <br/>自己写个小算法跑跑么也就算了。最蛋疼的是使用其他基于matlab的商业软件,可能会有问题。<br/>matlab提供的一些库可能也没法直接调用了[/quote]确实有这个问题。我们单位有发文章用了盗版模拟软件,刊出后被软件公司发现然后律师函警告了[s:ac:瞎],后来赔钱了事。<br/>再后来发文章牵扯到模拟了就找买了版权的合作高校挂名。 ---------- > `17.楼` 用户ID: `42701415` 发布时间: `2020-06-11 15:46:00` > 想说什么,但又觉得自己水平不够,说句卧槽吧[s:ac:哭笑] ---------- > `18.楼` 用户ID: `42182139` 发布时间: `2020-06-11 15:47:00` > yysy,qs。<br/>我们发的sci用的ansys也是盗版的[s:ac:哭笑] ---------- > `19.楼` 用户ID: `39670531` 发布时间: `2020-06-11 15:50:00` > [quote][pid=429133662,22134888,1]Reply[/pid] <b>Post by [uid=61431161]黑牛猎[/uid] (2020-06-11 15:34):</b><br/><br/>审稿肯定没问题。<br/>问题是,matlab专门指名道姓点了学校了,就不会派个法务部的实习生盯着这两个学校的出版物吗?点开文件(ctrl+f搜一下,一天就能查一年的出版物)<br/>到时候告一波呢? 学校以后申请国际专利呢?<br/><del class='gray'> 我不清楚这次Matlab终止授权是否违法 </del> <br/>自己写个小算法跑跑么也就算了。最蛋疼的是使用其他基于matlab的商业软件,可能会有问题。<br/>matlab提供的一些库可能也没法直接调用了[/quote]以个人名义买的软件呢?比如我进哈工大读个硕士,本科其他学校读的,本科期间我买了正版使用权,然后才进去读硕士,发了文章,这他还能怎么说? ---------- > `20.楼` 用户ID: `34827425` 发布时间: `2020-06-11 15:51:00` > 楼主那个大学的[s:ac:茶] ---------- > `21.楼` 用户ID: `36056885` 发布时间: `2020-06-11 15:51:00` > 泥潭卧虎藏龙 ---------- > `22.楼` 用户ID: `11108422` 发布时间: `2020-06-11 15:54:00` > [quote][pid=429134643,22134888,1]Reply[/pid] <b>Post by [uid=42212677]BanderS[/uid] (2020-06-11 15:38):</b><br/><br/>反正我觉得无所谓,前年吧,我们学院一教授专门致电邮给Matlab公司,商讨给咱们学院配一批正版的,对面报价以后(好像几十万吧),他反手就让我们把盗版装上了[s:ac:哭笑][/quote]Aspen公司还是鸡贼,给学校用教育版很便宜,培养惯性。<br/>给外面公司报价是80w一年一台pc[s:a2:鬼脸] ---------- > `23.楼` 用户ID: `665351` 发布时间: `2020-06-11 15:55:00` > [quote][pid=429138202,22134888,1]Reply[/pid] <b>Post by [uid=39670531]zx2298059044[/uid] (2020-06-11 15:50):</b><br/><br/>以个人名义买的软件呢?比如我进哈工大读个硕士,本科其他学校读的,本科期间我买了正版使用权,然后才进去读硕士,发了文章,这他还能怎么说?[/quote]只看作者单位。<br/><br/>不过就如楼主所说,在今时今日,这还不是什么太实质性的问题。<br/><br/>当然,局面会不会进一步恶化就不知道了 ---------- > `24.楼` 用户ID: `61476852` 发布时间: `2020-06-11 15:57:00` > 什么?matlab居然有人用正版?[s:ac:哭笑] ----------
Java
UTF-8
420
2.46875
2
[]
no_license
package fr.doodz.openmv.api.api.types; /** * Created by doods on 31/07/14. */ public enum Sortdir { ASC("ASC"), DESC("DESC"); private final String text; /** * @param text */ private Sortdir(final String text) { this.text = text; } /* (non-Javadoc) * @see java.lang.Enum#toString() */ @Override public String toString() { return text; } }
Java
UTF-8
4,839
3.78125
4
[]
no_license
package dawson111.labexercises; import javax.swing.*; /** Determines the value and suit of 9 cards, each corresponding to * the numbers, from 0 to 51, randomly generated by the program. * Rank from 1 to 13. * Suit from hearts, represented by 0, diamonds, clubs * and to spades, being 3. * Will display the string equivalent of the card numbers. * * @authors Simon Langlois, Pierre Miguel * and Vincenzo Patrinostro - A933125 - 420-111-DW section 1 * @version 11/27/2009 */ public class CardsThree { public static void main (String[] args) { //variable declarations int newCard = 0, cardsInDeck = 1; long deck = 0; String cardIdentity = "", listOfCards = ""; //Draw nine cards and output their identity while (cardsInDeck <= 9) { //Get a random card number, checked to not already have been dealt newCard = getCard(deck) + 1; //Add the new card to the deck deck = (deck * 100) + newCard; //Output the name of the card cardIdentity = convertToString(newCard); listOfCards = listOfCards + "\n Card " + cardsInDeck + " : " + cardIdentity; //Increment the drawing counter cardsInDeck = cardsInDeck + 1; } //Display the output JOptionPane.showMessageDialog (null, "********** Card Number and its Identity **********\n\n" + "Deck of card : " + deck + "\n\n" + "Name of the cards :" + listOfCards + "\n\n" + "Written by : Simon Langlois,\n" + " Pierre Miguel,\n" + " Vincenzo Patrinostro\n\n", "Cards", JOptionPane.INFORMATION_MESSAGE); System.exit (0); } //end main() //Check if the new card is already in the deck public static boolean checkIfAlreadyDealt (int newCard, long deck) { int oldCard; boolean cardIsDealt = false; //Check the card until it finds a match, or the deck is empty while (deck != 0 && !cardIsDealt) { //Isolate the last card in the deck oldCard = (int) (deck % 100); //Test is against the new card, and assign the result to isAlreadyDealt cardIsDealt = ((newCard + 1) == oldCard); //jump to the next card in the deck deck = deck / 100; } return cardIsDealt; } //Receives a card number from 0 to 51 and returns the corresponding name public static String convertToString (int cardNumber) { int cardFaceValue, cardSuit; String faceValueName, suitName; String cardIdentity; //determine the value and suit of the card, in numbers cardFaceValue = (cardNumber % 13) + 1; cardSuit = cardNumber / 13; //Get the value and suit strings faceValueName = getFaceValue(cardFaceValue); suitName = getSuit (cardSuit); //Get a coherent phrase out of the value and suit cardIdentity = "The " + faceValueName + " of " + suitName; //Return the whole identity of the card return cardIdentity; } //Deal a new card public static int getCard (long deck) { int newCard = 0; boolean cardIsDealt = true; //Draw cards until it finds one that is not already dealt while (cardIsDealt) { //Draw a card newCard = getCardNumber (); //Check if the card is dealt cardIsDealt = checkIfAlreadyDealt (newCard, deck); } return newCard; } //Returns a random integer between 0 and 51 public static int getCardNumber () { int newCard; //randomly select a card newCard = (int) (Math.random () * 52); //Return the random card number return newCard; } //Recieves a card value from 1 to 13 and returns the corresponding name public static String getFaceValue (int cardFaceValue) { String faceValueName; //Get the value of the card in words switch (cardFaceValue) { case 1: faceValueName = "Ace"; break; case 2: faceValueName = "Two"; break; case 3: faceValueName = "Three"; break; case 4: faceValueName = "Four"; break; case 5: faceValueName = "Five"; break; case 6: faceValueName = "Six"; break; case 7: faceValueName = "Seven"; break; case 8: faceValueName = "Eight"; break; case 9: faceValueName = "Nine"; break; case 10: faceValueName = "Ten"; break; case 11: faceValueName = "Jack"; break; case 12: faceValueName = "Queen"; break; case 13: faceValueName = "King"; break; default: faceValueName = "Error"; break; } //Return the value string return faceValueName; } //Get the name corresponding to a card suit from 0 to 3 public static String getSuit (int cardSuit) { String suitName; //Get the suit of the card in word if (cardSuit <= 2) if (cardSuit <= 1) if (cardSuit == 0) suitName = "Hearts"; else suitName = "Diamonds"; else suitName = "Clubs"; else suitName = "Spades"; //Return the suit string return suitName; } } //end CardsTwo class