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
1,493
1.828125
2
[]
no_license
// isComment package com.codebutler.farebot.transit.opal; import android.content.res.Resources; import android.support.annotation.NonNull; import com.codebutler.farebot.transit.Subscription; import com.google.auto.value.AutoValue; import java.util.Date; /** * isComment */ @AutoValue abstract class isClassOrIsInterface extends Subscription { @NonNull public static OpalSubscription isMethod() { return new AutoValue_OpalSubscription(); } @Override public int isMethod() { return isIntegerConstant; } @Override public Date isMethod() { // isComment return new Date(isIntegerConstant - isIntegerConstant, isIntegerConstant - isIntegerConstant, isIntegerConstant); } @Override public Date isMethod() { // isComment return new Date(isIntegerConstant - isIntegerConstant, isIntegerConstant - isIntegerConstant, isIntegerConstant); } @Override public String isMethod(@NonNull Resources isParameter) { return isMethod(isNameExpr); } @Override public String isMethod(@NonNull Resources isParameter) { return "isStringConstant"; } @Override public int isMethod() { return isIntegerConstant; } @Override public String isMethod(@NonNull Resources isParameter) { return isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); } @Override public String isMethod() { return null; } }
Python
UTF-8
3,292
2.734375
3
[ "BSD-3-Clause" ]
permissive
from mechsearch.graph import GraphMultiset, Graph import mod from typing import Dict, Optional from numpy import ndarray class State: def __init__(self, graph_multiset: GraphMultiset): self._graph_multiset: GraphMultiset = graph_multiset self._key: int = hash(self._graph_multiset) def __eq__(self, other: 'State') -> bool: return self._graph_multiset == other._graph_multiset def __ne__(self, other: 'State') -> bool: return not self == other def __hash__(self) -> int: return hash(self.key) def __str__(self) -> str: return f"State {str(self._graph_multiset)}" def to_json(self): return {g.name: i for g, i in self._graph_multiset.counter.items()} @staticmethod def from_json(jState: Dict[str, int], name2graph: Dict[str, mod.Graph]): graphs = {Graph(name2graph[name]): count for name, count in jState.items()} return State(GraphMultiset(graphs)) @property def key(self) -> int: return self._key @property def graph_multiset(self) -> GraphMultiset: return self._graph_multiset def fire(self, dg_edge: mod.DGHyperEdge, inverse: bool = False) -> Optional['State']: counter = self._graph_multiset.counter sources = dg_edge.sources targets = dg_edge.targets #sources = GraphMultiset.from_dg_vertices(dg_edge.sources) #targets = GraphMultiset.from_dg_vertices(dg_edge.targets) if inverse: sources, targets = targets, sources #new_multiset = self._graph_multiset - sources + targets for v in sources: counter[Graph(v.graph)] -= 1 for v in targets: counter[Graph(v.graph)] += 1 return State(GraphMultiset(counter)) class StateWithDistance(State): def __init__(self, graph_multiset: GraphMultiset, distance_matrix: ndarray, atom_id_map: Dict[mod.Graph.Vertex, int]): super().__init__(graph_multiset) self._distance_matrix: ndarray = distance_matrix self._atom_id_map: Dict[mod.Graph.Vertex, int] = dict(atom_id_map) def _compute_maximum_distance(self, rule: mod.Rule, morphism): maximum_distance = 0 for edge in rule.edges: if edge.left.isNull() and not edge.right.isNull(): source, target = morphism(edge.source)[0], morphism(edge.target)[0] if source not in self._atom_id_map or target not in self._atom_id_map: continue source_id = self._atom_id_map[source] target_id = self._atom_id_map[target] maximum_distance = max(maximum_distance, self._distance_matrix[source_id][target_id]) return maximum_distance def fire(self, dg_transition: mod.DGHyperEdge, inverse: bool = False) -> Optional['StateWithDistance']: simple_state: State = super().fire(dg_transition, inverse) new_state: StateWithDistance = StateWithDistance(simple_state.graph_multiset, self._distance_matrix, self._atom_id_map) distances = mod.atomMapEvaluate(dg_transition, self._compute_maximum_distance) if min(distances) > 3: return None return new_state
Java
UTF-8
4,222
2.328125
2
[]
no_license
package com.example.itwaretestapp; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ListView; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { ArrayList<DataModel> datasArray = new ArrayList<DataModel>(); RegistrAdapter adapter; ListView main_list; Button submit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); main_list= (ListView) findViewById(R.id.main_list); submit= (Button) findViewById(R.id.submit); new DownloadFilesTask().execute(); } public class DownloadFilesTask extends AsyncTask< Void, Void, String > { private final ProgressDialog dialog = new ProgressDialog(MainActivity.this); @Override protected void onPreExecute() { super.onPreExecute(); this.dialog.setMessage("Loading..."); this.dialog.show(); } @Override protected String doInBackground(Void...param) { ServiceHandler sh = new ServiceHandler(); String jsonStr = sh.makeServiceCall("https://5f0b3a919d1e150016b372f1.mockapi.io/api/data", ServiceHandler.GET); Log.d("res1", jsonStr); return jsonStr; } @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override protected void onPostExecute(String response) { super.onPostExecute(response); Log.d("res2", response); dialog.dismiss(); if (response != null) { try { JSONObject jObjct = new JSONObject(response); String status = jObjct.get("msg").toString(); if (status.equals("Success")) { JSONArray arr = jObjct.getJSONArray("surveyData"); for (int i = 0; i < arr.length(); i++) { try{ JSONObject c = arr.getJSONObject(i); DataModel dataModel = new DataModel(); dataModel.setControlType(c.getString("controlType")); dataModel.setQuestion(c.getString("question")); dataModel.setRequiredValidator(c.getString("requiredValidator")); dataModel.setRequiredValidatorMessage(c.getString("requiredValidatorMessage")); if(c.getString("controlType").equals("Textbox")){ dataModel.setRegularExpression(c.getString("regularExpression")); }else{ dataModel.setRegularExpression("Valid"); } Log.e("the ","ARAY"+dataModel.getQuestion()); datasArray.add(dataModel); Log.e("the ","ARAY"+datasArray.size()); } catch (Exception e) { e.printStackTrace(); } } adapter = new RegistrAdapter(MainActivity.this,datasArray,arr); main_list.setAdapter(adapter); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { adapter.checkValidation(view); } }); } } catch (Exception e) {e.printStackTrace();} } } } }
Ruby
UTF-8
1,807
2.671875
3
[]
no_license
#!/usr/bin/env ruby require 'autojenkins' URL='http://jenkins.ng.com:8080' AUTH=["neurogeek", "123qwe4r!!"] #TOKEN="" if URL == '' puts "To use this functions, please configure URL and AUTH" end JENK = AutoJenkins::Jenkins.new(URL, AUTH) def ListAll() jobs = JENK.all_jobs() if jobs jobs.each do |jb| print "#{jb.name} --> #{jb.get_url}\n" print "DisplayName: #{jb.get_displayName}\n" jb.info_items.each do |i| puts i end end end end def CreateFromJob(jobname, newjobname) job = JENK.get_job(jobname) job2 = job.copy(newjobname) print "#{job2.name}\n" end def GetBuildInfo(jobname, buildnum) job = JENK.get_job(jobname) bld = job.get_build(buildnum) return bld end def GetConfig(jobname) job = JENK.get_job(jobname) return job.get_config() end def GetJob(jobname) return JENK.get_job(jobname) end def GetInfo(jobname) def pretty_print(entry, tab=1) if entry.kind_of? Hash entry.keys.each do |k| print " " * tab * 2 print "#{k} ----> \n" pretty_print(entry[k], tab=tab+1) end elsif entry == nil print " " * tab * 2 print "[NONE]\n" elsif entry.kind_of? Array entry.each do |v| pretty_print(v, tab+1) end else print "\t" * tab print "#{entry}\n" end end job = JENK.get_job(jobname) job.info.keys.each do |k| print "#{k} ----> \n" pretty_print job.info[k] end end # Uncomment to test functions #ListAll() CreateFromJob("TestJOb", "NewJob") #puts GetBuildInfo("TestJOb", 1) #puts GetConfig("TestJOb") #puts GetInfo("TestJOb")
Java
UTF-8
285
3.0625
3
[]
no_license
package Problem102; public class Point { public int x, y, z; public Point(int abscissa, int ordinate, int azimuth) { this.x = abscissa; this.y = ordinate; this.z = azimuth; } public String toString() { return "(" + this.x + "," + this.y + "," + this.z + ")"; } }
Markdown
UTF-8
4,068
2.703125
3
[]
no_license
每个内存的使用都需要申请 循环中的结构体等局部变量,内存会被清除,留给下一个使用 maps.begin maps.end it->first it->second 1012 临时变量、map中添加的value、数组中的元素,指针不同。 栈内存由OS动态开辟回收,我们malloc的内存时是在堆中,需要我们手动释放,否则就会内存泄露。 [2020-02-13 12:24:39] memset(*n,1|0,sizeof(type)*len) [2020-02-13 03:52:07] 并查集:将有关系的结点组成一个集合 [2020-02-13 04:16:59] 在对问题进行建模的时候,我们应该尽量想清楚需要解决的问题是什么。 [2020-02-17 09:41:28] int n[m] 就是申请数组,如果需要指向一个数组,可以用指针int *n代替。 [2020-02-17 10:05:33] 0=false,-1||1=true [2020-02-17 12:33:45] pop之后都要判断一下队列是否为空 [2020-02-18 11:24:51] string=char[]可以这样赋值 [2020-02-18 11:53:08] 指针取值*p,取变量指针&n [2020-02-18 06:28:28] queue<btn*> q; [2020-02-20 10:44:54] c [2020-02-21 05:07:32] map中的元素(pair)放到序列容器(如vector)中,再用sort进行排序。 [2020-02-23 03:19:20] 大数字用python秒杀 [2020-02-24 01:16:51] string a="123""456"; [2020-02-25 10:16:54] 如果下标算起来太绕,直接多开一个,从1开始使用数组。写起来,思考起来都很方便,读起来也比较友好。 [2020-02-29 03:30:12] 大数据量(超过10000)都不要去用python [2020-02-29 04:29:31] c++ vector push_back对象的时候存起来的是拷贝 [2020-02-29 04:40:23] %ld用于long类型,%lld用于long long类型。 [2020-02-29 05:14:47] sort函数,comp结果为true,是第一个参数排在前面 [2020-02-29 05:40:36] 结构体结尾处有个分号 [2020-02-29 07:50:57] 大量数据的输入,用scanf,而不是cin [2020-03-01 03:39:08] 边的储存,因为题目限制65536kb,如果直接用数组int[10000][10000]至少用了800000000/1024 = 781 250kb [2020-03-01 10:18:28] printf("%lu", vector.size()); [2020-03-01 10:39:07] 注意多重循环的break [2020-03-03 09:15:07] 以数字型作为地址时,注意输出时的格式(一般前面都带0) [2020-03-08 05:38:26] map的实现是一颗红黑树,因此,map的内部键的数据都是排好序的,查找和删除、插入的效率都是lgN。 [2020-03-09 04:31:02] 平方探测法:H(key)=( key + i ^ 2 ) % TSize,其中Tsize为表长,i取值为[1,Tsize/2]。若i超出范围,就说明表中找不到合适的位置。 [2020-03-09 05:30:13] index不能作为变量名 [2020-03-10 03:46:07] 有两种传递方法,一种是function(int a[]); 另一种是function(int *a) [2020-03-10 03:46:15] 这两种两种方法在函数中对数组参数的修改都会影响到实参本身的值! [2020-03-10 03:47:02] 这里也不能在test()函数内部用sizeof求数组的大小,必须在外面算好了再传进来。 [2020-03-11 11:29:53] 由于是升序,所以可用用一个数组count_time[24 * 60 * 60]模拟(挺好的思路) [2020-03-12 12:07:48] 对他们排序,先按照车牌号排序,再按照来的时间先后排序。 [2020-03-12 04:19:13] int as={{}};int *a=as[0];这里只能用指针,不能赋值。 [2020-03-12 08:48:34] 一定要搞清楚index [2020-03-19 09:11:17] 相乘和相加要考虑溢出 [2020-03-19 09:12:17] 如果时间较长的测试没通过,考虑数值溢出问题 [2020-03-20 05:40:54] 考虑连通数,优先使用并查集,效率很高 [2020-03-21 03:12:43] 双端队列:deque [2020-03-22 06:17:36] 大型项目用什么编辑器或IDE根本无所谓,关键的是build tool。 [2020-03-23 12:01:17] string和char[]不能直接用等号判断是否相等 [2020-03-23 12:01:44] 结构体中的变量有默认初始值 [2020-03-24 11:44:43] C++ is not a tool for website development at all. [2020-03-27 10:43:22] 红黑树也是二叉查找树 [2020-03-27 01:53:07] 但要保持红黑树的性质,结点不能乱挪,还得靠变色了。
Java
UTF-8
11,878
2.828125
3
[]
no_license
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.text.DecimalFormat; //Author: Victor Chung //This class itself is "almost" self-contained. Unlike other classes in the program, the function call in this //class is not as spiral-like. //I personally think the Graphics2D paint function is the most interesting ones. Actually, most of the drawing is done in there for the utility graph //Comments are added below public class ContinuousUtilityGraph extends JPanel implements MouseListener, MouseMotionListener { private static final long serialVersionUID = 1L; //The basic idea is I have an array list of points, which has x-axis and y-axis. MoveablePoint[] p; //Lines will join the points Line2D.Float[] lines; MoveablePoint moving; int xaxis;//This one is needed to keep track of the x-axis. This is used when a point is being dragged, and make sure the dragging only happens along the y-axis. ContinuousAttributeDomain cdomain; int discrete_elements; double[] items; double[] weights; double[] undo; //This is used for undoing purposes String unit; int clicki; //This is to keep correct track of what is clicked String attributeName; ValueChart chart; DefineValueFunction dvf; AttributeCell acell; JPanel pnl; public ContinuousUtilityGraph(ValueChart ch, ContinuousAttributeDomain dd, double[] it, double[] we, String un, String att, DefineValueFunction d, AttributeCell ac) { //Setting variable names cdomain = dd; chart = ch; items = it; weights = we; unit = un; attributeName = att; dvf = d; acell = ac; setBackground(Color.white); p = new MoveablePoint[items.length]; lines = new Line2D.Float[items.length - 1]; plotPoints(); addMouseListener(this); addMouseMotionListener(this); if (chart!=null) showGraph(); else setGraph(); } void plotPoints(){ //Creating all the points of utility for(int i = 0; i < items.length; i++){ p[i] = new MoveablePoint(((int)(((items[i]-items[0])/((items[(items.length)-1])-items[0]))*200))+50, ((int) (200 - (weights[i] * 200) + 5))); //p[i] = new MoveablePoint(((Incre * i) + 50), ((int) (200 - (weights[i] * 200) + 5))); } //Joining all the points into lines for(int i = 0; i < (items.length - 1); i++){ lines[i] = new Line2D.Float(p[i], p[i+1]); } repaint(); } void setGraph(){ pnl = new JPanel(); this.setPreferredSize(new Dimension(275,260)); pnl.add(this, BorderLayout.CENTER); } ContinuousUtilityGraph getGraph(){ return(this); } public void mouseClicked(MouseEvent me) { if((me.getX()< 40) && (me.getX() > 0) && (me.getY() > 240)){ for(int i = 0; i < undo.length; i++){ cdomain.removeKnot(items[i]); cdomain.addKnot(items[i], undo[i]); } //Updating the weight for(int i = 0; i < items.length; i++){ p[i] = new MoveablePoint(((int)(((items[i]-items[0])/((items[(items.length)-1])-items[0]))*200))+50, ((int) (200 - (weights[i] * 200) + 5))); } //Rejoining the lines for(int i = 0; i < (items.length - 1); i++){ lines[i] = new Line2D.Float(p[i], p[i+1]); } repaint(); if (chart != null) chart.updateAll(); } if((me.getX()< 275) && (me.getX() > 210) && (me.getY() > 240)){ for(int i = 0; i < undo.length; i++){ cdomain.removeKnot(items[i]); cdomain.addKnot(items[i], weights[i]); } //Updating the weight for(int i = 0; i < items.length; i++){ p[i] = new MoveablePoint(((int)(((items[i]-items[0])/((items[(items.length)-1])-items[0]))*200))+50, ((int) (200 - (weights[i] * 200) + 5))); } //Rejoining the lines for(int i = 0; i < (items.length - 1); i++){ lines[i] = new Line2D.Float(p[i], p[i+1]); } repaint(); if (chart != null) chart.updateAll(); } } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mouseMoved(MouseEvent me) { } public void mousePressed(MouseEvent me) { xaxis = me.getX(); for (int i = 0; i < items.length; i++) { //This long if statement is only to make the dragging point more sensitive. There is nothing interesting about it. if ((p[i].hit(me.getX(), me.getY())) || (p[i].hit(me.getX() + 1, me.getY() + 1)) || (p[i].hit(me.getX() - 1, me.getY() - 1)) || (p[i].hit(me.getX() + 1, me.getY())) || (p[i].hit(me.getX(), me.getY() + 1)) || (p[i].hit(me.getX(), me.getY() - 1)) || (p[i].hit(me.getX(), me.getY() - 1)) || (p[i].hit(me.getX() + 2, me.getY() + 2)) || (p[i].hit(me.getX() + 2, me.getY())) || (p[i].hit(me.getX() - 2, me.getY() - 2)) || (p[i].hit(me.getX(), me.getY() + 2)) || (p[i].hit(me.getX() - 2, me.getY())) || (p[i].hit(me.getX(), me.getY() - 2)) || (p[i].hit(me.getX() + 3, me.getY() + 3)) || (p[i].hit(me.getX() + 3, me.getY())) || (p[i].hit(me.getX() - 3, me.getY() - 3)) || (p[i].hit(me.getX(), me.getY() + 3)) || (p[i].hit(me.getX() - 3, me.getY())) || (p[i].hit(me.getX(), me.getY() - 3))) { //if (SwingUtilities.isRightMouseButton(me)){ // dvf.popValueFunction.show(me.getComponent(), me.getX()+5, me.getY()+5); // setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); //} //else{ setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)); moving = p[i]; clicki = i; if (chart != null) chart.last_int.setUndoUtil(this, null, items[i], weights[i], cdomain); movePoint(xaxis, me.getY()); //} } } } public void mouseReleased(MouseEvent me) { for (int i = 0; i < items.length; i++) { if (p[i].hit(me.getX(), me.getY())) { movePoint(xaxis, me.getY()); } } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); moving = null; } public void mouseDragged(MouseEvent me) { if(me.getY() < 205 && me.getY() > 5){ movePoint(xaxis, me.getY()); } else{ if(me.getY() > 205){ movePoint(xaxis, 205); } else if(me.getY() < 5){ movePoint(xaxis,5); } } } void movePoint(int x, int y) { if (moving == null) return; moving.setLocation(x, y); //Updating all the lines for(int i = 0; i < (items.length - 1); i++){ lines[i].setLine(p[i].x, p[i].y, p[i+1].x, p[i+1].y); } repaint(); cdomain.removeKnot(items[clicki]); cdomain.addKnot(items[clicki],((float) (205 - y) / 200)); acell.cg.plotPoints(); if (chart!=null){ chart.updateAll(); } else dvf.checkUtility(dvf.obj_sel, dvf.lbl_sel); //Updating weights weights = cdomain.getWeights(); } public void paintComponent(Graphics gfx) { super.paintComponent(gfx); Graphics2D g = (Graphics2D) gfx; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setPaint(Color.blue); //Draw all the lines for(int i = 0; i < (items.length - 1); i++){ g.draw(lines[i]); } Shape[] s; s = new Shape[items.length]; String temp; g.setColor(Color.DARK_GRAY); for(int i = 0; i < items.length; i++){ Float test = new Float((205 - p[i].y) / 200); temp = test.toString(); g.drawString(temp.substring(0,3), (p[i].x + 5),p[i].y); s[i] = p[i].getShape(); } g.setColor(Color.red); //g.fill(s0); g.fill(s1); for(int i = 0; i < items.length; i++){ g.fill(s[i]); } g.setColor(Color.black); // g.draw(s0); g.draw(s1); for(int i = 0; i < items.length; i++){ g.draw(s[i]); } //Draw the Line axis g.drawLine(50, 5, 50, 205); //y-axis g.drawLine(50, 205, 260, 205); //x-axis //Draw the static labels String utility_label = new String("Utility"); g.setFont(new Font(null, Font.BOLD, 12)); g.drawString(utility_label, 10, 110); String utility_upper_bound = new String("1"); g.drawString(utility_upper_bound, 35, 15); String utility_lower_bound = new String("0"); g.drawString(utility_lower_bound, 35, 205); //Drawing the labels from variables passed g.setFont(new Font(null, Font.BOLD, 12)); int len = (attributeName + " (" + unit + ")").length(); g.setFont(new Font(null, Font.BOLD, 13)); g.drawString((attributeName + " (" + unit + ")"), 150 - 3 * len ,240); //Labelling different utilities for(int i = 0; i < items.length; i++){ if((weights[i] == 0.0) || (weights[i] == 1.0)){ g.setFont(new Font(null, Font.BOLD, 12)); } else{ g.setFont(new Font(null, Font.PLAIN, 12)); } DecimalFormat df = acell.obj.decimalFormat;; g.drawString((df.format(items[i])),((int)(((items[i]-items[0])/((items[(items.length)-1])-items[0]))*200))+40 ,220); } //Drawing the Undo and Redo button g.setColor(Color.RED); g.setFont(new Font(null, Font.PLAIN, 12)); g.drawString("UNDO", 2, 255); g.drawString("REDO", 235, 255); } private void showGraph(){ JDialog frame = new JDialog(chart.getFrame(), attributeName + " utility graph"); frame.setModal(true); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //ContinuousUtilityGraph moving = new ContinuousUtilityGraph(); //moving this.setPreferredSize(new Dimension(275,260)); frame.getContentPane().add(this, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } class MoveablePoint extends Point2D.Float { int r = 4; Shape shape; public MoveablePoint(int x, int y) { super(x, y); setLocation(x, y); } void setLocation(int x, int y) { super.setLocation(x, y); shape = new Ellipse2D.Float(x - r, y - r, 2*r, 2*r); } public boolean hit(int x, int y) { return shape.contains(x, y); } public Shape getShape() { return shape; } } }
Java
UTF-8
1,388
1.976563
2
[]
no_license
package com.facebook.graphql.model; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; import com.fasterxml.jackson.annotation.JsonProperty; public class NotificationStoriesDelta$NotificationStoryDeltaEdge implements Parcelable { public static final Parcelable.Creator<NotificationStoryDeltaEdge> CREATOR = new NotificationStoriesDelta.NotificationStoryDeltaEdge.1(); @JsonProperty("cursor") public final String cursor; @JsonProperty("node") public final NotificationStoriesDeltaNode node; protected NotificationStoriesDelta$NotificationStoryDeltaEdge() { this.node = null; this.cursor = null; } protected NotificationStoriesDelta$NotificationStoryDeltaEdge(Parcel paramParcel) { this.node = ((NotificationStoriesDeltaNode)paramParcel.readParcelable(NotificationStoriesDeltaNode.class.getClassLoader())); this.cursor = paramParcel.readString(); } public int describeContents() { return 0; } public void writeToParcel(Parcel paramParcel, int paramInt) { paramParcel.writeParcelable(this.node, paramInt); paramParcel.writeString(this.cursor); } } /* Location: /data1/software/apk2java/dex2jar-0.0.9.12/secondary-1.dex_dex2jar.jar * Qualified Name: com.facebook.graphql.model.NotificationStoriesDelta.NotificationStoryDeltaEdge * JD-Core Version: 0.6.2 */
Java
UTF-8
5,461
2.296875
2
[]
no_license
package com.cognizant.Dao; import java.math.BigDecimal; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.cognizant.controller.AdminController; import com.cognizant.entity.Patient; import com.cognizant.entity.Physician; import com.cognizant.helper.SessionCreator; @Repository("PhysicianDetailsDAOImpl") public class PhysicianDetailsDAOImpl implements PhysicianDetailsDAO{ @Autowired private SessionCreator sessionCreator; public SessionCreator getSessionCreator() { return sessionCreator; } public void setSessionCreator(SessionCreator sessionCreator) { this.sessionCreator = sessionCreator; } public static final Logger logger=LoggerFactory.getLogger(AdminController.class); //--------------------------------------------------------------------------------------------------------------------// //****************FUNCTION TO RETERIVE PHYSICIAN LIST********************// public List<Physician> getAllPhysicians() { logger.info("Reteriving Physician List"); Session session=sessionCreator.createSession(); Transaction tx=session.beginTransaction(); List<Physician> physicianList=session.createQuery("from Physician").list(); tx.commit(); return physicianList; } //--------------------------------------------------------------------------------------------------------------------// //****************FUNCTION TO PERSIST PHYSICIAN********************// public boolean persistPhysician(Physician physician) { logger.info("Persisting Physicain"); generatePhysicianId(); Session session=sessionCreator.createSession(); Transaction tx=session.beginTransaction(); session.persist(physician); tx.commit(); return true; } //--------------------------------------------------------------------------------------------------------------------// //****************FUNCTION TO RETERIVE PHYSICIAN OBJECT********************// public Physician getPhysicianObject(String physicianId) { logger.info("Getting Physician Object"); Session session=sessionCreator.createSession(); Transaction tx=session.beginTransaction(); Physician physician=(Physician) session.load(Physician.class, physicianId); tx.commit(); return physician; } //--------------------------------------------------------------------------------------------------------------------// //****************FUNCTION TO GENERATE PHYSICIAN ID********************// public void generatePhysicianId() { logger.info("Generating Physicain Id"); Session session=sessionCreator.createSession(); Transaction tx=session.beginTransaction(); Query query=session.createSQLQuery("select PHYSICIANSEQ.nextval FROM DUAL"); Long key=((BigDecimal) query.uniqueResult()).longValue(); StorePhyId.addId(key.intValue()); tx.commit(); } //--------------------------------------------------------------------------------------------------------------------// //****************FUNCTION TO UPDATE PHYSICIAN DETAILS********************// public boolean updatePhysician(Physician physician) { logger.info("Updating Physician Details"); Session session=sessionCreator.createSession(); Transaction tx=session.beginTransaction(); session.merge(physician); boolean res=true; tx.commit(); return res; } //--------------------------------------------------------------------------------------------------------------------// //****************FUNCTION TO CHECK PHYSICIAN DETAILS********************// public int checkPhysician(Physician physician) { logger.info("Check Physician Details"); Session session=sessionCreator.createSession(); Transaction tx=session.beginTransaction(); Query query=session.createQuery("from Physician o where o.contactNumber=:contactNumber"); query.setParameter("contactNumber", physician.getContactNumber()); List<Physician>contactList=query.list(); Query query1=session.createQuery("from Physician o where o.emailId=:emailId"); query1.setString("emailId", physician.getEmailId()); List<Physician>emailList=query.list(); tx.commit(); int physicianPersist=0; if ((contactList.isEmpty()) && (emailList.isEmpty())) { physicianPersist = 4; } else if (!(contactList.isEmpty())&& (emailList.isEmpty())) { physicianPersist = 1; } else if (!(emailList.isEmpty()) && (contactList.isEmpty()) ) { physicianPersist = 2; } else if (!(emailList.isEmpty()) && !(contactList.isEmpty())) { physicianPersist = 3; } return physicianPersist; } //-------------------------------------------------------------------------------------------------------------------// //****************FUNCTION TO RETERIVE ALL PHYSICIANS ID********************// public List<String> getAllPhysiciansId() { logger.info("Reteriving All Physician's Id"); Session session=sessionCreator.createSession(); Transaction tx=session.beginTransaction(); List<String> physicianIdList=session.createQuery("select o.physicianId from Physician o ").list(); tx.commit(); return physicianIdList; } }
Python
UTF-8
1,609
3.5625
4
[]
no_license
# # @lc app=leetcode.cn id=1260 lang=python3 # # [1260] 一年中的第几天 # # https://leetcode-cn.com/problems/shift-2d-grid/description/ # # algorithms # Easy (60.54%) # Total Accepted: 7.9K # Total Submissions: 13.1K # Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]\n1' # # 给你一个 m 行 n 列的二维网格 grid 和一个整数 k。你需要将 grid 迁移 k 次。 # # 每次「迁移」操作将会引发下述活动: # # # 位于 grid[i][j] 的元素将会移动到 grid[i][j + 1]。 # 位于 grid[i][n - 1] 的元素将会移动到 grid[i + 1][0]。 # 位于 grid[m - 1][n - 1] 的元素将会移动到 grid[0][0]。 # # # 请你返回 k 次迁移操作后最终得到的 二维网格。 # # # # 示例 1: # # # # 输入:grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1 # 输出:[[9,1,2],[3,4,5],[6,7,8]] # # # 示例 2: # # # # 输入:grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4 # 输出:[[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]] # # # 示例 3: # # 输入:grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9 # 输出:[[1,2,3],[4,5,6],[7,8,9]] # # # # # 提示: # # # 1 <= grid.length <= 50 # 1 <= grid[i].length <= 50 # -1000 <= grid[i][j] <= 1000 # 0 <= k <= 100 # # # class Solution: def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: m,n = len(grid),len(grid[0]) t = [] for i in range(m): t = t+grid[i] k = k % (m*n) x = t[-k:] + t[:-k] ans = [] for i in range(m): ans.append(x[i*n:(1+i)*n]) return ans
Markdown
UTF-8
3,679
2.703125
3
[]
no_license
Puppet Labs - Puppet Fundamental Training ========================================= September 18, 2012 - taught by Zack Smith (zack@puppetlabs.com) Introduction ------------ * Puppet advantage in level of detailed simulation versus other solutions * Facts - pieces of inventoried data (custom pieces of information) that the client sends to the Puppet Master (facts are inventory information) * conditional logic happens on the puppet master, not the puppet agents * Puppet Master sends the Catalog to the individual nodes (puppet agents) * Puppet caches the Catalog so it can manage itself even when network connectivity to the Puppet Master is cut off * SSL encryption used on all transmission between Master and agents * Reports can be many forms, such as emails, IRC chat, or custom * Puppet Enterprise is a stack that uses Puppet Open Source and provides certain additional features better role-based access control, support contracts, GUI, VMWare VM provisioning, and MCollective built in * Razor - tool built by EMC to provision bare metal servers * command puppet Setting Up ---------- * "puppet cert --list" command on the puppet master lists all certs waiting to be signed * search puppetlabs.com for autosign.conf to see how you can automatically sign certs from agents (useful for development environments) * PSSigner on github - wrapper for web-based certificate signing protocol * "puppet cert --sign [name]" to sign an individual certificate * "puppet cert --sign --all" to sign all certificates Puppet Enterprise Console ------------------------- * no automatic syncing for puppet modules (intentional) - manage the disconnect in the user interface * Puppet is idemopotent * there is a desired configuration state, puppet sees the drift in a node state, and uses convergence back to the desired state, then creates and sends a report * granularity in individual attributes * Puppet builds a graph of dependent resources * order does not matter in Puppet code, dependencies are set up automatically or manually * Puppet Resources are building blocks, combine them to make larger components * Package-File-Service for Puppet Resources * Puppet can both create Resources and remove them (for example you can have it remove users you no longer want - and run that across 1000s of servers) * "puppet describe user" - equivalent of man pages for "user", also do "puppet describe [command]" for other modules * there is only a single Catalog, you cannot have 2 different packages with the same title * providers are the interface between the underlying OS and the resource types * "puppet resource user root" -> shows the puppet code for how you would write the Puppet source to create the user root that mimics the one on this system Modules and Classes ------------------- * nodes are groups of classes that define behavior * site.pp is important in Puppet open source but not in Enterprise (because that is database-driven) * classes must have unique names! otherwise code will not work * modules are folders that contain the configuration * manifests is a key folder for Puppet, along with init.pp inside of it * auto-loading of classes (previously you had to tell your Puppet Master where to find your manifests) * within modules, classes are placed in predictable locations (and manifests helps tell where they are) * there is a difference between defining and declaring * *define* - specify contents and behavior * *declare* - direct Puppet to include or instantiate a class * you can use "puppet apply" locally and not use a Puppet master if desired * "puppet apply --noop" simulates what would actually happen without enforcing a change
PHP
UTF-8
10,666
2.640625
3
[]
no_license
<?php session_start(); if(!isset($_SESSION['userID'])){ header('Location:../index.php'); exit; } ini_set('date.timezone','Asia/Shanghai'); header("Content-type:text/html;charset=utf-8"); //$type=1; //$name="Excel导入"; //$excelfilename='ImportExcel\\2016.xls'; if(isset($_POST['type'])) { $type=$_POST["type"]; if (!empty($_FILES['file']['name'])){ if(preg_match("/.xlsx$/", $_FILES['file']['name'])) { $excelfilename='ImportExcel\\'.date("YmdHis").".xlsx"; }else { if(preg_match("/.xls$/", $_FILES['file']['name'])) { $excelfilename='ImportExcel\\'.date("YmdHis").".xls"; } else{echo "必须导入Excel表格.";exit;} } //echo $excelfilename; move_uploaded_file($_FILES['file']['tmp_name'], $excelfilename); }else{ echo "上传失败!";exit; } readexcel($type,$name,$excelfilename); } /* * 读取excel,兼容2003和2007,中文文件名有些问题 */ function readexcel($type,$name,$excelfilename){ include_once("Classes/PHPExcel/IOFactory.php"); if(preg_match("/.xlsx$/", $excelfilename)) { $reader = PHPExcel_IOFactory::createReader('Excel2007'); } else{ $reader = PHPExcel_IOFactory::createReader('Excel5'); } $PHPExcel = $reader->load($excelfilename); // 文档名称 $sheet = $PHPExcel->getSheet(0); // 读取第一个工作表(编号从 0 开始) $highestRow = $sheet->getHighestRow(); // 取得总行数 $highestColumn = $sheet->getHighestColumn(); // 取得总列数 //echo $highestRow.$highestColumn; //取前5行,判断导入的表格是否包括8列:"序号,工作目标,支撑项目,工作标准,,时间节点,,责任主体", //下边一行是否存在"年度投资,工作标准,启动时间,完成时间";如都存在,视为合法导入格式.否则给出错误提示 //取出相应列的列标号,取出起始行行标号 $start=0;//数据起始行 $end=$highestRow;//备注起始行 $li=array("id"=>"","target"=>"","title"=>"","investment"=>"","stage"=>"","startdate"=>"","enddate"=>"","depts"=>""); for($i=1;$i<=5;$i++) { for($j=0;$j<=10;$j++) { $val=$sheet->getCellByColumnAndRow($j, $i)->getValue(); if(preg_match("/系统内编号/", $val)){$li["id"]=$j;} if(preg_match("/工作目标/", $val)) {$li["target"]=$j;} if(preg_match("/支撑项目/", $val)) {$li["title"]=$j;} if(preg_match("/年度投资/", $val)) {$li["investment"]=$j;} if(preg_match("/工作标准/", $val)) {$li["stage"]=$j;} if(preg_match("/启动\s*时间/", $val)) {$li["startdate"]=$j;} if(preg_match("/完成\s*时间/", $val)) {$li["enddate"]=$j;$start=$i+1;} if(preg_match("/责任主体/", $val)) {$li["depts"]=$j;} } } if(empty($li["id"])) $li["id"]=100; foreach($li as $e){ if(empty($e)){echo "表格式不正确,请检查是否包括序号、工作目标、支撑项目、年度投资、工作标准、启动时间、完成时间、责任主体这8列。"; exit;}} //echo "start=$start"; //判断导入表最后5行是否存在"备注:",如存在,去掉备注行,不作为数据导入内容 for($i=0;$i<5;$i++) { $val=$sheet->getCellByColumnAndRow(0, $highestRow-$i)->getValue(); if(preg_match("/备注\s*/", $val)) $end=$highestRow-$i-1; } //echo "end=$end"; //按行读取数据,判断是否是总体目标的跨行,是的话放入当前的$generaltask,否则检验每行相应的数据合法性.放入二维数组$tasklist,其中工作标准、启动时间、完成时间为子二维数组,放入$tasklist中 $generaltask=""; $tasklist=array(); $inputrow=0; $task=array(); $progress=array(); $task["type"]=$type; for($i=$start;$i<=$end;$i++) { $investment=""; $stage=""; $startdate=""; $enddate=""; $val=trim($sheet->getCellByColumnAndRow(0, $i)->getValue()); $target=trim($sheet->getCellByColumnAndRow($li["target"], $i)->getValue()); if(preg_match("/^[\x{4e00}-\x{9fa5}]+/u", $val) && empty($target)) {//判断是否为总体任务 $task["generaltask"]=$val; continue; //echo $task["generaltask"]."<br>"; }//不是总体任务 $investment=trim($sheet->getCellByColumnAndRow($li["investment"], $i)->getValue()); $stage=trim($sheet->getCellByColumnAndRow($li["stage"], $i)->getValue()); $startdate=trim($sheet->getCellByColumnAndRow($li["startdate"], $i)->getValue()); $enddate=trim($sheet->getCellByColumnAndRow($li["enddate"], $i)->getValue()); if(empty($startdate) || !preg_match("/^\d{4}\.\d{1,2}\.{0,1}\d{0,2}$/",$startdate)) $startdate="2000-01-01"; if(empty($enddate) || !preg_match("/^\d{4}\.\d{1,2}\.{0,1}\d{0,2}$/",$enddate)) $enddate="2000-01-01"; if(preg_match("/^\d{4}\.\d{1,2}$/",$startdate)){$startdate=str_replace('.', '-', $startdate)."-1";} if(preg_match("/^\d{4}\.\d{1,2}\.\d{1,2}$/",$startdate)){$startdate=str_replace('.', '-', $startdate);} if(preg_match("/^\d{4}\.\d{1,2}$/",$enddate)){$enddate=str_replace('.', '-', $enddate)."-28";} if(preg_match("/^\d{4}\.\d{1,2}\.\d{1,2}$/",$enddate)){$enddate=str_replace('.', '-', $enddate);} $title=trim($sheet->getCellByColumnAndRow($li["title"], $i)->getValue()); $depts=trim($sheet->getCellByColumnAndRow($li["depts"], $i)->getValue()); if(!empty($target)) {//判断工作目标是否为空,不为空新加一行数据进入$tasklist if(count($progress)>0) $task["progress"]=$progress; $inputrow++; if(!empty($task['target'])){ array_push($tasklist,$task); //清除已存入数组$tasklist的数据,保留$task["generaltask"]和$task["target"]的内容 $progress=array(); $task['title']='';$task['investment']='';$task['progress']='';$task['depts']=''; } //添加老数据结束,新的一条数据加入读取到的本行内容 $task["target"]=$target; $task["title"]=$title; $task["depts"]=$depts; $task["investment"]=$investment; $task["id"]=trim($sheet->getCellByColumnAndRow($li["id"], $i)->getValue()); $arr=array("stage"=>$stage,"startdate"=>$startdate,"enddate"=>$enddate); if(count($arr)>0) array_push($progress,$arr); }else{//判断工作目标是否为空,为空时判断支撑项目是否存在多个 if(!empty($title)){//工作目标为空,支撑项目不为空,再次新增一条数据 if(count($progress)>0) $task["progress"]=$progress; $inputrow++; if(!empty($task['target'])){ array_push($tasklist,$task); //清除已存入数组$tasklist的数据,保留$task["generaltask"]和$task["target"] $task["title"] $task["depts"]的内容 $progress=array(); $task['investment']='';$task['progress']=''; } //添加老数据结束,新的一条数据加入读取到的本行内容 $task["title"]=$title; if(!empty($depts)) $task["depts"]=$depts; $task["investment"]=$task["investment"].$investment; $task["id"]=trim($sheet->getCellByColumnAndRow($li["id"], $i)->getValue()); $arr=array("stage"=>$stage,"startdate"=>$startdate,"enddate"=>$enddate); array_push($progress,$arr); $task["title"]=$title; }else{ $task["investment"]=$task["investment"].$investment; if(!empty($stage)){ $arr=array("stage"=>$stage,"startdate"=>$startdate,"enddate"=>$enddate); array_push($progress,$arr); } } } $task['progress']=$progress; if($i==$end) array_push($tasklist,$task); } //var_dump($tasklist); echo "读出:".$inputrow."条记录."; writedata($tasklist,$name); } //写入数据库 function writedata($tasklist,$name) { include_once "../mysql.php"; $link=new mysql; //逐条取出数据, $inputrow=0; foreach($tasklist as $task){ // //如果读取的数据中id非空,做修改处理,否则做新增处理 if($task["id"]>0) { $inputrow++; $updatesql='UPDATE task SET target=?,title=?,investment=?,modifier=?,modtime=now() WHERE id='.$task['id']; $link->update($updatesql,array($task['target'],$task['title'],$task['investment'],$name)); if(is_array($task["progress"])){ $prosql='SELECT taskid FROM progress WHERE taskid=?'; $prores=$link->getAll($prosql,array($task["id"])); if(count($prores)>0){$link->query("DELETE FROM progress WHERE taskid=".$task["id"]);} foreach($task["progress"] as $progress) { $inpsql='INSERT INTO progress(taskid,stage,startdate,enddate,modifier,modtime) VALUES (?,?,?,?,?,now())'; $pres=$link->insert($inpsql,array($task["id"],$progress['stage'],$progress['startdate'],$progress['enddate'],'Excel导入')); if($pres==0) echo "{存入".$progress['stage'].$progress['startdate'].$progress['enddate']."失败}"; } } }else{ $gtsql='SELECT id FROM generaltask WHERE name=?'; $gtres=$link->getAll($gtsql,array($task["generaltask"])); if(count($gtres)>0){ $generaltaskid=$gtres[0]['id']; }else { $gtsql='INSERT INTO generaltask(name) VALUES(?)'; $generaltaskid=$link->insert($gtsql,array($task["generaltask"])); } $resql='SELECT id FROM task WHERE type=? and generaltaskid=? and target=? and title=?'; $reres=$link->getAll($resql,array($task['type'],$generaltaskid,$task['target'],$task['title'])); if(count($reres)<1) { $insertsql='INSERT INTO task(type,generaltaskid,target,title,investment,modifier) VALUES(?,?,?,?,?,?)'; //echo $insertsql; $id=$link->insert($insertsql,array($task['type'],$generaltaskid,$task['target'],$task['title'],$task['investment'],$name)); if($id>0){ $inputrow++; if(is_array($task['progress'])){ foreach($task['progress'] as $progress) { $inpsql='INSERT INTO progress(taskid,stage,startdate,enddate,modifier) VALUES (?,?,?,?,?)'; $pres=$link->insert($inpsql,array($id,$progress['stage'],$progress['startdate'],$progress['enddate'],$name)); } } } }else{ if(is_array($task["progress"])){ $inputrow++; $prosql='SELECT id FROM progress WHERE taskid=?'; $prores=$link->getAll($prosql,array($reres[0]['id'])); if(count($prores)>0){$link->query("DELETE FROM progress WHERE taskid=".$reres[0]['id']);} foreach($task["progress"] as $progress) { $inpsql='INSERT INTO progress(taskid,stage,startdate,enddate,modifier,modtime) VALUES (?,?,?,?,?,now())'; $pres=$link->insert($inpsql,array($reres[0]['id'],$progress['stage'],$progress['startdate'],$progress['enddate'],'Excel导入')); if($pres==0) echo "{存入".$progress['stage'].$progress['startdate'].$progress['enddate']."失败}"; } } } } } echo "存入:".$inputrow."记录"; }
C++
UTF-8
617
2.515625
3
[]
no_license
#include <Wire.h> #include <LSM6.h> #include "compl_filter.h" LSM6 imu; char report[150]; void setup() { Serial.begin(9600); Wire.begin(); if (!imu.init()) { Serial.println("Failed to detect and initialize IMU!"); while (1); } imu.enableDefault(); } void loop() { int16_t x, y, z; compl_filter_read_angle(&imu, &x, &y, &z); imu.read(); snprintf(report, sizeof(report), "A: %6d %6d %6d G: %6d %6d %6d", imu.a.x, imu.a.y, imu.a.z, imu.g.x, imu.g.y, imu.g.z); snprintf(report, sizeof(report), "Angle: %6d %6d %6d", x, y, z); Serial.println(report); delay(100); }
TypeScript
UTF-8
615
3.03125
3
[]
no_license
// -------------define.d.ts---------------------- interface CodeGenOpt { className: string; properties: Property[]; } interface Property { name: string, optional: boolean, type: PBType } //-------------ClientCodeTemplate.ts------------------------- export function getCode(opt: CodeGenOpt) { return `class ${opt.className} { ${opt.properties.map(getProperties).join("\t")} }` } const typeDict = { [PBType.Int32]: "number", [PBType.Int64]: "number", } function getProperties({ name, type, optional }: Property) { return `${name}${optional ? "?" : ""}: ${typeDict[type]};` }
C++
UTF-8
10,395
3.078125
3
[]
no_license
/* * Maze Explorer for the Arduino Game Console * https://www.gameinstance.com/post/51/Maze-Explorer-game * * GameInstance.com * 2017 */ #include <GameConsole.h> struct Point { unsigned char m_x, m_y; void Init(unsigned char x, unsigned char y) { // m_x = x; m_y = y; } }; struct Maze { // can travel up bool UpBlocked(unsigned int i) { // if (PLAIN) { // return (m_map[i] & 0x01); } return (m_map[i / 4] & (0x01 << ((3 - (i % 4)) * 2))); } // can travel left bool LeftBlocked(unsigned int i) { // if (PLAIN) { // return (m_map[i] & 0x02); } return (m_map[i / 4] & (0x02 << ((3 - (i % 4)) * 2))); } /* /// maze size static const unsigned char W = 6, H = 4; /// the maze unsigned char m_map[(int)ceil(W * H / (PLAIN ? 1 : 4))] { 0xF5, 0xDA, 0xCA, 0x89, 0x2D, 0x54 // 3, 3, 1, 1, 3, 1, // 2, 2, 3, 0, 2, 2, // 2, 0, 2, 1, 0, 2, // 3, 1, 1, 1, 1, 0 }; /// plain data representation static const bool PLAIN = false; */ /// maze size static const unsigned char W = 9, H = 6; /// the maze unsigned char m_map[W * H] { 3, 1, 1, 1, 1, 3, 1, 3, 1, //1, 1, 3, 1, 3, 1, 0, 2, 2, 2, 1, //3, 0, 3, 2, 2, 1, 1, 0, 2, 2, 3, //0, 3, 2, 2, 1, 3, 1, 1, 0, 0, 3, //1, 0, 2, 0, 2, 2, 1, 3, 1, 2, 0, //3, 0, 3, 1, 0, 1, 1, 0, 2, 1, 0, //2, 1 }; /// plain data representation static const bool PLAIN = true; }; struct Walker : public Point { static const byte TICKNESS = 6; static const unsigned char MASK[3]; unsigned char m_direction; signed char m_dx, m_dy; Walker() : Point(), m_direction(0), m_dx(0), m_dy(0) { // } /// still moving bool IsMoving() { // return (m_direction != 0); } /// moves horizontally void GoX(signed char x, const Maze& maze) { // if ((m_x + maze.H < 0) || (m_x + x > maze.W - 1)) { // return; } if (x < 0) { // go left if (maze.LeftBlocked(m_x + m_y * maze.W)) { // left is blocked return; } m_direction = 1; return; } if (x > 0) { // go right if (maze.LeftBlocked(m_x + x + m_y * maze.W)) { // right is blocked return; } m_direction = 3; return; } return; } /// moves vertically bool GoY(signed char y, const Maze& maze) { // if ((m_y + y < 0) || (m_y + y > maze.H - 1)) { // return; } if (y < 0) { // go up if (maze.UpBlocked(m_x + m_y * maze.W)) { // up is blocked return; } m_direction = 2; return; } if (y > 0) { // go down if (maze.UpBlocked(m_x + (m_y + y) * maze.W)) { // down is blocked return; } m_direction = 4; return; } return; } /// moves the walker bool Move(unsigned char width, unsigned char height) { // if (m_direction == 1) { // going left m_dx -= 1; if (m_dx <= -width) { // m_dx = 0; m_x -= 1; m_direction = 0; } } if (m_direction == 2) { // going up m_dy -= 1; if (m_dy <= -height) { // m_dy = 0; m_y -= 1; m_direction = 0; } } if (m_direction == 3) { // going right m_dx += 1; if (m_dx >= width) { // m_dx = 0; m_x += 1; m_direction = 0; } } if (m_direction == 4) { // going down m_dy += 1; if (m_dy >= height) { // m_dy = 0; m_y += 1; m_direction = 0; } } } }; const unsigned char Walker::MASK[3] = {0x0E, 0x15, 0x17}; class MazeExplorer : public GameConsole { public: /// default constructor MazeExplorer() : GameConsole(), m_state(0), m_nowTime(0), m_lastTime(0) { // }; /// destructor virtual ~MazeExplorer() { // }; /// the game index unsigned char GameIndex() { // return 2; } /// game setup method void Setup() { // GameConsole::Setup(); m_lcd.Contrast(45); m_lcd.Fill(false); m_lcd.Text("MAZE", 31, 10, true); m_lcd.Text("EXPLORER", 19, 22, true); m_lcd.Update(); delay(2000); if (IsPressed(BUTTON_A) && IsPressed(BUTTON_B)) { // reseting high score m_storage.SetScore(0); } } /// the main method implementation void Execute() { // m_nowTime = millis(); if (m_state == 0) { // initial game state // m_lastTime = m_nowTime; m_walker.Init(0, 0); m_final.Init(0, 3); m_state = 1; } if (m_state == 1) { // reading input // m_joystickX = GetAxis(AXIS_X) / 64; m_joystickY = GetAxis(AXIS_Y) / 64; m_state = 2; } if (m_state == 2) { // moving // if (m_walker.IsMoving()) { // m_walker.Move(CHANNEL_WIDTH, CHANNEL_HEIGHT); } if (!m_walker.IsMoving()) { // if (abs(m_joystickX) > abs(m_joystickY)) { // if (m_joystickX > 0) { // right m_walker.GoX(1, m_maze); } else if (m_joystickX < 0) { // left m_walker.GoX(-1, m_maze); } } else { // if (m_joystickY > 0) { // up m_walker.GoY(-1, m_maze); } else if (m_joystickY < 0) { // down m_walker.GoY(1, m_maze); } } } m_state = 3; } if (m_state == 3) { // display // clear screen // m_lcd.Fill(false); ClearDisplay(); // maze for (unsigned char i = 0; i < m_maze.W * m_maze.H; i ++) { // if (m_maze.UpBlocked(i)) { // top m_lcd.Line( SCREEN_OFFSET_X + x + (i % m_maze.W) * CHANNEL_WIDTH - dx, SCREEN_OFFSET_Y + y + (i / m_maze.W) * CHANNEL_HEIGHT - dy, SCREEN_OFFSET_X + x + (i % m_maze.W) * CHANNEL_WIDTH + dx, SCREEN_OFFSET_Y + y + (i / m_maze.W) * CHANNEL_HEIGHT - dy, true); } if (m_maze.LeftBlocked(i)) { // left m_lcd.Line( SCREEN_OFFSET_X + x + (i % m_maze.W) * CHANNEL_WIDTH - dx, SCREEN_OFFSET_Y + y + (i / m_maze.W) * CHANNEL_HEIGHT - dy, SCREEN_OFFSET_X + x + (i % m_maze.W) * CHANNEL_WIDTH - dx, SCREEN_OFFSET_Y + y + (i / m_maze.W) * CHANNEL_HEIGHT + dy, true); } if (i % m_maze.W == m_maze.W - 1) { // right - end m_lcd.Line( SCREEN_OFFSET_X + x + (i % m_maze.W) * CHANNEL_WIDTH + dx + 1, SCREEN_OFFSET_Y + y + (i / m_maze.W) * CHANNEL_HEIGHT - dy, SCREEN_OFFSET_X + x + (i % m_maze.W) * CHANNEL_WIDTH + dx + 1, SCREEN_OFFSET_Y + y + (i / m_maze.W) * CHANNEL_HEIGHT + dy, true); } if (i / m_maze.W == m_maze.H - 1) { // bottom - end m_lcd.Line( SCREEN_OFFSET_X + x + (i % m_maze.W) * CHANNEL_WIDTH - dx, SCREEN_OFFSET_Y + y + (i / m_maze.W) * CHANNEL_HEIGHT + dy, SCREEN_OFFSET_X + x + (i % m_maze.W) * CHANNEL_WIDTH + dx, SCREEN_OFFSET_Y + y + (i / m_maze.W) * CHANNEL_HEIGHT + dy, true); } } // walker unsigned char column; for (int i = 0; i < Walker::TICKNESS; i ++) { // by columns column = Walker::MASK[(i < 3) ? i : Walker::TICKNESS - i - 1]; for (int j = 0; j < Walker::TICKNESS - 1; j ++) { // by rows if (column & (0x01 << j)) { // m_lcd.Point( SCREEN_OFFSET_X + m_walker.m_x * CHANNEL_WIDTH + m_walker.m_dx + i + 2, SCREEN_OFFSET_Y + m_walker.m_y * CHANNEL_HEIGHT + m_walker.m_dy + j + 2, true); } else { // m_lcd.Point( SCREEN_OFFSET_X + m_walker.m_x * CHANNEL_WIDTH + m_walker.m_dx + i + 2, SCREEN_OFFSET_Y + m_walker.m_y * CHANNEL_HEIGHT + m_walker.m_dy + j + 2, false); } } } // final point m_lcd.Point( SCREEN_OFFSET_X + m_final.m_x * CHANNEL_WIDTH + CHANNEL_WIDTH / 2, SCREEN_OFFSET_Y + m_final.m_y * CHANNEL_HEIGHT + CHANNEL_HEIGHT / 2, true); m_lcd.Update(); m_state = 4; } if (m_state == 4) { // destination test // if ((m_walker.m_x == m_final.m_x) && (m_walker.m_y == m_final.m_y)) { // m_state = 6; } else { // m_state = 5; } } if (m_state == 5) { // waiting state // if (m_nowTime > m_lastTime + 40) { // m_lastTime = m_nowTime; m_state = 1; } } if (m_state == 6) { // game complete // m_lcd.Text("Congrats!", 16, 4, true); m_lcd.Update(); m_state = 7; } if (m_state == 7) { // end state // } } private: /// on-screen maze offset unsigned char SCREEN_OFFSET_X = 1, SCREEN_OFFSET_Y = 0; /// maze channel dimensions static const unsigned char CHANNEL_WIDTH = 9, CHANNEL_HEIGHT = 8; /// the state of the automate byte m_state; /// high-res time probes unsigned long m_nowTime, m_lastTime; /// time divider unsigned char m_timeDivider; /// the walking character Walker m_walker; /// the maze Maze m_maze; /// the final destination Point m_final; /// alignment variables unsigned char dx = CHANNEL_WIDTH / 2, dy = CHANNEL_HEIGHT / 2, x = dx, y = dy; /// joystick position signed char m_joystickX, m_joystickY; }; /// the game instance MazeExplorer game; void setup() { // put your setup code here, to run once: game.Setup(); } void loop() { // put your main code here, to run repeatedly: game.Loop(); }
Shell
UTF-8
1,301
2.59375
3
[]
no_license
#!/bin/bash TEST_FILE=./data/test_data_1.txt cp ./data/training_data_1.txt ./data/train_data INPUT_FILE=./data/train_data sed '1d' $TEST_FILE | awk -F "\t" '{print $3}' > ./data/test_feature sed '1d' $TEST_FILE | awk '{print $1}' | sed 's/True/1/;s/False/0/' > ./data/test_label n=`python src/findmax_N.py ./data/train_feature` ((n=n+1)) ### for iteration END=5 for((i=1;i<=END;i++)); do sed '1d' $INPUT_FILE | awk '{print $1}' | sed 's/True/1/;s/False/0/' > ./data/train_label sed '1d' $INPUT_FILE | awk -F "\t" '{print $3}' > ./data/train_feature #### Decision Tree python ./src/vfdt.py --train_feature ./data/train_feature --train_label ./data/train_label \ --test_feature ./data/test_feature --test_label ./data/test_label --num $n --output_assign results/assign_file #### Prototype learning ### pre-train python2 ./src/rcnn_fc_softmax.py data/training_model_by_word2vec_1.vector data/train_feature \ ./data/train_label ./data/test_feature ./data/test_label ./data/train_lstm_output.npy ./data/test_lstm_output.npy ./results/rule_data_list ### prototype python2 ./src/prototype_save_distance.py results/assign_file ./data/train_lstm_output.npy ./data/train_label \ ./data/test_lstm_output.npy ./data/test_label ./results/similarity ### data reweight done
Java
UTF-8
808
1.835938
2
[]
no_license
package com.livegoods.recommendation.controller; import com.livegoods.commons.pojo.Result; import com.livegoods.pojo.Items; import com.livegoods.recommendation.service.RecommendationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin public class RecommendationController { @Autowired private RecommendationService recommendationService; @RequestMapping("/recommendation") public Result<Items> recommendation(String city){ return recommendationService.getRecommendations(city); } }
Go
UTF-8
410
2.828125
3
[ "MIT" ]
permissive
package battery type DeviceChemistry byte const ( Other DeviceChemistry = 1 << iota Unknown LeadAcid NickelCadmium NickelMetalHydride LithiumIon ZincAir LithiumPolymer ) func (d DeviceChemistry) String() string { factors := [...]string{ "Other", "Unknown", "Lead Acid", "Nickel Cadmium", "Nickel metal hydride", "Lithium-ion", "Zinc air", "Lithium Polymer", } return factors[d] }
Java
ISO-8859-10
627
2.8125
3
[]
no_license
/** * Esta es la clase principal del programa, esta es la que se debe ejecutar. * * @author Santiago Avendao y Samuel Cadavid * @version 11 de noviembre de 2017 */ import java.util.Scanner; import java.io.*; public class Principal { public static void main(String [] args) throws Exception { String nombreArchivo = "treeEtc.txt"; File archivo = new File (nombreArchivo); // LectorArchivo lector = new LectorArchivo(); //lector.muestraContenido(nombreArchivo); // lector.contarProfundidad(archivo); Arbol arb = new Arbol(); arb.arreglo(archivo); } }
Markdown
UTF-8
913
2.59375
3
[ "MIT" ]
permissive
amd-help(1) -- display the manpage for an amd command ===================================================== SYNOPSIS -------- `amd help` <command> DESCRIPTION ----------- `amd help` is a fallback to access the manpages when they have not been linked properly. It is also a godsend for people who enjoy remembering subtly different ways to do the same thing for every command line tool in their arsenal. Use man(1) e.g. `man amd`, `man amd-check`, `man amd-graph`, etc. if at all possible. If that's not working and it's not worth the effort to fix it, `amd help` is here for you. It's just a simple wrapper that invokes `man`, but it always knows where the manpages are located regardless of MANPATH or ~/.manpath settings. EXAMPLES -------- * amd help: Show the manpage for the main `amd` command * amd help check: Show the manpage for the `amd check` command AMD --- Part of the amd(1) suite
Java
UTF-8
635
3.515625
4
[]
no_license
package by.epam.course.cycles; /*Составить таблицу значений функции y = 5 - x2 /2 на отрезке [-5; 5] с шагом 0.5. */ public class CyclesTask13 { public static void solution() { double a;// начальная точка отрезка double b;// конечная точка отрезка double h;// шаг double y; a = -9; b = 6; h = 1; double i = a; while (i <= b) { y = 5 - (Math.pow(i, 2) / 2); System.out.println("значение функции y в точке " + i + " равно " + y); i = i + h; } } }
Java
UTF-8
320
1.84375
2
[]
no_license
package com.mygdx.xo; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Game; import com.badlogic.gdx.Screen; import view.GameScreen; public class MyGdxGame extends Game { private Screen gameScreen; @Override public void create() { gameScreen = new GameScreen(); setScreen(gameScreen); } }
Markdown
UTF-8
3,289
2.96875
3
[]
no_license
# Stream Handler ![Stream handler](figures/stream-handler-1.png) Quiver stream handler is designed following the Unix Philosophy. Unix process is well known for their extensibility through the uniform stream interfaces `STDIN`, `STDOUT`, and `STDERR`. Similarly stream handler is designed to have uniform interface across all kinds of programs to make them as easily composable as Unix processes. All quiver stream handler accept an `args` as their first argument, which is the equivalent of command line arguments. The second argument inputStreamable is a streamable object corresponds to STDIN. Finally the handler asynchronously returns either an error (STDERR) or a resultStreamable (STDOUT). ## API Specification ```javascript api streamHandler = function(args, inputStreamable, callback(err, resultStreamable)); ``` The `processStream3()` function signature arrived in the previous section is very close to the interface of a stream handler. Other than accepting and returning streamable, a stream handler also accepts an additional `args` argument which serve as key-value argument. The `args` argument allow stream handler functions to accept arbitrary number of keyword arguments while all have the same function signature. ## Stream Handler and HTTP Stream handler works similarly with typical HTTP handlers, which accept a HTTP request and return a HTTP response. In a quiver web application some stream handlers are mapped to the front-facing HTTP server to process HTTP requests. But most of the time stream handlers are used internally by forming a graph of stream handlers that communicate with each others. More importantly, stream handler is designed to be protocol-neutral and can be adapted to use for protocols other than HTTP. Stream handler is not obligated to understand standard HTTP headers such as transfer encoding, making it much simpler to implement and understand. The `args` argument is more often mapped to the query string parameters in HTTP request, but is also sometimes mapped to certain HTTP headers as long as it does not affect the interpretation of the input streamable content. Other than that stream handler only return a result streamable which correspond to the HTTP response body, but there is no equivalance of HTTP response headers. Although the result streamable may contain optional meta data such as content type and content length, it is not allowed to carry information that affect the interpretation of the stream content such as transfer encoding and cookies. On error the stream handler return an error object optionally containing HTTP error status code and a short error message to be written to the response body. By default undefined or invalid error code will cause the server to return status code 500 Internal Server Error. Stream handler is designed to handle a subset of HTTP that follows Fielding's RESTful architecture design. With minimal protocol constraint, implementing stream handlers is almost as simple as writing plain JavaScript functions. When stream handlers are implemented to be pure from side effects, there are many functional programming techniques that can be applied to the stream handler to gain significant performance optimization from it. ## Next: [Http Handler](05-http-handler.md)
Java
UTF-8
1,255
1.945313
2
[]
no_license
/* * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.glass.events; import java.lang.annotation.Native; public class MouseEvent { @Native final static public int BUTTON_NONE = 211; @Native final static public int BUTTON_LEFT = 212; @Native final static public int BUTTON_RIGHT = 213; @Native final static public int BUTTON_OTHER = 214; @Native final static public int DOWN = 221; @Native final static public int UP = 222; @Native final static public int DRAG = 223; @Native final static public int MOVE = 224; @Native final static public int ENTER = 225; @Native final static public int EXIT = 226; @Native final static public int CLICK = 227; // synthetic /** * Artificial WHEEL event type. * This kind of mouse event is NEVER sent to an app. * The app must listen to Scroll events instead. * This identifier is required for internal purposes. */ @Native final static public int WHEEL = 228; }
Python
UTF-8
36,672
2.75
3
[ "Apache-2.0" ]
permissive
""" Classes for loading raw graph""" import os import csv import numpy as np # TODO(xiangsx): Framework agnostic later import torch as th import dgl from dgl.data import save_graphs, load_graphs from .utils import save_info, load_info from .utils import field2idx, get_id from .csv_feature_loader import NodeFeatureLoader, EdgeFeatureLoader from .csv_feature_loader import EdgeLoader from .csv_label_loader import NodeLabelLoader, EdgeLabelLoader def _gen_reverse_etype(etype): return (etype[2], 'rev-'+etype[1], etype[0]) class GraphLoader(object): r""" Generate DGLGraph by parsing files. GraphLoader generate DGLGraph by collecting EdgeLoaders, FeatureLoaders and LabelLoders and parse them iteratively. Parameters ---------- name: str, optional name of the graph. default: 'graph' edge_loader: list of EdgeLoader edge loaders to load graph edges default: None feature_loader: list of NodeFeatureLoader and EdgeFeatureLoader feature loaders to load graph features and edges default: None label_loader: list of NodeLabelLoader and EdgeLabelLoader label loaders to load labels/ground-truth and edges default: None verbose: bool, optional Whether print debug info during parsing Default: False Attributes ---------- node2id: dict of dict The mappings from raw node id/name to internal node id. {node_type : {raw node id(string/int): dgl_id}} id2node: dict of dict The mappings from internal node id to raw node id/name. {node_type : {raw node id(string/int): dgl_id}} label_map: dict of dict The mapping from internal label id to original label. {node/edge_type: {label id(int) : raw label(string/int)}} graph: DGLGraph The generated DGLGraph Notes ----- **EdgeLoader is used to add edges that neither have features nor appeared in edge labels.** If one edge appears in both appendEdge and appendLabel, it will be added twice. **But if one edge appears in both EdgeFeatureLoader and EdgeLabelLoader, it will only be added once. **For each edge type, there should not exit duplicated edges** Examples -------- ** Creat a FeatureLoader to load user features from u.csv.** >>> user_loader = dgl.data.FeatureLoader(input='u.csv', separator="|") >>> user_loader.addCategoryFeature(cols=["id", "gender"], node_type='user') ** create node label loader to load labels ** >>> label_loader = dgl.data.NodeLabelLoader(input='label.csv', separator="|") >>> label_loader.addTrainSet([0, 1], rows=np.arange(start=0, stop=100)) ** Create a Graph Loader ** >>> graphloader = dgl.data.GraphLoader(name='example') >>> graphloader.appendFeature(user_loader) >>> graphloader.appendLabel(label_loader) ** Process the graph inputs ** >>> graphloader.process() >>> g = graphloader.graph """ def __init__(self, name='graph', edge_loader=None, feature_loader=None, label_loader=None, verbose=False): self._name = name if edge_loader is not None: if not isinstance(edge_loader, list): raise RuntimeError("edge loaders should be a list of EdgeLoader") self._edge_loader = edge_loader else: self._edge_loader = [] if feature_loader is not None: if not isinstance(feature_loader, list): raise RuntimeError("feature loaders should be " \ "a list of NodeFeatureLoader and EdgeFeatureLoader") self._feature_loader = feature_loader else: self._feature_loader = [] if label_loader is not None: if not isinstance(label_loader, list): raise RuntimeError("label loaders should be " \ "a list of NodeLabelLoader and EdgeLabelLoader") self._label_loader = label_loader else: self._label_loader = [] self._add_reverse = False self._graph = None self._verbose = verbose self._node_dict = {} self._label_map = None self._is_multilabel = False def appendEdge(self, edge_loader): """ Add edges into graph Parameters ---------- edge_loader: EdgeLoader edge loaders to load graph edges default: None Examples -------- ** create edge loader to load edges ** >>> edge_loader = dgl.data.EdgeLoader(input='edge.csv', separator="|") >>> edge_loader.addEdges([0, 1]) ** Append edges into graph loader ** >>> graphloader = dgl.data.GraphLoader(name='example') >>> graphloader.appendEdge(edge_loader) """ if not isinstance(edge_loader, EdgeLoader): raise RuntimeError("edge loader should be a EdgeLoader") self._edge_loader.append(edge_loader) def appendFeature(self, feature_loader): """ Add features and edges into graph Parameters ---------- feature_loader: NodeFeatureLoader or EdgeFeatureLoader feature loaders to load graph edges default: None Examples -------- ** Creat a FeatureLoader to load user features from u.csv.** >>> user_loader = dgl.data.FeatureLoader(input='u.csv', separator="|") >>> user_loader.addCategoryFeature(cols=["id", "gender"], node_type='user') ** Append features into graph loader ** >>> graphloader = dgl.data.GraphLoader(name='example') >>> graphloader.appendFeature(user_loader) """ if not isinstance(feature_loader, NodeFeatureLoader) and \ not isinstance(feature_loader, EdgeFeatureLoader): raise RuntimeError("feature loader should be a NodeFeatureLoader or EdgeFeatureLoader.") self._feature_loader.append(feature_loader) def appendLabel(self, label_loader): """ Add labels and edges into graph Parameters ---------- label_loader: NodeLabelLoader or EdgeLabelLoader label loaders to load graph edges default: None Examples -------- ** create node label loader to load labels ** >>> label_loader = dgl.data.NodeLabelLoader(input='label.csv', separator="|") >>> label_loader.addTrainSet([0, 1], rows=np.arange(start=0, stop=100)) ** Append labels into graph loader ** >>> graphloader = dgl.data.GraphLoader(name='example') >>> graphloader.appendLabel(label_loader) """ if not isinstance(label_loader, NodeLabelLoader) and \ not isinstance(label_loader, EdgeLabelLoader): raise RuntimeError("label loader should be a NodeLabelLoader or EdgeLabelLoader.") self._label_loader.append(label_loader) def addReverseEdge(self): """ Add Reverse edges with new relation type. addReverseEdge works for heterogenous graphs. It adds a new relation type for each existing relation. For example, with relation ('head', 'rel', 'tail'), it will create a new relation type ('tail', 'rev-rel', 'head') and adds edges belong to ('head', 'rel', 'tail') into new relation type with reversed head and tail entity order. Notes ----- Edge features are ignored. If the source edges have builtin features such as `train_mask`, `valid_mask` and `test_mask`, the corresponding `rev_train_mask`, `rev_valid_mask` and `rev_test_mask` features are added for the reversed edges. Example ------- ** create edge loader to load edges ** >>> edge_loader = dgl.data.EdgeLoader(input='edge.csv', separator="|") >>> edge_loader.addEdges([0, 1], src_type='user', edge_type='likes', dst_type='movie') ** Append edges into graph loader ** >>> graphloader = dgl.data.GraphLoader(name='example') >>> graphloader.appendEdge(edge_loader) ** add reversed edges into graph ** >>> graphloader.addReverseEdge() ** process graph ** >>> graphloader.process() """ self._add_reverse = True def process(self): """ Parsing EdgeLoaders, FeatureLoaders and LabelLoders to build the DGLGraph """ graphs = {} # edge_type: (s, d, feat) nodes = {} edge_feat_results = [] node_feat_results = [] edge_label_results = [] node_label_results = [] if self._verbose: print('Start processing graph structure ...') # we first handle edges for edge_loader in self._edge_loader: # {edge_type: (snids, dnids)} edge_result = edge_loader.process(self._node_dict) for edge_type, vals in edge_result.items(): snids, dnids = vals if edge_type in graphs: graphs[edge_type] = (np.concatenate((graphs[edge_type][0], snids)), np.concatenate((graphs[edge_type][1], dnids)), None) else: graphs[edge_type] = (snids, dnids, None) # we assume edges have features is not loaded by edgeLoader. for feat_loader in self._feature_loader: if feat_loader.node_feat is False: # {edge_type: (snids, dnids, feats)} edge_feat_result = feat_loader.process(self._node_dict) edge_feat_results.append(edge_feat_result) for edge_type, vals in edge_feat_result.items(): feats = {} snids, dnids, _ = vals[next(iter(vals.keys()))] for feat_name, val in vals.items(): assert val[0].shape[0] == val[1].shape[0], \ 'Edges with edge type {} has multiple features, ' \ 'But some features do not cover all the edges.' \ 'Expect {} edges, but get {} edges with edge feature {}.'.format( edge_type if edge_type is not None else "", snids.shape[0], val[0].shape[0], feat_name) feats[feat_name] = val[2] if edge_type in graphs: new_feats = {} for feat_name, feat in feats: assert graphs[edge_type][2] is not None, \ 'All edges under edge type {} should has features.' \ 'Please check if you use EdgeLoader to load edges ' \ 'for the same edge type'.format( edge_type if edge_type is not None else "") assert feat_name not in graphs[edge_type][2], \ 'Can not concatenate edges with features with other edges without features' assert graphs[edge_type][2][feat_name].shape[1:] == feat.shape[1:], \ 'Can not concatenate edges with different feature shape' new_feats[feat_name] = np.concatenate((graphs[edge_type][2][feat_name], feat)) graphs[edge_type] = (np.concatenate((graphs[edge_type][0], snids)), np.concatenate((graphs[edge_type][1], dnids)), new_feats) else: graphs[edge_type] = (snids, dnids, feats) else: # {node_type: {feat_name :(node_ids, node_feats)}} node_feat_result = feat_loader.process(self._node_dict) node_feat_results.append(node_feat_result) for node_type, vals in node_feat_result.items(): nids, _ = vals[next(iter(vals.keys()))] max_nid = int(np.max(nids)) + 1 if node_type in nodes: nodes[node_type] = max(nodes[node_type]+1, max_nid) else: nodes[node_type] = max_nid for label_loader in self._label_loader: if label_loader.node_label is False: # {edge_type: ((train_snids, train_dnids, train_labels, # valid_snids, valid_dnids, valid_labels, # test_snids, test_dnids, test_labels)} if self._label_map is None: edge_label_result = label_loader.process(self._node_dict) self._label_map = label_loader.label_map else: edge_label_result = label_loader.process(self._node_dict, label_map=self._label_map) for idx, label in self._label_map.items(): assert label == label_loader.label_map[idx], \ 'All label files should have the same label set' edge_label_results.append(edge_label_result) for edge_type, vals in edge_label_result.items(): train_snids, train_dnids, train_labels, \ valid_snids, valid_dnids, valid_labels, \ test_snids, test_dnids, test_labels = vals if edge_type in graphs: # If same edge_type also has features, # we expect edges have labels also have features. # Thus we avoid add edges twice. # Otherwise, if certain edge_type has no featus, add it directly if graphs[edge_type][2] is None: snids = graphs[edge_type][0] dnids = graphs[edge_type][1] if train_snids is not None: snids = np.concatenate((snids, train_snids)) dnids = np.concatenate((dnids, train_dnids)) if valid_snids is not None: snids = np.concatenate((snids, valid_snids)) dnids = np.concatenate((dnids, valid_dnids)) if test_snids is not None: snids = np.concatenate((snids, test_snids)) dnids = np.concatenate((dnids, test_dnids)) graphs[edge_type] = (snids, dnids, None) else: snids = np.empty((0,), dtype='long') dnids = np.empty((0,), dtype='long') if train_snids is not None: snids = np.concatenate((snids, train_snids)) dnids = np.concatenate((dnids, train_dnids)) if valid_snids is not None: snids = np.concatenate((snids, valid_snids)) dnids = np.concatenate((dnids, valid_dnids)) if test_snids is not None: snids = np.concatenate((snids, test_snids)) dnids = np.concatenate((dnids, test_dnids)) graphs[edge_type] = (snids, dnids, None) else: # {node_type: (train_nids, train_labels, # valid_nids, valid_labels, # test_nids, test_labels)} if self._label_map is None: node_label_result = label_loader.process(self._node_dict) self._label_map = label_loader.label_map else: node_label_result = label_loader.process(self._node_dict, label_map=self._label_map) for idx, label in self._label_map.items(): assert label == label_loader.label_map[idx], \ 'All label files should have the same label set' node_label_results.append(node_label_result) for node_type, vals in node_label_result.items(): train_nids, _, valid_nids, _, test_nids, _ = vals max_nid = 0 if train_nids is not None: max_nid = max(int(np.max(train_nids))+1, max_nid) if valid_nids is not None: max_nid = max(int(np.max(valid_nids))+1, max_nid) if test_nids is not None: max_nid = max(int(np.max(test_nids))+1, max_nid) if node_type in nodes: nodes[node_type] = max(nodes[node_type], max_nid) else: nodes[node_type] = max_nid if self._verbose: print('Done processing graph structure.') print('Start building dgl graph.') # build graph if len(graphs) > 1: assert None not in graphs, \ 'With heterogeneous graph, all edges should have edge type' assert None not in nodes, \ 'With heterogeneous graph, all nodes should have node type' graph_edges = {} for key, val in graphs.items(): graph_edges[key] = (val[0], val[1]) if self._add_reverse: graph_edges[_gen_reverse_etype(key)] = (val[1], val[0]) for etype, (src_nids, dst_nids) in graph_edges.items(): src_max_nid = int(np.max(src_nids))+1 dst_max_nid = int(np.max(dst_nids))+1 if etype[0] in nodes: nodes[etype[0]] = max(nodes[etype[0]], src_max_nid) else: nodes[etype[0]] = src_max_nid if etype[2] in nodes: nodes[etype[2]] = max(nodes[etype[2]], dst_max_nid) else: nodes[etype[2]] = dst_max_nid g = dgl.heterograph(graph_edges, num_nodes_dict=nodes) for edge_type, vals in graphs.items(): # has edge features if vals[2] is not None: for key, feat in vals[2].items(): g.edges[edge_type].data[key] = th.tensor(feat, dtype=th.float) else: g = dgl.graph((graphs[None][0], graphs[None][1]), num_nodes=nodes[None]) # has edge features if graphs[None][2] is not None: for key, feat in graphs[None][2].items(): g.edata[key] = th.tensor(feat, dtype=th.float) # no need to handle edge features # handle node features for node_feats in node_feat_results: # {node_type: (node_ids, node_feats)} for node_type, vals in node_feats.items(): if node_type is None: for key, feat in vals.items(): g.ndata[key] = th.tensor(feat[1], dtype=th.float) else: for key, feat in vals.items(): g.nodes[node_type].data[key] = th.tensor(feat[1], dtype=th.float) if self._verbose: print('Done building dgl graph.') print('Start processing graph labels...') train_edge_labels = {} valid_edge_labels = {} test_edge_labels = {} # concatenate all edge labels for edge_label_result in edge_label_results: for edge_type, vals in edge_label_result.items(): train_snids, train_dnids, train_labels, \ valid_snids, valid_dnids, valid_labels, \ test_snids, test_dnids, test_labels = vals # train edge labels if train_snids is not None: if edge_type in train_edge_labels: train_edge_labels[edge_type] = ( np.concatenate((train_edge_labels[edge_type][0], train_snids)), np.concatenate((train_edge_labels[edge_type][1], train_dnids)), None if train_labels is None else \ np.concatenate((train_edge_labels[edge_type][2], train_labels))) else: train_edge_labels[edge_type] = (train_snids, train_dnids, train_labels) # valid edge labels if valid_snids is not None: if edge_type in valid_edge_labels: valid_edge_labels[edge_type] = ( np.concatenate((valid_edge_labels[edge_type][0], valid_snids)), np.concatenate((valid_edge_labels[edge_type][1], valid_dnids)), None if valid_labels is None else \ np.concatenate((valid_edge_labels[edge_type][2], valid_labels))) else: valid_edge_labels[edge_type] = (valid_snids, valid_dnids, valid_labels) # test edge labels if test_snids is not None: if edge_type in test_edge_labels: test_edge_labels[edge_type] = ( np.concatenate((test_edge_labels[edge_type][0], test_snids)), np.concatenate((test_edge_labels[edge_type][1], test_dnids)), None if test_labels is None else \ np.concatenate((test_edge_labels[edge_type][2], test_labels))) else: test_edge_labels[edge_type] = (test_snids, test_dnids, test_labels) # create labels and train/valid/test mask assert len(train_edge_labels) >= len(valid_edge_labels), \ 'The training set should cover all kinds of edge types ' \ 'where the validation set is avaliable.' assert len(train_edge_labels) >= len(test_edge_labels), \ 'The training set should cover the same edge types as the test set.' for edge_type, train_val in train_edge_labels.items(): train_snids, train_dnids, train_labels = train_val if edge_type in valid_edge_labels: valid_snids, valid_dnids, valid_labels = valid_edge_labels[edge_type] else: valid_snids, valid_dnids, valid_labels = None, None, None if edge_type in test_edge_labels: test_snids, test_dnids, test_labels = test_edge_labels[edge_type] else: test_snids, test_dnids, test_labels = None, None, None u, v, eids = g.edge_ids(train_snids, train_dnids, return_uv=True, etype=edge_type) labels = None # handle train label if train_labels is not None: assert train_snids.shape[0] == eids.shape[0], \ 'Under edge type {}, There exists multiple edges' \ 'between some (src, dst) pair in the training set.' \ 'This is misleading and will not be supported'.format( edge_type if edge_type is not None else "") train_labels = th.tensor(train_labels) labels = th.full((g.num_edges(edge_type), train_labels.shape[1]), -1, dtype=train_labels.dtype) labels[eids] = train_labels # handle train mask train_mask = th.full((g.num_edges(edge_type),), False, dtype=th.bool) train_mask[eids] = True valid_mask = th.full((g.num_edges(edge_type),), False, dtype=th.bool) if valid_snids is not None: u, v, eids = g.edge_ids(valid_snids, valid_dnids, return_uv=True, etype=edge_type) assert valid_snids.shape[0] == eids.shape[0], \ 'Under edge type {}, There exists multiple edges' \ 'between some (src, dst) pair in the validation set.' \ 'This is misleading and will not be supported'.format( edge_type if edge_type is not None else "") # handle valid label if valid_labels is not None: assert labels is not None, \ 'We must have train_labels first then valid_labels' labels[eids] = th.tensor(valid_labels) # handle valid mask valid_mask[eids] = True test_mask = th.full((g.num_edges(edge_type),), False, dtype=th.bool) if test_snids is not None: u, v, eids = g.edge_ids(test_snids, test_dnids, return_uv=True, etype=edge_type) assert test_snids.shape[0] == eids.shape[0], \ 'Under edge type {}, There exists multiple edges' \ 'between some (src, dst) pair in the testing set.' \ 'This is misleading and will not be supported'.format( edge_type if edge_type is not None else "") # handle test label if test_labels is not None: assert labels is not None, \ 'We must have train_labels first then test_lavbels' labels[eids] = th.tensor(test_labels) # handle test mask test_mask[eids] = True # add label and train/valid/test masks into g if edge_type is None: assert len(train_edge_labels) == 1, \ 'Homogeneous graph only supports one type of labels' if labels is not None: g.edata['labels'] = labels g.edata['train_mask'] = train_mask g.edata['valid_mask'] = valid_mask g.edata['test_mask'] = test_mask else: # we have edge type assert 'train_mask' not in g.edges[edge_type].data if labels is not None: g.edges[edge_type].data['labels'] = labels g.edges[edge_type].data['train_mask'] = train_mask g.edges[edge_type].data['valid_mask'] = valid_mask g.edges[edge_type].data['test_mask'] = test_mask if self._add_reverse: reverse_edge_type = _gen_reverse_etype(edge_type) zero_train_mask = th.full(train_mask.shape, False, dtype=th.bool) zero_valid_mask = th.full(valid_mask.shape, False, dtype=th.bool) zero_test_mask = th.full(test_mask.shape, False, dtype=th.bool) g.edges[edge_type].data['rev_train_mask'] = zero_train_mask g.edges[edge_type].data['rev_valid_mask'] = zero_valid_mask g.edges[edge_type].data['rev_test_mask'] = zero_test_mask g.edges[reverse_edge_type].data['rev_train_mask'] = train_mask g.edges[reverse_edge_type].data['rev_valid_mask'] = valid_mask g.edges[reverse_edge_type].data['rev_test_mask'] = test_mask g.edges[reverse_edge_type].data['train_mask'] = zero_train_mask g.edges[reverse_edge_type].data['valid_mask'] = zero_valid_mask g.edges[reverse_edge_type].data['test_mask'] = zero_test_mask # node labels train_node_labels = {} valid_node_labels = {} test_node_labels = {} for node_labels in node_label_results: for node_type, vals in node_labels.items(): train_nids, train_labels, \ valid_nids, valid_labels, \ test_nids, test_labels = vals # train node labels if train_nids is not None: if node_type in train_node_labels: train_node_labels[node_type] = ( np.concatenate((train_node_labels[node_type][0], train_nids)), None if train_labels is None else \ np.concatenate((train_node_labels[node_type][1], train_labels))) else: train_node_labels[node_type] = (train_nids, train_labels) # valid node labels if valid_nids is not None: if node_type in valid_node_labels: valid_node_labels[node_type] = ( np.concatenate((valid_node_labels[node_type][0], valid_nids)), None if valid_labels is None else \ np.concatenate((valid_node_labels[node_type][0], valid_labels))) else: valid_node_labels[node_type] = (valid_nids, valid_labels) # test node labels if test_nids is not None: if node_type in test_node_labels: test_node_labels[node_type] = ( np.concatenate((test_node_labels[node_type][0], test_nids)), None if test_labels is none else \ np.concatenate((test_node_labels[node_type][0], test_labels))) else: test_node_labels[node_type] = (test_nids, test_labels) # create labels and train/valid/test mask assert len(train_node_labels) >= len(valid_node_labels), \ 'The training set should cover all kinds of node types ' \ 'where the validation set is avaliable.' assert len(train_node_labels) == len(test_node_labels), \ 'The training set should cover the same node types as the test set.' for node_type, train_val in train_node_labels.items(): train_nids, train_labels = train_val if node_type in valid_node_labels: valid_nids, valid_labels = valid_node_labels[node_type] else: valid_nids, valid_labels = None, None test_nids, test_labels = test_node_labels[node_type] labels = None # handle train label if train_labels is not None: train_labels = th.tensor(train_labels) labels = th.full((g.num_nodes(node_type), train_labels.shape[1]), -1, dtype=train_labels.dtype) labels[train_nids] = train_labels # handle train mask train_mask = th.full((g.num_nodes(node_type),), False, dtype=th.bool) train_mask[train_nids] = True valid_mask = None if valid_nids is not None: # handle valid label if valid_labels is not None: assert labels is not None, \ 'We must have train_labels first then valid_labels' labels[valid_nids] = th.tensor(valid_labels) # handle valid mask valid_mask = th.full((g.num_nodes(node_type),), False, dtype=th.bool) valid_mask[valid_nids] = True # handle test label if test_labels is not None: assert labels is not None, \ 'We must have train_labels first then test_labels' labels[test_nids] = th.tensor(test_labels) # handle test mask test_mask = th.full((g.num_nodes(node_type),), False, dtype=th.bool) test_mask[test_nids] = True # check for single label or multi label task num_labels = th.sum(labels) if num_labels == labels.shape[0]: # single label if self._verbose: print('Single Label') _, labels = labels.max(dim=1) self._is_multilabel = False else: if self._verbose: print('Multi Label') self._is_multilabel = True # add label and train/valid/test masks into g if node_type is None: assert len(train_node_labels) == 1, \ 'Homogeneous graph only supports one type of labels' g.ndata['labels'] = labels g.ndata['train_mask'] = train_mask g.ndata['valid_mask'] = valid_mask g.ndata['test_mask'] = test_mask else: # we have node type assert 'train_mask' not in g.nodes[node_type].data g.nodes[node_type].data['labels'] = labels g.nodes[node_type].data['train_mask'] = train_mask g.nodes[node_type].data['valid_mask'] = valid_mask g.nodes[node_type].data['test_mask'] = test_mask if self._verbose: print('Done processing labels') self._g = g self.cleanup() def cleanup(self): self._edge_loader = None self._feature_loader = None self._label_loader = None def save(self, path): """save the graph and the labels Parameters ---------- path: str Path to save the graph and the labels """ graph_path = os.path.join(path, 'graph.bin') info_path = os.path.join(path, 'info.pkl') save_graphs(graph_path, self._g) save_info(info_path, {'node_id_map': self._node_dict, 'label_map': self._label_map, 'is_multilabel': self._is_multilabel}) def load(self, path): """load the graph and the labels Parameters ---------- path: str Path where to load the graph and the labels """ graph_path = os.path.join(path, 'graph.bin') info_path = os.path.join(path, 'info.pkl') graphs, _ = load_graphs(graph_path) self._g = graphs[0] info = load_info(str(info_path)) self._node_dict = info['node_id_map'] self._label_map = info['label_map'] self._is_multilabel = info['is_multilabel'] @property def node2id(self): """ Return mappings from raw node id/name to internal node id Return ------ dict of dict: {node_type : {raw node id(string/int): dgl_id}} """ return self._node_dict @property def id2node(self): """ Return mappings from internal node id to raw node id/name Return ------ dict of dict: {node_type : {raw node id(string/int): dgl_id}} """ return {node_type : {val:key for key, val in node_maps.items()} \ for node_type, node_maps in self._node_dict.items()} @property def label_map(self): """ Return mapping from internal label id to original label Return ------ dict: {type: {label id(int) : raw label(string/int)}} """ return self._label_map @property def graph(self): """ Return processed graph """ return self._g @property def is_multilabel(self): """ Return whether label is multilabel or singlelebel """ return self._is_multilabel
Java
UTF-8
1,929
2.625
3
[]
no_license
package au.gov.vic.ecodev.mrt.rest.service.template.helper.headers; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @Component public class PropertyHeaderMappingHelper implements HeaderMappingHelper { private final String propertyString; private final Map<String, Map<String, Object>> templateHeaderMap; public PropertyHeaderMappingHelper(final String propertyString) throws Exception { this.propertyString = propertyString; this.templateHeaderMap = init(propertyString); } @Override public String lookUp(final String template, final String dataHeader) { Map<String, Object> templateMap = templateHeaderMap.get(template.toUpperCase()); if (null != templateMap) { return (String) templateMap.get(dataHeader.toUpperCase()); } return null; } public Map<String, Map<String, Object>> init(final String propertyString) throws Exception { ObjectMapper mapper = new ObjectMapper(); Map<String, Map<String, Object>> myMap = mapper.readValue(propertyString, new TypeReference<Map<String, Map<String, Object>>>(){}); Map<String, Map<String, Object>> dataMap = new HashMap<>(); Iterator<String> keys = myMap.keySet().iterator(); while(keys.hasNext()) { String key = keys.next(); Map<String, Object> map = myMap.get(key); Iterator<String> subKeys = map.keySet().iterator(); Map<String, Object> templateValueMap = new HashMap<>(); while(subKeys.hasNext()) { String subKey = subKeys.next(); Object value = map.get(subKey); templateValueMap.put(subKey.toUpperCase(), value); } dataMap.put(key.toUpperCase(), templateValueMap); } return dataMap; } public String getPropertyString() { return propertyString; } }
Java
GB18030
6,033
4.15625
4
[]
no_license
-------------day01---------------- 1:ѧjava 2:ñʼ : javaеĶʵ. ------------------------------------------- 1: ---(ִ)---> Ҹô ----(ָ)--> Ҹ ĸ : arr (С) :Ҫһʵִ for(){ for(){ } } : ûĸԶ---> Arrays Arrsys.sort(arr); ע:ҪûҪĶ ô? ûҪĶ ---> Լд,ֻҪ벻ɾ,һξܼʹ Լһд ----------> 뱣,´μ--> ̵ . ------------------------------------------------------------------------- 2:Ա;ֲ: class { ; //Ա ----> д η ֵ ( ..){//ֲ ----> дڷ ; } } : Ա ֲ λ Ĭֵ û ǰ (ʲôʱ ʲôʱ) 淽 ---------------------------------------------------------------- ʲô?-----> ݵķʽ ϳһ,һǶ. 1:ʲô? ֵ--->Ա 2:ʲô? ----->Ա() ô?----> ͨ new. ͶĹϵ: :....... ӱ һ(ʵ ) ʦ ** Ծ :ijһ :һ(ʵ) : ൱һŽͼֽ. Ǹͼֽ() һ(). ͼֽ ֻһ , ͼֽĽж. Ķ:(ص 1 / 3) 1:ʽ public class Xxx{ ---------Ա------- ; ---------Ա------- η ֵ (б){ ... } } 2:ע: Ա ܼ static ʹ:Ķ 1:ʽ = new (); Ķ ,öĵַ . : Cat Dog Cat c = new Cat(); Cat Ķ ,öĵַ c . Dog d = new Dog(); 2:ʹ: a:ʹóԱ ֵ---------> .Ա = ֵ; ȡֵ---------> =.Ա ; b:ʹóԱ .(); 2:ע: a:ҲǶ int[] arr = new int[10]; int len = arr.length;// arr lengthijԱֵ ȡ ֵ len b:new һ, һĶ Dog d1 = new Dog(); Dog d2 = new Dog(); Dog d3 = new Dog(); System.out.println(d1); System.out.println(d2); System.out.println(d3); // Ķ , ͬĵֵַ 3:(췽):----->󴴽õķ. 1:: a b Աֵ 2:ʽ: a: һ b: ûзֵ, void û : class XxxOoo{ public XxxOoo(){ ... } } 3:ע: a: Ҫûд,ĬṩһղεĹ (㲻д , ϵͳдһ) (д , ϵͳṩ) b: = new (); new (); ----->ִиĹ. c:һܲܶεù??? µĶ. Dog d = new Dog();//½һ,ֵַ ֵ d d = new Dog(); // ٴ½, ¸ֵ d , һεdеĵַ d = new Dog(); d = new Dog(); // d IJ ʼǸ. ------------------------------------------------------------- 1:ıд 2:Ĵʹ 3:ֵ ------------------------------------------------------------- :---------> Զ 80% ֪ʶ װ :ʵϸ, ṩʷʽ ------>Ϊ˸õʹ. ʵֲ: 1:-------> ͨηʵ private Ĭ protected() public 2:ṩʹ÷ʽ---->÷ٲ ô: 1:߰ȫ 2:ߴĸ ̳ ̬ ----------------------------javaBean淶-------------------------------------- 1: public 2:д ޲ι 3:ֶαprivate,getset public class Xxx{// public public Xxx(){} //д ޲ι private ooo; //ֶαprivate,getset public void setOoo( o){ ooo = o; } public getOoo(){ return ooo; } } --------------------------------------------------------------------------------- 1: 2: д public class { .... } 3: ͨ ʽ: = new (); 4:ʹö .(); .(); = .(); 5:,ֵ----> ʽ 6:װ 7:javaBean淶
Markdown
UTF-8
1,459
2.6875
3
[]
no_license
<p>In this integration approach, you barely have to do anything ! What we do is we provide you with a few lines of code you need to put on your website, which our mutual clients will use to login to idibu, something like you can observe on our <a href="http://www.idibu.com/wldemo/goodrecruitment/">demo page</a>:</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://www.idibu.com/images/stories/Portal_logos/goodrecdemo.png" alt="" width="500" height="417" /></p> <p>Which would lead your clients to an idibu website, but under your branding (and your URL!):</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://www.idibu.com/images/stories/Portal_logos/goodrecdem22.png" alt="" width="784" height="512" /></p> <p>And every email client will receive from your system will also be styled under your branding:</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://www.idibu.com/wldemo/goodrecruitment/expiry.png" alt="" width="644" height="779" /></p> <p>And it can be setup in a way, that all the idibu system links will point to your website (the same page used to login) so your clients will only see your brand, never idibu's!</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://www.idibu.com/wldemo/goodrecruitment/login.png" alt="" width="633" height="836" /></p> <p>Continue reading to find out how to set it up!</p>
C
UTF-8
2,253
3.375
3
[]
no_license
/* #Ad-Soyad = Huseyin Sahin #E-posta = huseyin.sahin@ceng.ktu.edu.tr #Proje = Isbn10 Digit Checker */ #include <stdio.h> #include <stdlib.h> int d1_hesapla(int sayi_basamaklari[9]); long long sayilari_birlestirme(int sayi_basamaklari[9],int d1_sayisi); int main(int argc, char* argv[]) { int i, basamaklar[9]; long long girilen_sayi=atoi(argv[1]); /* argv ile string olarak alinan sayi atoi fonksiyonu ile tam sayiya donusturur */ for(i=0; i<9; i++) { basamaklar[i]=girilen_sayi%10; girilen_sayi/= 10; /* girilen sayi basamaklarina ayrilip listeye kaydedilir */ } int d1_sayisi=d1_hesapla(basamaklar); /* d1 sayisini hesaplamak icin d1_hesapla() fonksiyonu cagrilir */ long long SonSayi=sayilari_birlestirme(basamaklar,d1_sayisi); /* Ekrana basilacak sayiyi hesaplamak icin sayilari_birlestirme() fonksiyonuna basamaklar listesi ve d1 sayisi gonderilir */ printf("Sayinin Hesaplanmis Hali = %lld",SonSayi); return 0; } int d1_hesapla(int sayi_basamaklari[9]) { int i, d1_sayisi, toplam=0, katsayi=2; for(i=0; i<9;i++) { toplam=toplam+(sayi_basamaklari[i]*katsayi); katsayi++; /* Her bir basamak ilgili katsayi ile carpilir ve toplamlari alinir */ } d1_sayisi=11-(toplam%11); d1_sayisi%=11; /* ilgili toplam sayisini 11'in kati yapmak icin eklenmesi gereken d1 hesaplanir */ return d1_sayisi; } long long sayilari_birlestirme(int sayi_basamaklari[9], int d1_sayisi) { int i; long long birlesik_sayi=0, basamak_kuvveti=10; /* long long kullanmamin sebebi integer degerinin yeterli kapasiteye sahip olmamasidir */ for(i=0;i<9;i++) { birlesik_sayi+=(sayi_basamaklari[i]*basamak_kuvveti); basamak_kuvveti*=10; /* Sayinin sonuna d1 eklenerek son haline getirilir */ } if(d1_sayisi>=0 && d1_sayisi<10) { birlesik_sayi+=d1_sayisi; /* Sayinin en anlamsiz hanesine, tek haneli olan d1 sayisi eklenir */ } else{ birlesik_sayi=(birlesik_sayi*10)+d1_sayisi; /* Eger d1 `10` ise, ana sayi 10 ile carpilarak 1 kez sola shift edilir.Olusan yeni sayiyla eklenecek hane toplanir */ } return birlesik_sayi; }
C++
UTF-8
1,514
2.6875
3
[ "MIT" ]
permissive
/* SIN Toolchain Symbol.cpp Copyright 2019 Riley Lannon The implementation of the Symbol struct */ #include "Symbol.h" // Our Symbol object Symbol::Symbol(std::string name, DataType type, std::string scope_name, size_t scope_level, bool defined, std::string struct_name) : name(name), type_information(type), scope_name(scope_name), scope_level(scope_level), defined(defined), struct_name(struct_name) { this->symbol_type = VARIABLE; this->stack_offset = 0; this->allocated = false; this->freed = false; } Symbol::Symbol() { this->symbol_type = VARIABLE; this->name = ""; this->type_information = DataType(); this->scope_name = ""; this->scope_level = 0; this->defined = false; this->allocated = false; this->struct_name = ""; this->stack_offset = 0; this->freed = false; } Symbol::~Symbol() { } FunctionSymbol::FunctionSymbol(std::string name, DataType type_information, std::string scope_name, size_t scope_level, std::vector<std::shared_ptr<Statement>> formal_parameters) : Symbol(name, type_information, scope_name, scope_level, true), formal_parameters(formal_parameters) { this->symbol_type = FUNCTION_DEFINITION; // override the Symbol constructor's definition of this member } FunctionSymbol::FunctionSymbol(Symbol base_symbol, std::vector<std::shared_ptr<Statement>> formal_parameters) : Symbol(base_symbol), formal_parameters(formal_parameters) { this->symbol_type = FUNCTION_DEFINITION; } FunctionSymbol::FunctionSymbol() { } FunctionSymbol::~FunctionSymbol() { }
PHP
UTF-8
2,595
2.75
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateFlashcardsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { /* * Each flashcard has it's id, id of its owner (since for every user there is a copy of that card), category to which that flashcard belongs, * and contents of that flashcard. * parent_flashcard_id -> since every user has its own copy of a flashcard, this is the id of its parent. If parent card will be edited, we will be informed about the change */ Schema::create('flashcards', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id')->nullable()->default(NULL); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->unsignedInteger('parent_flashcard_id')->nullable()->default(NULL); $table->foreign('parent_flashcard_id')->references('id')->on('flashcards')->onDelete('set null'); $table->string('category')->default('no category'); $table->string('side1_text',500)->default(''); $table->string('side2_text', 500)->default(''); $table->integer( 'number_of_compartment' )->default(0); // number of compartment in which this card currrently lays in given memobox $table->integer( 'number_in_compartment' )->default(0); // $table->unsignedInteger('memobox_id')->nullable()->default(NULL); $table->foreign( 'memobox_id' )->references('id')->on('memoboxes')->onDelete('set null'); $table->timestamps(); $table->date( 'last_edit_date' ); // date of last edit of this card. Needed to notify other users that has this card as a parent }); // $N = 2; // for( $i = 1; $i <= $N; ++$i ){ // DB::table('flashcards')->insert( // array( // 'user_id' => NULL, // 'parent_flashcard_id' => NULL, // 'category' => "category $i", // 'side1_text' => "side1_text = $i", // 'side2_text' => "side2_text = $i", // 'last_edit_date' => date('Y-m-d H:i:s') // ) // ); // } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('flashcards'); } }
PHP
UTF-8
939
2.84375
3
[]
no_license
<?php /** * These classes should probably just rewrite the base class functions (i.e. logLogin, logAction, etc and the constructor should carry table names **/ require_once dirname(__FILE__)."/log.php"; class ManagerLog extends Log{ //local class variables protected $_loginTable; protected $_actionTable; public function __construct(){ parent::__construct(); $this->_loginTable = "log_m_logins"; $this->_actionTable = "log_m_actions"; } public function logLogin($user,$login){ $eUser = base64_encode(PTC_SALT.$user); $sql = "INSERT $this->_loginTable (id, user, ip, sess_id, user_agent, status) values (0,'$eUser','$this->_ip','$this->_sessID','$this->_agent',$login)"; $result = $this->_mysqli->query($sql); } public function logAAction($user,$action){ $sql = "INSERT INTO $this->_actionTable (id, user_id, action) values (0,'$user','$action')"; $result = $this->_mysqli->query($sql); } } ?>
Python
UTF-8
4,824
3.015625
3
[]
no_license
import pygame # for clipboard saving import win32clipboard as clip import win32con from io import BytesIO from PIL import Image pygame.font.init() myfont = pygame.font.SysFont('Segoe UI', 18, bold=True) COLOR_TEXT = (10, 10, 10) COLOR_DARKER = (120, 120, 120) COLOR_DARK = (180, 180, 180) COLOR_LIGHT = (200, 200, 200) NEW_SNIP = pygame.event.custom_type() def set_setting(text): # Write to settings. Currently sets a single boolean saving Autocopy preference. f = open("settings.txt", "w") f.write(text) f.close() def read_setting(): #read settings. Currently a single boolean holding Autocopy preference. f = open("settings.txt", "r") return f.read() # Holder for buttons to change prefernces, new snip, etc. class Toolbar(): def __init__(self): self.visible = True self.color = (220, 220, 220) self.height = 35 # Add new buttons of NAME, (position), width, height. self.buttons = {"NewSnip":Button("New Snip", (10, 5), 100, 25), "Save": Button("Copy", (120, 5), 100, 25), "AutoCopy?": Button("AutoCopy?", (330, 5), 150, 25)} def draw(self, screen): # Draw toolbar as rectangle. width = pygame.display.get_surface().get_width() pygame.draw.rect(screen, self.color, pygame.Rect((0, 0), (width, self.height))) def update(self, screen, clicked): if self.visible: # Draw the toolbar. self.draw(screen) for button in self.buttons: # Draw each button. self.buttons[button].update(screen, clicked) # Button for toolbar. class Button(): def __init__(self, text, topLeft, width, height): self.color = COLOR_LIGHT self.rect = pygame.Rect(topLeft[0], topLeft[1], width, height) self.width = width self.height = height # Keep button on "clicked" visual for some time after click. self.total_time = 0 self.clicked_time = -1000 self.text = text if text == "AutoCopy?": if read_setting() == "True": self.text = "AutoCopy: On" else: self.text = "AutoCopy: Off" self.text_rect = myfont.render(self.text, False, COLOR_TEXT) def hover(self): # mouse hover (true if hover, false if not) - change color on hover. # only change to hover color if not on click state visual. self.total_time += 5 if self.total_time > self.clicked_time + 800: self.color = COLOR_LIGHT if self.rect.collidepoint(pygame.mouse.get_pos()): self.color = COLOR_DARK return True return False def clicked(self): self.color = COLOR_DARKER self.clicked_time = self.total_time # Change behavior depending on button. if self.text == "New Snip": # Make a new snip. pygame.event.post(pygame.event.Event(NEW_SNIP)) elif self.text == "Copy": # save to windows clipboard img = Image.open("cropped.png") output = BytesIO() img.convert("RGB").save(output, "BMP") data = output.getvalue()[14:] output.close() clip.OpenClipboard() clip.EmptyClipboard() clip.SetClipboardData(win32con.CF_DIB, data) clip.CloseClipboard() # Change text of button depending on setting, and save settings for Autocopy (whether to automatically copy image after snip.) elif self.text == "AutoCopy: On": global AUTO_COPY set_setting("False") self.text = "AutoCopy: Off" self.text_rect = myfont.render(self.text, False, COLOR_TEXT) elif self.text == "AutoCopy: Off": set_setting("True") self.text = "AutoCopy: On" self.text_rect = myfont.render(self.text, False, COLOR_TEXT) # idealing use file dialog to save image https://stackoverflow.com/questions/3579568/choosing-a-file-in-python-with-simple-dialog # https://www.geeksforgeeks.org/python-askopenfile-function-in-tkinter/ # Will revisit this later. def draw(self, screen): # Draw button. pygame.draw.rect(screen, self.color, self.rect) # Center text in button. text_x = self.rect.center[0] - self.text_rect.get_rect().center[0] text_y = self.rect.center[1] - self.text_rect.get_rect().center[1] screen.blit(self.text_rect, (text_x, text_y)) def update(self, screen, clicked): if self.hover() and clicked: self.clicked() self.draw(screen)
PHP
UTF-8
2,116
2.703125
3
[]
no_license
<!DOCTYPE HTML > <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>SOAP Client </title> </head> <body> <div id="err" > <?php if(count($temp_err)>0) { echo '<p>Err:</p>'; foreach($temp_err as $item ) { echo '<p>'.$item.'</p>'; } } ?> </div> <div> <form method="POST"> <label>id macth:</label> <input type="number" min="1" max="64" name="id" value="<?php print $content['id']; ?>" > <input type="submit"> </form> </div> <table> <tr> <td>data </td> <td><?php print $content['str']['date']; ?></td> </tr> <tr> <td>time </td> <td><?php print $content['str']['time']; ?> </td> </tr> <tr> <td>team 1</td> <td><?php print $content['str']['team1']['name']; ?> <img src="<?php print $content['str']['team1']['flag']; ?>"> </td> </tr> <tr> <td>team 2</td> <td><?php print $content['str']['team2']['name']; ?> <img src="<?php print $content['str']['team2']['flag']; ?>"> </td> </tr> <tr> <td>score</td> <td><?php print $content['str']['score']; ?> </td> </tr> </table> <hr /> <?php for($i=0;$i<count($content['all'] );$i++) { print '<p>№<b>'. $content['all'][$i]['id'].'</b>'. $content['all'][$i]['team1']['name'].'<img src="'.$content['all'][$i]['team1']['flag'].'">'. '-'. $content['all'][$i]['team2']['name'].'<img src="'.$content['all'][$i]['team2']['flag'].'">'. '</p>'; } //print $content['str']; /* foreach( $content as $item ){ echo $item.'<hr />'; }*/ ?> </body> </html>
Python
UTF-8
690
2.90625
3
[]
no_license
import cv2 as cv import numpy as np img = cv.imread('lane0.jpg') gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) edges = cv.Canny(gray, 50, 150, apertureSize=3) lines = cv.HoughLinesP(edges, rho=1, theta=np.pi/180, threshold=100, minLineLength=150, maxLineGap=10) ''' param: minLineLength: số điểm tối thiểu tạo nên đường thẳng maxLineGap: khoảng cách lớn nhất giữa 2 điểm vẫn coi chúng là 1 đường thẳng ''' print(lines) for line in lines: x1, y1, x2, y2 = line[0] cv.line(img, (x1, y1), (x2, y2), (0,0,255), 2, cv.LINE_AA) cv.imshow('img', img) cv.imshow('img2', edges) cv.waitKey(0) cv.destroyAllWindows()
Java
UTF-8
2,002
2.3125
2
[ "BSD-3-Clause" ]
permissive
package bsoule.tagtime; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Log; public class TagTime extends Application { private final static String TAG = "TagTime"; public final static boolean DISABLE_LOGV = true; public static final String APP_PNAME = "bsoule.tagtime"; private static Context sContext = null; public static final String PING_UPDATE_EVENT = "bsoule.tagtime.ping_update"; public static final String KEY_PING_ISNEW = "bsoule.tagtime.ping_isnew"; public static void broadcastPingUpdate( boolean pingisnew ) { // Send a broadcast Intent informing interested parties that this goal has been updated. Intent pingIntent = new Intent( TagTime.PING_UPDATE_EVENT ); pingIntent.putExtra(TagTime.KEY_PING_ISNEW, pingisnew ); getAppContext().sendBroadcast( pingIntent ); } public static Context getAppContext() { return TagTime.sContext; } public void onCreate() { super.onCreate(); sContext = getApplicationContext(); String pkgname = sContext.getPackageName(), version; try { version = sContext.getPackageManager().getPackageInfo(pkgname, 0).versionName; } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "getPackageInfo() failed! Msg:" + e.getMessage()); version = "???"; } BeeminderDbAdapter.initializeInstance(this); PingsDbAdapter.initializeInstance(this); Log.v(TAG, "Starting TagTime. Package=" + pkgname + ", Version=" + version); } public static boolean checkBeeminder() { if (sContext == null) return false; PackageManager pm = sContext.getPackageManager(); boolean app_installed = false; try { pm.getPackageInfo("com.beeminder.beeminder", PackageManager.GET_ACTIVITIES); app_installed = true; } catch (PackageManager.NameNotFoundException e) { app_installed = false; } return app_installed; } }
Java
UTF-8
4,984
2.265625
2
[]
no_license
package com.example.dibage.accountb.activity; import android.content.Context; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import com.example.dibage.accountb.R; import com.example.dibage.accountb.adapters.ChangeColorAdapter; import com.example.dibage.accountb.applications.MyApplication; import com.example.dibage.accountb.dao.AccountDao; import com.example.dibage.accountb.dao.DaoSession; import com.example.dibage.accountb.entitys.Account; import com.example.dibage.accountb.utils.AccountUtils; import org.greenrobot.greendao.query.QueryBuilder; import org.greenrobot.greendao.query.WhereCondition; import java.util.ArrayList; import java.util.List; public class SearchActivity extends AppCompatActivity { private Context context; List<Account> accountsList = new ArrayList<>(); private Button btn_cancel; private ListView lv_result; private TextView tv_tip; private EditText et_search; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); context = getApplicationContext(); btn_cancel = findViewById(R.id.btn_cancel); lv_result = findViewById(R.id.lv_result); tv_tip = findViewById(R.id.tv_tip); et_search = findViewById(R.id.et_search); et_search.addTextChangedListener(new mTextWatcher()); // et_search.getFocusable(true); btn_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SearchActivity.this.finish(); } }); } class mTextWatcher implements TextWatcher { String s; /** * CharSequence s:文本改变之前的内容 * int start:文本开始改变时的起点位置,从0开始计算 * int count:要被改变的文本字数,即将要被替代的选中文本字数 * int after:改变后添加的文本字数,即替代选中文本后的文本字数 */ @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //禁止输入空格 if (s.toString().contains(" ")) { String[] str = s.toString().split(" "); String str1 = ""; for (int i = 0; i < str.length; i++) { str1 += str[i]; } et_search.setText(str1); et_search.setSelection(start); } } //文本变化之后要做的事: // 得到文本输入框中的内容 // 先从数据库查数据,然后更新到ListView //把ListView中所有s字符变色 @Override public void afterTextChanged(Editable editable) { s = editable.toString().trim(); Log.e("SA输入字符:", s); if (!s.equals("")) { //获取dao实例 DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession(); AccountDao mAccountDao = daoSession.getAccountDao(); //获取queryBuilder,通过queryBuilder来实现查询功能 QueryBuilder<Account> qb = mAccountDao.queryBuilder(); WhereCondition whereCondition1 = AccountDao.Properties.Description.like('%' + s + '%'); WhereCondition whereCondition2 = AccountDao.Properties.Username.like('%' + s + '%'); qb.whereOr(whereCondition1, whereCondition2); qb.orderAsc(AccountDao.Properties.Firstchar, AccountDao.Properties.Username); accountsList = qb.list(); accountsList = AccountUtils.orderListAccount(accountsList); Log.e("SA结果:", accountsList.toString()); Log.e("SA结果总数:", accountsList.size() + ""); //填充到ListView tv_tip.setVisibility(View.GONE); if(accountsList.size()==0){ tv_tip.setText("抱歉,无匹配记录"); tv_tip.setVisibility(View.VISIBLE); } }else{ accountsList.clear(); tv_tip.setText("请输入关键字"); tv_tip.setVisibility(View.VISIBLE); } ChangeColorAdapter accountAdapter = new ChangeColorAdapter(context, R.layout.item_listview, accountsList); accountAdapter.setsearchString(s); lv_result.setAdapter(accountAdapter); } } }
Markdown
UTF-8
1,400
2.890625
3
[ "Apache-2.0" ]
permissive
# GiveLivly Final Year Project for Computer Science Students # Requirements **Users App Module** - Login permissions (Login functionalities) * Login (for administrators) * Login (for normal people) - Register * Registration (for everyone) **Client Side Main App Module** #### Onboarding -- Selection whether to go for cloths donation/receive or Food donation/receive ## Food donation App Module - Add Food item to donate - Time that is auto created when post is received - Delete the post after 6 hours so to maintain hygiene and space issue - Place location fetch by users address book - Name of owner who is donating food - Recieve food item * Filtered by location,time,etc * Authenticated people can only receive food for data security issue (for future) ## Cloth donation App Module - Add cloth item to donate * Receive or not saved in database (checkbox) or boolean * If received then delete post or pushed down * Time auto created whenever post is made * Address fetch by address book Set address visibility to authenticated users when admin will accept request of genuine people only - Recieve cloth item * Filter availability location wise, time wise, etc * Had to make request for receiving donation which is accepted by either admins or maybe with the post makers whether they want to give their addres*s
JavaScript
UTF-8
13,246
2.84375
3
[]
no_license
function World(gravity) { this.gravity = gravity; this.entities = {all: [], segmentGroups: []}; } World.prototype.add = function(entity) { entity.world = this; this.getEntityGroup("all").push(entity); for(var i = 0; i < entity.groups.length; ++i) { var group = this.getEntityGroup(entity.groups[i]); group.push(entity); } return entity; } World.prototype.remove = function(entity, groupName) { if(groupName === undefined) { this.remove(entity, "all"); for(var i = 0; i < entity.groups.length; ++i) { this.remove(entity, entity.groups[i]); } } else { var group = this.entities[groupName]; for(var i = 0; i < group.length; ++i) { if(group[i] === entity) { group.splice(i, 1); break; } } } } World.prototype.getEntityGroup = function(groupName) { var group = this.entities[groupName]; if(group === undefined) { group = []; this.entities[groupName] = group; } return group; } World.prototype.collideTerrain = function(entity, callback) { var collisions = true; var stop = false var relativeMotion = new Segment(new Vec2D(0, 0), new Vec2D(0, 0)); var n = 0; var segmentGroups = this.entities.segmentGroups; while(collisions && !stop && ++n < 50) { collisions = false; for(var i = 0; i < segmentGroups.length && !collisions && !stop; ++i) { var sg = segmentGroups[i]; var relativePosition = sg.position === null ? entity.position : entity.position.subtract(sg.position); var relativeVelocity = sg.velocity === null ? entity.velocity : entity.velocity.subtract(sg.velocity); relativeMotion.a = relativePosition; relativeMotion.b = relativePosition.add(relativeVelocity); sg.segments.querySegmentForEach(relativeMotion, function(segment) { var relativeIntersectionPoint = segment.intersectionPoint(relativeMotion); if(relativeIntersectionPoint !== null) { var segmentDelta = segment.delta(); if(segmentDelta.crossProduct(relativeVelocity) > 0) { collisions = true; var absoluteSegment = sg.position === null ? segment : new Segment(segment.a.add(sg.position), segment.b.add(sg.position)); var absoluteIntersectionPoint = sg.position === null ? relativeIntersectionPoint : relativeIntersectionPoint.add(sg.position); var segmentNormal = segmentDelta.normal().uniti(); stop = callback(absoluteSegment, absoluteIntersectionPoint, segmentNormal, sg); return true; } } return false; }); } } if(n == 50) console.log("infinite loop detected (point)"); return stop; } function SquishAnalyzer() { this.segments = []; this.addSegment = function(segment) { var ts = segment.delta(); var squished = false; for(var i = 0; i < this.segments.length; ++i) { var previousSegment = this.segments[i]; if(ts.dotProduct(previousSegment) < 0 && ts.unit().dotProduct(previousSegment.unit()) < -0.75) { squished = true; break; } } this.segments.push(ts); return squished; } } function Entity(position, velocity) { this.position = position ? position.copy() : position; this.velocity = velocity ? velocity.copy() : velocity; this.collideTerrain = true; } Entity.prototype.groups = [] Entity.prototype.intent = function() {}; Entity.prototype.reaction = function() { if(this.collideTerrain) { var this_ = this; var squishAnalyzer = new SquishAnalyzer(); this.world.collideTerrain(this, function(segment, collisionPoint, segmentNormal, segmentGroup) { if(squishAnalyzer.addSegment(segment)) { this_.squish(); return true; } return this_.terrainCollision(segment, collisionPoint, segmentNormal, segmentGroup); }); } }; Entity.prototype.update = function() { this.position.addi(this.velocity); }; Entity.prototype.delete = function() { this.world.remove(this); }; Entity.prototype.terrainCollision = function() {}; Entity.prototype.squish = function() {}; Entity.prototype.draw = function(ctx) {}; Entity.prototype.rect = function() { return new Rect(this.position.x, this.position.y, 0, 0); } function MultiPointEntity(points, position, velocity) { Entity.call(this, position, velocity); this.points = points; } MultiPointEntity.prototype = new Entity(); MultiPointEntity.prototype.reaction = function() { if(this.collideTerrain) { var this_ = this; var zeroPos = this.position; var collisions = true; var n = 0; var stop = false; var squishAnalyzer = new SquishAnalyzer(); while(collisions && !stop && ++n < 50) { collisions = false; for(var i = 0; i < this.points.length && !collisions && !stop; ++i) { this.position = zeroPos.add(this.points[i]); stop = this.world.collideTerrain(this, function(segment, collisionPoint, segmentNormal, segmentGroup) { collisions = true; if(squishAnalyzer.addSegment(segment)) { this_.squish(); return true; } return this_.terrainCollision(this_.points[i], segment, collisionPoint, segmentNormal, segmentGroup); }); } } if(n == 50) console.log("infinite loop detected (multipoint)"); this.position = zeroPos; } }; function Actor(points, position, velocity) { MultiPointEntity.call(this, points, position, velocity); this.onGround = false; this.reactionSum = new Vec2D(0, 0); } Actor.prototype = new MultiPointEntity(); this.Actor = Actor; Actor.prototype.reaction = function() { this.onGround = false; MultiPointEntity.prototype.reaction.call(this); }; Actor.prototype.terrainCollision = function(point, segment, collisionPoint, segmentNormal, segmentGroup) { var tox = collisionPoint.subtract(this.position); var rest = this.position.add(this.velocity).subtract(collisionPoint); this.velocity.assign(tox.addi(rest.projectioni(segment.delta()))).addi(segmentNormal.scale(0.1)); if(segmentGroup.velocity !== null) { this.velocity.addi(segmentGroup.velocity) this.reactionSum.addi(segmentGroup.velocity); } if(segmentNormal.dotProduct(this.world.gravity.unit()) < -0.5) { this.onGround = true; } return false; } Actor.prototype.update = function() { MultiPointEntity.prototype.update.call(this); this.velocity.subtracti(this.reactionSum); this.reactionSum.x = 0; this.reactionSum.y = 0; }; function Player(position, velocity) { Actor.call(this, [new Vec2D(0, 0), new Vec2D(0, -5)], position, velocity); this.facingRight = true; } Player.prototype = new Actor(); Player.prototype.intent = function() { if((keys.left || keys.a) && this.velocity.x > -3) { this.velocity.x -= 0.2; this.facingRight = false; } if((keys.right || keys.d) && this.velocity.x < 3) { this.velocity.x += 0.2; this.facingRight = true; } if(!keys.left && !keys.right && !keys.a && !keys.d) { if(this.velocity.x < -0.5) this.velocity.x += 0.4; else if(this.velocity.x > 0.5) this.velocity.x -= 0.4; else this.velocity.x = 0; } if(this.onGround && (keys.up || keys.w)) { this.velocity.projectioni(this.world.gravity.normal()); this.velocity.addi(this.world.gravity.scale(-20)); } this.velocity.addi(this.world.gravity); Actor.prototype.intent.call(this); } Player.prototype.draw = function(ctx) { ctx.fillStyle = "#2d2"; ctx.fillRect(this.position.x - 2, this.position.y - 5, 5, 5); } function Enemy(position, velocity) { Actor.call(this, [new Vec2D(0, 0), new Vec2D(0, -5)], position, velocity); this.moveLeft = true; } Enemy.prototype = new Actor(); Enemy.prototype.groups = ["enemies"] Enemy.prototype.intent = function() { if(this.velocity.x < -0.1) this.moveLeft = true; else if(this.velocity.x > 0.1) this.moveLeft = false; else this.moveLeft = !this.moveLeft; if(this.moveLeft && this.velocity.x > -2) { this.velocity.x -= 0.2; } else if(!this.moveLeft && this.velocity.x < 2) { this.velocity.x += 0.2; } this.velocity.addi(this.world.gravity); Entity.prototype.intent.call(this); } Enemy.prototype.draw = function(ctx) { ctx.fillStyle = "#d22"; ctx.fillRect(this.position.x - 2, this.position.y - 5, 5, 5); } Enemy.prototype.explode = function(direction) { direction = direction !== undefined ? direction : this.world.gravity.neg(); var dirUnit = direction.unit(); var dirUnitNormal = dirUnit.normal(); for(var i = 0; i < 50; ++i) { this.world.add(new BloodParticle(this.position.copy(), dirUnitNormal.scale((Math.random()-0.5) * 6).addi(dirUnit.scale(Math.random()*8)))); } this.delete(); } Enemy.prototype.squish = function() { for(var i = 0; i < 20; ++i) { this.world.add(new BloodParticle(this.position.copy(), new Vec2D((Math.random()-0.5) * 8, (Math.random()-0.5) * 8))); } this.delete(); } function Particle(position, velocity, life, applyGravity) { Entity.call(this, position, velocity); this.life = life; this.applyGravity = applyGravity; } Particle.prototype = new Entity(); Particle.prototype.groups = ["particles"]; Particle.prototype.intent = function() { if(this.applyGravity) this.velocity.addi(this.world.gravity); this.life -= 1; if(this.life <= 0) { this.delete(); } Entity.prototype.intent.call(this); } function BloodParticle(position, velocity) { Particle.call(this, position, velocity, parseInt(Math.random()*50)+50, true); this.attachedTo = null; } BloodParticle.prototype = new Particle(); BloodParticle.prototype.intent = function() { Particle.prototype.intent.call(this); if(this.attachedTo !== null) { this.velocity.assign(this.attachedTo.velocity); } } BloodParticle.prototype.terrainCollision = function(segment, collisionPoint, segmentNormal, segmentGroup) { this.position = collisionPoint.add(segmentNormal.scale(0.1)); if(segmentGroup === null) { this.velocity.x = 0; this.velocity.y = 0; } else { this.attachedTo = segmentGroup; this.velocity = this.attachedTo.velocity.copy(); } this.applyGravity = false; this.collideTerrain = false; return true; } BloodParticle.prototype.draw = function(ctx) { ctx.fillStyle = "#f44"; ctx.fillRect(this.position.x - 1, this.position.y - 1, 3, 3); } function BulletParticle(position, velocity, life) { Particle.call(this, position, velocity, life, false); } BulletParticle.prototype = new Particle(); BulletParticle.prototype.draw = function(ctx) { ctx.fillStyle = this.applyGravity ? "#555" : "#ccc"; ctx.fillRect(this.position.x - 1, this.position.y - 1, 3, 3); } BulletParticle.prototype.terrainCollision = function(segment, collisionPoint, segmentNormal, segmentGroup) { this.position.assign(collisionPoint); this.velocity.subtracti(this.velocity.projection(segmentNormal).scale(1.5)).scalei(0.5); this.applyGravity = true; return true; } BulletParticle.prototype.reaction = function() { var enemyCenter = new Vec2D(-3, 0); if(!this.applyGravity) { var enemies = this.world.getEntityGroup("enemies"); for(var i = 0; i < enemies.length; ++i) { if(enemies[i].position.add(enemyCenter).toLineSegment(this.position, this.position.add(this.velocity)).lengthSquared() <= 9) { enemies[i].explode(this.velocity); this.delete(); break; } } } Particle.prototype.reaction.call(this); } function SegmentGroup(position, segments, movementPattern, speed) { Entity.call(this, position, new Vec2D(0, 0)); this.zeroPosition = position === null ? null : position.copy(); this.collideTerrain = false; this.segments = new SegmentTree(segments); this.segments.construct(); this.path = movementPattern ? new Path(movementPattern) : null; this.speed = speed; this.progress = 0; } SegmentGroup.prototype = new Entity(); SegmentGroup.prototype.groups = ["segmentGroups"] SegmentGroup.prototype.intent = function() { if(this.path !== null) { this.progress = this.path.convert(this.progress + this.speed); this.velocity = this.path.positionAt(this.progress).addi(this.zeroPosition).subtracti(this.position); } Entity.prototype.intent.call(this); }; SegmentGroup.prototype.reaction = function() {}; SegmentGroup.prototype.update = function() { if(this.position !== null && this.velocity !== null) { Entity.prototype.update.call(this); } }; SegmentGroup.prototype.draw = function(ctx) { ctx.strokeStyle = "#dd2"; ctx.beginPath(); var v1 = new Vec2D(0, 0); var v2 = new Vec2D(0, 0); for(var i = 0; i < this.segments.segments.length; ++i) { var s = this.segments.segments[i]; v1.assign(s.a).addi(this.position); v2.assign(s.b).addi(this.position); ctx.moveTo(v1.x, v1.y); ctx.lineTo(v2.x, v2.y); } ctx.stroke(); ctx.closePath(); }; SegmentGroup.prototype.rect = function() { if(this.position === null) { return null; } else { return new Rect(this.position.x + this.segments.min.x, this.position.y + this.segments.min.y, this.segments.max.x - this.segments.min.x, this.segments.max.y - this.segments.min.y); } }
C#
UTF-8
1,546
2.671875
3
[ "BSD-3-Clause" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Maui.Trading.Indicators; using Maui.Trading.Model; namespace Maui.Trading.Modules.Calculators { public class SimpleMovingAverageCalculator : ISeriesCalculator { public SimpleMovingAverageCalculator( int numDays ) { NumDays = numDays; Name = "SMA." + NumDays; } public string Name { get; private set; } public int NumDays { get; private set; } public bool ContainsEnoughData( IPriceSeries prices ) { return prices.Count() >= NumDays; } public IPriceSeries Calculate( IPriceSeries prices ) { var points = new List<SimplePrice>(); for ( int i = NumDays; i < prices.Count; ++i ) { var pricesRange = new PriceSeriesRange( prices, ClosedInterval.FromOffsetLength( i - NumDays, NumDays ) ); double value = pricesRange.Average( p => p.Value ); var point = new SimplePrice( prices[ i ].Time, value ); points.Add( point ); } var descriptor = new ObjectDescriptor( "SMA", ObjectDescriptor.Param( "NumDays", NumDays ) ); var seriesId = prices.Identifier.Derive( descriptor ); return new PriceSeries( seriesId, points ); } } }
Java
UTF-8
119
2.328125
2
[]
no_license
public class Ryu extends Fighter{ public void greet(){ System.out.println("Hello, I am Ryu!!"); } }
Go
UTF-8
701
2.765625
3
[]
no_license
package main import ( "fmt" "os" "os/signal" "syscall" svc "github.com/theveloped/go-whatsapp-rest/service" ) // Server Variable var svr *svc.Server // Init Function func init() { // Initialize Service svc.Initialize() // Initialize Routes routesInit() // Initialize Server svr = svc.NewServer(svc.Router) } // Main Function func main() { // Starting Server svr.Start() // Make Channel for OS Signal sig := make(chan os.Signal, 1) // Notify Any Signal to OS Signal Channel signal.Notify(sig, os.Interrupt) signal.Notify(sig, syscall.SIGTERM) // Return OS Signal Channel // As Exit Sign <-sig // Log Break Line fmt.Println("") // Stopping Server defer svr.Stop() }
Java
UTF-8
361
1.992188
2
[]
no_license
package com.sinosoft.service; import org.springframework.stereotype.Service; /** * Created by gzh on 2017/2/12 0012. */ @Service //将业务处理实现类 添加到Spring容器 public class GuzhonghuiServiceImpl implements GuzhonghuiService { public String dealMsg(String msg) { System.out.println("Hello "+msg); return msg; } }
Python
UTF-8
875
3.5625
4
[ "MIT" ]
permissive
# _*_ coding: utf-8 _*_ __author__ = 'Di Meng' __date__ = '1/13/2018 7:29 PM' import pandas as pd import numpy as np # init a DF dates = pd.date_range('20130101', periods=6) df = pd.DataFrame(np.arange(24).reshape((6, 4)), index=dates, columns=['A', 'B', 'C', 'D']) print(df) # select column A print(df.A) # slice first 3 rows print(df[0:3]) # or slice by values print(df['20130102':'20130104']) print("\n") # select by label: loc print(df.loc['20130102']) # select only A and B columns print(df.loc[:, ['A', 'B']]) # select only A and B in one specific row print(df.loc['20130102', ['A', 'B']]) # select by position: iloc print(df.iloc[3]) print(df.iloc[3][1]) # row 4 column 2 # select by list of row print(df.iloc[[1, 3, 5], 1:3]) # mixed selection with index and labels ix print(df.ix[:3, ['A', 'C']]) # Boolean index with condition check print(df[df.A > 8])
PHP
UTF-8
607
2.890625
3
[]
no_license
<?php class Category extends AbstractModel { use UseTimestamps; private $id; private $name; private $createdAt; private $updatedAt; private $deletedAt; public function setId(int $id) : Category { $this->id = $id; return $this; } public function setName(string $name) : Category { $this->name = name; return $this; } public function getId() : int { return (int) $this->id; } public function getName() : string { return $this->name; } }
Python
UTF-8
20,544
3.078125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Apr 12 15:29:39 2019 @author:Wei Huajing @company:Nanjing University @e-mail:jerryweihuajing@126.com @title:简单剪切去褶皱函数库-VerticalShear @原理:用垂直剪切或斜剪切方法消除地层形变,将地层恢复到水平或假定的区域基准面。 """ '''垂直剪切''' import numpy as np import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties from Module import Image as Im #动态修改字体,需要在可视化参数中添加fontproperties=font font=FontProperties(fname=r"C:\Windows\Fonts\Simsun.ttc",size=12) #11.7 #============================================================================== #第0期次的恢复 def Originate(img_tag,rgb_dict,show=False): #纯地层的tag layer_tag_list=[this_tag for this_tag in list(rgb_dict.keys()) if this_tag>0] # print(layer_tag_list) #空白处面积 area_blank=len(np.where(img_tag==0)[1]) #新矩阵的行列 new_column=int(np.ceil(np.shape(img_tag)[1])) new_row=int(np.ceil(np.shape(img_tag)[0]-area_blank/new_column)) #新的tag矩阵 new_img_tag=np.full((new_row,new_column),-2) #tag厚度和深度的映射关系 map_layer_tag_thickness,\ map_layer_tag_bottom_depth,\ map_layer_tag_top_depth\ =TagThicknessAndDepth(img_tag,layer_tag_list) #重新上色 for j in range(np.shape(new_img_tag)[1]): for k in range(len(layer_tag_list)): #地层的tag this_tag=layer_tag_list[k] #上下界面的深度 this_bottom_depth=list(map_layer_tag_bottom_depth.values())[k][j] this_top_depth=list(map_layer_tag_top_depth.values())[k][j] #厚度 this_thickness=list(map_layer_tag_thickness.values())[k][j] new_img_tag[this_top_depth:this_bottom_depth,j]=int(this_thickness)*[this_tag] #显示与否 if show: plt.figure() plt.imshow(Im.Tag2RGB(new_img_tag,rgb_dict)) return new_img_tag #============================================================================== #求出img_tag中不同tag的平均深度 def TagMeanDepth(img_tag,tag_list): #比较他们的深度度 depth_list=[] for this_tag in tag_list: # print(np.mean(list(np.where(img_rgb==list(this_rgb))[0]))) depth_list.append(np.mean(list(np.where(img_tag==this_tag)[0]))) # 建立颜色何深度的索引 map_tag_depth=dict(zip(tag_list,depth_list)) return map_tag_depth #============================================================================== #不同tag的厚度和深度 def TagThicknessAndDepth(img_tag,layer_tag_list): #thickness #每层各列的厚度的列表之列表 layer_thickness_list=[] for this_tag in layer_tag_list: layer_thickness=[] for j in range(np.shape(img_tag)[1]): layer_thickness.append(len(np.where(img_tag[:,j]==this_tag)[0])) layer_thickness_list.append(layer_thickness) #建立tag和地层各列厚度的映射关系 map_layer_tag_thickness=dict(zip(layer_tag_list,layer_thickness_list)) # print(map_layer_tag_thickness) #bottom_depth #每层各列的底部深度的列表之列表 layer_bottom_depth_list=[] count=0 #计算底部深度 for this_tag in list(map_layer_tag_thickness.keys()): #第一层厚度即底部深度 if count==0: layer_bottom_depth=map_layer_tag_thickness[this_tag] layer_bottom_depth_list.append(layer_bottom_depth) #从第二层开始 if count>0: #底部深度来了 layer_bottom_depth=list(np.array(layer_bottom_depth_list[count-1])+np.array(map_layer_tag_thickness[this_tag])) layer_bottom_depth_list.append(layer_bottom_depth) count+=1 #建立tag和地层各列底部深度的映射关系 map_layer_tag_bottom_depth=dict(zip(layer_tag_list,layer_bottom_depth_list)) #top_depth #每层各列的顶部深度的列表之列表 layer_top_depth_list=[] #计算顶部深度 for k in range(len(layer_tag_list)): #顶部部深度来了 layer_top_depth=list(np.array(layer_bottom_depth_list[k])-np.array(layer_thickness_list[k])) layer_top_depth_list.append(layer_top_depth) #建立tag和地层各列顶部深度的映射关系 map_layer_tag_top_depth=dict(zip(layer_tag_list,layer_top_depth_list)) return map_layer_tag_thickness,map_layer_tag_bottom_depth,map_layer_tag_top_depth #============================================================================== #tag插值改变矩阵尺寸 def ReshapeTagNearby(img_tag,shape): new_img_tag=np.full(shape,-2) for i in range(np.shape(new_img_tag)[0]): for j in range(np.shape(new_img_tag)[1]): #新的坐标索引 new_i=int(np.floor(i*np.shape(img_tag)[0]/np.shape(new_img_tag)[0])) new_j=int(np.floor(j*np.shape(img_tag)[1]/np.shape(new_img_tag)[1])) new_img_tag[i,j]=img_tag[new_i,new_j] return new_img_tag #11.10 #============================================================================== #开始恢复 #original_img_tag为恢复之前的tag矩阵 def Recover(original_img_tag,rgb_dict,side='right',show=False): #输出的所有img_tag矩阵组成的列表 final_img_tag_list=[original_img_tag] #总位移量列表 transform_length_list=[0] #纯地层的tag layer_tag_list=[this_tag for this_tag in list(rgb_dict.keys()) if this_tag>0] # print(layer_tag_list) import copy img_tag=copy.deepcopy(original_img_tag) #建立tag和对应消去面积字典里 map_tag_area_to_diminish={} #进入每一期剥蚀的循环 for k in range(len(layer_tag_list)): #要消除的layer的tag tag_to_diminish=layer_tag_list[k] # print(tag_to_diminish) #要消除的tag面积 area_to_diminish=len(np.where(img_tag==tag_to_diminish)[1]) # print(area_to_diminish) #将消去面积和tag添加到另一个字典里 map_tag_area_to_diminish[tag_to_diminish]=area_to_diminish #消除tag后的宽度和高度 new_height=int(np.ceil(np.shape(img_tag)[0])) new_width=int(np.ceil(np.shape(img_tag)[1]-area_to_diminish/new_height)) """对他们进行横向压缩""" #缩放因子,axis=0,axis=1 factor_1=new_width/np.shape(img_tag)[1] factor_0=1/factor_1 # print(factor_0,factor_1) #新矩阵的尺寸:但最终会被截断,所以是临时的 new_shape_temp=(int(np.ceil(np.shape(img_tag)[0]*factor_0)), int(np.ceil(np.shape(img_tag)[1]*factor_1))) #新的矩阵 new_img_tag_temp=ReshapeTagNearby(img_tag,new_shape_temp) # plt.figure() # plt.imshow(whj.Tag2RGB(new_img_tag_temp,rgb_dict)) #正式的用于输出的tag矩阵 new_img_tag=np.full((new_height,new_width),-2) #tag厚度和深度的映射关系 map_layer_tag_thickness=TagThicknessAndDepth(new_img_tag_temp,layer_tag_list)[0] map_layer_tag_bottom_depth={} map_layer_tag_top_depth={} #然后,对这些个字典进行修改 #把tag_to_diminish那层剥掉 del map_layer_tag_thickness[tag_to_diminish] count=0 # print(list(map_layer_tag_thickness.keys())) for this_tag in list(map_layer_tag_thickness.keys()): # print(this_tag) #底部深度 #第一层厚度即底部深度 if count==0: #底部深度 layer_bottom_depth=map_layer_tag_thickness[this_tag] #顶部深度 layer_top_depth=[0]*len(layer_bottom_depth) #收录进来 map_layer_tag_bottom_depth[this_tag]=layer_bottom_depth map_layer_tag_top_depth[this_tag]=layer_top_depth #从第二层开始 if count>0: #顶部深度 layer_top_depth=list(map_layer_tag_bottom_depth.values())[count-1] #底部深度 layer_bottom_depth=list(np.array(layer_top_depth)+np.array(map_layer_tag_thickness[this_tag])) #收录进来 map_layer_tag_bottom_depth[this_tag]=layer_bottom_depth map_layer_tag_top_depth[this_tag]=layer_top_depth count+=1 #重新上色 for j in range(np.shape(new_img_tag)[1]): for k in range(len(map_layer_tag_thickness.keys())): #地层的tag this_tag=layer_tag_list[k] #上下界面的深度 this_bottom_depth=list(map_layer_tag_bottom_depth.values())[k][j] this_top_depth=list(map_layer_tag_top_depth.values())[k][j] #厚度 this_thickness=list(map_layer_tag_thickness.values())[k][j] new_img_tag[this_top_depth:this_bottom_depth,j]=int(this_thickness)*[list(map_layer_tag_thickness.keys())[k]] # #截断之前 # plt.figure() # plt.imshow(whj.Tag2RGB(new_img_tag,rgb_dict)) #输出矩阵 final_img_tag=np.zeros(np.shape(original_img_tag)) # print(list(map_tag_area_to_diminish.keys())) """对final_img_tag进行操作,补上消去地层""" #进入该循环 for k in range(len(map_tag_area_to_diminish.keys())): # print(list(map_tag_area_to_diminish.keys())[k]) #计算面积的界限 area_upper_bound=sum(list(map_tag_area_to_diminish.values())[:k+1]) area_lower_bound=sum(list(map_tag_area_to_diminish.values())[:k]) # print(area_upper_bound,area_lower_bound) #这一期次填补界面列坐标 j_lower_bound=int(np.ceil(area_lower_bound/np.shape(final_img_tag)[0])) j_upper_bound=int(np.ceil(area_upper_bound/np.shape(final_img_tag)[0])) # print(lower_bound,upper_bound) #填充各期次的剥蚀 #左右两种观赏模式 if side is 'right': l=np.shape(final_img_tag)[1] # print(l-upper_bound,l-lower_bound) final_img_tag[:,l-j_upper_bound:l-j_lower_bound]=list(map_tag_area_to_diminish.keys())[k] if side is 'left': # print(lower_bound,upper_bound) final_img_tag[:,j_lower_bound:j_upper_bound]=list(map_tag_area_to_diminish.keys())[k] #复制粘贴核心部分 final_img_tag[:np.shape(new_img_tag)[0],:np.shape(new_img_tag)[1]]=new_img_tag[:,:] #把位移量收录进来 transform_length_list.append(np.shape(final_img_tag)[1]-np.shape(new_img_tag)[1]) #把img_tag收录进来 final_img_tag_list.append(final_img_tag) # #截断之后 # plt.figure() # plt.imshow(Tag2RGB(final_img_tag,rgb_dict)) #更新输入矩阵 img_tag=copy.deepcopy(new_img_tag) #显示模块 if show: for this_final_img_tag in final_img_tag_list: plt.figure() plt.imshow(Im.Tag2RGB(this_final_img_tag,rgb_dict)) return final_img_tag_list,transform_length_list """ 1 os.path.exists(path) 判断一个目录是否存在 2 os.makedirs(path) 多层创建目录 3 os.mkdir(path) 创建目录 """ #11.12 #============================================================================== #在某路径下判断并创建文件夹 def GenerateFold(path): #引入模块 import os #去除首位空格 path=path.strip() #去除尾部\符号 path=path.rstrip("\\") #判断路径是否存在(True/False) Exist=os.path.exists(path) #判断结果 if not Exist: #如果不存在则创建目录 #创建目录操作函数 os.makedirs(path) #11.10 #============================================================================== #打印计算结果 def PrintResult(profile_length,final_img_tag_list,transform_length_list,save_path): #判断并创建文件夹 GenerateFold(save_path) #1km代表unit个像素点(需根据实际比例尺修改) unit=np.shape(final_img_tag_list[0])[1]/profile_length #输出重要参数 print('初始长度:%5.2fkm' %(np.shape(final_img_tag_list[0])[1]/unit)) for i in range(len(transform_length_list)): #当下的像素点长度 that_length=np.shape(final_img_tag_list[0])[1]-transform_length_list[i] print('第%d期长度:%5.2fkm,拉张量:%5.2fkm,拉张率:%4.2f%%' %(i,that_length/unit, transform_length_list[i]/unit, transform_length_list[i]/(np.shape(final_img_tag_list[0])[1]/100))) #将计算结果写入result.txt文件 with open(save_path+'\\'+"result.txt","w") as file: file.write('初始长度:%5.2fkm' %(np.shape(final_img_tag_list[0])[1]/unit)) file.write('\n') for i in range(len(transform_length_list)): #当下的像素点长度 that_length=np.shape(final_img_tag_list[0])[1]-transform_length_list[i] file.write('第%d期长度:%5.2fkm,拉张量:%5.2fkm,拉张率:%4.2f%%' %(i,that_length/unit, transform_length_list[i]/unit, transform_length_list[i]/(np.shape(final_img_tag_list[0])[1]/100))) file.write('\n') #11.11 #============================================================================== #处理结果的单独表示 #final_img_tag_list为恢复后各期次的tag矩阵 def PrintSingle(img_rgb,final_img_tag_list,rgb_dict,save_path,show=False): #判断并创建文件夹 GenerateFold(save_path) #子目录路径 save_path+='\\single' #生成子文件夹 GenerateFold(save_path) #修改路径 import os FigName=os.path.join(save_path,'原图.png') import imageio #保存原图 imageio.imwrite(FigName,img_rgb) # ax=plt.gca() # ax.imshow(img_rgb) # # #去掉坐标刻度 # ax.set_xticks([]) # ax.set_yticks([]) # # #去掉上下左右边框 # ax.spines['top'].set_visible(False) # ax.spines['bottom'].set_visible(False) # ax.spines['left'].set_visible(False) # ax.spines['right'].set_visible(False) # # # fig.savefig(FigName,dpi=300,bbox_inches='tight') # # #关闭图片 # plt.close() #保存列表中的img_tag number=0 for this_final_img_tag in final_img_tag_list: #修改路径 FigName='第'+str(number)+'期.png' FigName=os.path.join(save_path,FigName) #先转为rgb矩阵 this_final_img_rgb=Im.Tag2RGB(this_final_img_tag,rgb_dict) #逐个保存 imageio.imwrite(FigName,this_final_img_rgb) # fig=plt.figure() # ax=plt.gca() # ax.imshow(this_final_img_rgb) # # #去掉坐标刻度 # ax.set_xticks([]) # ax.set_yticks([]) # # #去掉上下左右边框 # ax.spines['top'].set_visible(False) # ax.spines['bottom'].set_visible(False) # ax.spines['left'].set_visible(False) # ax.spines['right'].set_visible(False) # # fig.savefig(FigName,dpi=300,bbox_inches='tight') # #关闭图片 # if not show: # # plt.close() number+=1 #11.12 #============================================================================== #处理结果生成组合图 #accurate表示两种显示模式的开关(True/False) def PrintSubplot(img_rgb,final_img_tag_list,rgb_dict,save_path,show=False): #判断并创建文件夹 GenerateFold(save_path) #子目录路径 save_path+='\\subplot' #生成子文件夹 GenerateFold(save_path) import os #最终要打印的rgb矩阵组成的列表 final_img_rgb_list=[img_rgb]+[Im.Tag2RGB(this_final_img_tag,rgb_dict) for this_final_img_tag in final_img_tag_list] """不准确地输出(好看)""" #可视化,仅仅是表示 fig=plt.figure() #子图序号 number=1 #一共这么多小图 amount_of_subplot=len(final_img_rgb_list) #打印每一期次 for this_img_rgb in final_img_rgb_list: ax=plt.subplot(amount_of_subplot,1,number) ax.imshow(this_img_rgb) #去掉坐标刻度 ax.set_xticks([]) ax.set_yticks([]) #去掉上下左右边框 ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.axis('tight') number+=1 #修改图名 FigName='inaccurate组合图.png' #修改路径 FigName=os.path.join(save_path,FigName) fig.savefig(FigName,dpi=300,bbox_inches='tight') #关闭图片 if not show: plt.close() """实打实地输出""" # #把原图去掉 # final_img_rgb_list.remove(final_img_rgb_list[0]) '''设定一个坐标轴范围''' x_boundary=[0,np.shape(img_rgb)[1]] y_boundary=[0,np.shape(img_rgb)[0]] #一共这么多张图 amount_of_fig=int(np.ceil(len(final_img_rgb_list)/5)) #一共这么多小图 amount_of_subplot=len(final_img_rgb_list) #背景色 background_rgb=np.array([255,255,255],dtype=np.uint8) #第k张图 for k in range(amount_of_fig): #可视化,仅仅是表示 fig=plt.figure() #子图序号 number=1 this_fig_final_img_rgb_list=final_img_rgb_list[5*k:min(5*(k+1),amount_of_subplot)] #打印每一期次 for this_img_rgb in this_fig_final_img_rgb_list: #翻转一波 this_img_rgb_to_show=np.full(np.shape(this_img_rgb),background_rgb) for kk in range(np.shape(this_img_rgb_to_show)[0]): this_img_rgb_to_show[-kk-1]=this_img_rgb[kk] ax=plt.subplot(5,1,number) ax.imshow(this_img_rgb_to_show) ax.axis([x_boundary[0],x_boundary[1],y_boundary[0],y_boundary[1]]) #去掉坐标刻度 ax.set_xticks([]) ax.set_yticks([]) #去掉上下左右边框 ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) number+=1 #修改图名 FigName='accurate组合图'+str(k+1)+'.png' #修改路径 FigName=os.path.join(save_path,FigName) fig.savefig(FigName,dpi=300,bbox_inches='tight') #关闭图片 if not show: plt.close()
C++
UTF-8
1,316
2.640625
3
[]
no_license
//////////////////////////////////////////////////////////////////////////////// // $Id: FeedbackScene.h 1781 2008-02-15 11:06:21Z mellinger $ // Author: juergen.mellinger@uni-tuebingen.de // Description: An abstract class interface for feedback scenes. // A feedback scene consists of a cursor and a number of targets. // // (C) 2000-2008, BCI2000 Project // http://www.bci2000.org //////////////////////////////////////////////////////////////////////////////// #ifndef FEEDBACK_SCENE_H #define FEEDBACK_SCENE_H #include "Environment.h" #include "Color.h" class FeedbackScene : protected Environment { typedef FeedbackScene self; public: FeedbackScene() {} virtual ~FeedbackScene() {} virtual self& Initialize() = 0; virtual float CursorRadius() const = 0; virtual float CursorXPosition() const = 0; virtual float CursorYPosition() const = 0; virtual float CursorZPosition() const = 0; virtual self& SetCursorPosition( float x, float y, float z ) = 0; virtual self& SetCursorVisible( bool ) = 0; virtual self& SetCursorColor( RGBColor ) = 0; virtual int NumTargets() const = 0; virtual bool TargetHit( int ) const = 0; virtual self& SetTargetVisible( bool, int ) = 0; virtual self& SetTargetColor( RGBColor, int ) = 0; }; #endif // FEEDBACK_SCENE_H
C#
UTF-8
788
3.125
3
[ "MIT" ]
permissive
namespace FastFood.Models { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public class Position { [Key] public int Id { get; set; } [Required] [MinLength(3), MaxLength(30)] public string Name { get; set; } public ICollection<Employee> Employees { get; set; } = new HashSet<Employee>(); public override bool Equals(object obj) { if (!(obj is Position)) { return false; } var pos = (Position)obj; return this.Name == pos.Name; } public override int GetHashCode() { return 539060726 + EqualityComparer<string>.Default.GetHashCode(Name); } } }
C++
UTF-8
2,586
3.25
3
[]
no_license
#ifndef QUEUE_H #define QUEUE_H #include "Object.h" #include "Exception.h" #include "List.h" using namespace ZQLib; namespace ZQLib { template<typename T> class Queue : public Object { public: virtual void Add(const T& e) = 0; virtual void Remove() = 0; virtual T Front() const = 0; virtual void Clear() = 0; virtual int Length() const = 0; }; template<typename T, int N> class StaticQueue : public Queue<T> { protected: T m_space[N]; int m_front; int m_rear; int m_length; public: StaticQueue() { this->m_front = 0; this->m_rear = 0; this->m_length = 0; } int Capacity() const { return N; } void Add(const T& e) { if(this->m_length < N) { this->m_space[this->m_rear] = e; this->m_rear = (this->m_rear + 1) % N; this->m_length++; } else { THROW_EXCEPTION(InvalidOperationException, "No space in current queue ..."); } } void Remove() { if(this->m_length > 0) { this->m_front = (this->m_front + 1) % N; this->m_length--; } else { THROW_EXCEPTION(InvalidOperationException, "No element in current queue ..."); } } T Front() const { if(this->m_length > 0) { return this->m_space[this->m_front]; } else { THROW_EXCEPTION(InvalidOperationException, "No element in current queue ..."); } } void Clear() { this->m_front = 0; this->m_rear = 0; this->m_length = 0; } int Length() const { return this->m_length; } }; template<typename T> class LinkQueue : public Queue<T> { protected: CircleSinglyLinkList<T> m_sl; public: void Add(const T& e) { this->m_sl.Add(e); } void Remove() { if(this->m_sl.Length() > 0) { this->m_sl.Remove(0); } else { THROW_EXCEPTION(InvalidOperationException, "No element in current queue ..."); } } T Front() const { if(this->m_sl.Length() > 0) { return this->m_sl.GetBy(0); } else { THROW_EXCEPTION(InvalidOperationException, "No element in current queue ..."); } } void Clear() { this->m_sl.Clear(); } int Length() const { return this->m_sl.Length(); } }; } #endif // QUEUE_H
Java
UTF-8
2,433
2.1875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.reseval.mash.entities; import java.io.Serializable; import java.math.BigDecimal; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; /** * * @author Muhammad Imran */ @Entity @Table(name = "RESEARCH_AREAS") @NamedQueries({ @NamedQuery(name = "ResearchAreas.findAll", query = "SELECT r FROM ResearchAreas r")}) public class ResearchAreas implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "RA_ID_PK") private BigDecimal raIdPk; @Column(name = "RA_NAME") private String raName; @OneToMany(mappedBy = "researchAreas") private Collection<Sectors> sectorsCollection; public ResearchAreas() { } public ResearchAreas(BigDecimal raIdPk) { this.raIdPk = raIdPk; } public BigDecimal getRaIdPk() { return raIdPk; } public void setRaIdPk(BigDecimal raIdPk) { this.raIdPk = raIdPk; } public String getRaName() { return raName; } public void setRaName(String raName) { this.raName = raName; } public Collection<Sectors> getSectorsCollection() { return sectorsCollection; } public void setSectorsCollection(Collection<Sectors> sectorsCollection) { this.sectorsCollection = sectorsCollection; } @Override public int hashCode() { int hash = 0; hash += (raIdPk != null ? raIdPk.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ResearchAreas)) { return false; } ResearchAreas other = (ResearchAreas) object; if ((this.raIdPk == null && other.raIdPk != null) || (this.raIdPk != null && !this.raIdPk.equals(other.raIdPk))) { return false; } return true; } @Override public String toString() { return "com.reseval.resevalmashejbs.ResearchAreas[raIdPk=" + raIdPk + "]"; } }
Java
UTF-8
2,429
1.625
2
[ "Apache-2.0" ]
permissive
// Copyright 2020 Google LLC // // 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.cse.creatine; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** Reads application default properties in the resources/application.properties file. */ @Component @PropertySource("classpath:application.properties") public class AppProperties { @Value("${bqDataSet}") private String bqDataSet; @Value("${cloudProject}") private String cloudProject; @Value("${entityId}") private String entityId; @Value("${bqAccountTable}") private String bqAccountTable; @Value("${bqAccountLabelTable}") private String bqAccountLabelTable; @Value("${bqCampaignTable}") private String bqCampaignTable; @Value("${bqCampaignBudgetTable}") private String bqCampaignBudgetTable; @Value("${bqAdGroupAdTable}") private String bqAdGroupAdTable; @Value("${bqAdGroupTable}") private String bqAdGroupTable; @Value("${gcsBucket}") private String gcsBucket; @Value("${googleAdsMccId}") private String googleAdsMccId; public String getGoogleAdsMccId() { return googleAdsMccId; } public String getBqDataSet() { return bqDataSet; } public String getCloudProject() { return cloudProject; } public String getEntityId() { return entityId; } public String getAccountTable() { return bqAccountTable; } public String getAccountLabelTable() { return bqAccountLabelTable; } public String getCampaignTable() { return bqCampaignTable; } public String getCampaignBudgetTable() { return bqCampaignBudgetTable; } public String getAdGroupTable() { return bqAdGroupTable; } public String getAdGroupAdTable() { return bqAdGroupAdTable; } public String getBucketName() { return gcsBucket; } }
JavaScript
UTF-8
18,762
2.765625
3
[]
no_license
var companieSelected; var productoSelected; var companiesList; var variationsList = []; var variationSelected; // COMPANIE // function showCompanies() { var button = '<div class="col-6"> <a href="#" onclick="openModalCompanie(0)" class="btn btn-info" >Nueva Empresa</a> </div><hr>'; $.get('/companie', function (companies) { var title = 'Empresas'; console.log(companies); companiesList = companies; var list = ''; companiesList.forEach(function (companie) { list = list + '<tr>' + '<td colspan="4">' + companie.name + '</td>' + '<td colspan="4">' +'<a href="#" onclick="openModalCompanie(' + companie.id + ')" id="button-edit" class="btn btn-info btn-sm btn-block"> Editar</a>' +'<a href="#" onclick="openDeleteModal(' + companie.id + ')" class="btn btn-danger btn-sm btn-block"> Eliminar</a>' +'</td>' + '</tr>' }); if(list.length > 0){ list = '' + '<table class="table ">' +'<thead>' +'<th colspan="4">Nombre</th>' +'<th colspan="4">Acciones</th>' +'</thead>' +'<tbody>' + list + '</tbody>' +'</table>'; }else { list = "No existen Empresas registradas"; document.getElementById('buttonProducts').disabled = true; } $('#list-companies').html(list); $('#title').html(title); $('#button').html(button); }); } function addCompanie() { if($('#nameCompanie').val().trim()){ $.post({ url: '/companie/addCompanie', contentType: 'application/json', data: JSON.stringify({ name: $('#nameCompanie').val(), }) }).then(showCompanies); document.getElementById("nameCompanie").value = ""; $("#addModalCompanie").modal('hide'); document.getElementById('buttonProducts').disabled = false; showCompanies(); messageSucces(); }else{ messageErrorForm(); } } function editCompanie() { if($('#nameEditCompanie').val().trim()){ $.ajax({ url: '/companie/editCompanie', type: 'PUT', data: JSON.stringify({ id: companieSelected, name: $('#nameEditCompanie').val(), }), contentType: 'application/json' }).then(showCompanies); $("#editModal").modal("hide"); showCompanies(); messageSucces(); }else{ messageErrorForm(); } } function deleteCompanie() { var idCompanie = companieSelected; $.ajax({ url: '/companie/deleteCompanie/' + idCompanie, type: 'DELETE', contentType: 'application/json' }).then(showCompanies); $("#deleteModal").modal("hide"); messageDelete(); } function openModalCompanie(idCompanie){ if(idCompanie!=0){ $("#editModal").modal("show"); companieSelected = idCompanie; $.get('/companie/'+idCompanie, function (companie) { document.getElementById('nameEditCompanie').value = companie.name; }); }else{ $("#addModalCompanie").modal("show"); } } function openDeleteModal(idCompanie){ $("#deleteModal").modal("show"); companieSelected = idCompanie; } // PRODUCTS // function showProducts() { var title = 'Productos'; var button = '<div class="col-6"> <a href="#" onclick="openModalProduct(0)" class="btn btn-info" >Nuevo producto</a> </div><hr>'; var hasIva = false; $.get('/products/getProducts', function (products) { console.log(products); var list = ''; products.forEach(function (product) { console.log(product); if(product.hasIva){ hasIva = 'Si'; }else{ hasIva = 'No'; } list = list + '<tr>' + '<td>' + product.name + '</td>' + '<td>' + product.stock + '</td>' + '<td> $' + product.cost + '</td>' + '<td> $' + product.price + '</td>' + '<td> ' + hasIva + '</td>' + '<td> ' + product.listVariations.length + '</td>' + '<td>' +'<a href="#" onclick="openModalProduct(' + product.id +')" class="btn btn-info btn-sm btn-block"> Editar</a>' +'<a href="#" onclick="openDeleteModalProduct(' + product.id +')" class="btn btn-danger btn-sm btn-block"> Eliminar</a>' +'</td>' + '</tr>' }); if(list.length > 0){ list = '' + '<div ><table class="table ">' +'<thead>' +'<th scope="col-4">Nombre</th>' +'<th scope="col-4">Stock</th>' +'<th scope="col-4">Costo</th>' +'<th scope="col-4">Precio</th>' +'<th scope="col-4">IVA</th>' +'<th scope="col-4">N. Variaciones</th>' +'<th scope="col-4">Acciones</th>' +'</thead>' +'<tbody>' + list + '</tbody>' +'</table></div>'; }else{ list = "No existen Productos registrados"; } $('#list-companies').html(list); $('#title').html(title); $('#button').html(button); }); } function openModalProduct(idProduct){ var companies = ''; companiesList.forEach(function (companie) { companies = companies + '<option>' + companie.name + '</option>' }); companies = '<select class="form-control" id="empresaProduct" >' + companies + '</select>'; if(idProduct!=0){ $("#modalProduct").modal("show"); $.get('/products/getProduct/'+idProduct, function (product) { document.getElementById('nameEditProduct').value = product.name; document.getElementById('stockEditProduct').value = product.stock; document.getElementById('costEditProduct').value = product.cost; document.getElementById('priceEditProduct').value = product.price; if(product.listVariations.length == 0 ){ variationsList = []; $('#listEditVariations').html("No existen Variaciones"); }else{ tableVariations(product.listVariations); } }); productoSelected = idProduct; }else{ variationsList = []; $("#modalAddProduct").modal("show"); $('#list-variations').html("No existen Variaciones"); } $('#listCompaniesProduct').html(companies); } function openDeleteModalProduct(idProduct){ $("#deleteModalProduct").modal("show"); productoSelected = idProduct; } function addProduct() { var iva = false; var newsVariations = []; if($("#ivaProduct").val() == "Si"){ iva = true; } var companieProduct = companiesList.find(function (companie){ return companie.name = $("#empresaProduct").val(); }); if($('#nameProduct').val().trim() && $('#stockProduct').val().trim() && $('#costProduct').val().trim() && $('#priceProduct').val().trim()){ if($('#stockProduct').val() > 0 ){ if($('#costProduct').val() < $('#priceProduct').val()){ if( variationsList != undefined){ variationsList.forEach(function (variation){ if(variation.id == undefined){ newsVariations.push({ name: variation.name, brand: variation.brand, sku: variation.sku, stock: variation.stock }); } }); } $.post({ url: '/products/addProduct', contentType: 'application/json', data: JSON.stringify({ name: $('#nameProduct').val(), stock: $('#stockProduct').val(), cost: $('#costProduct').val(), price: $('#priceProduct').val(), hasIva: iva, companiesId: companieProduct, listVariations : newsVariations }) }).then(showProducts); document.getElementById('nameProduct').value = ""; document.getElementById('stockProduct').value = ""; document.getElementById('costProduct').value = ""; document.getElementById('priceProduct').value = ""; showProducts(); $("#modalAddProduct").modal("hide"); messageSucces(); }else{ messageErrorPriceCost(); } }else{ messageErrorStock(); } }else{ messageErrorForm(); } } function editProduct() { var iva = false; if($("#ivaProduct").val() == "Si"){ iva = true; } console.log($("#ivaEditProduct").val()); var companieProduct = companiesList.find(function (companie){ return companie.name = $("#empresaEditProduct").val(); }); if($('#nameEditProduct').val().trim() && $('#stockEditProduct').val().trim() && $('#costEditProduct').val().trim() && $('#priceEditProduct').val().trim()){ if($('#stockEditProduct').val() > 0){ if($('#costEditProduct').val() < $('#priceEditProduct').val()){ variationsList.forEach(function (variation){ if(!variation.id){ $.post({ url: '/variations/addVariation', contentType: 'application/json', data: JSON.stringify({ name: $('#nameVariation').val(), brand: $('#brandVariation').val(), sku: $('#skuVariation').val(), stock: $('#stockVariation').val() }) }).then(tableVariations); } }); $.ajax({ url: '/products/editProduct', type: 'PUT', data: JSON.stringify({ id: productoSelected, name: $('#nameEditProduct').val(), stock: $('#stockEditProduct').val(), cost: $('#costEditProduct').val(), price: $('#priceEditProduct').val(), hasIva: iva, listVariations: variationsList, companiesId: companieProduct }), contentType: 'application/json' }).then(showProducts); document.getElementById('nameEditProduct').value = ""; document.getElementById('stockEditProduct').value = ""; document.getElementById('costEditProduct').value = ""; document.getElementById('priceEditProduct').value = ""; showProducts(); $("#modalProduct").modal("hide"); messageSucces(); }else{ messageErrorPriceCost(); } }else{ messageErrorStock(); } }else{ messageErrorForm(); } } function deleteProduct() { var idProduct = productoSelected; $.ajax({ url: '/products/deleteProduct/' + idProduct, type: 'DELETE', contentType: 'application/json' }).then(showProducts,showCompanies); $("#deleteModalProduct").modal("hide"); messageDelete(); } // VARIATIONS // function tableVariations(listVariations){ variationsList = listVariations; var listVariation = ''; variationsList.forEach(function (variation) { listVariation = listVariation + '<tr>' + '<td>' + variation.name + '</td>' + '<td>' + variation.brand + '</td>' + '<td>' + variation.sku + '</td>' + '<td>' + variation.stock + '</td>' + '<td>' +'<a href="#" onclick="openDeleteModalVariation(' + variation.id +')" class="btn btn-danger btn-sm btn-block"> Eliminar</a>' +'</td>' + '</tr>' }); if(variationsList.length > 0){ listVariation = '' + '<table class="table table-dark">' +'<thead>' +'<th scope="col-4">Nombre</th>' +'<th scope="col-4">Brand</th>' +'<th scope="col-4">SKU</th>' +'<th scope="col-4">Stock</th>' +'<th scope="col-4">Acciones</th>' +'</thead>' +'<tbody>' + listVariation + '</tbody>' +'</table>'; }else{ listVariation = "No existen variaciones registradas"; } $('#listEditVariations').html(listVariation); $('#list-variations').html(listVariation); } function addVariationList(){ if($('#nameVariation').val().trim() && $('#brandVariation').val().trim() && $('#skuVariation').val().trim() && $('#stockVariation')){ var sku = document.getElementById('skuVariation').value ; $.get('/variations/validateSku/'+ sku , function (data) { if(data){ if(document.getElementById('stockVariation').value > 0){ var newVariation = { "name": document.getElementById('nameVariation').value, "brand": document.getElementById('brandVariation').value, "sku": document.getElementById('skuVariation').value, "stock": document.getElementById('stockVariation').value }; document.getElementById('nameVariation').value = ""; document.getElementById('brandVariation').value = ""; document.getElementById('skuVariation').value = ""; document.getElementById('stockVariation').value = ""; variationsList.push(newVariation); tableVariations(variationsList); }else{ messageErrorStock(); } }else{ messageErrorSku(); } }); }else{ messageErrorForm(); } } function editVariationList(){ if($('#nameEditVariation').val().trim() && $('#brandEditVariation').val().trim() && $('#skuEditVariation').val().trim() && $('#stockEditVariation')){ var sku = document.getElementById('skuEditVariation').value ; $.get('/variations/validateSku/'+ sku , function (data) { if(data){ if(document.getElementById('stockEditVariation').value > 0){ var newVariation = { "name": document.getElementById('nameEditVariation').value, "brand": document.getElementById('brandEditVariation').value, "sku": document.getElementById('skuEditVariation').value, "stock": document.getElementById('stockEditVariation').value }; document.getElementById('nameEditVariation').value = ""; document.getElementById('brandEditVariation').value = ""; document.getElementById('skuEditVariation').value = ""; document.getElementById('stockEditVariation').value = ""; variationsList.push(newVariation); tableVariations(variationsList); }else{ } }else{ } }); }else{ messageErrorForm(); } } function openDeleteModalVariation(idVariation){ $("#deleteModalVariation").modal("show"); variationSelected = idVariation; } function deleteVariation() { if(variationSelected != undefined){ var idVariation = variationSelected; $.ajax({ url: '/variations/deleteVariation/' + idVariation, type: 'DELETE', contentType: 'application/json' }); } variationsList.splice(variationsList.findIndex(element => element.id === idVariation),1); tableVariations(variationsList); $("#deleteModalVariation").modal("hide"); } function messageSucces(){ Swal.fire({ icon: 'success', title: 'Datos guardados', showConfirmButton: false, timer: 2000 }); } function messageDelete(){ Swal.fire({ icon: 'success', title: 'Datos eliminados', showConfirmButton: false, timer: 2000 }); } function messageErrorStock(){ Swal.fire({ icon: 'error', title: 'ERROR', text: 'El valor de stock debe ser igual o mayor a 1', showConfirmButton: false, timer: 2000 }); } function messageErrorPriceCost(){ Swal.fire({ icon: 'error', title: 'ERROR', text: 'El costo debe ser menor al precio', showConfirmButton: false, timer: 2000 }); } function messageErrorSku(){ Swal.fire({ icon: 'error', title: 'ERROR', text: 'SKU ya regitrado', showConfirmButton: false, timer: 2000 }); } function messageErrorForm(){ Swal.fire({ icon: 'error', title: 'ERROR', text: 'Debe llenar todos los datos', showConfirmButton: false, timer: 2000 }); } showCompanies();
Markdown
UTF-8
3,764
3.375
3
[]
no_license
# The REST API in a nutshell The REST API is very easy to use. From a technical standpoint is simply comes down that your website or app sends HTTP requests to Copernica's servers: HTTP GET requests to fetch data, and POST and PUT requests to modify data. These requests are processed by our API servers, and the requested data is sent back in a format that can easily be handled by computers (JSON). ## Registering your app To prevent that unauthorized applications get access to the API, you must first register your website or app with Copernica. Only after you have registered and you have a valid API access token, you can start making calls to the REST API. The registration form for the REST API can be found on the dashboard of the Copernica website. This is probably not the location that you had expected, because we usually use the Marketing Suite of the Publisher for these kind of configuration forms. However, the REST API registration forms can only be found on the [the dashboard](/en/applications) on www.copernica.com. If you register an application, it is best to use a descriptive name, for example the address of the website from where you will be making the API calls. Copernica uses the [*OAuth*](./rest-oauth.md) protocol to authorize applications to access the REST API. This is a standardized protocol in which you first have to register the application that is going to make the API calls, and then you have to link this application to one or more accounts. It is possible to give a single application access to multiple accounts. The Copernica dashboard has forms to perform both steps: registering the application, and linking it to accounts. After you've registered your application and have linked it to your account, you receive an API access token. This is a long string of alphanumeric characters that you should pass to each API call. Once you have this access token, you can test whether you have access to the API by entering the following URL in your browser: `https://api.copernica.com/v1/identify?access_token=youraccesstoken` The text "youraccesstoken" should of course be replaced by the access token that was given to you in the dashboard. If you have successfully completed the registration process, this method returns a JSON object with the name of your company and account. ## HTTP requests The REST API uses the HTTP protocol for exchanging data. Your website or app simply can simply send a HTTP request to one of our API servers to fetch or update data. There are four types of requests that are supported: * HTTP GET to fetch data * HTTP POST to add/append data * HTTP PUT to edit/modify data * HTTP DELETE to remove data This distinction is important. It makes a big difference whether you send a HTTP GET or a HTTP POST request to the server. GET is used for retrieving data, and POST/PUT to modify things. In practice the difference between HTTP POST and HTTP PUT is not so sharp. For most URL's our servers treat the POST and PUT requests completely the same. If you send a POST request to a method that only supports PUT, we treat your call as if it was a PUT call. However, there are methods that do treat PUT and POST differently, so we recommend to stick to the recommendations: POST is used for adding data, and PUT for modify'ing. Every API request requires a access_token parameter. You can simply add this parameter to the URL as a regular get-parameter. ## More information De following articles also contain information about the REST API: * [OAuth integrations with the REST API](./rest-oauth.md) * [The format of requests and responses](./rest-requests.md) * [Overview of all available API methods](./rest-api.md) * [Paging though lists of entities](./rest-paging.md)
Markdown
UTF-8
991
3.3125
3
[]
no_license
## `限价单`<div id='insert_limit_order'></div> `context.insert_limit_order(instrument_id, exchange_id, account_id,limit_price, volume, side, offset)` **参数** | 参数 | 类型 | 说明 | | ------------- | :---: | -------- | | instrument_id | str | 合约ID | | exchange_id | str | 交易所ID | | account_id | str | 交易账号 | | limit_price | float | 价格 | | volume | int | 数量 | | side | str | 买卖方向 | | offset | str | 开平方向 | **返回** | 返回 | 类型 | 说明 | | :------: | ---- | :----: | | order_id | long | 订单ID | **范例** - 通过交易账户acc_1以12.0的价格买200股浦发银行: `context.insert_limit_order("600000", Exchange.SSE, "acc_1", 12.0, 200, Side.Buy, Offset.Open)` - 通过交易账户acc_2以3500的价格开仓买入2手上期所rb1906合约: `context.insert_limit_order("rb1906", Exchange.SHFE, "acc_2", 3500.0, 2, Side.Buy, Offset.Open)`
Java
GB18030
6,660
2.75
3
[]
no_license
package until; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import dao.User; public class JDBC { private Connection conn=getConnection(); public Connection getConnection() { try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("ݿسɹ"); String url="jdbc:mysql://localhost:3306/tiantian?useUnicode=true&characterEncoding=utf-8"; conn=DriverManager.getConnection(url, "root", ""); System.out.println("ɹmysqlݿ⽨ӣ\n"); } catch(ClassNotFoundException e) { e.printStackTrace(); } catch(SQLException e) { e.printStackTrace(); } return conn; } public void select(Object obj) { Class c=obj.getClass(); System.out.println(c); System.out.println(c.getName() + "\n" + c.getSimpleName()); try { PreparedStatement pre=conn.prepareStatement("select *from " + c.getSimpleName()); ResultSet res=pre.executeQuery(); // // һijЩ Field 飬Щӳ Class ʾӿڵпɷʹֶΡ Field[] f=c.getDeclaredFields(); while(res.next()) { for(int i=0; i < f.length; i++) { f[i].setAccessible(true); // ָϴ Field ʾֶΪֵָ f[i].set(obj, res.getObject(f[i].getName()));// res.getString("name"); // res.getString(1) // ָϴ Field ʾֶεֵ System.out.print(f[i].get(obj) + "\t"); } System.out.println(); } } catch(SQLException e) { e.printStackTrace(); } catch(IllegalArgumentException e) { // TODO Զɵ catch e.printStackTrace(); } catch(IllegalAccessException e) { // TODO Զɵ catch e.printStackTrace(); } } // insert into User(User_id, User_name, User_password, // User_telephone,User_idcard,User_sex,User_birthday)values(?,?,?,?,?,?,?)" public void insert(Object obj) { Class c=obj.getClass(); StringBuffer str=new StringBuffer("insert into " + c.getName() + "("); Field[] f=c.getDeclaredFields(); for(int i=0; i < f.length; i++) { if(i + 1 == f.length) str.append(f[i].getName() + ")values("); else str.append(f[i].getName() + ", "); } for(int i=0; i < f.length; i++) { if(i + 1 == f.length) str.append("?)"); else str.append("?, "); } try { PreparedStatement pre=conn.prepareStatement(str.toString()); for(int i=0; i < f.length; i++) { f[i].setAccessible(true); pre.setObject(i + 1, f[i].get(obj)); System.out.print(f[i].get(obj) + "\t"); } pre.executeUpdate(); // ResultSet res=pre.executeQuery(); } catch(SQLException e) { e.printStackTrace(); } catch(IllegalArgumentException e) { // TODO Զɵ catch e.printStackTrace(); } catch(IllegalAccessException e) { // TODO Զɵ catch e.printStackTrace(); } } public void delete(Object obj) { Class c=obj.getClass(); Field[] f=c.getDeclaredFields(); try { f[0].setAccessible(true); PreparedStatement pre=conn.prepareStatement("delete from " + c.getName() + " where " + f[0].getName() + "=?"); pre.setObject(1, f[0].get(obj)); pre.executeUpdate(); } catch(SQLException e) { e.printStackTrace(); } catch(IllegalArgumentException e) { e.printStackTrace(); } catch(IllegalAccessException e) { // TODO Զɵ catch e.printStackTrace(); } } // update Rent_rented set Rent_rented_station=?,End_time=? where User_id=? and House_id=? public void update(Object obj) { Class c=obj.getClass(); try { StringBuffer str=new StringBuffer("update " + c.getName() + " set "); Field[] f=c.getDeclaredFields(); for(int i=1; i < f.length; i++) { if(i + 1 == f.length) str.append(f[i].getName() + "=? where " + f[0].getName() + "=?"); else str.append(f[i].getName() + "=?, "); } PreparedStatement pre=conn.prepareStatement(str.toString()); for(int i=0; i < f.length; i++) { f[i].setAccessible(true); if(i == 0) pre.setObject(f.length, f[0].get(obj)); else pre.setObject(i, f[i].get(obj)); } pre.executeUpdate(); } catch(SQLException e) { e.printStackTrace(); } catch(IllegalArgumentException e) { e.printStackTrace(); } catch(IllegalAccessException e) { e.printStackTrace(); } } public static void main(String[] args) { JDBC f=new JDBC(); // User user=new User("86868686", "HG", "123456", "1882929", "75437894", "", new Date(2015 // - 1900, 8 - 1, 8)); // f.insert(user); /* User user=new User("222", "HG", "654321", "1882929", "8888888888888", "Ů", new Date(2015 - 1900, 8 - 1, 8)); f.update(user);*/ User user = new User(); f.select(user); } }
C#
UTF-8
4,131
3.109375
3
[ "MIT" ]
permissive
using System; using System.IO; /// <summary> /// IMG sharp namespace /// </summary> namespace IMGSharp { /// <summary> /// IMG entry class /// </summary> internal class IMGArchiveEntry : IIMGArchiveEntry { /// <summary> /// IMG archive /// </summary> private IMGArchive archive; /// <summary> /// Data is available /// </summary> private bool available = true; /// <summary> /// IMG archive /// </summary> public IIMGArchive Archive => archive; /// <summary> /// Data offset in bytes /// </summary> public long Offset { get; } /// <summary> /// Length in bytes /// </summary> public int Length { get; } /// <summary> /// Full name /// </summary> public string FullName { get; } /// <summary> /// Is new entry /// </summary> public bool IsNewEntry { get; } /// <summary> /// Name /// </summary> public string Name => Path.GetFileName(FullName); /// <summary> /// Constructor /// </summary> /// <param name="archive">Archive</param> /// <param name="offset">Data offset</param> /// <param name="length">Length in bytes</param> /// <param name="fullName">Full name</param> internal IMGArchiveEntry(IMGArchive archive, long offset, int length, string fullName) { this.archive = archive; Offset = offset; Length = length; FullName = fullName; } /// <summary> /// Constructor /// </summary> /// <param name="archive">Archive</param> /// <param name="offset">Data offset</param> /// <param name="length">Length in bytes</param> /// <param name="fullName">Full name</param> /// <param name="isNewEntry">Is new entry</param> internal IMGArchiveEntry(IMGArchive archive, long offset, int length, string fullName, bool isNewEntry) { this.archive = archive; Offset = offset; Length = length; FullName = fullName; IsNewEntry = isNewEntry; } /// <summary> /// Commit changes /// </summary> private void Commit(IIMGArchiveEntryStream stream) { if (archive.AccessMode != EIMGArchiveAccessMode.Read) { archive.CommitEntry(this, stream); } } /// <summary> /// Delete IMG archive entry /// </summary> public void Delete() { if (available) { available = false; if (archive.InternalEntries.Remove(FullName.ToLower())) { archive.CommitEntry(null, null); } } } /// <summary> /// Open IMG archive entry /// </summary> /// <returns>Stream to archive entry if successful, otherwise "null"</returns> public IIMGArchiveEntryStream Open() { IIMGArchiveEntryStream ret = null; try { if (available && archive.Stream.CanRead) { byte[] data = new byte[Length]; archive.Stream.Seek(Offset, SeekOrigin.Begin); archive.Stream.Read(data, 0, Length); ret = new IMGArchiveEntryStream(this); ret.Stream.Write(data, 0, data.Length); ret.Stream.Seek(0L, SeekOrigin.Begin); ret.OnIMGArchiveEntryClosed += (entry, stream) => (entry as IMGArchiveEntry)?.Commit(stream); } } catch (Exception e) { if (ret != null) { ret.Dispose(); ret = null; } Console.Error.WriteLine(e); } return ret; } } }
C++
UTF-8
586
3.078125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); if(n == 0) return 0; vector<int> profit(n, 0); int min_price = prices[0], max_profit = 0; for(int i = 1; i < n; i++){ profit[i] = max(profit[i - 1], prices[i] - min_price); if(min_price > prices[i]) min_price = prices[i]; if(profit[i] > max_profit) max_profit = profit[i]; } return max_profit; } };
C
UTF-8
2,578
2.640625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* do_command.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: volyvar- <volyvar-@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/28 16:47:03 by volyvar- #+# #+# */ /* Updated: 2020/12/08 21:19:58 by volyvar- ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" int ft_do_simple_command(char **command_parts, t_env **myenv) { if (!ft_strcmp(command_parts[0], "echo")) ft_do_echo(command_parts, *myenv); else if (!ft_strcmp(command_parts[0], "env")) ft_print_env(command_parts, *myenv); else if (!ft_strcmp(command_parts[0], "setenv")) ft_do_setenv(command_parts, myenv); else if (!ft_strcmp(command_parts[0], "clear")) ft_do_clear(command_parts); else if (!ft_strcmp(command_parts[0], "unsetenv")) ft_do_unsetenv(command_parts, myenv); else if (!ft_strcmp(command_parts[0], "help")) ft_do_help(command_parts); else if (!ft_strcmp(command_parts[0], "iamgay")) ft_iamgay(command_parts); else if (!ft_strcmp(command_parts[0], "iambi")) ft_iambi(command_parts); else return (1); return (0); } int ft_do_hard_command(char **command_parts, t_env **myenv, uint8_t *exit_stat) { if (!ft_strcmp(command_parts[0], "cd")) { *exit_stat = ft_do_cd(command_parts, myenv); return (0); } else if (!ft_strcmp(command_parts[0], "exit")) { return (ft_do_exit(command_parts, exit_stat)); } else { ft_do_process(command_parts, myenv, exit_stat); return (0); } } int ft_do_command(char *command, t_env **myenv, uint8_t *exit_stat) { char **command_parts; int ret; command_parts = NULL; if (!(command_parts = ft_strsplit_sh(command, ' ', '\t'))) ft_error(); if (!command_parts) return (0); if (!command_parts[0]) { free(command_parts); return (0); } if (!ft_do_simple_command(command_parts, myenv)) { *exit_stat = 0; ret = 0; } else ret = ft_do_hard_command(command_parts, myenv, exit_stat); ft_free_after_split(command_parts); free(command_parts); return (ret); }
C#
UTF-8
5,823
2.625
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; using taskt.Core.Attributes.ClassAttributes; using taskt.Core.Attributes.PropertyAttributes; using taskt.Core.Command; using taskt.Core.Enums; using taskt.Core.Infrastructure; using taskt.Core.Utilities.CommonUtilities; using taskt.Engine; using taskt.UI.CustomControls; namespace taskt.Commands { [Serializable] [Group("DataTable Commands")] [Description("This command removes specific DataRows from a DataTable.")] public class RemoveDataRowCommand : ScriptCommand { [XmlAttribute] [PropertyDescription("DataTable")] [InputSpecification("Enter an existing DataTable.")] [SampleUsage("{vDataTable}")] [Remarks("")] [PropertyUIHelper(UIAdditionalHelperType.ShowVariableHelper)] public string v_DataTable { get; set; } [XmlAttribute] [PropertyDescription("Removal Tuple")] [InputSpecification("Enter a tuple containing the column name and item you would like to remove.")] [SampleUsage("(ColumnName1,Item1),(ColumnName2,Item2) || ({vColumn1},{vItem1}),({vCloumn2},{vItem2}) || {vRemovalTuple}")] [Remarks("")] [PropertyUIHelper(UIAdditionalHelperType.ShowVariableHelper)] public string v_SearchItem { get; set; } [XmlAttribute] [PropertyDescription("Overwrite Option")] [PropertyUISelectionOption("And")] [PropertyUISelectionOption("Or")] [InputSpecification("Indicate whether this command should remove rows with all the constraints or remove them with 1 or more constraints.")] [SampleUsage("")] [Remarks("")] public string v_AndOr { get; set; } public RemoveDataRowCommand() { CommandName = "RemoveDataRowCommand"; SelectionName = "Remove DataRow"; CommandEnabled = true; CustomRendering = true; } public override void RunCommand(object sender) { var engine = (AutomationEngineInstance)sender; var vSearchItem = v_SearchItem.ConvertUserVariableToString(engine); DataTable Dt = (DataTable)v_DataTable.ConvertUserVariableToObject(engine); var t = new List<Tuple<string, string>>(); var listPairs = vSearchItem.Split(')'); int i = 0; listPairs = listPairs.Take(listPairs.Count() - 1).ToArray(); foreach (string item in listPairs) { string temp; temp = item.Trim('(', '"'); var tempList = temp.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); for (int z = 0; z < tempList.Count; z++) { tempList[z] = tempList[z].Trim('('); } t.Insert(i, Tuple.Create(tempList[0], tempList[1])); i++; } List<DataRow> listrows = Dt.AsEnumerable().ToList(); if (v_AndOr == "Or") { List<DataRow> templist = new List<DataRow>(); //for each filter foreach (Tuple<string, string> tuple in t) { //for each datarow foreach (DataRow item in listrows) { if (item[tuple.Item1] != null) { if (item[tuple.Item1].ToString() == tuple.Item2.ToString()) { //add to list if filter matches if (!templist.Contains(item)) templist.Add(item); } } } } foreach (DataRow item in templist) { Dt.Rows.Remove(item); } Dt.AcceptChanges(); Dt.StoreInUserVariable(engine, v_DataTable); } //If And operation is checked if (v_AndOr == "And") { List<DataRow> templist = new List<DataRow>(listrows); //for each tuple foreach (Tuple<string, string> tuple in t) { //for each datarow foreach (DataRow drow in Dt.AsEnumerable()) { if (drow[tuple.Item1].ToString() != tuple.Item2) { //remove from list if filter matches templist.Remove(drow); } } } foreach (DataRow item in templist) { Dt.Rows.Remove(item); } Dt.AcceptChanges(); //Assigns Datatable to newly updated Datatable Dt.StoreInUserVariable(engine, v_DataTable); } } public override List<Control> Render(IfrmCommandEditor editor) { base.Render(editor); RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_DataTable", this, editor)); RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_SearchItem", this, editor)); RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_AndOr", this, editor)); return RenderedControls; } public override string GetDisplayValue() { return base.GetDisplayValue() + $" [Remove Rows With '{v_SearchItem}' From '{v_DataTable}']"; } } }
Python
UTF-8
316
2.890625
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 import numpy as np def first_half_second_half(a): first, second = np.split(a, 2, axis=1) # (first version): c = first.sum(axis=1) > second.sum(axis=1) c = np.sum(first, axis=1) > np.sum(second, axis=1) return a[c] def main(): pass if __name__ == "__main__": main()
Markdown
UTF-8
4,285
3.296875
3
[ "MIT", "GPL-1.0-or-later", "CC-BY-4.0", "CC-BY-SA-2.0", "LicenseRef-scancode-public-domain" ]
permissive
--- layout: doc title: 航空影像 permalink: /zh_CNjosm/aerial-imagery/ lang: zh_CN category: josm --- 航空影像 ================ > 已审核 2015-09-21 描绘影像是为OSM做出贡献的一种简单而有力的方式。使用影像在地面上绘制点、线和形状被称为**数字化**。它通常可以与在地面上收集属性数据的行为分开,后者通常被称为**地面实测**。数字化影像可以提供OSM地图的骨架,这使得地面实测人员在野外更容易作业。在本章中,我们将进一步了解航空影像的工作原理。 关于影像 ------------- 航空图像是我们用来描述从天空拍摄的照片的术语,可以从飞机、无人机、直升机、甚至风筝和气球上拍摄,但最常见的影像来源是围绕地球运行的卫星。 [在关于GPS的一章中](/zh_CN/mobile-mapping/using-gps),我们了解了环绕地球运行的几十颗卫星,这些卫星使我们的GPS接收器能够确定我们的经纬度。除了这些GPS卫星,还有一些卫星可以拍摄地球的照片。这些照片经过处理后,可用于GIS(绘图)软件。Bing航空影像就是由卫星照片组成的。 分辨率 ---------- 所有的数码照片都是由像素组成的。如果你把照片放大到很近,你会发现图像开始变得模糊,最后你会发现图像是由成千上万个小方块组成的,每个小方块都有不同的颜色。无论照片是用手持相机、手机还是环绕地球的卫星拍摄,都是如此。 ![Image resolution][] 分辨率指的是图像的水平方向像素数乘以垂直方向像素数。像素越多意味着分辨率越高,也就是说你能够看到照片中更多的细节。手持相机的分辨率通常以百万像素为单位。你的相机能够记录的百万像素越多,照片的分辨率就越高。 航空影像也是一样的,只是我们通常对分辨率的说法不同。对于航空照片来说,测量是很重要的 - 因此,一个像素代表着地面上的一定距离。我们通常把影像描述为"两米分辨率影像"之类的,也就是说,一个像素相当于地面上的两米。一米分辨率的影像的分辨率会比这个高,50厘米的分辨率就更高了。这一般是Bing提供的图像范围,不过不同地方的图像范围有所不同,很多地方的影像比两米还差,这时就很难识别图像中的物体了。 ![Comparison of low and high resolution imagery][] 航空影像的分辨率越高,用来制作地图就越容易。 地理参考 --------------- 航空影像的每个像素都有一个尺寸,每个像素也有一个位置。如上所述,这是因为航空影像是有地理坐标的。 就像GPS点有经纬度一样,航空图像中的像素也会有经纬度。然而,正如较低的分辨率会给测绘带来挑战一样,糟糕的几何校正的影像也会带来挑战。 让我们想一想地理参考是如何工作的,以及为什么它具有挑战性。当有人对一张图片进行地理参考时,他们首先会识别出图片中少数几个已知位置的像素。如果我们有一张正方形的照片,我们可能会确定所有四个角的坐标,这样整个图像就可以被正确放置。 这一切看起来很简单,但想想看,地球是圆的,相机镜头是圆的,但照片却是平面的、二维的。这意味着,当一个平面的图像被映射到圆形的地球上时,总是会有一些图像的拉伸和变形。想象一下,试图将一个橘子皮压平。它不会最终变成长方形。由于这个问题,航拍图像中的所有像素可能不会都被完美放置。 幸运的是,一些非常聪明的人已经设计了聪明的算法来解决这个问题,所以你在Bing上看到的图像非常接近准确。在大多数地方,它根本不会有明显的错误 - 而且它对于制作地图来说肯定是没有问题的。最常见的图像不准确的地方是在丘陵、山区。在 [校正影像偏移章节](/zh_CN/josm/correcting-imagery-offset)中,我们将看到如何纠正这个问题。 [Image resolution]: /images/josm/orange-resolution.png [Comparison of low and high resolution imagery]: /images/josm/low-res-high-res.png
Python
UTF-8
2,393
2.65625
3
[]
no_license
import json import os import re import requests from newsapi.articles import Articles from newsapi.sources import Sources API_KEY = "f044f5b63a7c4139858611a1ae6dc5f0" s = Sources(API_KEY=API_KEY) a = Articles(API_KEY=API_KEY) # print(s.information().all_categories()) # print(s.get_by_category("general")) def get_country_news(country): country_id = country + "&" url = ('https://newsapi.org/v2/top-headlines?' 'country=' + country_id + 'apiKey=' + API_KEY) response = requests.get(url) response = response.json() path = os.path.join(os.getcwd(), "posts") path = os.path.join(path, "regional_news") path = os.path.join(path, country) for main_key in response.items(): if main_key[0] == "articles": for posts in main_key[1]: posts = json.loads(json.dumps(posts)) print(posts) filename = re.sub(r'[^\w]', ' ', posts['title']) filename = filename.replace(" ", "_") + ".json" print(filename) with open(os.path.join(path, filename), "w") as output: json.dump(posts, output) # 'sources=bbc-news&' # 'country=us&' # 'q=Apple&' # 'from=2018-05-30&' # 'sortBy=popularity&' # url = ('https://newsapi.org/v2/top-headlines?' # 'sources=' + source + # 'apiKey=' + API_KEY) # response = requests.get(url) # response = response.json() def get_post_by_category(category): res = s.get_by_category(category=category) for i in res.items(): if i[0] == "sources": post_list = i[1] # for each post for post in post_list: # print(post) path = os.path.join(os.getcwd(), "posts") path = os.path.join(path, category) path = os.path.join(path, post["id"] + ".json") response = a.get_by_popular(post['id']) # print(content) # print(id) # print(post) print(response) with open(path, "w") as output: json.dump(response, output) print("_____________________") # get_post_by_category("general") # get_post_by_category("technology") # get_post_by_category("sports") # get_post_by_category("business") # get_post_by_category("entertainment") # get_post_by_category ("science") get_country_news("ro")
Go
UTF-8
1,456
2.515625
3
[]
no_license
package main import ( "context" "errors" "log" "net/http" "os" "os/signal" "sync" "time" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { cfg, err := ReadServerConfig("config.yml") if err != nil { log.Fatalf("failed to read config: %v", err) } mc, err := mongo.Connect(context.Background(), options.Client().ApplyURI(cfg.MongoDB.URI)) if err != nil { log.Fatalf("failed to connect to mongodb: %v", err) } defer mc.Disconnect(context.Background()) ss := NewStoreService(cfg.MongoDB, mc) if err := ss.CreateIndexes(context.Background()); err != nil { log.Fatalf("failed to create mongodb indexes: %v", err) } s := NewServer(cfg, ss) ctx, cancel := context.WithCancel(context.Background()) var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() log.Printf("server listening on %s", cfg.BindAddr) if err := s.Start(cfg.BindAddr); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatalf("failed to run server: %v", err) } }() go func() { defer wg.Done() log.Printf("starting updater") if err := s.StartUpdater(ctx); err != nil { log.Fatalf("failed to run updater: %w", err) } }() sig := make(chan os.Signal, 1) signal.Notify(sig, os.Interrupt) <-sig log.Printf("gracefully shutting down") cancel() if err := s.ShutdownWithTimeout(10 * time.Second); err != nil { log.Fatalf("failed to shutdown server: %v", err) } wg.Wait() }
Markdown
UTF-8
2,076
2.65625
3
[ "MIT" ]
permissive
--- layout: post title: 某朋友博客上的 author: gavinkwoe date: !binary |- MjAwNi0xMi0xMyAxNzo0MzowNiArMDgwMA== date_gmt: !binary |- MjAwNi0xMi0xMyAwOTo0MzowNiArMDgwMA== --- <p dir="ltr" style="MARGIN-RIGHT: 0px">暴强啊~! 这公司太帅了!要是我们公司也这样就 Happy 了…… <blockquote dir="ltr" style="MARGIN-RIGHT: 0px"> 从2004年11月开始就职于现在这家网络公司,说白了就是一鼓捣网站的公司 至今公司存活2年多了,从原来的50多人发展到现在的10来个人 从原来的游戏网、生活网、社区论坛3个站发展到现在的一个站也没有 可说是前途无量~~~ 给公司算了笔帐,现在月工资投入大约需要8W元(别看就10来个人) 其中4万是总监工资(总监加经理有5个人,我有幸成为他们其中之一) 办公室200平,月2W元租金 加上其他一些办公和固定投入一个月10W应该够了。 从2006年开始,我每天的任务就是早9点上班,坐在那里等到18点下班 给我的感受就是公司花钱雇我在这坐着。 我们公司真有钱啊,一年多了,啥项目没有,啥钱没赚 还在这坚挺着。听总经理那意思,怎么的也得等2008再倒闭 因为投资人的钱还没花完... 谁投资的啊~~~现在这样的菩萨上哪找啊!!! 我就这样的残废了~~~ 2004年11月&mdash;&mdash;2005年9月 网页设计 工资3000 2005年9月&mdash;&mdash;2006年5月 网站管理兼社区运营 工资4000[其中干满一年加了500] 2006年5月至今 网站总监 工资5000[其中干满了2年加了500] </blockquote> <p dir="ltr">和一群同样强的同事…… <blockquote dir="ltr" style="MARGIN-RIGHT: 0px"> <p dir="ltr">汇报下公司现在人员动态: 4个人出去抽烟,讨论之前结束的魔兽争霸2V2对战情况 1个人在逛淘宝性用品店,听说他女朋友和他分手已经1年多了,最近火大 1个人在和女朋友聊天,他每天都聊,从早9点聊到下班,他有3个女朋友 剩下的全在游戏中... </blockquote>
C++
UTF-8
8,649
2.71875
3
[]
no_license
#include <iostream> #include <assert.h> #include <stdlib.h> #include <time.h> #include <stdio.h> #include "chip8.h" #include "chip8_fontset.h" using namespace std; Chip8::Chip8(){} Chip8::~Chip8(){} // Clear the memory, registers, and screen void Chip8::initialize(){ pc = 0x200; // Start of program counter opcode = 0; // Reset current opcode I = 0; // Reset index register sp = 0; // Reset stack pointer // Reset random seed srand(time(NULL)); // Clear display for (int i = 0; i < WIDTH * HEIGHT; ++i) gfx[i] = 0; drawFlag = true; // Clear stack for (int i = 0; i < STACK_SIZE; ++i) stack[i] = 0; // Clear keys (all unpressed) for (int i = 0; i < NUM_KEYS; ++i) key[i] = 0; // Clear registers V0-VF for (int i = 0; i <= 0xF; ++i) V[i] = 0; // Clear memory for (int i = 0; i < MEMORY_SIZE; ++i) memory[i] = 0; // Load fontset for (int i = 0; i < 80; ++i){ memory[i] = chip8_fontset[i]; } // Reset timers delay_timer = 0; sound_timer = 0; soundFlag = false; } // Copy the program into the memory bool Chip8::loadGame(const char* filename){ FILE * pFile = fopen(filename, "rb"); assert(pFile != NULL); // Check file size fseek(pFile , 0 , SEEK_END); long lSize = ftell(pFile); rewind(pFile); // Allocate memory to contain the whole file char * buffer = (char*)malloc(sizeof(char) * lSize); if (buffer == NULL) { fputs ("Memory error", stderr); return false; } // Copy the file into the buffer size_t result = fread (buffer, 1, lSize, pFile); if (result != lSize) { fputs("Reading error",stderr); return false; } // Copy buffer to Chip8 memory if(lSize >= 4096 - 512){ printf("Error: ROM too big for memory"); return false; } for(int i = 0; i < lSize; ++i) memory[i + 512] = buffer[i]; // Close file, free buffer fclose(pFile); free(buffer); return true; } void print_hex(unsigned short c){ cout << hex << "0x" << ((c<0x10)?"0":"") << ((c<0x100)?"0":"") << ((c<0x1000)?"0":"") << (static_cast<unsigned int>(c) & 0xFFFF) << dec << endl; } bool op_error = false; void Chip8::unknown_opcode(){ cout << "Unknown opcode: "; print_hex(opcode); op_error = true; } void Chip8::op_debug(){ cout << "PC: " << pc << ", opcode: "; print_hex(opcode); } // Emulate one cycle of the system void Chip8::emulateCycle(){ if (op_error) return; // Fetch opcode opcode = memory[pc] << 8 | memory[pc + 1]; // Uses bit-shifting and bitwise OR to combine the two byte opcode into one piece of data // Decode opcode and execute opcode // Reference: https://en.wikipedia.org/wiki/CHIP-8#Opcode_table unsigned short NNN = opcode & 0x0FFF; unsigned short NN = opcode & 0x00FF; unsigned short N = opcode & 0x000F; unsigned short X = (opcode & 0x0F00) >> 8; unsigned short Y = (opcode & 0x00F0) >> 4; switch (opcode & 0xF000){ case 0x0000: switch (N){ case 0x0000: // 00E0: Clears the screen for (int i = 0; i < WIDTH * HEIGHT; ++i) gfx[i] = 0; drawFlag = true; pc += 2; break; case 0x000E: // 00EE: Returns from subroutine --sp; pc = stack[sp] + 2; break; default: unknown_opcode(); } break; case 0x1000: // 1NNN: Jumps to address at NNN pc = NNN; break; case 0x2000: // 2NNN: Calls subroutine at NNN stack[sp] = pc; ++sp; pc = NNN; break; case 0x3000: // 3XNN: Skips the next instruction if VX equals NN if (V[X] == NN) pc += 4; else pc += 2; break; case 0x4000: // 4XNN: Skips the next instruction if VX doesn't equal NN if (V[X] != NN) pc += 4; else pc += 2; break; case 0x5000: // 5XY0: Skips the next instruction if VX equals VY if (V[X] == V[Y]) pc += 4; else pc += 2; break; case 0x6000: // 6XNN: Sets VX to NN V[X] = NN; pc += 2; break; case 0x7000: // 7XNN: Addes NN to VX V[X] += NN; pc += 2; break; case 0x8000: switch(N){ case 0x0000: // 8XY0: Sets VX to the value of VY V[X] = V[Y]; pc += 2; break; case 0x0001: // 8XY1: Sets VX to VX or VY V[X] |= V[Y]; pc += 2; break; case 0x0002: // 8XY2: Sets VX to VX and VY V[X] &= V[Y]; pc += 2; break; case 0x0003: // 8XY3: Sets VX to VX xor VY V[X] ^= V[Y]; pc += 2; break; case 0x0004: // 8XY4: Adds VY to VX. VF set to 1 if there's a carry, else 0 if (V[X] + V[Y] > 0xFF) V[0xF] = 1; // carry else V[0xF] = 0; // No carry V[X] += V[Y]; pc += 2; break; case 0x0005: // 8XY5: VY is subtracted from VX. VF is set to 0 when there's a borrow, else 1 if (V[X] - V[Y] < 0) V[0xF] = 0; // borrow else V[0xF] = 1; // no borrow V[X] -= V[Y]; pc += 2; break; case 0x0006: // 8XY6: Stores the least sig. bit of VX in VF and then shifts VX to the right by 1 V[0xF] = V[X] & 0x000F; V[X] >>= 1; pc += 2; break; case 0x0007: // 8XY7: Sets VX to VY minus VX. VF is set to 0 when there's a borrow, else 1 if (V[Y] - V[X] < 0) V[0xF] = 0; // borrow else V[0xF] = 1; // no borrow V[X] = V[Y] - V[X]; pc += 2; break; case 0x000E: // 8XYE: Stores the most sig. bit of VX in VF and then shifts VX to the left by 1 V[0xF] = V[X] >> 7; // Most significant bit V[X] <<= 1; pc += 2; break; default: unknown_opcode(); } break; case 0x9000: // 9XY0: Skips the next instruction if VX doesn't equal VY if (V[X] != V[Y]) pc += 4; else pc += 2; break; case 0xA000: // ANNN: Sets I to the address NNN I = NNN; pc += 2; break; case 0xB000: // BNNN: Jumps to the address NNN plus V0 pc = NNN + V[0]; break; case 0xC000: // CXNN: Sets VX to the result of a bitwise and operation on a random number (0 to 255) and NN V[X] = (rand() % 255) & NN; pc += 2; break; case 0xD000: // DXYN: Draws 8xN pixel sprite at (VX, VY). See reference table { unsigned short x = V[X]; // Fetch coordinate value from registers unsigned short y = V[Y]; unsigned short pixel; // Pixel value V[0xF] = 0; // Reset VF register // Loop through each row for (int yline = 0; yline < N; ++yline){ pixel = memory[I + yline]; // Fetch pixel value from memory starting at I // Loop over 8 bits of one row for (int xline = 0; xline < 8; ++xline){ // Scan through each byte of currently evaluated pixel to check if it is 1 if ((pixel & (0x80 >> xline)) != 0){ // Check for collision and register result in VF int index = x + xline + ((y + yline) * WIDTH); if(gfx[index] == 1) V[0xF] = 1; // Set pixel value with XOR gfx[index] ^= 1; } } } drawFlag = true; // To be used by graphics implementation to update screen pc += 2; } break; case 0xE000: switch (NN){ case 0x009E: // EX9E: Skips the next instruction if the key stored in VX is pressed if (key[V[X]] != 0) pc += 4; else pc += 2; break; case 0x00A1: // EXA1: Skips the next instruction if the key stored in VX isn't pressed if (key[V[X]] == 0) pc += 4; pc += 2; break; default: unknown_opcode(); } break; case 0xF000: switch (NN){ case 0x0007: // FX07: Sets VX to the value of the delay timer V[X] = delay_timer; pc += 2; break; case 0x000A: // FX0A: A key press is awaited, and then stored in VX. Blocking Operation. for (int i = 0; i < NUM_KEYS; ++i){ if (key[i] != 0){ V[X] = i; pc += 2; break; } } // Don't increment pc because it's a blocking operation break; case 0x0015: // FX15: Sets the delay timer to VX delay_timer = V[X]; pc += 2; break; case 0x0018: // FX18: Sets the sound timer to VX sound_timer = V[X]; pc += 2; break; case 0x001E: // FX1E: Adds VX to I if (I + V[X] > 0xFFF) V[0xF] = 1; // range overflow else V[0xF] = 0; I += V[X]; pc += 2; break; case 0x0029: // FX29: Sets I to the location of the sprite for the character in VX I = V[X] * 5; // Memory of fonts starts at 0x000, and each character is 5 px tall pc += 2; break; case 0x0033: // FX33: Stores the binary-coded decimal representation of VX. See reference table for specs. memory[I] = V[X] / 100; // Hundreds digit memory[I + 1] = (V[X] / 10) % 10; // Tens digit memory[I + 2] = (V[X] % 100) % 10; // Ones digit pc += 2; break; case 0x0055: // FX55: Stores V0 to VX (including VX) in memory starting at address I for (int i = 0; i <= X; ++i){ memory[I + i] = V[i]; } I += X + 1; pc += 2; break; case 0x0065: // FX65: Fills V0 to VX (including VX) with values from memory starting at address I for (int i = 0; i <= X; ++i){ V[i] = memory[I + i]; } I += X + 1; pc += 2; break; default: unknown_opcode(); } break; default: unknown_opcode(); } // Update timers if (delay_timer > 0) --delay_timer; if (sound_timer > 0){ if (sound_timer == 1) soundFlag = true; --sound_timer; } }
C++
UTF-8
2,649
2.65625
3
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
// RUN: %clang_cc1 -std=c++11 -verify %s // Note that this puts the expected lines before the directives to work around // limitations in the -verify mode. void test(int *List, int Length, int Value) { int i = 0; #pragma unroll_and_jam for (int i = 0; i < Length; i++) { for (int j = 0; j < Length; j++) { List[i * Length + j] = Value; } } #pragma nounroll_and_jam for (int i = 0; i < Length; i++) { for (int j = 0; j < Length; j++) { List[i * Length + j] = Value; } } #pragma unroll_and_jam 4 for (int i = 0; i < Length; i++) { for (int j = 0; j < Length; j++) { List[i * Length + j] = Value; } } /* expected-error {{expected ')'}} */ #pragma unroll_and_jam(4 /* expected-error {{missing argument; expected an integer value}} */ #pragma unroll_and_jam() /* expected-warning {{extra tokens at end of '#pragma unroll_and_jam'}} */ #pragma unroll_and_jam 1 2 for (int i = 0; i < Length; i++) { for (int j = 0; j < Length; j++) { List[i * Length + j] = Value; } } /* expected-warning {{extra tokens at end of '#pragma nounroll_and_jam'}} */ #pragma nounroll_and_jam 1 for (int i = 0; i < Length; i++) { for (int j = 0; j < Length; j++) { List[i * Length + j] = Value; } } #pragma unroll_and_jam /* expected-error {{expected a for, while, or do-while loop to follow '#pragma unroll_and_jam'}} */ int j = Length; #pragma unroll_and_jam 4 /* expected-error {{expected a for, while, or do-while loop to follow '#pragma unroll_and_jam'}} */ int k = Length; #pragma nounroll_and_jam /* expected-error {{expected a for, while, or do-while loop to follow '#pragma nounroll_and_jam'}} */ int l = Length; #pragma unroll_and_jam 4 /* expected-error {{incompatible directives '#pragma nounroll_and_jam' and '#pragma unroll_and_jam(4)'}} */ #pragma nounroll_and_jam for (int i = 0; i < Length; i++) { for (int j = 0; j < Length; j++) { List[i * Length + j] = Value; } } #pragma nounroll_and_jam #pragma unroll(4) for (int i = 0; i < Length; i++) { for (int j = 0; j < Length; j++) { List[i * Length + j] = Value; } } // pragma clang unroll_and_jam is disabled for the moment /* expected-error {{invalid option 'unroll_and_jam'; expected vectorize, vectorize_width, interleave, interleave_count, unroll, unroll_count, pipeline, pipeline_initiation_interval, vectorize_predicate, or distribute}} */ #pragma clang loop unroll_and_jam(4) for (int i = 0; i < Length; i++) { for (int j = 0; j < Length; j++) { List[i * Length + j] = Value; } } #pragma unroll_and_jam /* expected-error {{expected statement}} */ }
Markdown
UTF-8
2,519
2.671875
3
[]
no_license
# TensorFlow 中 tf.app.flags.FLAGS 的用法介绍 - lyc_yongcai的博客 - CSDN博客 2017年06月19日 09:31:41[刷街兜风](https://me.csdn.net/lyc_yongcai)阅读数:24225 下面介绍 tf.app.flags.FLAGS 的使用,主要是在用命令行执行程序时,需要传些参数,代码如下: 新建一个名为:app_flags.py 的文件。 ```python #coding:utf-8 # 学习使用 tf.app.flags 使用,全局变量 # 可以再命令行中运行也是比较方便,如果只写 python app_flags.py 则代码运行时默认程序里面设置的默认设置 # 若 python app_flags.py --train_data_path <绝对路径 train.txt> --max_sentence_len 100 # --embedding_size 100 --learning_rate 0.05 代码再执行的时候将会按照上面的参数来运行程序 import tensorflow as tf FLAGS = tf.app.flags.FLAGS # tf.app.flags.DEFINE_string("param_name", "default_val", "description") tf.app.flags.DEFINE_string("train_data_path", "/home/yongcai/chinese_fenci/train.txt", "training data dir") tf.app.flags.DEFINE_string("log_dir", "./logs", " the log dir") tf.app.flags.DEFINE_integer("max_sentence_len", 80, "max num of tokens per query") tf.app.flags.DEFINE_integer("embedding_size", 50, "embedding size") tf.app.flags.DEFINE_float("learning_rate", 0.001, "learning rate") def main(unused_argv): train_data_path = FLAGS.train_data_path print("train_data_path", train_data_path) max_sentence_len = FLAGS.max_sentence_len print("max_sentence_len", max_sentence_len) embdeeing_size = FLAGS.embedding_size print("embedding_size", embdeeing_size) abc = tf.add(max_sentence_len, embdeeing_size) init = tf.global_variables_initializer() #with tf.Session() as sess: #sess.run(init) #print("abc", sess.run(abc)) sv = tf.train.Supervisor(logdir=FLAGS.log_dir, init_op=init) with sv.managed_session() as sess: print("abc:", sess.run(abc)) # sv.saver.save(sess, "/home/yongcai/tmp/") # 使用这种方式保证了,如果此文件被其他文件 import的时候,不会执行main 函数 if __name__ == '__main__': tf.app.run() # 解析命令行参数,调用main 函数 main(sys.argv) ``` 调用方法: 其中参数可以根据需求进行修改。 ```python python app_flags.py --train_data_path <绝对路径 train.txt> --max_sentence_len 100 --embedding_size 100 --learning_rate 0.05 ``` 如果这样调用: ```python python app_flags.py ``` 则会执行程序时会自动调用程序中 default 中的参数。
Python
UTF-8
4,173
2.515625
3
[]
no_license
import math import gym from gym import * from gym import spaces from gym.utils import seeding import numpy as np import pandas as pd from statsmodels.tsa.vector_ar import var_model def limiter10(x): if x<=0.0: return 1e-12 if x>=1.0: return 1.0-1e-4 return(x) class MyGym(gym.Env): # based on description of model in metadata = {'render.modes': ['human']} def __init__(self,**kwargs): self.action_space=spaces.Box(np.array([1e-8]),np.array([1.0])) self._reset() print(self.observation.shape) self.observation_space = spaces.Box(-1.0e8, 1.0e8, self.observation.shape) self.z_t=1 self.rho=.9 self.sigma=np.sqrt(.0038) self.alpha=.7 self.delta=.025 self.phi=.8 # value of consumption relative to leisure -- .5 is balanced value between the two self.episode_len=99 self.t=0 self.sum_u_t=0.0 self.k_t1=1.0 self.l_t=kwargs.get("l_t",.3) self.n_t=1.0-self.l_t def _step(self,action): # set current capital based on last period ending capital old_observation=self.observation.copy() self.k_t=self.k_t1 # get economic shocks: self.z_t=np.exp((self.rho*np.log(self.z_t))+np.random.normal(0,self.sigma**2,1)[0]) #self.z_t=1 action[0]=limiter10(action[0]) self.c_action=action[0] # get current output given labor and shocks self.y_t = self.z_t * (self.k_t ** self.alpha) * self.n_t ** (1.0 - self.alpha) # set consumption and leisure based on actions self.c_t = action[0] * self.y_t if self.y_t>0 else 9e-5 # set investment self.i_t=self.y_t-self.c_t self.k_t1=self.k_t*(1-self.delta)+self.i_t # get ready to output state # self.state={"k_t":self.k_t,"k_t1":self.k_t1,"y_t":self.y_t,"i_t":self.i_t,"c_t":self.c_t,"l_t":self.l_t,"n_t":self.n_t} self.state={ "k_t":self.k_t, "k_t1":self.k_t1, "z_t":self.z_t, "y_t":self.y_t } self.set_observation(self.y_t, self.k_t, self.k_t1, self.z_t,old_observation=old_observation) self.u_t = (self.phi * np.log(self.c_t)) + ((1 - self.phi) * np.log(self.l_t)) self.t += 1 # add to total utilities since beginning of episode self.sum_u_t+= self.u_t done=(self.t>=self.episode_len or np.isnan(self.u_t)) or (self.y_t<0) return self.observation, self.u_t,done,{"reward":self.u_t} def _render(self,mode='human',close=False): if not close: print({"t":self.t,"n_t":self.n_t,"action":[ self.c_action,self.l_t],'reward':[self.u_t,self.sum_u_t],"state":self.state}) def _reset(self): self.t=0 self.sum_u_t=0.0 self.k_t1=10.0 self.z_t=1.0 self.k_t=self.k_t1 self.y_t=0.0 self.c_t=0.0 self.state={ "k_t":self.k_t, "k_t1":self.k_t1, "z_t":self.z_t } #self.episode_len=np.random.choice(range(50,99)) self.set_observation(self.y_t,self.k_t,self.k_t1,self.z_t, old_observation=[self.y_t,self.k_t,self.k_t1,self.z_t]) # # "k_t": self.k_t, # "k_t1": self.k_t1, # "y_t": self.y_t, # "i_t": self.i_t, # "c_t": self.c_t, # "l_t": self.l_t, # "n_t": self.n_t return self.observation def set_observation(self,y_t,k_t,k_t1,z_t,**kwargs): if kwargs.get('old_observation',None) is not None: obs=kwargs['old_observation'] # dk_t=k_t/obs[0] # dk_t1=k_t1/obs[1] # dy_t=y_t/obs[3] # self.observation = np.array([k_t, k_t1,y_t,dk_t,dk_t1,dy_t]) self.observation = np.array([k_t,self.c_t, k_t1, y_t,self.t]) else: self.observation= np.array([k_t, k_t1, z_t,y_t]) return self.observation def _seed(self,seed=None): if seed: np.random.seed(seed) else: pass # gym.envs.register( # id='RBCGym-v0', # entry_point='RBCGym', # )
Java
UTF-8
568
3.671875
4
[]
no_license
package Day5_LoopsSwitch; /** * Write a description of class While here. * * @author (your name) * @version (a version number or a date) */ public class WhileFor { public static void main(String args[]) { // How many times will this loop run // Whats gonna be the output? int count = 0; for(int i = 10; i>-10; i--) { count++; if(i%4==0) { System.out.println("MULTIPLE"); } } System.out.println(count); //20 } }
Markdown
UTF-8
695
2.671875
3
[]
no_license
# reuze REUZE is an environmentally friendly mobile app. Its goal is to help users locate resources whose materials they can use to design amazing upcycled works and art. Additionally, the app helps to reduce environmental impacts. The mobile app was designed with User Centered Design principles baked in to ensure that I empathized and understood users expressed and latent needs. User Journeys, surveys and interviews were used to accomplish this goal. Design Thinking is infused into the design process to ensure the mobile app works effectively. Mobile design patterns, gesture optimization, wireframes, prototypes and field testing were implemented to ensure the goal was achieved.
JavaScript
UTF-8
8,974
2.859375
3
[]
no_license
/** * @file Tests the Chunk class * @copyright Stephen R. Veit 2015 */ 'use strict'; var Chunk = require('../riff/chunk'), _ = require('lodash'); describe('Chunk', function () { var chunk; describe('with id and data parameters', function () { var data; beforeEach(function (done) { data = new Buffer([1, 2, 3, 4, 5]); chunk = Chunk.createChunk({id: 'RIFF', data: data}); done(); }); it('should return a chunk', function (done) { expect(chunk).not.toBeUndefined(); done(); }); it('should have a id of "RIFF"', function (done) { expect(chunk.id).toBe('RIFF'); done(); }); it('should have bufferLength', function (done) { expect(chunk.bufferLength).toBe(14); done(); }); it('should have a size', function (done) { expect(chunk.size).toBe(5); done(); }); it('should have contents', function (done) { expect(Buffer.isBuffer(chunk.contents)).toBe(true); done(); }); it('should have data', function (done) { expect(Buffer.isBuffer(chunk.data)).toBe(true); done(); }); it('should have decodeString', function (done) { expect(chunk.decodeString(0, 4)).toBe('RIFF'); done(); }); it('should have a spaces utility function', function (done) { expect(chunk.spaces(5)).toBe(' '); done(); }); it('should have a description', function (done) { expect(chunk.description()).toBe('RIFF(5)'); done(); }); describe('description with indentation of 4', function () { var description; beforeEach(function (done) { description = chunk.description(4); done(); }); it('should start with four spaces', function (done) { expect(description).toBe('RIFF(5)'); done(); }); }); }); describe('with no parameters', function () { beforeEach(function (done) { chunk = Chunk.createChunk(); done(); }); it('should return a chunk', function (done) { expect(chunk).not.toBeUndefined(); done(); }); it('should have a id of " "', function (done) { expect(chunk.id).toBe(' '); done(); }); it('should have bufferLength', function (done) { expect(chunk.bufferLength).toBe(8); done(); }); it('should have a size of 0', function (done) { expect(chunk.size).toBe(0); done(); }); it('should have contents', function (done) { var expectedContents = new Buffer(8); expectedContents.writeUInt32LE(0x20202020, 0); expectedContents.writeUInt32LE(0, 4); expect(chunk.contents.length).toBe(8); _.forEach(chunk.contents, function (byte, i) { expect(byte).toBe(expectedContents[i]); }); done(); }); it('should have a id of " "', function (done) { expect(chunk.id).toBe(' '); done(); }); it('should have bufferLength', function (done) { expect(chunk.bufferLength).toBe(8); done(); }); it('should have a size', function (done) { expect(chunk.size).toBe(0); done(); }); describe('and data is appended', function () { beforeEach(function (done) { chunk.appendData(new Buffer(7)); done(); }); it('should have increased bufferLength', function (done) { expect(chunk.bufferLength).toBe(15); done(); }); it('should have increased size', function (done) { expect(chunk.size).toBe(7); done(); }); }); describe('and data array is appended', function () { beforeEach(function (done) { chunk.appendData([new Buffer(7), new Buffer(5)]); done(); }); it('should have increased bufferLength', function (done) { expect(chunk.bufferLength).toBe(20); done(); }); it('should have increased size', function (done) { expect(chunk.size).toBe(12); done(); }); }); }); describe('createChunkFromBuffer', function () { describe('with no offset', function () { var myConstructor; beforeEach(function (done) { var contents = new Buffer(22); contents.write('mcla', 0, 4, 'ascii'); contents.writeUInt32LE(4, 4); contents.writeUInt32LE(1234, 8); myConstructor = function (spec) { var that = Chunk.createChunk(spec); return that; }; Chunk.registerChunkConstructor('mcla', myConstructor); chunk = Chunk.createChunkFromBuffer({contents: contents}); done(); }); it('should exist', function (done) { expect(chunk).not.toBeUndefined(); done(); }); it('should have a id', function (done) { expect(chunk.id).toBe('mcla'); done(); }); }); describe('with an offset', function () { var myConstructor; beforeEach(function (done) { var contents = new Buffer(21); contents.write('mcla', 10, 4, 'ascii'); contents.writeUInt32LE(3, 14); myConstructor = function (spec) { var that = Chunk.createChunk(spec); return that; }; Chunk.registerChunkConstructor('mcla', myConstructor); chunk = Chunk.createChunkFromBuffer({contents: contents, offset: 10}); done(); }); it('should exist', function (done) { expect(chunk).not.toBeUndefined(); done(); }); it('should have a id', function (done) { expect(chunk.id).toBe('mcla'); done(); }); it('should have bufferLength', function (done) { expect(chunk.bufferLength).toBe(12); done(); }); it('should have a size', function (done) { expect(chunk.size).toBe(3); done(); }); }); describe('with string contents', function () { var myConstructor; beforeEach(function (done) { var contents = new Buffer(21); contents.write('mcla', 10, 4, 'ascii'); contents.writeUInt32LE(3, 14); myConstructor = function (spec) { var that = Chunk.createChunk(spec); return that; }; Chunk.registerChunkConstructor('mcla', myConstructor); chunk = Chunk.createChunkFromBuffer({contents: contents.toString('binary'), offset: 10}); done(); }); it('should exist', function (done) { expect(chunk).not.toBeUndefined(); done(); }); it('should have a id', function (done) { expect(chunk.id).toBe('mcla'); done(); }); it('should have bufferLength', function (done) { expect(chunk.bufferLength).toBe(12); done(); }); it('should have a size', function (done) { expect(chunk.size).toBe(3); done(); }); }); describe('with an offset greater than contents size', function () { var myConstructor; beforeEach(function (done) { var contents = new Buffer(21); contents.write('mcla', 10, 4, 'ascii'); contents.writeUInt32LE(3, 14); myConstructor = function (spec) { var that = Chunk.createChunk(spec); return that; }; Chunk.registerChunkConstructor('mcla', myConstructor); chunk = Chunk.createChunkFromBuffer({contents: contents, offset: 18}); done(); }); it('should exist', function (done) { expect(chunk).not.toBeUndefined(); done(); }); it('should have a JUNK id', function (done) { expect(chunk.id).toBe('JUNK'); done(); }); it('should have bufferLength', function (done) { expect(chunk.bufferLength).toBe(3); done(); }); it('should have a size', function (done) { expect(chunk.size).toBe(0); done(); }); }); describe('with JUNK', function () { beforeEach(function (done) { var contents = new Buffer(80), junk = 'gggog\u007F\u007Fooooooooooooooooooooooooooooooooo' + 'oooooooooooooooooooooooooooooooooooooooo'; contents.write(junk, 0, 80, 'ascii'); chunk = Chunk.createChunkFromBuffer({contents: contents}); done(); }); it('should exist', function (done) { expect(chunk).not.toBeUndefined(); done(); }); it('should have a id', function (done) { expect(chunk.id).toBe('JUNK'); done(); }); it('should have bufferLength', function (done) { expect(chunk.bufferLength).toBe(80); done(); }); it('should have a size', function (done) { expect(chunk.size).toBe(80 - 8); done(); }); it('should have contents', function (done) { expect(chunk.contents.length).toBe(80); done(); }); it('should have a description', function (done) { expect(chunk.description()).toBe('JUNK(72)'); done(); }); }); }); });
C
UTF-8
666
2.734375
3
[]
no_license
#ifndef _BOX_INCLUDED #define _BOX_INCLUDED /* * * structure for bounding box * * */ struct box { unsigned left, top, width, height; box() = default; box( unsigned init_left, unsigned init_top, unsigned init_width, unsigned init_height ) : left{init_left}, top{init_top}, width{init_width}, height{init_height} {}; const int area() const { return width*height; } const bool overlaps( const box& ); const int intersection_area( const box& ); const int union_area( const box& ); }; #endif
PHP
UTF-8
1,054
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php use yii\db\Migration; use yii\db\Expression; use common\models\TeamMember; class m160912_131321_add_data_to_team_member extends Migration { public function up() { $now = new Expression('NOW()'); $status = TeamMember::STATUS_PUBLISHED; $rootId = 1; $columns = [ 'first_name', 'last_name', 'photo', 'post', 'position', 'status', 'created_by', 'updated_by', 'created_at', 'updated_at', ]; $this->batchInsert('{{%team_member}}', $columns, [ ['Kay', 'Garland', '1.jpg', 'Lead Desinger', 1, $status, $rootId, $rootId, $now, $now], ['Larry', 'Parker', '2.jpg', 'Lead Marketer', 2, $status, $rootId, $rootId, $now, $now], ['Diana', 'Pertersen', '3.jpg', 'Lead Developer', 3, $status, $rootId, $rootId, $now, $now], ]); } public function down() { $this->delete('{{%team_member}}', ['id' => [1, 2, 3]]); } }
Java
UTF-8
7,863
1.640625
2
[ "Apache-2.0" ]
permissive
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you 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. */ //---------------------------------------------------- // THIS CODE IS GENERATED. MANUAL EDITS WILL BE LOST. //---------------------------------------------------- package co.elastic.clients.elasticsearch.core.termvectors; import co.elastic.clients.json.JsonpDeserializable; import co.elastic.clients.json.JsonpDeserializer; import co.elastic.clients.json.JsonpMapper; import co.elastic.clients.json.JsonpSerializable; import co.elastic.clients.json.JsonpUtils; import co.elastic.clients.json.ObjectBuilderDeserializer; import co.elastic.clients.json.ObjectDeserializer; import co.elastic.clients.util.ObjectBuilder; import co.elastic.clients.util.WithJsonObjectBuilderBase; import jakarta.json.stream.JsonGenerator; import java.lang.Integer; import java.util.Objects; import java.util.function.Function; import javax.annotation.Nullable; // typedef: _global.termvectors.Filter /** * * @see <a href="../../doc-files/api-spec.html#_global.termvectors.Filter">API * specification</a> */ @JsonpDeserializable public class Filter implements JsonpSerializable { @Nullable private final Integer maxDocFreq; @Nullable private final Integer maxNumTerms; @Nullable private final Integer maxTermFreq; @Nullable private final Integer maxWordLength; @Nullable private final Integer minDocFreq; @Nullable private final Integer minTermFreq; @Nullable private final Integer minWordLength; // --------------------------------------------------------------------------------------------- private Filter(Builder builder) { this.maxDocFreq = builder.maxDocFreq; this.maxNumTerms = builder.maxNumTerms; this.maxTermFreq = builder.maxTermFreq; this.maxWordLength = builder.maxWordLength; this.minDocFreq = builder.minDocFreq; this.minTermFreq = builder.minTermFreq; this.minWordLength = builder.minWordLength; } public static Filter of(Function<Builder, ObjectBuilder<Filter>> fn) { return fn.apply(new Builder()).build(); } /** * API name: {@code max_doc_freq} */ @Nullable public final Integer maxDocFreq() { return this.maxDocFreq; } /** * API name: {@code max_num_terms} */ @Nullable public final Integer maxNumTerms() { return this.maxNumTerms; } /** * API name: {@code max_term_freq} */ @Nullable public final Integer maxTermFreq() { return this.maxTermFreq; } /** * API name: {@code max_word_length} */ @Nullable public final Integer maxWordLength() { return this.maxWordLength; } /** * API name: {@code min_doc_freq} */ @Nullable public final Integer minDocFreq() { return this.minDocFreq; } /** * API name: {@code min_term_freq} */ @Nullable public final Integer minTermFreq() { return this.minTermFreq; } /** * API name: {@code min_word_length} */ @Nullable public final Integer minWordLength() { return this.minWordLength; } /** * Serialize this object to JSON. */ public void serialize(JsonGenerator generator, JsonpMapper mapper) { generator.writeStartObject(); serializeInternal(generator, mapper); generator.writeEnd(); } protected void serializeInternal(JsonGenerator generator, JsonpMapper mapper) { if (this.maxDocFreq != null) { generator.writeKey("max_doc_freq"); generator.write(this.maxDocFreq); } if (this.maxNumTerms != null) { generator.writeKey("max_num_terms"); generator.write(this.maxNumTerms); } if (this.maxTermFreq != null) { generator.writeKey("max_term_freq"); generator.write(this.maxTermFreq); } if (this.maxWordLength != null) { generator.writeKey("max_word_length"); generator.write(this.maxWordLength); } if (this.minDocFreq != null) { generator.writeKey("min_doc_freq"); generator.write(this.minDocFreq); } if (this.minTermFreq != null) { generator.writeKey("min_term_freq"); generator.write(this.minTermFreq); } if (this.minWordLength != null) { generator.writeKey("min_word_length"); generator.write(this.minWordLength); } } @Override public String toString() { return JsonpUtils.toString(this); } // --------------------------------------------------------------------------------------------- /** * Builder for {@link Filter}. */ public static class Builder extends WithJsonObjectBuilderBase<Builder> implements ObjectBuilder<Filter> { @Nullable private Integer maxDocFreq; @Nullable private Integer maxNumTerms; @Nullable private Integer maxTermFreq; @Nullable private Integer maxWordLength; @Nullable private Integer minDocFreq; @Nullable private Integer minTermFreq; @Nullable private Integer minWordLength; /** * API name: {@code max_doc_freq} */ public final Builder maxDocFreq(@Nullable Integer value) { this.maxDocFreq = value; return this; } /** * API name: {@code max_num_terms} */ public final Builder maxNumTerms(@Nullable Integer value) { this.maxNumTerms = value; return this; } /** * API name: {@code max_term_freq} */ public final Builder maxTermFreq(@Nullable Integer value) { this.maxTermFreq = value; return this; } /** * API name: {@code max_word_length} */ public final Builder maxWordLength(@Nullable Integer value) { this.maxWordLength = value; return this; } /** * API name: {@code min_doc_freq} */ public final Builder minDocFreq(@Nullable Integer value) { this.minDocFreq = value; return this; } /** * API name: {@code min_term_freq} */ public final Builder minTermFreq(@Nullable Integer value) { this.minTermFreq = value; return this; } /** * API name: {@code min_word_length} */ public final Builder minWordLength(@Nullable Integer value) { this.minWordLength = value; return this; } @Override protected Builder self() { return this; } /** * Builds a {@link Filter}. * * @throws NullPointerException * if some of the required fields are null. */ public Filter build() { _checkSingleUse(); return new Filter(this); } } // --------------------------------------------------------------------------------------------- /** * Json deserializer for {@link Filter} */ public static final JsonpDeserializer<Filter> _DESERIALIZER = ObjectBuilderDeserializer.lazy(Builder::new, Filter::setupFilterDeserializer); protected static void setupFilterDeserializer(ObjectDeserializer<Filter.Builder> op) { op.add(Builder::maxDocFreq, JsonpDeserializer.integerDeserializer(), "max_doc_freq"); op.add(Builder::maxNumTerms, JsonpDeserializer.integerDeserializer(), "max_num_terms"); op.add(Builder::maxTermFreq, JsonpDeserializer.integerDeserializer(), "max_term_freq"); op.add(Builder::maxWordLength, JsonpDeserializer.integerDeserializer(), "max_word_length"); op.add(Builder::minDocFreq, JsonpDeserializer.integerDeserializer(), "min_doc_freq"); op.add(Builder::minTermFreq, JsonpDeserializer.integerDeserializer(), "min_term_freq"); op.add(Builder::minWordLength, JsonpDeserializer.integerDeserializer(), "min_word_length"); } }
TypeScript
UTF-8
790
2.6875
3
[]
no_license
import PlayerScore from "../../models/PlayerScore"; import { TeamPickWithScore } from "../../models/TeamPickWithScore"; import PlayerScoreBuilder from "./playerScoreBuilder"; export default class TeamPickWithScoreBuilder { private teamPickWithScore: TeamPickWithScore; constructor() { const playerScore = new PlayerScoreBuilder().build(); this.teamPickWithScore = { playerScore: playerScore, pick: { element: playerScore.player.id, selling_price: 5 } as FantasyPick, }; } withPlayerScore(playerScore: PlayerScore) { this.teamPickWithScore.playerScore = playerScore; return this; } withSellPrice(price: number) { this.teamPickWithScore.pick.selling_price = price; return this; } build() { return this.teamPickWithScore; } }
Java
UTF-8
973
2.25
2
[]
no_license
package car_test; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import model.ARSCar; @RunWith(JUnitPlatform.class) class Car_Test_Lombok { @BeforeAll static void setUpBeforeClass() throws Exception { } @AfterAll static void tearDownAfterClass() throws Exception { } @BeforeEach void setUp() throws Exception { } @AfterEach void tearDown() throws Exception { } @Test void test_getter_setter() { ARSCar car = new ARSCar(1); car.setId(0); assertTrue(car.getId()==0); } @Test void test_direction_constructor() { assertThrows(NullPointerException.class,()-> new ARSCar(3)); } }
Java
UTF-8
798
2.5625
3
[]
no_license
package model.user; import model.bikeservice.BikeOrder; import javax.persistence.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @Entity public class Seller extends Worker { @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="seller") public List<BikeOrder> doneOrders = new ArrayList<>(); @Column private int doneOrdersCount; public Seller() { } public Seller(String name, String surname, String address, String login, String password, LocalDate hireDate, double salary) { super(name, surname, address, login, password, hireDate, salary); } public void addOrder(BikeOrder bikeOrder){ bikeOrder.setSeller(this); doneOrders.add(bikeOrder); doneOrdersCount++; } }
PHP
UTF-8
855
2.609375
3
[]
no_license
<?php namespace App\Rules; use App\Categories; use Illuminate\Contracts\Validation\Rule; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Request; class ValidCategory implements Rule { /** * Create a new rule instance. * * @return void */ public function __construct() { // } /** * Determine if the validation rule passes. * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { if(Categories::where('campus_id', request()->route('campus'))->where('id', $value)->get()) return true; } /** * Get the validation error message. * * @return string */ public function message() { return 'You provided an invalid category.'; } }
Markdown
UTF-8
2,638
2.984375
3
[]
no_license
--- layout: post title: "Installing Github Pages on Ubuntu 15.10" date: 2016-02-24 19:44:59 +0000 categories: jekyll ruby ubuntu github --- # Simples I wanted to create a blog using github pages, but despite looking in all the obvious places I couldn't find a simple set of instructions _all in one place_ that explained how to do this. Sigh. Cue neverending redirect from one site to another saying I needed to do this, that or the other first. This would probably be easy if I used ruby and had it and rubygems already installed, but it's been years since I've done anything with it. I use Ubuntu as my distro of choice and started out from a vanilla Ubuntu (an OpenSSH server install). # Github Pages [Github Pages](https://pages.github.com/) uses [jekyll](https://jekyllrb.com/). To use jekyll you need [ruby](https://www.ruby-lang.org/en/downloads/). I had tried the apt-get route before and had problems, so decided to build form source. # Install Ruby From Source Here's how to do that: sudo apt-get -y install build-essential zlib1g-dev libssl-dev libreadline6-dev libyaml-dev wget https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.0.tar.gz tar zxvf ruby-2.3.0.tar.gz cd ruby-2.3.0/ make sudo make install cd .. ruby --version Check the output is 2.3.0: ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux] # RubyGems Again, from source: sudo apt-get install git git clone https://github.com/rubygems/rubygems.git cd rubygems/ ruby setup.py # # Github Pages Now it's easy get install github-pages # Creating Github Pages Site This was easy - I had already created a github repo _piersfinlayson.github.io_. Here's how I created the jekyll site (obviously change all the piersfinlayson stuff to your own github account and pages site): git clone https://github.com/piersfinlayson/piersfinlayson.github.io cd piersfinlayson.github.io jekyll new . Next I edited _config.yml and about.md entering the info about my site. # First Post Finally I did: cd _posts And then modified the sample post already there and turned it into this one. # Running jekyll The usual instructions tell you how to run jekyll to serve pages up on localhost. Not much good to me with a headless virtual Ubuntu instance. So here's how to expose externally: cd .. # Back to ~/piersfinalayson.github.io jekyll -serve --host 0.0.0.0 Job's a goodun. All that's left is to push this to github and it should be visible [publicly](https://piersfinlayson.github.io/).
Ruby
UTF-8
1,658
3.34375
3
[]
no_license
class Color PROPERTIES = [:timestamp, :hex, :id, :tags] PROPERTIES.each do |prop| attr_accessor prop end def initialize(properties = {}) properties.each do |k, v| if PROPERTIES.member? k.to_sym self.send((k.to_s + "=").to_s, v) end end end # methods to ensure "tags" property is an array of Tag objects #define custom getter to return an array if it's empty def tags @tags ||= [] end #define custom setter to make sure every object in tags will be a Tag object def tags=(tags) if tags.first.is_a? Hash tags = tags.collect { |tag| Tag.new(tag) } end tags.each { |tag| if not tag.is_a? Tag raise "Wrong class for attempted tag #{tag.inspect}" end } @tags = tags end # class method! ... # block argument is for callbacks def self.find(hex, &block) BW::HTTP.get("http://www.colr.org/json/color/#{hex}") do |response| # p response.body.to_str # awesome_print it # parses the object into a ruby hash result_data = BW::JSON.parse(response.body.to_str) color_data = result_data["colors"][0] #create a new color, setup because match between API and model. color = Color.new(color_data) #handle the API's return of a non-existent entity if color.id.to_i == -1 block.call(nil) else block.call(color) end end end def add_tag(tag, &block) BW::HTTP.post("http://www.colr.org/js/color/#{self.hex}/addtag/", payload: {tags:tag}) do |response| if response.ok? block.call(tag) else block.call(nil) end end end end
PHP
UTF-8
9,200
2.671875
3
[]
no_license
<?php ob_start(); require_once("gen/gen/config.php"); class CreateProduct{ /*public $name; public $category; public $description; public $price; #public $image; public $status; public $addition; public $msg;*/ public function __construct(){ /*$this->name = $name; $this->description = $description; $this->price = $price; $this->category = $category; $this->addition = $addition;*/ } public static function storeProduct($name, $description, $price, $image, $status, $category, $addition){ $image_stm = "SELECT Image FROM `products` ORDER BY Image DESC LIMIT 1"; $image_result = getOut($image_stm); if($image_result != 0 or $image_result != 1){ $image = intval($image_result['result'][0]['Image'])+1; $image_path = "ProductImages/char".$image.".jpg"; if(move_uploaded_file($_FILES['image']['tmp_name'], $image_path)){ //echo "Image: ".(intval($image_result['result'][0]['Image'])+1); $stm1 = "INSERT INTO products VALUES('$name', $price, $image, '$category', NULL, NOW())"; $result1 = getIn($stm1); if($result1[0] == 2){ $id_stm = "SELECT ID FROM Products ORDER BY ID DESC LIMIT 1"; $id_result = getOut($id_stm); if($id_stm[0] != 0 or $id_stm[0] != 1){ $product_id = $id_result['result'][0]['ID']; $stm2 = "INSERT INTO Product_info VALUES(NULL, $product_id, '$description', '$status', '$addition')"; $result2 = getIn($stm2); if($result2[0] == 2){ return 2; }else{ var_dump($result2); return 1; } }else{ return 5; } }else{ var_dump($result1); return 0; } }else{ return 4; } }else{ var_dump($image_result); return 3; } /*if((getIn($stm1)[0] == 2) or (getIn($stm2)[0] == 2)){ return getIn($stm1)[1]; }else if((getIn($stm1)[0] == 1) or (getIn($stm2)[0] == 1)){ return getIn($stm1)[1]."<br/>".getIn($stm2)[1]; }else if((getIn($stm1)[0] == 0) or (getIn($stm2)[0] == 0)){ return getIn($stm1)[1]."<br/>".getIn($stm2)[1]; }else{ return "no output"; }*/ } public static function getLatestProducts(){ $stm = "SELECT Name, Price, ID, Image FROM products ORDER BY DATE DESC"; $result = getOut($stm); if($result == 0){ return "cannot connect to the server at this time"; }else if($result == 1){ return "cannot connect to the server at this time to fetch out any info"; }else{ return $result; } } Public static function getAllProducts(){ $stm = "SELECT Name, Price, Image, ID FROM products LIMIT 15"; $result = getOut($stm); if($result == 0){ return "cannot connect to the server at this time"; }else if($result == 1){ return "cannot connect to the server at this time to fetch out any info"; }else{ return $result; } } Public static function getAllProductsAdmin(){ $stm = "SELECT Name, Price, ID FROM products"; $result = getOut($stm); if($result == 0){ return "cannot connect to the server at this time"; }else if($result == 1){ return "cannot connect to the server at this time to fetch out any info"; }else{ return $result; } } Public static function getProductById($id){ $stm = "SELECT Name, Price, ID FROM products WHERE ID = '$id' "; $result = getOut($stm); if($result == 0){ return "cannot connect to the server at this time"; }else if($result == 1){ return "cannot connect to the server at this time to fetch out any info"; }else{ return $result; } } public static function getProductsByCategory($category){ $stm = "SELECT Name, Price, ID FROM products WHERE Category = '$category' ORDER BY DATE DESC"; $result = getOut($stm); if($result == 0){ return "cannot connect to the server at this time"; }else if($result == 1){ return "cannot connect to the server at this time to fetch out any info"; }else{ return $result; } } public function getRecomendedProducts(){ //use category $stm = "SELECT 6 Name, price FROM products ORDER BY DATE DESC"; $result = getOut($stm); if($resilt == 0){ return "cannot connect to the server at this time"; }else if($result == 1){ return "cannot connect to the server at this time to fetch out any info"; }else{ return $result; } } public static function getProductDetails($id){ $stm = "SELECT Name, Price, products.ID, Image, Description, Addition FROM products, product_info WHERE products.ID = product_info.Product_Id and products.ID = '$id' and status='1'"; $result = getOut($stm); //echo $result[1]; if($result == 0){ return 0; }else if($result == 1){ return 0; }else{ return $result; } } } class Customer{ public static function registerUser($v_fname, $v_lname , $v_email , $v_password, $v_pnum , $v_country , $v_state){ $stm = "INSERT INTO customers(F_Name, L_Name, E_ADDRESS, Passcode, Phone_no, Country, State, DATE) VALUES('$v_fname', '$v_lname' , '$v_email' , '$v_password', '$v_pnum' , '$v_country' , '$v_state', NOW())"; // echo $stm; $result = getIn($stm); //var_dump($result); if($result[0] == 0){ return [0, "cannot connect to the server, try again"]; }else if($result[0] == 1){ return [1, $result[1]]; }else if($result[0] == 2){ return [2, "You are registered!, kindly activate your account via your email address"]; } } public static function logOut($customer_id){ session_destroy(); header("Location: C-login_form.php"); } public static function checkEmail($email){ $stm = "SELECT COUNT(E_ADDRESS) FROM customers WHERE E_ADDRESSS == '$email' "; $result = getOut($stm); if($result == 0){ return 0; }else if($result == 1){ return 1; }else{ return $result; } } public static function orderProduct($customer_id){ $stm = "INSERT INTO customers_transaction(Product_Id, Product_status, Quantity, Customer_Id, ID, DATE) VALUES('$Product_id', 'O', 1, $customer_id, NULL, NOW()) "; $result = getOut($stm); if($result == 0){ return 0; }else if($result == 1){ return 1; }else{ return $result; } } public static function storeInvoice_Now($customer_id, $product_id, $invoice_id){ $stm = "INSERT INTO customers_transaction VALUES($product_id, '0', 1, $customer_id, $invoice_id, NULL, NOW())"; $result = getIn($stm); if($result[0] == 0){ var_dump($result); return 0; }else if($result[0] == 1){ var_dump($result); return 1; }else if($result[0] == 2){ return $result; } //var_dump($result[0]); } public static function getAccount($customer_id){ $stm = "SELECT F_name, L_name, E_ADDRESS, Phone_no, State, Country FROM customers WHERE ID = '$customer_id' "; $result = getOut($stm); if($result == 0){ return "cannot connect to the server at this time"; }else if($result == 1){ return "cannot connect to the server at this time to fetch out any info"; }else{ return $result; } } public static function getOrderedProducts($customer_id){ //$stm = "SELECT Product_Id, Products.Name, Quantity, Invoice_ID FROM customers_transaction, products WHERE customers_transaction.Customer_Id = '$customer_id' and customers_transaction.Product_Status = 'O' and customers_transaction.Product_Id = products.ID"; $stm = "SELECT Name, Product_Id, Quantity, Customer_Id, Invoice_ID FROM customers_transaction, Products WHERE Customer_id='$customer_id' AND Product_Id=Products.ID AND Product_status='0'"; //$stm = "SELECT * FROM Customers_transaction"; $result = getOut($stm); if($result == 0){ //return "cannot connect to the server at this time"; return $result; }else if($result == 1){ //return "cannot connect to the server at this time to fetch out any info"; return $result; }else{ return $result; } } public static function getPurchasedProducts($customer_id){ //$stm = "SELECT Name, Quantity, Transaction_ID FROM customers_transaction, products WHERE customers_transaction.customer_Id = '$customer_id' and customers_transaction.product_status = 'P' and customers_transaction.Product_Id = products.ID"; $stm = "SELECT Name, Product_Id, Quantity, Customer_Id, Invoice_ID FROM customers_transaction, Products WHERE Customer_id='$customer_id' AND Product_Id=Products.ID AND Product_status='1'"; $result = getOut($stm); if($result == 0){ return "cannot connect to the server at this time"; }else if($result == 1){ return "cannot connect to the server at this time to fetch out any info"; }else{ return $result; } } public static function SupplyProduct($p_name, $p_description, $customer_id){ $stm = "INSERT INTO supply VALUES('$p_name', '$p_description', '$customer_id', '0', NULL, NOW())"; $result = getIn($stm); if($result[0] == 0){ return 0; }else if($result[0] == 1){ return 1; }else if($result[0] == 2){ return 2; } } public static function getSuppliedProducts($customer_id){ $stm = "SELECT ProductName, Description, Status FROM Supply WHERE Customer_ID='$customer_id'"; $result = getOut($stm); if($result == 0){ //return "cannot connect to the server at this time"; return 0; }else if($result == 1){ return 1; //return "cannot connect to the server at this time to fetch out any info"; }else{ return $result; } } }?>
Go
UTF-8
798
2.765625
3
[]
no_license
package microbio // Ribosome : Here we attempt to model the Translation phase // of gene expression done by the Ribosome type Ribosome struct { } var startCodon = MakeStrand([]byte("AUG"), RIBOSE) // Translate returns an AminoAcidStrand for a given NucleotideStrand // Use WaitForTRNAAndGetAttachedAminoAcid(codon) to get AminoAcid func (t *Ribosome) Translate(nucleotides NucleotideStrand) AminoAcidStrand { // TODO: implement // First, loop through nucleotides looking for START (matching startCodon) // then adding amino acids to an AminoAcidStrand until STOP. // A STOP is when WaitForTRNAAndGetAttachedAminoAcid() returns nil. // If reach the end of the NucleotideStrand without a STOP, // then consider that an error and return an empty AminoAcidStrand. return AminoAcidStrand{} }
Markdown
UTF-8
1,760
2.671875
3
[]
no_license
# js ``` 在JavaScript中,对象就是一个键/值对的集合 -- 你可以把JavaScript的对象想象成一个键为字符串类型的字典。 ``` # frame - frameattached,附加到页面时触发,只能触发一次 - framenavigated 当提交导航栏到不同的url中触发 - framedetached 分离页面的时候触发,只能触发一次 ``` 获取ifame elements const frame = page.frames().find(frame => frame.name() === 'myframe'); const text = await frame.$eval('.selector', element => element.textContent); console.log(text); ``` # ExecutionContext - js解析上下文,一个页面可能有多个执行上下文 - frame触发dom的时候创建默认执行上下文,通过frame.executionContext()方法返回上下文 - 内容脚本创建其他执行上下文 # JSHandle - JSHandle表示页内JavaScript对象。可以使用page.evaluateHandle方法创建JSHandles ``` const windowHandle = await page.evaluateHandle(() => window); ``` - 除非处理了句柄,否则JSHandle会阻止引用的JavaScript对象被垃圾回收。 JSHandles在其原始帧被导航或父上下文被破坏时自动处理 - JSHandle实例可以在页面中用作参数。$ eval(),page.evaluate()和page.evaluateHandle方法。 # ElementHandle - ElementHandle表示页内DOM元素,page.$方法来创建ElementHandles。 # Request 不管啥时候发送一个请求,以下事件触发 - request 页面发出请求 - response 当相应被reqeust接受 - requestfinished 请求体下载完成,而且请求断开 如果请求再某些非erquetfinished 地方失败,触发requestfaided 触发 # CDPSession - CDPSession实例用于讨论原始Chrome Devtools协议 - 可以使用session.send方法调用协议 - 使用session.on 注册协议
C++
UTF-8
1,693
3.296875
3
[]
no_license
//Problem: Switching on the Lights (Silver) //Type: BFS //Solution: Just go down the path, the fact that you can light rooms far away from you makes this really hardcore #include <fstream> #include <cstring> #include <queue> #include <vector> using namespace std; ifstream fin("lightson.in"); ofstream fout("lightson.out"); int N, M, illu; typedef struct{int x, y;}edge; int main(){ //Instantiation fin >> N >> M; int room[N+2][N+2], connected[N+2][N+2], mapped[N+2][N+2]; memset(room, 0, sizeof(room)); memset(connected, 0, sizeof(connected)); memset(mapped, 0, sizeof(mapped)); vector<edge> list[N+1][N+1]; queue<edge> q; for(int i = 0; i < M; i++){ int x, y; fin >> x >> y; edge temp; fin >> temp.x >> temp.y; list[x][y].push_back(temp); } //BFS //Start Point edge temp; room[1][1] = 1; temp.x = 1; temp.y = 1; illu++; q.push(temp); //Queue while(!q.empty()){ //Get next queue int x = q.front().x; int y = q.front().y; q.pop(); if(!room[x][y] || mapped[x][y]) continue; mapped[x][y] = 1; //Make this room connectable to others connected[x][y] = 1; //Lit the list and queue any connected for(int i = 0; i < list[x][y].size(); i++){ int tx = list[x][y][i].x, ty = list[x][y][i].y; if(!room[tx][ty]){ room[tx][ty] = 1; illu++; if(connected[tx-1][ty] || connected[tx+1][ty] || connected[tx][ty+1] || connected[tx][ty-1]){ temp.x = tx; temp.y = ty; q.push(temp); } } } //BFS all around temp.x = x + 1; temp.y = y; q.push(temp); temp.x = x - 1; q.push(temp); temp.x = x; temp.y = y + 1; q.push(temp); temp.y = y - 1; q.push(temp); } //Print results fout << illu << endl; return 0; }
C++
UTF-8
1,149
3.15625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <queue> using namespace std; bool compare(string a, string b) { return a.size() < b.size(); } int main() { vector<int> answers; vector<int> answer; int aaa = 0; int bbb = 0; int ccc = 0; int a[5] = { 1,2,3,4,5 }; int b[8] = { 2,1,2,3,2,4,2,5 }; int c[10] = { 3,3,1,1,2,2,4,4,5,5 }; int acount = 0; int bcount = 0; int ccount = 0; for (int i = 0; i < answers.size(); i++) { if (a[aaa++] == answers[i]) { acount++; } if (aaa % 5 == 0) { aaa = 0; } if (b[bbb++] == answers[i]) { bcount++; } if (bbb % 8 == 0) { bbb = 0; } if (c[ccc++] == answers[i]) { ccount++; } if (ccc % 10 == 0) { ccc = 0; } } vector<int> check; check.push_back(acount); check.push_back(bcount); check.push_back(ccount); sort(check.begin(), check.end()); if (check[2] == acount) { answer.push_back(1); } if (check[2] == bcount) { answer.push_back(2); } if (check[2] == ccount) { answer.push_back(3); } }
C++
UTF-8
1,551
2.765625
3
[]
no_license
#include <cstdio> #include <algorithm> #include <cstring> #include <vector> using std::vector; using std::swap; const int MAXN = 300 + 10; int n; int a[MAXN]; char G[MAXN][MAXN]; int groupId[MAXN]; int index[MAXN]; int ret[MAXN]; void Read() { for (int i = 0; i < n; ++i) { scanf("%d", a + i); } for (int i = 0; i < n; ++i) { scanf("%s", G[i]); } } void Dfs(int x, int id) { groupId[x] = id; for (int i = 0; i < n; ++i) { if (G[x][i] == '1' && groupId[i] == -1) { Dfs(i, id); } } } void Solve() { int cnt = 0; vector<int> vt[MAXN]; memset(groupId, -1, sizeof(groupId)); memset(index, 0, sizeof(index)); for (int i = 0; i < n; ++i) { if (groupId[i] == -1) { Dfs(i, cnt); ++cnt; } } for (int i = 0; i < n; ++i) { vt[groupId[i]].push_back(a[i]); } for (int i = 0; i < cnt; ++i) { sort(vt[i].begin(), vt[i].end()); } for (int i = 0; i < n; ++i) { ret[i] = vt[groupId[i]][index[groupId[i]]++]; } } void Output() { printf("%d", ret[0]); for (int i = 1; i < n; ++i) { printf(" %d", ret[i]); } puts(""); } int main() { while (scanf("%d", &n) == 1) { Read(); Solve(); Output(); } return 0; } /* 7 5 2 4 3 6 7 1 0001001 0000000 0000010 1000001 0000000 0010000 1001000 5 4 2 1 5 3 00100 00011 10010 01101 01010 output 1 2 4 3 6 7 5 output 1 2 3 4 5 */
Markdown
UTF-8
4,504
2.546875
3
[]
no_license
### 法南马赛两建筑物突然倒塌 恐10人遭活埋 ------------------------ <div class="wysiwyg"> 【新唐人北京时间2018年11月06日讯】 <a href="http://www.ntdtv.com/xtr/gb/articlelistbytag_法国.html" target="_blank"> 法国 </a> 南部港都 <a href="http://www.ntdtv.com/xtr/gb/articlelistbytag_马赛.html" target="_blank"> 马赛 </a> 市(Marseille)中心两栋毗邻建筑,5日疑因年久失修突然倒塌,有两名刚好路过的民众受伤,另有至少10人遭活埋。当局派出约百名救援人员寻找受困者。 <br/> <br/> 综合媒体报导,事发在当地上午9时左右,两栋分别为5层楼高及6层楼高的建筑物突然倒塌,瓦砾残骸堆满街道,宛如遭地震袭撃一般,大量的瓦砾阻挡狭窄购物街。邻近建筑物的数十位居民已被疏散。 <br/> <br/> 事发当时在巷口购物的诺尔(Djaffar Nour)表示,〝短短几秒钟〞建筑物就倒了下来,有两名路人遭到波及,受到轻伤。 <br/> <br/> 据谷歌地图(Google Maps)近几个月拍摄的影像显示,倒塌的两栋建筑物外墙有明显裂缝。 <br/> <br/> 救难人员表示,倒塌的其中一栋建筑物内有12户公寓,9户有住人,担心恐有10人遭活埋。另有官员称,另一栋已被判定为危楼,窗户有用木板钉牢,应该很安全,且理论上无人居住。 <br/> <br/> <center> <a href="http://imgs.ntdtv.com/pic/2018/11-6/p9113443a304628009.jpg" target="_blank"> <img border="0" src="http://imgs.ntdtv.com/pic/2018/11-6/p9113443a304628009-ss.jpg"/> <br/> <font size="-1"> <a href="http://www.ntdtv.com/xtr/gb/articlelistbytag_法国.html" target="_blank"> 法国 </a> 南部港都 <a href="http://www.ntdtv.com/xtr/gb/articlelistbytag_马赛.html" target="_blank"> 马赛 </a> 市(Marseille)中心两栋毗邻建筑,5日疑因年久失修突然倒塌。(GERARD JULIEN/AFP/Getty Images) </font> </a> </center> <br/> 从巴黎赶到马赛的住宅部长德诺曼第(Julien Denormandie)表示,约100名救援人员带搜救犬〝不眠不休〞地翻遍碎砖烂瓦,无人机也从上方侦察。马赛市长高丹(Jean-Claude Gaudin)表示,我们认为有民众伤亡,但盼死亡人数愈少愈好。 <br/> <br/> 在西方国家城镇很少发生建筑物坍塌事件,这起事件已掀起政治涟漪,当地贫穷居民住屋品质成为争议焦点。据2015年份的政府报告,约10万马赛居民的住宅不安全且危及他们的健康。 <br/> <br/> <center> <a href="http://imgs.ntdtv.com/pic/2018/11-6/p9113444a531957990.jpg" target="_blank"> <img border="0" src="http://imgs.ntdtv.com/pic/2018/11-6/p9113444a531957990-ss.jpg"/> <br/> <font size="-1"> 法国南部港都马赛市(Marseille)中心两栋毗邻建筑,5日疑因年久失修突然倒塌。(GERARD JULIEN/AFP/Getty Images) </font> </a> <br/> <br/> <a href="http://imgs.ntdtv.com/pic/2018/11-6/p9113445a127914910.jpg" target="_blank"> <img border="0" src="http://imgs.ntdtv.com/pic/2018/11-6/p9113445a127914910-ss.jpg"/> <br/> <font size="-1"> 法国南部港都马赛市(Marseille)中心两栋毗邻建筑,5日疑因年久失修突然倒塌。(GERARD JULIEN/AFP/Getty Images) </font> </a> <br/> <br/> <a href="http://imgs.ntdtv.com/pic/2018/11-6/p9113451a321598886.jpg" target="_blank"> <img border="0" src="http://imgs.ntdtv.com/pic/2018/11-6/p9113451a321598886-ss.jpg"/> <br/> <font size="-1"> 法国南部港都马赛市(Marseille)中心两栋毗邻建筑,5日疑因年久失修突然倒塌。图为数辆救护车现场待命。(GERARD JULIEN/AFP/Getty Images) </font> </a> </center> <br/> <br/> <b> 相关视频: </b> <center> </center> <br/> (责任编辑:卢勇信) </div> <br/>原文链接:http://www.ntdtv.com/xtr/gb/2018/11/06/a1398223.html ------------------------ #### [禁闻聚合首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) &nbsp;|&nbsp; [Web代理](https://github.com/gfw-breaker/open-proxy/blob/master/README.md) &nbsp;|&nbsp; [一键翻墙软件](https://github.com/gfw-breaker/nogfw/blob/master/README.md) &nbsp;|&nbsp; [《九评共产党》](https://github.com/gfw-breaker/9ping.md/blob/master/README.md#九评之一评共产党是什么) &nbsp;|&nbsp; [《解体党文化》](https://github.com/gfw-breaker/jtdwh.md/blob/master/README.md#绪论)
Java
UTF-8
909
2.0625
2
[]
no_license
package me.nurio.events.testclasses; import me.nurio.events.handler.EventHandler; import me.nurio.events.handler.EventListener; import me.nurio.events.handler.EventPriority; public class PriorityTestListener implements EventListener { @EventHandler public void nonTagEvent(TestEvent eve) { // Non-tag event } @EventHandler(priority = EventPriority.MONITOR) public void monitorEvent(TestEvent eve) { // Monitor event } @EventHandler public void nonTagEventTwo(TestEvent eve) { // Non-tag event } @EventHandler(priority = EventPriority.LOW) public void lowEvent(TestEvent eve) { // Lowest event } @EventHandler(priority = EventPriority.LOWEST) public void lowestEvent(TestEvent eve) { // Lowest event } @EventHandler public void nonTagEventTree(TestEvent eve) { // Non-tag event } }
JavaScript
UTF-8
3,661
2.640625
3
[]
no_license
$(document).ready(manipulateDOM); function manipulateDOM() { renderStaticContent(); renderPasswordAnalysis(); registerEventHandlers(); } function renderStaticContent() { $('body').append(` <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">Password Strength</a> </div> </div> </nav> <div class="container"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> <div class="form-group"> <label for="password">Password:</label> <input id="password" type="password" class="form-control success" placeholder="Analyze a password"> </div> </div> </div> </div> `); } function renderPasswordAnalysis() { $('.container').append(` <div id="password-analysis" class="row"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> <div id="score-in-bar"></div> </div> </div> <h3 class="text-center" id="feedback-warning"></h3> <p>If this password were used for on online banking site, it could probably be cracked within <span id="crack-bank"></span></p> <p>If this password would leak as encrypted string, it could probably be cracked within <span id="crack-leaked"></span></p> <ul id="feedback-suggestions"></ul> <pre> <div id="print-json"></div> </pre> </div> `).children().last().hide(); renderPasswordBars(); } function renderPasswordBars() { $('#score-in-bar div').remove(); let pwFieldWidth = $('#password').width(); let margin = 5; let barWidth = (pwFieldWidth-5*2) / 5; const bar = $("<div>"); bar.css({ "display": "inline-block", "width": barWidth, "height": "15px", "background-color": "grey", "border-radius": "5px", "margin": "0px " + margin+"px" }); $('#score-in-bar').append(bar.clone()); $('#score-in-bar').append(bar.clone()); $('#score-in-bar').append(bar.clone()); $('#score-in-bar').append(bar.clone()); $('#score-in-bar').append(bar.clone()); } function registerEventHandlers() { $('#password').keyup(setValuesOnDOM); $(window).resize(renderPasswordBars); } function resetState() { $('#score-in-bar div').css( "backgroundColor", "grey" ); $('#feedback-suggestions li').remove(); } function setValuesOnDOM() { resetState(); var analysis = zxcvbn($(this).val()); if(!analysis.password) { $('#password-analysis').hide(); return; } else $('#password-analysis').show(); console.log(analysis); switch (analysis.score){ case 0: $("#score-in-bar div:lt(1)" ).css( "backgroundColor", "#BF1251" ); break; case 1: $("#score-in-bar div:lt(2)" ).css( "backgroundColor", "#FF1C14" ); break; case 2: $("#score-in-bar div:lt(3)" ).css( "backgroundColor", "yellow" ); break; case 3: $("#score-in-bar div:lt(4)" ).css( "backgroundColor", "#d2ff4d" ); break; case 4: $("#score-in-bar div:lt(5)" ).css( "backgroundColor", "#33cc33" ); break; default: $("#score-in-bar div" ).css( "backgroundColor", "grey" ); break; } $('#feedback-warning').text(analysis.feedback.warning); $('#crack-bank').text(analysis.crack_times_display.online_throttling_100_per_hour); $('#crack-leaked').text(analysis.crack_times_display.offline_slow_hashing_1e4_per_second); analysis.feedback.suggestions.forEach(s=> { $('#feedback-suggestions').append('<li> '+s+'</li>'); }); $('#print-json').text(JSON.stringify(analysis, null, 2)); }
Java
UTF-8
4,495
2.140625
2
[]
no_license
package com.example.practicamoviles_1tr.fragments; import android.annotation.SuppressLint; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import com.example.practicamoviles_1tr.MainActivity; import com.example.practicamoviles_1tr.R; import com.example.practicamoviles_1tr.api_manager.IfaceApi; import com.example.practicamoviles_1tr.api_manager.JsonResponse; import com.example.practicamoviles_1tr.common.FavsSettings; import com.example.practicamoviles_1tr.common.MapPointAdapter; import com.example.practicamoviles_1tr.models.MapPoint; import java.io.Serializable; import java.util.Collections; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import static com.example.practicamoviles_1tr.common.Constantes.CURRENT_LOCATION_LATITUDE; import static com.example.practicamoviles_1tr.common.Constantes.CURRENT_LOCATION_LONGITUDE; import static com.example.practicamoviles_1tr.common.Constantes.DISTANCE; import static com.example.practicamoviles_1tr.common.Constantes.ENTRY_POINT; import static com.example.practicamoviles_1tr.common.Constantes.MAPPOINT_LATITUDE; import static com.example.practicamoviles_1tr.common.Constantes.MAPPOINT_LONGITUDE; public class PoolsFragment extends Fragment implements Serializable { private ImageView imgFav; private List<MapPoint> mapPoints, mapPointsFavs; private ListView listView; private MapPointAdapter adapter = null; private FavsSettings favsSettings; private MapPoint mapPoint; private double longitude, latitude; public PoolsFragment(double longitude, double latitude) { this.longitude = longitude; this.latitude = latitude; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_mappoints, container, false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); listView = getActivity().findViewById(R.id.lvMapPoints); getPools(); favsSettings = new FavsSettings(getActivity()); listView.setOnItemLongClickListener((parent, view, position, id) -> { mapPoint = mapPoints.get(position); favsSettings.setFav(mapPoint); ImageView favImg = view.findViewById(R.id.favIcon); favImg.setImageResource(R.drawable.ic_star_on); return false; }); } public void getPools(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(ENTRY_POINT) .addConverterFactory(GsonConverterFactory.create()) .build(); IfaceApi ifaceApi = retrofit.create(IfaceApi.class); ifaceApi.getPools(latitude, longitude, DISTANCE).enqueue(new Callback<JsonResponse>() { @Override public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) { if(response!=null && response.body() != null){ mapPoints = response.body().results; mapPointsFavs = new FavsSettings(getActivity()).getFavs(); //bucle para recuperar todos los mappoints con los favoritos que ya haya(para tener el atributo isFav) for (int i=0; i<mapPoints.size();i++){ for (MapPoint fav:mapPointsFavs){ if(mapPoints.get(i).getTitle().equalsIgnoreCase(fav.getTitle())){ mapPoints.set(i, fav); } } } adapter=new MapPointAdapter(getContext(), mapPoints, getActivity()); listView.setAdapter(adapter); adapter.notifyDataSetChanged(); } } @Override public void onFailure(Call <JsonResponse> call, Throwable t) {} }); } }
JavaScript
UTF-8
2,519
2.609375
3
[]
no_license
import React, {Component} from 'react' class CreateContact extends Component { state = { name: '', phone: '', birthday: '', } componentDidMount () { this.setState({ name: this.props.name, phone: this.props.phone, birthday: this.props.birthday, }) } onNameChange = (e) => { this.setState({ name: e.target.value }) } onPhoneChange = (e) => { this.setState({ phone: e.target.value }) } onBirthdayChange = (e) => { this.setState({ birthday: e.target.value }) } onCreate = (e) => { const {name, phone, birthday} = this.state; fetch('/contact/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, phone, birthday }) }).then((res)=> { if(res.status === 200) { console.log(res) } else { console.log('error'); } }).catch((err) => { console.log(err); }) this.setState({ name: '', phone: '', date: '', }) this.props.cancel(); } onUpdate = (id) => { const {name, phone, birthday} = this.state; fetch('/contact/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, phone, birthday, id }) }).then((res)=> { if(res.status === 200) { console.log(res) } else { console.log('error'); } }).catch((err) => { console.log(err); }) this.setState({ name: '', phone: '', date: '', }) this.props.cancel(); } render() { return ( <div className="contact-form"> <input value={this.state.name} type="text" onChange={this.onNameChange} className="field" placeholder="name"/> <input value={this.state.phone} type="text" onChange={this.onPhoneChange} className="field" placeholder="phone"/> <input value={this.state.birthday} type="date" onChange={this.onBirthdayChange} className="field" placeholder="birthday"/> {this.props.update ? <button onClick={()=> this.onUpdate(this.props.id)} className="btn">Update</button> : <button onClick={this.onCreate} className="btn">Create</button> } <button onClick={()=>this.props.cancel()} className="btn">Cancel</button> </div> ) } } export default CreateContact;
Java
UTF-8
2,553
3.4375
3
[]
no_license
import java.io.*; public class FileRW { public static void main (String[] args) { File fileIn = new File("src/main/java/FileRW.java"); File fileOut = new File("output.txt"); System.out.println(fileIn.getAbsolutePath()); System.out.println(fileOut.getAbsolutePath()); try (FileInputStream in = new FileInputStream(fileIn)){ int data = in.read(); while (data != -1) { System.out.print((char)data); data = in.read(); } in.close(); } catch (FileNotFoundException e) { System.out.println("A file nem letezik!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Hiba a filekezeles soran!"); e.printStackTrace(); } try (FileOutputStream out = new FileOutputStream(fileOut)) { String s1 = "Output string 1 "; String s2 = "Output string 2 "; String newLine = System.getProperty("line.separator"); out.write((s1 + newLine + s2 + newLine).getBytes()); out.flush(); out.close(); } catch (FileNotFoundException e) { System.out.println("A file nem letezik!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Hiba a filekezeles soran!"); e.printStackTrace(); } try (BufferedWriter fileBufferedOut = new BufferedWriter(new FileWriter(fileOut, true))) { fileBufferedOut.write("Buffered output string"); fileBufferedOut.newLine(); fileBufferedOut.flush(); fileBufferedOut.close(); } catch (FileNotFoundException e) { System.out.println("A file nem letezik!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Hiba a filekezeles soran!"); e.printStackTrace(); } try (BufferedReader fileBufferedIn = new BufferedReader(new FileReader(fileOut))) { String sor = null; while ( (sor = fileBufferedIn.readLine()) != null) System.out.println(sor); } catch (FileNotFoundException e) { System.out.println("A file nem letezik!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Hiba a filekezeles soran!"); e.printStackTrace(); } } }
Markdown
UTF-8
4,550
2.9375
3
[ "MIT" ]
permissive
> ##### 通用属性 * textColor 文本颜色 * disabledTextColor 禁用状态时文本颜色 * color 背景颜色 * disabledColor 禁用状态时背景颜色 * highlightColor 高亮状态时背景,如按下时 * splashColor 水波纹颜色 > ##### RaisedButton material风格的凸起按钮 ``` RaisedButton _raisedButton = RaisedButton( onPressed: () { // 点击回调,required,当为空时则禁用状态 print('RaisedButton OnPressed'); }, onLongPress: () { // 长按回调 print('RaisedButton OnLongPress'); }, onHighlightChanged: (highLight) { // 高亮状态改变回调 print('RaisedButton OnHighlightChanged ${highLight}'); }, textColor: Colors.black, // 正常状态文本颜色 disabledTextColor: Colors.white, // 禁用状态文本颜色 color: Colors.green, // 正常状态背景颜色 disabledColor: Colors.grey, // 禁用状态背景颜色 splashColor: Colors.transparent, // 水波纹颜色 colorBrightness: Brightness.light, // 明暗主题 ); ``` > ##### ElevatedButton Flutter 1.22后新增的material风格的凸起按钮,对应的旧版RaisedButton,但主题管理不同 ``` ElevatedButton _elevatedButton = ElevatedButton( onPressed: () { print('ElevatedButton OnPressed'); }, onLongPress: () { print('ElevatedButton OnlongPress'); }, style: ButtonStyle( // 按钮样式 textStyle: MaterialStateProperty.all(TextStyle(color: Colors.blue, fontSize: 14)), backgroundColor: MaterialStateProperty.all(Colors.green), // 背景色 foregroundColor: MaterialStateProperty.all(Colors.grey), // 字体颜色通过通过前景色设置,通过textStyle设置无效 overlayColor: MaterialStateProperty.all(Colors.red), // 高亮色,按钮处于focused, hovered, or pressed时的颜色 shadowColor: MaterialStateProperty.all(Colors.black), // 阴影颜色 elevation: MaterialStateProperty.all(5), // 阴影值 ), ); ``` > ##### FlatButton 扁平按钮 > ##### TextButton Flutter 1.22后新增的扁平按,对应旧版FlatButton,但主题管理不同 > ##### OutlineButton 带边框的按钮 ``` OutlineButton _outlineButton = OutlineButton( onPressed: () { print('OutlineButton OnPressed'); }, borderSide: BorderSide(width: 1, color: Colors.red.shade500), disabledBorderColor: Colors.grey, highlightedBorderColor: Colors.red, ); ``` > ##### OutlinedButton Flutter 1.22后新增的带边框的按钮,对应旧版OutlineButton,当主题管理不同 > ##### DropdownButton 下拉选择菜单按钮 > ##### RawMaterialButton RawMaterialButton是基于Semantic,Material和InkWell创建的组件,不使用当前系统主题和按钮主题,用于自定义按钮或者合并现有的样式。 RaisedButton和FlatButton都是基于RawMaterialButton配置了系统主题和按钮主题的。 > ##### PopupMenuButton 弹出菜单的按钮 > ##### IconButton 图标按钮 > ##### BackButton material风格的返回按钮,本身是一个IconButton,点击默认执行Navigator.maybePop,即如果路由栈有上一页则返回上一页。 > ##### CloseButon material风格的关闭按钮,本身是一个IconButton,点击默认执行Navigator.maybePop,即如果路由栈有上一页则返回上一页。 使用场景:BackButton一般适用于全屏页面,CloseButton一般适用于弹出的Dialog页面 > ##### CupertinoButton iOS风格按钮 > ##### ButtonBar ButtonBar不是一个单独的按钮控件,而是末端对齐的容器类控件。当在水平方向没有足够空间的时候,按钮将整体垂直排列,而不是换行。 > ##### ButtonStyle ``` const ButtonStyle({ this.textStyle, //字体 this.backgroundColor, //背景色 this.foregroundColor, //前景色 this.overlayColor, // 高亮色,按钮处于focused, hovered, or pressed时的颜色 this.shadowColor, // 阴影颜色 this.elevation, // 阴影值 this.padding, // padding this.minimumSize, //最小尺寸 this.side, //边框 this.shape, //形状 this.mouseCursor, //鼠标指针的光标进入或悬停在此按钮的[InkWell]上时。 this.visualDensity, // 按钮布局的紧凑程度 this.tapTargetSize, // 响应触摸的区域 this.animationDuration, //[shape]和[elevation]的动画更改的持续时间。 this.enableFeedback, // 检测到的手势是否应提供声音和/或触觉反馈。例如,在Android上,点击会产生咔哒声,启用反馈后,长按会产生短暂的振动。通常,组件默认值为true。 }); ```
JavaScript
UTF-8
879
3.21875
3
[]
no_license
const _ = require('../underbar'); describe('every()', () => { describe('processing an array of numbers', () => { it('will return true if no callback is supplied', () => { const nums = [1, 3, 5, 7]; expect(_.every(nums)).toBe(true); }); it('returns true if all numbers in an array are odd and we test for odd numbers', () => { const nums = [1, 3, 5, 7]; expect(_.every(nums, num => num % 2 === 1)).toBe(true); }); it('returns false if not all numbers in an array are odd and we test for odd numbers', () => { const nums = [1, 3, 5, 6, 7]; expect(_.every(nums, num => num % 2 === 1)).toBe(false); }); it('returns true if all values in the array are typeof string', () => { const elements = ['A', 'B', 'C', 'D']; expect(_.every(elements, el => typeof el === 'string')).toBe(true); }); }); });
Java
UTF-8
1,676
2.625
3
[ "MIT" ]
permissive
package com.github.elegantwhelp.boxmania.gui; import org.joml.Vector2f; import com.github.elegantwhelp.boxmania.BoxMania; import com.github.elegantwhelp.boxmania.gui.widget.WidgetButton; import com.github.elegantwhelp.boxmania.gui.widget.WidgetLabel; import com.github.elegantwhelp.boxmania.io.KeyState; public class GuiMain extends Gui { private WidgetButton buttonPlay; private WidgetButton buttonMultiplayer; private WidgetButton buttonOptions; private WidgetButton buttonQuit; private BoxMania game; public GuiMain(BoxMania game) { super(); this.game = game; } @Override public void closeGui() { } @Override public void openGui() { buttonPlay = new WidgetButton(new Vector2f(0, 0), new Vector2f(256, 16), "Play", 32, 0); buttonMultiplayer = new WidgetButton(new Vector2f(0, 50), new Vector2f(256, 16), "Multiplayer", 32, 0); buttonOptions = new WidgetButton(new Vector2f(0, 100), new Vector2f(256, 16), "Options", 32, 0); buttonQuit = new WidgetButton(new Vector2f(0, 150), new Vector2f(256, 16), "Quit", 32, 0); addWidget(new WidgetLabel(new Vector2f(0, -200), "Box Mania", 128, WidgetLabel.ALIGN_CENTER, 0)); addWidget(new WidgetLabel(new Vector2f(0, -100), "A Game By Richard Olsen", 32, WidgetLabel.ALIGN_CENTER, 0)); addWidget(buttonPlay); addWidget(buttonMultiplayer); addWidget(buttonOptions); addWidget(buttonQuit); } @Override public void updateGui() { if (buttonPlay.isClicked()) game.startGame(); if (buttonOptions.isClicked()) guiHandler.setActiveGUI(new GuiOptions(game, this)); if (buttonQuit.isClicked() || guiHandler.getInput().getKey("quit") == KeyState.PRESSED) System.exit(0); } }
Markdown
UTF-8
1,109
2.78125
3
[]
no_license
This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). ## Key dependencies * [Ant Design](https://ant.design/docs/react/introduce) * [Axios](https://github.com/axios/axios) * [Redux](https://redux.js.org/) * [Redux Thunk](https://github.com/gaearon/redux-thunk) * [React Router](https://github.com/ReactTraining/react-router) ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.<br> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br> You will also see any lint errors in the console. ### `yarn test` Launches the test runner in the interactive watch mode.<br> See the section about [running tests](#running-tests) for more information. ### `yarn run build` Builds the app for production to the `build` folder.<br> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br> Your app is ready to be deployed!
Shell
UTF-8
771
3.53125
4
[]
no_license
#!/bin/sh #------------------------------------------------------------------------------- # Create versions file # #------------------------------------------------------------------------------- VER="$HOME/workspace/SnpEff/html/versions.txt" # SnpEff version number SNPEFF=`java -jar snpEff.jar 2>&1 | grep "snpEff version" | cut -f 3,4,6 -d " " | cut -f 1 -d ")" | tr "[a-z]" "[A-Z]" ` # SnpSift version number SNPSIFT=`java -jar SnpSift.jar 2>&1 | grep "SnpSift version" | cut -f 3,4,6 -d " " | cut -f 1 -d ")" | tr "[a-z]" "[A-Z]"` # Create file ( echo $SNPEFF "http://sourceforge.net/projects/snpeff/files/snpEff_latest_core.zip" echo $SNPSIFT "http://sourceforge.net/projects/snpeff/files/snpEff_latest_core.zip" ) | tr " " "\t" > $VER # Show file cat $VER
Ruby
UTF-8
3,025
2.9375
3
[]
no_license
require 'test_helper' class PhysicianTest < ActiveSupport::TestCase # Other methods available to instancs of Physician model (provided by has_many). # # patients # patients<<(object, ...) # patients.delete(object, ...) # patients.destroy(object, ...) # patients=(objects) # patient_ids # patient_ids=(ids) # patients.clear # patients.empty? # patients.size # patients.find(...) # patients.where(...) # patients.exists?(...) # patients.build(attributes = {}, ...) # patients.create(attributes = {}) # patients.create!(attributes = {}) # patients.reload # Notice above patients is a method. What's the matter here? # If `patients` is a method, where is the name from? It's given by us when we declare # the association, like this, has_many :patients # So, we are not free to use any name for our associations. This also means, we need # to be careful not to cause name collisions when creating our models and associations. # For example, `attributes` is aleady defined in ActiveRecord::Base test "should load all patients for Dr. Stephen" do physician = Physician.find_by(name: "Dr. Stephen") assert_equal 2, physician.patients.size assert_equal 2, physician.appointments.size end test "should reconnect patients" do stephen = Physician.find_by(name: "Dr. Stephen") new_patient = Patient.new(name: "Tony") # the xxxx=(object) method resets the associated models in database by creating new # records (if not exist) and deleting missing records. # This is a rather dangerous method as it performe these actions sliently. I'd suggest # to give it a more prompting method name. stephen.patients = [new_patient] assert_equal 1, stephen.patients.size end # join test "should join" do # select only physicians who have appointments # # => SELECT DISTINCT "physicians".* FROM "physicians" # INNER JOIN "appointments" ON "appointments"."physician_id" = "physicians"."id" # # you can add conditions to the join to further filter the results # Physician.joins(:appointments).where(...) physicians = Physician.joins(:appointments).distinct assert_equal 2, physicians.size physicians.each { |p| puts p.inspect } end test "should include all physicians" do physicians = Physician.left_outer_joins(:appointments).distinct assert_equal 3, physicians.size end test "should load physicians with appointments data" do # with includes, Rails will loads associated records of the object # without incldues, Rails will query DB for each iteration of the loop # If you know you are gonna need to access the associated data after, # use includes to do eager loading. physicians = Physician.includes(appointments: :patient).all assert_equal 3, physicians.size physicians.each do |p| p.appointments.each do |a| puts "#{p.name} has an appointment with #{a.patient.name} at #{a.appointment_date}" end end end end
C#
UTF-8
1,885
2.625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum MusicType { Full, Loop, GameOver, FailSound, CollectedSound } public class AudioController : Singleton<AudioController> { protected AudioController () { } [SerializeField] public AudioSource MusicAudioSource; [SerializeField] public AudioSource SoundAudioSource; [SerializeField] public AudioClip ThemeMusicMain; [SerializeField] public AudioClip ThemeMusicLoop; [SerializeField] public AudioClip ThemeMusicGameOver; [SerializeField] public AudioClip FailSound; [SerializeField] public AudioClip CollectedSound; // public void PlaySound(AudioClip clip, bool loop=false){ // if( loop){ // AudioSource.PlayOneShot(clip); // }else{ // AudioSource.pla // } // } public void PlayMusic (MusicType type, bool stop = false) { MusicAudioSource.volume = 1; switch (type) { case MusicType.Full: MusicAudioSource.clip = ThemeMusicMain; MusicAudioSource.loop = true; break; case MusicType.Loop: MusicAudioSource.clip = ThemeMusicLoop; MusicAudioSource.loop = true; break; case MusicType.GameOver: MusicAudioSource.clip = ThemeMusicGameOver; MusicAudioSource.loop = false; MusicAudioSource.volume = 0.5f; break; case MusicType.FailSound: // SoundAudioSource.clip = FailSound; // SoundAudioSource.loop = false; SoundAudioSource.PlayOneShot (FailSound); return; case MusicType.CollectedSound: // SoundAudioSource.clip = CollectedSound; // SoundAudioSource.loop = false; SoundAudioSource.PlayOneShot (CollectedSound); return; } if (stop) { MusicAudioSource.Stop (); } else { MusicAudioSource.Play (); } } public void PlayGameOver () { MusicAudioSource.PlayOneShot (ThemeMusicGameOver); } }
Markdown
UTF-8
1,881
2.9375
3
[ "MIT" ]
permissive
# Dokumentacja Algorytmu levenberga marquardta: funkcja zawiera algorytm oparty na metodzie marquardta, liczy przybliżone minimum funkcji dwóch zmiennych, i wypisuje to minimum, wraz ze zmiennymi w tym punkcie oraz liczbę iteracji # Zmienne zewnętrzne: M - maksymalna ilość kroków algorytmów epsilon - tolerancja błędu algorytmu. x - zmienne początkowe funkcja - funkcja dwóch zmiennych, z której algorytm liczy minimum # opis: W metodzie Marquardta, stosuje się na początku metodę Cauchy’ego, a następnie wykorzystuje się metodę Newtona. Metoda Cauchy’ego jest używana do rozwiązania problemu minimalizacji funkcji. W ogólnym przypadku jest ona wolno zbieżna, więc korzystając z wiedzy o drugiej pochodnej minimalizowanej funkcji w badanym punkcie możemy skorzystać z rozwinięcia gradientu minimalizowanej funkcji w szereg Taylora. Wtedy przyjmujemy przybliżenie kwadratowe funkcji w otoczeniu do rozwiązania równania W ten sposób otrzymujemy metodę Gaussa-Newtona opisaną schematem: Kenneth Levenberg zauważył, że opisane metody (największego spadku i Gaussa-Newtona) nawzajem się uzupełniają i zaproponował następującą modyfikację kroku metody: Donald Marquardt zauważył, że nawet w sytuacji gdzie hesjan jest niewykorzystywany można wykorzystać informację zawartą w drugiej pochodnej minimalizowanej funkcji, poprzez skalowanie każdego komponentu wektora gradientu w zależności od krzywizny w danym kierunku (co pomaga w źle uwarunkowanych zadaniach minimalizacji typu error valley). Po uwzględnieniu poprawki Marquardta otrzymujemy następującą postać kroku metody: # Przykład: ``` julia> function sincos(x) = sin(x[1]) + cos(x[2]) julia> HyperCube(sincos,[10.0,10.0],0.0001,100) norma mniejsz/równa E ilosc krokow: 20 wartosc x y dla minimum: [-6.83358e-7, -6.83358e-7] minimum: 9.339560643078874e-13 ```