language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
1,459
2.53125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: "C28198 | Microsoft Docs" ms.custom: "" ms.date: 11/15/2016 ms.prod: "visual-studio-dev14" ms.reviewer: "" ms.suite: "" ms.technology: - "vs-devops-test" ms.tgt_pltfrm: "" ms.topic: "article" f1_keywords: - "C28198" helpviewer_keywords: - "C28198" ms.assetid: 8bad4acb-712c-43f5-81d1-45d92092d4c5 caps.latest.revision: 5 author: mikeblome ms.author: mblome manager: "ghogen" --- # C28198 [!INCLUDE[vs2017banner](../includes/vs2017banner.md)] warning C28198: Possibly leaking memory due to an exception. This warning indicates that allocated memory is not being freed after an exception is raised. The statement at the end of the path can raise an exception. The memory was passed to a function that might have saved a copy to be freed later. This warning is very similar to warning [C28197](../code-quality/c28197.md). The annotations that are recommended for use with warning [C28197](../code-quality/c28197.md) can also be used here. ## Example The following code example generates this warning: ``` char *p1 = new char[10]; char *p2 = new char[10]; test(p1); // does not save a copy of p delete[] p2; delete[] p1; ``` The following code example avoids this warning: ``` char *p1 = new char[10]; char *p2 = NULL; test(p1); // does not save a copy of p try { p2 = new char[10]; } catch (std::bad_alloc *e) { // just handle the throw ; } ```
TypeScript
UTF-8
510
2.546875
3
[]
no_license
import { Pipe, PipeTransform } from '@angular/core'; import { FriendRelationUnit } from '../Models/friend-relation-unit'; @Pipe({ name: 'search' }) export class SearchPipe implements PipeTransform { transform(items: FriendRelationUnit[], term: string): any { if (items===undefined || term === undefined || term.trim() =='') return items; return items.filter(function(item) { if(item.NickName.toLowerCase().includes(term.toLowerCase())) return true; return false; }); } }
JavaScript
UTF-8
577
2.6875
3
[]
no_license
import React, { useState, useEffect } from "react"; import axios from "axios"; import Book from "./Book"; export default function ListBooks() { const [bookList, setBookList] = useState([]); useEffect(() => { axios .get("https://www.googleapis.com/books/v1/volumes?filter=free-ebooks&q=a") .then((response) => { setBookList(response.data.items); }) .catch((error) => console.log(error)); }, [bookList]); return ( <div> {bookList.map((item) => ( <Book item={item} key={item.id}></Book> ))} </div> ); }
C++
UTF-8
1,277
3.625
4
[]
no_license
#include "trackingDeck.h" //create a tracking deck TrackingDeck::TrackingDeck(int a_size) { m_length = a_size; m_data = new card [m_length]; for(int r = 0; r < m_length; ++r) { //make sure the tracking deck is empty m_data[r].m_type = NULL; m_data[r].m_color = NULL; m_data[r].m_quantity = NULL; } } //add a card to the tracking deck void TrackingDeck::add(int loc, char a_type, char a_color) { m_data[loc].m_type = a_type; m_data[loc].m_color = a_color; } //clear the contents of the tracking deck void TrackingDeck::clear() { for(int r = 0; r < m_length; ++r) { //clear data m_data[r].m_type = NULL; m_data[r].m_color = NULL; m_data[r].m_quantity = NULL; } } //check to see if the tracking deck is empty bool TrackingDeck::empty() { for(int r = 0; r < m_length; ++r) { //if not empty if(m_data[r].m_type != NULL || m_data[r].m_color != NULL) { return false; } } return true; } //release the memory void TrackingDeck::release() { clear(); delete m_data; } //get a type at a certain element char TrackingDeck::getTypeAt(int loc) { return m_data[loc].m_type; } //get a color at a certain element char TrackingDeck::getColorAt(int loc) { return m_data[loc].m_color; }
Java
UTF-8
2,409
2.703125
3
[ "Apache-2.0" ]
permissive
package org.quicktheories.generators; import static org.assertj.core.api.Assertions.assertThat; import static org.quicktheories.impl.GenAssert.assertThatGenerator; import org.junit.Test; import org.mockito.Mockito; import org.quicktheories.core.Gen; import org.quicktheories.core.RandomnessSource; import org.quicktheories.generators.Generate; public class ArbritaryTest { @Test public void shouldReturnValuesFromConstant() { Gen<Integer> testee = Generate.constant(42); RandomnessSource unused = Mockito.mock(RandomnessSource.class); assertThat(testee.generate(unused)).isEqualTo(42); assertThat(testee.generate(unused)).isEqualTo(42); } @Test public void shouldReturnValuesFromSupplier() { Gen<Integer> testee = Generate.constant(() -> 42); RandomnessSource unused = Mockito.mock(RandomnessSource.class); assertThat(testee.generate(unused)).isEqualTo(42); assertThat(testee.generate(unused)).isEqualTo(42); } @Test public void shouldReturnAllItemsInListWhenPickingRandomly() { Gen<String> testee = Generate .pick(java.util.Arrays.asList("a", "1", "b", "2")); assertThatGenerator(testee).generatesAllOf("a", "1", "b", "2"); } @Test public void shouldShrinkTowardsFirstItemInList() { Gen<String> testee = Generate .pick(java.util.Arrays.asList("a", "1", "b", "2")); assertThatGenerator(testee).shrinksTowards("a"); } @Test public void shouldNotShrinkInAnyParticularDirectionWhenNoShrinkPointRequested() { Gen<String> testee = Generate.pickWithNoShrinkPoint(java.util.Arrays.asList("a", "1", "b", "2")); assertThatGenerator(testee).hasNoShrinkPoint(); } @Test public void shouldReturnAllItemsInListWhenPickingRandomlyWithoutShrinkPoint() { Gen<String> testee = Generate .pickWithNoShrinkPoint(java.util.Arrays.asList("a", "1", "b", "2")); assertThatGenerator(testee).generatesAllOf("a", "1", "b", "2"); } @Test public void shouldRandomlySelectEnumValues() { Gen<AnEnum> testee = Generate.enumValues(AnEnum.class); assertThatGenerator(testee).generatesAllOf(AnEnum.A, AnEnum.B, AnEnum.C, AnEnum.D, AnEnum.E); } @Test public void shouldShrinkEnumsTowardsFirstDefinedConstant() { Gen<AnEnum> testee = Generate.enumValues(AnEnum.class); assertThatGenerator(testee).shrinksTowards(AnEnum.A); } enum AnEnum { A, B, C, D, E } }
Rust
UTF-8
643
2.9375
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::time::Instant; use std::cmp::{Ord, Ordering, PartialOrd, PartialEq}; #[derive(Debug, Clone, Copy)] pub enum TaskType { Resend, } #[derive(Clone)] pub struct Task { pub tasktype: TaskType, pub time: Instant, pub message_id: String, } impl Ord for Task { fn cmp(&self, other: &Self) -> Ordering { self.time.cmp(&other.time) } } impl PartialOrd for Task { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.time.partial_cmp(&other.time) } } impl PartialEq for Task { fn eq(&self, other: &Self) -> bool { self.time.eq(&other.time) } } impl Eq for Task { }
C#
UTF-8
889
2.90625
3
[]
no_license
using System.Collections.Generic; public class MultiTask : Task { private List<SingleTask> taskList; private float createdAt; private string id; public MultiTask(List<SingleTask> taskList, float createdAt) { this.taskList = taskList; this.createdAt = createdAt; this.id = System.Guid.NewGuid().ToString(); } public bool evaluate(List<ButtonHistory> buttonHistory, float time) { foreach (Task item in taskList) { if (item.evaluate(buttonHistory, time)) { continue; } else { return false; } } return true; } public int score() { int totalScore = 0; foreach (SingleTask task in taskList) { totalScore += task.score(); } return totalScore; } public float timeGenerated() { return createdAt; } public string getId() { return id; } }
Java
UTF-8
37,146
3.296875
3
[]
no_license
package uk.co.geolib.geopolygons; import uk.co.geolib.geolib.*; import java.util.ArrayList; public class C2DHoledPolyBase { /** * Constructor. */ public C2DHoledPolyBase() { } /** * Constructor. * * @param Other Other polygon to set this to. */ public C2DHoledPolyBase(C2DHoledPolyBase Other) { Rim = new C2DPolyBase(Other.Rim); for (int i = 0; i < Other.getHoleCount(); i++) { Holes.add(new C2DPolyBase(Other.GetHole(i))); } } /** * Constructor. * * @param Other Other polygon to set this to. */ public C2DHoledPolyBase(C2DPolyBase Other) { Rim = new C2DPolyBase(Other); } /** * Assignment. * * @param Other Other polygon to set this to. */ public void Set(C2DHoledPolyBase Other) { Rim.Set(Other.Rim); Holes.clear(); for (int i = 0; i < Other.getHoleCount(); i++) { Holes.add(new C2DPolyBase(Other.GetHole(i))); } } /** * Return the number of lines. */ public int GetLineCount() { int nResult = 0; nResult += Rim.Lines.size(); for (int i = 0; i < Holes.size(); i++) { nResult += Holes.get(i).Lines.size(); } return nResult; } /** * Clears the shape. */ public void Clear() { Rim.Clear(); Holes.clear(); } /** * Validity check. True if the holes are contained and non-intersecting. */ public boolean IsValid() { for (int i = 0; i < Holes.size(); i++) { if (!Rim.Contains(Holes.get(i))) return false; } int h = 0; while (h < Holes.size()) { int r = h + 1; while (r < Holes.size()) { if (Holes.get(h).Overlaps(Holes.get(r))) return false; r++; } h++; } return true; } /** * Rotates to the right by the angle around the origin. * * @param dAng Angle in radians to rotate by. * @param Origin The origin. */ public void RotateToRight(double dAng, C2DPoint Origin) { Rim.RotateToRight(dAng, Origin); for (int i = 0; i < Holes.size(); i++) { Holes.get(i).RotateToRight(dAng, Origin); } } /** * Moves the polygon. * * @param Vector Vector to move by. */ public void Move(C2DVector Vector) { Rim.Move(Vector); for (int i = 0; i < Holes.size(); i++) { Holes.get(i).Move(Vector); } } /** * Grows around the origin. * * @param dFactor Factor to grow by. * @param Origin Origin to grow this around. */ public void Grow(double dFactor, C2DPoint Origin) { Rim.Grow(dFactor, Origin); for (int i = 0; i < Holes.size(); i++) { Holes.get(i).Grow(dFactor, Origin); } } /** * Point reflection. * * @param Point Point through which to reflect this. */ public void Reflect(C2DPoint Point) { Rim.Reflect(Point); for (int i = 0; i < Holes.size(); i++) { Holes.get(i).Reflect(Point); } } /** * Reflects throught the line provided. * * @param Line Line through which to reflect this. */ public void Reflect(C2DLine Line) { Rim.Reflect(Line); for (int i = 0; i < Holes.size(); i++) { Holes.get(i).Reflect(Line); } } /** * Distance from the point. * * @param TestPoint Point to find the distance to. */ public double Distance(C2DPoint TestPoint) { double dResult = Rim.Distance(TestPoint); boolean bInside = dResult < 0; dResult = Math.abs(dResult); for (int i = 0; i < Holes.size(); i++) { double dDist = Holes.get(i).Distance(TestPoint); if (dDist < 0) bInside = false; if (Math.abs(dDist) < dResult) dResult = Math.abs(dDist); } if (bInside) return dResult; else return -dResult; } /** * Distance from the line provided. * * @param Line Line to find the distance to. */ public double Distance(C2DLineBase Line) { double dResult = Rim.Distance(Line); if (dResult == 0) return 0; boolean bInside = dResult < 0; dResult = Math.abs(dResult); for (int i = 0; i < Holes.size(); i++) { double dDist = Holes.get(i).Distance(Line); if (dDist == 0) return 0; if (dDist < 0) bInside = false; if (Math.abs(dDist) < dResult) dResult = Math.abs(dDist); } if (bInside) return dResult; else return -dResult; } /** * Distance from the polygon provided. * * @param Poly Polygon to find the distance to. * @param ptOnThis Closest point on this to recieve the result. * @param ptOnOther Closest point on the other to recieve the result. */ public double Distance(C2DPolyBase Poly, C2DPoint ptOnThis, C2DPoint ptOnOther) { C2DPoint ptOnThisResult = new C2DPoint(); C2DPoint ptOnOtherResult = new C2DPoint(); double dResult = Rim.Distance(Poly, ptOnThis, ptOnOther); if (dResult == 0) return 0; ptOnThisResult.Set(ptOnThis); ptOnOtherResult.Set(ptOnOther); boolean bInside = dResult < 0; dResult = Math.abs(dResult); for (int i = 0; i < Holes.size(); i++) { double dDist = Holes.get(i).Distance(Poly, ptOnThis, ptOnOther); if (dDist == 0) return 0; if (dDist < 0) bInside = false; if (Math.abs(dDist) < dResult) { ptOnThisResult.Set(ptOnThis); ptOnOtherResult.Set(ptOnOther); dResult = Math.abs(dDist); } } ptOnThis.Set(ptOnThisResult); ptOnOther.Set(ptOnOtherResult); if (bInside) return dResult; else return -dResult; } /** * Proximity test. * * @param TestPoint Point to test against. * @param dDist Distance threshold. */ public boolean IsWithinDistance(C2DPoint TestPoint, double dDist) { if (Rim.IsWithinDistance(TestPoint, dDist)) return true; for (int i = 0; i < Holes.size(); i++) { if (Holes.get(i).IsWithinDistance(TestPoint, dDist)) return true; } return false; } /** * Perimeter. */ public double GetPerimeter() { double dResult = Rim.GetPerimeter(); for (int i = 0; i < Holes.size(); i++) { dResult += Holes.get(i).GetPerimeter(); } return dResult; } /** * Projection onto the line. * * @param Line Line to project this on. * @param Interval Interval to recieve the result. */ public void Project(C2DLine Line, CInterval Interval) { Rim.Project(Line, Interval); } /** * Projection onto the vector. * * @param Vector Vector to project this on. * @param Interval Interval to recieve the result. */ public void Project(C2DVector Vector, CInterval Interval) { Rim.Project(Vector, Interval); } /** * Returns true if there are crossing lines. */ public boolean HasCrossingLines() { C2DLineBaseSet Lines = new C2DLineBaseSet(); Lines.addAll(0, Rim.Lines); for (int i = 0; i < Holes.size(); i++) { Lines.addAll(0, Holes.get(i).Lines); } return Lines.HasCrossingLines(); } /** * Returns the bounding rectangle. * * @param Rect Rectangle to recieve the result. */ public void GetBoundingRect(C2DRect Rect) { Rect.Set(Rim.BoundingRect); for (int i = 0; i < Holes.size(); i++) { Rect.ExpandToInclude(Holes.get(i).BoundingRect); } } /** * Point inside test. * * @param pt Point to test for. */ public boolean Contains(C2DPoint pt) { if (!Rim.Contains(pt)) return false; for (int i = 0; i < Holes.size(); i++) { if (Holes.get(i).Contains(pt)) return false; } return true; } /** * Line entirely inside test. * * @param Line Line to test for. */ public boolean Contains(C2DLineBase Line) { if (!Rim.Contains(Line)) return false; for (int i = 0; i < Holes.size(); i++) { if (Holes.get(i).Crosses(Line) || Holes.get(i).Contains(Line.GetPointFrom())) return false; } return true; } /** * Polygon entirely inside test. * * @param Polygon Polygon to test for. */ public boolean Contains(C2DPolyBase Polygon) { if (Rim == null) return false; if (!Rim.Contains(Polygon)) return false; for (int i = 0; i < Holes.size(); i++) { if (Holes.get(i).Overlaps(Polygon)) return false; } return true; } /** * Polygon entirely inside test. * * @param Polygon Polygon to test for. */ public boolean Contains(C2DHoledPolyBase Polygon) { if (!Contains(Polygon.Rim)) return false; for (int i = 0; i < Polygon.getHoleCount(); i++) { if (!Contains(Polygon.GetHole(i))) return false; } return true; } /** * True if this crosses the line * * @param Line Line to test for. */ public boolean Crosses(C2DLineBase Line) { if (Rim.Crosses(Line)) return true; for (int i = 0; i < Holes.size(); i++) { if (Holes.get(i).Crosses(Line)) return true; } return false; } /** * True if this crosses the line. * * @param Line Line to test for. * @param IntersectionPts Point set to recieve the intersections. */ public boolean Crosses(C2DLineBase Line, C2DPointSet IntersectionPts) { C2DPointSet IntPts = new C2DPointSet(); Rim.Crosses(Line, IntPts); for (int i = 0; i < Holes.size(); i++) { Holes.get(i).Crosses(Line, IntPts); } boolean bResult = (IntPts.size() != 0); IntersectionPts.ExtractAllOf(IntPts); return (bResult); } /** * True if this crosses the other polygon. * * @param Poly Polygon to test for. */ public boolean Crosses(C2DPolyBase Poly) { if (Rim == null) return false; if (Rim.Crosses(Poly)) return true; for (int i = 0; i < Holes.size(); i++) { if (Holes.get(i).Crosses(Poly)) return true; } return false; } /** * True if this crosses the ray, returns the intersection points. * * @param Ray Ray to test for. * @param IntersectionPts Intersection points. */ public boolean CrossesRay(C2DLine Ray, C2DPointSet IntersectionPts) { C2DPointSet IntPts = new C2DPointSet(); Rim.CrossesRay(Ray, IntPts); IntersectionPts.ExtractAllOf(IntPts); for (int i = 0; i < Holes.size(); i++) { if (Holes.get(i).CrossesRay(Ray, IntPts)) { double dDist = Ray.point.Distance(IntPts.get(0)); int nInsert = 0; while (nInsert < IntersectionPts.size() && Ray.point.Distance(IntersectionPts.get(nInsert)) < dDist) { nInsert++; } IntersectionPts.addAll(nInsert, IntPts); } } return (IntersectionPts.size() > 0); } /** * True if this overlaps the other. * * @param Other Other polygon to test for. */ public boolean Overlaps(C2DHoledPolyBase Other) { if (!Overlaps(Other.Rim)) return false; for (int i = 0; i < Other.getHoleCount(); i++) { if (Other.GetHole(i).Contains(Rim)) return false; } return true; } /** * True if this overlaps the other. * * @param Other Other polygon to test for. */ public boolean Overlaps(C2DPolyBase Other) { if (Rim == null) return false; if (!Rim.Overlaps(Other)) return false; for (int i = 0; i < Holes.size(); i++) { if (Holes.get(i).Contains(Other)) return false; } return true; } /** * Function to convert polygons to complex polygons. Assigning holes to those that are contained. * The set of holed polygons will be filled from the set of simple polygons. * * @param HoledPolys Holed polygon set. * @param Polygons Simple polygon set. */ public static void PolygonsToHoledPolygons(ArrayList<C2DHoledPolyBase> HoledPolys, ArrayList<C2DPolyBase> Polygons) { ArrayList<C2DPolyBase> Unmatched = new ArrayList<C2DPolyBase>(); ArrayList<C2DHoledPolyBase> NewHoledPolys = new ArrayList<C2DHoledPolyBase>(); for (int i = Polygons.size() - 1; i >= 0; i--) { boolean bMatched = false; C2DPolyBase pPoly = Polygons.get(i); Polygons.remove(i); // Cycle through the newly created polygons to see if it's a hole. for (int p = 0; p < NewHoledPolys.size(); p++) { if (NewHoledPolys.get(p).Rim.Contains(pPoly.Lines.get(0).GetPointFrom())) { NewHoledPolys.get(p).AddHole(pPoly); bMatched = true; break; } } // If its not then compare it to all the other unknowns. if (!bMatched) { int u = 0; boolean bKnownRim = false; while (u < Unmatched.size()) { if (!bKnownRim && Unmatched.get(u).Contains(pPoly.Lines.get(0).GetPointFrom())) { // This is a hole. NewHoledPolys.add(new C2DHoledPolyBase()); NewHoledPolys.get(NewHoledPolys.size() - 1).Rim = Unmatched.get(u); Unmatched.remove(u); NewHoledPolys.get(NewHoledPolys.size() - 1).AddHole(pPoly); bMatched = true; break; } else if (pPoly.Contains(Unmatched.get(u).Lines.get(0).GetPointFrom())) { // int nCount = OverlapPolygons->GetCount(); // This is a rim. if (!bKnownRim) { // If we haven't alreay worked this out then record that its a rim // and set up the new polygon. bKnownRim = true; NewHoledPolys.add(new C2DHoledPolyBase()); NewHoledPolys.get(NewHoledPolys.size() - 1).Rim = pPoly; NewHoledPolys.get(NewHoledPolys.size() - 1).AddHole(Unmatched.get(u)); Unmatched.remove(u); } else { // We already worked out this was a rim so it must be the last polygon. NewHoledPolys.get(NewHoledPolys.size() - 1).AddHole(Unmatched.get(u)); Unmatched.remove(u); } // Record that its been matched. bMatched = true; } else { // Only if there was no match do we increment the counter. u++; } } } if (!bMatched) { Unmatched.add(pPoly); } } for (int i = 0; i < Unmatched.size(); i++) { C2DHoledPolyBase NewHoled = new C2DHoledPolyBase(); NewHoled.Rim = Unmatched.get(i); HoledPolys.add(NewHoled); } HoledPolys.addAll(NewHoledPolys); } /** * Returns the overlaps between this and the other complex polygon. * * @param Other Other polygon. * @param HoledPolys Set to receieve all the resulting polygons. * @param grid Grid containing the degenerate handling settings. */ public void GetOverlaps(C2DHoledPolyBase Other, ArrayList<C2DHoledPolyBase> HoledPolys, CGrid grid) { GetBoolean(Other, HoledPolys, true, true, grid); } /** * Returns the difference between this and the other polygon. * * @param Other Other polygon. * @param HoledPolys Set to receieve all the resulting polygons. * @param grid Grid containing the degenerate handling settings. */ public void GetNonOverlaps(C2DHoledPolyBase Other, ArrayList<C2DHoledPolyBase> HoledPolys, CGrid grid) { GetBoolean(Other, HoledPolys, false, true, grid); } /** * Returns the union of this and the other. * * @param Other Other polygon. * @param HoledPolys Set to receieve all the resulting polygons. * @param grid Grid containing the degenerate handling settings. */ public void GetUnion(C2DHoledPolyBase Other, ArrayList<C2DHoledPolyBase> HoledPolys, CGrid grid) { GetBoolean(Other, HoledPolys, false, false, grid); } /** * Returns the routes (multiple lines or part polygons) either inside or * outside the polygons provided. These are based on the intersections * of the 2 polygons e.g. the routes / part polygons of one inside or * outside the other. * * @param Poly1 The first polygon. * <param name="bP1RoutesInside">True if routes inside the second polygon are * required for the first polygon.</param> * @param Poly2 The second polygon. * <param name="bP2RoutesInside">True if routes inside the first polygon are * required for the second polygon.</param> * @param Routes1 Output. Set of lines for the first polygon. * @param Routes2 Output. Set of lines for the second polygon. * @param CompleteHoles1 Output. Complete holes for the first polygon. * @param CompleteHoles2 Output. Complete holes for the second polygon. * @param grid Contains the degenerate handling settings. */ public static void GetRoutes(C2DHoledPolyBase Poly1, boolean bP1RoutesInside, C2DHoledPolyBase Poly2, boolean bP2RoutesInside, C2DLineBaseSetSet Routes1, C2DLineBaseSetSet Routes2, ArrayList<C2DPolyBase> CompleteHoles1, ArrayList<C2DPolyBase> CompleteHoles2, CGrid grid) { if (Poly1.Rim.Lines.size() == 0 || Poly2.Rim.Lines.size() == 0) { // Debug.Assert(false, "Polygon with no lines" ); return; } C2DPointSet IntPointsTemp = new C2DPointSet(); C2DPointSet IntPointsRim1 = new C2DPointSet(); C2DPointSet IntPointsRim2 = new C2DPointSet(); ArrayList<Integer> IndexesRim1 = new ArrayList<Integer>(); ArrayList<Integer> IndexesRim2 = new ArrayList<Integer>(); ArrayList<C2DPointSet> IntPoints1AllHoles = new ArrayList<C2DPointSet>(); ArrayList<C2DPointSet> IntPoints2AllHoles = new ArrayList<C2DPointSet>(); ArrayList<ArrayList<Integer>> Indexes1AllHoles = new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> Indexes2AllHoles = new ArrayList<ArrayList<Integer>>(); // std::vector<C2DPointSet* > IntPoints1AllHoles, IntPoints2AllHoles; // std::vector<CIndexSet*> Indexes1AllHoles, Indexes2AllHoles; int usP1Holes = Poly1.getHoleCount(); int usP2Holes = Poly2.getHoleCount(); // *** Rim Rim Intersections Poly1.Rim.Lines.GetIntersections(Poly2.Rim.Lines, IntPointsTemp, IndexesRim1, IndexesRim2, Poly1.Rim.BoundingRect, Poly2.Rim.BoundingRect); IntPointsRim1.AddCopy(IntPointsTemp); IntPointsRim2.ExtractAllOf(IntPointsTemp); // *** Rim Hole Intersections for (int i = 0; i < usP2Holes; i++) { // Debug.Assert(IntPointsTemp.size() == 0); IntPoints2AllHoles.add(new C2DPointSet()); Indexes2AllHoles.add(new ArrayList<Integer>()); if (Poly1.Rim.BoundingRect.Overlaps(Poly2.GetHole(i).BoundingRect)) { Poly1.Rim.Lines.GetIntersections(Poly2.GetHole(i).Lines, IntPointsTemp, IndexesRim1, Indexes2AllHoles.get(i), Poly1.Rim.BoundingRect, Poly2.GetHole(i).BoundingRect); IntPointsRim1.AddCopy(IntPointsTemp); IntPoints2AllHoles.get(i).ExtractAllOf(IntPointsTemp); } } // *** Rim Hole Intersections for (int j = 0; j < usP1Holes; j++) { // Debug.Assert(IntPointsTemp.size() == 0); IntPoints1AllHoles.add(new C2DPointSet()); Indexes1AllHoles.add(new ArrayList<Integer>()); if (Poly2.Rim.BoundingRect.Overlaps(Poly1.GetHole(j).BoundingRect)) { Poly2.Rim.Lines.GetIntersections(Poly1.GetHole(j).Lines, IntPointsTemp, IndexesRim2, Indexes1AllHoles.get(j), Poly2.Rim.BoundingRect, Poly1.GetHole(j).BoundingRect); IntPointsRim2.AddCopy(IntPointsTemp); IntPoints1AllHoles.get(j).ExtractAllOf(IntPointsTemp); } } // *** Quick Escape boolean bRim1StartInPoly2 = Poly2.Contains(Poly1.Rim.Lines.get(0).GetPointFrom()); boolean bRim2StartInPoly1 = Poly1.Contains(Poly2.Rim.Lines.get(0).GetPointFrom()); if (IntPointsRim1.size() != 0 || IntPointsRim2.size() != 0 || bRim1StartInPoly2 || bRim2StartInPoly1) // pos no interaction { // *** Rim Routes Poly1.Rim.GetRoutes(IntPointsRim1, IndexesRim1, Routes1, bRim1StartInPoly2, bP1RoutesInside); Poly2.Rim.GetRoutes(IntPointsRim2, IndexesRim2, Routes2, bRim2StartInPoly1, bP2RoutesInside); if (IntPointsRim1.size() % 2 != 0) // Must be even { grid.LogDegenerateError(); // Debug.Assert(false); } if (IntPointsRim2.size() % 2 != 0) // Must be even { grid.LogDegenerateError(); assert false; } // *** Hole Hole Intersections for (int h = 0; h < usP1Holes; h++) { for (int k = 0; k < usP2Holes; k++) { assert IntPointsTemp.size() == 0; C2DPolyBase pHole1 = Poly1.GetHole(h); C2DPolyBase pHole2 = Poly2.GetHole(k); if (pHole1.BoundingRect.Overlaps(pHole2.BoundingRect)) { pHole1.Lines.GetIntersections(pHole2.Lines, IntPointsTemp, Indexes1AllHoles.get(h), Indexes2AllHoles.get(k), pHole1.BoundingRect, pHole2.BoundingRect); IntPoints1AllHoles.get(h).AddCopy(IntPointsTemp); IntPoints2AllHoles.get(k).ExtractAllOf(IntPointsTemp); } } } // *** Hole Routes for (int a = 0; a < usP1Holes; a++) { C2DPolyBase pHole = Poly1.GetHole(a); if (IntPoints1AllHoles.get(a).size() % 2 != 0) // Must be even { grid.LogDegenerateError(); assert false; } if (pHole.Lines.size() != 0) { boolean bHole1StartInside = Poly2.Contains(pHole.Lines.get(0).GetPointFrom()); if (IntPoints1AllHoles.get(a).size() == 0) { if (bHole1StartInside == bP1RoutesInside) CompleteHoles1.add(new C2DPolyBase(pHole)); } else { pHole.GetRoutes(IntPoints1AllHoles.get(a), Indexes1AllHoles.get(a), Routes1, bHole1StartInside, bP1RoutesInside); } } } // *** Hole Routes for (int b = 0; b < usP2Holes; b++) { C2DPolyBase pHole = Poly2.GetHole(b); if (IntPoints2AllHoles.get(b).size() % 2 != 0) // Must be even { grid.LogDegenerateError(); // Debug.Assert(false); } if (pHole.Lines.size() != 0) { boolean bHole2StartInside = Poly1.Contains(pHole.Lines.get(0).GetPointFrom()); if (IntPoints2AllHoles.get(b).size() == 0) { if (bHole2StartInside == bP2RoutesInside) CompleteHoles2.add(new C2DPolyBase(pHole)); } else { pHole.GetRoutes(IntPoints2AllHoles.get(b), Indexes2AllHoles.get(b), Routes2, bHole2StartInside, bP2RoutesInside); } } } } //for (unsigned int i = 0 ; i < IntPoints1AllHoles.size(); i++) // delete IntPoints1AllHoles.get(i); //for (unsigned int i = 0 ; i < IntPoints2AllHoles.size(); i++) // delete IntPoints2AllHoles.get(i); //for (unsigned int i = 0 ; i < Indexes1AllHoles.size(); i++) // delete Indexes1AllHoles.get(i); //for (unsigned int i = 0 ; i < Indexes2AllHoles.size(); i++) // delete Indexes2AllHoles.get(i); } /** * Moves this by a small random amount. */ public void RandomPerturb() { C2DPoint pt = Rim.BoundingRect.GetPointFurthestFromOrigin(); double dMinEq = Math.max(pt.x, pt.y) * Constants.conEqualityTolerance; CRandomNumber rn = new CRandomNumber(dMinEq * 10, dMinEq * 100); C2DVector cVector = new C2DVector(rn.Get(), rn.Get()); if (rn.GetBool()) cVector.i = -cVector.i; if (rn.GetBool()) cVector.j = -cVector.j; Move(cVector); } /** * Snaps this to the conceptual grip. * * @param grid The grid to snap to. */ public void SnapToGrid(CGrid grid) { Rim.SnapToGrid(grid); for (int i = 0; i < Holes.size(); i++) { GetHole(i).SnapToGrid(grid); } } /** * Returns the boolean result (e.g. union) of 2 shapes. Boolean Operation defined by * the inside / outside flags. * * @param Other Other polygon. * @param HoledPolys Set of polygons to recieve the result. * @param bThisInside Does the operation require elements of this INSIDE the other. * @param bOtherInside Does the operation require elements of the other INSIDE this. * @param grid The grid with the degenerate settings. */ public void GetBoolean(C2DHoledPolyBase Other, ArrayList<C2DHoledPolyBase> HoledPolys, boolean bThisInside, boolean bOtherInside, CGrid grid) { if (Rim.Lines.size() == 0 || Other.Rim.Lines.size() == 0) return; if (Rim.BoundingRect.Overlaps(Other.Rim.BoundingRect)) { switch (grid.DegenerateHandling) { case None: { ArrayList<C2DPolyBase> CompleteHoles1 = new ArrayList<C2DPolyBase>(); ArrayList<C2DPolyBase> CompleteHoles2 = new ArrayList<C2DPolyBase>(); C2DLineBaseSetSet Routes1 = new C2DLineBaseSetSet(); C2DLineBaseSetSet Routes2 = new C2DLineBaseSetSet(); GetRoutes(this, bThisInside, Other, bOtherInside, Routes1, Routes2, CompleteHoles1, CompleteHoles2, grid); Routes1.ExtractAllOf(Routes2); if (Routes1.size() > 0) { Routes1.MergeJoining(); ArrayList<C2DPolyBase> Polygons = new ArrayList<C2DPolyBase>(); for (int i = Routes1.size() - 1; i >= 0; i--) { C2DLineBaseSet pRoute = Routes1.get(i); if (pRoute.IsClosed(true)) { Polygons.add(new C2DPolyBase()); Polygons.get(Polygons.size() - 1).CreateDirect(pRoute); } else { assert false; grid.LogDegenerateError(); } } C2DHoledPolyBaseSet NewComPolys = new C2DHoledPolyBaseSet(); PolygonsToHoledPolygons(NewComPolys, Polygons); NewComPolys.AddKnownHoles(CompleteHoles1); NewComPolys.AddKnownHoles(CompleteHoles2); if (!bThisInside && !bOtherInside && NewComPolys.size() != 1) { // Debug.Assert(false); grid.LogDegenerateError(); } HoledPolys.addAll(NewComPolys); NewComPolys.clear(); } } break; case RandomPerturbation: { C2DHoledPolyBase OtherCopy = new C2DHoledPolyBase(Other); OtherCopy.RandomPerturb(); grid.DegenerateHandling = CGrid.eDegenerateHandling.None; GetBoolean(OtherCopy, HoledPolys, bThisInside, bOtherInside, grid); grid.DegenerateHandling = CGrid.eDegenerateHandling.RandomPerturbation; } break; case DynamicGrid: { C2DRect Rect = new C2DRect(); if (Rim.BoundingRect.Overlaps(Other.Rim.BoundingRect, Rect)) { //double dOldGrid = CGrid::GetGridSize(); grid.SetToMinGridSize(Rect, false); grid.DegenerateHandling = CGrid.eDegenerateHandling.PreDefinedGrid; GetBoolean(Other, HoledPolys, bThisInside, bOtherInside, grid); grid.DegenerateHandling = CGrid.eDegenerateHandling.DynamicGrid; } } break; case PreDefinedGrid: { C2DHoledPolyBase P1 = new C2DHoledPolyBase(this); C2DHoledPolyBase P2 = new C2DHoledPolyBase(Other); P1.SnapToGrid(grid); P2.SnapToGrid(grid); C2DVector V1 = new C2DVector(P1.Rim.BoundingRect.getTopLeft(), P2.Rim.BoundingRect.getTopLeft()); double dPerturbation = grid.getGridSize(); // ensure it snaps back to original grid positions. if (V1.i > 0) V1.i = dPerturbation; else V1.i = -dPerturbation; // move away slightly if possible if (V1.j > 0) V1.j = dPerturbation; else V1.j = -dPerturbation; // move away slightly if possible V1.i *= 0.411923;// ensure it snaps back to original grid positions. V1.j *= 0.313131;// ensure it snaps back to original grid positions. P2.Move(V1); grid.DegenerateHandling = CGrid.eDegenerateHandling.None; P1.GetBoolean(P2, HoledPolys, bThisInside, bOtherInside, grid); for (int i = 0; i < HoledPolys.size(); i++) HoledPolys.get(i).SnapToGrid(grid); grid.DegenerateHandling = CGrid.eDegenerateHandling.PreDefinedGrid; } break; case PreDefinedGridPreSnapped: { C2DHoledPolyBase P2 = new C2DHoledPolyBase(Other); C2DVector V1 = new C2DVector(Rim.BoundingRect.getTopLeft(), P2.Rim.BoundingRect.getTopLeft()); double dPerturbation = grid.getGridSize(); if (V1.i > 0) V1.i = dPerturbation; else V1.i = -dPerturbation; // move away slightly if possible if (V1.j > 0) V1.j = dPerturbation; else V1.j = -dPerturbation; // move away slightly if possible V1.i *= 0.411923; // ensure it snaps back to original grid positions. V1.j *= 0.313131;// ensure it snaps back to original grid positions. P2.Move(V1); grid.DegenerateHandling = CGrid.eDegenerateHandling.None; GetBoolean(P2, HoledPolys, bThisInside, bOtherInside, grid); for (int i = 0; i < HoledPolys.size(); i++) HoledPolys.get(i).SnapToGrid(grid); grid.DegenerateHandling = CGrid.eDegenerateHandling.PreDefinedGridPreSnapped; } break; }// switch } } /** * Transform by a user defined transformation. e.g. a projection. */ public void Transform(CTransformation pProject) { if (Rim != null) Rim.Transform(pProject); for (int i = 0; i < Holes.size(); i++) { Holes.get(i).Transform(pProject); } } /** * Transform by a user defined transformation. e.g. a projection. */ public void InverseTransform(CTransformation pProject) { if (Rim != null) Rim.InverseTransform(pProject); for (int i = 0; i < Holes.size(); i++) { Holes.get(i).Transform(pProject); } } /** * True if this overlaps the rect. */ public boolean Overlaps(C2DRect rect) { if (Rim == null) return false; if (!Rim.Overlaps(rect)) return false; for (int i = 0; i < Holes.size(); i++) { if (Holes.get(i).Contains(rect)) return false; } return true; } /** * Polygon entirely inside test. */ public boolean Contains(C2DRect rect) { if (Rim == null) return false; if (!Rim.Contains(rect)) return false; for (int i = 0; i < Holes.size(); i++) { if (Holes.get(i).Overlaps(rect)) return false; } return true; } /** * True if this crosses the other rect. */ public boolean Crosses(C2DRect rect) { if (Rim == null) return false; if (Rim.Crosses(rect)) return true; for (int i = 0; i < Holes.size(); i++) { if (Holes.get(i).Crosses(rect)) return true; } return false; } /** * True if this is contained by the rect. */ public boolean IsContainedBy(C2DRect rect) { if (Rim == null) return false; return Rim.IsContainedBy(rect); } /** * The outer rim. */ protected C2DPolyBase Rim = null; /** * Rim access. */ public C2DPolyBase getRim() { return Rim; } /** * Rim access. */ public void setRim(C2DPolyBase rim) { Rim = rim; } /** * Holes. */ protected ArrayList<C2DPolyBase> Holes = new ArrayList<C2DPolyBase>(); /** * Hole count. */ public int getHoleCount() { return Holes.size(); } /** * Hole access. */ public C2DPolyBase GetHole(int i) { return Holes.get(i); } /** * Hole assignment. */ public void SetHole(int i, C2DPolyBase Poly) { Holes.set(i, Poly); } /** * Hole addition. */ public void AddHole(C2DPolyBase Poly) { Holes.add(Poly); } /** * Hole removal. */ public void RemoveHole(int i) { Holes.remove(i); } }
C++
UTF-8
5,139
2.515625
3
[]
no_license
#include <gui-engine/engine.hpp> #include <istream> #include <fstream> #include <string.h> #include <glm/mat4x4.hpp> #include <glm/gtc/matrix_transform.hpp> #include <stb/stb_image.h> using namespace unibox::gui; GuiEngine::GuiEngine(const RenderEngine& renderEngine) { this->renderEngine = renderEngine; nextHandle = 1; gui_resource_handle shader = createShader("shaders/gui/texture/vertex.spv", "shaders/gui/texture/fragment.spv", SPIRV, "default_textured_shader"); gui_resource_handle shader2 = createShader("shaders/gui/color/vertex.spv", "shaders/gui/color/fragment.spv", SPIRV, "default_colored_shader"); gui_resource_handle shader3 = createShader("shaders/gui/atlas/vertex.spv", "shaders/gui/atlas/fragment.spv", SPIRV, "default_texture_atlas_shader"); projection = glm::ortho(0.0f, (float)renderEngine.width, 0.0f, (float)renderEngine.height, 10.0f, -10.0f); renderEngine.set_shader_variable(shader, "projectMatrix", &projection, 0, sizeof(projection)); renderEngine.set_shader_variable(shader2, "projectMatrix", &projection, 0, sizeof(projection)); renderEngine.set_shader_variable(shader3, "projectMatrix", &projection, 0, sizeof(projection)); default_mesh = renderEngine.create_mesh(); float data[] = { -0.5, -0.5, 0.0, 0.0, 0.0, -0.5, 0.5, 0.0, 0.0, 1.0, 0.5, -0.5, 0.0, 1.0, 0.0, -0.5, 0.5, 0.0, 0.0, 1.0, 0.5, 0.5, 0.0, 1.0, 1.0, 0.5, -0.5, 0.0, 1.0, 0.0 }; std::vector<uint8_t> vec(sizeof(data)); memcpy(vec.data(), data, sizeof(data)); renderEngine.add_mesh_vertex_data(default_mesh, vec, 6); this->width = renderEngine.width; this->height = renderEngine.height; } GuiEngine::~GuiEngine() { } uint GuiEngine::getWidth() { return width; } uint GuiEngine::getHeight() { return height; } gui_handle GuiEngine::addItem(GuiObject* object) { // TODO: [11.09.2021] Should propably check if the handle is actually available. auto last = guiObjects.begin(); gui_handle handle = nextHandle; nextHandle++; for(auto iter = guiObjects.begin(); iter != guiObjects.end(); iter++) { if((*iter)->getLayer() < object->getLayer()) { auto ins = guiObjects.insert(iter, object); mappings.insert({ handle, object }); return handle; } last = iter; } guiObjects.push_back(object); mappings.insert({ handle, object }); return handle; } void GuiEngine::removeItem(gui_handle handle) { auto map = mappings.find(handle); if(map != mappings.end()) { guiObjects.remove(map->second); mappings.erase(handle); } } gui_resource_handle GuiEngine::createShader(const std::string& vertex, const std::string& fragment, ShaderLanguage lang, const std::string& registryName) { std::ifstream vs(vertex, std::ios::binary | std::ios::ate); std::ifstream fs(fragment, std::ios::binary | std::ios::ate); if(!vs.is_open() || !fs.is_open()) return 0; size_t lenV = vs.tellg(); size_t lenF = fs.tellg(); vs.seekg(0); fs.seekg(0); std::vector<uint8_t> vcode(lenV); std::vector<uint8_t> fcode(lenF); vs.read((char*)vcode.data(), lenV); fs.read((char*)fcode.data(), lenF); gui_resource_handle handle = renderEngine.create_shader(vcode, fcode, lang); shaders.insert({ registryName, handle }); return handle; } gui_resource_handle GuiEngine::getShader(const std::string& shaderName) { auto res = shaders.find(shaderName); if(res == shaders.end()) return 0; return res->second; } gui_resource_handle GuiEngine::getOrCreateShader(const std::string& shaderName, const std::string& vertex, const std::string& fragment, ShaderLanguage lang, const std::function<void(GuiEngine&, gui_resource_handle)>& initFunc) { gui_resource_handle handle = getShader(shaderName); if(handle == 0) { handle = createShader(vertex, fragment, lang, shaderName); initFunc(*this, handle); } return handle; } void GuiEngine::render(double frameTime, double x, double y) { std::for_each(guiObjects.rbegin(), guiObjects.rend(), [frameTime, x, y](GuiObject* object) { object->render(frameTime, x, y); }); } gui_resource_handle GuiEngine::createTexture(const std::string& filepath) { int width, height, channels; stbi_uc* pixels = stbi_load(filepath.c_str(), &width, &height, &channels, STBI_rgb_alpha); return renderEngine.create_texture(width, height, pixels, R8G8B8A8, NEAREST, NEAREST); } void GuiEngine::onMouseDown(double x, double y, int button) { for(auto& object : guiObjects) { if(object->isInside(x, y) && object->mouseDown(x, y, button)) break; } } void GuiEngine::onMouseUp(double x, double y, int button) { for(auto& object : guiObjects) { if(object->isInside(x, y) && object->mouseUp(x, y, button)) break; } } const RenderEngine& GuiEngine::getRenderEngine() { return renderEngine; } gui_resource_handle GuiEngine::getDefaultMesh() { return default_mesh; } const glm::mat4& GuiEngine::getProjectionMatrix() { return projection; }
Java
UTF-8
3,643
2.125
2
[]
no_license
package mobius.bmlvcgen.bml.bmllib; import java.util.Enumeration; import mobius.bmlvcgen.bml.ClassFile; import mobius.bmlvcgen.bml.ClassVisitor; import mobius.bmlvcgen.bml.InvExprVisitor; import mobius.bmlvcgen.util.Visitable; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import annot.attributes.clazz.ClassInvariant; import annot.bcclass.BCClass; import annot.bcclass.BMLModifiersFlags; import com.sun.org.apache.xalan.internal.xsltc.compiler.Constants; /** * Bmllib implementation of ClassFile interface. * @author Tadeusz Sznuk (tsznuk@mimuw.edu.pl) */ public class BmllibClassFile implements ClassFile { // Bmllib handle. private final BCClass clazz; // BCEL handle. private final JavaClass jc; // Object used to wrap invariants. private final InvExprWrapper invWrapper; /** * Constructor. * @param clazz Class to be wrapped. */ public BmllibClassFile(final BCClass clazz) { this.clazz = clazz; invWrapper = new InvExprWrapper(); jc = clazz.getJC().getJavaClass(); } /** {@inheritDoc} */ public void accept(final ClassVisitor v) { v.visitVersion(jc.getMajor(), jc.getMinor()); v.visitFlags(AccessFlag.fromMask(jc.getAccessFlags())); v.visitName(jc.getClassName()); processSuper(v); processInterfaces(v); processFields(v); processMethods(v); processInvariants(v); } // Visit superclass name. private void processSuper(final ClassVisitor v) { try { if (jc.getSuperClass() == null) { v.visitSuperName(null); } else { v.visitSuperName(jc.getSuperclassName()); } } catch (final ClassNotFoundException e) { v.visitSuperName(null); } } // Visit interfaces. private void processInterfaces(final ClassVisitor v) { v.beginInterfaces(); for (final String i : jc.getInterfaceNames()) { v.visitInterface(i); } v.endInterfaces(); } // Visit fields. private void processFields(final ClassVisitor v) { // TODO: How to parse field flags?? v.beginFields(); for (final Field field : jc.getFields()) { v.visitField(new BmllibField(field)); } v.endFields(); } // Visit methods. private void processMethods(final ClassVisitor v) { v.beginMethods(); for (int i = 0; i < clazz.getMethodCount(); i++) { v.visitMethod(new BmllibMethod(clazz.getMethod(i))); } v.endMethods(); } // Wrap all invariants and pass them to a visitor. private void processInvariants(final ClassVisitor v) { final Enumeration<?> i = clazz.getInvariantEnum(); while (i.hasMoreElements()) { final ClassInvariant inv = (ClassInvariant)i.nextElement(); final Visitable<InvExprVisitor> wrappedInv = invWrapper.wrap(inv.getInvariant()); final int flags = inv.getAccessFlags(); if ((flags & Constants.ACC_STATIC) != 0) { throw new UnsupportedOperationException( "Static invariants are not supported" ); } else { v.visitInvariant(getVisibility(flags), wrappedInv); } } } // Read visibility from bml flags. private static Visibility getVisibility(final int flags) { final Visibility result; if ((flags & BMLModifiersFlags.BML_SPEC_PUBLIC) != 0) { result = Visibility.PUBLIC; } else if ( (flags & BMLModifiersFlags.BML_SPEC_PROTECTED) != 0) { result = Visibility.PROTECTED; } else { result = Visibility.DEFAULT; } return result; } }
Java
UTF-8
2,793
3.78125
4
[]
no_license
package com.ifeng.yanggz.day6; import java.util.LinkedList; import java.util.Queue; /** * 1、拓扑排序算法 * 2、深度优先算法 * * 1-->3-->2-->5 * 3-->6-->4 * 0-->7 */ public class TopoSort { private int v; private LinkedList<Integer>[] adj; public TopoSort(int v) { this.v = v; adj = new LinkedList[v]; for(int i=0; i<v; i++) { adj[i] = new LinkedList<>(); } } /** * 添加边 */ public void addEdge(int s, int t) { adj[s].add(t); } /** * 深度优先遍历 */ public void topoSortDFS() { // 构建逆邻接表 LinkedList<Integer>[] inverseAdj = new LinkedList[v]; // 申请空间 for(int k=0; k<v; k++) { inverseAdj[k] = new LinkedList<>(); } for(int i=0; i<v; i++) { for(int j=0; j<adj[i].size(); j++) { int p = adj[i].get(j); inverseAdj[p].add(i); } } boolean[] visited = new boolean[v]; // 深度优先遍历 for(int j=0; j<v; j++) { if(visited[j] == false) { visited[j] = true; recurDFS(j, inverseAdj, visited); } } } private void recurDFS(int w, LinkedList<Integer>[] inverseAdj, boolean[] visited) { for(int i=0; i<inverseAdj[w].size(); i++) { int p = inverseAdj[w].get(i); if(visited[p]) { continue; } visited[p] = true; recurDFS(p, inverseAdj, visited); } System.out.print("-->" + w); } /** * apn算法 */ public void topoSortKapn() { int[] inDegree = new int[v]; for(int i=0; i<v; i++) { for(int j=0; j<adj[i].size(); j++) { int p = adj[i].get(j); inDegree[p]++; } } Queue<Integer> queue = new LinkedList<>(); for (int i=0; i<v; i++) { if(inDegree[i] == 0) { queue.add(i); } } while (!queue.isEmpty()) { int q = queue.poll(); System.out.print("-->" + q); for(int j=0; j<adj[q].size(); j++) { int w = adj[q].get(j); inDegree[w]--; if(inDegree[w] == 0) { queue.add(w); } } } } public static void main(String[] args) { TopoSort graph = new TopoSort(8); graph.addEdge(1, 3); graph.addEdge(3, 2); graph.addEdge(2, 5); graph.addEdge(3, 6); graph.addEdge(6, 4); graph.addEdge(0, 7); //graph.topoSortKapn(); graph.topoSortDFS(); } }
Java
UTF-8
5,371
1.929688
2
[]
no_license
package com.example.sjyy_expert_android.activity.patient; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.sjyy_expert_android.BaseActivity; import com.example.sjyy_expert_android.R; import com.example.sjyy_expert_android.entity.BaseRespons; import com.example.sjyy_expert_android.entity.orderBean.CancelRequest; import com.example.sjyy_expert_android.http.NetRequestEngine; import com.example.sjyy_expert_android.util.ShareUtil; /*** * 类描述:患者取消预约界面 * * @author 海洋 */ public class CancelActivity extends BaseActivity { private Button btn_title_left, btn_title_right; private TextView tv_title_content,tv_cancel; private final static int SUCCESS = 1; private CancelRequest bean; private BaseRespons base; private RelativeLayout rl_cancel_refuse; private EditText et_cancel; private Button btn_cancel_commit; private String refuse, orderId; private int refuseId; private String refuseType; private String[] provinces = new String[] { "病情已经好转", "已在附近就医", "预约时间冲突", "其他" }; private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case SUCCESS: if (msg.obj != null && msg.obj instanceof BaseRespons) { base = (BaseRespons) msg.obj; if (base.resultCode.equals("1000")) { showToast("已成功取消!"); finish(); } else { showToast(base.resultInfo); } } else { showToast(msg.obj+""); } break; default: break; } stopProgressDialog(); }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cancel_activity); initview(); } private void initview() { Intent intent = getIntent(); orderId = intent.getStringExtra("orderId"); tv_cancel=(TextView) findViewById(R.id.tv_cancel); btn_title_left = (Button) findViewById(R.id.btn_title_left); btn_title_right = (Button) findViewById(R.id.btn_title_right); tv_title_content = (TextView) findViewById(R.id.tv_title_content); btn_title_left.setOnClickListener(this); btn_title_left.setText(""); btn_title_left.setBackgroundResource(R.drawable.back); btn_title_right.setText(""); tv_title_content.setText("取消预约"); btn_cancel_commit = (Button) findViewById(R.id.btn_cancel_commit); btn_cancel_commit.setOnClickListener(this); rl_cancel_refuse = (RelativeLayout) findViewById(R.id.rl_cancel_refuse); rl_cancel_refuse.setOnClickListener(this); et_cancel = (EditText) findViewById(R.id.et_cancel); } @Override public void onClick(View v) { super.onClick(v); switch (v.getId()) { case R.id.btn_title_left: break; case R.id.btn_cancel_commit: refuseType = tv_cancel.getText().toString().trim(); refuse = et_cancel.getText().toString(); if (refuseType.equals("拒绝原因")) { showToast("请选择取消原因"); } else { if (refuseType.equals("病情已经好转")) { refuseId = 0; } else if (refuseType.equals("已在附近就医")) { refuseId = 1; } else if (refuseType.equals("预约时间冲突")) { refuseId = 2; } else if (refuseType.equals("其他")) { refuseId = 3; } new dataThread().start(); } break; case R.id.rl_cancel_refuse: showListDialog(); break; default: break; } } class dataThread extends Thread { @Override public void run() { bean = new CancelRequest(); bean.orderStatus = 100; bean.cancelType = refuseId; bean.cancelContent = refuse; bean.orderId = orderId; bean.userId = ShareUtil.getAccountId(CancelActivity.this); Object data = NetRequestEngine.patientOrderCancel(bean); Message message = Message.obtain(); message.obj = data; message.what = SUCCESS; handler.sendMessage(message); } } private void showListDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("请选择原因"); /** * * 1、public Builder setItems(int itemsId, final OnClickListener * * listener) itemsId表示字符串数组的资源ID,该资源指定的数组会显示在列表中。 2、public Builder * * setItems(CharSequence[] items, final OnClickListener listener) * * items表示用于显示在列表中的字符串数组 */ builder.setItems(provinces, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: tv_cancel.setText("病情已经好转"); break; case 1: tv_cancel.setText("已在附近就医"); break; case 2: tv_cancel.setText("预约时间冲突"); break; case 3: tv_cancel.setText("其他"); break; default: break; } } }); builder.create().show(); } }
Java
UTF-8
762
2.328125
2
[]
no_license
package com.keven.springDemo.serviceImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import com.keven.springDemo.service.PublishService; @Service("publishService") public class PublishServiceImpl implements PublishService { private static Logger logger = LoggerFactory.getLogger(PublishServiceImpl.class); private StringRedisTemplate redisTempplate; @Override public String sendMessage(String name) { try { redisTempplate.convertAndSend("TOPOC_USERNAME", name); return "消息发送成功"; } catch (Exception e) { logger.error("消息发送失败:{}", e.getMessage()); return "消息嘎松失败"; } } }
Swift
UTF-8
2,642
3.09375
3
[]
no_license
// // Adder // sugarPackageDescription // // Created by Aidar Nugmanov on 1/22/18. // import Foundation import Commander import Files // MARK: - AdderError public enum AdderError { case failedToLocatePodfile case failedToReadContents case corruptedStructureError case failedToUpdatePodfile } extension AdderError: PrintableError { public var message: String { switch self { case .failedToLocatePodfile: return "Failed to located Podfile in the current directory." case .failedToReadContents: return "Failed to read contents of Podfile." case .corruptedStructureError: return "Corrupted structure of Podfile detected." case .failedToUpdatePodfile: return "Failed to update Podfile." } } } // MARK: - Adder public final class Adder { private var runner = ScriptRunner() private typealias Error = AdderError // MARK: - Init public init() { } public func perform(pod: String, version: Double, path: String) { addPod(pod, with: version, and: path) } // MARK: - Private private func addPod(_ pod: String, with version: Double, and path: String) { do { var podfile = try getContents(from: path) let index = try getIndex(for: podfile) var entry = "\n pod '\(pod)'" entry += (version != -1.0 ? ", '~> \(version)'" : "") podfile.insert(contentsOf: entry.characters, at: String.Index.init(encodedOffset: index)) try updatePodfile(with: podfile, at: path) } catch { print(error.localizedDescription) } } private func updatePodfile(with contents: String, at path: String) throws { guard let file = try? Folder(path: path).file(named: "Podfile") else { throw Error.failedToLocatePodfile } do { try file.write(data: contents.data(using: .utf8)!) } catch { throw Error.failedToUpdatePodfile } } private func getIndex(for podfile: String) throws -> Int { guard let lastIndex = podfile.lastIndex(of: "end") else { throw Error.corruptedStructureError } return lastIndex - 1 } private func getContents(from path: String) throws -> String { guard let file = try? Folder(path: path).file(named: "Podfile") else { throw Error.failedToLocatePodfile } guard let contents = try? file.readAsString() else { throw Error.failedToReadContents } return contents } }
JavaScript
UTF-8
1,474
2.578125
3
[]
no_license
import React from 'react'; import { ScrollView, View, Text, FlatList, useWindowDimensions, } from 'react-native'; const height = 200; const data = new Array(10).fill(0); const App = () => { const {width} = useWindowDimensions(); const renderItem = ({index}) => { return ( <View style={{ width, height, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center', borderWidth: 1, }} key={index}> <Text>{`Count is ${index}`}</Text> </View> ); }; return ( <View style={{ width, }}> <Text style={{height: 50, textAlign: 'center', textAlignVertical: 'center'}}> This is a Horizontal ScrollView </Text> <ScrollView horizontal={true} pagingEnabled={false} snapToInterval={width} decelerationRate={'fast'} persistentScrollbar> {data.map((_, index) => renderItem({index}))} </ScrollView> <Text style={{height: 50, textAlign: 'center', textAlignVertical: 'center'}}> This is a Vertical FlatList </Text> <FlatList renderItem={renderItem} data={data} keyExtractor={(item, index) => index.toString()} style={{height}} snapToInterval={height} persistentScrollbar decelerationRate={'fast'} /> </View> ); }; export default App;
Python
UTF-8
2,150
4.46875
4
[]
no_license
#Given an integer array, you need to find one continuous subarray that #if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. # O(N) O(1) class Solution(object): def findUnsortedSubarray(self, nums): """ :type nums: List[int] :rtype: int """ i, j = 0, len(nums) - 1 length = len(nums) while i < length - 1 and nums[i] <= nums[i + 1]: i += 1 if i == len(nums) - 1: return 0 while j > 0 and nums[j - 1] <= nums[j]: j -= 1 curmin, curmax = min(nums[i: (j + 1)]), max(nums[i:(j + 1)]) while i >= 0 and nums[i] > curmin: i -= 1 while j <= length -1 and nums[j] < curmax: j += 1 return j - i - 1 ''' The idea behind this method is that the correct position of the minimum element in the unsorted subarray helps to determine the required left boundary. Similarly, the correct position of the maximum element in the unsorted subarray helps to determine the required right boundary. Thus, firstly we need to determine when the correctly sorted array goes wrong. We keep a track of this by observing rising slope starting from the beginning of the array. Whenever the slope falls, we know that the unsorted array has surely started. Thus, now we determine the minimum element found till the end of the array numsnums, given by minmin. Similarly, we scan the array numsnums in the reverse order and when the slope becomes rising instead of falling, we start looking for the maximum element till we reach the beginning of the array, given by maxmax. Then, we traverse over numsnums and determine the correct position of minmin and maxmax by comparing these elements with the other array elements. e.g. To determine the correct position of minmin, we know the initial portion of numsnums is already sorted. Thus, we need to find the first element which is just larger than minmin. Similarly, for maxmax's position, we need to find the first element which is just smaller than maxmax searching in numsnums backwards. '''
Markdown
UTF-8
3,167
2.75
3
[]
no_license
# 第二章. 创建数据索引 本章覆盖了: 1. 索引PDF文件 2. 自动生成unique字段 3. 怎样正确配置JDBC数据导入 4. 使用数据导入工具从数据库创建数据索引 5. 怎样使用数据导入工具导入数据和delta查询 6. 怎样使用数据导入工具从URL数据源导入数据 7. 怎样在导入数据时对数据做修改 8. 更新文档中的一个简单的字段 9. 处理多个currencies 10. 检测文档语言 11. 优化主键索引 ## 简介 在Solr和Lucene部署中创建数据索引是最重要的一步。配置不当的话搜索结果会很少。搜索结果很少的话,那么用户肯定会对应用不满,这就是为什么我们需要尽可能地准备和所有数据。 另外一方面,获取数据也不是件容易的事儿。我们身边有着各种各样的数据。我们需要从多重格式的数据中创建多重格式的索引。我们需要手工解析和准备XML格式的数据?当然,我们会使用solr做这个。本章主要从怎样索引二进制的PDF文件讲索引创建过程和数据准备,讲述怎样使用数据导入工具从数据库抓取数据并使用Apache的solr创建索引。最终描述怎样在创建索引的时候判断文档的语言类型。 ## 索引PDF文件 >想象下把图书馆中收藏的书放到互联网上。需要书籍提供商提供书的PDF格式的样张,然后才可以分享给网络上的用户。假如所有的样章都提供了,然后问题出现了,怎样从海量的PDF文件中索引准确的数据。Solr可以通过Apache的 Tika实现。 ### 实现步骤 1. 使用PDFCreator创建测试PDF文件book.pdf,内容为“This is a Solr cookbook” 2. 使用CURL从文件创建索引:curl "http://localhost:8983/solr/update/extract?literal.id=1&commit=true"-F "myfile=@book.pdf" 返回值如下: `<?xml version="1.0" encoding="UTF-8"?> <response> <lst name="responseHeader"> <int name="status">0</int> <int name="QTime">578</int> </lst> </response>` 3. 从浏览器查询: http://localhost:8983/solr/select/?q=text:solr 返回结果如下: `<?xml version="1.0" encoding="UTF-8"?> <response> ... <result name="response" numFound="1" start="0"> <doc> <arr name="attr_created"><str>Thu Oct 21 16:11:51 CEST 2010</ str></arr> <arr name="attr_creator"><str>PDFCreator Version 1.0.1</str></arr> <arr name="attr_producer"><str>GPL Ghostscript 8.71</str></arr> <arr name="attr_stream_content_type"><str>application/octet- stream</str></arr> <arr name="attr_stream_name"><str>cookbook.pdf</str></arr> <arr name="attr_stream_size"><str>3209</str></arr> <arr name="attr_stream_source_info"><str>myfile</str></arr> <str name="author">Gr0</str> <arr name="content_type"><str>application/pdf</str></arr> <str name="id">1</str> <str name="keywords"/> <date name="last_modified">2010-10-21T14:11:51Z</date> <str name="subject"/> <arr name="title"><str>cookbook</str></arr> </doc> </result> </response>`
JavaScript
UTF-8
1,878
2.734375
3
[ "GPL-3.0-only" ]
permissive
/*global alert, confirm, console, prompt, pageJson, window */ /*jslint es6 */ window.dataLayer = window.dataLayer || []; const giftProcess = pageJson.giftProcess; console.log("Looking for giftProcess..."); if (giftProcess) { // If giftProcess has any value other than the boolean "false" // window.dataLayer.push({ event: 'giftProcess-' + giftProcess}); console.log("giftProcess is present, logging an event with its value: giftProcess-", giftProcess); window.dataLayer.push({ 'event': 'experiments', 'gtmCategory': 'Engaging Networks Experiment - giftProcess Testing', 'gtmAction': 'Engaging Networks Donation Thank You Page', 'gtmLabel': 'giftProcess-' + giftProcess, 'gtmValue': undefined }); } else if (giftProcess === false) { // If giftProcess has a boolean value of "false" // window.dataLayer.push({ event: 'giftProcess-false' }); console.log("giftProcess is present but 'false', logging an event with its value: giftProcess-", giftProcess); window.dataLayer.push({ 'event': 'experiments', 'gtmCategory': 'Engaging Networks Experiment - giftProcess Testing', 'gtmAction': 'Engaging Networks Donation Thank You Page', 'gtmLabel': 'giftProcess-false', 'gtmValue': undefined }); } else { // If giftProcess has no defined value or is non-existant // window.dataLayer.push({ event: 'giftProcess-' + x}); console.log("giftProcess is present and without a value or missing Logging an event with its value: giftProcess-", x); const x = typeof giftProcess; window.dataLayer.push({ 'event': 'experiments', 'gtmCategory': 'Engaging Networks Experiment - giftProcess Testing', 'gtmAction': 'Engaging Networks Donation Thank You Page', 'gtmLabel': 'giftProcess-' + x, 'gtmValue': undefined }); }
Java
UTF-8
39,625
2.84375
3
[]
no_license
package edu.cwru.sepia.agent.planner; import java.util.ArrayList; import java.util.List; import edu.cwru.sepia.agent.planner.actions.CreateAction; import edu.cwru.sepia.agent.planner.actions.DepositAction; import edu.cwru.sepia.agent.planner.actions.HarvestAction; import edu.cwru.sepia.agent.planner.actions.MoveAction; import edu.cwru.sepia.agent.planner.actions.StripsAction; import edu.cwru.sepia.environment.model.state.ResourceNode; import edu.cwru.sepia.environment.model.state.State; import edu.cwru.sepia.environment.model.state.Unit; /** * This class is used to represent the state of the game after applying one of * the available actions. It will also track the A* specific information such as * the parent pointer and the cost and heuristic function. Remember that unlike * the path planning A* from the first assignment the cost of an action may be * more than 1. Specifically the cost of executing a compound action such as * move can be more than 1. You will need to account for this in your heuristic * and your cost function. * * The first instance is constructed from the StateView object (like in PA2). * Implement the methods provided and add any other methods and member variables * you need. * * Some useful API calls for the state view are * * state.getXExtent() and state.getYExtent() to get the map size * * I recommend storing the actions that generated the instance of the GameState * in this class using whatever class/structure you use to represent actions. */ public class GameState implements Comparable<GameState> { // The Action done to get to this state private ArrayList<StripsAction> parentAction = null; // The state of the parent prior to the parent Action private GameState parentState = null; private ArrayList<Peasant> peasants; private ArrayList<Forest> forests; private ArrayList<GoldMine> goldMines; private TownHall townHall; private int goalWood; private int goalGold; private int myWood = 0; private int myGold = 0; private int totalWoodOnMap = 0; private int totalGoldOnMap = 0; private boolean buildPeasants = false; private int totalFoodOnMap = 0; private int playerNum; private State.StateView state; private int myCost = 0; /** * Construct a GameState from a stateview object. This is used to construct * the initial search node. All other nodes should be constructed from the * another constructor you create or by factory functions that you create. * * @param state * The current stateview at the time the plan is being created * @param playernum * The player number of agent that is planning * @param requiredGold * The goal amount of gold (e.g. 200 for the small scenario) * @param requiredWood * The goal amount of wood (e.g. 200 for the small scenario) * @param buildPeasants * True if the BuildPeasant action should be considered */ public GameState(State.StateView state, int playernum, int requiredGold, int requiredWood, boolean buildPeasants) { this.state = state; this.playerNum = playernum; this.goalWood = requiredWood; this.goalGold = requiredGold; this.buildPeasants = buildPeasants; peasants = new ArrayList<Peasant>(); forests = new ArrayList<Forest>(); goldMines = new ArrayList<GoldMine>(); // extracts the resources from the state for (ResourceNode.ResourceView resource : state.getAllResourceNodes()) { if (resource.getType().toString().equals("TREE")) { forests.add(new Forest(false, resource.getAmountRemaining(), new Position(resource.getXPosition(), resource.getYPosition()))); totalWoodOnMap += resource.getAmountRemaining(); } else if (resource.getType().toString().equals("GOLD_MINE")) { goldMines.add(new GoldMine(false, resource.getAmountRemaining(), new Position(resource.getXPosition(), resource.getYPosition()))); totalGoldOnMap += resource.getAmountRemaining(); } } // extracts the units from the state for (Unit.UnitView unit : state.getAllUnits()) { if (unit.getTemplateView().getName().toLowerCase().equals("peasant")) { this.peasants.add(new Peasant(null, 0, new Position(unit.getXPosition(), unit.getYPosition()), this.peasants.size())); } if (unit.getTemplateView().getName().toLowerCase().equals("townhall")) { this.townHall = new TownHall(true, unit, new Position(unit.getXPosition(), unit.getYPosition())); } } totalFoodOnMap = state.getSupplyCap(playernum); } public GameState(ArrayList<StripsAction> parentAction, GameState parentState, ArrayList<Peasant> peasant, ArrayList<Forest> forests, ArrayList<GoldMine> goldMines, TownHall townHall, int goalWood, int goalGold, int myWood, int myGold, int playerNum, State.StateView state, int costToState, int totalWoodOnMap, int totalGoldOnMap, boolean buildPeasants, int totalFoodOnMap) { this.parentAction = parentAction; this.parentState = parentState; this.peasants = peasant; this.forests = forests; this.goldMines = goldMines; this.townHall = townHall; this.goalWood = goalWood; this.goalGold = goalGold; this.myWood = myWood; this.myGold = myGold; this.playerNum = playerNum; this.state = state; this.myCost = costToState; this.totalWoodOnMap = totalWoodOnMap; this.totalGoldOnMap = totalGoldOnMap; this.buildPeasants = buildPeasants; this.totalFoodOnMap = totalFoodOnMap; } /** * Unlike in the first A* assignment there are many possible goal states. As * long as the wood and gold requirements are met the peasants can be at any * location and the capacities of the resource locations can be anything. * Use this function to check if the goal conditions are met and return true * if they are. * * @return true if the goal conditions are met in this instance of game * state. */ public boolean isGoal() { return myWood >= goalWood && myGold >= goalGold; } /** * The branching factor of this search graph are much higher than the * planning. Generate all of the possible successor states and their * associated actions in this method. * * @return A list of the possible successor states and their associated * actions */ public List<GameState> generateChildren() { List<ArrayList<GameState>> prelimaryChildren = new ArrayList<ArrayList<GameState>>(); for (int i = 0; i < this.peasants.size(); i++) { ArrayList<GameState> children = getChildren(peasants.get(i)); if (children != null) { prelimaryChildren.add(children); } } return mergeChildren(prelimaryChildren); } /** * Once when there are more than 2 parent actions, we need to merge the * children * * @param listChildren * @return */ private List<GameState> mergeChildren(List<ArrayList<GameState>> listChildren) { if (listChildren.size() == 1) { return listChildren.get(0); } List<GameState> children = new ArrayList<GameState>(); if (listChildren.size() == 2) { for (GameState gamestate1 : listChildren.get(0)) { for (GameState gamestate2 : listChildren.get(1)) { GameState newChild = mergeState(gamestate1, gamestate2); if (newChild != null) { children.add(newChild); } } } for (int i = 0; i < children.size(); i++) { Position p1 = children.get(i).getPeasants().get(0).getPosition(); Position p2 = children.get(i).getPeasants().get(1).getPosition(); // to avoid SEPIA collision (which is full of bugs) we avoid // trying to go to the same place if (p1.x == p2.x && p1.y == p2.y) { if (children.size() > 1) { children.remove(i); } } } } else if (listChildren.size() == 3) { for (GameState gamestate1 : listChildren.get(0)) { for (GameState gamestate2 : listChildren.get(1)) { for (GameState gamestate3 : listChildren.get(2)) { GameState newChild = mergeState(gamestate1, gamestate2, gamestate3); if (newChild != null) { children.add(newChild); } } } } for (int i = 0; i < children.size(); i++) { Position p1 = children.get(i).getPeasants().get(0).getPosition(); Position p2 = children.get(i).getPeasants().get(1).getPosition(); Position p3 = children.get(i).getPeasants().get(2).getPosition(); // To avoid collision, avoid going to the same place if ((p1.x == p2.x && p1.y == p2.y) || (p1.x == p3.x && p1.y == p3.y) || (p3.x == p2.x && p3.y == p2.y)) { if (children.size() > 1) { children.remove(i); } } } } return children; } /** * If action1 is to harvest from resource x, and action 2 and or action 3 * moves towards that resource (to harvest eventually), we need to make sure * that resource has enough for 3 peasants * * @param action1Name * @param action2Name * @param action3Name * @param action1 * @param action2 * @param action3 * @return */ private boolean collisionCheck(String action1Name, String action2Name, String action3Name, StripsAction action1, StripsAction action2, StripsAction action3) { MapObject a1 = null; MapObject a2 = null; MapObject a3 = null; int r1 = 0; int r2 = 0; int r3 = 0; if (action1Name.toString().equals("HARVEST")) { HarvestAction harvest = (HarvestAction) action1; a1 = harvest.getResource(); if (a1.getName().toString().equals("FOREST")) { Forest forest = (Forest) a1; for (Forest f : this.getForests()) { if (f.getPosition().x == forest.getPosition().x && f.getPosition().y == forest.getPosition().y) { r1 = f.getResourceQuantity(); break; } } } else if (a1.getName().toString().equals("GOLDMINE")) { GoldMine goldmine = (GoldMine) a1; for (GoldMine g : this.getGoldMines()) { if (g.getPosition().x == goldmine.getPosition().x && g.getPosition().y == goldmine.getPosition().y) { r1 = g.getResourceQuantity(); break; } } } } else if (action1Name.toString().equals("MOVE")) { MoveAction move = (MoveAction) action1; a1 = move.getMapObject(); if (a1.getName().toString().equals("FOREST")) { Forest forest = (Forest) a1; for (Forest f : this.getForests()) { if (f.getPosition().x == forest.getPosition().x && f.getPosition().y == forest.getPosition().y) { r1 = f.getResourceQuantity(); break; } } } else if (a1.getName().toString().equals("GOLDMINE")) { GoldMine goldmine = (GoldMine) a1; for (GoldMine g : this.getGoldMines()) { if (g.getPosition().x == goldmine.getPosition().x && g.getPosition().y == goldmine.getPosition().y) { r1 = g.getResourceQuantity(); break; } } } } else if (action1Name.toString().equals("DEPOSIT")) { a1 = this.townHall; } if (action2Name.toString().equals("HARVEST")) { HarvestAction harvest = (HarvestAction) action2; a2 = harvest.getResource(); if (a2.getName().toString().equals("FOREST")) { Forest forest = (Forest) a2; for (Forest f : this.getForests()) { if (f.getPosition().x == forest.getPosition().x && f.getPosition().y == forest.getPosition().y) { r2 = f.getResourceQuantity(); break; } } } else if (a2.getName().toString().equals("GOLDMINE")) { GoldMine goldmine = (GoldMine) a2; for (GoldMine g : this.getGoldMines()) { if (g.getPosition().x == goldmine.getPosition().x && g.getPosition().y == goldmine.getPosition().y) { r2 = g.getResourceQuantity(); break; } } } } else if (action2Name.toString().equals("MOVE")) { MoveAction move = (MoveAction) action2; a2 = move.getMapObject(); if (a2.getName().toString().equals("FOREST")) { Forest forest = (Forest) a2; for (Forest f : this.getForests()) { if (f.getPosition().x == forest.getPosition().x && f.getPosition().y == forest.getPosition().y) { r2 = f.getResourceQuantity(); break; } } } else if (a2.getName().toString().equals("GOLDMINE")) { GoldMine goldmine = (GoldMine) a2; for (GoldMine g : this.getGoldMines()) { if (g.getPosition().x == goldmine.getPosition().x && g.getPosition().y == goldmine.getPosition().y) { r2 = g.getResourceQuantity(); break; } } } } else if (action2Name.toString().equals("DEPOSIT")) { a2 = this.townHall; } if (action3Name.toString().equals("HARVEST")) { HarvestAction harvest = (HarvestAction) action3; a3 = harvest.getResource(); if (a3.getName().toString().equals("FOREST")) { Forest forest = (Forest) a3; for (Forest f : this.getForests()) { if (f.getPosition().x == forest.getPosition().x && f.getPosition().y == forest.getPosition().y) { r3 = f.getResourceQuantity(); break; } } } else if (a3.getName().toString().equals("GOLDMINE")) { GoldMine goldmine = (GoldMine) a3; for (GoldMine g : this.getGoldMines()) { if (g.getPosition().x == goldmine.getPosition().x && g.getPosition().y == goldmine.getPosition().y) { r3 = g.getResourceQuantity(); break; } } } } else if (action3Name.toString().equals("MOVE")) { MoveAction move = (MoveAction) action3; a3 = move.getMapObject(); if (a3.getName().toString().equals("FOREST")) { Forest forest = (Forest) a3; for (Forest f : this.getForests()) { if (f.getPosition().x == forest.getPosition().x && f.getPosition().y == forest.getPosition().y) { r3 = f.getResourceQuantity(); break; } } } else if (a3.getName().toString().equals("GOLDMINE")) { GoldMine goldmine = (GoldMine) a3; for (GoldMine g : this.getGoldMines()) { if (g.getPosition().x == goldmine.getPosition().x && g.getPosition().y == goldmine.getPosition().y) { r3 = g.getResourceQuantity(); break; } } } } else if (action3Name.toString().equals("DEPOSIT")) { a3 = this.townHall; } // if 1, 2, 3 are the same // if 1, 2 are the same // if 2, 3 are the same // if 1, 3 are the same Position p1 = a1.getPosition(); Position p2 = a2.getPosition(); Position p3 = a3.getPosition(); if (p1.x == p2.x && p1.y == p2.y && p2.x == p3.x && p2.y == p3.y) { if (!a1.getName().toString().equals("TOWNHALL") && r1 < 300) { return true; } } else if (p1.x == p2.x && p1.y == p2.y) { if (!a1.getName().toString().equals("TOWNHALL") && r1 < 200) { return true; } } else if (p2.x == p3.x && p2.y == p3.y) { if (!a2.getName().toString().equals("TOWNHALL") && r2 < 200) { return true; } } else if (p1.x == p3.x && p1.y == p3.y) { if (!a3.getName().toString().equals("TOWNHALL") && r3 < 200) { return true; } } return false; } /** * Merging the state of 3 actions into one. * * @param state1 * @param state2 * @param state3 * @return */ private GameState mergeState(GameState state1, GameState state2, GameState state3) { StripsAction action1 = state1.parentAction.get(0); StripsAction action2 = state2.parentAction.get(0); StripsAction action3 = state3.parentAction.get(0); String action1Name = action1.getAction(); String action2Name = action2.getAction(); String action3Name = action3.getAction(); Peasant peasant1 = null; Peasant peasant2 = null; Peasant peasant3 = null; if (collisionCheck(action1Name, action2Name, action3Name, action1, action2, action3)) { return null; } ArrayList<StripsAction> newAction = new ArrayList<StripsAction>(); ArrayList<Peasant> newPeasants = new ArrayList<Peasant>(); ArrayList<Forest> newForests = new ArrayList<Forest>(); ArrayList<GoldMine> newGoldMines = new ArrayList<GoldMine>(); TownHall newTownHall = state1.getTownHall(); int newMyWood = state1.getMyWood(); int newMyGold = state1.getMyGold(); int newCost = state1.getMyCost(); for (Peasant peasant : state1.peasants) { if (peasant.getUnitID() == action1.getPeasant().getUnitID()) { peasant1 = peasant; } } for (Peasant peasant : state2.peasants) { if (peasant.getUnitID() == action2.getPeasant().getUnitID()) { peasant2 = peasant; } } for (Peasant peasant : state3.peasants) { if (peasant.getUnitID() == action3.getPeasant().getUnitID()) { peasant3 = peasant; } } for (Forest forest : state1.getForests()) { newForests.add(forest); } for (GoldMine goldmine : state1.getGoldMines()) { newGoldMines.add(goldmine); } newAction.add(action1); newAction.add(action2); newAction.add(action3); newPeasants.add(peasant1); newPeasants.add(peasant2); newPeasants.add(peasant3); GameState newState = new GameState(newAction, this, newPeasants, newForests, newGoldMines, newTownHall, state1.getGoalWood(), state1.getGoalGold(), newMyWood, newMyGold, state1.getPlayerNum(), state1.getState(), newCost, state1.getTotalWoodOnMap(), state1.getTotalGoldOnMap(), state1.isBuildPeasants(), state1.getTotalFoodOnMap()); switch (action2Name) { case ("MOVE"): newState.setMyCost(newState.getMyCost() + state2.getMyCost()); break; case ("HARVEST"): newState.setMyCost(newState.getMyCost() + 1); HarvestAction harvest = (HarvestAction) action2; MapObject resource = harvest.getResource(); if (resource.getName().equals("FOREST")) { for (int i = 0; i < newState.getForests().size(); i++) { Forest forest = newState.getForests().get(i); if (forest.getPosition().x == resource.getPosition().x && forest.getPosition().y == resource.getPosition().y) { if (forest.getResourceQuantity() == 0) { return null; } forest.setResourceQuantity(forest.getResourceQuantity() - 100); // If the amount of wood at that forest is less than 0, // then // we don't consider it anymore if (forest.getResourceQuantity() <= 0) { ArrayList<Forest> newForest = newState.getForests(); ArrayList<Forest> updateForest = new ArrayList<Forest>(); for (Forest forests : newForest) { if (forests.getResourceQuantity() != 0) { updateForest.add(forests); } } newState.setForests(updateForest); } break; } } } else if (resource.getName().equals("GOLDMINE")) { for (int i = 0; i < newState.getGoldMines().size(); i++) { GoldMine goldmine = newState.getGoldMines().get(i); if (goldmine.getPosition().x == resource.getPosition().x && goldmine.getPosition().y == resource.getPosition().y) { if (goldmine.getResourceQuantity() == 0) { return null; } goldmine.setResourceQuantity(goldmine.getResourceQuantity() - 100); // If the amount of wood at that forest is less than 0, // then // we don't consider it anymore if (goldmine.getResourceQuantity() <= 0) { ArrayList<GoldMine> newGoldMine = newState.getGoldMines(); ArrayList<GoldMine> updateGoldMine = new ArrayList<GoldMine>(); for (GoldMine goldmines : newGoldMine) { if (goldmines.getResourceQuantity() != 0) { updateGoldMine.add(goldmines); } } newState.setGoldMines(updateGoldMine); } break; } } } break; case ("DEPOSIT"): newState.setMyCost(newState.getMyCost() + 1); DepositAction deposit = (DepositAction) action2; if (deposit.getPeasant().getHoldingObject().toString().equals("WOOD")) { newState.setMyWood(newState.getMyWood() + deposit.getPeasant().getResourceQuantity()); } else if (deposit.getPeasant().getHoldingObject().toString().equals("GOLD")) { newState.setMyGold(newState.getMyGold() + deposit.getPeasant().getResourceQuantity()); } break; } switch (action3Name) { case ("MOVE"): newState.setMyCost(newState.getMyCost() + state3.getMyCost()); break; case ("HARVEST"): newState.setMyCost(newState.getMyCost() + 1); HarvestAction harvest = (HarvestAction) action3; MapObject resource = harvest.getResource(); if (resource.getName().equals("FOREST")) { for (int i = 0; i < newState.getForests().size(); i++) { Forest forest = newState.getForests().get(i); if (forest.getPosition().x == resource.getPosition().x && forest.getPosition().y == resource.getPosition().y) { if (forest.getResourceQuantity() == 0) { return null; } forest.setResourceQuantity(forest.getResourceQuantity() - 100); // If the amount of wood at that forest is less than 0, // then // we don't consider it anymore if (forest.getResourceQuantity() <= 0) { ArrayList<Forest> newForest = newState.getForests(); ArrayList<Forest> updateForest = new ArrayList<Forest>(); for (Forest forests : newForest) { if (forests.getResourceQuantity() != 0) { updateForest.add(forests); } } newState.setForests(updateForest); } break; } } } else if (resource.getName().equals("GOLDMINE")) { for (int i = 0; i < newState.getGoldMines().size(); i++) { GoldMine goldmine = newState.getGoldMines().get(i); if (goldmine.getPosition().x == resource.getPosition().x && goldmine.getPosition().y == resource.getPosition().y) { if (goldmine.getResourceQuantity() == 0) { return null; } goldmine.setResourceQuantity(goldmine.getResourceQuantity() - 100); // If the amount of wood at that forest is less than 0, // then // we don't consider it anymore if (goldmine.getResourceQuantity() <= 0) { ArrayList<GoldMine> newGoldMine = newState.getGoldMines(); ArrayList<GoldMine> updateGoldMine = new ArrayList<GoldMine>(); for (GoldMine goldmines : newGoldMine) { if (goldmines.getResourceQuantity() != 0) { updateGoldMine.add(goldmines); } } newState.setGoldMines(updateGoldMine); } break; } } } break; case ("DEPOSIT"): newState.setMyCost(newState.getMyCost() + 1); DepositAction deposit = (DepositAction) action3; if (deposit.getPeasant().getHoldingObject().toString().equals("WOOD")) { newState.setMyWood(newState.getMyWood() + deposit.getPeasant().getResourceQuantity()); } else if (deposit.getPeasant().getHoldingObject().toString().equals("GOLD")) { newState.setMyGold(newState.getMyGold() + deposit.getPeasant().getResourceQuantity()); } break; } return newState; } /** * Merging the state of 2 actions into 1 * * @param state1 * @param state2 * @return */ private GameState mergeState(GameState state1, GameState state2) { StripsAction action1 = state1.parentAction.get(0); StripsAction action2 = state2.parentAction.get(0); String action1Name = action1.getAction(); String action2Name = action2.getAction(); if (action1Name.equals(action2Name) && action1Name.equals("CREATE")) { return null; } Peasant peasant1 = null; Peasant peasant2 = null; ArrayList<StripsAction> newAction = new ArrayList<StripsAction>(); ArrayList<Peasant> newPeasants = new ArrayList<Peasant>(); ArrayList<Forest> newForests = new ArrayList<Forest>(); ArrayList<GoldMine> newGoldMines = new ArrayList<GoldMine>(); TownHall newTownHall = state1.getTownHall(); int newMyWood = state1.getMyWood(); int newMyGold = state1.getMyGold(); int newCost = state1.getMyCost(); for (Peasant peasant : state1.peasants) { if (peasant.getUnitID() == action1.getPeasant().getUnitID()) { peasant1 = peasant; } } for (Peasant peasant : state2.peasants) { if (peasant.getUnitID() == action2.getPeasant().getUnitID()) { peasant2 = peasant; } } for (Forest forest : state1.getForests()) { newForests.add(forest); } for (GoldMine goldmine : state1.getGoldMines()) { newGoldMines.add(goldmine); } newAction.add(action1); newAction.add(action2); newPeasants.add(peasant1); newPeasants.add(peasant2); GameState newState = new GameState(newAction, this, newPeasants, newForests, newGoldMines, newTownHall, state1.getGoalWood(), state1.getGoalGold(), newMyWood, newMyGold, state1.getPlayerNum(), state1.getState(), newCost, state1.getTotalWoodOnMap(), state1.getTotalGoldOnMap(), state1.isBuildPeasants(), state1.getTotalFoodOnMap()); switch (action2Name) { case ("MOVE"): newState.setMyCost(newState.getMyCost() + state2.getMyCost()); break; case ("HARVEST"): newState.setMyCost(newState.getMyCost() + 1); HarvestAction harvest = (HarvestAction) action2; MapObject resource = harvest.getResource(); if (resource.getName().equals("FOREST")) { for (int i = 0; i < newState.getForests().size(); i++) { Forest forest = newState.getForests().get(i); if (forest.getPosition().x == resource.getPosition().x && forest.getPosition().y == resource.getPosition().y) { if (forest.getResourceQuantity() == 0) { return null; } forest.setResourceQuantity(forest.getResourceQuantity() - 100); // If the amount of wood at that forest is less than 0, // then // we don't consider it anymore if (forest.getResourceQuantity() <= 0) { ArrayList<Forest> newForest = newState.getForests(); ArrayList<Forest> updateForest = new ArrayList<Forest>(); for (Forest forests : newForest) { if (forests.getResourceQuantity() != 0) { updateForest.add(forests); } } newState.setForests(updateForest); } break; } } } else if (resource.getName().equals("GOLDMINE")) { for (int i = 0; i < newState.getGoldMines().size(); i++) { GoldMine goldmine = newState.getGoldMines().get(i); if (goldmine.getPosition().x == resource.getPosition().x && goldmine.getPosition().y == resource.getPosition().y) { if (goldmine.getResourceQuantity() == 0) { return null; } goldmine.setResourceQuantity(goldmine.getResourceQuantity() - 100); // If the amount of wood at that forest is less than 0, // then // we don't consider it anymore if (goldmine.getResourceQuantity() <= 0) { ArrayList<GoldMine> newGoldMine = newState.getGoldMines(); ArrayList<GoldMine> updateGoldMine = new ArrayList<GoldMine>(); for (GoldMine goldmines : newGoldMine) { if (goldmines.getResourceQuantity() != 0) { updateGoldMine.add(goldmines); } } newState.setGoldMines(updateGoldMine); } break; } } } break; case ("DEPOSIT"): newState.setMyCost(newState.getMyCost() + 1); DepositAction deposit = (DepositAction) action2; if (deposit.getPeasant().getHoldingObject().toString().equals("WOOD")) { newState.setMyWood(newState.getMyWood() + deposit.getPeasant().getResourceQuantity()); } else if (deposit.getPeasant().getHoldingObject().toString().equals("GOLD")) { newState.setMyGold(newState.getMyGold() + deposit.getPeasant().getResourceQuantity()); } break; case ("CREATE"): if (newState.getPeasants().size() == newState.getTotalFoodOnMap()) { return null; } newState.setMyCost(newState.getMyCost() + 1); for (Peasant peasant : state2.getPeasants()) { if (peasant.getUnitID() != newState.getPeasants().get(0).getUnitID() && peasant.getUnitID() != newState.getPeasants().get(1).getUnitID()) { newState.getPeasants().add(peasant); } } newState.setMyGold(newState.getMyGold() - 400); break; } return newState; } /** * Gets all possible children of a peasant * * @param peasant * @return */ private ArrayList<GameState> getChildren(Peasant peasant) { ArrayList<GameState> children = new ArrayList<GameState>(); StripsAction actionOfInterest = null; if (parentAction == null || parentAction.isEmpty() || parentAction.size() == 0) { } else { for (StripsAction action : parentAction) { if (peasant.getUnitID() == action.getPeasant().getUnitID()) { actionOfInterest = action; } else { if (action.getAction().equals("CREATE")) { actionOfInterest = action; } } } } // If peasant isn't holding anything, it should move to a resource, or // harvest at a resource if (peasant.getIsEmpty()) { for (GoldMine goldmine : goldMines) { HarvestAction harvest = new HarvestAction(peasant, goldmine); if (harvest.preconditionsMet(this)) { children.add(harvest.apply(this)); } if (parentAction == null || actionOfInterest.getAction() != "MOVE") { MoveAction move = new MoveAction(peasant, goldmine, goldmine.getPosition()); children.add(move.apply(this)); } } for (Forest forest : forests) { HarvestAction harvest = new HarvestAction(peasant, forest); if (harvest.preconditionsMet(this)) { children.add(harvest.apply(this)); } if (parentAction == null || actionOfInterest.getAction() != "MOVE") { MoveAction move = new MoveAction(peasant, forest, forest.getPosition()); children.add(move.apply(this)); } } } // If a peasant is holding something, it should move towards the // TownHall, or deposit at TownHall if (!peasant.getIsEmpty()) { DepositAction deposit = new DepositAction(peasant); if (deposit.preconditionsMet(this)) { children.add(deposit.apply(this)); } if (parentAction == null || actionOfInterest == null || actionOfInterest.getAction() != "MOVE") { MoveAction move = new MoveAction(peasant, this.townHall, townHall.getPosition()); children.add(move.apply(this)); } } if (peasant.getPosition().isAdjacent(this.getTownHall().getPosition())) { CreateAction create = new CreateAction(peasant); if (create.preconditionsMet(this)) { children.add(create.apply(this)); } } return children; } /** * Write your heuristic function here. Remember this must be admissible for * the properties of A* to hold. If you can come up with an easy way of * computing a consistent heuristic that is even better, but not strictly * necessary. * * Add a description here in your submission explaining your heuristic. * * @return The value estimated remaining cost to reach a goal state from * this state. */ public double heuristic() { double heuristic = 0; ArrayList<StripsAction> lastAction = parentAction; ArrayList<StripsAction> ancestorAction = this.getParentState().getParentAction(); if (ancestorAction == null) { return heuristic; } if (lastAction.size() == 1) { heuristic += heuristicPerPeasant(lastAction.get(0), ancestorAction.get(0)); } if (lastAction.size() == 2) { heuristic += 1000; StripsAction lAct1 = lastAction.get(0); StripsAction lAct2 = null; StripsAction aAct1 = ancestorAction.get(0); StripsAction aAct2 = null; if (lastAction.size() > 1) { lAct2 = lastAction.get(1); } if (ancestorAction.size() > 1) { aAct2 = ancestorAction.get(1); } if (lAct2 == null) { heuristic += 1000; return heuristic; } // This means that the ancestor just did a create action if (aAct2 == null) { heuristic += 1000; heuristic += heuristicPerPeasant(lAct1, aAct1); heuristic += heuristicPerPeasant(lAct2, aAct1); } else { heuristic += heuristicPerPeasant(lAct1, aAct1); heuristic += heuristicPerPeasant(lAct2, aAct2); } } if (lastAction.size() == 3) { heuristic += 2000; StripsAction lAct1 = lastAction.get(0); StripsAction lAct2 = lastAction.get(1); StripsAction lAct3 = lastAction.get(2); StripsAction aAct1 = ancestorAction.get(0); StripsAction aAct2 = null; StripsAction aAct3 = null; if (ancestorAction.size() > 1) { aAct2 = ancestorAction.get(1); } if (ancestorAction.size() > 2) { aAct3 = ancestorAction.get(2); } if (aAct2 == null) { heuristic += 2000; return heuristic; } // This means that the ancestor just did a create action if (aAct3 == null) { heuristic += 1000; if (lAct1.getAction().toString().equals("CREATE")) { heuristic += heuristicPerPeasant(lAct1, aAct1); heuristic += heuristicPerPeasant(lAct2, aAct2); heuristic += heuristicPerPeasant(lAct3, aAct1); } else { heuristic += heuristicPerPeasant(lAct1, aAct1); heuristic += heuristicPerPeasant(lAct2, aAct2); heuristic += heuristicPerPeasant(lAct3, aAct2); } } else { heuristic += heuristicPerPeasant(lAct1, aAct1); heuristic += heuristicPerPeasant(lAct2, aAct2); heuristic += heuristicPerPeasant(lAct3, aAct3); } } return heuristic; } /** * The heuristic such that it prioritizes getting gold first since we need * gold to build peasants and it is more advantageous to build peasants * early on than later. * * Also punishes the peasant if it tries to get more gold if we have already * reached gold's goal. Likewise for wood. * * @param parentAction * @param ancestorsAction * @return */ private double heuristicPerPeasant(StripsAction parentAction, StripsAction ancestorsAction) { double heuristic = 0; String lastAction = parentAction.getAction(); String ancestorAction = ancestorsAction.getAction(); switch (ancestorAction) { case "MOVE": switch (lastAction) { case "HARVEST": HarvestAction harvest = (HarvestAction) parentAction; if (harvest.getResource().getName().equals("FOREST")) { if (myWood < goalWood) { heuristic += 200; } if (myWood > goalWood) { heuristic -= 1000; } } else if (harvest.getResource().getName().equals("GOLDMINE")) { if (myGold < goalGold) { heuristic += 400; } if (myGold > goalGold) { heuristic -= 1000; } } break; case "DEPOSIT": heuristic += 100; break; } break; case "HARVEST": switch (lastAction) { case "MOVE": heuristic += 500; break; } break; case "DEPOSIT": switch (lastAction) { case "MOVE": MoveAction moveAction = (MoveAction) parentAction; String moveToResourceType = moveAction.getMapObject().getName(); switch (moveToResourceType) { case "FOREST": if (myWood < goalWood) { heuristic += 200; } if (myWood > goalWood) { heuristic -= 1000; } break; case "GOLDMINE": if (myGold < goalGold) { heuristic += 400; } if (myGold > goalGold) { heuristic -= 1000; } break; case "CREATE": heuristic += (goalWood - myWood) * 10; heuristic += (goalGold - myGold) * 10; break; } break; case "CREATE": heuristic += 500; break; } break; case "CREATE": switch (lastAction) { case "MOVE": MoveAction moveAction = (MoveAction) parentAction; String moveToResourceType = moveAction.getMapObject().getName(); switch (moveToResourceType) { case "FOREST": if (myWood < goalWood) { heuristic += 200; } if (myWood > goalWood) { heuristic -= 1000; } break; case "GOLDMINE": if (myGold < goalGold) { heuristic += 400; } if (myGold > goalGold) { heuristic -= 1000; } break; } break; } break; } return heuristic; } /** * * Write the function that computes the current cost to get to this node. * This is combined with your heuristic to determine which actions/states * are better to explore. * * @return The current cost to reach this goal */ public double getCost() { return this.myCost + heuristic(); } /** * This is necessary to use your state in the Java priority queue. See the * official priority queue and Comparable interface documentation to learn * how this function should work. * * @param o * The other game state to compare * @return 1 if this state costs more than the other, 0 if equal, -1 * otherwise */ @Override public int compareTo(GameState o) { // TODO: Implement me! return new Double(this.getCost()).compareTo(o.getCost()); } /** * This will be necessary to use the GameState as a key in a Set or Map. * * @param o * The game state to compare * @return True if this state equals the other state, false otherwise. */ @Override public boolean equals(Object o) { if (!o.getClass().equals(GameState.class)) { return false; } GameState otherState = (GameState) o; if (goalWood != otherState.getGoalWood() || goalGold != otherState.getGoalGold() || myWood != otherState.getMyWood() || myGold != otherState.getMyGold()) { return false; } if (!parentAction.equals(otherState.getParentAction())) { return false; } return true; } /** * This is necessary to use the GameState as a key in a HashSet or HashMap. * Remember that if two objects are equal they should hash to the same * value. * * @return An integer hashcode that is equal for equal states. */ @Override public int hashCode() { // TODO: Implement me! return 0; } public ArrayList<StripsAction> getParentAction() { return parentAction; } public void setParentAction(ArrayList<StripsAction> parentAction) { this.parentAction = parentAction; } public GameState getParentState() { return parentState; } public void setParentState(GameState parentState) { this.parentState = parentState; } public ArrayList<Peasant> getPeasants() { return peasants; } public void setPeasants(ArrayList<Peasant> peasants) { this.peasants = peasants; } public ArrayList<Forest> getForests() { return forests; } public void setForests(ArrayList<Forest> forests) { this.forests = forests; } public ArrayList<GoldMine> getGoldMines() { return goldMines; } public void setGoldMines(ArrayList<GoldMine> goldMines) { this.goldMines = goldMines; } public TownHall getTownHall() { return townHall; } public void setTownHall(TownHall townHall) { this.townHall = townHall; } public int getGoalWood() { return goalWood; } public void setGoalWood(int goalWood) { this.goalWood = goalWood; } public int getGoalGold() { return goalGold; } public void setGoalGold(int goalGold) { this.goalGold = goalGold; } public int getMyWood() { return myWood; } public void setMyWood(int myWood) { this.myWood = myWood; } public int getMyGold() { return myGold; } public void setMyGold(int myGold) { this.myGold = myGold; } public int getPlayerNum() { return playerNum; } public void setPlayerNum(int playerNum) { this.playerNum = playerNum; } public State.StateView getState() { return state; } public void setState(State.StateView state) { this.state = state; } public int getTotalWoodOnMap() { return totalWoodOnMap; } public void setTotalWoodOnMap(int totalWoodOnMap) { this.totalWoodOnMap = totalWoodOnMap; } public int getTotalGoldOnMap() { return totalGoldOnMap; } public void setTotalGoldOnMap(int totalGoldOnMap) { this.totalGoldOnMap = totalGoldOnMap; } public boolean isBuildPeasants() { return buildPeasants; } public int getTotalFoodOnMap() { return totalFoodOnMap; } public void setTotalFoodOnMap(int totalFoodOnMap) { this.totalFoodOnMap = totalFoodOnMap; } public void setMyCost(int cost) { this.myCost = cost; } public int getMyCost() { return this.myCost; } public String toString() { StringBuilder sb = new StringBuilder(); for (Peasant peasant : peasants) { sb.append("[PEASANT: " + peasant.getPosition().toString() + "] \n"); } sb.append("[Action: " + this.parentAction.toString() + "] \n [HEURISTIC: " + heuristic() + "]"); return sb.toString(); } }
Markdown
UTF-8
1,934
3.359375
3
[]
no_license
--- title: Servlet表单数据 time: 2019-11-07 categories: Servlet tags: Servlet --- # Servlet表单数据 --- 很多情况下,需要传递一些信息,从浏览器到 Web 服务器,最终到后台程序。浏览器使用两种方法可将这些信息传递到 Web 服务器,分别为 GET 方法和 POST 方法。 ## GET 方法 GET 方法向页面请求发送已编码的用户信息。页面和已编码的信息中间用 ? 字符分隔,如下所示: ``` http://www.test.com/hello?key1=value1&key2=value2 ``` GET 方法是默认的从浏览器向 Web 服务器传递信息的方法,它会产生一个很长的字符串,出现在浏览器的地址栏中。如果您要向服务器传递的是密码或其他的敏感信息,请不要使用 GET 方法。GET 方法有大小限制:请求字符串中最多只能有 1024 个字符。 这些信息使用 QUERY_STRING 头传递,并可以通过 QUERY_STRING 环境变量访问,Servlet 使用 doGet() 方法处理这种类型的请求。 ## POST 方法 另一个向后台程序传递信息的比较可靠的方法是 POST 方法。POST 方法打包信息的方式与 GET 方法基本相同,但是 POST 方法不是把信息作为 URL 中 ? 字符后的文本字符串进行发送,而是把这些信息作为一个单独的消息。消息以标准输出的形式传到后台程序,您可以解析和使用这些标准输出。Servlet 使用 doPost() 方法处理这种类型的请求。 ## 使用 Servlet 读取表单数据 Servlet 处理表单数据,这些数据会根据不同的情况使用不同的方法自动解析: * getParameter():您可以调用 request.getParameter() 方法来获取表单参数的值。 * getParameterValues():如果参数出现一次以上,则调用该方法,并返回多个值,例如复选框。 * getParameterNames():如果您想要得到当前请求中的所有参数的完整列表,则调用该方法。
Python
UTF-8
1,051
2.75
3
[]
no_license
#!/usr/bin/env python import os,sys,time import Tkinter,subprocess class PyRun(): def __init__(self): self.root = Tkinter.Tk() self.entry = Tkinter.Entry(self.root,width=20) self.entry.pack(expand=1,fill=Tkinter.X,pady=10,padx=15) #self.entry.bind("<Return>",self.ParseCmd) self.entry.focus_set() #self.center_window() self.root.mainloop() def ParseCmd(self,event): cmd = self.entry.get() if cmd == "chrome": subprocess.Popen([cmd]) elif cmd == "mintty": subprocess.Popen(["d:\\msys\\bin\mintty","-e","d:\\msys\\bin\\bash.exe","--login","-i"]) elif cmd == "explorer": subprocess.Popen(["d:\\msys\\bin\mintty","-e","d:\\msys\\bin\\bash.exe","--login","-i"]) sys.exit() def center_window(self): ws = self.root.winfo_screenwidth() hs = self.root.winfo_screenheight() x = (ws/2) y = (hs/2) self.root.geometry('+%d+%d' % (x, y)) if __name__ == "__main__": PyRun()
Markdown
UTF-8
539
2.59375
3
[ "MIT" ]
permissive
# Discretize ![Mixture.Discretize](../../images/Mixture.Discretize.png) ## Inputs Port Name | Description --- | --- Source | Step Count | Min | Max | ## Output Port Name | Description --- | --- Out | ## Description Discretize an image, rounding it's color components to make the specified number of steps in the image. This node can also be used to make a posterize effect. By default the input values are considered to be between 0 and 1, you can change these values in the node inspector to adapt the effect to your input data.
Java
UTF-8
1,336
3.53125
4
[]
no_license
package com.yy.thread.communication; import java.util.concurrent.CountDownLatch; /** * 倒计时触发器Demo * @author zhaoming@yy.com * */ public class CountDownLatchDemo { static final int countDownSize = 5; public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(countDownSize); Waiter waiter = new Waiter(latch); Decrementer decrementer = new Decrementer(latch); new Thread(waiter).start(); new Thread(decrementer).start(); Thread.sleep(6000); } } /** * 等待 * @author zhaoming@yy.com * 2014-4-6 */ class Waiter implements Runnable { CountDownLatch latch = null; public Waiter(CountDownLatch latch) { this.latch = latch; } public void run() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Waiter Released"); } } /** * 递减操作 * @author zhaoming@yy.com * 2014-4-6 */ class Decrementer implements Runnable { CountDownLatch latch = null; public Decrementer(CountDownLatch latch) { this.latch = latch; } public void run() { try { for (int i = 1; i <= CountDownLatchDemo.countDownSize; i++) { Thread.sleep(1000); this.latch.countDown(); System.out.println(this + " run " + i + " times."); } } catch (InterruptedException e) { e.printStackTrace(); } } }
PHP
UTF-8
3,671
2.609375
3
[]
no_license
<?php // Name: Developer Working On Display // Format: Custom Text // Data Source: Fogbugz Working On data for each customer $app->get('/developers', $apiAuthenticate(), $setFormat, function () use ($app) { $fogbugz = new FogBugz( $app->config->user, $app->config->pass, $app->config->url ); try { $developers = array(); $fogbugz->logon(); $xml = $fogbugz->listPeople(); $ignore = explode(',', $app->config->ignore); $now = new DateTime(); foreach ($xml->people->children() as $person) { // Ignore users idle for more than 4 months $lastseen = new DateTime((string) $person->dtLastActivity); $interval = $now->diff($lastseen); if ($interval->format('%m') > 4) { continue; } if (in_array((string) $person->sFullName, $ignore)) { continue; } $developers[] = (object) array( "name" => utf8_encode((string) $person->sFullName), "email" => utf8_encode((string) $person->sEmail), "workingOn" => utf8_encode((string) $person->ixBugWorkingOn) ); } //print "<pre>";var_dump($developers); foreach ($developers as &$developer) { if (empty($developer->workingOn) || ($developer->workingOn === 0)) { $developer->workingOn = (object) array( "number" => "", "title" => "&nbsp;", "status" => "" ); continue; } $xml = $fogbugz->search(array( 'q' => (int) $developer->workingOn, 'cols' => 'ixBug,sTitle,sStatus' )); $case = $xml->cases->case; $developer->workingOn = (object) array( "number" => utf8_encode((string) $case->ixBug), "title" => utf8_encode((string) $case->sTitle), "status" => utf8_encode((string) $case->sStatus) ); } unset($developer); //https://insight.geckoboard.com/css/dashboard.css $html = '<div><dl class="b-project-list">'; foreach ($developers as $developer) { if (empty($developer->workingOn->number)) { $html .= '<dt class="t-size-x14 t-main"><span class="led red"></span>' . $developer->name . "</dt>"; $html .= '<dd class="t-size-x11"><span class="t-muted">&nbsp;</span></dd>'; } else { $html .= '<dt class="t-size-x14 t-main"><span class="led green"></span>' . $developer->name . "</dt>"; $html .= sprintf( '<dd class="t-size-x11 t-main"><a class="t-muted" href="https://learningstation.fogbugz.com/default.asp?%d">Case %d</a><span class="t-muted">: %s</span></dd>', $developer->workingOn->number, $developer->workingOn->number, $developer->workingOn->title ); } } $html .= "</dl></div>"; $data = array('item' => array( array('text' => $html) )); $response = $app->geckoResponse->getResponse($data); echo $response; } catch (Exception $e) { $error = sprintf( "[Code %d] %s\n", $e->getCode(), $e->getMessage() ); Header("HTTP/1.1 500 Internal Server Error"); $data = array('error' => $error); echo $app->geckoResponse->getResponse($data); exit(1); } }); /* End of file developers.php */
Java
UTF-8
4,305
1.84375
2
[]
no_license
package cn.com.fubon.interceptors; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jodd.util.StringUtil; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import org.jeecgframework.core.extend.datasource.DataSourceContextHolder; import org.jeecgframework.core.extend.datasource.DataSourceType; import org.jeecgframework.core.util.JSONHelper; import org.jeecgframework.core.util.ResourceUtil; import org.springframework.util.StringUtils; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import weixin.guanjia.account.entity.WeixinAccountEntity; import weixin.guanjia.account.service.WeixinAccountServiceI; import weixin.guanjia.core.util.WeixinUtil; import weixin.popular.util.JsonUtil; import cn.com.fubon.fo.customerbind.entity.WeiXinGzUserInfo; import cn.com.fubon.fo.customerbind.service.CustomerBindService; import cn.com.fubon.fo.event.service.IEventProcessingService; import cn.com.fubon.util.Constants; import cn.com.fubon.util.FBStringUtils; /** * 未关注用户,获取openid * * @author shanqi.wang * */ public class GetUnsubscribeOpenidInterceptor extends HandlerInterceptorAdapter { private static final Logger logger = Logger .getLogger(GetUnsubscribeOpenidInterceptor.class); private List<String> excludeUrls; @Resource private WeixinAccountServiceI weixinAccountService; @Resource private CustomerBindService customerBindService; @Resource private IEventProcessingService eventProcessingService; public List<String> getExcludeUrls() { return excludeUrls; } public void setExcludeUrls(List<String> excludeUrls) { this.excludeUrls = excludeUrls; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String openid = (String)request.getSession().getAttribute(Constants.SESSION_KEY_OPENID); String activedProfile = request.getSession().getServletContext().getInitParameter("spring.profiles.active"); if(StringUtil.isEmpty(openid)&&!"prod".equals(activedProfile)){ openid = request.getParameter("openid"); } String code = request.getParameter("code"); logger.info("code from request Parameter,code==>" + code); // 如果code不为空,且openid为空 if (!StringUtil.isEmpty(code) && StringUtil.isEmpty(openid)) { DataSourceContextHolder .setDataSourceType(DataSourceType.dataSource_jeecg); List<WeixinAccountEntity> weixinAccountEntityList = weixinAccountService .findValidWeixinAccounts(); WeixinAccountEntity weixinAccountEntity = weixinAccountEntityList .get(0); openid = WeixinUtil.getOpenId( weixinAccountEntity.getAccountappid(), weixinAccountEntity.getAccountappsecret(), code); logger.info("get openid from code,openid=>" + openid); } //开始下载未关注客户信息 logger.info("begin_download_customer_info_openid=>" + openid); List<WeixinAccountEntity> weixinAccountEntityList = weixinAccountService.findValidWeixinAccounts(); WeixinAccountEntity weixinAccountEntity = weixinAccountEntityList.get(0); String accessToken = weixinAccountService.getAccessToken( weixinAccountEntity); String requestUrl = WeixinUtil.get_customer_url.replace("ACCESS_TOKEN", accessToken).replace("OPENID",openid); JSONObject CustomerJSONObject = WeixinUtil.httpRequest(requestUrl, "GET", null); logger.info("Unsubscribe_customer_info=>" + CustomerJSONObject.toString()); //WeiXinGzUserInfo weiXinGzUserInfo = (WeiXinGzUserInfo) JSONHelper.json2Object(CustomerJSONObject.toString(),WeiXinGzUserInfo.class); WeiXinGzUserInfo weiXinGzUserInfo = JsonUtil.parseObject(CustomerJSONObject.toString(), WeiXinGzUserInfo.class); java.util.Date date = new Date(); weiXinGzUserInfo.setAccount(weixinAccountEntity); weiXinGzUserInfo.setAddtime(date); try { eventProcessingService.customerSubscribe(weiXinGzUserInfo); } catch (Exception e) { logger.info("saveCustomerSubscribeError===openid====>" + weiXinGzUserInfo.getOpenid() + ".ErrorMessage:" + e.getMessage(),e); } return true; } }
TypeScript
UTF-8
2,905
2.65625
3
[]
no_license
import { Component } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { CardsService } from './app.CardsService'; import { Deck } from './deck.object'; import { Card } from './card.object'; import { stringify } from '@angular/core/src/util'; @Component({ template: ` <div *ngIf="cards"> <form name ="drawCards"> <div class="form-group"> <label for="name">Number of cards to draw</label> <input type="number" class="form-control" name="cardsToDraw" [(ngModel)]="cardsToDraw" required> </div> <button type="submit" class="btn btn-success" (click)="drawCard()">Submit</button> </form> <button type="submit" class="btn btn-success" (click)="loadDeck()">Reload Deck</button> <br> Remaining cards: {{this.cards.length}} <div *ngIf="resultString"> {{resultString}} </div> <div *ngFor=" let card of drawnCards" class="mdl-cell mdl-cell--4-col"> {{card.name}} </div> </div>`, providers: [CardsService] }) export class CardComponent { private cards: Card[]; private drawnCards: Card[] = []; private cardsLeft: number = 54; private resultString: string; private cardsToDraw: number = 0; private successes: number = 0; private failures: number = 0; private characterName: string = "Something"; constructor(private _cardService: CardsService) { } public drawCard(): void { this.resultString = ""; this.successes = 0; this.failures = 0; this.drawnCards = []; if (this.cardsToDraw < 1) { this.resultString = "Cannot draw less than one card, son!"; return; } else if (this.cardsToDraw > this.cards.length) { this.resultString = "You only have " + this.cards.length + " cards left!"; return; } for (var i = 0; i < this.cardsToDraw; i++) { var cardNumber = Math.floor(Math.random() * this.cardsLeft); var card = this.cards[cardNumber]; if (card) { this.drawnCards.push(card); this.cards.splice(cardNumber, 1); this.cardsLeft = this.cards.length; this.checkCard(card); } } this.resultString += "Sucesses: " + this.successes; this.resultString += " Failures: " + this.failures; this.resultString += " You drew:"; console.log(this.resultString) } public checkCard(card: Card): void { console.log(card.value); switch (card.value) { case 'JACK': case 'QUEEN': case 'KING': case 'ACE': this.successes++; console.log("Increasing Successes by 1!"); break; case 'JOKER': this.failures++; console.log("Increasing Failures by 1!"); break; } } public loadDeck(): void { this._cardService.getCards().subscribe( cards => this.cards = cards ); this.drawnCards = []; this.resultString = ""; } ngOnInit(): void { this.loadDeck(); } }
Python
UTF-8
1,478
2.515625
3
[]
no_license
import socket from threading import * serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "52.49.91.111" port = 2019 print (host) print (port) serversocket.bind((host, port)) class client(Thread): def __init__(self, socket, address): Thread.__init__(self) self.sock = socket self.addr = address self.start() def run(self): while 1: print('Client sent:', self.sock.recv(1024).decode()) self.sock.send(b''' SELECT STATES.user_id, MIN(STATES.date_time) session_from , MAX(STATES.date_time) session_to , -TIMESTAMPDIFF(second,MAX(STATES.date_time),MIN(STATES.date_time)) seconds , sum(DUPS.duplication) num_actions FROM ( select SUM( CASE WHEN (b.date_time<a.date_time and (b.action='open' or b.action='close')) or (b.date_time=a.date_time and b.action='open') THEN 1 ELSE 0 END ) State, a.user_id,a.action,a.date_time from activity a join activity b on a.user_id=b.user_id group by a.user_id,a.action,a.date_time ) STATES join (select user_id,date_time,action,count(*) duplication from activity group by user_id,date_time,action) DUPS on STATES.user_id = DUPS.user_id where STATES.date_time = DUPS.date_time and STATES.action = DUPS.action GROUP BY user_id,state order by user_id,session_from ''') serversocket.listen(5) print ('server started and listening') while 1: clientsocket, address = serversocket.accept() client(clientsocket, address)
Markdown
UTF-8
687
2.953125
3
[]
no_license
# SASS-Project ### Improved the efficiency of SCSS (Sassy CSS) compiled into CSS accomplishing the following steps: Incorporated variables; Utilized the power of mixins; Nested the mixins; Created functions; Improved the usage of Flexbox by creating a Flex container; Added conditionals to different media queries; Incorporated maps and used loops to iterate through the maps; ### Made 2 commits to the repository. First one is the initial code and the second one has all of my modifications. ### References The original version of the SCSS and CSS files come from the Treehouse's SASS course: https://teamtreehouse.com/library/sass-basics-2
JavaScript
UTF-8
1,134
3.078125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//the <GifListContainer /> will be responsible for fetching the data //from the giphy api, storing the first 3 gifs from the response in it's //component state, and passing that data down to it's child the <GifList> //component as a prop. //It will also render a <GifSearch /> component that renders the form. //<GifListContainer /> should pass down a submit handler function to <GifSearch /> //as a prop. import React, { Component } from 'react'; import GifList from '../components/GifList' import GifSearch from '../components/GifSearch' export default class GifListContainer extends Component { constructor(){ super(); this.state = { gifs: [] } } render() { return ( <div> <GifSearch fetchGifs={this.fetchGifs} /> <GifList gifs={this.state.gifs} /> </div> ) } fetchGifs = (query) => { try{ fetch(`http://api.giphy.com/v1/gifs/search?q=${query}&api_key=dc6zaTOxFJmzC&rating=g`) .then(res => res.json()) .then(data => { this.setState({ gifs: data.data.slice(0, 3) }) }) } catch(e){ console.error(e) } } }
C++
UTF-8
1,168
2.734375
3
[ "MIT" ]
permissive
#ifndef _Wire_h_ #define _Wire_h_ #include "Arduino.h" #include "driver/i2c.h" #include "Stream.h" class TwoWire: public Stream { private: i2c_port_t num; gpio_num_t sda = GPIO_NUM_MAX; gpio_num_t scl = GPIO_NUM_MAX; i2c_cmd_handle_t cmd = nullptr; bool init = false; uint8_t rxBuffer[128]; uint8_t rxIndex = 0; uint8_t rxCount = 0; public: TwoWire(int8_t num); ~TwoWire(); bool begin(); bool begin(int sda, int scl); void setClock(uint32_t); void end(void); // void onReceive(void (*)(int)); // void onRequest(void (*)(void)); void beginTransmission(int address, i2c_rw_t type = I2C_MASTER_WRITE); uint8_t endTransmission(bool sendStop = true); uint8_t requestFrom(int address, size_t size, bool sendStop = true); int available(void); int peek(void); int read(void); size_t write(uint8_t b); size_t write(const uint8_t* data, size_t size); size_t write(const char* str) { return write((uint8_t*)str, strlen(str)); } size_t write(int data) { return write((uint8_t)data); } using Print::write; }; extern TwoWire Wire; extern TwoWire Wire1; #endif
C#
UTF-8
889
3.4375
3
[]
no_license
using System; namespace LeetCode.Problems.Medium; /// 数组中的最长山脉 /// https://leetcode-cn.com/problems/longest-mountain-in-array/ public class P0845_LongestMountainInArray { public int LongestMountain(int[] A) { if (A.Length < 3) return 0; var ans = 0; var start = -1; var state = 0; for (var i = 0; i < A.Length - 1; i++) { var diff = A[i + 1] - A[i]; if (diff > 0) { if (state != 1) start = i; state = 1; } else if (diff < 0) { if (start != -1) ans = Math.Max(ans, i + 2 - start); state = -1; } else { state = 0; start = -1; } } if (ans < 3) return 0; return ans; } }
Java
UTF-8
15,873
1.898438
2
[]
no_license
//package com.example.avi.pecolx; // //import android.content.Intent; //import android.os.Bundle; //import android.os.Handler; //import android.support.design.widget.NavigationView; //import android.support.v4.view.GravityCompat; //import android.support.v4.widget.DrawerLayout; //import android.support.v7.app.ActionBarDrawerToggle; //import android.support.v7.app.AppCompatActivity; //import android.support.v7.widget.Toolbar; //import android.view.Menu; //import android.view.MenuItem; //import android.view.View; //import android.widget.ArrayAdapter; //import android.widget.Spinner; //import android.widget.Toast; // //public class sidebar extends AppCompatActivity // implements NavigationView.OnNavigationItemSelectedListener { // @Override // protected void onCreate(Bundle savedInstanceState) { // try { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_sidebar); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // String[] items = new String[]{"Categories", "CSE", "ECE", "Mech", "Civil", "Metallurgy", "Electrical", "Aero"}; // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items); // Spinner dropdown = (Spinner) findViewById(R.id.spinner); // dropdown.setAdapter(adapter); // // // DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); // ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( // this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); // drawer.setDrawerListener(toggle); // toggle.syncState(); // // NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); // navigationView.setNavigationItemSelectedListener(this); // Intent intent = getIntent(); // try { // SessionManager session_object = (SessionManager) intent.getSerializableExtra("KEY"); // session_object.tetsing="abc"; // } catch (Exception es) { // es.printStackTrace(); // } // } // catch (Exception e) // { // e.printStackTrace(); // } // // editor=getIntent().getExtras().get("editor"); // } //////////////////////////// //private boolean doubleBackToExitPressedOnce; // private Handler mHandler = new Handler(); // // private final Runnable mRunnable = new Runnable() { // @Override // public void run() { // doubleBackToExitPressedOnce = false; // } // }; // // @Override // protected void onDestroy() // { // super.onDestroy(); // // if (mHandler != null) { mHandler.removeCallbacks(mRunnable); } // } // @Override // public void onBackPressed() { // DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); // if (drawer.isDrawerOpen(GravityCompat.START)) { // drawer.closeDrawer(GravityCompat.START); // } // else if (doubleBackToExitPressedOnce) { // super.onBackPressed(); // return; // } // // this.doubleBackToExitPressedOnce = true; // Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show(); // // mHandler.postDelayed(mRunnable, 2000); // // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.sidebar, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // Handle action bar item clicks here. The action bar will // // automatically handle clicks on the Home/Up button, so long // // as you specify a parent activity in AndroidManifest.xml. // int id = item.getItemId(); // // //noinspection SimplifiableIfStatement // if (id == R.id.action_logout) { // return true; // } // // return super.onOptionsItemSelected(item); // } // // @SuppressWarnings("StatementWithEmptyBody") // @Override // public boolean onNavigationItemSelected(MenuItem item) { // // Handle navigation view item clicks here. // int id = item.getItemId(); // // if (id == R.id.nav_camera) { // // Handle the camera action // } else if (id == R.id.nav_gallery) { // // } else if (id == R.id.nav_slideshow) { // // } else if (id == R.id.nav_manage) { // // } else if (id == R.id.nav_share) { // // } else if (id == R.id.nav_send) { // // } // // DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); // drawer.closeDrawer(GravityCompat.START); // return true; // } // // public void postad123(View view) // { // Intent i=new Intent(this,post_ad.class); // startActivity(i); // // // } // // // /** // * Clear session details // * */ // public void logoutUser(View view){ // // Clearing all data from Shared Preferences // try { //// session_object.editor.clear(); //// session_object.editor.commit(); // // // After logout redirect user to Loing Activity // Intent i = new Intent(this, login.class); // // Closing all the Activities // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // // // Add new Flag to start new Activity // i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // // // Staring Login Activity // startActivity(i); // } // catch (Exception e) // { // e.printStackTrace(); // } // } // // // // // //} package com.example.avi.pecolx; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class sidebar extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { String PhoneNumber; String uid; String trending_books_data; public SessionManager session; String my_profile_jason; public String getjasonString() { return trending_books_data; } public String getMyProfiledata(){ return my_profile_jason; } public String getuid(){ return uid; } @Override protected void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sidebar); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); session=new SessionManager(getApplicationContext()); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); //Intent intent = getIntent();I uid=getIntent().getExtras().getString("uid"); trending_books_data=getIntent().getExtras().getString("trending_books_data"); FragmentManager fm= getFragmentManager(); FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.add(R.id.FrameLayout, new Begin_main_fragment(), "Main_window"); fragmentTransaction.commit(); // try { // SessionManager session_object = (SessionManager) intent.getSerializableExtra("KEY"); // session_object.tetsing="abc"; // } catch (Exception es) { // es.printStackTrace(); // } } catch (Exception e) { e.printStackTrace(); } } private boolean doubleBackToExitPressedOnce; private Handler mHandler = new Handler(); private final Runnable mRunnable = new Runnable() { @Override public void run() { doubleBackToExitPressedOnce = false; } }; @Override protected void onDestroy() { super.onDestroy(); if (mHandler != null) { mHandler.removeCallbacks(mRunnable); } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else if(getFragmentManager().getBackStackEntryCount() == 0) { super.onBackPressed(); } else { FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.FrameLayout, new Begin_main_fragment(), "Main_window"); fragmentTransaction.commit(); } // this.doubleBackToExitPressedOnce = true; // Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show(); // mHandler.postDelayed(mRunnable, 2000); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.sidebar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_logout) { session.logoutUser(); finish(); return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.my_profile) { RequestPackage requestPackage = new RequestPackage(); requestPackage.setMethod("GET"); requestPackage.setParam("uid", uid); Log.d("post", uid); requestPackage.setUri("http://192.168.43.66/pecolx/my_profile.php"); SignupTask signupTask = new SignupTask("my_profile"); signupTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, requestPackage); FragmentTransaction fragmentTransaction= getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.FrameLayout, new Begin_main_fragment(), "Main_window"); fragmentTransaction.addToBackStack("MainWindow"); fragmentTransaction.replace(R.id.FrameLayout, new MyProfileFragment(), "MyProfile"); fragmentTransaction.commit(); } else if (id == R.id.my_posts) { try { // String uid = getIntent().getExtras().getString("uid"); RequestPackage requestPackage = new RequestPackage(); requestPackage.setMethod("GET"); requestPackage.setParam("ui" + "d", uid); Log.d("post",uid); requestPackage.setUri("http://192.168.43.66/pecolx/my_ads.php"); SignupTask signupTask = new SignupTask("myads"); signupTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, requestPackage); } catch(NullPointerException e) { e.printStackTrace(); } } else if (id == R.id.sell_books) { FragmentTransaction fragmentTransaction= getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.FrameLayout, new Begin_main_fragment(), "Main_window"); fragmentTransaction.addToBackStack("MainWindow"); fragmentTransaction.replace(R.id.FrameLayout,new PostAddFragment(),"Post"); fragmentTransaction.commit(); } else if (id == R.id.nav_log_out) { session.logoutUser(); finish(); } else if (id == R.id.nav_share) { } //else if (id == R.id.nav_send) { //} else if(id==R.id.aboutpecolx) { FragmentTransaction fragmentTransaction= getFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.FrameLayout, new Begin_main_fragment(), "Main_window"); fragmentTransaction.addToBackStack("MainWindow"); fragmentTransaction.replace(R.id.FrameLayout,new about_us_fragment(),"Post"); fragmentTransaction.commit(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } // public void postad123(View view) // { // FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction(); // fragmentTransaction.replace(R.id.FrameLayout,new PostAddFragment(),"PostAd"); // fragmentTransaction.commit(); // // } /** * Clear session details * */ public void logoutUser(View view){ // Clearing all data from Shared Preferences try { // session_object.editor.clear(); // session_object.editor.commit(); // After logout redirect user to Loing Activity Intent i = new Intent(this, login.class); // Closing all the Activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Add new Flag to start new Activity i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Staring Login Activity startActivity(i); } catch (Exception e) { e.printStackTrace(); } } public class SignupTask extends AsyncTask<RequestPackage,Integer, Void> { Integer x; String content,json_string; String check_butoon; SignupTask() {} SignupTask(String position) { check_butoon=position; } @Override protected Void doInBackground(RequestPackage... params) { //System.out.println("thread"); content = HttpManager.getData(params[0]); //System.out.println(content); // Toast.makeText(login.this, "registration successful", Toast.LENGTH_SHORT).show(); Log.d("con", content); json_string = content; return null; } @Override protected void onPostExecute(Void aVoid) { if(check_butoon.equals("myads")) { Intent i = new Intent(getApplicationContext(), display_listview.class); i.putExtra("books_data", json_string); startActivity(i); } else if(check_butoon.equals("my_profile")) { my_profile_jason=content; } } } }
Java
UTF-8
2,629
1.953125
2
[]
no_license
package com.ctrip.train.kefu.system.job.worker.domain; public class StaffPriority { private String staffName; private String staffNum; private int envenType; private int noticeProductLine; private String noticeTypes; private int noticeWaitLimit; private long complainWaitLimit; private double staffNoticeBusy; private long solveAbility; private double staffComplainBusy; private long noticeWait; private long complainWait; public String getStaffName() { return staffName; } public void setStaffName(String staffName) { this.staffName = staffName; } public String getStaffNum() { return staffNum; } public void setStaffNum(String staffNum) { this.staffNum = staffNum; } public int getEnvenType() { return envenType; } public void setEnvenType(int envenType) { this.envenType = envenType; } public int getNoticeProductLine() { return noticeProductLine; } public void setNoticeProductLine(int noticeProductLine) { this.noticeProductLine = noticeProductLine; } public String getNoticeTypes() { return noticeTypes; } public void setNoticeTypes(String noticeTypes) { this.noticeTypes = noticeTypes; } public int getNoticeWaitLimit() { return noticeWaitLimit; } public void setNoticeWaitLimit(int noticeWaitLimit) { this.noticeWaitLimit = noticeWaitLimit; } public long getComplainWaitLimit() { return complainWaitLimit; } public void setComplainWaitLimit(long complainWaitLimit) { this.complainWaitLimit = complainWaitLimit; } public double getStaffNoticeBusy() { return staffNoticeBusy; } public void setStaffNoticeBusy(double staffNoticeBusy) { this.staffNoticeBusy = staffNoticeBusy; } public long getSolveAbility() { return solveAbility; } public void setSolveAbility(long solveAbility) { this.solveAbility = solveAbility; } public double getStaffComplainBusy() { return staffComplainBusy; } public void setStaffComplainBusy(double staffComplainBusy) { this.staffComplainBusy = staffComplainBusy; } public long getNoticeWait() { return noticeWait; } public void setNoticeWait(long noticeWait) { this.noticeWait = noticeWait; } public long getComplainWait() { return complainWait; } public void setComplainWait(long complainWait) { this.complainWait = complainWait; } }
Markdown
UTF-8
7,844
2.734375
3
[]
no_license
--- title: '2017年经历的那些灵异事件' date: 2018-12-22 2:30:11 hidden: true slug: muh28ezjeur categories: [reprint] --- {{< raw >}} <p>2017年快要过去了,回顾这一年来,在业务代码里,开发新功能占据70%,修复BUG占了30%,在解决的这些BUG中,大部分都是代码级别的错误,使用 <code>Chrome Devtools</code> 基本都可以解决,但其中有三个比较神奇,算得上是灵异事件了。</p> <h3 id="articleHeader0">鬼打墙</h3> <p>有一次后端同学重构了一下 <code>DSP</code> 广告平台的接口,让 <code>Java</code> 服务化提供接口, <code>PHP</code> 做 <code>web</code> 控制层掌管路由和透传接口,于是对之前的接口URL重新规划统一了一下,内测没问题后就高高兴兴上线了,然而没过多久就有商家上报说页面报错没数据,于是我赶紧复现,但怎么都复现不出来,然后问商家浏览器是不是版本太低,网络是不是不稳定之类的,但商家的浏览器和网络环境都没问题,这就纳闷了,于是果断找了一台 <code>Windows</code> 机器(因为我们都是Mac而且没装虚拟机),让商家加 <code>QQ</code> 远程协助看一下到底报了什么错,倒腾了半天,连上商家电脑,复现果然报错了 <code>NetWork Error</code> ,打开 <code>Chrome Devtools</code> 一查, <code>ajax</code> 请求居然没没发出去。看了一眼浏览器上那一排插件,怀疑是不是插件搞的鬼,发现居然有屏蔽广告的插件,大哥,你特么自己都在我们平台上投广告,你还装屏蔽广告插件。果断让他关闭这个插件,然后果然没问题。原来我们的接口URL里有 <code>advertisement</code> 这个单词,插件直接屏蔽了这个URL。没过多久,又有一个商家报页面没数据,呵呵,我们直接叫他关闭浏览器屏蔽广告插件,结果商家告诉我还是不行。?,还是远程协助查一下,发现开了隐身窗口,接口还是没返回数据,看到商家电脑右下角运行的系统杀毒软件,眉头一皱,难道是这货搞的鬼?打开设置一看,赫然有屏蔽广告这个选项。果然国产软件都流氓,你这所有的浏览记录都被人家知道了啊。第二天果断把 <code>advertisement</code> 改成<code>gg(guanggao)</code>,整个世界都清净了。</p> <h3 id="articleHeader1">断头鬼</h3> <p>过了一段时间,我司搭了一个前端错误监控平台,可以收集客户端错误,上报到这个平台然后邮件告警开发者。收集的信息包括用户操作系统、浏览器版本、 <code>IP</code> 、操作路径等,这样就不需要再用 <code>Windows</code> 远程了。某一天,告警平台发邮件报错,店铺选择页面 <code>js</code> 运行报错,那还得了,选择不了店铺,相当于我们的后台入口挂了啊。果断按照报错的操作路径操作一次,又没复现。再一看操作系统与浏览器版本,找了一个一模一样的环境,还是复现不出来。晕了,还是用远程协助吧。商家那里确实有 <code>js</code> 运行报错,由于线上 <code>js</code> 也没有 <code>source map</code> ,压缩的代码也看不懂,查半天也没查出什么东西。回到监控平台后台,反复比对各条报错。结果发现 <code>IP</code> 都是差不多的范围,一查都是合肥电信的运营商,难道所有合肥电信的用户加载的这个 <code>js</code> 有问题?然后报给运维同学,他把那个 <code>js</code> 下载下来一看,长度不一样,和正常的版本比,少了一小段。肯定是 <code>cdn</code> 同步的时候,出了故障,果断把锅丢给七牛。</p> <h3 id="articleHeader2">替死鬼</h3> <p>前几天,有一次发布后,一直收到邮件告警某个 <code>base</code> 的 <code>js</code> 运行报错,涉及的浏览器版本都是<code>Chrome 31到37</code>,轻车熟路开虚拟机复现,找半天找了一个<code>Chrome 31</code>,确实报错了,然而报错内容看不懂。想着那天发布内容包括升级基础 <code>react</code> 组件,加了一个 <code>babel runtime</code> ,还有一些其他的改动,难道是这些问题引起的?<br>然后尝试想让虚拟机 <code>Chrome</code> 运行本地代码,于是在 <code>win</code> 里面装 <code>node</code> 、 <code>git</code> 、下载仓库、打包、把线上代码代理到本地。结果<code>node-modules</code>都装不上去。然后再试试装 <code>fiddler</code> 抓包软件,把打包后的代码放在 <code>win</code> 里面,抓取那几个 <code>js</code> ,替换成打包后的本地代码,然而还是看不懂,只知道是一个基础函数,可能是 <code>babel polyfill</code> 的问题,于是尝试把前端仓库那几天的改成一一 <code>revert</code> ,看看到底是哪个改动导致的问题。结果回退到发布之前都还是报错,这就尴尬了,至此我已经花了一天时间去排查这个问题,期间让几个同事一起排查也没发现问题本源。<br>最后想着把 <code>win</code> 的网络设置成 <code>Mac</code> 一样的网络,把 <code>win</code> 浏览器使用 <code>SwitchySharp</code> 设置成 <code>Mac</code> 的代理,这样就可以在 <code>win</code> 里面使用 <code>Mac</code> 的开发环境,(其实就是在 <code>Mac</code> 起一个 <code>node</code> 服务,监听一个端口,在这个服务里把所有的线上的前端资源( <code>js</code> , <code>css</code> )替换成本地代码,本地这个服务相当于一个网关服务器,还可以把网址指向不同环境的服务器。)结果惊奇的发现在预发环境是没有问题的,只有线上环境才有报错。我的第一反应是难道后端改造了什么数据类型?把线上数据和预发环境数据比对一下,然而一模一样。这个时候,对比两个环境只有两个差异了,一个线上环境多一个统计日志上报的 <code>js</code> ,还有一个就是错误收集上报的 <code>js</code> ,问了一下这两个 <code>js</code> 的维护者,果然统计日志的js,在那次发布的时候改动了,为了使用<code>Object.assign</code>,加了一个 <code>polyfill</code> ,然后和 <code>base js</code> 里面的 <code>polyfill</code> 冲突了,由于统计日志的 <code>js</code> 先加载,所以报错是在 <code>base js</code> 里面。<br>这个问题比较难排查的地方是:</p> <ol> <li>复现环境比较苛刻</li> <li>后端仓库的改动(统计日志的 <code>js</code> )和前端仓库产生了关联,版本回退难以排查</li> <li>产生问题的 <code>js</code> 并不是出现报错的 <code>js</code> </li> </ol> <h3 id="articleHeader3">总结</h3> <p>出现BUG在所难免,代码逻辑、浏览器兼容性、网络故障等等都会导致一些意想不到的问题,遇到问题首先不要慌,解决问题要有方法论,先把问题复现出来,然后使用 <code>Chrome Devtools</code> ,设置断点,观察数据条件,基本可以找出代码错误,其他问题,可以类似高中生物实验,结合条件对照,找出差异的条件,定位到问题,这个过程中需要敏锐的观察力。</p> {{< /raw >}} # 版权声明 本文资源来源互联网,仅供学习研究使用,版权归该资源的合法拥有者所有, 本文仅用于学习、研究和交流目的。转载请注明出处、完整链接以及原作者。 原作者若认为本站侵犯了您的版权,请联系我们,我们会立即删除! ## 原文标题 2017年经历的那些灵异事件 ## 原文链接 [https://segmentfault.com/a/1190000012387287](https://segmentfault.com/a/1190000012387287)
Python
UTF-8
791
2.515625
3
[]
no_license
import urllib2 import re class CheckUpdate(): def __init__(self, target_url): self.url = target_url def get_htmlContent(self): try: html_Context = urllib2.urlopen(self.url).read() return unicode(html_Context, 'utf-8') except IOError: print 'Failed to open xml file, please check it' exit(1) def return_checks(self): html_Context = get_htmlContent() return re.findall(r"href=(.+).iso\">", html_Context) class CheckId(CheckUpdate): def return_checks(self): html_Context = self.get_htmlContent() return re.findall(r"<testid>(.+)</testid>", html_Context)[0] # test=Check_id("http://192.168.32.18/Lsts-i/stability.xml") # isoname=test.return_checks() # print isoname
Markdown
UTF-8
1,562
2.53125
3
[]
no_license
# Chapter 2: Battle in the King's Army or explore the caves unaided Upon arriving at the castle entrance you find yourself in awe of the many colours and scents you could never dream of experiencing in Villa Pisci. Usually the castle entrance would be booming with peddlers trying to sell their wares to novice adventurers, or children playing in the streets chasing each other while mimicking their heroes from some historic battle. However, today was no such day. It is hard for the castle entrance to keep its usual level of cheer when the gates are suddenly flooded by refugees. After some pushing and shoving you are able to get to one of the guards, telling him you must have an audience with the king. A large, pig-faced man steps forward holding his hand up high, catching the crowds attention and silencing you. He begins eyeing the crowd up and down and with a satisfied grunt he begins speaking. "Fear not weary souls, for you are safe behind these walls. King Roidür is a good and charitable liege, and he will come make sure you are cared for, for you are his people!". His speech seems to rally some of the wearier refugees and with a content grin he signals for some of his subordinates to begin picking out those fit enough for being drafted into the King's army. He then grabs you buy the shoulder and nods towards the castle. “You seem strong, young man. Go to the palace and tell your tale to the king. I am sure he will want to hear it.” His inspiring voice seems to give you some strength and you swiftly make your way to the castle.
C#
UTF-8
1,387
3.265625
3
[]
no_license
using System; namespace Indexers { class Dictionary { const int size = 5; private string[] ENG = new string[size]; private string[] RU = new string[size]; private string[] UA = new string[size]; public Dictionary() { RU[0] = "книга"; UA[0] = "книга"; ENG[0] = "book"; RU[1] = "ручка"; UA[1] = "ручка"; ENG[1] = "pen"; RU[2] = "солнце"; UA[2] = "сонце"; ENG[2] = "sun"; RU[3] = "яблоко"; UA[3] = "яблуко"; ENG[3] = "apple"; RU[4] = "стол"; UA[4] = "стіл"; ENG[4] = "table"; } public string this[string index] { get { for (int i = 0; i < RU.Length; i++) if ((RU[i] == index) || (UA[i] == index) || (ENG[i] == index)) return string.Format($"{RU[i]} - {UA[i]} - {ENG[i]}"); return string.Format($"{index} - нет перевода для этого слова."); } } public string this[int index] { get { return (index >= 0 && index < RU.Length) ? string.Format($"{RU[index]} - {UA[index]} - {ENG[index]}") : "Попытка обращения за пределы массива."; } } } }
Markdown
UTF-8
1,513
2.84375
3
[]
no_license
# Remote Esto se refiere a repositorios remotos como Github, con remote podemos acceder a distintos repositorios no hay limite - git remote - Muestra que remotos tenemos - git remote -v - Muestra la URL de los remote ## Añadir remotos - git remote add <nombre_repositorio> <URL> - Ya con añadir el remoto, al subir o enviar los cambios al repositorio remote lo hacemos con su nombre - Para subir los archivos se usa git pull <nombre_remote> <nombre_rama> - git fech <nombre_remote> > La diferencia entre estos dos es que fetch trae los archivos pero los guarda en otra rama la cual no es main (git branch -a) y debemos hacer un merge para añadirlo a la rama que deseemos y pull es un shortcut ya que en donde lo ejecutemos traera los archivos y el merge ## Enviar remote - git push origin main - Este comando envia modificaciones o archivos nuevos al repositorio remoto, cabe mencionar que se enviaran si tienes permisos de escritura de lo contrario se debe realizar un fork ## Inspeccionar un remoto - git remote show <nombre_remoto> - Muestra informacion del remoto sobre la URL, la rama donde se estan guardando los archivos y al final si se esta enviando o no los archivos remotos ## Renombrar y eliminar remotos - git remote rename <nombre_actual> <nuevo_nombre> - Al renombrar un remoto tambien renombramos la ramas remotas - git remote -rm - Se usa cuando ya no queremos utilizarlo, cambiamos de repositorio remoto o algun colaborardor ya no trabajar en el proyecto
Java
UTF-8
1,764
3.125
3
[]
no_license
package test; /** * 2020-06-22 11:21 */ public class NewTest { public static void main(String[] args){ System.out.println(Integer.toBinaryString(128)); System.out.println(128 << 1); System.out.println(Integer.toBinaryString(128 << 1)); System.out.println(Integer.toBinaryString(127)); System.out.println(Integer.toBinaryString(126)); Thread t1 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 3; i++){ try { if(i == 0){ System.out.println("t1 is ready"); }else{ System.out.println("t1 is sleep"); } Thread.sleep(3000); }catch (Exception e){ e.printStackTrace(); } } System.out.println("t1 is over"); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 3; i++){ try { if(i == 0){ System.out.println("t2 is ready"); t1.join(); }else{ System.out.println("t2 is sleep"); } Thread.sleep(3000); }catch (Exception e){ e.printStackTrace(); } } System.out.println("t2 is over"); } }); t1.start(); t2.start(); } }
Markdown
UTF-8
2,217
2.859375
3
[ "MIT" ]
permissive
# be-pretty ![fabolous](https://media.giphy.com/media/XmiTYLQ5qXTqM/giphy.gif) :lipstick: adds prettier to an existing project with all bells and whistles-including husky and pretty-quick. Have you ever been bothered by all the steps you need to do in a legacy codebase to get prettier all set up? Well now you don't have to. ## Install ``` npm i be-pretty -g ``` Requires that you have npm/yarn and `npx` globally available. be pretty defaults to running npm, but if there is `yarn.lock` file it will use `yarn`. ## Usage When you are in an old codebase which needs to be pretty now, and stay pretty forever and ever execute `be-pretty`. An output looks like this: ``` be-pretty ✔ Installing prettier husky pretty-quick ✔ Copying custom .prettierrc ✔ Adding pretty-quick pre-commit to package.json ✔ Formatting whole repo ``` Now you should have everything ready to just commit&push. You may skip formatting step with a flag `--skipFormatting` ## Customize .prettierrc by default, be-pretty creates this prettier config. ```js { "arrowParens": "always", // good for typescript/flow when you want to type your function arguments "singleQuote": true // IMHO better readability } ``` if you want to customize this, just run `be-pretty setDefault -p="/path/to/your/defaultPrettierRc"`. You can omit the path and if there is a prettierc file in the current working directory it will be used. be-pretty will use this as default from now on. ## Format all if you just want to reformat everything, you can call `be-pretty formatAll` ## All Commands ``` be-pretty setDefault sets a .prettierrc file as your default, if ommited will look for the .prettierrc file in CWD[aliases: d] be-pretty formatAll formats everything excluding node_modules[aliases: f] be-pretty run run the series of commands to make a codebase pretty [default] ``` ## FAQ ### Will this work for a newly added languages as well? Yes, the list of supported file extensions is not hardcoded anywhere-format all just invokes prettier in the current folder and let's it format all supported extensions.
Java
UTF-8
359
1.976563
2
[ "MIT" ]
permissive
package org.jmisb.st0808; import org.jmisb.api.klv.IKlvValue; /** * ST 0808 metadata value. * * <p>All ST 0808 Ancillary Text Local Set values implement this interface. */ public interface IAncillaryTextMetadataValue extends IKlvValue { /** * Get the encoded bytes. * * @return The encoded byte array */ byte[] getBytes(); }
Python
UTF-8
886
2.671875
3
[]
no_license
def main(): n,m=map(int,input().split()) h=list(map(int,input().split())) w=list(map(int,input().split())) h.sort() h.append(h[n-1]) w.sort() dim_h=[0 for i in range(n)] for i in range(1,n): dim_h[i]=h[i]-h[i-1] # print(dim_h) index=0 ansLeft=0 ansRight=sum([dim_h[i] if i%2==0 else 0 for i in range(n)]) ans=[] for wi in w: while index<n and wi>h[index]: if index%2==1: ansLeft+=dim_h[index] ansRight-=dim_h[index+1] index+=1 # print(h[:index]+[wi]+h[index:]) # print(index,ansLeft,abs(h[index]-wi),ansRight) if index%2==1: ans.append(ansLeft+abs(h[index-1]-wi)+ansRight) else: ans.append(ansLeft+abs(h[index]-wi)+ansRight) return min(ans) if __name__=='__main__': ans=main() print(ans)
C#
UTF-8
5,387
2.84375
3
[]
no_license
using System; using ExpensesSplitter.WebApi.Algorithms; using ExpensesSplitter.WebApi.Models; using Xunit; namespace ExpensesSplitter.WebApi.Tests.Algorithms { public class SettlementSolverTests { [Fact] public void Solve_SimpleScenario() { var balances = new[] { CreateUserBalance("A", 100), CreateUserBalance("B", 90), CreateUserBalance("C", -50), CreateUserBalance("D", -50), CreateUserBalance("E", -90), }; var solver = new SettlementSolver(balances); var result = solver.Solve(); Assert.Equal(3, result.Count); Assert.Contains(result, t => IsTransaction(t, "C", "A", 50)); Assert.Contains(result, t => IsTransaction(t, "D", "A", 50)); Assert.Contains(result, t => IsTransaction(t, "E", "B", 90)); } [Fact] public void Solve_QuiteComplexScenario() { var balances = new[] { CreateUserBalance("A", 100), CreateUserBalance("B", 91), CreateUserBalance("C", -10), CreateUserBalance("D", -11), CreateUserBalance("E", -40), CreateUserBalance("F", -40), CreateUserBalance("G", -90), }; var solver = new SettlementSolver(balances); var result = solver.Solve(); Assert.Equal(6, result.Count); Assert.Contains(result, t => IsTransaction(t, "G", "B", 90)); Assert.Contains(result, t => IsTransaction(t, "F", "A", 40)); Assert.Contains(result, t => IsTransaction(t, "E", "A", 40)); Assert.Contains(result, t => IsTransaction(t, "D", "A", 11)); Assert.Contains(result, t => IsTransaction(t, "C", "A", 9)); Assert.Contains(result, t => IsTransaction(t, "C", "B", 1)); } [Fact] public void Solve_OnePersonReturnsMoneyToEverybodyElse() { var balances = new[] { CreateUserBalance("A", 1), CreateUserBalance("B", 2), CreateUserBalance("C", 3), CreateUserBalance("D", 4), CreateUserBalance("E", -10), }; var solver = new SettlementSolver(balances); var result = solver.Solve(); Assert.Equal(4, result.Count); Assert.Contains(result, t => IsTransaction(t, "E", "A", 1)); Assert.Contains(result, t => IsTransaction(t, "E", "B", 2)); Assert.Contains(result, t => IsTransaction(t, "E", "C", 3)); Assert.Contains(result, t => IsTransaction(t, "E", "D", 4)); } [Fact] public void Solve_WhenBalancesAreZero_ReturnsEmptyList() { var balances = new[] { CreateUserBalance("A", 0), CreateUserBalance("B", 0), CreateUserBalance("C", 0), CreateUserBalance("D", 0), CreateUserBalance("E", 0), }; var solver = new SettlementSolver(balances); var result = solver.Solve(); Assert.Empty(result); } [Fact] public void Solve_EverybodyReturnsMoneyToOnePerson() { var balances = new[] { CreateUserBalance("A", -1), CreateUserBalance("B", -2), CreateUserBalance("C", -3), CreateUserBalance("D", -4), CreateUserBalance("E", 10), }; var solver = new SettlementSolver(balances); var result = solver.Solve(); Assert.Equal(4, result.Count); Assert.Contains(result, t => IsTransaction(t, "A", "E", 1)); Assert.Contains(result, t => IsTransaction(t, "B", "E", 2)); Assert.Contains(result, t => IsTransaction(t, "C", "E", 3)); Assert.Contains(result, t => IsTransaction(t, "D", "E", 4)); } [Fact] public void Solve_WhenSumOfBalancesIsNotZero() { var balances = new[] { CreateUserBalance("A", 6.67M), CreateUserBalance("B", -3.33M), CreateUserBalance("C", -3.33M), }; var solver = new SettlementSolver(balances); var result = solver.Solve(); Assert.Equal(2, result.Count); Assert.Contains(result, t => IsTransaction(t, "B", "A", 3.33M)); Assert.Contains(result, t => IsTransaction(t, "C", "A", 3.33M)); } bool IsTransaction(SolutionTransaction t, string from, string to, decimal amount) { return t.From.DisplayName == from && t.To.DisplayName == to && t.Amount == amount; } UserBalance CreateUserBalance(string name, decimal balance) { return new UserBalance { User = new SettlementUser { DisplayName = name, Id = Guid.NewGuid() }, Balance = balance }; } } }
Java
UTF-8
9,831
2.15625
2
[ "MIT" ]
permissive
package com.knowyourknot.enderporter; import net.minecraft.advancement.criterion.Criteria; import net.minecraft.block.Block; import net.minecraft.block.Blocks; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUsageContext; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.packet.s2c.play.DifficultyS2CPacket; import net.minecraft.network.packet.s2c.play.EntityStatusEffectS2CPacket; import net.minecraft.network.packet.s2c.play.PlayerAbilitiesS2CPacket; import net.minecraft.network.packet.s2c.play.PlayerRespawnS2CPacket; import net.minecraft.network.packet.s2c.play.WorldEventS2CPacket; import net.minecraft.server.PlayerManager; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.Identifier; import net.minecraft.util.InvalidIdentifierException; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.math.Vec3d; import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.RegistryKey; import net.minecraft.world.World; import net.minecraft.world.WorldProperties; import net.minecraft.world.biome.source.BiomeAccess; public class DimPos { private static final String DIMENSION_NAMESPACE = "dimensionNamespace"; private static final String DIMENSION_PATH = "dimensionPath"; private static final String POS_X = "posX"; private static final String POS_Y = "posY"; private static final String POS_Z = "posZ"; private final Identifier identifier; private final BlockPos pos; public DimPos(Identifier identifier, BlockPos pos) { this.identifier = identifier; this.pos = pos; } public boolean isInDimension(Identifier dimensionId) { return (this.getIdentifier().equals(dimensionId)); } public float distanceTo(BlockPos target) { Vec3d startPos = new Vec3d(pos.getX(), pos.getY(), pos.getZ()); Vec3d targetPos = new Vec3d(target.getX(), target.getY(), target.getZ()); return (float) startPos.distanceTo(targetPos); } public String toString() { return identifier.toString() + ", " + pos.toString(); } public static DimPos getContextDimPos(ItemUsageContext context) { World world = context.getWorld(); Identifier newIdentifier = world.getRegistryKey().getValue(); BlockPos newPos = context.getBlockPos(); Direction side = context.getSide(); // the offset when setting the location to the underside of a block isn't quite right // there is no way to fix this without getting the size of the entity making the dimpos // and I want the dimpos to be independent of the entity. return new DimPos(newIdentifier, newPos.add(side.getOffsetX(), side.getOffsetY(), side.getOffsetZ())); } public static DimPos getStackDimPos(ItemStack stack) { if (stack.hasTag()) { CompoundTag data = stack.getTag(); return DimPos.getNbtDimPos(data); } else { return null; } } public static DimPos getNbtDimPos(CompoundTag data) { if (data.contains(DIMENSION_NAMESPACE) && data.contains(DIMENSION_PATH) && data.contains(POS_X) && data.contains(POS_Y) && data.contains(POS_Z)) { String namespace = data.getString(DIMENSION_NAMESPACE); String path = data.getString(DIMENSION_PATH); Identifier newIdentifier; try { newIdentifier = new Identifier(namespace, path); } catch (InvalidIdentifierException e) { return null; } BlockPos newPos = new BlockPos(data.getFloat(POS_X), data.getFloat(POS_Y), data.getFloat(POS_Z)); return new DimPos(newIdentifier, newPos); } else { return null; } } public void setNbtDimensionLocation(CompoundTag data) { data.putString(DIMENSION_NAMESPACE, this.getNamespace()); data.putString(DIMENSION_PATH, this.getPath()); data.putFloat(POS_X, this.pos.getX()); data.putFloat(POS_Y, this.pos.getY()); data.putFloat(POS_Z, this.pos.getZ()); } public static DimPos setContextDimensionLocation(ItemUsageContext context) { PlayerEntity playerEntity = context.getPlayer(); if (playerEntity.isSneaking()) { DimPos dimLoc = getContextDimPos(context); ItemStack stack = context.getStack(); CompoundTag data; if (stack.hasTag()) { data = stack.getTag(); } else { data = new CompoundTag(); } dimLoc.setNbtDimensionLocation(data); stack.setTag(data); return dimLoc; } return null; } public String getNamespace() { return this.identifier.getNamespace(); } public String getPath() { return this.identifier.getPath(); } public BlockPos getPos() { return pos.mutableCopy(); } public Identifier getIdentifier() { return identifier; } public boolean canFitEntity(ServerWorld world, ServerPlayerEntity player) { RegistryKey<World> registryKey = RegistryKey.of(Registry.DIMENSION, this.identifier); ServerWorld destination = world.getServer().getWorld(registryKey); // decide which blocks to check float width = player.getWidth(); float height = player.getHeight(); int radius = ((int) Math.ceil(width))/2; // next odd integer + 1 / 2 int diameter = radius * 2 + 1; int intHeight = (int) Math.ceil(height); // check blocks empty BlockPos initialPos = new BlockPos(this.pos).add(-radius, 0, -radius); for (int y = 0; y < intHeight; y++) { for (int x = 0; x < diameter; x++) { for (int z = 0; z < diameter; z++) { BlockPos posToCheck = initialPos.add(x, y, z); Block blockAtPos = destination.getBlockState(posToCheck).getBlock(); if (blockAtPos != Blocks.AIR && blockAtPos != Blocks.CAVE_AIR && blockAtPos != Blocks.VOID_AIR) { return false; } } } } return true; } public ServerPlayerEntity moveEntity(World world, ServerPlayerEntity serverPlayerEntity) { RegistryKey<World> registryKey = RegistryKey.of(Registry.DIMENSION, this.getIdentifier()); ServerWorld destination = ((ServerWorld) world).getServer().getWorld(registryKey); ServerWorld currentWorld = (ServerWorld) serverPlayerEntity.world; if (currentWorld.getRegistryKey() != destination.getRegistryKey()) { this.moveToDimension(destination, serverPlayerEntity); } else { serverPlayerEntity.requestTeleport(this.pos.getX() + 0.5f, this.pos.getY(), this.pos.getZ() + 0.5f); } return serverPlayerEntity; } // from ServerPlayerEntity.moveToWorld, inspired by kryptonaut's custom portal API private ServerPlayerEntity moveToDimension(ServerWorld destination, ServerPlayerEntity player) { ServerWorld origin = player.getServerWorld(); WorldProperties worldProperties = destination.getLevelProperties(); player.networkHandler.sendPacket(new PlayerRespawnS2CPacket(destination.getDimension(), destination.getRegistryKey(), BiomeAccess.hashSeed(destination.getSeed()), player.interactionManager.getGameMode(), player.interactionManager.getPreviousGameMode(), destination.isDebugWorld(), destination.isFlat(), true)); player.networkHandler.sendPacket(new DifficultyS2CPacket(worldProperties.getDifficulty(), worldProperties.isDifficultyLocked())); PlayerManager playerManager = player.server.getPlayerManager(); playerManager.sendCommandTree(player); origin.removePlayer(player); player.removed = false; origin.getProfiler().pop(); origin.getProfiler().push("placing"); player.setWorld(destination); destination.onPlayerChangeDimension(player); player.refreshPositionAfterTeleport(this.pos.getX() + 0.5f, this.pos.getY(), this.pos.getZ() + 0.5f); origin.getProfiler().pop(); worldChanged(origin, player); player.interactionManager.setWorld(destination); player.networkHandler.sendPacket(new PlayerAbilitiesS2CPacket(player.abilities)); playerManager.sendWorldInfo(player, destination); playerManager.sendPlayerStatus(player); for (StatusEffectInstance statusEffectInstance : player.getStatusEffects()) { player.networkHandler.sendPacket(new EntityStatusEffectS2CPacket(player.getEntityId(), statusEffectInstance)); } player.networkHandler.sendPacket(new WorldEventS2CPacket(1032, BlockPos.ORIGIN, 0, false)); // moveToWorld then tells the game that health, hunger and xp are synced, but this doesn't appear to be necessary return player; } private static void worldChanged(ServerWorld origin, ServerPlayerEntity player) { RegistryKey<World> registryKey = origin.getRegistryKey(); RegistryKey<World> registryKey2 = player.world.getRegistryKey(); Criteria.CHANGED_DIMENSION.trigger(player, registryKey, registryKey2); } public boolean isInVoid(ServerWorld world) { RegistryKey<World> registryKey = RegistryKey.of(Registry.DIMENSION, this.identifier); ServerWorld destination = world.getServer().getWorld(registryKey); return (destination == null) || (destination.getBlockState(this.pos).getBlock() == Blocks.VOID_AIR); } }
PHP
UTF-8
4,320
3.203125
3
[ "BSD-3-Clause", "OFL-1.1", "MPL-1.1", "MIT", "LGPL-2.1-or-later", "GPL-2.0-or-later", "GPL-2.0-only", "LGPL-2.1-only", "GPL-3.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-other-copyleft", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php /** * Initialisation de mysqli * * * * Include this file after defining the following variables: * - $dbHost = The hostname of the database server * - $dbUser = The username to use when connecting to the database * - $dbPass = The database account password * - $dbDb = The database name. * - Including this file connects you to the database, or exits on error * */ // Etablir la connexion à la base //echo 'mysql:host='.$dbHost.';port=".$dbPort.";dbname='.$dbDb.'<br />'; if (isset($utiliser_pdo) AND $utiliser_pdo == 'on') { // On utilise le module pdo de php pour entrer en contact avec la base // $cnx = new PDO('mysql:host='.$dbHost.';dbname='.$dbDb, $dbUser, $dbPass); if(isset($dbPort)) { $cnx = new PDO('mysql:host='.$dbHost.';dbname='.$dbDb.';port='.$dbPort, $dbUser, $dbPass); } else { $cnx = new PDO('mysql:host='.$dbHost.';dbname='.$dbDb, $dbUser, $dbPass); } } if (!isset($db_nopersist) || $db_nopersist) { if(isset($dbPort)) { $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbDb, $dbPort); } else { $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbDb); } } else { if(isset($dbPort)) { $mysqli = new mysqli("p:".$dbHost, $dbUser, $dbPass, $dbDb, $dbPort); } else { $mysqli = new mysqli("p:".$dbHost, $dbUser, $dbPass, $dbDb); } } if ($mysqli->connect_errno) { printf("Echec lors de la connexion à MySQL : (" . mysqli_connect_errno() . ") " . mysqli_connect_error()); exit(); } /* Modification du jeu de résultats en utf8 */ if (!$mysqli->set_charset("utf8")) { printf("Erreur lors du chargement du jeu de caractères utf8 : %s\n", $mysqli->error); } // Fonctions GEPI /** * Execute an SQL query. * * Retourne FALSE en cas d'échec. * Pour des requêtes SELECT, SHOW, DESCRIBE ou EXPLAIN réussies, mysqli_query() * retournera un objet mysqli_result. * Pour les autres types de requêtes ayant réussies, mysqli_query() retournera TRUE. * * @param type $sql * @return type */ function sqli_query ($sql) { global $mysqli; $r = mysqli_query($mysqli, $sql); return $r; } /** * Execute an SQL query which should return a single non-negative number value. * * This is a lightweight alternative to sql_query, good for use with count(*) * and similar queries. It returns -1 on error or if the query did not return * exactly one value, so error checking is somewhat limited. * It also returns -1 if the query returns a single NULL value, such as from * a MIN or MAX aggregate function applied over no rows. * @param type $sql * @return type */ function sqli_query1 ($sql) { global $mysqli; $resultat = mysqli_query($mysqli, $sql); if (!$resultat) {return (-1);} if ($resultat->num_rows != 1) {return (-1);} if ($resultat->field_count != 1) {return (-1);} $ligne1 = $resultat->fetch_row(); $result = $ligne1[0]; if ($result == "") {return (-1);} $resultat->close(); return $result; } /** * Return a row from a result. The first row is 0. * The row is returned as an array with index 0=first column, etc. * When called with i >= number of rows in the result, cleans up from * the query and returns 0. * Typical usage: $i = 0; while ((a = sql_row($r, $i++))) { ... } */ function sqli_row ($r, $i) { if ($i >= $r->num_rows) { $r->free(); return 0; } $r->data_seek($i); return $r->fetch_row(); } /** * Retourne le nombre de lignes d'un objet mysqli. * @param type $r * @return type */ function sqli_count ($r) { return ($r->num_rows); } // Le mode strict de mysql 5.7 pose des problèmes avec certaine valeurs par défaut de certains champs (date à 0000-00-00 00:00:00 par exemple) // Le mode forcé par défaut dans Gepi permet de revenir au comportement mysql 5.6 // Voir http://dev.mysql.com/doc/refman/5.6/en/sql-mode.html et http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html // https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html , https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_only_full_group_by // Il est possible de définir un autre mode via une variable $set_mode_mysql à déclarer dans le secure/connect.inc.php if(!isset($set_mode_mysql)) { sqli_query("SET sql_mode ='NO_ENGINE_SUBSTITUTION'"); } else { sqli_query("SET sql_mode ='$set_mode_mysql'"); }
PHP
UTF-8
639
2.59375
3
[]
no_license
<?php require('db_connect.php'); $query_statement = "SELECT id,name,hidden FROM keywords ORDER BY hidden, name"; $query = mysql_query($query_statement, $db_conn); $response = ""; $already_hidden = 0; while ($row = mysql_fetch_row($query)){ if ($row[2] == '1' && $already_hidden == 0){ $response .= "<h3 style='color: #E20B3A'>Hidden Keywords</h3>"; } $response .= "<li keyword_id='" . $row[0] . "'>"; //$response .= "<img class='select-toggle' src='images/checkbox-". $row[2] . ".png' />"; if ($row[2] == '1'){ $already_hidden = 1; } $response .= $row[1]; $response .= "</li>"; } echo $response; ?>
C++
UTF-8
696
2.71875
3
[]
no_license
#include <cstdio> int main() { int queryNum; while (true) { int divPointX, divPointY; scanf("%d", &queryNum); if (queryNum == 0) break; scanf("%d%d", &divPointX, &divPointY); for (int i=0; i<queryNum; i++) { int x, y; scanf("%d%d", &x, &y); if (divPointX == x || divPointY == y) printf("divisa\n"); else if (x < divPointX && y > divPointY) printf("NO\n"); else if (x > divPointX && y > divPointY) printf("NE\n"); else if (x > divPointX && y < divPointY) printf("SE\n"); else if (x < divPointX && y < divPointY) printf("SO\n"); } } return 0; }
Swift
UTF-8
3,566
2.765625
3
[]
no_license
// // MapViewController.swift // CollegeBuilderApp // // Created by Samone on 7/27/16. // Copyright © 2016 Simon Stephanos. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var mapTextField: UITextField! var college = "" override func viewDidLoad() { super.viewDidLoad() mapTextField.text = college let geocoder = CLGeocoder() geocoder.geocodeAddressString(mapTextField.text!, completionHandler: { (placemarks, error) in if error != nil { print (error) } else { let placemark = placemarks!.first as CLPlacemark! let center = placemark.location!.coordinate let span = MKCoordinateSpanMake(0.1, 0.1) self.displayMap(center, span: span, pinTitle: self.mapTextField.text!) } }) mapTextField.resignFirstResponder() } func displayMap(center: CLLocationCoordinate2D, span: MKCoordinateSpan, pinTitle: String){ let region = MKCoordinateRegionMake(center, span) let pin = MKPointAnnotation() pin.coordinate = center pin.title = pinTitle mapView.addAnnotation(pin) mapView.setRegion(region, animated: true) } func textFieldShouldReturn(mapTextField: UITextField) -> Bool { let geocoder = CLGeocoder() geocoder.geocodeAddressString(mapTextField.text!, completionHandler: { (placemarks, error) in if error != nil { print (error) } else { if placemarks!.count > 1{ let actionController = UIAlertController(title: "Select an option", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) for i in 0..<placemarks!.count{ let locationSlot = UIAlertAction(title: "\(mapTextField.text!), \(placemarks![i].administrativeArea!)", style: .Default) { (action) in let placemark : CLPlacemark = placemarks![i] as CLPlacemark! let center = placemark.location!.coordinate let span = MKCoordinateSpanMake(0.1, 0.1) self.displayMap(center, span: span, pinTitle: mapTextField.text!) } actionController.addAction(locationSlot) } let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) actionController.addAction(cancelAction) self.presentViewController(actionController, animated: true, completion: nil) } else{ } let placemark : CLPlacemark = placemarks!.first as CLPlacemark! let center = placemark.location!.coordinate let span = MKCoordinateSpanMake(0.1, 0.1) self.displayMap(center, span: span, pinTitle: mapTextField.text!) } }) mapTextField.resignFirstResponder() return true } }
Python
UTF-8
3,141
2.96875
3
[ "MIT" ]
permissive
""" Represents the routes and controllers for authenthication By: Tom Orth """ from app.auth.model import User from app.auth.form import AuthForm from app.setup import conn from flask import Blueprint, render_template, request, current_app, redirect, url_for, flash from flask_login import login_user, logout_user import bcrypt # Sets up the Blueprint auth = Blueprint("auth", __name__, url_prefix="/auth") # Signup route for a user @auth.route("/signup", methods=["GET", "POST"]) def signup(): # Construct a form signup_form = AuthForm(request.form) # Handle a post request if request.method == "POST" and signup_form.validate_on_submit(): # Check if user exists _, content = conn.execute_and_return(f"SELECT * FROM users WHERE email=\'{signup_form.email.data}\'") # If it does not, we insert into the database, construct the User object and login the user if len(content) == 0: password_hash = bcrypt.hashpw(bytes(signup_form.password.data, "utf-8"), bcrypt.gensalt()).decode("utf-8") lflag = int(signup_form.lflag.data) _, col = conn.execute_and_return(f"INSERT INTO users(email, password_hash, lflag) VALUES (\'{signup_form.email.data}\', \'{password_hash}\', \'{lflag}\') RETURNING user_id") user = User(int(col[0][0]), signup_form.email.data, password_hash, lflag) login_user(user) return redirect(url_for("main")) # If it does exist, we flash a message to the user else: flash("User exists already") return redirect(url_for("auth.signup")) return render_template("auth/signup.html", title="Sign-up", form=signup_form) # Route to signin @auth.route('/signin', methods=["GET", "POST"]) def signin(): # Instantiate the form signin_form = AuthForm(request.form) # Handle the post request if request.method == "POST" and signin_form.validate_on_submit(): # Check if the user exists _, content = conn.execute_and_return(f"SELECT COUNT(user_id) FROM users WHERE email=\'{signin_form.email.data}\'") count = content[0][0] # If it does, we construct the object if count > 0: user = User.run_and_return(conn, f"SELECT * FROM users WHERE email=\'{signin_form.email.data}\'") # We check the hash, if it matches, we login if bcrypt.checkpw(bytes(signin_form.password.data, "utf-8"), bytes(user.password_hash, "utf-8")): login_user(user) return redirect(url_for("main")) # If it doesn't match, we flash a warning else: flash("Incorrect Password") return redirect(url_for("auth.signin")) # If the user doesn't exist, we flash a message else: flash("User does not exist. Please check the email you entered") return redirect(url_for("auth.signin")) return render_template("auth/signin.html", title="Sign-in", form=signin_form) # Route to logout @auth.route('/logout') def logout(): logout_user() return redirect(url_for("main"))
Go
UTF-8
1,019
3.578125
4
[]
no_license
// Package menu provides a command-line menu interface. package menu import ( "fmt" "strconv" "strings" "bufio" "os" ) type Option struct { Choice string Desc string } type Menu struct { options []Option } func New(options []Option) *Menu { return &Menu{ options: options, } } func (m *Menu) Ask() string { fmt.Println("Options: ") for i, opt := range m.options { fmt.Printf("\t%d: %s\n", i, opt.Desc) } for { fmt.Print(" Choice > ") input := bufio.NewReader(os.Stdin) choice, err := input.ReadString('\n') if err != nil { return "" } trimmed := strings.TrimSpace(choice) c, err := strconv.Atoi(trimmed) if err != nil { fmt.Printf("'%s' is not a valid choice. Please choose a number.", trimmed) } else if c < 0 || c >= len(m.options) { fmt.Printf("'%d' is not a valid choice. Please choose one of the options.", c) } else { return m.options[c].Choice } } }
Ruby
UTF-8
1,001
2.5625
3
[ "MIT" ]
permissive
require 'faraday' module FaradayMiddleware # Request middleware that signs the request with the signature gem. # # Adds authentication params based on a HMAC signature generated from a # combination of the secret, token, and body supplied. See the signature # gem for more information on how to verify the signature on the # receiving end. # # The body must be a hash for a signature to be generated. class Signature < Faraday::Middleware dependency 'signature' def initialize(app, key, secret) super(app) @key = key @secret = secret raise ArgumentError, "Both :key and :secret are required" unless @key && @secret end def call(env) if env[:body] && !env[:body].respond_to?(:to_str) auth_hash = ::Signature::Request.new(env[:method].to_s.upcase, env[:url].path.to_s, env[:body]).sign(::Signature::Token.new(@key, @secret)) env[:body] = env[:body].merge(auth_hash) end @app.call(env) end end end
JavaScript
UTF-8
766
3.359375
3
[]
no_license
const API_KEY = `fdf9257aafbed128dbd819a44a2f14d9` const cityTemperture = () => { const city = document.getElementById('city-name').value; const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric` fetch(url) .then(res => res.json()) .then(data => displayTemperture(data)) } const setCity= (id,text) => { document.getElementById(id).innerText = text; } const displayTemperture = (weather) => { setCity('city', weather.name); setCity('temp', weather.main.temp); setCity('clouds', weather.weather[0].main); const icon = `http://openweathermap.org/img/wn/${weather.weather[0].icon}@2x.png` const iconImg = document.getElementById('icon'); iconImg.setAttribute('src', icon); }
C++
UTF-8
582
3.65625
4
[]
no_license
#include<iostream> #include<algorithm> using namespace std; void show(int a[], int array_size) { for(int i = 0; i < array_size; i++) cout<<a[i]<<" "; } int main() { int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int asize = sizeof(a) / sizeof(a[0]); cout << "The array before sorting is : \n"; show(a, asize); sort(a, a + asize); cout << "\n\nThe array after sorting is :\n"; show(a, asize); //sort in descending order sort(a, a + asize, greater<int>()); cout<<"sorting in descending order\n"; show(a, asize); return 0; }
Markdown
UTF-8
12,975
2.625
3
[]
no_license
# CSCI/CMPE 2333.01: Computer Organization and # Assembly Language ## Carlos Pena ## Spring 2019 ``` E-mail:carlos.penacaballero01@utrgv.edu Class Hours: MW 1:40pm-2:55 pm Office Hours: MTWR 3:00pm-4:20pm Class Room: IEAB 1.204 Office: IEAB 3. ``` ## Textbooks - Assembly Language for x86 Processors, 7th Ed., by Kip R. Irvine, ISBN 978-0-13-376940- (Required) - Computer Organization and Architecture: Designing for Performance, 9th Ed., by William Stallings, ISBN 978-0-13-293633-0 (Recommended) ## Objectives This course is intended to provide the student with an introduction to computer organization and assembly language programming. Its purpose is to provide the student with a better under- standing of the internal operation of the computer. ## Prerequisites This course part of the required sequence of introductory Computer Science and Computer En- gineering courses. Students are expected to have successfully completed CSCI/CMPE 1370, or have the consent of the instructor. **(If you do not meet these requirements, you will be dropped from the course.)** This course must be successfully completed (with a grade of ‘C’ or better) to continue the course of studies in Computer Science. ## Grading Policy - **40%** of your grade will be determined by 2 major exams during normal class hours. - **20%** of your grade will be determined by assignments (in-class or at home) and quizzes - **20%** of your grade will be determined by programming assignments - **20%** of your grade will be determined by a final exam. ## Assignments There will be about 5-6 programs assigned. These are expected to be organized and well docu- mented. The specific details for grading and documentation will be given at the time of the first program assignment. Assignments will be graded on correctness, quality, and style. You MUST submit ALL home- work/programming projects, with no exceptions, in order to get overall credit for the assign- ments/programming projects. All homework must be turned in on Blackboard and must be completely legible. Any portion which is not clearly and easily legible will receive a 0. All pro- gramming projects must be submitted using the tool provided by Blackboard. I will not accept programming projects through e mail or by hard copy. Also, all programming projects must compile or they will receive a 10% AT MOST. ## Late Policy All assignments should be turned in on their due date. Programs turned in late will be graded on the following basis: - **10 point penalty** if turned in within 24 hours late - **20 point penalty** if turned in within 48 hours late - **No points awarded** if more than 48 hours late Make up exams will not be given except by my prior consent. You must notify me within 24 hours after missing the exam so that I may determine the appropriateness of allowing a make up exam. Examples of acceptable excuses would be the death of an immediate family member, or an illness requiring physician’s attention. You must take all exams in order to pass the course; missing any one exam will result in an ‘F’ as your course grade. ## Expectations I am committed to quality teaching and to providing you a meaningful experience in this course but learning is your responsibility so please do your part in order to receive the maximum benefit from the course. For this class, **I expect you to** : - **Have your electronic devices (cell phones, notebooks, music players, etc.) OFF at all** **times (tests, and lectures).** - Attend each class, arrive on time and remain in the classroom throughout the entire class meeting. If you have a legitimate and important reason for needing to leave early, please let me know before class starts. - Complete all assignments and submit them on time (this is very important for you!). - Interact respectfully with me, the course assistants, and your other classmates. - Participate in class discussions and activities. - **Remain on task and focused during class (i.e., no doing homework, engaging in side** **conversations, web-surfing, reading e-mail, Facebooking, chatting, IMing, etc. during** **class).** - Access your Blackboard account frequently to get information on course policies, assign- ments, tests, grades, etc. **All information posted on it will be assumed to be known by** **the student 24 hours later.** - Come speak to me IN PERSON and IMMEDIATELY at the **first** sign that you are having trouble with the class or if you miss assignments so I can try to help you. ## Tentative Schedule ``` The following is a general outline for the course and may be revised as the semester progresses. In this, ST is Stallings book, and IR is Irvines book. ``` ``` Jan 14th Computer Numbers and ArithmeticST: 9 ``` ``` 16th Computer Numbers and ArithmeticST: 9 21st MLK ``` ``` 23rd Computer EvolutionST: 1- 28th Computer FunctionST: 3 ``` ``` 30th Internal & External MemoryST: 5- ``` ``` Feb 4th Internal & External MemoryST: 5- ``` ``` 6th Review 11th Exam 1 ``` ``` 13th Assembly Language Fundamentals / LAB IR: 3 18th Assembly Language Fundamentals / LAB IR: 3 ``` ``` 20th Data transfer; Arithmetic; AddressingIR: 4 ``` ``` 25th Data transfer; Arithmetic; AddressingIR: 4 ``` ``` 27th Procedures and Parameter PassingIR: 5 ``` ``` Mar 4th Procedures and Parameter PassingIR: 5 ``` ``` 6th Logic and Decision InstructionsIR: 6 11th Spring Break ``` ``` 13th Spring Break 18th Logic and Decision InstructionsIR: 6 ``` ``` 20th Review ``` ``` 25th Exam 2 ``` ``` 27th Integer ArithmeticIR: 7 ``` ``` Apr 1st Integer ArithmeticIR: 7 ``` ``` 3rd Advanced ProceduresIR: 8 8th Advanced ProceduresIR: 8 ``` ``` 10th Reverse Engineering 15th Exploiting Vulnerabilities in Binaries ``` ``` 17th Misc topics as time permits 22nd Misc topics as time permits ``` ``` 24th Misc topics as time permits ``` ``` 29th Misc topics as time permits ``` ``` May 1st Final Exam ``` ## Important Dates - January 14 - First day of classes - January 17 - Last day to add a course or register for spring 2019 - January 21 - MLK - March 11-16 SPRING BREAK - No classes - April 10 - Last day to drop a course; will count toward the 6-drop rule - April 19-20 EASTER HOLIDAY - No classes - May 1 - Last day of classes - May 2 - Study Day - No class - May 3-9 - Spring 2018 Final Exams - May 10-11 Commencement Ceremonies ## Learning outcomes At the end of this course, the student should be able to 1. Describe the progression of computer architecture from vacuum tubes to VLSI. 2. Demonstrate an understanding of the basic building blocks and their role in the historical development of computer architecture. 3. Design a simple circuit using the fundamental building blocks. 4. Explain how interrupts are used to implement I/O control and data transfers. 5. Identify various types of buses in a computer system. 6. Explain the reasons for using different formats to represent numerical data. 7. Explain how negative integers are stored in sign magnitude and twos complement repre- sentation. 8. Convert numerical data from one format to another. 9. Discuss how fixed length number representations affect accuracy and precision. 10. Describe the internal representation of nonnumeric data. 11. Describe the internal representation of characters, strings, records, and arrays. 12. Explain the organization of the classical von Neumann machine and its major functional units. 13. Explain how an instruction is executed in a classical von Neumann machine. 14. Write assembly language programs that use basic computation and simple I/o, standard conditional structures, basic iterative structures, and the definition of functions. 15. Demonstrate how fundamental high level programming constructs are implemented at the machine language level. 16. Explain how subroutine calls are handled at the assembly level. 17. Explain the basic concepts of interrupts and I/O operations. 18. Choose appropriate conditional and iteration constructs for a given programming task. 19. Describe the mechanics of parameter passing. ## ABET Student Learning Outcomes 1. An ability to apply knowledge of computing and mathematics appropriate to the discipline. 2. An ability to analyze a problem, and identify and define the computing requirements ap- propriate to its solution. 3. An ability to design, implement, and evaluate a computer-based system, process, compo- nent, or program to meet desired needs. 4. An ability to use current techniques, skills, and tools necessary for computing practice. ## Students with Disabilities Students with a documented disability (physical, psychological, learning, or other disability which affects academic performance) who would like to receive academic accommodations should contact Student Accessibility Services (SAS) as soon as possible to schedule an appointment to initiate services. Accommodations can be arranged through SAS at any time, but are not retroac- tive. Students who suffer a broken bone, severe injury or undergo surgery during the semester are eligible for temporary services. **Brownsville Campus:** Student Accessibility Services is lo- cated in Cortez Hall Room 129 and can be contacted by phone at (956) 882-7374 (Voice) or via email at ability@utrgv.edu. **Edinburg Campus:** Student Accessibility Services is located in 108 University Center and can be contacted by phone at (956) 665-7005 (Voice), (956) 665-3840 (Fax), or via email at ability@utrgv.edu. ## Mandatory Course Evaluation Period Students are required to complete an ONLINE evaluation of this course, accessed through your UTRGV account (http://my.utrgv.edu); you will be contacted through email with further instruc- tions. Students who complete their evaluations will have priority access to their grades. Online evaluations will be available: - Fall 2018 Module 1: October 4 - 10 - Fall 2018 Module 2: November 29 - Decemeber 5 - Fall 2018 (full semester): November 15 - December 5 ## Attendance Students are expected to attend all scheduled classes and may be dropped from the course for excessive absences. UTRGV’s attendance policy excuses students from attending class if they are participating in officially sponsored university activities, such as athletics; for observance of religious holy days; or for military service. Students should contact the instructor in advance of the excused absence and arrange to make up missed work or examinations. ## Scholastic Integrity As members of a community dedicated to Honesty, Integrity and Respect, students are reminded that those who engage in scholastic dishonesty are subject to disciplinary penalties, including the possibility of failure in the course and expulsion from the University. Scholastic dishonesty includes but is not limited to: cheating, plagiarism (including self-plagiarism), and collusion; submission for credit of any work or materials that are attributable in whole or in part to another person; taking an examination for another person; any act designed to give unfair advantage to a student; or the attempt to commit such acts. Since scholastic dishonesty harms the individual, all students and the integrity of the University, policies on scholastic dishonesty will be strictly enforced (Board of Regents Rules and Regulations and UTRGV Academic Integrity Guidelines). All scholastic dishonesty incidents will be reported to the Dean of Students. ## Sexual Harassment, Discrimination, and Violence In accordance with UT System regulations, your instructor is a “Responsible Employee” for re- porting purposes under Title IX regulations and so must report any instance, occurring during a student’s time in college, of sexual assault, stalking, dating violence, domestic violence, or sexual harassment about which she/he becomes aware during this course through writing, discussion, or personal disclosure. More information can be found at [http://www.utrgv.edu/equity,](http://www.utrgv.edu/equity,) including confidential resources available on campus. The faculty and staff of UTRGV actively strive to provide a learning, working, and living environment that promotes personal integrity, civility, and mutual respect that is free from sexual misconduct and discrimination. ## Course Drops According to UTRGV policy, students may drop any class without penalty earning a grade of DR until the official drop date. Following that date, students must be assigned a letter grade and can no longer drop the class. Students considering dropping the class should be aware of the “3-peat rule” and the “6-drop” rule so they can recognize how dropped classes may affect their academic success. The 6-drop rule refers to Texas law that dictates that undergraduate students may not drop more than six courses during their undergraduate career. Courses dropped at other Texas public higher education institutions will count toward the six-course drop limit. The 3-peat rule refers to additional fees charged to students who take the same class for the third time.
Python
UTF-8
2,771
2.828125
3
[]
no_license
######################################################################################################## # 종목 일 - 시각 시세 추출. # thistime=20210408153000. 추출 일자와 장 종료시각 # max page = 50 ######################################################################################################## import datetime # 라이브러리 로드 # requests는 작은 웹브라우저로 웹사이트 내용을 가져온다. import requests # BeautifulSoup 을 통해 읽어 온 웹페이지를 파싱한다. from bs4 import BeautifulSoup as bs # 크롤링 후 결과를 데이터프레임 형태로 보기 위해 불러온다. import pandas as pd # 환경파일 import yaml # 당일 now_dtm = datetime.datetime.now() # 시작일자 start_dt = (now_dtm - datetime.timedelta(days=7)).strftime("%Y%m%d") # 종료일자 end_dt = now_dtm.strftime("%Y%m%d") # 날짜형 시작일자 dtm_start = datetime.datetime.strptime(start_dt, "%Y%m%d") # CSV 파일명 csv_filename = "./csv/agreement_" + end_dt + ".csv" # 최종 데이터 리스트 list_agree = [] # 날짜 증가를 위한 변수 icnt = 0 while True: dtm_dt = dtm_start + datetime.timedelta(days=icnt) dt = dtm_dt.strftime("%Y%m%d") if dt > end_dt: break print(dt) last_tf = False for pages in range(50): # 0 페이지는 없어서 스킵 if pages == 0: continue # 9시 데이터 읽었으면 종료 if last_tf == True: break jongmok = "122630" main_url = f"https://finance.naver.com/item/sise_time.nhn?code={jongmok}&thistime={dt}153000&page={pages}" response = requests.get( main_url, headers={"User-agent": "Mozilla/5.0"} ) soup = bs(response.text, 'html.parser') idx = 0 num = 0 for href in soup.find_all("td"): str_href = str(href) idx += 1 # time if 'class="tah p10 gray03' in str_href: list_data = [] agree_time = str_href.replace("</span></td>", "").replace('<td align="center"><span class="tah p10 gray03">', "").replace(":", "").zfill(4) num = idx + 1 list_data.append(str(dt)) list_data.append(str(agree_time)) if agree_time == "0900": last_tf = True # price elif idx == num: agree_price = str_href.replace("</span></td>", "").replace('<td class="num"><span class="tah p11">', "").replace(",", "") list_data.append(agree_price) list_agree.append(list_data) icnt += 1 df_agree = pd.DataFrame(list_agree, columns=["date", "time", "price"]) df_agree.to_csv(csv_filename, encoding="utf-8-sig", index=False)
TypeScript
UTF-8
3,951
2.75
3
[]
no_license
import { AnyAction } from 'redux'; import { BookResType, BookReqType } from '../../types'; import { getTokenFromState } from '../utils'; import { call, put, select, takeEvery } from 'redux-saga/effects'; import { push } from 'connected-react-router'; import BookService from '../../services/BookService'; import { createAction, ActionType, createReducer } from 'typesafe-actions'; export interface BooksState { books: BookResType[] | null; loading: boolean; error: Error | null; } const initialState: BooksState = { books: null, loading: false, error: null, }; export const pending = createAction('PENDING')(); export const success = createAction('SUCCESS')<BookResType[]>(); export const errorHandler = createAction('ERROR')<Error>(); export const list = createAction('GET_BOOKS_LIST')(); export const add = createAction('ADD_BOOK')<BookReqType>(); export const edit = createAction('EDIT_BOOK')<BookReqType, number>(); export const deleteBook = createAction('DELETE_BOOK')<number>(); const bookActions = { pending, success, errorHandler, list, add, edit, deleteBook, }; type BooksAction = ActionType<typeof bookActions>; const reducer = createReducer<BooksState, BooksAction>(initialState) .handleAction(pending, (state) => ({ ...state, loading: true, })) .handleAction([list, add, edit, deleteBook], (state) => ({ ...state, loading: false, error: null, })) .handleAction(errorHandler, (state, action) => ({ ...state, books: null, loading: false, error: action.payload, })) .handleAction(success, (state, action) => ({ ...state, books: action.payload, loading: false, error: null, })); export default reducer; // [project] 책 목록을 가져오는 saga 함수를 작성했다. function* getBooksSaga() { try { yield put(pending()); const token: string = yield select(getTokenFromState); const books: BookResType[] = yield call(BookService.getBooks, token); yield put(success(books)); } catch (error) { yield put(errorHandler(error)); } } interface AddAction extends AnyAction { payload: BookReqType; } // [project] 책을 추가하는 saga 함수를 작성했다. function* addBookSaga(action: AddAction) { try { yield put(pending()); const token: string = yield select(getTokenFromState); yield call(BookService.addBook, token, action.payload); const books: BookResType[] = yield call(BookService.getBooks, token); yield put(success(books)); yield put(push('/')); } catch (error) { yield put(errorHandler(error)); } } interface DeleteAction extends AnyAction { payload: number; } // [project] 책을 삭제하는 saga 함수를 작성했다. function* deleteBookSaga(action: DeleteAction) { try { yield put(pending()); const token: string = yield select(getTokenFromState); yield call(BookService.deleteBook, token, action.payload); const books: BookResType[] = yield call(BookService.getBooks, token); yield put(success(books)); } catch (error) { yield put(errorHandler(error)); } } interface EditAction extends AnyAction { payload: BookReqType; meta: number; } // [project] 책을 수정하는 saga 함수를 작성했다. function* editBookSaga(action: EditAction) { try { yield put(pending()); const token: string = yield select(getTokenFromState); yield call(BookService.editBook, token, action.meta, action.payload); const books: BookResType[] = yield call(BookService.getBooks, token); yield put(success(books)); yield put(push('/')); } catch (error) { yield put(errorHandler(error)); } } // [project] saga 함수를 실행하는 액션과 액션 생성 함수를 작성했다. export function* sagas() { yield takeEvery('GET_BOOKS_LIST', getBooksSaga); yield takeEvery('ADD_BOOK', addBookSaga); yield takeEvery('DELETE_BOOK', deleteBookSaga); yield takeEvery('EDIT_BOOK', editBookSaga); }
C#
UTF-8
4,760
2.53125
3
[ "MIT" ]
permissive
using System; namespace Assembler.Frontend { internal interface ITypeRContext { string Operator { get; } int RegisterD { get; } int RegisterS { get; } int RegisterT { get; } } internal static class TypeRHelper { public static int Serialize(this ITypeRContext inst, SymbolResolver symbols, bool enableLongJump) { var op = GetOpcode(inst.Operator); var rd = (inst.RegisterD); var rs = (inst.RegisterS); var rt = (inst.RegisterT); return (op << 12) | (rs << 10) | (rt << 8) | (rd << 6); } public static string Prettify(this ITypeRContext inst, SymbolResolver symbols, bool enableLongJump) => $"{inst.Operator.ToUpper().PadRight(4)} R{(inst.RegisterD)}, R{(inst.RegisterS)}, R{(inst.RegisterT)}"; private static int GetOpcode(string text) { switch (text.ToUpper()) { case "AND": return 0x0; case "OR": return 0x1; case "ADD": return 0x2; case "SUB": return 0x3; case "ADDC": return 0x6; case "SUBC": return 0x5; case "SLT": return 0x4; default: throw new ArgumentOutOfRangeException(nameof(text)); } } public static PCTarget Execute(this ITypeRContext inst, Context context) { switch (inst.Operator.ToUpper()) { case "AND": context.Registers[inst.RegisterD] = (byte)(context.Registers[inst.RegisterS] & context.Registers[inst.RegisterT]); context.ZeroFlag = context.Registers[inst.RegisterD] == 0; return null; case "OR": context.Registers[inst.RegisterD] = (byte)(context.Registers[inst.RegisterS] | context.Registers[inst.RegisterT]); context.ZeroFlag = context.Registers[inst.RegisterD] == 0; return null; case "ADD": { var s = context.Registers[inst.RegisterS] + context.Registers[inst.RegisterT]; context.CFlag = (s & ~0xff) != 0; context.Registers[inst.RegisterD] = (byte)s; context.ZeroFlag = context.Registers[inst.RegisterD] == 0; return null; } case "SUB": { var s = context.Registers[inst.RegisterS] - context.Registers[inst.RegisterT]; context.CFlag = (s & ~0xff) == 0; context.Registers[inst.RegisterD] = (byte)s; context.ZeroFlag = context.Registers[inst.RegisterD] == 0; return null; } case "ADDC": { var s = context.Registers[inst.RegisterS] + context.Registers[inst.RegisterT] + (context.CFlag ? 1 : 0); context.CFlag = (s & ~0xff) != 0; context.Registers[inst.RegisterD] = (byte)s; context.ZeroFlag = context.Registers[inst.RegisterD] == 0; return null; } case "SUBC": { var s = context.Registers[inst.RegisterS] - context.Registers[inst.RegisterT] - (context.CFlag ? 0 : 1); context.CFlag = (s & ~0xff) == 0; context.Registers[inst.RegisterD] = (byte)s; context.ZeroFlag = context.Registers[inst.RegisterD] == 0; return null; } case "SLT": context.Registers[inst.RegisterD] = (context.Registers[inst.RegisterS] < context.Registers[inst.RegisterT]) ? (byte)1 : (byte)0; context.ZeroFlag = context.Registers[inst.RegisterD] == 0; return null; default: throw new InvalidOperationException(); } } } }
JavaScript
UTF-8
697
2.703125
3
[]
no_license
import React from 'react'; const Balance = props => { const getBalance = () => { const balanceAmount = props.getTotals('income') - props.getTotals('savings') - props.getTotals('expense'); return balanceAmount.toFixed(2).toLocaleString(); } return ( <div className="totalsContainer"> <h2>Expenses:</h2>${parseFloat(props.getTotals('expense')).toLocaleString('en')} <h2>Income:</h2>${parseFloat(props.getTotals('income')).toLocaleString('en')} <h2>Savings:</h2>${parseFloat(props.getTotals('savings')).toLocaleString('en')} <h2>Balance:</h2>${parseFloat(getBalance()).toLocaleString('en')} </div> ) } export default Balance;
Python
UTF-8
7,499
2.625
3
[]
no_license
import json ,urllib.request import json import time import datetime """"" yesterday = datetime.datetime.now() - datetime.timedelta(days = 1) dateTime = datetime.date(2019,1,25) unixtime = str(int(time.mktime(dateTime.timetuple()))) """"" def downloadStockData(array, minIndex): counterStockSymbols = minIndex strStockSymbols = "" indexRange = 500 if minIndex == 5500: indexRange = 372 while counterStockSymbols < minIndex + indexRange: strStockSymbols = strStockSymbols + array[counterStockSymbols] counterStockSymbols = counterStockSymbols + 1 data = urllib.request.urlopen("https://query1.finance.yahoo.com/v7/finance/quote?symbols="+strStockSymbols).read() output = json.loads(data.decode('utf-8')) dateToday = str(datetime.datetime.now()) counterStockSymbols = 0 while counterStockSymbols < indexRange: isLegalLine = 1 title1 = "Stock #" + str(minIndex + counterStockSymbols) title11 = "------------" try: symbol = str(output['quoteResponse']['result'][counterStockSymbols]['symbol']) except Exception: symbol = "" isLegalLine = 0 try: DaysRange = str(output['quoteResponse']['result'][counterStockSymbols]['regularMarketDayRange']) except Exception: DaysRange = 0 try: bid = str(output['quoteResponse']['result'][counterStockSymbols]['bid']) except Exception: bid = 0 try: earningsTimestampStart = str( output['quoteResponse']['result'][counterStockSymbols]['earningsTimestampStart']) except Exception: earningsTimestampStart = 0 try: earningsTimestampEnd = str \ (output['quoteResponse']['result'][counterStockSymbols]['earningsTimestampEnd']) except Exception: earningsTimestampEnd = 0 try: marketCap = str(output['quoteResponse']['result'][counterStockSymbols]['marketCap']) except Exception: marketCap = 0 try: averageDailyVolume10Day = str \ (output['quoteResponse']['result'][counterStockSymbols]['averageDailyVolume10Day']) except Exception: averageDailyVolume10Day = 0 try: epsTrailingTwelveMonths = str(output['quoteResponse']['result'][counterStockSymbols]['epsTrailingTwelveMonths']) except Exception: epsTrailingTwelveMonths = 0 try: regularMarketPreviousClose = str(output['quoteResponse']['result'][counterStockSymbols]['regularMarketPreviousClose']) except Exception: regularMarketPreviousClose = 0 try: ask = str(output['quoteResponse']['result'][counterStockSymbols]['ask']) except Exception: ask = 0 try: fiftyTwoWeekLowChange = str (output['quoteResponse']['result'][counterStockSymbols]['fiftyTwoWeekLowChange']) except Exception: fiftyTwoWeekLowChange = 0 try: fiftyTwoWeekLow = str(output['quoteResponse']['result'][counterStockSymbols]['fiftyTwoWeekLow']) except Exception: fiftyTwoWeekLow = 0 try: regularMarketPrice = str( output['quoteResponse']['result'][counterStockSymbols]['regularMarketPrice']) except Exception: regularMarketPrice = 0 try: regularMarketTime = str \ (output['quoteResponse']['result'][counterStockSymbols]['regularMarketTime']) except Exception: regularMarketTime = 0 try: regularMarketChange = str(output['quoteResponse']['result'][counterStockSymbols]['regularMarketChange']) except Exception: regularMarketChange = 0 try: regularMarketOpen = str(output['quoteResponse']['result'][counterStockSymbols]['regularMarketOpen']) except Exception: regularMarketOpen = 0 try: regularMarketDayHigh = str(output['quoteResponse']['result'][counterStockSymbols]['regularMarketDayHigh']) except Exception: regularMarketDayHigh = 0 try: regularMarketDayLow = str( output['quoteResponse']['result'][counterStockSymbols]['regularMarketDayLow']) except Exception: regularMarketDayLow = 0 try: regularMarketVolume = str(output['quoteResponse']['result'][counterStockSymbols]['regularMarketVolume']) except Exception: regularMarketVolume = 0 try: fiftyTwoWeekRange = str(output['quoteResponse']['result'][counterStockSymbols]['fiftyTwoWeekRange']) except Exception: fiftyTwoWeekRange = 0 try: earningsTimestampStart = output['quoteResponse']['result'][counterStockSymbols]['earningsTimestampStart'] earningTimestampStartDate = datetime.datetime.utcfromtimestamp(earningsTimestampStart).strftime('%m-%d-%Y') except Exception: earningTimestampStartDate = 0 try: earningsTimestampEnd = output['quoteResponse']['result'][counterStockSymbols]['earningsTimestampEnd'] earningsTimestampEndDate = datetime.datetime.utcfromtimestamp(earningsTimestampEnd).strftime('%m-%d-%Y') except Exception: earningsTimestampEndDate = 0 try: trailingAnnualDividend = output['quoteResponse']['result'][counterStockSymbols]['trailingAnnualDividend'] except Exception: trailingAnnualDividend = 0 try: trailingAnnualDividendRate = output['quoteResponse']['result'][counterStockSymbols]['trailingAnnualDividendRate'] except Exception: trailingAnnualDividendRate = 0 try: regularMarketChangePercent = str( output['quoteResponse']['result'][counterStockSymbols]['regularMarketChangePercent']) except Exception: regularMarketChangePercent = 0 message = symbol + '\t' + str(regularMarketChangePercent) + '\t' + str(regularMarketChange) + '\t' + 'NA' + '\t' + str(regularMarketPrice) + '\t' + \ str(regularMarketDayLow) + '\t' + 'NA' + '\t' + str(regularMarketDayHigh) + '\t' + \ str(regularMarketPreviousClose) + '\t' + str(regularMarketOpen) + '\t' + str(bid) + '\t' + \ str(ask) + '\t' + str(DaysRange) + '\t' + str(fiftyTwoWeekRange) + \ '\t' + str(regularMarketVolume) + '\t' + str(averageDailyVolume10Day) + '\t' + str(marketCap) + '\t' + 'NA' + '\t' + 'NA' + \ '\t' + str(epsTrailingTwelveMonths) + '\t' + str(earningTimestampStartDate) + ' - ' + str(earningsTimestampEndDate) + \ '\t' + str(trailingAnnualDividend) + '\t' + str(trailingAnnualDividendRate) + '\t' + 'NA' + '\n' if isLegalLine == 1: with open('stockout.txt', 'a') as the_file: the_file.write(message) counterStockSymbols = counterStockSymbols + 1 with open("stockin.txt", "r") as ins: array = [] for line in ins: ext = "," fileNameOnly = line[:line.find(ext) + len(ext)] array.append(fileNameOnly) countQueries = 0 minIndex = 0 while countQueries < 12: downloadStockData(array, minIndex) minIndex = minIndex + 500 countQueries = countQueries + 1 time.sleep(30)
C#
UTF-8
1,780
2.921875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApp1 { class Trainer : Employee { private PhysicalHealth Health; private List<String> Proficiency; private List<Customer> PersCustomers; //Getter public PhysicalHealth GetHealth() { return Health; } public List<String> GetProfi() { return Proficiency; } public List<Customer> GetPCusts() { return PersCustomers; } public new String GetType() { TheType = "Trainer"; return TheType; } //Setter public Boolean SetHealth(PhysicalHealth HP) { if () { Health = HP; return true; } else { return false; } } public Boolean SetProfi(List<String> Pr) { if () { Proficiency = Pr; return true; } else { return false; } } public Boolean SetPCusts(List<Customer> PCust) { if () { PersCustomers = PCust; return true; } else { return false; } } public new Boolean SetType(String T) { if (T == "Trainer") { TheType = T; return true; } else { return false; } } } }
C#
BIG5
2,002
2.75
3
[]
no_license
using UnityEngine; /// <summary> /// t /// TqP /// </summary> public class AtackSystem : MonoBehaviour { #region :} [Header("ѼƦW")] public string praAttackPart = "qq"; public string parAttackGather = "𶰮"; [Header("s浥ݮɶ"), Range(0, 2)] public float intervalBetweenAttackPart = 0.2f; [Header("ɶ"), Range(0, 2)] public float timeToAttackGather = 1; #endregion #region :pH private Animator ani; /// <summary> /// aU䪺ɶ /// </summary> private float timer; #endregion #region ƥ //ƥ:Cw Start 椧e@ private void Awake() { ani = GetComponent<Animator>(); } //}lƥ:Cw Awake 椧e@ private void Start() { } private void Update() { ClickTime(); } #endregion #region k:pH /// <summary> /// Iɶ֥[ /// </summary> private void ClickTime() { if (Input.GetKey(KeyCode.Mouse0)) //t { timer += Time.deltaTime;@@@@@@@@@@@ //֥[ pɾ } else if (Input.GetKey(KeyCode.Mouse0)) //} { if (timer >= timeToAttackGather) //pG pɾ >= ɶ { AttackGather(); } else // _h { print("ɶ"); } timer = 0; // pɾks } print("U䪺ɶ:" + timer); } /// /// /// private void AttackGather() { ani.SetTrigger(parAttackGather); } #endregion }
Rust
UTF-8
30,864
2.9375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CTRL { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `start`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum STARTR { #[doc = r" Reserved"] _Reserved(bool), } impl STARTR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { STARTR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> STARTR { match value { i => STARTR::_Reserved(i), } } } #[doc = "Possible values of the field `opsel`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OPSELR { #[doc = "Exponentiation."] EXP, #[doc = "Square operation."] SQR, #[doc = "Multiply."] MUL, #[doc = "Square operation followed by multiply."] SQRMUL, #[doc = "Addition."] ADD, #[doc = "Subtraction."] SUB, #[doc = r" Reserved"] _Reserved(u8), } impl OPSELR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { OPSELR::EXP => 0, OPSELR::SQR => 1, OPSELR::MUL => 2, OPSELR::SQRMUL => 3, OPSELR::ADD => 4, OPSELR::SUB => 5, OPSELR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> OPSELR { match value { 0 => OPSELR::EXP, 1 => OPSELR::SQR, 2 => OPSELR::MUL, 3 => OPSELR::SQRMUL, 4 => OPSELR::ADD, 5 => OPSELR::SUB, i => OPSELR::_Reserved(i), } } #[doc = "Checks if the value of the field is `EXP`"] #[inline] pub fn is_exp(&self) -> bool { *self == OPSELR::EXP } #[doc = "Checks if the value of the field is `SQR`"] #[inline] pub fn is_sqr(&self) -> bool { *self == OPSELR::SQR } #[doc = "Checks if the value of the field is `MUL`"] #[inline] pub fn is_mul(&self) -> bool { *self == OPSELR::MUL } #[doc = "Checks if the value of the field is `SQRMUL`"] #[inline] pub fn is_sqrmul(&self) -> bool { *self == OPSELR::SQRMUL } #[doc = "Checks if the value of the field is `ADD`"] #[inline] pub fn is_add(&self) -> bool { *self == OPSELR::ADD } #[doc = "Checks if the value of the field is `SUB`"] #[inline] pub fn is_sub(&self) -> bool { *self == OPSELR::SUB } } #[doc = "Possible values of the field `ocalc`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OCALCR { #[doc = r" Reserved"] _Reserved(bool), } impl OCALCR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { OCALCR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> OCALCR { match value { i => OCALCR::_Reserved(i), } } } #[doc = "Possible values of the field `if_done`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum IF_DONER { #[doc = r" Reserved"] _Reserved(bool), } impl IF_DONER { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { IF_DONER::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> IF_DONER { match value { i => IF_DONER::_Reserved(i), } } } #[doc = "Possible values of the field `inten`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum INTENR { #[doc = r" Reserved"] _Reserved(bool), } impl INTENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { INTENR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> INTENR { match value { i => INTENR::_Reserved(i), } } } #[doc = "Possible values of the field `if_error`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum IF_ERRORR { #[doc = r" Reserved"] _Reserved(bool), } impl IF_ERRORR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { IF_ERRORR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> IF_ERRORR { match value { i => IF_ERRORR::_Reserved(i), } } } #[doc = "Possible values of the field `ofs_a`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OFS_AR { #[doc = r" Reserved"] _Reserved(u8), } impl OFS_AR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { OFS_AR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> OFS_AR { match value { i => OFS_AR::_Reserved(i), } } } #[doc = "Possible values of the field `ofs_b`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OFS_BR { #[doc = r" Reserved"] _Reserved(u8), } impl OFS_BR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { OFS_BR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> OFS_BR { match value { i => OFS_BR::_Reserved(i), } } } #[doc = "Possible values of the field `ofs_exp`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OFS_EXPR { #[doc = r" Reserved"] _Reserved(u8), } impl OFS_EXPR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { OFS_EXPR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> OFS_EXPR { match value { i => OFS_EXPR::_Reserved(i), } } } #[doc = "Possible values of the field `ofs_mod`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OFS_MODR { #[doc = r" Reserved"] _Reserved(u8), } impl OFS_MODR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { OFS_MODR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> OFS_MODR { match value { i => OFS_MODR::_Reserved(i), } } } #[doc = "Possible values of the field `seg_a`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SEG_AR { #[doc = r" Reserved"] _Reserved(u8), } impl SEG_AR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { SEG_AR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> SEG_AR { match value { i => SEG_AR::_Reserved(i), } } } #[doc = "Possible values of the field `seg_b`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SEG_BR { #[doc = r" Reserved"] _Reserved(u8), } impl SEG_BR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { SEG_BR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> SEG_BR { match value { i => SEG_BR::_Reserved(i), } } } #[doc = "Possible values of the field `seg_res`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SEG_RESR { #[doc = r" Reserved"] _Reserved(u8), } impl SEG_RESR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { SEG_RESR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> SEG_RESR { match value { i => SEG_RESR::_Reserved(i), } } } #[doc = "Possible values of the field `seg_tmp`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SEG_TMPR { #[doc = r" Reserved"] _Reserved(u8), } impl SEG_TMPR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { SEG_TMPR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> SEG_TMPR { match value { i => SEG_TMPR::_Reserved(i), } } } #[doc = "Values that can be written to the field `start`"] pub enum STARTW {} impl STARTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self {} } } #[doc = r" Proxy"] pub struct _STARTW<'a> { w: &'a mut W, } impl<'a> _STARTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: STARTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `opsel`"] pub enum OPSELW { #[doc = "Exponentiation."] EXP, #[doc = "Square operation."] SQR, #[doc = "Multiply."] MUL, #[doc = "Square operation followed by multiply."] SQRMUL, #[doc = "Addition."] ADD, #[doc = "Subtraction."] SUB, } impl OPSELW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { OPSELW::EXP => 0, OPSELW::SQR => 1, OPSELW::MUL => 2, OPSELW::SQRMUL => 3, OPSELW::ADD => 4, OPSELW::SUB => 5, } } } #[doc = r" Proxy"] pub struct _OPSELW<'a> { w: &'a mut W, } impl<'a> _OPSELW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: OPSELW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Exponentiation."] #[inline] pub fn exp(self) -> &'a mut W { self.variant(OPSELW::EXP) } #[doc = "Square operation."] #[inline] pub fn sqr(self) -> &'a mut W { self.variant(OPSELW::SQR) } #[doc = "Multiply."] #[inline] pub fn mul(self) -> &'a mut W { self.variant(OPSELW::MUL) } #[doc = "Square operation followed by multiply."] #[inline] pub fn sqrmul(self) -> &'a mut W { self.variant(OPSELW::SQRMUL) } #[doc = "Addition."] #[inline] pub fn add(self) -> &'a mut W { self.variant(OPSELW::ADD) } #[doc = "Subtraction."] #[inline] pub fn sub(self) -> &'a mut W { self.variant(OPSELW::SUB) } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 7; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `ocalc`"] pub enum OCALCW {} impl OCALCW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self {} } } #[doc = r" Proxy"] pub struct _OCALCW<'a> { w: &'a mut W, } impl<'a> _OCALCW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: OCALCW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `if_done`"] pub enum IF_DONEW {} impl IF_DONEW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self {} } } #[doc = r" Proxy"] pub struct _IF_DONEW<'a> { w: &'a mut W, } impl<'a> _IF_DONEW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: IF_DONEW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 5; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `inten`"] pub enum INTENW {} impl INTENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self {} } } #[doc = r" Proxy"] pub struct _INTENW<'a> { w: &'a mut W, } impl<'a> _INTENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: INTENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `if_error`"] pub enum IF_ERRORW {} impl IF_ERRORW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self {} } } #[doc = r" Proxy"] pub struct _IF_ERRORW<'a> { w: &'a mut W, } impl<'a> _IF_ERRORW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: IF_ERRORW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 7; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `ofs_a`"] pub enum OFS_AW {} impl OFS_AW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self {} } } #[doc = r" Proxy"] pub struct _OFS_AW<'a> { w: &'a mut W, } impl<'a> _OFS_AW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: OFS_AW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `ofs_b`"] pub enum OFS_BW {} impl OFS_BW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self {} } } #[doc = r" Proxy"] pub struct _OFS_BW<'a> { w: &'a mut W, } impl<'a> _OFS_BW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: OFS_BW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 10; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `ofs_exp`"] pub enum OFS_EXPW {} impl OFS_EXPW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self {} } } #[doc = r" Proxy"] pub struct _OFS_EXPW<'a> { w: &'a mut W, } impl<'a> _OFS_EXPW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: OFS_EXPW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 12; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `ofs_mod`"] pub enum OFS_MODW {} impl OFS_MODW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self {} } } #[doc = r" Proxy"] pub struct _OFS_MODW<'a> { w: &'a mut W, } impl<'a> _OFS_MODW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: OFS_MODW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 14; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `seg_a`"] pub enum SEG_AW {} impl SEG_AW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self {} } } #[doc = r" Proxy"] pub struct _SEG_AW<'a> { w: &'a mut W, } impl<'a> _SEG_AW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SEG_AW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `seg_b`"] pub enum SEG_BW {} impl SEG_BW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self {} } } #[doc = r" Proxy"] pub struct _SEG_BW<'a> { w: &'a mut W, } impl<'a> _SEG_BW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SEG_BW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 20; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `seg_res`"] pub enum SEG_RESW {} impl SEG_RESW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self {} } } #[doc = r" Proxy"] pub struct _SEG_RESW<'a> { w: &'a mut W, } impl<'a> _SEG_RESW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SEG_RESW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `seg_tmp`"] pub enum SEG_TMPW {} impl SEG_TMPW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self {} } } #[doc = r" Proxy"] pub struct _SEG_TMPW<'a> { w: &'a mut W, } impl<'a> _SEG_TMPW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SEG_TMPW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 28; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Start MAA Calculation"] #[inline] pub fn start(&self) -> STARTR { STARTR::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 1:3 - Select Operation Type"] #[inline] pub fn opsel(&self) -> OPSELR { OPSELR::_from({ const MASK: u8 = 7; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 4 - Optimized Calculation Control"] #[inline] pub fn ocalc(&self) -> OCALCR { OCALCR::_from({ const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 5 - Interrupt Flag - Calculation Done"] #[inline] pub fn if_done(&self) -> IF_DONER { IF_DONER::_from({ const MASK: bool = true; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 6 - MAA Interrupt Enable"] #[inline] pub fn inten(&self) -> INTENR { INTENR::_from({ const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 7 - Interrupt Flag - Error"] #[inline] pub fn if_error(&self) -> IF_ERRORR { IF_ERRORR::_from({ const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 8:9 - Operand A Memory Offset Select"] #[inline] pub fn ofs_a(&self) -> OFS_AR { OFS_AR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 10:11 - Operand B Memory Offset Select"] #[inline] pub fn ofs_b(&self) -> OFS_BR { OFS_BR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 12:13 - Exponent Memory Offset Select"] #[inline] pub fn ofs_exp(&self) -> OFS_EXPR { OFS_EXPR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 14:15 - Modulus Memory Select"] #[inline] pub fn ofs_mod(&self) -> OFS_MODR { OFS_MODR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 16:19 - Operand A Memory Segment Select"] #[inline] pub fn seg_a(&self) -> SEG_AR { SEG_AR::_from({ const MASK: u8 = 15; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 20:23 - Operand B Memory Segment Select"] #[inline] pub fn seg_b(&self) -> SEG_BR { SEG_BR::_from({ const MASK: u8 = 15; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 24:27 - Result Memory Segment Select"] #[inline] pub fn seg_res(&self) -> SEG_RESR { SEG_RESR::_from({ const MASK: u8 = 15; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 28:31 - Temporary Memory Segment Select"] #[inline] pub fn seg_tmp(&self) -> SEG_TMPR { SEG_TMPR::_from({ const MASK: u8 = 15; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Start MAA Calculation"] #[inline] pub fn start(&mut self) -> _STARTW { _STARTW { w: self } } #[doc = "Bits 1:3 - Select Operation Type"] #[inline] pub fn opsel(&mut self) -> _OPSELW { _OPSELW { w: self } } #[doc = "Bit 4 - Optimized Calculation Control"] #[inline] pub fn ocalc(&mut self) -> _OCALCW { _OCALCW { w: self } } #[doc = "Bit 5 - Interrupt Flag - Calculation Done"] #[inline] pub fn if_done(&mut self) -> _IF_DONEW { _IF_DONEW { w: self } } #[doc = "Bit 6 - MAA Interrupt Enable"] #[inline] pub fn inten(&mut self) -> _INTENW { _INTENW { w: self } } #[doc = "Bit 7 - Interrupt Flag - Error"] #[inline] pub fn if_error(&mut self) -> _IF_ERRORW { _IF_ERRORW { w: self } } #[doc = "Bits 8:9 - Operand A Memory Offset Select"] #[inline] pub fn ofs_a(&mut self) -> _OFS_AW { _OFS_AW { w: self } } #[doc = "Bits 10:11 - Operand B Memory Offset Select"] #[inline] pub fn ofs_b(&mut self) -> _OFS_BW { _OFS_BW { w: self } } #[doc = "Bits 12:13 - Exponent Memory Offset Select"] #[inline] pub fn ofs_exp(&mut self) -> _OFS_EXPW { _OFS_EXPW { w: self } } #[doc = "Bits 14:15 - Modulus Memory Select"] #[inline] pub fn ofs_mod(&mut self) -> _OFS_MODW { _OFS_MODW { w: self } } #[doc = "Bits 16:19 - Operand A Memory Segment Select"] #[inline] pub fn seg_a(&mut self) -> _SEG_AW { _SEG_AW { w: self } } #[doc = "Bits 20:23 - Operand B Memory Segment Select"] #[inline] pub fn seg_b(&mut self) -> _SEG_BW { _SEG_BW { w: self } } #[doc = "Bits 24:27 - Result Memory Segment Select"] #[inline] pub fn seg_res(&mut self) -> _SEG_RESW { _SEG_RESW { w: self } } #[doc = "Bits 28:31 - Temporary Memory Segment Select"] #[inline] pub fn seg_tmp(&mut self) -> _SEG_TMPW { _SEG_TMPW { w: self } } }
C
UTF-8
2,117
3.0625
3
[]
no_license
/*------------------------------------------------*/ /*Maxime ESCOURBIAC */ /* */ /*Principe du tp: */ /*Version du motus a 5 lettres */ /*cette version utilisera un dico predefini */ /*par l'utilisateur dans dico.txt */ /*------------------------------------------------*/ #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { FILE * fic; int number,hasard,i,j; int essai = 0; char name[]="dico.txt"; char tableau [255][255]; char myst[6]; char reponse[255]; char visu[6]; fic = fopen(name,"r"); fscanf(fic,"%d",&number); /*initialisation du tableau*/ for(i=0;i<number;i++) { fscanf(fic,"%s",tableau[i]); } srand(time(0)); /*choix du mot au hasard*/ hasard = rand()%number; strcpy(myst,tableau[hasard]); /*pour eviter de manipuler le tab principal */ printf("vous avez 5 essais pour trouver le mot mystere \n"); do { printf("il vous reste %d essais\n",5-essai); essai++; printf("veuillez tapez votre essai\n"); scanf("%s", reponse); if(strlen(reponse)==5) { for(i=0;i < 5;i++) /*boucle pour tester element par element*/ { if(reponse[i]==myst[i]) visu[i]=myst[i]; /*lettre juste*/ else { j=0; while(j<5 && reponse[i]!=myst[j]) /*cas de la lettre mal placee*/ { j++; } if(j==5)visu[i]='#'; /*si lettre inexistante*/ else visu[i]='_'; } } printf("reponse\n"); printf("%s\n",visu); } else printf("essai perdu car votre reponse n'a pas 5 caracteres\n"); }while(essai < 5 && strcmp(reponse,myst)); if(!strcmp(reponse,myst))printf("bravo champion\n"); else printf("vous vous etes lourdee\n"); return 0; }
Markdown
UTF-8
21,206
3.46875
3
[]
no_license
--- title: ADODB用法详解 tags: - SQL url: 115.html id: 115 categories: - SQL date: 2017-08-10 17:19:43 --- 1.GetAll方法 我们可以使用GetAll方法代替Execute()方法,该方法返回的结果为一个二维关联数据,这样可以使用foreach或for循环语句处理,非常方便。另外,GetAll取得的数组与Smarty模板的foreach配合得非常好。 我们一起看下面的脚本例子: <?php include\_once("libs/adodb/adodb.inc.php"); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", "root", "root", "library") or die("Unable to connect"); // 构造并执行一个查询 $query = "SELECT * FROM library"; $result = $db->GetAll($query) or die("Error in query: $query. " . $db->ErrorMsg()); // 清除无用的对象 $db->Close(); // 可以使用print\_r打印该数组的内容 // print\_r($result); exit(0); // 遍历记录集,显示列的内容:TITLE 和AUTHOR foreach ($result as $row){ echo $row\[1\] . " - " . $row\[2\] . "\\n"; } // 取得和显示返回的记录行数 echo "\\n\[" . sizeof($result) . " 行记录被返回\]\\n"; ?> GetAll()方法取得记录集后,产生一个二维数组,类似于下面的样子: Array ( \[0\] => Array ( \[0\] => 14 \[id\] => 14 \[1\] => Mystic River \[title\] => Mystic River \[2\] => Dennis Lehane \[author\] => Dennis Lehane ) \[1\] => Array ( \[0\] => 15 \[id\] => 15 \[1\] => For Kicks \[title\] => For Kicks \[2\] => Dick Francis \[author\] => Dick Francis ) //下略 ) 我们在数组一章,提到过这类混合数组最适合用foreach来处理。这种方法是对Execute()方法的补充或替代,尤其适合在遍历查询整个表时使用。 另外,ADODB还提供取得一条记录的方法:GetOne()。 2.GetOne()方法 ADODB有个比较直接的方法可以比较方便地检测某条记录是否存在,那就是它的GetOne($sql)方法。 该方法返回查询记录的第1条第1个字段名的值,如果执行过程中出现错误,则返回布尔值false。 我们可以检测这个值是否存在: <?php Include\_once("libs/adodb/adodb.inc.php"); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", “root”, “passwd”, “adodb”) or die("Unable to connect!"); $rs = $db->GetOne("SELECT * FROM library WHERE id='$id'"); if($rs){ echo '记录存在'; }else { echo '记录不存在'; } ?> 不过这样有一个问题是,如果数据表中id=$id的记录有多条,不仅仅要知道是否存在有这样一条记录,还要把这条记录提取出来,则可以使用ADODB的GetRow()方法。 3.GetRow()方法 <?php Include\_once("libs/adodb/adodb.inc.php"); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", “root”, “passwd”, “adodb”) or die("Unable to connect!"); $rs = $db->GetRow("SELECT * FROM library WHERE id='$id'"); if(is\_array($rs)){ echo '记录存在'; print\_r($rs); } else { echo '记录不存在'; } ?> 需要注意的是,GetOne($sql) 和 GetRow($sql) 都能得到一条特定的记录,或者得到该记录不存在的信息,但是如果符合查询条件的记录存在多条时,则这两个方法只传回第一条记录,其他的都自动抛弃。 如果只要得到查询结果的行数,则可以使用结果集方法中的RecordCount()方法。 4.取得返回的记录行数 ADODB还提供了一批实用功能,如在进行查询时,提供了非常有用的RecordCount() 和FieldCount()方法,分别返回记录的数量和字段的数量,以下是应用这两个方法的例子。 <?php include("libs/adodb/adodb.inc.php"); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", “root”, “passwd”, “adodb”) or die("Unable to connect!"); // 构造并执行一个查询 $query = "SELECT * FROM library"; $result = $db->Execute($query) or die("Error in query: $query. " . $db->ErrorMsg()); // 取得和显示返回的记录行数 echo $result->RecordCount() . " 行记录被返回\\n"; // 取得和显示返回的字段个数 echo $result->FieldCount() . " 个字段被返回\\n"; // clea up $db->Close(); ?> 我们可以使用FetchField()方法取得字段的信息,其中含有该字段的详细资料,包括名称和类型等,请看如下的脚本例子。 <?php include("libs/adodb/adodb.inc.php"); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", "root", "passwd", "adodb") or die("Unable to connect!"); // 构造并执行一个查询 $query = "SELECT * FROM library"; $result = $db->Execute($query) or die("Error in query: $query. " . $db->ErrorMsg()); // 取得记录集中字段的结构信息 for($x=0; $x<$result->FieldCount(); $x++){ print\_r($result->FetchField($x)); } // 清理无用的对象 $db->Close(); ?> 下面输出的是有关id字段的结构信息。 stdClass myMagicbject ( \[name\] => id \[table\] => library \[def\] => \[max\_length\] => 3 \[not\_null\] => 1 \[primary\_key\] => 1 \[multiple\_key\] => 0 \[unique\_key\] => 0 \[numeric\] => 1 \[blob\] => 0 \[type\] => int \[unsigned\] => 1 \[zerofill\] => 0 \[binary\] => ) 5.其他相关方法 当执行一个INSERT查询时,如果该表的主键是一个自动增量的字段,则可以使用ADODB的insert\_id()方法,来获得最后数据插入时自动产生的增量值。 <?php include\_once(“libs/adodb/adodb.inc.php”); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", “root”, “root”, “adodb”) or die("Unable to connect!"); // 构造并执行INSERT插入操作 $title = $db->qstr("PHP5与MySQL5 Web开发技术详解"); $author = $db->qstr("杜江"); $query = "INSERT INTO library (title, author) VALUES ($title, $author)"; $result = $db->Execute($query) or die("Error in query: $query. " . $db->ErrorMsg()); // 显示插入的记录号 if ($result){ echo "最后插入的记录ID: " . $db->Insert\_ID(); } // 清理无用的对象 $db->Close(); ?> 脚本中的qstr()方法,功能是过滤SQL查询中的非法字符。 执行后,即无论查询(SELECT)、删除(DELETE)或修改(UPDATE)数据,如果想知道是否对表有影响,可以使用affected\_rows()方法,它可以告诉我们操作后有多少(记录)行受到了影响。请看下面的脚本例子: <?php include\_once("libs/adodb/adodb.inc.php"); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", “root”, “root”, “adodb”) or die("Unable to connect!"); // 构造并执行一个查询 $query = "DELETE FROM library WHERE author = 'J. Luser'"; $result = $db->Execute($query) or die("Error in query: $query. " . $db->ErrorMsg()); // 取得和显示执行后影响的记录行数 if ($result){ echo $db->Affected\_Rows() . " 行已被删除"; } // 清理无用的对象 $db->Close(); ?> 6.限制查询结果 上面 我们讨论了如何通过使用一个数据库库函数使应用程序更简洁,更易于移植。比如从MS SQL Server转移到MySQL,在MS SQL Server中使用指令“SELECT TOP 15 name FROM employee”取得数据的前15条,可在MySQL中却不支持这种写法,而要写成:SELECT name FROM employee LIMIT 15。 它似乎对我们敲响了警钟,应该停止在查询语句中使用非标准SQL指令,而去认真地学习标准的SQL。 幸运的是,ADODB有一个处理 LIMIT的方法:SelectLimit(),这样我们就根本不用管连接的是MySQL还是MS SQL Server,ADODB会在底层为我们自动转换,请见下面的脚本例子: <?php include\_once("libs/adodb/adodb.inc.php"); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", "root", "passwd", "adodb") or die("Unable to connect!"); // 构造并执行一个查询 // 我们要取得5行记录,从符合记录的第3行开始取 $query = "SELECT * FROM library"; $result = $db->SelectLimit($query, 5, 3) or die("Error in query: $query. " . $db->ErrorMsg()); // 遍历记录集 while (!$result->EOF) { echo $result->fields\[1\] . " - " . $result->fields\[2\] . "\\n"; $result->MoveNext(); } // 清理无用的对象 $db->Close(); ?> 在这个例子中,selectlimit()方法类似于MySQL的LIMIT语句,可用于控制从某行开始查询,到某行的结果,从而取得我们指定的记录集。 我们可以利用ADODB提供的MetaDatabases()方法取得当前服务器中所有数据库的清单。还有一个方法和它很类似,即使用MetaTables()方法可以取得当前库中所有表的清单。请看下面的例子: <?php include(“libs/adodb/adodb.inc.php”); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", "root", "passwd", "adodb") or die("Unable to connect!"); // 取得数据列表 echo "数据库:\\n"; foreach($db->MetaDatabases() as $d){ echo "* $d\\n"; } // 取得数据表清单 echo "\\n当前数据库下的表:\\n"; foreach($db->MetaTables() as $table){ echo "* $table\\n"; } // 清理无用的对象 $db->Close(); ?> 7.快速存取 有时,我们需要对一些不同的值做一些特殊的查询,比如一系列的INSERT(插入)语句。ADODB类提供了两个方法,可以使我们既节约时间又节省系统的开销,请看如下示例: <?php include(“libs/adodb/adodb.inc.php”); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", "root", "passwd", "adodb") or die("Unable to connect!"); // 构造准备查询,使用参数绑定 $query = $db->Prepare("INSERT INTO library (title, author) VALUES (?, ?)"); // 从CSV 中取得要插入的标题和作者名称 $data = file("./book\_list.csv"); // 遍历该文件,并执行插入操作 foreach ($data as $l){ $arr = explode(",", $l); // 插入值并绑定准备语句 $result = $db->Execute($query, array($arr\[0\], $arr\[1\])) or die("Error in query: $query. " . $db->ErrorMsg()); } // 清理无用的对象 $db->Close; ?> prepare()函数,把一个SQL查询作为参数,读取一个查询,但并不立即执行。prepare()返回一个句柄给一个prepare查询,当保存和传递给Execute()方法后,则立即执行该查询。 8.处理事务 处理事务是许多应用程序的一个重要的特征(比如,钱从你的账户转出,然后转入到某个人的账户中。只要其中任意一步操作失败,这整个过程都必须被认定为失败。不然,钱被划出,而没有进对方的账户;或者,钱没有划出,但对方账户无端多了一笔钱)。 处理事务可以在代码级上进行机警地管理控制。常数错误检查被用来判断执行COMMIT(事务的所有各项都正确,执行正确,结束事务)还是执行ROLLBACK(事务中有错误,所有改动需要恢复原来状况)。 现在的数据库系统绝大多数都支持事务,如MySQL、Oracle、MS SQL Server等,ADODB提供一个非常好的功能,能够让你更透明地使用这一特性。请看下面的例子: <?php include(“libs/adodb/adodb.inc.php”); // 创建一个mysql连接实例对 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", “root”, “root”, “adodb”) or die("Unable to connect!"); //关闭auto-commit自动提交事务 // 开始事务处理语句块 $db->BeginTrans(); // 第一次查询 $query = "INSERT INTO library (title, author) VALUES ('测试用书', '佚名')"; $result = $db->Execute($query) or die("Error in query: $query. " . $db->ErrorMsg()); //使用第一次查询返回的ID号 if ($result){ $id = $db->Insert\_ID(); $query = "INSERT INTO purchase\_info (id, price) VALUES ($id, 'RMB 31.9')"; $result = $db->Execute($query) or die("Error in query: $query. " . $db->ErrorMsg()); } // 如果操作成功 if ($result){ // 事务提交 $db->CommitTrans(); }// 否则回滚 else{ $db->RollbackTrans(); } // 清理无用的对象 $db->Close; ?> 该脚本首先 需要关掉数据库的auto commit功能,通过begintrans()方法来处理,这种方法也标志着一个事务的开始。可以使用CommitTrans()或 RollbackTrans()函数来处理操作,一旦auto commit已经关掉,你就可以任意执行所需要的查询,确认事务的查询执行无误并完毕后,由我们自己决定何时执行commit操作。 每一 次执行Execute()事务块后,它会返回一个布尔值,告诉我们是否成功地执行了查询。可以跟踪到这个值,以及使用的时间,以决定是否要进行整个交易行 为。一旦你相信一切都没问题,则告诉数据库committrans()方法;如果发现有错误发生,则可以进行回滚操作——执行 rollbacktrans()方法。 值得注意的是,注意您的数据库类型是否支持这些事务函数,前面已经说过,MySQL的InnoDB类型表支持事务,但是MyISAM类型并不支持。 9.使用缓存查询 在一个动态页面中,如果其中的一个查询指令很少改变且频繁被执行,我们则可以使用ADODB的缓存功能,可以将查询指令的结果缓存成静态文件,从而提高PHP脚本的性能。 当试图通过缓存来提高你的应用程序的性能之前,建议先去优化查询指令再开始本操作,这样才会起到事半功倍之效果。 ADODB最棒的功能就是提供查询缓存的功能。缓存可以大大改善应用程序的性能,尤其是网站系统,因为大部分用户都是在浏览网站,数据库完成的任务多半是查询(SELECT操作)。为了更好地理解与应用缓存查询的功能,我们来看下面的脚本例子。 <?php include\_once("libs/adodb/adodb.inc.php"); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", "root", "root", "adodb") or die("Unable to connect!"); // 构造并执行一个查询 $query = "SELECT * FROM library"; $result = $db->Execute($query) or die("Error in query: $query. " . $db->ErrorMsg()); // 遍历返回的记录集,显示列数据的内容 TITLE 和 AUTHOR while (!$result->EOF) { echo $result->fields\[1\] . " - " . $result->fields\[2\] . "\\n"; $result->MoveNext(); } // 显示取得的记录行数 echo "\\n\[" . $result->RecordCount() . " 行记录被返回\]\\n"; // 关闭数据库连接 $db->Close(); ?> 这段代码使用ADODB进行一个SELECT操作。比如说,这就是您的网站,平均有每分钟5000次的点击(PV,Page View)量,那么数据库系统每小时至少要被查询3万次以上,可以想象,这对我们的MySQL数据库的负载是相当繁重的。 因此ADODB提供了缓存的功能,可以将经常查询的结果保存起来,进而降低数据库服务器的负荷,同时也向用户提供更快速的内容响应。 下面是修改上面的脚本,改为使用CacheExecute来进行缓存查询的示例: <?php include("libs/adodb/adodb.inc.php"); //设置缓存保存的路径,.表示当前目录 $ADODB\_CACHE\_DIR = '.'; //为了管理方便,实际开发环境请指向到独立的目录中,如/tmp/adodb // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", "root", "passwd", "adodb") or die("Unable to connect!"); // 构造并执行一个查询 $query = "SELECT * FROM library"; $result = $db->CacheExecute(300,$query) or die("Error in query: $query. " . $db->ErrorMsg()); // 遍历返回的记录集,显示列数据的内容 TITLE 和 AUTHOR while (!$result->EOF) { echo $result->fields\[1\] . " - " . $result->fields\[2\] . "\\n"; $result->MoveNext(); } // 取得和显示返回的记录行数 echo "\\n\[" . $result->RecordCount() . " 行记录被返回\]\\n"; // 关闭数据库连接 $db->Close(); ?> CacheExecute()方法的第一个参数是缓存文件(缓存文件被命名为adodb_*.cache)将被保留的时间,以秒计时;第二个参数是SQL声明。第一个参数是可选择的,若没有限定时间,默认值是3600秒,也就是1个小时。 值得一提的是,使用CacheExcute()方法时,需要将php.ini中的参数magic\_quotes\_runtime设为0。 也可以根据需要,在程序运行时动态修改它的值: set\_magic\_quotes\_runtime(0); 注意:将上述代码放到调用数据库的指令之前,我们还可以在任何时候,通过调用CacheFlush()来清除过时的缓存。 10.生成下拉列表菜单 ADODB特意为Web开发任务提供几个通用的方法。其中,最有用的是GetMenu()方法,通过抽取数据库的记录集,自动地生成表单及菜单列表框。 下面介绍的就是从数据库动态构建下拉菜单(Option)的例子。 <html> <head></head> <body> <?php include\_once("libs/adodb/adodb.inc.php"); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", "root", "root", "library") or die("Unable to connect!"); // 构造并执行一个查询 $query = "SELECT title, id FROM library"; $result = $db->Execute($query) or die("Error in query: $query. " . $db->ErrorMsg()); //显示HTML下拉列表菜单 echo $result->GetMenu("library", '', false); // 关闭数据库连接 $db->Close(); ?> </body> </html> GetMenu()方法需要传入参数,用来控制列表框的行为。上例中第一个参数是列表框的名字(这个例子为“library”);第二个参数是显示时默认的值,可以为空,从第一个记录开始;第三个参数,指定列表框的项目是否为空;第四个参数,控制是否允许用户多选。 上例的显示结果如下: <select name="library" > <option value="15">Mystic River</option> <option value="16">Where Eagles Dare</option> <option value="17">XML and PHP</option> </select> 可以看到,该列表菜单内容是从library表抽取的记录,列表框的名字为“library”,在记录集中,ID是菜单选项的值,名称为菜单框显示的元素。 由此可以看出,GetMenu()方法可以大幅度简化Web开发任务,大大减少代码量。 11.输出到文件 ADODB还允许我们将记录输出为一个不同形式的文件:如逗号分隔符CSV文件,制表符表格,甚至于HTML形式的表格。 这些功能属于ADODB的附属功能,在使用时需要包含相关ADODB类文件,下面是样例的内容。 <?php include("libs/adodb/adodb.inc.php"); // 包含转换方法的文件 include\_once("libs/adodb/toexport.inc.php"); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", "root", "passwd", "library") or die("Unable to connect!"); // 构造并执行一个查询 $query = "SELECT title, id FROM library"; $result = $db->Execute($query) or die("Error in query: $query. " . $db->ErrorMsg()); // 返回一个CSV字符串 echo rs2csv($result); // 关闭数据库的连接 $db->Close(); ?> 输出结果如下: title,id Mystic River,15 Where Eagles Dare,16 XML and PHP,17 我们也可以去除结果中第一行,即字段的名称,使用脚本格式如下: // 返回一个 CSV 字符串 echo rs2csv($result, false); 脚本的输出结果将没有字段名称,如下: Mystic River,15 Where Eagles Dare,16 XML and PHP,17 ADODB还提供生成制表符或分隔符文件功能,使用rs2tab()方法: <?php include("libs/adodb/adodb.inc.php"); // 包含转换方法的文件 include("toexport.inc.php"); //创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", "root", "root", "library") or die("Unable to connect!"); // 构造并执行一个查询 $query = "SELECT title, id FROM library"; $result = $db->Execute($query) or die("Error in query: $query. " . $db->ErrorMsg()); // 返回一个TAB制表符分隔的字符串 echo rs2tab($result); // 关闭数据库连接 $db->Close(); ?> 显示结果如下: title   id Mystic River   15 Where Eagles Dare   16 XML and PHP   17 ADODB还提供生成HTML表格的功能,使用rs2html()方法: <html> <head></head> <body> <?php include\_once(“libs/adodb/adodb.inc.php”); // 包含转换方法的文件 include_once("libs/adodb/tohtml.inc.php"); // 创建一个mysql连接实例对象 $db = NewADOConnection("mysql"); // 打开一个数据库连接 $db->Connect("localhost", "root", "passwd", "library") or die("Unable to connect!"); // 构造并执行一个查询 $query = "SELECT title, id FROM library"; $result = $db->Execute($query) or die("Error in query: $query. " . $db->ErrorMsg()); // 返回一个HTML格式的表格 echo rs2html($result); // 关闭数据库连接 $db->Close(); ?> </body> </html>   原文链接:[http://blog.163.com/kefan_1987/blog/static/8978013120126215158950/](http://blog.163.com/kefan_1987/blog/static/8978013120126215158950/)
Java
UTF-8
9,193
1.921875
2
[]
no_license
package com.hgsoft.carowner.action; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.struts2.ServletActionContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import com.hgsoft.carowner.entity.CarTraveltrack; import com.hgsoft.carowner.service.CarTraveltrackService; import com.hgsoft.common.action.BaseAction; import com.hgsoft.common.utils.DateUtil; import com.hgsoft.common.utils.ExcelUtil; import com.hgsoft.common.utils.Pager; import com.hgsoft.common.utils.StrUtil; /** * 行程数据查询及导出 * * @author lsw * */ @Controller @Scope("prototype") public class TravelTrackAction extends BaseAction { // private CarTraveltrack carTraveltrack; private String obdSn; private String obdMSn; private String startTime; private String endTime; private String quickenNum; private String quickSlowDown; private String voltageFlag; private String voltage; private String driverTimeFlag; private String driverTime; private String distanceFlag; private String distance; private String type; private List<CarTraveltrack> carTraveltracks; @Resource private CarTraveltrackService carTraveltrackService; /* * 返回行程查询列表 */ public List<CarTraveltrack> getCarTravelTrackList(Pager pager) { String obdSN = "";//表面号解析成设备号 if (!StringUtils.isEmpty(obdMSn)) { //将表面号解析成设备号 try { obdSN = StrUtil.obdSnChange(obdMSn);// 设备号 if(StringUtils.isEmpty(obdSN)){ return null; } } catch (Exception e) { e.printStackTrace(); return null; } } if(!StringUtils.isEmpty(obdSn) && !StringUtils.isEmpty(obdSN)){ if(!obdSn.equals(obdSN)){ return null; }else{ obdSN = ""; } } Map<String, Object> map = new HashMap<>(); Integer total=0; if (!StringUtils.isEmpty(obdSn)) { map.put("obdSn", obdSn); total++; } if(!StringUtils.isEmpty(obdSN)){ map.put("obdSn", obdSN); total++; } if (!StringUtils.isEmpty(quickenNum)) { map.put("quickenNum", Long.parseLong(quickenNum)); total++; } if (!StringUtils.isEmpty(quickSlowDown)) { map.put("quickSlowDown", Integer.parseInt(quickSlowDown)); total++; } if (!StringUtils.isEmpty(voltage)) { map.put("voltage", Double.parseDouble(voltage)); map.put("voltageFlag", voltageFlag); total++; } if (!StringUtils.isEmpty(driverTime)) { map.put("driverTime", Integer.parseInt(driverTime)); map.put("driverTimeFlag", driverTimeFlag); total++; } if (!StringUtils.isEmpty(distance)) { map.put("distance", Long.parseLong(distance)); map.put("distanceFlag", distanceFlag); total++; } if (!StringUtils.isEmpty(type)) { map.put("type", Integer.parseInt(type)); total++; } if (!StringUtils.isEmpty(startTime)) { map.put("startTime", startTime); total++; } if (!StringUtils.isEmpty(endTime)) { map.put("endTime", endTime); total++; } map.put("paramsTotal", total); return carTraveltrackService.queryByParams(pager, map); } /* * 返回行程查询结果 */ public String travelTrackSearch() { if (StrUtil.arraySubNotNull(obdSn,obdMSn,quickenNum,quickSlowDown,voltage,driverTime,distance,type,startTime,endTime)) { carTraveltracks = getCarTravelTrackList(pager); }else{ //设置默认时间 Calendar c = Calendar.getInstance(); Date now = c.getTime(); endTime=DateUtil.getTimeString(now, "yyyy-MM-dd HH:mm:ss"); c.add(Calendar.MONTH, -1); Date s= c.getTime(); startTime=DateUtil.getTimeString(s, "yyyy-MM-dd HH:mm:ss"); } return "travelTrackSearch"; } /* * 导出excel */ public String exportExcel() { String[] headers = { "ID", "设备号", "导入时间", "行程结束", "行程序号", "行程开始", "距离", "最大速度", "超速次数", "急刹车次数", "急转弯次数", "急加速次数", "急减速次数", "急变道次数", "怠速次数", "发动机最高水温", "发动机最高工作转速", "发动机最高工作转速次数", "车速转速不匹配次数", "电压值", "总油耗", "平均油耗", "疲劳驾驶时长", "行程类型", "报文" }; String[] cloumn = { "id", "obdsn", "insesrtTime", "travelEnd", "travelNo", "travelStart", "distance", "speed", "overspeedTime", "brakesNum", "quickTurn", "quickenNum", "quickSlowDown", "quickLaneChange", "idling", "temperature", "rotationalSpeed", "engineMaxSpeed", "speedMismatch", "voltage", "totalFuel", "averageFuel", "driverTime", "type", "message" }; String fileName = "行程数据表.xls"; String filepath = ServletActionContext.getServletContext().getRealPath("/")+ fileName; List<CarTraveltrack> carTraveltracks = getCarTravelTrackList(null); List<HashMap<String, Object>> lists = new ArrayList<>(); for (CarTraveltrack carTrack : carTraveltracks) { HashMap<String, Object> map = new HashMap<>(); map.put("id", carTrack.getId()); map.put("obdsn", carTrack.getObdsn()); map.put("insesrtTime", carTrack.getInsesrtTime()); map.put("travelEnd", carTrack.getTravelEnd()); map.put("travelNo", carTrack.getTravelNo()); map.put("travelStart", carTrack.getTravelStart()); map.put("distance", carTrack.getDistance()); map.put("speed", carTrack.getSpeed()); map.put("overspeedTime", carTrack.getOverspeedTime()); map.put("brakesNum", carTrack.getBrakesNum()); map.put("quickTurn", carTrack.getQuickTurn()); map.put("quickenNum", carTrack.getQuickenNum()); map.put("quickSlowDown", carTrack.getQuickSlowDown()); map.put("quickLaneChange", carTrack.getQuickLaneChange()); map.put("idling", carTrack.getIdling()); map.put("temperature", carTrack.getTemperature()); map.put("rotationalSpeed", carTrack.getRotationalSpeed()); map.put("engineMaxSpeed", carTrack.getEngineMaxSpeed()); map.put("speedMismatch", carTrack.getSpeedMismatch()); map.put("voltage", carTrack.getVoltage()); map.put("totalFuel", carTrack.getTotalFuel()); map.put("averageFuel", carTrack.getAverageFuel()); map.put("driverTime", carTrack.getDriverTime()); map.put("type", carTrack.getType()); map.put("message", carTrack.getMessage()); lists.add(map); } ExcelUtil<Object> ex = new ExcelUtil<Object>(); OutputStream out; try { out = new FileOutputStream(filepath); ex.carOwnerExport("行程数据表", headers, lists, cloumn, out); out.close(); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("filepath", filepath); request.setAttribute("fileName", fileName); return "excel"; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public List<CarTraveltrack> getCarTraveltracks() { return carTraveltracks; } public void setCarTraveltracks(List<CarTraveltrack> carTraveltracks) { this.carTraveltracks = carTraveltracks; } public String getObdSn() { return obdSn; } public void setObdSn(String obdSn) { this.obdSn = obdSn; } public String getObdMSn() { return obdMSn; } public void setObdMSn(String obdMSn) { this.obdMSn = obdMSn; } public String getQuickenNum() { return quickenNum; } public void setQuickenNum(String quickenNum) { this.quickenNum = quickenNum; } public String getQuickSlowDown() { return quickSlowDown; } public void setQuickSlowDown(String quickSlowDown) { this.quickSlowDown = quickSlowDown; } public String getVoltageFlag() { return voltageFlag; } public void setVoltageFlag(String voltageFlag) { this.voltageFlag = voltageFlag; } public String getVoltage() { return voltage; } public void setVoltage(String voltage) { this.voltage = voltage; } public String getDriverTimeFlag() { return driverTimeFlag; } public void setDriverTimeFlag(String driverTimeFlag) { this.driverTimeFlag = driverTimeFlag; } public String getDriverTime() { return driverTime; } public void setDriverTime(String driverTime) { this.driverTime = driverTime; } public String getDistanceFlag() { return distanceFlag; } public void setDistanceFlag(String distanceFlag) { this.distanceFlag = distanceFlag; } public String getDistance() { return distance; } public void setDistance(String distance) { this.distance = distance; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
PHP
UTF-8
1,010
2.765625
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class Color extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('color', function($table){ $table->integer('id'); $table->string('color_text'); }); DB::table('color')->insert( array('id' => 1, 'color_text' => 'Red') ); DB::table('color')->insert( array('id' => 2, 'color_text' => 'Blue') ); DB::table('color')->insert( array('id' => 3, 'color_text' => 'Green') ); DB::table('color')->insert( array('id' => 4, 'color_text' => 'Yellow') ); DB::table('color')->insert( array('id' => 5, 'color_text' => 'Orange') ); } /** * Reverse the migrations. * * @return void */ public function down() { // } }
Java
UTF-8
7,121
2.03125
2
[ "Apache-2.0" ]
permissive
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.server.handlers.proxy.mod_cluster; /** * {@code Node} Created on Jun 11, 2012 at 11:10:06 AM * * @author <a href="mailto:nbenothm@redhat.com">Nabil Benothman</a> */ public class NodeConfig { private final String hostname; private final int port; private final String type; private final long id; private final String balancer; private final String domain; private final String jvmRoute; /** * Tell how to flush the packets. On: Send immediately, Auto wait for flushwait time before sending, Off don't flush. * Default: "Off" */ private boolean flushPackets; /** * Time to wait before flushing. Value in milliseconds. Default: 10 */ private final int flushwait; /** * Time to wait for a pong answer to a ping. 0 means we don't try to ping before sending. Value in seconds Default: 10 * (10_000 in milliseconds) */ private final int ping; /** * soft max inactive connection over that limit after ttl are closed. Default depends on the mpm configuration (See below * for more information) */ private final int smax; /** * max time in seconds to life for connection above smax. Default 60 seconds (60_000 in milliseconds). */ private final int ttl; /** * Max time the proxy will wait for the backend connection. Default 0 no timeout value in seconds. */ private final int timeout; NodeConfig(NodeBuilder b) { hostname = b.hostname; port = b.port; type = b.type; id = b.id; balancer = b.balancer; domain = b.domain; jvmRoute = b.jvmRoute; flushPackets = b.flushPackets; flushwait = b.flushwait; ping = b.ping; smax = b.smax; ttl = b.ttl; timeout = b.timeout; } public String getHostname() { return hostname; } public int getPort() { return port; } public String getType() { return type; } /** * Getter for id * * @return the id */ public long getId() { return this.id; } /** * Getter for domain * * @return the domain */ public String getDomain() { return this.domain; } /** * Getter for flushwait * * @return the flushwait */ public int getFlushwait() { return this.flushwait; } /** * Getter for ping * * @return the ping */ public int getPing() { return this.ping; } /** * Getter for smax * * @return the smax */ public int getSmax() { return this.smax; } /** * Getter for ttl * * @return the ttl */ public int getTtl() { return this.ttl; } /** * Getter for timeout * * @return the timeout */ public int getTimeout() { return this.timeout; } /** * Getter for balancer * * @return the balancer */ public String getBalancer() { return this.balancer; } public boolean isFlushPackets() { return flushPackets; } public void setFlushPackets(boolean flushPackets) { this.flushPackets = flushPackets; } public String getJvmRoute() { return jvmRoute; } public static NodeBuilder builder() { return new NodeBuilder(); } public static class NodeBuilder { private String hostname; private int port; private String type; private long id; private String balancer = "mycluster"; private String domain = ""; private String jvmRoute; private boolean flushPackets = false; private int flushwait = 10; private int ping = 10000; private int smax; private int ttl = 60000; private int timeout = 0; private int elected; private NodeStatus status = NodeStatus.NODE_UP; private int oldelected; private long read; private long transfered; private int connected; private int load; NodeBuilder() { } public void setHostname(String hostname) { this.hostname = hostname; } public void setPort(int port) { this.port = port; } public void setType(String type) { this.type = type; } public void setId(long id) { this.id = id; } public void setStatus(NodeStatus status) { this.status = status; } public void setBalancer(String balancer) { this.balancer = balancer; } public void setDomain(String domain) { this.domain = domain; } public void setJvmRoute(String jvmRoute) { this.jvmRoute = jvmRoute; } public void setFlushPackets(boolean flushPackets) { this.flushPackets = flushPackets; } public void setFlushwait(int flushwait) { this.flushwait = flushwait; } public void setPing(int ping) { this.ping = ping; } public void setSmax(int smax) { this.smax = smax; } public void setTtl(int ttl) { this.ttl = ttl; } public void setTimeout(int timeout) { this.timeout = timeout; } public void setElected(int elected) { this.elected = elected; } public void setOldelected(int oldelected) { this.oldelected = oldelected; } public void setRead(long read) { this.read = read; } public void setTransfered(long transfered) { this.transfered = transfered; } public void setConnected(int connected) { this.connected = connected; } public void setLoad(int load) { this.load = load; } public NodeConfig build() { return new NodeConfig(this); } } /** * {@code NodeStatus} */ public enum NodeStatus { /** * The node is up */ NODE_UP, /** * The node is down */ NODE_DOWN, /** * The node is paused */ NODE_PAUSED; } }
C
UTF-8
394
3.546875
4
[]
no_license
/* Program to compute the size of int, float, double and char of Your System */ #include<stdio.h> #include<conio.h> int main(){ int a; float b; double c; char d; printf("Size of int: %d bytes\n",sizeof(a)); printf("Size of float: %d bytes\n",sizeof(b)); printf("Size of double: %d bytes\n",sizeof(c)); printf("Size of char: %d byte\n",sizeof(d)); getch(); }
Markdown
UTF-8
477
2.84375
3
[]
no_license
# Random-Number The computer will think 3 digit number that has no repeating digitd. You will then guess a 3 digit number. The computer will then give back clues. Based on these clues you will guess again until youu break the code with a match."\n" The possible clues are : Close : You've guessed a correct number but in the wrong position Match : You've guessed a correct number in the correct position Nope : You haven;t guess any of the numbers correctly.
Shell
UTF-8
1,206
2.875
3
[]
no_license
#!/bin/bash export X509_USER_PROXY x509up_u46545 echo "Grid Init: " ls -l -h x509up_u46545 JOB_NUMBER=$1 WORK_DIR=`pwd` tar -xzf fileLists.tgz export VO_CMS_SW_DIR=/uscmst1/prod/sw/cms source $VO_CMS_SW_DIR/cmsset_default.sh export SCRAM_ARCH=slc5_amd64_gcc462 scramv1 project CMSSW CMSSW_5_3_8_patch3 cd CMSSW_5_3_8_patch3/src/ mv $WORK_DIR/condor_src.tgz . tar -xzf condor_src.tgz cd SusyAnalysis/SusyNtuplizer/macro eval `scramv1 runtime -sh` make mv $WORK_DIR/ANALYZER . mv $WORK_DIR/filelist_$JOB_NUMBER . mv $WORK_DIR/filelist_outputdir.txt . mv $WORK_DIR/JSON . mv $WORK_DIR/SusyEvent* . echo "Chaining Files from: filelist_$JOB_NUMBER" while read file do sed -i '19i chain.Add("'$file'");' ANALYZER echo "Chaining File: $file" done < filelist_$JOB_NUMBER ls filelist_outputdir.txt output_dir=$(sed -n 1p filelist_outputdir.txt) echo $output_dir root -b -q -l ANALYZER #touch result.root echo "Moving files: root file, analyzer, and filelist" cp *.root $output_dir/hist_analysis_$JOB_NUMBER.root mv ANALYZER $WORK_DIR/ANALYZER_$JOB_NUMBER mv filelist_$JOB_NUMBER $WORK_DIR/filelist_used_$JOB_NUMBER cd $WORK_DIR rm -rf CMSSW_5_3_8_patch3/ rm fileLists.tgz rm *.root #rm filelist_*
Markdown
UTF-8
5,166
3.015625
3
[]
no_license
--- nav: blog categories: - Cinematography comments: true date: 2013-06-03T00:00:00Z title: Stabilization url: /2013/06/03/stabilization/ --- Cinematography is, first and foremost, an artform. That being said, I'd like to also emphasize the caveat that it is a *technical* artform, and requires a certain degree of skill and/or technical proficiency to be able to consistently create artful work. It could be argued that no, this isn't the case, based solely on the promulgation of iDevice and consumer-grade video device footage. This type of footage does not require a modicum of skill, or even practice. In the same way that it is possible to take a fantastic picture with an Android or iOS device, it is *possible* to film usable content with a consumer grade device -- but not only is it technically limiting (based on the sensors, alone), but it offers virtually no control over the footage, other than some basic focus and exposure controls. I would argue that the resulting footage could result in decent quality output if either a) the operator had an artistic eye, and was able to use their technology with some skill/proficiency, or b) they were extremely lucky. However, I digress. One of the most consistently over-used (and misused, incidentally) is "[cinéma vérité][1]". In modern cinematographer parlance, it has come to mean any footage which resembles that of an unskilled operator, which theoretically lends an air of realism and observationalism (see any first year film school book on observational cinema if you're unfamiliar with the concept) to a piece. It's easier, for example, to immerse a viewer in the world of a Zombie Apocalypse if they feel as though they could be the one sitting behind the camera. [1]: https://en.wikipedia.org/wiki/Cinéma_vérité This concept has been expanded, partially through the over-saturation of "[reality television][2]" and "[found footage][3]" genre pieces. Far from being necessitated by the artistic content of those genres, it is rather [much more profitable][4], and can be executed with far crummier equipment and with a lower technical skill (and ostensibly artistic skill) element. I'm not going to argue that there is *no* artistic or technical skill involved in making either of those genres of television or film, as that would be foolhardy -- and there are always exceptions to the general rule. [2]: http://en.wikipedia.org/wiki/Reality_television [3]: http://en.wikipedia.org/wiki/Found_footage_(genre) [4]: http://alifetimeindarkrooms.blogspot.com/2012/02/okay-for-pitys-sake-enough-with-found.html Cinéma vérité is a bit more troubling when used as an excuse for technical incompetence, lack of technique, or lack of foresight and caring. Most recently, I've heard shaky and unstabilized footage "explained away" as being necessitated by the genre of cinéma vérité -- and I'm not buying that excuse. The majority of footage in film can and should be stabilized, as well as planned out and executed in a thoughtful manner. That's where the "art" of cinematography lies; otherwise, you're just a camera jockey, no matter how fancy your equipment may be. As I've said before, the most important piece of equipment you own is your eye; everything else just helps your execution. There is no excuse for shaky footage in this age of [image stabilization systems][5] and [inexpensive stabilizers][6] which you can build for a few dollars worth of parts from your local home improvement store. It adds a lot of cinematographic value and apparent production value to have more stable shots. I'd prefer not to experience vertigo when watching a simple walking tracking shot, when possible. One of my favorite "why the hell did that guy do that" moments was in [G.I. Jane][7] (of which I'm not a fan), where the combat scenes are filmed with what appears to be *intentional* camera shake. Far from transporting the viewer into the middle of the morass, it only conveys confusion and vertigo. Used in more moderate amounts, it could have proved much more effective, in my opinion. [5]: http://www.usa.canon.com/cusa/consumer/standard_display/Lens_Advantage_IS [6]: http://littlegreatideas.com/stabilizer/diy/ [7]: http://www.imdb.com/title/tt0119173/ Even if you're dead-set on the idea of making your next film project using the "cinéma vérité" genre, there are a few things you should consider before proceeding unstabilized: 1. *Does this somehow add to the feel of the film?* If you are introducing camera shake into your cinematography, it should be adding something tangible, like a certain feeling, to a scene. 2. *Am I overusing this?* If you're shooting every shot this way, you might want to reconsider your methodology, unless you're shooting a guerilla documentary. 3. *Am I doing this due to a technical limitation?* If you are using "cinéma vérité" as an excuse for being unable to stabilize your footage, invest in a cheap stabilization system, IS lenses, a tripod, or any of the other ways of creating less shaky footage. They're too inexpensive to let shake stand in the way of otherwise great footage. Good luck!
Markdown
UTF-8
1,635
2.703125
3
[]
no_license
# Système expert - Classification des fruits ## Fonctionnalités Le moteur demande à l'utilisateur des précisions sur le fruit à trouver. A la fin, le moteur retournera le nom du fruit cherché. ## Lancer le programme Il vous faut [CLisp 2.49](https://sourceforge.net/projects/clisp/) installé sur votre système. Dans un terminal, entrez la commande suivante: ``` clisp main.lisp ``` ## Classification des fruits Notre classification se base sur la classification donnée par Jean Duperrex. Vous pouvez la retrouver [en cliquant sur ce lien](http://www.jeanduperrex.ch/Site/Classification_fruits_files/Classification%20FRUITS%20Duperrex.pdf). La classification de Jean Duperrex n'étant pas suffisante pour permettre à un système expert de retrouver un fruit spécifique d'une sous-catégorique, notre travail était de rajouter des règles afin de distinguer chaque fruit. Le fichier Fruits.cmap vous permet de visualiser notre nouvelle classification. ## Architecture ### [main.lisp](main.lisp) Le programme principal. Récupère le contenu de l'ensemble des fichiers du projet et lance le moteur d'inférences. ### [src/modele](src/modele) Les fonctions relatives aux règles et fruits sont retrouvables dans ce dossier. ### [src/interface](src/interface) Les fonctions associées aux interactions utilisateur sont définies ici. ### [src/bases](src/bases) La base de faits et la base de règles sont déclarées dans ce dossier. ## Sources ### Classification des fruits http://www.jeanduperrex.ch/Site/Classification_fruits_files/Classification%20FRUITS%20Duperrex.pdf ## Auteurs * Alexandre Ascenci * Jia Qin * Sabrina Khelifi
Java
UTF-8
797
1.609375
2
[]
no_license
/*************************************************************************** * Product made by Quang Dat * **************************************************************************/ package com.vtc.gateway.scoinv2api.common.dto.response; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * Author : Dat Le Quang * Email: Quangdat0993@gmail.com * Jul 14, 2019 */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class ScoinBasicResponse<R> { @JsonProperty("_code") private int code; @JsonProperty("_data") private R data; @JsonProperty("_message") private String message; }
C#
UTF-8
727
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bill_Manager_App { class BillDatabase { private static BillDatabase instance; private List<BillData> database = new List<BillData>(); private BillDatabase() {} public static BillDatabase Instance { get { if (instance == null) instance = new BillDatabase(); return instance; } } public List<BillData> Database { get { return database; } } public void AddBill(BillData bill) { database.Add(bill); } } }
C#
UTF-8
6,537
3.328125
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Security.Cryptography; //using Message; public static class Utilities { private static string titulo = "Apollo"; public static string Titulo { get { return titulo; } set { titulo = value; } } static Utilities() { Titulo = "Apollo"; } /// <summary> /// Exibe mensagem de confirmação (Com padrão de ícone "question" e de opções "YesNo") /// </summary> /// <param name="message">Mensagem a ser exibida</param> /// <returns></returns> public static bool Confirm(string message) { DialogResult result = MessageBox.Show(message, Titulo, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) return true; else return false; } /// <summary> /// Exibe mensagem ao usuário (Com padrão de ícone "error" e de opções "OkCancel") /// </summary> /// <param name="message">Mensagem a ser exibida</param> /// <returns></returns> public static DialogResult Message(string message) { return MessageBox.Show(message, Titulo, MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } /*/// <summary> /// Exibe mensagem ao usuário (Com padrão de opções "OkCancel") /// </summary> /// <param name="message">Mensagem a ser exibida</param> /// <param name="icon"> /// <para>O ícone a ser exibido</para> /// <para>("error", "info", "warning" ou "question")</para> /// </param> /// <returns></returns> public static DialogResult Message(string message, string icon) { return MessageBox.Show(message, Titulo, MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } /// <summary> /// Exibe mensagem ao usuário /// </summary> /// <param name="message">Mensagem a ser exibida</param> /// <param name = "icon" > /// <para>O ícone a ser exibido</para> /// <para>("error", "info", "warning" ou "question")</para> /// </param> /// <param name="options"> /// <para>As opções do usuário</para> /// <para>("Ok", "OkCancel", "RetryCancel", "YesNo", "YesNoCancel")</para> /// </param> /// <returns></returns> public static DialogResult Message(string message, string icon, string options) { frmMsg Message = new frmMsg(message, icon, options); return Message.ShowDialog(); }*/ /// <summary> /// Retorna entrada codificada em MD5 /// </summary> /// <param name="input">Entrada a ser convertida</param> /// <returns></returns> public static string Md5(string input) { MD5 md5Hash = MD5.Create(); // Converter a String para array de bytes, que é como a biblioteca trabalha. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Cria-se um StringBuilder para recompôr a string. StringBuilder sBuilder = new StringBuilder(); // Loop para formatar cada byte como uma String em hexadecimal for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); } /// <summary> /// Retorna se a entrada tem algum número entre seus caracteres /// </summary> /// <param name="input">Entrada a ser analisada</param> /// <returns></returns> public static bool HasNumber(string input) { return input.Where(x => Char.IsDigit(x)).Any(); } /// <summary> /// Seleciona todo o conteúdo de uma TextBox, se esta estiver vazia /// </summary> /// <param name="textBox">TextBox a ser selecionada</param> public static void SelectTextBoxIfEmpty(TextBox textBox) { if (!String.IsNullOrEmpty(textBox.Text)) { textBox.SelectAll(); } } /// <summary> /// Método DateTime.AddDays que só conta dias úteis /// </summary> /// <param name="originalDate">Data original</param> /// <param name="workDays">Dias a serem adicionados</param> /// <returns></returns> public static DateTime AddWorkdays(DateTime originalDate, int workDays) { DateTime tmpDate = originalDate; while (workDays > 0) { tmpDate = tmpDate.AddDays(1); if (tmpDate.DayOfWeek < DayOfWeek.Saturday && tmpDate.DayOfWeek > DayOfWeek.Sunday && !IsHoliday(tmpDate)) workDays--; } return tmpDate; } /// <summary> /// Checa se determinada data é ou não feriado /// </summary> /// <param name="originalDate">Data a ser analisada</param> /// <returns></returns> public static bool IsHoliday(DateTime originalDate) { // INSERT YOUR HOLIDAY-CODE HERE! return false; } /// <summary> /// Dias de diferença contando somente dias úteis /// </summary> /// <param name="a">Data A</param> /// <param name="b">Data B</param> /// <returns></returns> public static int WorkdaysDifference(DateTime a, DateTime b) { int diff = 0; if (a > b) { while (a.Date > b.Date) { b = AddWorkdays(b, 1); diff++; } } else { while (b.Date > a.Date) { a = AddWorkdays(a, 1); diff++; } } return diff; } /// <summary> /// Dias de diferença contando todos os dias /// </summary> /// <param name="a">Data A</param> /// <param name="b">Data B</param> /// <returns></returns> public static int DaysDifference(DateTime a, DateTime b) { int diff = 0; if (a > b) { while (a.Date > b.Date) { b = b.AddDays(1); diff++; } } else { while (b.Date > a.Date) { a = a.AddDays(1); diff++; } } return diff; } }
JavaScript
UTF-8
3,221
2.640625
3
[]
no_license
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; //var fs = require("fs"); //import './index.html'; var data = require('./la_fourchette_stars_deals.json'); // forward slashes will depend on the file location var monjs=data.la_fourchette_deals; /*var datatest = require('./test.json'); // forward slashes will depend on the file location const monjstest=datatest.la_fourchette_deals;*/ for(var i = 0; i < data.la_fourchette_deals.length; i++) { console.log("Name:" + data.la_fourchette_deals[i].resaurant_name ); } var bgColors = { "Default": "#81b71a", "Blue": "#00B1E1", "Cyan": "#37BC9B", "Green": "#8CC152", "Red": "#E9573F", "Yellow": "#F6BB42", }; class ProductCategoryRow extends React.Component { render() { const stars = this.props.stars; return ( <tr> <th colSpan="5"> {stars} </th> </tr> ); } } class ProductRow extends React.Component { render() { const product = this.props.product; const resaurant_name = product.resaurant_name ; return ( <tr style={{backgroundColor: "rgb(120,120,120)"}}> <td >{resaurant_name}</td> <td> </td> <td >{product.city}</td> <td></td> <td >{product.stars}</td> <td></td> <td >{product.chef}</td> <td></td> <td > <a target="_blank" style={{color: 'black'}} style={{backgroundColor: "rgb(128,128,128)"},{color: 'black'}} href={product.url_restaurant}>{product.name_of_deal}</a></td> </tr> ); } } class ProductTable extends React.Component { render() { const rows = []; let lastCategory = null; this.props.products.forEach((product) => { if (product.stars !== lastCategory) { rows.push( <ProductCategoryRow category={product.stars} key={product.stars} /> ); } rows.push( <ProductRow product={product} key={product.resaurant_name} /> ); lastCategory = product.category; }); return ( <table> <thead> <tr> <fieldset class="column-layout" ><th>Nom du restaurant</th></fieldset> <td></td> <fieldset class="column-layout"> <th>Ville</th></fieldset> <td></td> <fieldset class="column-layout"> <th>Nombre d'étoiles</th></fieldset> <td></td> <fieldset class="column-layout"><th>Chef</th></fieldset> <td></td> <fieldset class="column-layout"> <th >Description : cliquez sur l'offre pour aller sur le lien</th></fieldset> </tr> </thead> <tbody>{rows}</tbody> </table> ); } } class FilterableProductTable extends React.Component { render() { return ( <div> <ProductTable products={this.props.products} /> </div> ); } } const PRODUCTS = monjs; ReactDOM.render( <FilterableProductTable products={PRODUCTS} />, document.getElementById('root') );
C++
UTF-8
1,831
2.546875
3
[]
no_license
// // Created by wang yang on 2016/12/3. // #include "ELBoard.h" #include "../core/ELGameObject.h" ELBoard::ELBoard(ELVector2 size) : size(size) { } ELBoard::~ELBoard() { delete vertexBuffer; } ELGeometryData ELBoard::generateData() { vertexBuffer = new ELGeometryVertexBuffer(); ELGeometryRect rect = { {0.5f * size.x , 0.5f * size.y , 0.0f }, {0.5f * size.x , -0.5f * size.y , 0.0f }, {-0.5f * size.x , -0.5f * size.y , 0.0f }, {-0.5f * size.x , 0.5f * size.y , 0.0f }, {0, 0}, {0, 1}, {1, 1}, {1, 0} }; vertexBuffer->append(rect); // vertexBuffer->caculatePerVertexNormal(); GLfloat *vertex = (GLfloat *)vertexBuffer->data(); ELGeometryData data; glGenBuffers(1, &data.vertexVBO); glBindBuffer(GL_ARRAY_BUFFER, data.vertexVBO); glBufferData(GL_ARRAY_BUFFER, vertexBuffer->rawLength(), vertex, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); data.vertexCount = vertexBuffer->rawLength() / sizeof(ELGeometryVertex); data.vertexStride = sizeof(ELGeometryVertex); data.supportIndiceVBO = false; return data; } void ELBoard::render() { glDisable(GL_CULL_FACE); ELGeometry::render(); glEnable(GL_CULL_FACE); } void ELBoard::update(ELFloat timeInSecs) { ELGeometry::update(timeInSecs); ELVector3 cameraPosition = gameObject()->mainCamera()->position(); ELFloat cx = cameraPosition.x - gameObject()->transform->position.x; ELFloat cz = cameraPosition.z - gameObject()->transform->position.z; ELFloat angle = 0; if (cz == 0) { angle = 0; } else { ELFloat tanVal = cx / cz; angle = atan(tanVal); } gameObject()->transform->quaternion = ELQuaternionMakeWithAngleAndAxis(angle,0,1,0); }
Python
UTF-8
2,533
3.546875
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Feb 17 22:56:46 2017 @author: user """ import math import numpy as np ## Reading in the atoms and their coordinates from a .xyz file ## The input file contains the number of atoms, their respective atomic coordinates ## and their 3D Cartesian coordinates. class Molecule(object): def __init__(self, n_atoms, atoms, coordinates): self.n_atoms = n_atoms self.atoms = atoms self.coordinates = coordinates self.bonds = np.zeros((self.n_atoms, self.n_atoms)) self.angles = [] self.torsions = [] def bond_length(self): """ Calculates the bond length for each bond from the atomic Cartesian coordinates. """ for i in range(self.n_atoms): for j in range(i): x_i = self.coordinates[i][0] y_i = self.coordinates[i][1] z_i = self.coordinates[i][2] x_j = self.coordinates[j][0] y_j = self.coordinates[j][1] z_j = self.coordinates[j][2] self.bonds[i, j] = math.sqrt((x_i - x_j)**2 + (y_i - y_j)**2 + (z_i - z_j)**2) return self.bonds def unit_vectors(self): """ Calculates the unit vector between each atom pair in the molecule """ unit_x = np.zeros((self.n_atoms, self.n_atoms)) unit_y = np.zeros((self.n_atoms, self.n_atoms)) unit_z = np.zeros((self.n_atoms, self.n_atoms)) for i in range(n_atoms): for j in range(i): unit_x[i, j] = -(self.coordinates[i][0] - self.coordinates[j][0]) / self.bonds[i, j] unit_y[i, j] = -(self.coordinates[i][1] - self.coordinates[j][1]) / self.bonds[i, j] unit_z[i, j] = -(self.coordinates[i][2] - self.coordinates[j][2]) / self.bonds[i, j] return unit_x, unit_y, unit_z def bond_angle(self): """ Calcualtes every bond angle in the molecule. """ pass filename = input("Enter the filename: ") file = open(filename, "r") data = file.readlines() n_atoms = int(data[0]) atoms = [] coordinates = [] for line in data[1:]: new_atom = line.split() atomic_number = int(new_atom[0]) x = float(new_atom[1]) y = float(new_atom[2]) z = float(new_atom[3]) atoms.append(atomic_number) coordinates.append((x, y, z)) new_molecule = Molecule(n_atoms, atoms, coordinates) #R = new_molecule.bond_length() #print(R[:,0]) file.close()
JavaScript
UTF-8
612
2.703125
3
[]
no_license
const Util = { inherits(BaseClass, SuperClass) { BaseClass.prototype = Object.create(SuperClass.prototype); // eslint-disable-line no-param-reassign BaseClass.prototype.constructor = BaseClass; // eslint-disable-line no-param-reassign }, randomVec(length) { const deg = 2 * Math.PI * Math.random(); return Util.scale([Math.sin(deg), Math.cos(deg)], length); }, scale(vec, m) { return [vec[0] * m, vec[1] * m]; }, dist(pos1, pos2) { const [x1, y1] = pos1; const [x2, y2] = pos2; return Math.sqrt(((x1 - x2) ** 2) + ((y1 - y2) ** 2)); }, }; export default Util;
PHP
UTF-8
1,456
2.65625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); /** * Contains the HasImages trait. * * @copyright Copyright (c) 2020 Attila Fulop * @author Attila Fulop * @license MIT * @since 2020-12-19 * */ namespace Vanilo\Support\Traits; use Illuminate\Support\Collection; trait HasImagesFromMediaLibrary { protected $mediaCollectionName = 'default'; public function hasImage(): bool { return $this->getMedia()->isNotEmpty(); } public function imageCount(): int { return $this->getMedia()->count(); } public function getThumbnailUrl(): ?string { return $this->getImageUrl('thumbnail'); } public function getThumbnailUrls(): Collection { return $this->getImageUrls('thumbnail'); } public function getImageUrl(string $variant = ''): ?string { $medium = $this->fetchPrimaryMedium(); if (null === $medium) { return null; } return $medium->getUrl($variant); } public function getImageUrls(string $variant = ''): Collection { return $this->getMedia($this->mediaCollectionName)->map(function ($medium) use ($variant) { return $medium->getUrl($variant); }); } private function fetchPrimaryMedium() { $primary = $this->getFirstMedia($this->mediaCollectionName, ['isPrimary' => true]); return $primary ?: $this->getFirstMedia($this->mediaCollectionName); } }
Python
UTF-8
657
4
4
[]
no_license
import math # Exercise 26 - Months to Pay Off a Credit Card # Assign variables: num_months, daily_rate(APR/365), bal, payment bal = float(input('What is your balance (USD)?')) apr = float(input('What is the APR on the card (as a percent)? ')) payment = float(input('What is the monthly payment you can make (USD)? ')) daily_rate = apr/365 def pay_calendar(): """ function to determine how long it takes""" divisor = math.log10(1+(bal/payment)) * (1 - ((1 + daily_rate)**30)) dividend = math.log10(1+daily_rate) months = divisor/dividend*(-1/30) return months time_till = pay_calendar() print(time_till)
Python
UTF-8
1,369
3.53125
4
[]
no_license
from rbt import RedBlackTree class BoundedPriorityQueue: """Simple bounded priority queue which uses a Red Black Tree as the underlying data structure.""" def __init__(self, k): self.maxkey = -float('inf') if k < 0: raise ValueError("k should be larger than 0") self.k = k self._bpq = RedBlackTree() def insert(self, key, item): if self.k == 0: return self.maxkey if len(self._bpq) < self.k or key < self.maxkey: self._bpq.insert(key, item) # O (lg n) if len(self._bpq) > self.k: self._bpq.delete(self._bpq.maximum[0]) # O(lg n) self.maxkey = self._bpq.maximum[0] # (lg n) def __setitem__(self, key, item=0): assert (type(key)) in [int, float], "Invalid type of key." self.insert(key, item) @property def isfull(self): return len(self._bpq) == self.k def iteritems(self): return self._bpq.iteritems() def __repr__(self): return repr(self._bpq.root) def __str__(self): return str(list(self._bpq.iteritems())) if __name__ == '__main__': from random import randint values = [(randint(0, 100), randint(1000, 10000)) for _ in range(10)] bp = BoundedPriorityQueue(1) print(values) for key, val in values: bp[key] = val print(bp)
Java
UTF-8
2,357
2.5
2
[]
no_license
package co.onemeter.oneapp.ui; import android.content.Context; import android.media.AudioManager; import android.media.SoundPool; import java.util.HashMap; /** * Created with IntelliJ IDEA. * User: xuxiaofeng * Date: 13-8-5 * Time: 下午12:00 * To change this template use File | Settings | File Templates. */ public class SoundPoolManager { public final static int USED_AUDIO_STREAM_TYPE=AudioManager.STREAM_MUSIC; private static SoundPool soundPool = new SoundPool(3, USED_AUDIO_STREAM_TYPE, 0); //soundIdInRaw(R.raw.xxx) ----- soundIdInSoundPool private static HashMap<Integer, Integer> soundPoolMapForRaw = new HashMap<Integer, Integer>(); private static void loadSoundFromRaw(Context context,int rawResId) { if(!soundPoolMapForRaw.containsKey(rawResId)) { soundPoolMapForRaw.put(rawResId, soundPool.load(context, rawResId, 1)); Log.i("raw id "+rawResId+" loaded"); } else { Log.i("raw id "+rawResId+" already loaded"); } } public static void playSoundFromRaw(final Context context,final int rawResId) { Integer soundId=soundPoolMapForRaw.get(rawResId); if(null == soundId) { loadSoundFromRaw(context,rawResId); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(500); playSoundFromRaw(context,rawResId); } catch (Exception e) { e.printStackTrace(); } } }).start(); } else { AudioManager mgr = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); int ringtoneMode=mgr.getRingerMode(); if(AudioManager.RINGER_MODE_NORMAL == ringtoneMode) { float streamVolumeCurrent = mgr.getStreamVolume(USED_AUDIO_STREAM_TYPE); float streamVolumeMax = mgr.getStreamMaxVolume(USED_AUDIO_STREAM_TYPE); float volume = streamVolumeCurrent/streamVolumeMax; Log.i("volume cur: "+streamVolumeCurrent+",max:"+streamVolumeMax); soundPool.play(soundId, volume, volume, 1, 0, 1f); } } } public static void release() { soundPool.release(); } }
Python
UTF-8
1,479
3.78125
4
[]
no_license
import math func_glob = lambda x: 6*x**5 - 3* x**4 - x**3 + 9 func_first = lambda x: 30 * x**4 - 12 * x**3 -3* x**2 a = -2; b = -0.2; e = 1e-05 def secant_method(a, b, f): y1 = f(a) y2 = f(b) if y1 * y2 >= 0: print ('no roots') else: c = (y2*a - y1*b)/(y2 - y1); y3 = f(c) while (abs(y3) > e) or math.fabs(b - a) > e: print('a=',a,'b=',b,'f(a)=',f(a), 'f(b)=',f(b)) c = (y2*a - y1*b)/(y2 - y1); y3 = f(c) if y1 * y3 < 0: b = c else: a = c return c def half_divide_method(a, b, f): x = (a + b) / 2 while math.fabs(f(x)) >= e or math.fabs(b-a)>e: x = (a + b) / 2 a, b = (a, x) if f(a) * f(x) < 0 else (x, b) print('a=',a,'b=',b,'f(a)=',f(a), 'f(b)=',f(b)) return (a + b) / 2 def newtons_method(a, b, f, f1): x0 = (a + b) / 2 x1 = x0 - (f(x0) / f1(x0)) while True: if math.fabs(x1 - x0) < e or math.fabs(f(x1))<e: return x1 x0 = x1 x1 = x0 - (f(x0) / f1(x0)) print('x1 =', x1, 'f(x1)=', f(x1)) print('half_divide method:') print ('result:', half_divide_method(a, b, func_glob)) print(' ') print('newtons method:') print ('result:', newtons_method(a, b, func_glob, func_first)) print(' ') print('secant method:') print ('result:', secant_method(a, b, func_glob))
Markdown
UTF-8
1,393
3.734375
4
[ "MIT" ]
permissive
--- layout: post title: 360. Sort Transformed Array category: [Leetcode] description: keywords: ['Math', 'Two Pointers', 'Leetcode', 'Medium'] --- ### [360. Sort Transformed Array](https://leetcode.com/problems/sort-transformed-array) #### Tags: 'Math', 'Two Pointers' <div class="content__u3I1 question-content__JfgR"><div><p>Given a <b>sorted</b> array of integers <i>nums</i> and integer values <i>a</i>, <i>b</i> and <i>c</i>. Apply a quadratic function of the form f(<i>x</i>) = <i>ax</i><sup>2</sup> + <i>bx</i> + <i>c</i> to each element <i>x</i> in the array.</p> <p>The returned array must be in <b>sorted order</b>.</p> <p>Expected time complexity: <b>O(<i>n</i>)</b></p> <div> <p><strong>Example 1:</strong></p> <pre><strong>Input: </strong>nums = <span id="example-input-1-1">[-4,-2,2,4]</span>, a = <span id="example-input-1-2">1</span>, b = <span id="example-input-1-3">3</span>, c = <span id="example-input-1-4">5</span> <strong>Output: </strong><span id="example-output-1">[3,9,15,33]</span> </pre> <div> <p><strong>Example 2:</strong></p> <pre><strong>Input: </strong>nums = <span id="example-input-2-1">[-4,-2,2,4]</span>, a = <span id="example-input-2-2">-1</span>, b = <span id="example-input-2-3">3</span>, c = <span id="example-input-2-4">5</span> <strong>Output: </strong><span id="example-output-2">[-23,-5,1,7]</span> </pre> </div> </div></div></div> ### Solution
Python
UTF-8
2,723
2.96875
3
[]
no_license
import numpy as numpy from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn import datasets from sklearn import svm from sklearn import neighbors import csv import time import seaborn as sns import pandas as pd import matplotlib.pyplot as plt t1=time.time() def load_data(file_name,train_data,target_data,test_data,test_target,split_percentage): with open(file_name,'r') as csvfile: line = csv.reader(csvfile) dataset = list(line) for i in range(1,len(dataset)): temp=[] dataset[i][8]=float(dataset[i][8]) target_data.append(dataset[i][8]) for j in range(8): dataset[i][j]=float(dataset[i][j]) temp.append(dataset[i][j]) train_data.append(temp) x_train, x_test, y_train, y_test = train_test_split(train_data,target_data,test_size=split_percentage,random_state=0) train_data = x_train target_data = y_train test_data = x_test test_target = y_test # print("test_target",test_target) return train_data,target_data,test_data,test_target def res(res): with open(r'res_kaggle_pima.csv','w',newline='') as result: writer = csv.writer(result) count=0 for i in res: count+=1 temp=[count] temp.append(i) writer.writerow(temp) def main(): train_data=[] target_data=[] test_data=[] test_target=[] split_percentage = input("Input the split percentage of test data among original datasets:") split_percentage = float(split_percentage) print("Loading data.......") train_data,target_data,test_data,test_target=load_data(r'diabetes.csv',train_data,target_data,test_data,test_target,split_percentage) myList = list(range(1,100)) neighbors1 = filter(lambda x:x,myList) cv_scores = [] for k in neighbors1: knn = neighbors.KNeighborsClassifier(n_neighbors = k) scores = cross_val_score(knn, train_data, target_data, cv = 10, scoring = 'accuracy') cv_scores.append(scores.mean()) mse = [1-x for x in cv_scores] optimal_k=mse.index(min(mse)) print("the optimal number of neighbors is:"+ str(optimal_k+1)) knn = neighbors.KNeighborsClassifier(n_neighbors=optimal_k+1) print("Starting training KNN model.......") knn.fit(train_data,target_data) print("Training complete!! Starting classifying.......") prediction = knn.predict(test_data) res(prediction) count=0 for i in range(len(prediction)): if prediction[i]==test_target[i]: count+=1 accuracy = count/len(test_target) print("Accuracy is", accuracy) diad=pd.read_csv('diabetes.csv') sns.countplot(x='Age',data=diad) plt.show() if __name__ == '__main__': main() t2=time.time() a=t2-t1 minute=a//60 hour=minute//60 second=a-hour*3600-minute*60 print("Time using totally: "+str(hour)+"h "+str(minute)+"min "+str(second)+"s ")
Java
UTF-8
37,095
2.421875
2
[]
no_license
package UMS.service; import UMS.dbHelper.DB; import UMS.dto.*; import UMS.util.MailUtil; import com.itextpdf.text.*; import com.itextpdf.text.Image; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.chart.AreaChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Alert; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.awt.*; import java.io.File; import java.io.FileOutputStream; import java.security.MessageDigest; import java.sql.*; import java.time.LocalDate; import java.util.Arrays; import java.util.Base64; import static UMS.util.AlertUtil.callAlert; public class DBService { private Connection con; Alert alert = new Alert(Alert.AlertType.NONE); private static byte[] key; private static SecretKeySpec secretKey; private final String secret = "ssshhhhhhhhhhh!!!!"; public DBService() { this.con = DB.getConnection(); } @FXML public void addStock(ItemDTO itemDTO) { int count = 0; String selectQuery = "select * from item where iname = ? "; try { PreparedStatement pst = con.prepareStatement(selectQuery); pst.setString(1, itemDTO.getItemName()); ResultSet rs = pst.executeQuery(); while (rs.next()) { count = Integer.parseInt(rs.getString("count")); System.out.println(count); } String updateCountQuery = "update item set count = ?" + " where iname = ? "; pst = con.prepareStatement(updateCountQuery); pst.setInt(1, count + 1); pst.setString(2, itemDTO.getItemName()); pst.executeUpdate(); System.out.println("insertion done"); } catch (Exception s) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + s); alert.show(); } //order String orderquery = "INSERT INTO orders ( empid,orderdate,aname,iname,qty) VALUES (?, ?, ?,?,?)"; try { PreparedStatement pst = con.prepareStatement(orderquery); pst.setString(1, "Order"); pst.setDate(2, Date.valueOf(LocalDate.now())); pst.setString(3,"Item Added to Stock"); pst.setString(4, itemDTO.getItemName()); pst.setInt(5, 1); pst.executeUpdate(); } catch (Exception s) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessful\n" + s); alert.show(); } } public ObservableList<AddTableDTO> view(String gender, String cloth) { String viewQuery = "select * from item where iname like ?"; double gTotal=0; double cost = 0; ObservableList<AddTableDTO> obList = FXCollections.observableArrayList(); try { PreparedStatement pst = con.prepareStatement(viewQuery); if (!(gender.isEmpty()) && !(cloth.isEmpty())) pst.setString(1, gender.toUpperCase() + "_" + cloth.toUpperCase() + "%"); else if ((gender.isEmpty()) && (cloth.isEmpty())) pst.setString(1, "%"); else if (!(gender.isEmpty()) && (cloth.isEmpty())) pst.setString(1, gender.toUpperCase() + "%"); ResultSet rs = pst.executeQuery(); while (rs.next()) { AddTableDTO addTableDTO=new AddTableDTO(); addTableDTO.setItemName(rs.getString("iname")); addTableDTO.setItemCount(rs.getInt("count")); cost = Double.parseDouble(rs.getString("cost"))*Double.parseDouble(rs.getString("count")); addTableDTO.setCost(cost); gTotal+=cost; addTableDTO.setGrandTotal(gTotal); obList.add(addTableDTO); } } catch (Exception era) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + era); alert.show(); return obList; } return obList; } public String getGrand(String gender, String cloth) { String viewquery = "select * from item where iname like ?"; int gTotal=0; try { PreparedStatement pst = con.prepareStatement(viewquery); if (!(gender.isEmpty()) && !(cloth.isEmpty())) pst.setString(1, gender.toUpperCase() + "_" + cloth.toUpperCase() + "%"); else if ((gender.isEmpty()) && (cloth.isEmpty())) pst.setString(1, "%"); else if (!(gender.isEmpty()) && (cloth.isEmpty())) pst.setString(1, gender.toUpperCase() + "%"); ResultSet rs = pst.executeQuery(); while (rs.next()) { gTotal+=Integer.parseInt(rs.getString("cost"))*Integer.parseInt(rs.getString("count")); } } catch (Exception era) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + era); alert.show(); return ""; } return gTotal+""; } public ObservableList<FindTableDTO> find(EmployeeDTO employeeDTO) { int itemCount = 0; String findQuerry = "SELECT * FROM orders WHERE empid = ?"; ObservableList<FindTableDTO> obList = FXCollections.observableArrayList(); try { PreparedStatement pST = con.prepareStatement(findQuerry); pST.setString(1, employeeDTO.getEmpID()); ResultSet rs = pST.executeQuery(); while (rs.next()) { itemCount++; obList.add(new FindTableDTO(rs.getString("empid"), itemCount, rs.getString("iname"), rs.getString("qty"), rs.getDate("orderdate"))); } } catch (SQLException era) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Not Found\n" + era); alert.show(); return null; } return obList; } public AreaChart view(String type, Date startDate, Date endDate, String itemName, AreaChart areachart) { switch (type) { case "in": { XYChart.Series dataSeries1 = new XYChart.Series(); dataSeries1.setName(itemName); if (itemName.contains("Count")) { switch (itemName) { case "Male Shirts Count": { return getCount("MALE_SHIRT%", startDate, endDate, areachart, "in"); } case "Male Pants Count": { return getCount("MALE_PANT%", startDate, endDate, areachart, "in"); } case "Male Tie Count": { return getCount("MALE_TIE%", startDate, endDate, areachart, "in"); } case "Male Blazer Count": { return getCount("MALE_BLAZER%", startDate, endDate, areachart, "in"); } case "Female Shirts Count": { return getCount("FEMALE_SHIRT%", startDate, endDate, areachart, "in"); } case "Female Pants Count": { return getCount("FEMALE_PANT%", startDate, endDate, areachart, "in"); } case "Female Tie Count": { return getCount("FEMALE_TIE%", startDate, endDate, areachart, "in"); } case "Female Blazer Count": { return getCount("FEMALE_BLAZER%", startDate, endDate, areachart, "in"); } } } else if (itemName.contains("Cost")) { switch (itemName) { case "Male Shirts Cost": { return getCost("MALE_SHIRT%",startDate, endDate, areachart,"in"); } case "Male Pants Cost": { return getCost("MALE_PANT%",startDate, endDate, areachart,"in"); } case "Male Tie Cost": { return getCost("MALE_TIE%",startDate, endDate, areachart,"in"); } case "Male Blazer Cost": { return getCost("MALE_BLAZER%",startDate, endDate, areachart,"in"); } case "Female Shirts Cost": { return getCost("FEMALE_SHIRT%",startDate, endDate, areachart,"in"); } case "Female Pants Cost": { return getCost("FEMALE_PANT%",startDate, endDate, areachart,"in"); } case "Female Tie Cost": { return getCost("FEMALE_TIE%",startDate, endDate, areachart,"in"); } case "Female Blazer Cost": { return getCost("FEMALE_BLAZER%",startDate, endDate, areachart,"in"); } } } else return areachart; } case "out": { XYChart.Series dataSeries1 = new XYChart.Series(); dataSeries1.setName(itemName); if (itemName.contains("Count")) { switch (itemName) { case "Male Shirts Count": { return getCount("MALE_SHIRT%", startDate, endDate, areachart, "out"); } case "Male Pants Count": { return getCount("MALE_PANT%", startDate, endDate, areachart, "out"); } case "Male Tie Count": { return getCount("MALE_TIE%", startDate, endDate, areachart, "out"); } case "Male Blazer Count": { return getCount("MALE_BLAZER%", startDate, endDate, areachart, "out"); } case "Female Shirts Count": { return getCount("FEMALE_SHIRT%", startDate, endDate, areachart, "out"); } case "Female Pants Count": { return getCount("FEMALE_PANT%", startDate, endDate, areachart, "out"); } case "Female Tie Count": { return getCount("FEMALE_TIE%", startDate, endDate, areachart, "out"); } case "Female Blazer Count": { return getCount("FEMALE_BLAZER%", startDate, endDate, areachart, "out"); } } } else if (itemName.contains("Cost")) { switch (itemName) { case "Male Shirts Cost": { return getCost("MALE_SHIRT%", startDate, endDate, areachart,"out"); } case "Male Pants Cost": { return getCost("MALE_PANT%", startDate, endDate, areachart,"out"); } case "Male Tie Cost": { return getCost("MALE_TIE%", startDate, endDate, areachart,"out"); } case "Male Blazer Cost": { return getCost("MALE_BLAZER%", startDate, endDate, areachart,"out"); } case "Female Shirts Cost": { return getCost("FEMALE_SHIRT%", startDate, endDate, areachart,"out"); } case "Female Pants Cost": { return getCost("FEMALE_PANT%", startDate, endDate, areachart,"out"); } case "Female Tie Cost": { return getCost("FEMALE_TIE%", startDate, endDate, areachart,"out"); } case "Female Blazer Cost": { return getCost("FEMALE_BLAZER%", startDate, endDate, areachart,"out"); } } } else return areachart; } default: return new AreaChart(new NumberAxis(),new NumberAxis()); } } AreaChart getCost(String item, Date startDate, Date endDate, AreaChart areaChart,String option){ XYChart.Series dataSeries1 = new XYChart.Series(); dataSeries1.setName(item); String viewquery=""; if(option.equals("in")) viewquery = " Select o.orderdate,SUM(o.qty * i.Cost) as c from orders o join item i on o.IName = i.IName" + " where (orderdate between ? and ? ) " + "and i.IName like ? " + "and qty>0 "+ "group by orderdate"; else if (option.equals("out")) viewquery = " Select o.orderdate,SUM(o.qty * i.Cost) as c from orders o join item i on o.IName = i.IName" + " where (orderdate between ? and ? ) " + "and i.IName like ? " + "and qty<0 "+ "group by orderdate"; try { PreparedStatement pst = con.prepareStatement(viewquery); pst.setDate(1, startDate); pst.setDate(2, endDate); pst.setString(3, item); ResultSet rs = pst.executeQuery(); while (rs.next()) { dataSeries1.getData().add(new XYChart.Data(rs.getString("orderdate"), Math.abs(Integer.parseInt(rs.getString("c"))))); } areaChart.getData().add(dataSeries1); return areaChart; } catch (SQLException era) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + era); alert.show(); return null; } } AreaChart getCount(String item, Date startDate, Date endDate, AreaChart areaChart,String option){ XYChart.Series dataSeries1 = new XYChart.Series(); dataSeries1.setName(item); String viewquery=""; if(option.equals("in")) viewquery = " Select orderdate,SUM(qty) as s from orders where (orderdate between ? and ?) " + "and iname like ? " + " and qty>0 " + " group by orderdate "; else if (option.equals("out")) viewquery = " Select orderdate,SUM(qty) as s from orders where (orderdate between ? and ?) " + "and iname like ? " + " and qty<0 " + " group by orderdate "; try { PreparedStatement pst = con.prepareStatement(viewquery); pst.setDate(1, startDate); pst.setDate(2, endDate); pst.setString(3, item); ResultSet rs = pst.executeQuery(); while (rs.next()) { dataSeries1.getData().add(new XYChart.Data(rs.getString("orderdate"), Math.abs(Integer.parseInt(rs.getString("s"))))); } areaChart.getData().add(dataSeries1); return areaChart; } catch (SQLException era) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + era); alert.show(); return null; } } public void report(String empID, int flag, Date sDate, Date eDate, String email) { String v1,v2,v3,v4,v5,sql=""; Document pdfsup = new Document(); // creating the pdfs using itext Image logo = null; try { PdfWriter.getInstance(pdfsup, new FileOutputStream("D:\\UMS\\UMS\\src\\UMS\\assets\\Report.pdf")); } catch (Exception e) { callAlert(alert,e.getMessage()); } pdfsup.open(); try { logo = Image.getInstance("D:\\UMS\\UMS\\src\\UMS\\assets\\logo.jpg"); logo.setAlignment(Element.ALIGN_CENTER); } catch (Exception e1) { callAlert(alert,e1.getMessage()); } try { Paragraph paragraph = new Paragraph(); paragraph.add(new java.util.Date().toString()); paragraph.setAlignment(Element.ALIGN_RIGHT); pdfsup.add(paragraph); pdfsup.add(new Paragraph("____________________________________________________________________________")); pdfsup.add(logo); Paragraph paragraph1 = new Paragraph(); paragraph1.add("PILLAR SECURITY"); paragraph1.setAlignment(Element.ALIGN_CENTER); paragraph1.setSpacingAfter(15); paragraph1.setSpacingBefore(15); pdfsup.add(paragraph1); } catch (Exception e3) { callAlert(alert,e3.getMessage()); } PdfPTable tablesup = new PdfPTable(5); PdfPCell cell = new PdfPCell(new Paragraph("Unit Report")); cell.setColspan(8); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBackgroundColor(BaseColor.ORANGE); tablesup.addCell(cell); tablesup.addCell("Employee ID"); tablesup.addCell("Order Date"); tablesup.addCell("Issuer Name"); tablesup.addCell("Item Name"); tablesup.addCell("Quantity"); try { if (flag == 0) sql = "Select * from orders where empid = ?"; else if (flag == 1) sql = "Select * from orders where orderdate between ? and ?"; PreparedStatement pst = con.prepareStatement(sql); if (flag == 0) pst.setString(1, empID); else if (flag == 1) { pst.setDate(1, sDate); pst.setDate(2, eDate); } ResultSet rs = pst.executeQuery(); while (rs.next()) { v1 = rs.getString("empid"); v2 = rs.getString("orderdate"); v3 = rs.getString("aname"); v4 = rs.getString("iname"); v5 = rs.getString("qty"); tablesup.addCell(v1); tablesup.addCell(v2); tablesup.addCell(v3); tablesup.addCell(v4); tablesup.addCell(v5); } pdfsup.add(new Paragraph("")); pdfsup.add(new Paragraph("")); pdfsup.add(new Paragraph("")); pdfsup.add(tablesup); Paragraph paragraph3 = new Paragraph(); paragraph3.setFont(FontFactory.getFont(FontFactory.TIMES_ITALIC, 2f)); paragraph3.add("SIMRANJEET SINGH :)"); paragraph3.setAlignment(Paragraph.ALIGN_RIGHT); pdfsup.add(paragraph3); pdfsup.close(); if (Desktop.isDesktopSupported()) { try { File file = new File("D:\\UMS\\UMS\\src\\UMS\\assets\\Report.pdf"); Desktop.getDesktop().open(file); } catch (Exception e) { System.out.println(e); } } //default report receiver MailUtil.sendMail("simranjeet271@gmail.com", "Report"); alert.setAlertType(Alert.AlertType.INFORMATION); alert.setContentText("Report Generated Successfully"); alert.show(); if (!(email.isEmpty())) { MailUtil.sendMail(email, "Report"); alert.setAlertType(Alert.AlertType.INFORMATION); alert.setContentText("Report Generated Successfully"); alert.show(); } } catch (Exception e4) { callAlert(alert,e4.getMessage()); } } // void insert(Utility utility) { // // int count = 0; // String selectquery = "select * from item where iname = ? "; // // try { // PreparedStatement pst = con.prepareStatement(selectquery); // pst.setString(1, utility.getName()); // ResultSet rs = pst.executeQuery(); // while (rs.next()) { // count = Integer.parseInt(rs.getString("count")); // System.out.println(count); // } // // String updatecountquery = "update item set count = ?" // + " where iname = ? "; // pst = con.prepareStatement(updatecountquery); // pst.setInt(1, count + utility.getCount()); // pst.setString(2, utility.getName()); // pst.executeUpdate(); // System.out.println("insertion done"); // alert.setAlertType(Alert.AlertType.INFORMATION); // alert.setContentText("Stock Added Successfully\n"+utility.getName()); // alert.show(); // } catch (Exception s) { // alert.setAlertType(Alert.AlertType.ERROR); // alert.setContentText("Task Unsuccessfully\n" + s); // alert.show(); // } // } public void update(UpdateItemDTO updateItemDTO) { int count = 0; int mincount=0; String itemName = updateItemDTO.getItemName(); int quantity = updateItemDTO.getQuantity(); String empID = updateItemDTO.getEmpID(); Date date = updateItemDTO.getDate(); String providerName = updateItemDTO.getProviderName(); String site = updateItemDTO.getSite(); String selectquery = "select * from item where iname = ? "; try { PreparedStatement pst = con.prepareStatement(selectquery); pst.setString(1, itemName); ResultSet rs = pst.executeQuery(); while (rs.next()) { count = Integer.parseInt(rs.getString("count")); mincount=Integer.parseInt(rs.getString("MinCount")); } String updatecountquery = "update item set count = ?" + " where iname = ? "; pst = con.prepareStatement(updatecountquery); int updatedCount = count - quantity; pst.setInt(1, updatedCount); pst.setString(2, itemName); pst.executeUpdate(); System.out.println("count updation done"); if (updatedCount < mincount){ MailUtil.sendMail("simranjeet271@gmail.com", "Stock needed\n" + itemName + "\nItem left: " + updatedCount+"\nOrder "+(mincount-updatedCount)+" more items to achieve Min"+ " " + "Count"); } } catch (Exception s) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + s); alert.show(); } //order table String orderquery = "INSERT INTO orders ( empid,orderdate,aname,iname,qty) VALUES (?, ?, ?,?,?)"; try { PreparedStatement pst = con.prepareStatement(orderquery); pst.setString(1, empID); pst.setDate(2, date); pst.setString(3, providerName); pst.setString(4, itemName); pst.setInt(5, quantity); pst.executeUpdate(); } catch (Exception s) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + s); alert.show(); } //testing item String sitequery; if (itemName.contains("BLAZER")) { count = 0; String selectqueryB = "select * from site where sitename = ? "; try { //step 1 PreparedStatement pst = con.prepareStatement(selectqueryB); pst.setString(1, site); ResultSet rs = pst.executeQuery(); while (rs.next()) { count = Integer.parseInt(rs.getString("noofblazers")); System.out.println(count); } sitequery = "update site set noofblazers = ? where sitename = ? "; pst = con.prepareStatement(sitequery); pst.setInt(1, count + quantity); pst.setString(2, site); pst.executeUpdate(); System.out.println("site update done"); } catch (Exception s) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + s); alert.show(); } } else if (itemName.contains("JACKET")) { count = 0; String selectqueryJ = "select * from site where sitename = ? "; try { //step 1 PreparedStatement pst = con.prepareStatement(selectqueryJ); pst.setString(1, itemName); ResultSet rs = pst.executeQuery(); while (rs.next()) { count = Integer.parseInt(rs.getString("noofjackets")); } sitequery = "update site set noofjackets = ? where sitename = ? "; pst = con.prepareStatement(sitequery); pst.setInt(1, count + quantity); pst.setString(2, site); pst.executeUpdate(); System.out.println("site update done"); } catch (Exception s) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + s); alert.show(); } } } public ObservableList<String> itemNames() { String viewquery = "select * from item "; ObservableList<String> names = FXCollections.observableArrayList(); try { Statement st = con.createStatement(); ResultSet rs = st.executeQuery(viewquery); while (rs.next()) { names.add(rs.getString("IName")); } } catch (Exception e) { e.printStackTrace(); } return names; } public ObservableList<String> sitename() { String viewquery = "select * from site"; ObservableList<String> names = FXCollections.observableArrayList(); try { Statement st = con.createStatement(); ResultSet rs = st.executeQuery(viewquery); while (rs.next()) { names.add(rs.getString("SiteName")); } } catch (Exception e) { System.out.println(e); } return names; } public ObservableList<String> empidList() { String viewquery = "select * from employee "; ObservableList<String> names = FXCollections.observableArrayList(); try { Statement st = con.createStatement(); ResultSet rs = st.executeQuery(viewquery); while (rs.next()) { names.add(rs.getString("empid")); } } catch (Exception e) { e.printStackTrace(); } return names; } public void resetItem(ItemDTO itemDTO) { if(itemDTO.getCost().isEmpty() && !itemDTO.getMinCount().isEmpty()){ String selectquery = "UPDATE item SET MinCount=? WHERE IName=?"; try { PreparedStatement pst = con.prepareStatement(selectquery); pst.setString(1, itemDTO.getMinCount()); pst.setString(2, itemDTO.getItemName()); pst.executeUpdate(); alert.setAlertType(Alert.AlertType.INFORMATION); alert.setContentText("Item Reset Done"); alert.show(); } catch (Exception s) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + s); alert.show(); }}else if(!itemDTO.getCost().isEmpty() && itemDTO.getMinCount().isEmpty()){ String selectquery = "UPDATE item SET Cost=? WHERE IName=?"; try { PreparedStatement pst = con.prepareStatement(selectquery); pst.setString(1, itemDTO.getCost()); pst.setString(2, itemDTO.getItemName()); pst.executeUpdate(); alert.setAlertType(Alert.AlertType.INFORMATION); alert.setContentText("Item Reset Done"); alert.show(); } catch (Exception s) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + s); alert.show(); }}else if(!itemDTO.getCost().isEmpty() && !itemDTO.getMinCount().isEmpty()){ String selectquery = "UPDATE item SET MinCount=? , Cost=? WHERE IName=?"; try { PreparedStatement pst = con.prepareStatement(selectquery); pst.setString(1, itemDTO.getMinCount()); pst.setString(2, itemDTO.getCost()); pst.setString(3, itemDTO.getItemName()); pst.executeUpdate(); alert.setAlertType(Alert.AlertType.INFORMATION); alert.setContentText("Item Reset Done"); alert.show(); } catch (Exception s) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + s); alert.show(); } }} public void addEmployee(EmployeeDTO employeeDTO) { String selectquery = "insert into employee (empid,empname,phone,email,address,sitename) values" + "(?,?,?,?,?,?)"; try { PreparedStatement pst = con.prepareStatement(selectquery); pst.setString(1, employeeDTO.getEmpID()); pst.setString(2, employeeDTO.getEmpName()); pst.setString(3, employeeDTO.getPhoneNumber()); pst.setString(4, employeeDTO.getEmail()); pst.setString(5, employeeDTO.getAddress()); pst.setString(6, employeeDTO.getSite()); pst.executeUpdate(); System.out.println("employee added"); alert.setAlertType(Alert.AlertType.INFORMATION); alert.setContentText("Employee Added Successfully"); alert.show(); } catch (SQLException e) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + e); alert.show(); } } public void addSite(SiteDTO siteDTO) { String selectquery = "insert into site (sitename,address,noofblazers,noofjackets) values" + "(?,?,?,?)"; PreparedStatement pst = null; try { pst = con.prepareStatement(selectquery); pst.setString(1, siteDTO.getSite()); pst.setString(2, siteDTO.getAddress()); pst.setInt(3, 0); pst.setInt(4, 0); pst.executeUpdate(); alert.setAlertType(Alert.AlertType.INFORMATION); alert.setContentText("Site Added Successfully"); alert.show(); } catch (SQLException ex) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + ex); alert.show(); } } public void addItem( ItemDTO itemDTO) { String selectquery = "insert into item (IName,MinCount,Cost,Count) values" + "(?,?,?,?)"; PreparedStatement pst = null; try { pst = con.prepareStatement(selectquery); pst.setString(1, itemDTO.getItemName()); pst.setString(2, itemDTO.getMinCount()); pst.setString(3, itemDTO.getCost()); pst.setInt(4, 0); pst.executeUpdate(); alert.setAlertType(Alert.AlertType.INFORMATION); alert.setContentText("Item Added Successfully"); alert.show(); } catch (SQLException ex) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + ex); alert.show(); } } private static void setKey(String myKey) { MessageDigest sha = null; try { key = myKey.getBytes("UTF-8"); sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key, 16); secretKey = new SecretKeySpec(key, "AES"); } catch (Exception e) { e.printStackTrace(); } } private String hash(String strToEncrypt, String secret) { try { setKey(secret); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))); } catch (Exception e) { System.out.println("Error while encrypting: " + e.toString()); } return null; } public boolean forgot(UserDTO userDTO) { int rows = 0; try { String generatedPassword = hash(userDTO.getPassword(), secret); String updateQueryPre = "UPDATE login SET password=? WHERE login=?"; PreparedStatement pst = con.prepareStatement(updateQueryPre); pst.setString(1, generatedPassword); pst.setString(2, userDTO.getUsername()); rows = pst.executeUpdate(); alert.setAlertType(Alert.AlertType.INFORMATION); alert.setContentText("Reset Successful"); alert.show(); System.out.println("reset"); if (rows != 0) { return true; } } catch (Exception s) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + s); alert.show(); return false; } return false; } public boolean addUser(UserDTO userDTO) { try { String generatedPassword = hash(userDTO.getPassword(), secret); String addQueryPre = "INSERT INTO login (login,password) " + " VALUES (?,?)"; PreparedStatement pst = con.prepareStatement(addQueryPre); pst.setString(1, userDTO.getUsername()); pst.setString(2, generatedPassword); pst.executeUpdate(); alert.setAlertType(Alert.AlertType.INFORMATION); alert.setContentText("User Added Successfully"); alert.show(); } catch (Exception e) { alert.setAlertType(Alert.AlertType.ERROR); alert.setContentText("Task Unsuccessfully\n" + e); alert.show(); return false; } return true; } public boolean match(UserDTO userDTO) { String database_password = ""; String updateQueryPre = "SELECT * FROM login WHERE login=?"; ResultSet rs = null; try { PreparedStatement pst = con.prepareStatement(updateQueryPre); pst.setString(1, userDTO.getUsername()); rs = pst.executeQuery(); while (rs.next()) { database_password = rs.getString("Password"); return database_password.equals(hash(userDTO.getPassword(), secret)); } } catch (Exception s) { s.printStackTrace(); } return false; } // public String getTotal() { // String viewquery = "select * from item "; // int gTotal=0; // // try { // PreparedStatement pst = con.prepareStatement(viewquery); // // ResultSet rs = pst.executeQuery(); // while (rs.next()) { // gTotal+=Integer.parseInt(rs.getString("cost"))*Integer.parseInt(rs.getString("count")); // // } // // // // } catch (Exception era) { // alert.setAlertType(Alert.AlertType.ERROR); // alert.setContentText("Task Unsuccessfully\n" + era); // alert.show(); // return ""; // } // return gTotal+""; // } }
Java
UTF-8
1,810
2.109375
2
[]
no_license
package com.pzj.core.trade.sms.engine.handle.saas; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.pzj.core.trade.sms.engine.common.SmsSendTypeEnum; import com.pzj.core.trade.sms.engine.convert.SendSMSAroundConvert; import com.pzj.core.trade.sms.engine.model.SMSSendModel; import com.pzj.trade.order.entity.OrderEntity; @Component public class SaasPaymentMakeUpHandle { @Autowired private SendSMSAroundConvert sendSMSAroundConvert; public void sendSMS(OrderEntity order, double currentOrderAmount, double makeUpAmount) { // final String orderURL = SMSContentTool.getOrderURL(order.getOrder_id(), order.getCreate_time()); StringBuffer sb = new StringBuffer("尊敬的用户您好,您的订单"); sb.append(order.getOrder_id()).append("需要补差价,应付金额:").append(currentOrderAmount).append("元,,需补差价:").append(makeUpAmount) .append("请您在60分钟内登录魔方SaaS系统完成补差"); //需要补差的人应该是本级订单的分销商,但补差的人应该获取到当前人的供应商电话信息 long currentSupplierId = order.getReseller_id(); //供应商电话 final String supllierPhone = sendSMSAroundConvert.getSupplierPhone(currentSupplierId); //供应商联系人电话 final List<String> supplierContactee = sendSMSAroundConvert.getSupplierContacteePhone(currentSupplierId); supplierContactee.add(supllierPhone); for (final String phoneNum : supplierContactee) { final SMSSendModel sendModel = new SMSSendModel(); sendModel.setMsg(sb.toString()); sendModel.setPhoneNum(phoneNum); sendModel.setSaleOrderId(order.getOrder_id()); sendSMSAroundConvert.sendSMS(sendModel, SmsSendTypeEnum.orderSupplier); } } }
Java
UTF-8
1,782
2.375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.kasneb.util; import java.util.Random; /** * * @author jikara */ public class GeneratorUtil { public static String generateReceiptNumber() { Integer maximum = 100000; Integer minimum = 1000; Random rn = new Random(); int n = maximum - minimum + 1; int i = Math.abs(rn.nextInt() % n); return String.valueOf(minimum + i); } public static String generateRandomPassword() { Integer maximum = 10000000; Integer minimum = 1000000; Random rn = new Random(); int n = maximum - minimum + 1; int i = Math.abs(rn.nextInt() % n); return String.valueOf(minimum + i); } public static String generateRandomPin() { Integer maximum = 10000; Integer minimum = 1000; Random rn = new Random(); int n = maximum - minimum + 1; int i = Math.abs(rn.nextInt() % n); return String.valueOf(minimum + i); } public static String generateInvoiceNumber() { Integer maximum = 10000; Integer minimum = 1000; Random rn = new Random(); int n = maximum - minimum + 1; int i = Math.abs(rn.nextInt() % n); return String.valueOf(minimum + i); } public static String generateRandomId() { Integer maximum = 100000000; Integer minimum = 100000; Random rn = new Random(); int n = maximum - minimum + 1; int i = Math.abs(rn.nextInt() % n); return String.valueOf(minimum + i); } }
Shell
UTF-8
4,169
2.671875
3
[]
no_license
function createOrderer() { infoln "Enrolling the CA admin" mkdir -p organizations/ordererOrganizations/example.com export FABRIC_CA_CLIENT_HOME=${PWD}/organizations/ordererOrganizations/example.com set -x fabric-ca-client enroll -u https://admin:adminpw@localhost:portca --caname ca-orderer --tls.certfiles ${PWD}/organizations/fabric-ca/ordererOrg/tls-cert.pem { set +x; } 2>/dev/null echo 'NodeOUs: Enable: true ClientOUIdentifier: Certificate: cacerts/localhost-portca-ca-orderer.pem OrganizationalUnitIdentifier: client PeerOUIdentifier: Certificate: cacerts/localhost-portca-ca-orderer.pem OrganizationalUnitIdentifier: peer AdminOUIdentifier: Certificate: cacerts/localhost-portca-ca-orderer.pem OrganizationalUnitIdentifier: admin OrdererOUIdentifier: Certificate: cacerts/localhost-portca-ca-orderer.pem OrganizationalUnitIdentifier: orderer' >${PWD}/organizations/ordererOrganizations/example.com/msp/config.yaml infoln "Registering orderer" set -x fabric-ca-client register --caname ca-orderer --id.name orderer --id.secret ordererpw --id.type orderer --tls.certfiles ${PWD}/organizations/fabric-ca/ordererOrg/tls-cert.pem { set +x; } 2>/dev/null infoln "Registering the orderer admin" set -x fabric-ca-client register --caname ca-orderer --id.name ordererAdmin --id.secret ordererAdminpw --id.type admin --tls.certfiles ${PWD}/organizations/fabric-ca/ordererOrg/tls-cert.pem { set +x; } 2>/dev/null infoln "Generating the orderer msp" set -x fabric-ca-client enroll -u https://orderer:ordererpw@localhost:portca --caname ca-orderer -M ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp --csr.hosts orderer.example.com --csr.hosts localhost --tls.certfiles ${PWD}/organizations/fabric-ca/ordererOrg/tls-cert.pem { set +x; } 2>/dev/null cp ${PWD}/organizations/ordererOrganizations/example.com/msp/config.yaml ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/config.yaml infoln "Generating the orderer-tls certificates" set -x fabric-ca-client enroll -u https://orderer:ordererpw@localhost:portca --caname ca-orderer -M ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/tls --enrollment.profile tls --csr.hosts orderer.example.com --csr.hosts localhost --tls.certfiles ${PWD}/organizations/fabric-ca/ordererOrg/tls-cert.pem { set +x; } 2>/dev/null cp ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/tls/tlscacerts/* ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/tls/ca.crt cp ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/tls/signcerts/* ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt cp ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/tls/keystore/* ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.key mkdir -p ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts cp ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/tls/tlscacerts/* ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem mkdir -p ${PWD}/organizations/ordererOrganizations/example.com/msp/tlscacerts cp ${PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/tls/tlscacerts/* ${PWD}/organizations/ordererOrganizations/example.com/msp/tlscacerts/tlsca.example.com-cert.pem infoln "Generating the admin msp" set -x fabric-ca-client enroll -u https://ordererAdmin:ordererAdminpw@localhost:portca --caname ca-orderer -M ${PWD}/organizations/ordererOrganizations/example.com/users/Admin@example.com/msp --tls.certfiles ${PWD}/organizations/fabric-ca/ordererOrg/tls-cert.pem { set +x; } 2>/dev/null cp ${PWD}/organizations/ordererOrganizations/example.com/msp/config.yaml ${PWD}/organizations/ordererOrganizations/example.com/users/Admin@example.com/msp/config.yaml }
JavaScript
UTF-8
437
2.609375
3
[]
no_license
const select = (name) => { return document.querySelector(name); }; let ham = select('.ham'); let overlay = select('.overlay'); let mobileNav = select('.header__mobileNav'); ham.addEventListener('click', () => { ham.classList.toggle("change"); overlay.classList.toggle("display"); mobileNav.classList.toggle("display") // overlay.style.display = "block"; // nav.style.display = "block"; });
PHP
UTF-8
1,700
3.140625
3
[ "MIT" ]
permissive
<?php namespace Opf\Validator; class StringLength extends ValidatorAbstract implements ValidatorInterface { const TO_LONG = 'stringLengthToLong'; const TO_SHORT = 'stringLengthToShort'; protected $options = array( 'maxStringLength' => null, 'minStringLength' => 0 ); protected $errorTemplates = array( self::TO_LONG => 'The input is more than %maxStringLength% characters long', self::TO_SHORT => 'The input is lesser than %minStringLength% characters long' ); public function __construct($max = null, $min = null, array $errorTemplates = array()) { $this->setMax($max); if ($min !== null) { $this->setMin($min); } if (count($errorTemplates) > 0) { $this->errorTemplates = array_merge($this->errorTemplates, $errorTemplates); } } public function setMax($max) { $this->options['maxStringLength'] = $max; } public function setMin($min) { $this->options['minStringLength'] = $min; } public function isValid($value) { if (is_integer($this->options['maxStringLength']) && mb_strlen($value) > $this->options['maxStringLength']) { $this->addError(self::TO_LONG); } /** check only the minimum string length, when a string has been entered */ if (mb_strlen($value) > 0) { if (is_integer($this->options['minStringLength']) && mb_strlen($value) < $this->options['minStringLength']) { $this->addError(self::TO_SHORT); } } if (count($this->errors) == 0) { return true; } return false; } }
Markdown
UTF-8
2,631
2.71875
3
[]
no_license
# Deteksi Plat Nomor Kendaraan Indonesia Deteksi Plat Nomor Kendaraan Indonesia dari potongan gambar plat nomor yang sudah di melewati proses Pengambilan *Region of Interest* (ROI) Plat nomor kendaraan dari penangkapan citra gambar di lapangan (proses pengambilan ROI tidak dilampirkan pada repository ini) ## Masters.ipynb File ini berisi algoritma *image processing* untuk mendeteksi bagian citra gambar yang merupakan plat kendaraan bermotor hasil pemngambilan *Region of Interest* (ROI) sebelumnya , sekaligus menggunakan model dari Keras-OCR untuk membaca tulisan pada plat nomor kendaraan. ![image](https://github.com/maulanaisa/plate-detector/blob/main/Alur_proses.png) Dua metode digunakan pada proses kali ini, yaitu menggunakan proses *closed contour & edge detection* dan yang kedua menggunakan *morphological operation*. Dimana metode pertama diprioritaskan terlebih dahulu dibanding metode kedua untuk memaksimalkan akurasi hasil pembacaan. Hal ini kemudian akan dimasukkan ke dalam fungsi yang berguna untuk melakukan perubahan perspektif gambar dengan hanya mengambil 4 titik sudut kontur sehingga dihasilkan transformasi gambar “bird view” yang akan memetakan gambar ke bentuk quadrilateral yang sesuai, hal ini dilakukan dengan menggunakan fungsi warpPerspective di OpenCV. ![image](https://github.com/maulanaisa/plate-detector/blob/main/Deteksi_metode1.png) ![image](https://github.com/maulanaisa/plate-detector/blob/main/Deteksi_metode2.png) Setelah itu dilakukan koreksi sudut pada gambar hasil transformasi warp dengan mengambil nilai kemiringan kontur plat kendaraan yang sebelumnya terdeteksi. Sehingga sudut dapat dikoreksi agar hasil pembacaan benar dari kiri ke kanan (plat nomor kendaraan di Indonesia). Pembacaan karakter dari gambar yang sudah melewati proses *preprocessing* selanjutnya menggunakan Keras-OCR yang sudah di *training* kembali menggunakan dataset plat kendaraan bermotor di Indonesia (tidak dilampirkan dalam repository ini). User bisa menggunakan model lainnya untuk membaca karakter pada gambar. Berikut ini adalah *flow chart* umum dari sistem ![image](https://github.com/maulanaisa/plate-detector/blob/main/Flow_chart.jpg) ### Credit : - https://www.pyimagesearch.com/2020/09/21/opencv-automatic-license-number-plate-recognition-anpr-with-python/, diakses 9 April 2021 - https://www.pyimagesearch.com/2014/05/05/building-pokedex-python-opencv-perspective-warping-step-5-6/, diakses 9 April 2021 - https://medium.com/programming-fever/license-plate-recognition-using-opencv-python-7611f85cdd6c#:~:text=1.,location%20of%20the%20number%20plate, diakses 9 April 2021
Java
UTF-8
3,977
2.21875
2
[]
no_license
package stellarium.stellars.background; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import net.minecraft.client.Minecraft; import sciapi.api.value.IValRef; import sciapi.api.value.euclidian.EVector; import sciapi.api.value.euclidian.IEVector; import stellarium.StellarSky; import stellarium.stellars.ExtinctionRefraction; import stellarium.stellars.StellarManager; import stellarium.util.math.SpCoordf; import stellarium.util.math.Spmath; import stellarium.util.math.Transforms; public class BrStar extends Star { public boolean unable; //constants public static final int NumStar=9110; public static final int Bufsize=198; //Magnitude public float Mag; //Apparent Magnitude public float App_Mag; //B-V Value public float B_V; //Apparant B-V public float App_B_V; //stars public static BrStar stars[]; //File public static byte str[]; //Initialization check public static boolean IsInitialized=false; /* * Get star's position * time is 'tick' unit * world is false in Overworld, and true in Ender */ public IValRef<EVector> GetPositionf(){ IValRef pvec=Transforms.ZTEctoNEc.transform((IEVector)EcRPos); pvec=Transforms.EctoEq.transform(pvec); pvec=Transforms.NEqtoREq.transform(pvec); pvec=Transforms.REqtoHor.transform(pvec); return pvec; } public IValRef<EVector> GetAtmPosf(){ return ExtinctionRefraction.Refraction(GetPositionf(), true); } @Override public void Update() { if(Mag>StellarSky.getManager().Mag_Limit) this.unable=true; AppPos.set(GetAtmPosf()); float Airmass=(float) ExtinctionRefraction.Airmass(AppPos, true); App_Mag= (Mag+Airmass*ExtinctionRefraction.ext_coeff_Vf); App_B_V= (B_V+Airmass*ExtinctionRefraction.ext_coeff_B_Vf); } //Load Stars public static final void InitializeAll() throws IOException{ //stars stars=new BrStar[NumStar]; //Counter Variable int i, j, k; //Initialize star_value for(i=0; i<NumStar; i++) { stars[i]=new BrStar(); stars[i].star_value=new byte[Bufsize]; } System.out.println("[Stellarium]: "+"Loading Bright Stars Data..."); //Read str=new byte[NumStar*Bufsize]; InputStream brs=BrStar.class.getResourceAsStream("/data/bsc5.dat"); BufferedInputStream bbrs = new BufferedInputStream(brs); bbrs.read(str); bbrs.close(); //Input Star Information j=0; for(i=0; i<NumStar; i++) { k=0; while(str[j]!='\n'){ stars[i].star_value[k]=str[j]; j++; k++; } j++; stars[i].Initialize(); } str=null; System.out.println("[Stellarium]: "+"Bright Stars are Loaded!"); IsInitialized=true; } public static void UpdateAll(){ int i; for(i=0; i<NumStar; i++) if(!stars[i].unable) stars[i].Update(); } //Initialization in each star public void Initialize(){ float RA, Dec; if(star_value[103]==' '){ this.unable=true; return; } else this.unable=false; Mag=Spmath.sgnize(star_value[102], (float)Spmath.btoi(star_value, 103, 1) +Spmath.btoi(star_value, 105, 2)*0.01f); if(Mag>StellarSky.getManager().Mag_Limit-ExtinctionRefraction.ext_coeff_Vf) unable=true; B_V=Spmath.sgnize(star_value[109], (float)Spmath.btoi(star_value, 110, 1) +Spmath.btoi(star_value, 112, 2)*0.01f); //J2000 RA=Spmath.btoi(star_value, 75, 2)*15.0f +Spmath.btoi(star_value, 77, 2)/4.0f +Spmath.btoi(star_value, 79, 2)/240.0f +Spmath.btoi(star_value, 82, 1)/2400.0f; Dec=Spmath.sgnize(star_value[83], Spmath.btoi(star_value, 84, 2) +Spmath.btoi(star_value, 86, 2)/60.0f +Spmath.btoi(star_value, 88, 2)/3600.0f); EcRPos.set((IValRef)Transforms.EqtoEc.transform((IValRef)new SpCoordf(RA, Dec).getVec())); star_value=null; } }
Markdown
UTF-8
983
2.859375
3
[]
no_license
# [React Portfolio](https://gidmp.github.io/react-portfolio/#/) ## Description This is my deployed React portfolio. I am a full-stack coding bootcamp student from University of Washington hoping to develop a career as a web developer. I built this portfolio using REACT, which I enjoy more than I expected. Weary traveler, please have a quick look if you may, and if you are interested, feel free to contact me. ## Table of Contents * [Technologies](#technologies) * [Usage](#usage) * [Demo](#demo) * [Questions](#questions) ## Technologies ------ * HTML * CSS * JavaScript * Node.js * REACT * React router * UIKit ## Usage ------ * Navigate to the [deployed portfolio](https://gidmp.github.io/react-portfolio/#/). ## Demo ------ ![](./src/assets/portfolio1.gif) ## Questions ------ <img src="https://avatars2.githubusercontent.com/u/6896220?v=4" alt="a guy" width="75px" height="75px"> If you have any questions, please contact me, [Daniel Luke Tanoeihusada](danielluke08@gmail.com) directly at danielluke08@gmail.com
C#
UTF-8
1,389
3.453125
3
[]
no_license
using System; namespace hash_table { class Program { static void Main(string[] args) { // chaining solution Console.WriteLine("Chaining :"); Chaining sample = new Chaining(); sample.Add(10); sample.Add(20); sample.Add(30); sample.Add(40); sample.Add(11); sample.Add(17); sample.Add(21); sample.Add(25); sample.Add(23); sample.Remove(30); sample.Remove(20); Console.WriteLine(sample.Search(40)); // Linear probing solution Console.WriteLine("Linear probing :"); LinearProbing L = new LinearProbing(); L.Add(10); L.Add(12); L.Add(14); L.Add(13); L.Add(11); L.Add(15); L.Add(28); L.Delete(6); L.Add(3); Console.WriteLine(L.Search(3)); // Double probing solution Console.WriteLine("Double probing"); DoubleProbing D = new DoubleProbing(); D.Add(79); D.Add(69); D.Add(98); D.Add(72); D.Add(80); D.Add(50); D.Add(14); D.Delete(1); Console.WriteLine(D.Search(14)); } } }
JavaScript
UTF-8
1,212
2.640625
3
[]
no_license
'use strict' const datetime = require('node-datetime') const StatByWeek = require('../models').StatByWeek class StatByWeekController{ async addStatOnWeek(attraction){ var dateToday = new Date(Date.now()); var diff = dateToday.getDate() - dateToday.getDay() + (dateToday.getDay() === 0 ? -6 : 1); var weekDay = new Date(dateToday.setDate(diff)); const newweekDay = datetime.create(weekDay); const weekDayFormat = newweekDay.format('d/m/y'); var statWeek = await StatByWeek.findOne({ date : weekDayFormat, attraction : attraction }); if(statWeek){ statWeek.nb_use += 1; statWeek.save(function(err){ if(err) throw err; }); } else{ var newStatWeek = new StatByWeek({ date : weekDayFormat, attraction : attraction, nb_use : 1 }); newStatWeek.save(function(err){ if(err) throw err; }) } } } module.exports = new StatByWeekController();
Python
UTF-8
6,504
2.671875
3
[]
no_license
import time from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from appium.webdriver.webdriver import WebDriver from lxml.html import tostring from lxml import etree class BasePage(object): def __init__(self, appium_driver): self.driver: WebDriver = appium_driver def swipeUp(self, t=1000, n=1): '''向上滑动屏幕''' l = self.driver.get_window_size() x1 = l['width'] * 0.5 # x坐标 y1 = l['height'] * 0.75 # 起始y坐标 y2 = l['height'] * 0.25 # 终点y坐标 for i in range(n): self.driver.swipe(x1, y1, x1, y2, t) time.sleep(1) def swipeDown(self, t=1000, n=1): '''向下滑动屏幕''' l = self.driver.get_window_size() x1 = l['width'] * 0.5 # x坐标 y1 = l['height'] * 0.25 # 起始y坐标 y2 = l['height'] * 0.75 # 终点y坐标 for i in range(n): self.driver.swipe(x1, y1, x1, y2, t) def swipLeft(self, t=1000, n=1): '''向左滑动屏幕''' l = self.driver.get_window_size() x1 = l['width'] * 0.75 y1 = l['height'] * 0.5 x2 = l['width'] * 0.25 for i in range(n): self.driver.swipe(x1, y1, x2, y1, t) def swipRight(self, t=1000, n=1): '''向右滑动屏幕''' l = self.driver.get_window_size() x1 = l['width'] * 0.25 y1 = l['height'] * 0.5 x2 = l['width'] * 0.75 for i in range(n): self.driver.swipe(x1, y1, x2, y1, t) def find_byID_(self,id): '''根据id定位元素''' return self.driver.find_element_by_id(id) def return_elements_num(self,text): return self.driver.find_elements_by_xpath('//*[contains(@text,"%s")]'%text) def find_bytext(self,find_text): '''根据名称定位,然后点击''' loc_text = 'new UiSelector().text("%s")'%(find_text) # ele = self.driver.find_element_by_android_uiautomator(loc_text) # ele.click() # return ele return self.driver.find_element_by_android_uiautomator(loc_text) def click_tap(self, shuzu): self.driver.tap(shuzu) def by_className(self, classname): # reid = 'newUiSelector().resourceId("%s")'%resourceId # self.driver.find_element_by_android_uiautomator(reid).click() #clss = 'newUiSelector().className("%s")'%resourceId self.driver.find_element_by_android_uiautomator('new UiSelector().className("%s")'%classname).click() def by_index_android_instance(self): self.driver.find_element_by_android_uiautomator('new UiSelector().className("android.widget.EditText").instance(2)').send_keys('可以了吧????') def find_byandroid_text(self,text): return self.driver.find_element_by_android_uiautomator('new UiSelector().text("%s")'%text) def find_byH5_className(self, class_name, num): return self.driver.find_elements_by_class_name(class_name)[num] def find_byH5class(self,classN): return self.driver.find_element_by_class_name(classN) def find_byxpath(self,xpath): return self.driver.find_element_by_xpath(xpath) def find_by_H5_name(self,H5_text): return self.driver.find_element_by_name(H5_text) def find_byClassAndTag(self,clsname,tagname,num,num2): return self.driver.find_elements_by_class_name(clsname)[num].find_elements_by_tag_name(tagname)[num2] def find_classtag(self): self.driver.find_element_by_class_name('dialog-body').find_element_by_tag_name('textarea').send_keys('121323123') # print('cla'*9) # print(cla) # print('cla'*9) def get_context(self): get_contexts = self.driver.contexts return get_contexts def to_now_context(self,context): return self.driver.switch_to.context(context) def back_(self): return self.driver.back() def by_TouchAction_dingwei(self,x,y): action1 = TouchAction(self.driver) #点击21 #li = action1.press(x=950, y=1400).wait(300).release().wait(300).perform() # return action1.press(x=x, y=y).wait(300).release().wait(300).perform() return action1.press(x=x, y=y).release().perform() def by_touchAction_uiautomator2(self, x, y): action2 = TouchAction(self.driver) return action2.press(x=x, y=y).release().perform() def touchAction_point_to_point(self,x1,y1,x2,y2): TouchAction(self.driver).press(x=x1, y=y1).wait(300).move_to(x=x2, y=y2).wait(300).perform() def js_to_block(self): ''' 通过js 将display 设置为block 可见模式 display="block"; 修改样式的display="block" ,表示可见。 ''' t1 = time.time() js = 'document.querySelectorAll("div").display="block";' self.driver.execute_script(js) def return_all_handles(self): ''' 返回所有的window_handles''' return self.driver.window_handles def return_current_window_handle(self): '''返回当前的window_handle''' return self.driver.current_window_handle def get_current_context(self): return self.driver.current_context def js_input_textarea(self): # css = "document.querySelector('.mt-item-textarea');" css = "sum = document.querySelectorAll('.mt-item-textarea')[0];sum.value='驳回的原因';" return self.driver.execute_script(css) def js_return_html(self): js = "document.querySelector('html')" self.driver.execute_script(js) def classname_(self, cls_name): return self.driver.find_elements_by_class_name(cls_name) def css_select(self,css_select): # self.driver.find_elements_by_css_selector() return self.driver.find_elements_by_css_selector(css_select) def css_ele_select(self,css_select): return self.driver.find_element_by_css_selector(css_select) def to_alert(self): # self.driver.switch_to_alert() self.driver.switch_to.alert def F5(self): self.driver.refresh() def return_page(self): return self.driver.page_source def a_m(self): return self.driver.find_elements_by_android_uiautomator('new UiSelector().className("mt-item-textarea")') return self.driver.find_element_by_android_uiautomator('new UiSelector().className("mt-item-textarea"))') #.childSelector(newUiSelector().index("3")
Swift
UTF-8
1,222
2.703125
3
[ "MIT" ]
permissive
// // UILabelReactiveSpec.swift // ReaktiveBoarTests // // Created by Peter Ovchinnikov on 3/22/19. // Copyright © 2019 Peter Ovchinnikov. All rights reserved. // import Quick import Nimble import ReaktiveBoar import ReactiveKit class UILabelReactiveSpec: QuickSpec { override func spec() { describe("UILabel+Reactive") { var label: UILabel! let frame = CGRect(x: 10, y: 10, width: 20, height: 20) beforeEach { label = UILabel(frame: frame) } describe("reactive.font") { it("should be applied to value") { let font = UIFont.systemFont(ofSize: 30) SafeSignal(just: font) .bind(to: label.reactive.font) expect(label.font).to(be(font)) } } describe("reactive.numberOfLines") { it("should be applied to value") { let numberOfLines = 5 SafeSignal(just: numberOfLines) .bind(to: label.reactive.numberOfLines) expect(label.numberOfLines).to(equal(numberOfLines)) } } } } }
PHP
UTF-8
441
2.75
3
[]
no_license
<?php class master { function __construct() { $this -> mysqli = new mysqli('localhost', 'root', '', 'exam_system'); if ($this -> mysqli -> connect_error) { die('Connect Error (' . $this -> $mysqli -> connect_errno . ') ' . $this -> $mysqli -> connect_error); } } function echoFooter() { echo '<p class="footer">Design: <a href="http://www.evanlouie.com"><strong>www.evanlouie.com</strong></a></p>'; } } ?>