language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
WINDOWS-1252
7,994
2.6875
3
[]
no_license
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import javax.swing.JFileChooser; import java.io.FileReader; import java.util.Iterator; import java.util.Scanner; public class GraphicUserInterface extends javax.swing.JFrame { String path; private javax.swing.JTextField automataString; private javax.swing.JTextField fileLabel; private javax.swing.JSeparator jSeparator1; private javax.swing.JButton openButton; private javax.swing.JLabel stateLabel; private javax.swing.JLabel stringLabel; private javax.swing.JButton testButton; private javax.swing.JLabel title; public GraphicUserInterface() { initComponents(); } private void initComponents() { title = new javax.swing.JLabel(); openButton = new javax.swing.JButton(); automataString = new javax.swing.JTextField(); fileLabel = new javax.swing.JTextField(); stringLabel = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); testButton = new javax.swing.JButton(); stateLabel = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Postfix Evaluator"); title.setFont(new java.awt.Font("Ebrima", 0, 18)); // NOI18N title.setText("Postfix Evaluator 1.2.5.b.0"); openButton.setText("Open file"); openButton.setBorderPainted(false); openButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openButtonActionPerformed(evt); } }); fileLabel.setEditable(false); fileLabel.setText("No file chosen"); stringLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); stringLabel.setText("Postfix to evaluate"); testButton.setText("Test"); testButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { testButtonActionPerformed(evt); } }); stateLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(98, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(fileLabel) .addComponent(automataString) .addComponent(openButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(title, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSeparator1) .addComponent(stringLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(testButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(stateLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(99, 99, 99)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(title) .addGap(21, 21, 21) .addComponent(fileLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(openButton) .addGap(18, 18, 18) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(stringLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(automataString, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(35, 35, 35) .addComponent(testButton) .addGap(18, 18, 18) .addComponent(stateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(16, 16, 16)) ); pack(); }// </editor-fold> private void openButtonActionPerformed(java.awt.event.ActionEvent evt) { try { JFileChooser jfc = new JFileChooser(); jfc.showOpenDialog(null); File open = jfc.getSelectedFile(); path = open.getAbsolutePath(); String fileName = open.getName(); fileLabel.setText(fileName); } catch(NullPointerException e) { stateLabel.setText("Choose a file"); } } private void testButtonActionPerformed(java.awt.event.ActionEvent evt) { try { BufferedWriter buffer = new BufferedWriter(new FileWriter(new File("result.txt"))); PrintWriter printer = new PrintWriter(buffer); Postfix p = new Postfix(automataString.getText()); System.out.println(); AFNE a = new AFNE(p); Scanner s = new Scanner(new FileReader(path)); while (s.hasNextLine()) { String line = s.nextLine().replaceAll("[\r\n]", " ").concat(""); Iterator it = a.accepted(line).iterator(); while(it.hasNext()){ printer.println(it.next().toString().replaceAll("", "")); } } printer.close(); buffer.close(); } catch(Exception e) { e.printStackTrace(); stateLabel.setText("Error, try again."); } } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(GraphicUserInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GraphicUserInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GraphicUserInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GraphicUserInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new GraphicUserInterface().setVisible(true); } }); } }
Java
UTF-8
1,216
2.796875
3
[]
no_license
package com.zl.concurrency.example.concurrent; import com.zl.concurrency.example.temp.AbstractCountDownLunchTemp; import lombok.extern.slf4j.Slf4j; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArraySet; /** * ConcurrentSkipListSet้ชŒ่ฏ--->ๆ˜ฏTreeSet็š„ๅนถๅ‘ๅฎž็Žฐ * * @author zhagnlei * @ProjectName: MapDemo * @create 2018-09-16 20:35 * @Version: 1.0 * <p>Copyright: Copyright (zl) 2018</p> **/ @Slf4j public class ConcurrentSkipListSetExample extends AbstractCountDownLunchTemp{ private final static int clientTotal = 5000; private final static int threadTotal = 200; private static Set<Integer> set = new ConcurrentSkipListSet<>(); public static void main(String[] args) { ConcurrentSkipListSetExample copyOnWriteExample = new ConcurrentSkipListSetExample(); try { copyOnWriteExample.execute(clientTotal,threadTotal); log.info("้›†ๅˆๅคงๅฐๆ˜ฏ๏ผš{}",set.size()); } catch (Exception e) { e.printStackTrace(); } } @Override public void definedMethods(int param) { set.add(param); } }
Python
UTF-8
1,592
3.109375
3
[]
no_license
import pygame import pygame.freetype as freetype import numpy as np from pygame import Color from pygame.locals import * from game import Game, GameObject class Body(GameObject): TRACE_PRECISION=2**2 # Minimal distance of two trace points squared def __init__(self, game, name, mass, position, speed, radius, color, trace=True): super().__init__(game) self.name = name self.mass = mass self.position = position self.radius = radius self.color = color self.accel = np.array([0,0], dtype=np.int32) self.speed = speed self.trace = trace transpos = self.transform(self.position) self.points = [ (transpos[0], transpos[1]) ] def transform(self, pos): pos = np.array([self.position[0], self.position[1], 1]) return np.squeeze(np.asarray(self.game.get_camera().dot(pos))).astype(int) def paint(self, time, surface): self.speed = self.speed + self.accel * time self.position = self.position + self.speed * time pos = self.transform(self.position) if self.trace: if (pos[0] - self.points[-1][0]) ** 2 + (pos[1] - self.points[-1][1]) ** 2 > Body.TRACE_PRECISION: self.points.append((pos[0], pos[1])) if len(self.points) > 1000: self.points.pop(0) if len(self.points) > 1: pygame.draw.aalines(surface, (self.color[0]/2,self.color[1]/2,self.color[2]/2), False, self.points) pygame.draw.circle(surface, self.color, (pos[0], pos[1]), self.radius)
Java
UTF-8
1,372
3.203125
3
[]
no_license
package com.test01; import java.util.*; public class TestService { TestDAO dao = new TestDAO(); //์ถœ๋ ฅ ์•ก์…˜ ๋ฉ”์†Œ๋“œ public void list() { List<Test>temp = dao.list(); StringBuilder sb = new StringBuilder(); for(Test t : temp) { sb.append(String.format("%s%n", t.toString())); } sb.insert(0, String.format("์•„์ด๋”” ๋‚˜์ด ์„ฑ ์ด๋ฆ„%n")); System.out.println(sb.toString()); } //์ž…๋ ฅ ์•ก์…˜ ๋ฉ”์†Œ๋“œ public void add(Scanner sc) { System.out.println("๋‚˜์ด๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); int age_ = sc.nextInt(); sc.nextLine(); System.out.println("์„ฑ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); String first_ = sc.next(); System.out.println("์ด๋ฆ„์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”. "); String last_ = sc.next(); if(dao.add(new Test(0, age_, first_, last_)) == 0) { System.out.println("๋ฐ์ดํ„ฐ ์ €์žฅ ์ค‘, ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค."); } else { System.out.println("์‚ฌ์šฉ์ž ์ •๋ณด๊ฐ€ ๋“ฑ๋ก๋˜์—ˆ์Šต๋‹ˆ๋‹ค."); } } public void remove(Scanner sc) { System.out.println("์‚ญ์ œํ•  id๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์šฉ"); int id_ = sc.nextInt(); int result = dao.remove(id_); if(result!=0) { System.out.printf("%d ํ–‰์˜ ์‚ญ์ œ๊ฐ€ ์ •์ƒ์ ์œผ๋กœ ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.%n", result); }else { System.out.println("์‚ญ์ œ๊ฐ€ ์ •์ƒ์ ์œผ๋กœ ์ด๋ฃจ์–ด์ง€์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค."); } } }
PHP
UTF-8
604
2.796875
3
[]
no_license
<?php /** * This is a generated class based on the schema.org type catalog. * * @license MIT */ declare(strict_types=1); namespace EFrane\SchemaObjects; /** * The legal availability status of a medical drug. */ class DrugLegalStatus extends MedicalIntangible { /** * The location in which the status applies. */ private $applicableLocation; public function getApplicableLocation() { return $this->applicableLocation; } public function setApplicableLocation($applicableLocation) { $this->applicableLocation = $applicableLocation; } }
Java
UTF-8
2,923
2.09375
2
[]
no_license
/******************************************************************************* * Copyright (c) 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.zend.php.zendserver.deployment.ui; import java.util.*; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; /** * A visitor which collects changed class files. */ public class ChangedFilesVisitor implements IResourceDeltaVisitor { private static final IProject[] ZERO_PROJECTS = new IProject[0]; /** * The collection of changed class files. */ final protected Map<IProject, List<IResourceDelta>> map = new HashMap<IProject, List<IResourceDelta>>(); /** * Answers whether children should be visited. * <p> * If the associated resource is a file which has been changed, record it. */ public boolean visit(IResourceDelta delta) { if (delta == null) return false; if (delta.getKind() == IResourceDelta.REMOVED || delta.getKind() == IResourceDelta.ADDED) { addResourceDelta(delta); return true; } if (0 == (delta.getKind() & IResourceDelta.CHANGED)) { return false; } IResource resource = delta.getResource(); if (resource != null) { switch (resource.getType()) { case IResource.FOLDER: // ignore configuration folders (.settings,.svn) String name = resource.getName(); if (name.startsWith(".")) { //$NON-NLS-1$ return false; } break; case IResource.FILE: if (0 == (delta.getFlags() & IResourceDelta.CONTENT)) return false; addResourceDelta(delta); return false; default: return true; } } return true; } private void addResourceDelta(IResourceDelta delta) { IResource resource = delta.getResource(); IProject project = resource.getProject(); List<IResourceDelta> deltas = map.get(project); if (deltas == null) { deltas = new ArrayList<IResourceDelta>(); } deltas.add(delta); map.put(project, deltas); } public IProject[] getAllProjects() { Set<IProject> keySet = map.keySet(); if (keySet.size() == 0) { return ZERO_PROJECTS; } return (IProject[]) keySet.toArray(new IProject[keySet.size()]); } /** * Answers a collection of changed files */ public IResourceDelta[] getChangedFiles(IProject project) { List<IResourceDelta> list = map.get(project); if (list == null) { return null; } return (IResourceDelta[]) list.toArray(new IResourceDelta[list.size()]); } }
Python
UTF-8
1,550
2.53125
3
[]
no_license
import threading import cv2 import numpy as np import tensorflow as tf from skimage.feature import hog from torch.autograd import Variable from torchvision.transforms import transforms def predict_using_cnn(img, classifier): test_input = tf.estimator.inputs.numpy_input_fn( x={"x": img}, num_epochs=1, shuffle=False ) return list(classifier.predict(input_fn=test_input))[0]['classes'] def threaded_predict(x, clf_name, clf, all): pred = clf.predict_proba(x)[0] all[clf_name] = pred[1] # only one used def predict_using_pytorch_cnn(img, clsf): imsize = 28 loader = transforms.Compose([transforms.Resize(imsize), transforms.CenterCrop(28), transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) image = loader(img).float() image = Variable(image, requires_grad=True) image = image.unsqueeze(0) pred = clsf(image.cuda()).data.max(1, keepdim=True) return pred[1][0][0], pred[0][0][0] def predict_using_svm(img, clfs): roi_hog_fd = hog(img, orientations=9, pixels_per_cell=(14, 14), cells_per_block=(1, 1), visualise=False) threads = [] all = {} cv2.imshow("dbg", roi_hog_fd) x = np.array([roi_hog_fd], 'float64') for clf_name in clfs: clf = clfs[clf_name] thr = threading.Thread(target=threaded_predict, args=(x, clf_name, clf, all)) thr.start() for t in threads: t.join() #if max(all.values()) > 0.5: return max(all, key=all.get) return "?"#[max(all.values()), max(all, key=all.get)]
Java
UTF-8
3,025
2.359375
2
[]
no_license
package com.lan.bjgh; import com.arronlong.httpclientutil.HttpClientUtil; import com.arronlong.httpclientutil.common.HttpConfig; import com.arronlong.httpclientutil.exception.HttpProcessException; import com.fasterxml.jackson.databind.ObjectMapper; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; public class BjghToken { private static final Logger logger = LoggerFactory.getLogger(BjghToken.class); // ๆ•ฐๆฎไธญๅฐ public static String getMonitoreSupervision(String openapiUrl) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("appKey", "2c9849536c502347016c506774120003"); map.put("appSecret", "Am3iIOHFnPkItsY"); return getBjghToken(openapiUrl, map); } public static String getBjghToken(String openapiUrl, String appKey, String appSecret) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("appKey", appKey); map.put("appSecret", appSecret); return getBjghToken(openapiUrl, map); } // ่Žทๅ–token๏ผŒ่ฟ™้‡Œ้‡‡็”จpost ่กจๅ•ๆไบค๏ผŒ ๅ…ถไป–ๆ–นๅผๅ‚็œ‹ใ€Šไบงๅ“็†่งฃใ€‹ private static String getBjghToken(String openapiUrl, Map<String, Object> map) throws HttpProcessException { String url = openapiUrl + "auth"; //ๆ’ไปถๅผ้…็ฝฎ่ฏทๆฑ‚ๅ‚ๆ•ฐ๏ผˆ็ฝ‘ๅ€ใ€่ฏทๆฑ‚ๅ‚ๆ•ฐใ€็ผ–็ ใ€client๏ผ‰ HttpConfig config = HttpConfig.custom() // .headers(headers) //่ฎพ็ฝฎheaders๏ผŒไธ้œ€่ฆๆ—ถๅˆ™ๆ— ้œ€่ฎพ็ฝฎ .timeout(1000) //่ถ…ๆ—ถ .url(url) //่ฎพ็ฝฎ่ฏทๆฑ‚็š„url .map(map) //่ฎพ็ฝฎ่ฏทๆฑ‚ๅ‚ๆ•ฐ๏ผŒๆฒกๆœ‰ๅˆ™ๆ— ้œ€่ฎพ็ฝฎ .encoding("utf-8") //่ฎพ็ฝฎ่ฏทๆฑ‚ๅ’Œ่ฟ”ๅ›ž็ผ–็ ๏ผŒ้ป˜่ฎคๅฐฑๆ˜ฏCharset.defaultCharset() // .client(client) //ๅฆ‚ๆžœๅชๆ˜ฏ็ฎ€ๅ•ไฝฟ็”จ๏ผŒๆ— ้œ€่ฎพ็ฝฎ๏ผŒไผš่‡ชๅŠจ่Žทๅ–้ป˜่ฎค็š„ไธ€ไธชclientๅฏน่ฑก //.inenc("utf-8") //่ฎพ็ฝฎ่ฏทๆฑ‚็ผ–็ ๏ผŒๅฆ‚ๆžœ่ฏทๆฑ‚่ฟ”ๅ›žไธ€็›ด๏ผŒไธ้œ€่ฆๅ†ๅ•็‹ฌ่ฎพ็ฝฎ //.inenc("utf-8") //่ฎพ็ฝฎ่ฟ”ๅ›ž็ผ–็ ๏ผŒๅฆ‚ๆžœ่ฏทๆฑ‚่ฟ”ๅ›žไธ€็›ด๏ผŒไธ้œ€่ฆๅ†ๅ•็‹ฌ่ฎพ็ฝฎ //.json("jsonๅญ—็ฌฆไธฒ") //jsonๆ–นๅผ่ฏทๆฑ‚็š„่ฏ๏ผŒๅฐฑไธ็”จ่ฎพ็ฝฎmapๆ–นๆณ•๏ผŒๅฝ“็„ถไบŒ่€…ๅฏไปฅๅ…ฑ็”จใ€‚ //.context(HttpCookies.custom().getContext()) //่ฎพ็ฝฎcookie๏ผŒ็”จไบŽๅฎŒๆˆๆบๅธฆcookie็š„ๆ“ไฝœ //.out(new FileOutputStream("ไฟๅญ˜ๅœฐๅ€")) //ไธ‹่ฝฝ็š„่ฏ๏ผŒ่ฎพ็ฝฎ่ฟ™ไธชๆ–นๆณ•,ๅฆๅˆ™ไธ่ฆ่ฎพ็ฝฎ //.files(new String[]{"d:/1.txt","d:/2.txt"}) //ไธŠไผ ็š„่ฏ๏ผŒไผ ้€’ๆ–‡ไปถ่ทฏๅพ„๏ผŒไธ€่ˆฌ่ฟ˜้œ€map้…็ฝฎ๏ผŒ่ฎพ็ฝฎๆœๅŠกๅ™จไฟๅญ˜่ทฏๅพ„ ; //ไฝฟ็”จๆ–นๅผ๏ผš String result2 = HttpClientUtil.post(config); //post่ฏทๆฑ‚ logger.info("token็ป“ๆžœ๏ผš" + result2); JSONObject jsonTeaObject= JSONObject.fromObject(result2); return jsonTeaObject.getString("token"); } }
C++
UTF-8
725
2.625
3
[]
no_license
// Bai029.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <conio.h> #include <stdio.h> #include <math.h> #include <iostream> using namespace std; void main() { float a,b,c; cout<<"Nhap a:"<<endl; cin>>a; cout<<"Nhap b:"<<endl; cin>>b; cout<<"Nhap c:"<<endl; cin>>c; float D=b*b-4*a*c; if(a==0) { float x; x=float(-c/b); cout<<"Nghiem : "<<x; } else if(D>0) { float x1,x2; x1=float((-b-sqrt(D))/(2*a)); x2=float((-b+sqrt(D))/(2*a)); cout<<"Nghiem 1: "<<x1<<endl; cout<<"Nghiem 2: "<<x2<<endl; } if(D<0) { cout<<"Vo Nghiem"<<endl; } if(D==0) { float x3; x3= float(-b/2*a); cout<<"Nghiem kep: "<<x3<<endl; } }
Markdown
UTF-8
4,005
3.578125
4
[]
no_license
--- title: jQueryใ€HTMLใ€CSSไธญ็š„ๅฐ็ป†่Š‚ๆฑ‡ๆ€ป๏ผˆไธ€๏ผ‰ tags: - jQuery - CSS categories: ๅ‰็ซฏๅผ€ๅ‘ index_img: /img/css.jpg date: 2020-04-15 22:33:57 --- ่ฟ™ไธชๅšๅฎขๅ…ถไธญไธ€ไธช็›ฎ็š„๏ผŒๆ˜ฏไธ€่พนๅผ€ๅ‘ๅ‰็ซฏ้กต้ข๏ผŒไธ€่พน่ฎฐๅฝ•ไธ‹่‡ชๅทฑ้‡ๅˆฐ็š„้—ฎ้ข˜๏ผŒๅพˆๅคšๆ˜ฏ้žๅธธๆœ‰tricks็š„๏ผŒไน‹ๅŽไนŸๅฏ่ƒฝไผš้ข‘็น็”จๅˆฐใ€‚ ไธ‹่พนไธป่ฆๆ€ป็ป“็š„ๆ˜ฏ jQuery ๅ’Œ CSS ไธญ็š„ไธ€ไบ›ๅฐ็ป†่Š‚๏ผŒไน‹ๅŽๅฆ‚ๆžœ็งฏ็ดฏไบ†ๆ›ดๅคš็š„็‚น๏ผŒๅ†่กฅๅ……็ฌฌไบŒ็ฏ‡ใ€‚ <!-- more --> <br> # HTML ไธญ่Žทๅ– `<span>` ๆ ‡็ญพๅ†…็š„ๅ€ผ - jQuery ๅœจ jQuery ไธญ๏ผŒ่Žทๅ– HTML ไธญๅ„ไธชๆ ‡็ญพๅ†…ๅ€ผ็š„ๆ–นๆณ•ๆœ‰ๅ‡ ไธชใ€‚ ๆœ€่ฟ‘้‡ๅˆฐไบ†ๅฆ‚ไฝ•่Žทๅ– `<span>` ๆ ‡็ญพๅ†…็š„ๅ€ผ็š„้—ฎ้ข˜๏ผŒ่ฏ•้ชŒไบ†ไธ€ไธ‹ๅ‡ ็ง่Žทๅ–ๅ€ผ็š„ๆ–นๆณ•๏ผš ```html <html> <head> <script language=JavaScript src="js/jquery.min.js"></script> </head> <body> <span id="spId">show me</span> <script language=JavaScript> var test1 = $("#spId").val(); var test2 = $("#spId").html(); var test3 = $("#spId").text(); alert("val: " + test1); alert("html: " + test2); alert("text: " + test3); </script> </body> </html> ``` ไธ‰็ง่Žทๅ–ๆ‰€ๅพ—็š„ๅ€ผๅˆ†ๅˆซไธบ๏ผš ``` val: ็ฉบ html: show me text: show me ``` ๅ› ๆญค๏ผŒ - ่Žทๅ–input็š„ไฟกๆฏๆ—ถ๏ผŒๅฏไปฅ็”จ `val()` - ่Žทๅ– `<span>` ็š„ๅ€ผ๏ผŒๅฏไปฅ็”จ `html()` ๆˆ–่€… `text()` <br> # CSS ไธญ `active` ้€‰ๆ‹ฉๅ™จ็š„็”จๆณ• CSS ้€‰ๆ‹ฉๅ™จ `active` ไปฃ่กจๅ…ƒ็ด ่ขซๆฟ€ๆดป๏ผˆๆŒ‰ไธ‹๏ผ‰ๆ—ถ็š„ๆ ทๅผใ€‚โ€œๆฟ€ๆดปโ€ๆ˜ฏๆŒ‡ไปŽ็‚นๅ‡ปๆจกๅ—ๅŽ็›ดๅˆฐๆพๅผ€ๆจกๅ—็š„่ฟ‡็จ‹ใ€‚ ไพ‹ๅฆ‚๏ผš ```css a:active { background-color: yellow; } ``` ๆฅไธ€ไธช็ฎ€ๅ•็š„ๅฎž็Žฐไพ‹ๅญ๏ผš ```html <!DOCTYPE html> <html> <head> <style> a:active { background-color:yellow; } </style> </head> <body> <a href="http://www.google.com">Google</a> </body> </html> ``` **ๅฆๅค–๏ผŒ้œ€่ฆๆณจๆ„ไธ€ไธชๅŒบๅˆซ๏ผš** - `a.active` ๆ˜ฏๅฏน`class=active`็š„`a`ๆ ‡็ญพ็”Ÿๆ•ˆ - `a:active` ๆ˜ฏๅฏนๆŒ‰ไธ‹็š„`a`ๆ ‡็ญพ็”Ÿๆ•ˆ ไธค่€…ๆ‰€ไปฃ่กจ็š„ๅ†…ๆถตๆ˜ฏไธไธ€ๆ ท็š„ใ€‚ ๆญคๅค–๏ผŒ`active` ไนŸๅฏไปฅๅฎž็Žฐๅ…ƒ็ด  `display:none` ๅ’Œ `display:block` ็š„ๅˆ‡ๆขใ€‚ <br> # CSS ่ฎพ็ฝฎ่ƒŒๆ™ฏใ€่ƒŒๆ™ฏๅ›พ็‰‡ใ€blurๆ•ˆๆžœ - `background: url('url')` ็”จๆฅ่ฎพ็ฝฎ่ƒŒๆ™ฏๅ›พ็‰‡๏ผŒๅŽ่พนๅฏไปฅๅŠ  `no-repeat` ้™ๅˆถๆ˜ฏๅฆ้‡ๅคๅนณ้“บๅ›พๅƒ - `background-position` ๅ’Œ `background-size` ็”จๆฅ่ฐƒๆ•ดๅ›พ็‰‡็š„ๆ˜พ็คบๆ–นๅผ ```css .bg { background: url('1.jpg') no-repeat; height:600px; width: 100%; text-align: center; line-height: 600px; background-position: center; background-size: cover; } ``` - ๆœ€็ฎ€ๅ•็ฒ—ๆšด็š„่ฎพ็ฝฎ blur ็š„ๆ–นๆณ•๏ผŒๆ˜ฏ็›ดๆŽฅๅŠ ไธŠ `filter: blur(3px)` ็š„ๅฑžๆ€งใ€‚ไฝ†ๆ˜ฏ๏ผŒ่ฟ™ๆ ทไผšๅฏผ่‡ด่ƒŒๆ™ฏๅ›พๆ‰€ๅœจ `<div>` ๅ†…็š„ๅ…ถไป–ๅ…ƒ็ด ๏ผŒๅŒ…ๆ‹ฌๆ–‡ๅญ—๏ผŒ้ƒฝไผš่™šๅŒ–ใ€‚่งฃๅ†ณๅŠžๆณ•ๆœ‰ไธค็ง๏ผš - ็ฌฌไธ€๏ผŒๅฐ†่ƒŒๆ™ฏๅ›พ็‰‡ๅ•็‹ฌๆ”พๅˆฐไธ€ไธชdiv้‡Œ๏ผŒ่ฟ™ๆ ทๅฐฑไธไผšๅ’Œๅ…ถไป–ๅ…ƒ็ด ็š„ๆ•ˆๆžœๆœ‰ๅ†ฒ็ช - ็ฌฌไบŒ๏ผŒ้€š่ฟ‡ `:before` ็š„็Šถๆ€ๅ’Œ `z-index` ๆฅๆŽงๅˆถ๏ผŒๅช่ฎฉ่ƒŒๆ™ฏๅ›พ็‰‡่™šๅŒ–ใ€‚ไธพไธชไพ‹ๅญ๏ผš ```css .demo1{ width: 500px; height: 300px; line-height: 50px; text-align: center; } .demo1:before{ background: url(http://csssecrets.io/images/tiger.jpg) no-repeat; background-size: cover; width: 500px; height: 300px; content: ""; position: absolute; top: 0; left: 0; z-index: -1;/*-1 ๅฏไปฅๅฝ“่ƒŒๆ™ฏ*/ -webkit-filter: blur(3px); filter: blur(3px); } <div class="demo1">่ƒŒๆ™ฏๅ›พๅŠ้€ๆ˜Ž๏ผŒๆ–‡ๅญ—ไธ้€ๆ˜Ž<br/> ๆ–นๆณ•๏ผš่ƒŒๆ™ฏๅ›พ+ filter๏ผšblur </div> ``` ่ฟ™็ง่ฎพ็ฝฎๅฏไปฅๅœจไธๆ”นๅ˜div็ป“ๆž„็š„ๆƒ…ๅ†ตไธ‹๏ผŒไฝฟ่ƒŒๆ™ฏๅ›พ็‰‡่™šๅŒ–ใ€‚ --- **ๅ‚่€ƒๆฅๆบ๏ผš** - *[cssๅฎž็Žฐ display: noneๅ’Œdisplay: block็š„ๅˆ‡ๆขๅŠจ็”ป](https://blog.csdn.net/qq_37540004/article/details/78280454)* - *[CSSๆ ทๅผ็š„็Šถๆ€hoverใ€focusใ€activeใ€linkใ€visited่ฏฆ่งฃ](https://blog.csdn.net/xiaoxiao20121314/article/details/81103500)* - *[CSSๅฎž็Žฐ่ƒŒๆ™ฏๅ›พ็‰‡้€ๆ˜Žๅ’Œๆ–‡ๅญ—ไธ้€ๆ˜Žๆ•ˆๆžœ](https://www.jianshu.com/p/12a938e5c557)*
Java
UTF-8
1,629
2.75
3
[]
no_license
package angry1980.audio.dao; import angry1980.audio.model.TrackHash; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; public class TrackHashDAOInMemoryImpl implements TrackHashDAO { private static Comparator<TrackHash> c = Comparator.comparingInt(TrackHash::getTime); private final long mask; private final ConcurrentMap<Long, Collection<TrackHash>> index; public TrackHashDAOInMemoryImpl(){ this(16, -1); } public TrackHashDAOInMemoryImpl(long mask){ this(16, mask); } public TrackHashDAOInMemoryImpl(int expectedSize, long mask){ this.index = new ConcurrentHashMap<>(expectedSize); this.mask = mask; } @Override public Optional<TrackHash> create(TrackHash hash) { if(hash != null){ index.computeIfAbsent(getKey(hash.getHash()), l -> new CopyOnWriteArrayList<>()).add(hash); } return Optional.ofNullable(hash); } @Override public Collection<TrackHash> findByHash(long hash) { return index.getOrDefault(getKey(hash), Collections.emptyList()); } @Override public Collection<TrackHash> findByHashes(long[] hashes) { return Arrays.stream(hashes) .mapToObj(this::findByHash) .flatMap(data -> data.stream()) .collect(Collectors.toSet()); } private long getKey(long hash){ if(mask == -1){ return hash; } return hash & mask; } }
Markdown
UTF-8
1,509
2.890625
3
[]
no_license
--- id: 463 title: Puppet filebucketing fail with NFS date: 2012-09-27T14:09:28+00:00 author: Andy Botting layout: post permalink: /puppet-filebucketing-fail-with-nfs aktt_notify_twitter: - 'no' categories: - Personal --- I&#8217;ve got back to Australia and I&#8217;m continuing my UK job from home. So yesterday, I was doing some cleaning up and needed to unmount an NFS share and clean up its mount point directory. You can see from the Puppet code below that I marked both resources as &#8216;absent&#8217; to clean them up. <pre>file { '/tmp/install': ensure =&gt; 'absent' } mount { '/tmp/install': ensure ย  =&gt; 'absent', device ย  =&gt; nfs-server:/install, fstype ย  =&gt; nfs }</pre> This triggered Puppet to start filebucketing everything it could from the NFS share and subsequently filling up the root filesystem. I managed to revert my commit fairly quickly, but a large number of hosts in our infrastructure had already picked this up. This included both development and production systems. There is an existing Puppet bug report about the issue atย <http://projects.puppetlabs.com/issues/2019> Apart from the obvious mistake that I should have just run this in a test environment first, this was totally unexpected behaviour. A couple of things you could do to prevent this happening to you: 1. Disable filebucketing either globally, or just for this file resource 2. Don&#8217;t try to remove the NFS mount and directory at the same time Hope this helps.
PHP
UTF-8
1,840
2.78125
3
[ "MIT" ]
permissive
<?php /******************************************************************************* * * CrystalPHP Framework by Crystal Collective * An open source application development framework for PHP * * This file is part of CrystalPHP which is released under the MIT License (MIT) * * Copyright (c) 2019 - 2019, Crystal Collective * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. * ******************************************************************************/ /** * User: Pankaj Vaghela * Date: 19-05-2019 * Time: 12:45 */ namespace CrystalPHP; /** * Class Registry * @package CrystalPHP * * * @property App $app * @property Registry $registry * @property Config\Config $config * @property Request $request * @property Response $response * @property Lib\Logger\Logger $logger * * @property array $dispatch_data */ class Registry{ static private $instance = null; private $data_array_list = array(); public function __construct(){ } /** * @return Registry */ static function getInstance(){ if(self::$instance == null){ self::$instance = new Registry(); } return self::$instance; } /** * @param $key string * @return bool */ public function has($key){ return isset($this->data_array_list[$key]); } public function __get($key){ return $this->get($key); } public function __set($key, $value){ return $this->set($key, $value); } /** * @param $key * @return mixed|null */ public function get($key){ return (isset($this->data_array_list[$key]) ? $this->data_array_list[$key] : null); } /** * @param $key * @param $value * @return mixed */ public function set($key, $value){ return $this->data_array_list[$key] = $value; } private function __clone(){ } }
JavaScript
UTF-8
936
2.84375
3
[]
no_license
// Create section.container document.write('<section class="container">'); for(let i=1; i<=30; i++){ var id = String(i); document.write('<div class="box unlocked" id="_' + id + '"><i class="fa fa-unlock-alt" onclick=lock("_' + id + '");></i><p onclick=copy(' + id + ');></p></div>'); } document.write('</section>'); // Onclick "REFRESH" button make section.container visible $(".btn").click(function(){ $(".container").css("display", "flex"); }); // Display Functionality $(document).ready(function(){ $(".list").click(function(){ const value = $(this).attr("data-filter"); if (value == "all"){ $(".box").show("1000"); } else{ $(".box").not("." + value).hide("1000"); $(".box").filter("." + value).show("1000"); } $(this).addClass("active").siblings().removeClass("active"); }) })
Java
UTF-8
431
1.890625
2
[]
no_license
package zalex.person.com.frameworklib.location; import android.content.Context; import com.baidu.location.BDAbstractLocationListener; /** * Created by zhouweinan on 2018/5/2. */ public abstract class LocationInterface extends BDAbstractLocationListener { public abstract void init(Context context); public abstract void bindListener(LocationListener locationListener); public abstract void unbindListener(); }
PHP
UTF-8
2,405
2.953125
3
[ "MIT" ]
permissive
<?php /* * This file is part of the sfMediaBrowser package. * * (c) 2010 Vincent Agnano <vincent.agnano@particul.es> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * sfValidatorMediaBrowser validates a directory. * * @package sfMediaBrowserPlugin * @subpackage validator * @author Vincent Agnano <vincent.agnano@particul.es> */ class sfValidatorMediaBrowserDirectory extends sfValidatorBase { /** * Configures the current validator. * * Available options: * * * root string full system path to root directory * * relative boolean|false wether the value to test will be relative to root instead of an absolute file system path. * * root_allowed boolean|true wether the root itself is an allowed value * * * @param array $options An array of options * @param array $messages An array of error messages * @return return an absolute system path or null * * @see sfValidatorBase */ protected function configure($options = array(), $messages = array()) { $this->setMessage('invalid', '"%directory%" is not a valid directory path.'); $this->addOption('root'); $this->addOption('relative', false); $this->addOption('root_allowed', true); if(!isset($options['trim'])) { $this->setOption('trim', true); } } /** * @see sfValidatorBase */ protected function doClean($value) { $full_path = $this->getOption('relative') ? realpath($this->getOption('root').'/'.$value) : realpath($value); // check directory exists if(!$full_path) { throw new sfValidatorError($this, 'invalid', array('directory' => $full_path)); } // check directory is inside the specified root elseif($this->getOption('root')) { $root = realpath($this->getOption('root')); // specified root does not exist if(!file_exists($root)) { throw new sfConfigurationException(sprintf('sfValidatorMediaBrowserDirectory root option "%s" is not an existing directory.', $this->getOption('root'))); } // value is not inside root $root_mask = $this->getOption('root_allowed') ? $root : $root.'/'; if(mb_strpos($full_path, $root_mask) !== 0) { throw new sfValidatorError($this, 'invalid', array('directory' => $full_path)); } } return $full_path; } }
C++
UTF-8
3,384
3.15625
3
[]
no_license
#include "matrix.h" #include <iostream> #include <cstdlib> #include <ctime> #include <fstream> #include <thread> void MatrixProduct(const MyMatrix& matrix_a, const MyMatrix& matrix_b, MyMatrix *matrix_result, const int& start, const int& end); int main(int argc, char* argv[]){ clock_t start, end; double result = 0; srand(time(NULL)); auto matrix_c = new MyMatrix(); auto matrix_d = new MyMatrix(); auto matrix_result = new MyMatrix("C.dat"); if (argv[1] == nullptr){ // if not exist A.dat B.dat // create A.dat B.dat auto matrix_a = new MyMatrix("A.dat"); auto matrix_b = new MyMatrix("B.dat"); matrix_a->CreateMatrix(); matrix_b->CreateMatrix(); matrix_a->CreateDataFile(); matrix_b->CreateDataFile(); matrix_c->ReadMatrix("A.dat"); matrix_d->ReadMatrix("B.dat"); delete matrix_a; delete matrix_b; } else { matrix_c->ReadMatrix(argv[1]); matrix_d->ReadMatrix(argv[2]); } matrix_c->PrintMatrix(); std:: cout << "-----------------------------" << std::endl; matrix_d->PrintMatrix(); std:: cout << "-----------------------------" << std::endl; start = clock(); std::thread t1(MatrixProduct, *matrix_c, *matrix_d, matrix_result, 0, kThreadWorkQuantum); std::thread t2(MatrixProduct, *matrix_c, *matrix_d, matrix_result, kThreadWorkQuantum, kThreadWorkQuantum*2); std::thread t3(MatrixProduct, *matrix_c, *matrix_d, matrix_result,kThreadWorkQuantum*2 ,kThreadWorkQuantum*3); std::thread t4(MatrixProduct, *matrix_c, *matrix_d, matrix_result,kThreadWorkQuantum*3 ,kThreadWorkQuantum*4); t1.join(); t2.join(); t3.join(); t4.join(); end = clock(); result = (double)(end-start); std::cout << std::endl << "Thread 1 Result" << std::endl; matrix_result->PrintMatrix(0,kThreadWorkQuantum -1); //thread work range std:: cout << "-----------------------------" << std::endl; std::cout << std::endl << "Thread 2 Result" << std::endl; matrix_result->PrintMatrix(kThreadWorkQuantum,(kThreadWorkQuantum*2)-1); std:: cout << "-----------------------------" << std::endl; std::cout << std::endl << "Thread 3 Result" << std::endl; matrix_result->PrintMatrix(kThreadWorkQuantum*2,(kThreadWorkQuantum*3)-1); std:: cout << "-----------------------------" << std::endl; std::cout << std::endl << "Thread 4 Result" << std::endl; matrix_result->PrintMatrix(kThreadWorkQuantum*3,(kThreadWorkQuantum*4)-1); std:: cout << "-----------------------------" << std::endl; matrix_result->PrintMatrix(); matrix_result->CreateDataFile(); //create C.dat delete matrix_c; delete matrix_d; delete matrix_result; std::cout << "End main()" << std::endl; std::cout << "time :" << (double)result/ CLOCKS_PER_SEC << "sec" << std::endl; return 0; } void MatrixProduct(const MyMatrix& matrix_a, const MyMatrix& matrix_b, MyMatrix *matrix_result, const int& start, const int& end){ int row, column; int i; for (row = start; row<end; row++){ for (column = 0; column<kMaxColumn;column++){ for (i=0;i<kMaxColumn;i++){ matrix_result->matrix_[row][column] += matrix_a.matrix_[row][i] * matrix_b.matrix_[i][column]; } } } }
Markdown
UTF-8
1,181
3.53125
4
[ "MIT" ]
permissive
--- categories: - Java - Beginning date: 2019-04-20 16:37:53 tag: Java title: Java-ๆกไปถ --- # Java ๆกไปถ่ฏญๅฅ ## if-else ่ฏญๅฅ Java ็š„ `if` ๆกไปถ่ฏญๅฅๅ’Œ C ๅฎŒๅ…จไธ€่‡ดใ€‚ ```java if (expression_0) { // statements } else if (expression_1) { // statements } else { // statements } ``` ~~ๆ— ้œ€่งฃ้‡Š~~ ## switch-case ่ฏญๅฅ ```java switch(expression){ case value_0 : //่ฏญๅฅ break; //ๅฏ้€‰ case value_1 : //่ฏญๅฅ break; //ๅฏ้€‰ //ไฝ ๅฏไปฅๆœ‰ไปปๆ„ๆ•ฐ้‡็š„case่ฏญๅฅ default : //ๅฏ้€‰ //่ฏญๅฅ } ``` Java ไธญ็š„ `switch` ๅคงไฝ“ไธŠๅ’Œ C ็š„็›ธๅŒ๏ผŒไฝ†ไนŸๆœ‰ไธๅŒ็š„ๅœฐๆ–นใ€‚ๅ€ผๅพ—ไธ€ๆ็š„ๆ˜ฏๅฆ‚ไธ‹ๅ‡ ็‚น๏ผš * ๅŒ C ไธ€ๆ ท๏ผŒ * case ่ฏญๅฅไธญ็š„ๅ€ผ็š„ๆ•ฐๆฎ็ฑปๅž‹ๅฟ…้กปไธŽๅ˜้‡็š„ๆ•ฐๆฎ็ฑปๅž‹็›ธๅŒ๏ผŒ่€Œไธ”ๅช่ƒฝๆ˜ฏๅธธ้‡ๆˆ–่€…ๅญ—้ขๅธธ้‡ใ€‚ * ๅŒๆ—ถ้œ€่ฆๆณจๆ„ `case` ๅŽไธ€็›ดๆ‰ง่กŒๅˆฐ `break` ๆ‰ไผšๅœๆญข๏ผˆๆˆ–่€…ๆ‰ง่กŒๅˆฐๅ…จ้ƒจ็ป“ๆŸ๏ผ‰๏ผŒไธไผšๅœจไธ€ไธช case ็ป“ๆŸๅŽ่‡ชๅŠจๅœๆญข๏ผ * ไธŽ C ไธๅŒ็š„ๆ˜ฏ๏ผŒ * Java ไธญ `switch` ๅŽ้ข็š„ expression ๅฏไปฅๆ˜ฏ `byte`ใ€`short`ใ€`int` ๆˆ–่€… `char`ใ€‚ไปŽ Java SE 7 ๅผ€ๅง‹๏ผŒswitch ๆ”ฏๆŒๅญ—็ฌฆไธฒ `String` ็ฑปๅž‹ไบ†ใ€‚
PHP
UTF-8
4,631
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\TraitClass; use Illuminate\Http\Request; trait GetListTrait { public $rq; public $isGetListData; /** * ๅˆ—่กจๆ•ฐๆฎ * limit ๅˆ†้กตๆ•ฐ * @param Request $request * @return array|\Illuminate\Http\JsonResponse|string */ public function getList(Request $request) { $this->rq = $request; $page = $request->input('page', 1); $pagesize = $request->input('limit', 30); $order_by_name = $this->orderByName(); $order_by_type = $this->orderByType(); $debug = $request->input('debug', 0); //ๅฆ‚ๆžœๅผ€ๅง‹ๆฒกๆœ‰ๆ•ฐๆฎ๏ผŒ็›ดๆŽฅ่ฟ”ๅ›ž็ฉบ็š„ if (!method_exists($this, 'getModel')) { return $this->returnApi(200, 'ๆฒกๆœ‰ๅˆๅง‹ๅŒ–ๆจกๅž‹2', []); } if (!$this->getModel()) { return $this->returnApi(200, 'ๆฒกๆœ‰ๅˆๅง‹ๅŒ–ๆจกๅž‹', []); } $model = $this->getSearchModel($this->setSearchParam($request->all())); $model = $this->addListSearchWhere($model); //ๆ˜ฏๅฆๆ˜ฏๅฆๅ…ณ่”ๆ•ฐๆฎ็ญ‰ๆ“ไฝœ $model = $this->setModelRelaction($model); $total = $model->count();//ๆ”พๅˆฐๅพŒ้ข $model = $this->orderBy($model, $order_by_name, $order_by_type); $result = $model->forPage($page, $pagesize)->get(); //ๆ˜พ็คบๅ†…ๅฎน่ฎพ็ฝฎ $arr_data = $this->listOutputData($result); return $this->listOutputJson($total, $arr_data, $debug); } public function listOutputJson($total, $data, $debug = "0") { $json = [ 'code' => 200, 'msg' => $total > 0 ? '่ฏทๆฑ‚ๆ•ฐๆฎๆˆๅŠŸ' : 'ๆš‚ๆ— ๆ•ฐๆฎ', 'count' => $total, 'data' => $data, 'other' => $this->listOutputOtherData($total, $data) ]; if ($debug) { return dd($data); } if ($this->isGetListData) { return $json; } return $this->returnApiData($json); } /** * ๆ•ฐๆฎๅˆ—่กจๅ…ถไป–ๆ•ฐๆฎ่พ“ๅ‡บ๏ผŒๅฏ็”จไบŽ็ปŸ่ฎกๅ†…ๅฎน่พ“ๅ‡บ้™„ๅŠ  * @param int $total * @param array $data */ public function listOutputOtherData($total = 0, $data = []) { } /** * ๅˆ—่กจ่พ“ๅ‡บๆ ผๅผ * @param $result * @return array */ public function listOutputData($result) { $data = []; foreach ($result as $k => $v) { //ๅˆ—่กจ่พ“ๅ‡บๆ ผๅผๅ•้กน็›ฎ่ฎพ็ฝฎ $v = $this->setListOutputItem($v); $data[] = $v; } return $data; } /** * ๅˆ—่กจ่พ“ๅ‡บๆ ผๅผๅ•้กน็›ฎ่ฎพ็ฝฎ * @param $item * @return mixed */ public function setListOutputItem($item) { $item = $this->editUrlShow($item); $item = $this->setListOutputItemExtend($item); return $item; } //็ผ–่พ‘็š„ๅœฐๅ€่ต‹ๅ€ผ public function editUrlShow($item) { $item['edit_url'] = ''; $item['edit_post_url'] = ''; return $item; } /** * ๅˆ—่กจ่พ“ๅ‡บๆ ผๅผๅ•้กน็›ฎ้™„ๅŠ ่ฎพ็ฝฎ * @param $item * @return mixed */ public function setListOutputItemExtend($item) { return $item; } /** * ๆŽ’ๅบๅญ—ๆฎตๅๅญ— * @return mixed */ public function orderByName() { return $this->rq->input('sort', 'id'); } /** * ๆŽ’ๅบ็ฑปๅž‹ * @return mixed */ public function orderByType() { return $this->rq->input('order', 'desc') ?: 'desc'; } /** * ่ฎพ็ฝฎๆŽ’ๅบๆ–นๆณ• * @param $model * @param $order_id * @param $order_type * @return mixed */ public function orderBy($model, $order_by_name, $order_by_type) { if ($order_by_name == 'id') { return $model->orderBy($order_by_name, $order_by_type); } else { return $model->orderBy($order_by_name, $order_by_type)->orderBy('id', 'desc'); } } /** * ่ฎพ็ฝฎๆœ็ดขๆจกๅž‹็š„POSTๆ•ฐๆฎ * ๆฏ”ๅฆ‚้œ€่ฆๆ‰‹ๅŠจ่ฟฝๅŠ ่ฟ™้‡Œ้™„ๅŠ  * @param $data * @return mixed */ public function setSearchParam($data) { return $data; } /** * ่ฎพ็ฝฎๆœ็ดขๆกไปถๅ‚ๆ•ฐ * @param $data * @return mixed */ public function getSearchModel($data, $type = '') { $model = $this->getModel()->getSearchModel($this->getModel(), $data, $type); return $model; } /** * ่ฎพ็ฝฎ็›ธๅ…ณๅขžๅŠ ๆœ็ดขๆกไปถๆˆ–่€…ๅ…ถไป–็š„ๆ“ไฝœ * @param $model * @return mixed */ public function setModelRelaction($model) { return $model; } }
Python
UTF-8
3,216
2.90625
3
[]
no_license
''' The lepspho (LEPS plus harmonic oscillator) potential module plus two Gaussians. ''' import numpy import lepspho_ class lepspho: ''' The lepspho (LEPS plus harmonic oscillator) potential class. ''' def __init__(self): ''' Initialize the lepspho (LEPS plus harmonic oscillator) potential module. ''' self.atoms = None self.u = None self.f = None def calculate(self): ''' Perform a force call with the lepspho (LEPS plus harmonic oscillator) potential. Parameters: p: tsse.point object. ''' ra = numpy.zeros(6,'d') fa = numpy.zeros(6,'d') uRet = numpy.array([0],'d') rtmp = self.atoms.get_positions() ra[0] = rtmp[0][0] ra[3] = rtmp[0][1] lepspho_.force(ra,fa,uRet) self.f = rtmp * 0.0 self.f[0][0] = fa[0] self.f[0][1] = fa[3] self.u = uRet[0] ugauss, fgauss = self.gaussianpart(ra) self.u += ugauss self.f += fgauss def get_potential_energy(self, atoms=None, force_consistent=False): if self.calculation_required(atoms, "energy"): self.atoms = atoms.copy() self.calculate() return self.u def get_forces(self, atoms): if self.calculation_required(atoms, "forces"): self.atoms = atoms.copy() self.calculate() return self.f.copy() def get_stress(self, atoms): raise NotImplementedError def calculation_required(self, atoms, quantities): if atoms != self.atoms or self.atoms == None: return True if self.f == None or self.u == None or atoms == None: return True return False def set_atoms(self, atoms): pass def gaussianpart(self, ra): A1 = -1.5 x01 = 2.02083 y01 = -0.172881 sigmax1 = 0.1 sigmay1 = 0.35 A2 = 6.0 x02 = 0.8 y02 = 2.0 sigmax2 = 0.5 sigmay2 = 0.7 rx = ra[0] ry = ra[3] ugauss1 = self.gaussian_u(rx, ry, A1, x01, y01, sigmax1, sigmay1) ugauss2 = self.gaussian_u(rx, ry, A2, x02, y02, sigmax2, sigmay2) ugauss = ugauss1 + ugauss2 fgauss1 = -self.gaussian_f(rx, ry, A1, x01, y01, sigmax1, sigmay1) fgauss2 = -self.gaussian_f(rx, ry, A2, x02, y02, sigmax2, sigmay2) fgauss = fgauss1 + fgauss2 return ugauss, fgauss def gaussian_u(self, rx, ry, A, x0, y0, sigmax, sigmay): gxy = A * numpy.exp(-(rx - x0)**2 / (2 * sigmax**2)) \ * numpy.exp(-(ry - y0)**2 / (2 * sigmay**2)) return gxy def gaussian_f(self, rx, ry, A, x0, y0, sigmax, sigmay): gfx = A * numpy.exp(-(rx - x0)**2 / (2 * sigmax**2)) \ * numpy.exp(-(ry - y0)**2 / (2 * sigmay**2)) \ * (-rx + x0) / sigmax**2 gfy = A * numpy.exp(-(rx - x0)**2 / (2 * sigmax**2)) \ * numpy.exp(-(ry - y0)**2 / (2 * sigmay**2)) \ * (-ry + y0) / sigmay**2 return numpy.array([[gfx, gfy, 0]])
C++
UTF-8
822
2.671875
3
[]
no_license
#pragma once #include "Engine\Math\IntVector2.hpp" #include "Engine\Core\Rgba.hpp" #include "Engine\Math\Matrix4.hpp" #include "Engine\Renderer\RHI\SpriteSheet2D.hpp" //Forward Declares class Character; //Enums enum StatusEffectType { STATUS_WALL = 0, STATUS_CHARM, STATUS_CONFUSE, STATUS_POISON, NUM_STATUS_EFFECTS }; enum StatusEffectVisualType { VISUAL_SPRITE, VISUAL_TINT }; //Class class StatusEffect { public: StatusEffect(StatusEffectType typeToCreate, int duration); ~StatusEffect(); void DrawSpriteAtOffsetFromTransform(const Matrix4& transform, const Vector3& offset, float radius) const; public: StatusEffectType m_type; int m_remainingDuration; StatusEffectVisualType m_visualType; IntVector2 m_spriteCoords; Rgba m_characterTint; static SpriteSheet2D* s_statusEffectSpriteSheet; };
Markdown
UTF-8
2,944
3.03125
3
[ "Apache-2.0" ]
permissive
# ZenSwitch GPIO ## Overview Mongoose OS library for GPIO-enabled ZenSwitches. ## GET STARTED Build up your own device in few minutes just starting from one of the following samples. |Sample|Notes| |--|--| |[zswitch-gpio-demo](https://github.com/zendiy-mgos/zswitch-gpio-demo)|Mongoose OS demo firmware for using GPIO-enabled ZenSwitches.| ## Usage Include the library into your `mos.yml` file. ```yaml libs: - origin: https://github.com/zendiy-mgos/zswitch-gpio ``` If you are developing a JavaScript firmware, load `api_zswitch_gpio.js` in your `init.js` file. ```js load('api_zswitch_gpio.js'); ``` ## C/C++ API Reference ### mgos_zswitch_gpio_cfg ```c struct mgos_zswitch_gpio_cfg { bool active_high; }; ``` GPIO configuration settings for `mgos_zswitch_gpio_attach()`. |Field|| |--|--| |active_high|`true` if switch is ON when GPIO output is high (1).| ### mgos_zswitch_gpio_attach() ```c bool mgos_zswitch_gpio_attach(struct mgos_zswitch *handle, int pin, struct mgos_zswitch_gpio_cfg *cfg); ``` Attach the switch to the GPIO. Returns `true` on success, `false` otherwise. |Parameter|| |--|--| |handle|Switch handle.| |pin|GPIO pin.| |cfg|Optional. GPIO configuration. If `NULL`, following default configuration values are used: active_high=`true`.| **Example** - Create a switch using default configuration values and attach it to the GPIO 5. ```c struct mgos_zswitch *sw = mgos_zswitch_create("sw-1", NULL); mgos_zswitch_gpio_attach(sw, 5, NULL); } ``` ### mgos_zswitch_gpio_detach() ```c bool mgos_zswitch_gpio_detach(struct mgos_zswitch *handle); ``` Detach the switch from the GPIO that was previously attached using `mgos_zswitch_gpio_attach()`. Returns `true` on success, `false` otherwise. |Parameter|| |--|--| |handle|Switch handle.| ## JS API Reference ### .GPIO.attach() ```js let success = sw.GPIO.attach(pin, cfg); ``` Attach the switch to the GPIO. Returns `true` on success, `false` otherwise. |Parameter|Type|| |--|--|--| |pin|numeric|GPIO pin.| |cfg|object|Optional. GPIO configuration. If missing, default configuration values are used.| **GPIO configuration properties** |Property|Type|| |--|--|--| |*cfg*.activeHigh|boolean|Optional. `true` if switch is ON when GPIO output is high (1).| **Example** - Create a switch using default configuration values and attach it to the GPIO 5. ```js let sw = ZenSwitch.create('sw-1'); let success = sw.GPIO.attach(5, {activeHigh: true}); ``` ### .GPIO.detach() ```js let success = sw.GPIO.detach(); ``` Detach the switch from the GPIO that was previously attached using `.GPIO.attach()`. Returns `true` on success, `false` otherwise. ## Additional resources Take a look to some other demo samples. |Sample|Notes| |--|--| |[zswitch-demo](https://github.com/zendiy-mgos/zswitch-demo)|Mongoose OS demo firmware for using ZenSwitches.| |[zswitch-mqtt-demo](https://github.com/zendiy-mgos/zswitch-mqtt-demo)|Mongoose OS demo firmware for using MQTT to drive ZenSwitches.|
Markdown
UTF-8
1,261
2.859375
3
[ "MIT" ]
permissive
## British Columbia: Who should I contact if I think I have COVID-19? If you have traveled to an affected area or develop symptoms, avoid contact with others and call ahead to a health-care professional. Do the same if you develop symptoms and have been in contact with a confirmed case or a traveller returning from the affected area with these symptoms. Tell your health-care professional: - your symptoms; - where you have been travelling or living; - if you had direct contact with animals (for example, if you visited a live animal market); and - if you had close contact with a sick person, especially if they had a fever, cough or difficulty breathing. Call ahead to the health-care facility you are planning to visit so they can be prepared to take precautions. In an emergency, describe your symptoms, travel history and any sick contacts when you first arrive at the facility so that appropriate precautions can be taken. Until more is understood about the virus, older people and people with a weakened immune system or underlying medical condition are considered at higher risk of severe disease. [Source: BC Centre for Disease Control](<http://www.bccdc.ca/health-info/diseases-conditions/coronavirus-(novel)#Information--about--the--virus>)
Python
UTF-8
154
3.796875
4
[]
no_license
#using the input function name=input("Enter your name:") regno=int(input("Enter your regno:")) print("My name is ",name) print("My regno is ",regno)
Java
UTF-8
1,163
2.34375
2
[]
no_license
package com.shaw.blog.model; import com.shaw.blog.core.BaseEntity; import javax.persistence.*; @Table(name = "article_sort") public class ArticleSort extends BaseEntity { /** * ๆ–‡็ซ ็ฑปๅˆซ่‡ชๅขžID */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * ๅˆ†็ฑปๅ็งฐ */ @Column(name = "sort_article_name") private String sortArticleName; /** * ่Žทๅ–ๆ–‡็ซ ็ฑปๅˆซ่‡ชๅขžID * * @return id - ๆ–‡็ซ ็ฑปๅˆซ่‡ชๅขžID */ public Long getId() { return id; } /** * ่ฎพ็ฝฎๆ–‡็ซ ็ฑปๅˆซ่‡ชๅขžID * * @param id ๆ–‡็ซ ็ฑปๅˆซ่‡ชๅขžID */ public void setId(Long id) { this.id = id; } /** * ่Žทๅ–ๅˆ†็ฑปๅ็งฐ * * @return sort_article_name - ๅˆ†็ฑปๅ็งฐ */ public String getSortArticleName() { return sortArticleName; } /** * ่ฎพ็ฝฎๅˆ†็ฑปๅ็งฐ * * @param sortArticleName ๅˆ†็ฑปๅ็งฐ */ public void setSortArticleName(String sortArticleName) { this.sortArticleName = sortArticleName; } }
C#
UTF-8
2,805
2.59375
3
[]
no_license
๏ปฟusing System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.IO; using System.Web; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json; namespace StokProgramiApp { public partial class Product_Add : Form { public Product_Add() { InitializeComponent(); } private static readonly HttpClient client = new HttpClient(); private async void button1_ClickAsync(object sender, EventArgs e) { var values = new Dictionary<string, string> { { "name", textBox1.Text }, { "id_product_type", textBox2.Text }, {"serial_no", textBox3.Text }, {"product_stock", textBox4.Text } }; var content = new FormUrlEncodedContent(values); var response = await client.PostAsync("http://localhost:54012/api/Products/1", content); var responseString = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { MessageBox.Show("You have been Added a Product Successfully"); } else MessageBox.Show("Invalid Property Values"); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void Form4_Load(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { DialogResult select = MessageBox.Show("Are You Sure Want to Return Main Menu? ", "Main Menu", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (select == DialogResult.No) { return; } this.Hide(); new Main_Menu().Show(); } private void panel1_Paint(object sender, PaintEventArgs e) { } private void textBox4_TextChanged(object sender, EventArgs e) { } private void pictureBox2_Click(object sender, EventArgs e) { DialogResult select = MessageBox.Show("Are You Sure Want to Exit? ", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (select == DialogResult.No) { return; } Application.Exit(); } } }
Java
ISO-8859-1
3,806
3.34375
3
[]
no_license
package id3; import java.util.HashMap; import java.util.LinkedList; public class ExampleSet { LinkedList<Example> l; HashMap<Category,LinkedList<Example>> hm; int size; /* * Le constructeur standard */ public ExampleSet(LinkedList<Example> l) { this.l = new LinkedList<Example>(l); size = l.size(); this.hm = new HashMap<Category, LinkedList<Example>>(); Category c = null; for (Example e : l) { c = e.getCategory(); if (hm.get(c) == null) { hm.put(c, new LinkedList<Example>()); } hm.get(c).add(e); } } public int getSize() { return size; } public int numCats() { return hm.size(); } /* * Renvoie d * log(d), ou 0 si d=0. */ double plogp(double d) { if (d <= 0) { // System.out.println("Plogp called with value <= 0"); return 0; } else { // System.out.println("Plogp called with value " + d); return (d*Math.log(d)); } } /* * Renvoie l'entropie d'un ExampleSet */ // TODO : ne le calculer qu'une fois.. double entropy() { double rep = 0; double prop = 0; for(Category c : hm.keySet()) { prop = (1/(double)size) * hm.get(c).size(); rep -= plogp(prop); } // System.out.println("Entropy computed with value " + rep); return rep; } /* * Calcule la prochaine meilleure question * Pas de garantie que a fonctionne si l'ensemble est vide.. */ Answer getNextQuestion(LinkedList<Attribute> attributes) { Attribute rep = null; HashMap<AttrValue,ExampleSet> argrep = null; double maxGain = -1; HashMap<AttrValue,ExampleSet> argcur = null; double gaincur = 0; for (Attribute a : attributes) { argcur = possibleDistributions(a); gaincur = gain(a,argcur); if (gaincur > maxGain) { rep = a; maxGain = gaincur; argrep = argcur; } } // System.out.println("Thus we choose attribute " + rep + " because gain is " + maxGain); return new Answer(rep, argrep); } /* * Calcule le gain d'une question donne */ double gain(Attribute a, HashMap<AttrValue,ExampleSet> m) { double rep = this.entropy(); // System.out.println("rep : " + rep); ExampleSet es = null; double tmp = 0; for (AttrValue v : m.keySet()) { es = m.get(v); // System.out.println("(1/"+size+"[size])*("+es.getSize()+"[es.getSize()])*("+es.entropy()+"[es.entropy()])"); // System.out.println("rep : " + rep); tmp = (1/(double)size)*(es.getSize())*(es.entropy()); // System.out.println("tmp : " + tmp); rep -= tmp; // System.out.println("rep : " + rep); } // System.out.println("Choosing attribute " + a + " would mean a gain of " + rep); return rep; } /* * Renvoie l'ensemble des distributions que l'on peut recevoir aprs avoir pos une question donne */ HashMap<AttrValue,ExampleSet> possibleDistributions(Attribute a) { HashMap<AttrValue,LinkedList<Example>> sv = new HashMap<AttrValue, LinkedList<Example>>(); HashMap<AttrValue,ExampleSet> sv2 = new HashMap<AttrValue, ExampleSet>(); // On calcule la liste parmi l de ceux qui rpondent v a, pour tous les v. AttrValue v = null; for (Example e : l) { v = e.getAnswer(a); if (sv.get(v) == null) { sv.put(v, new LinkedList<Example>()); } sv.get(v).add(e); } for (AttrValue v2 : sv.keySet()) { sv2.put(v2, new ExampleSet(sv.get(v2))); } return sv2; } /* * Renvoie la catgorie la plus frquente */ Category mostProbableCat() { Category rep = null; int mSize = -1; int tmpSize = 0; for (Category c : hm.keySet()) { tmpSize = hm.get(c).size(); if (tmpSize > mSize) { rep = c; mSize = tmpSize; } } return rep; } }
JavaScript
UTF-8
4,407
3.15625
3
[]
no_license
(function(){ var canvas, ctx, map, tileWidth = 48, tileHeight = 48, player, lastRenderTime, currentKey, createCanvas = function() { canvas = document.createElement( 'CANVAS' ); screen.container.appendChild( canvas ); canvas.width = map.width * tileWidth; canvas.height = map.height * tileHeight; ctx = canvas.getContext( '2d' ); }, createPlayer = function() { player = new Actor( 28, // hitbox 3 // speed ); player.x = 1; player.y = 1; }, loadMap = function() { map = new Map(); }, onKeyDown = function( e ) { currentKey = e.keyCode; }, onKeyUp = function() { currentKey = undefined; }, processKey = function() { var accuracy = 0.1; if ( player.x % 1 > accuracy && player.x % 1 < 1 - accuracy ) { return; } if ( player.y % 1 > accuracy && player.y % 1 < 1 - accuracy ) { return; } switch ( currentKey ) { // Left case 37: if ( map.nextToWall( player.x, Math.round( player.y ), 'left' ) ) { return; } player.direction = 'left'; player.y = Math.round( player.y ); break; // Up case 38: if ( map.nextToWall( Math.round( player.x ), player.y, 'up' ) ) { return; } player.direction = 'up'; player.x = Math.round( player.x ); break; // Right case 39: if ( map.nextToWall( player.x, Math.round( player.y ), 'right' ) ) { return; } player.direction = 'right'; player.y = Math.round( player.y ); break; case 40: if ( map.nextToWall( Math.round( player.x ), player.y, 'down' ) ) { return; } player.direction = 'down'; player.x = Math.round( player.x ); break; } }; // Create the game screen object var screen = Screen.create( 'game', { init: function() { loadMap(); createCanvas(); createPlayer(); document.body.addEventListener( 'keydown', onKeyDown ); document.body.addEventListener( 'keyup', onKeyUp ); }, destroy: function() { this.container.removeChild( canvas ); canvas = ctx = null; document.body.removeEventListener( 'keydown', onKeyDown ); document.body.removeEventListener( 'keyup', onKeyUp ); }, start: function() { window.requestAnimationFrame( this.render ); }, // Render is bound below so that `this` is _always_ `Screen.game` render: function() { var now = window.performance.now(), timeDelta = ( now - ( lastRenderTime || now ) ) / 1000; lastRenderTime = now; // Clear screen ctx.fillStyle = '#000'; ctx.fillRect( 0, 0, canvas.width, canvas.height ); // Render those map tiles! for ( var i = 0; i < map.width; i++ ) { for ( var j = 0; j < map.height; j++ ) { var tileIdx = i + j * map.width, tile = map.tiles[ tileIdx ]; if ( tile === 0 ) { // Empty Space } else if ( tile === 1 ) { // Wall ctx.fillStyle = '#666'; ctx.fillRect( i * tileWidth, j * tileHeight, tileWidth, tileHeight ); } } } processKey(); // Move & render player if ( player.direction === 'down' ) { player.y += player.speed * timeDelta; // Check for a wall if ( map.tiles[ player.x + Math.ceil( player.y ) * map.width ] === 1 ) { player.y = Math.floor( player.y ); } } else if ( player.direction === 'up' ) { player.y -= player.speed * timeDelta; // Check for a wall if ( map.tiles[ player.x + Math.floor( player.y ) * map.width ] === 1 ) { player.y = Math.ceil( player.y ); } } else if ( player.direction === 'right' ) { player.x += player.speed * timeDelta; // Check for a wall if ( map.tiles[ Math.ceil( player.x ) + player.y * map.width ] === 1 ) { player.x = Math.floor( player.x ); } } else if ( player.direction === 'left' ) { player.x -= player.speed * timeDelta; // Check for a wall if ( map.tiles[ Math.floor( player.x ) + player.y * map.width ] === 1 ) { player.x = Math.ceil( player.x ); } } player.render( ctx, player.x * tileWidth + tileWidth * 0.5, player.y * tileHeight + tileHeight * 0.5 ); window.requestAnimationFrame( this.render ); } } ); screen.render = screen.render.bind( screen ); })();
Markdown
UTF-8
1,469
2.9375
3
[ "MIT" ]
permissive
# ExcelImporter The purpose of the ExcelImporter is to speed development of etl tasks where an Excel spreadsheet file is the data source. By passing the Importer class a path and file name and an ImportDefinition class, the Importer will return an ImportResult object. This object will contain a collection of ImportedRow objects, each one representing a parsed row from the source. It also contains a collection of error messages that were created while reading and parsing the file. You create the ImportDefinition using the ImportDefinitionFactory static classโ€™s Create method. The source for this a text string that defines, in English phrases, the layout of the excel file, the data types of the columns, and some validation parameters. Rules can be written to verify the content of each column, even depending on the contents of other columns for the rule. This grammer is referred to as Import Definition Language. Alternatively, you can programmatically create the import definition. Because you can map the resulting records from a spreadsheet to either a class or a database table using the included Mapper classes, the terms โ€œcolumnโ€ and โ€œpropertyโ€ are used interchangeably when discussing the destination of an import. ExcelImporter uses the ExcelDataReader project (https://github.com/ExcelDataReader/ExcelDataReader) to actually read the Excel source. As such, the ExcelImporter tools can also be used to import comma separated value files.
C#
UTF-8
3,724
3.3125
3
[]
no_license
๏ปฟusing Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NewtonsoftJsonSample { class Program { static void Main(string[] args) { serializeJson(); deserialize(); Console.Read(); } static void serializeJson() { List<Student> students = new List<Student>(); Student a = new Student() { id = "tom", school = new School() { major = "IM", name = "ntpu" }, exeam = new Exeam() { subject = "C#", score = 95 } }; Student b = new Student() { id = "mary", nickname = "kitty", school = new School() { major = "IM", name = "SHU" } }; students.Add(a); students.Add(b); //Formatting.Indented ๆ ผๅผๅŒ–Json่ณ‡ๆ–™๏ผŒไฝฟไป–ๆœ‰ๆŽ’็‰ˆ๏ผŒnoneๅ‰‡ๅไน‹ //new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore } ๅฏไปฅๅฟฝ็•ฅๆމ็‰ฉไปถๅ…งๅฎนๆ˜ฏnull็š„่ณ‡ๆ–™๏ผŒไฝฟไป–ๅœจๅบๅˆ—ๅŒ–็‚บJson่ณ‡ๆ–™ๆ™‚๏ผŒไธ่ขซๅˆปๆ„่ผธๅ‡บใ€‚ Console.WriteLine(JsonConvert.SerializeObject(students, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }).ToString()); Console.WriteLine(JsonConvert.SerializeObject(students, Formatting.None).ToString()); } static void deserialize() { string sampleJson = @"[{""id"":""tom"",""nickname"":null,""exeam"":{""score"":95,""subject"":""C#""},""school"":{""name"":""ntpu"",""major"":""IM""}},{""id"":""mary"",""nickname"":""kitty"",""exeam"":null,""school"":{""name"":""SHU"",""major"":""IM""}}]"; List<Student> GroupOfStudents = JsonConvert.DeserializeObject<List<Student>>(sampleJson); foreach (Student student in GroupOfStudents) { Console.WriteLine(string.Format("Student.id : {0}", student.id != null ? student.id : "NULL")); Console.WriteLine(string.Format("Student.nickname : {0}", student.nickname != null ? student.nickname : "NULL")); School school = student.school; if (school != null) { Console.WriteLine(string.Format("School.name : {0}", school.name != null ? school.name : "NULL")); Console.WriteLine(string.Format("School.major : {0}", school.major != null ? school.major : "NULL")); } Exeam exeam = student.exeam; if (exeam != null) { Console.WriteLine(string.Format("Exeam.subject : {0}", exeam.subject != null ? exeam.subject : "NULL")); Console.WriteLine(string.Format("Exeam.score : {0}", exeam.score != 0 ? exeam.score.ToString() : "NULL")); } Console.WriteLine("======================"); } } } public class School { public string name { get; set; } public string major { get; set; } } public class Student { public string id { get; set; } public string nickname { get; set; } public Exeam exeam { get; set; } public School school { get; set; } } public class Exeam { public int score { get; set; } public string subject { set; get; } } }
Python
UTF-8
23,102
2.796875
3
[]
no_license
## @package maker_bus # # MakerBus serial communication package # # This package provides the software needed to send and receive # MakerBus protocol packets. from serial import * import sys import glob import time ## @class Maker_Bus_Base # # Provide the shared interface to the MakerBus. # # *Maker_Bus_Base* provides an interface to the serial port that # talks the 8-bit to 9-bit protocol needed to communicate packets # back and forth from the Makerbus class Maker_Bus_Base: def __init__(self, serial_name): """ {Maker_Bus_Base}: Initialize a Maker_Bus object. """ serial_name = None if not isinstance(serial_name, str): # Search command line arguments for pattern "/dev/tty*": argv_serials = [] for arg in sys.argv: if arg.find("/dev/tty") == 0: # Found one: argv_serials.append(arg) unix_serials = glob.glob("/dev/ttyUSB*") macos_serials = glob.glob("/dev/tty.usbserial-*") pi_serials = glob.glob("/dev/ttyAMA*") # Sort everything that we found and concatente them together: argv_serials.sort() pi_serials.sort() unix_serials.sort() macos_serials.sort() serials = argv_serials + unix_serials + macos_serials + pi_serials print("serials={0}".format(serials)) # Squirt out an error message if len(serials) == 0: print "There is no serial port to open" serial_name = None else: # Use the device listed on the command line: serial_name = serials[0] # Try to open a serial connection: serial = None if serial_name != None: try: serial = Serial(serial_name, 115200) except SerialException: serial = None if serial == None: print "Unable to open serial port '{0}'".format(serial_name) self.address = -1 self.auto_flush = True self.request = [] self.request_safe = 0 self.response = [] self.same_address_requests = 0 self.serial = serial self.trace = True self.trace_pad = "" #FIXME: Only open serial if it is not already open: #serial.open() if serial != None: serial.flushInput() serial.setTimeout(0.004) def auto_flush_set(self, flush_mode): """ {Maker_Bus_Base}: This routine will set the auto flush mode for {self} to {flush_mode}. When {flush_mode} is set to {True}, it will automatically flush each command sequence as it soon as possible. When {flush_mode} is {False}, the command sequences are queued up until they are explicitly flushed by calling {flush}(). """ assert isinstance(flush_mode, bool) trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.auto_flush({1})". \ format(trace_pad, flush_mode)) self.auto_flush = flush_mode if flush_mode: self.flush() if trace: self.trace_pad = trace_pad print("{0}<=Maker_Bus.auto_flush({1})". format(trace_pad, flush_mode)) def bus_test(self): """ {Maker_Buse_Base} """ for count in range(0, 10000): self.frame_put(0x185) self.flush() time.sleep(0.05) def flush(self): """ {Maker_Bus_Base}: Flush out current request. """ trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.flush()".format(trace_pad)) # Do not do anything unless we have something to send: request = self.request request_length = len(request) while request_length != 0: # Make sure that the correct module is selected: if request_length >= 16: request_length = self.request_safe assert request_length < 16, \ "Request is {0} bytes >= 16".format(request_length) # Compute checksum: checksum = 0 for index in range(0, request_length): checksum += request[index] checksum = (checksum + (checksum >> 4)) & 0xf # Compute request header and send it out: request_header = (request_length << 4) | checksum serial = self.serial self.frame_put(request_header) # Send out the rest of the request: for index in range(0, request_length): ubyte = request[index] self.frame_put(ubyte) del request[0: request_length] request_length = len(request) self.request_safe -= request_length # Flush the serial output buffer: if trace: print("{0}Maker_Bus.flush:serial.flush()".format(trace_pad)) serial.flush() # Now get a response: response = self.response response_header = self.frame_get() if response_header < 0: # We had a time-out: print("Response header timeout") else: response_length = response_header >> 4 response_checksum = response_header & 0xf # Get the rest of the response: del response[:] while response_length != 0: response_frame = self.frame_get() if response_frame < 0: # We have a timeout: print("Response byte timeout") break response.append(response_frame) response_length -= 1 # Compute checksum: checksum = 0 for ubyte in response: checksum += ubyte checksum = (checksum + (checksum >>4)) & 0xf if trace: print("{0}response={1}, checksum=0x{2:x}". \ format(trace_pad, response, checksum)) if checksum != response_checksum: print("Got checksum of 0x{0:x} instead of 0x{1:x}". \ format(checksum, response_checksum)) del response[:] if trace: self.trace_pad = trace_pad print("{0}<=Maker_Bus.flush() response={1}". \ format(trace_pad, self.response)) def bus_reset(self): """ {Maker_Bus_Base}: Reset the bus. """ trace = self.trace if trace: print("=>bus_reset()") # Shove a 0xc5 out there to force a bus reset: serial = self.serial serial.write(chr(0xc5)) serial.flush() # Wait for a response: byte = serial.read(1) if len(byte) == 0: print("Bus reset failed with no response") elif ord(byte) != 0xa5: print("Bus reset failed 0x{0:x}".format(ord(byte))) else: if trace: print("Bus reset succeeded") if trace: print("<=bus_reset()") def discovery_mode(self): """ {Maker_Bus_Base}: Perform discovery mode """ trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " serial = self.serial serial.write(chr(0xc4)) if trace: print("{0}write(0xc4)".format(trace_pad)) serial.flush() line = [] ids = [] done = False while not done: byte = serial.read(1) if trace: print("{0}read() => 0x{1:x}".format(trace_pad, ord(byte))) if byte == '\n': ids.append("".join(line[1:])) done = len(line) != 0 and line[0] == '!' del line[:] else: line.append(byte) if trace: self.trace_pad = trace_pad print("{0}<=Maker_Bus.discovery_mode() =>{1}". \ format(trace_pad, ids)) return ids def frame_get(self): """ {Maker_Bus_Base}: Return the next frame from the bus connected to {self}. """ trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.frame_get()".format(trace_pad)) frame = -10; serial = self.serial result = serial.read(1) if len(result) != 0: frame = ord(result[0]) else: print("Timeout1") frame = -1 self.address = -1 if trace: self.trace_pad = trace_pad print("{0}<=Maker_Bus.frame_get()=>0x{1:x}". \ format(trace_pad, frame)) return frame def frame_put(self, frame): """ {Maker_Bus_Base}: Send frame to the bus connected to {self}. """ trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.frame_put(0x{1:x})".format(trace_pad, frame)) serial = self.serial if (frame > 0xff or (0xc1 <= frame and frame <= 0xc5)): # Send {frame} as two bytes: byte1 = 0xc0 | ((frame >> 7) & 3) byte2 = frame & 0x7f serial.write(chr(byte1)) serial.write(chr(byte2)) if trace: print("{0}write(0x{1:x});write(0x{2:x})". \ format(trace_pad, byte1, byte2)) else: # Send {frame} as one byte: serial.write(chr(frame)) if trace: print("{0}write(0x{1:x})".format(trace_pad, frame)) if trace: self.trace_pad = trace_pad print("{0}<=Maker_Bus.frame_put(0x{1:x})".format(trace_pad, frame)) def request_begin(self, address, command): """ {Maker_Bus_Base}: Append {command} to self.request. """ trace = self.trace if trace: trace_pad = self.trace_pad print("{0}=>Maker_Bus.request_begin(0x{1:x}, 0x{2:x})". \ format(trace_pad, address, command)) self.trace_pad = trace_pad + " " request = self.request request_length = len(request) self.request_safe = request_length if self.auto_flush and request_length != 0: self.flush() if address == self.address: if self.same_address_requests >= 8: self.address = -1 else: self.same_address_requests += 1 if address != self.address: self.same_address_requests = 0 self.frame_put(address | 0x100) self.address = address if (address & 0x80) == 0: self.serial.flush() self.frame_get() request.append(command) if trace: print("{0}<=Maker_Bus.request_begin(0x{1:x}, 0x{2:x})". \ format(trace_pad, address, command)) self.trace_pad = trace_pad def request_byte_put(self, byte): """ {Maker_Bus_Base}: Append {byte} to current request in {self}. """ if byte >= 0: ubyte = byte else: ubyte = 0xff + byte + 1 self.request_ubyte_put(self, ubyte); def request_end(self): """ {Maker_Bus_Base}: Indicate that current command is complete. """ trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.request_end()".format(trace_pad)) request = self.request request_length = len(request) if request_length >= 16: self.flush() self.request_safe = len(request) if self.auto_flush: self.flush() if trace: self.trace_pad = trace_pad print("{0}<=Maker_Bus.request_end() response={1}". \ format(trace_pad, self.response)) def request_integer_put(self, integer): """ {Maker_Bus_Base}: Append {int32} to current request in {self}. """ # Python 3.0 has infinite precision *int*'s, so we we have to # convert carefully: if integer >= 0: uinteger = integer else: uinteger = 0xffffffff + integer + 1 self.request_uinteger_put(uinteger); def request_short_put(self, short): """ {Maker_Bus_Base}: Append {int16} to current request in {self}. """ # Python 3.0 has infinite precision *int*'s, so we we have to # convert carefully: if short >= 0: ushort = short else: ushort = 0xffff + short + 1 self.request_ushort_put(ushort); def request_ubyte_put(self, ubyte): """ {Maker_Bus_Base}: Append {ubyte} to current request in {self}. """ trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.request_ubyte_put({1})". \ format(trace_pad, ubyte)) request = self.request request.append(ubyte & 0xff) if trace: self.trace_pad = trace_pad print("{0}<=Maker_Bus.request_ubyte_put({1}) request={2}". \ format(trace_pad, ubyte, request)) def request_uinteger_put(self, uinteger): """ {Maker_Bus_Base}: Append {uinteger} to current request in {self}. """ trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.request_uinteger_put({1})". \ format(trace_pad, uinteger)) assert isinstance(uinteger, int) self.request_ubyte_put((uinteger >> 24) & 0xff) self.request_ubyte_put((uinteger >> 16) & 0xff) self.request_ubyte_put((uinteger >> 8) & 0xff) self.request_ubyte_put( uinteger & 0xff) if trace: print("{0}<=Maker_Bus.request_uinteger_put({1})". \ format(trace_pad, uinteger)) def request_ushort_put(self, ushort): """ {Maker_Bus_Base}: Append {ushort} to current request in {self}. """ trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.request_ushort_put({1})". \ format(trace_pad, ushort)) assert isinstance(ushort, int) self.request_ubyte_put((ushort >> 8) & 0xff) self.request_ubyte_put( ushort & 0xff) if trace: self.trace_pad = trace_pad print("{0}<=Maker_Bus.request_ushort_put({1})". \ format(trace_pad, ushort)) def response_begin(self): """ {Maker_Bus_Base}: Begin a response sequence. """ trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.response_begin() response={1}". \ format(trace_pad, self.response)) self.flush() if trace: print("{0}<=Maker_Bus.response_begin()".format(trace_pad)) self.trace_pad = trace_pad def response_byte_get(self): """ {Maker_Bus_Base}: Return next unsigned byte from response in {self}. """ ubyte = self.response_ubyte_get() if ubyte & 0x80 != 0: ubyte |= 0xffffff00 return ubyte def response_end(self): """ {Maker_Bus_Base}: End a response sequence. """ trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.response_end() response={1}". \ format(trace_pad, self.response)) response = self.response response_length = len(response) assert len(response) == 0, \ "{0} bytes left over from response".format(response_length) if trace: print("{0}<=Maker_Bus.response_end()".format(trace_pad)) self.trace_pad = trace_pad def response_integer_get(self): """ {Maker_Bus_Base}: Return next unsigned byte from response in {self}. """ # Python 3.0 has infinte precesion *int*'s, so we have to # carefully convert to negative numbers: uinteger = self.response_uinteger_get() if (uinteger & 0x8000000) == 0: integer = uinteger else: integer = -((uinteger & 0x7fffffff) ^ 0x7fffffff) - 1 return integer def response_byte_get(self): """ {Maker_Bus_Base}: Return next unsigned byte from response in {self}. """ # Python 3.0 has infinte precesion *int*'s, so we have to # carefully convert to negative numbers: ubyte = self.response_ubyte_get() if ubyte & 0x80 == 0: byte = ubyte else: byte = -((ubyte & 0x7f) ^ 0x7f) - 1 return byte def response_short_get(self): """ {Maker_Bus_Base}: Return next unsigned byte from response in {self}. """ # Python 3.0 has infinte precesion *int*'s, so we have to # carefully convert to negative numbers: ushort= self.response_ushort_get() if ushort & 0x8000 == 0: short = ushort else: short = -((ushort & 0x7fff) ^ 0x7fff) - 1 return short def response_ubyte_get(self): """ {Maker_Bus_Base}: Return next unsigned byte from response in {self}. """ response = self.response trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.response_ubyte_get() response={1}". \ format(trace_pad, response)) ubyte = response[0] del response[0] if trace: print("{0}<=Maker_Bus.response_ubyte_get()=>{1}". \ format(trace_pad, ubyte)) self.trace_pad = trace_pad return ubyte def response_uinteger_get(self): """ {Maker_Bus_Base}: Return next unsigned integer from response in {self}. """ byte0 = self.response_ubyte_get() byte1 = self.response_ubyte_get() byte2 = self.response_ubyte_get() byte3 = self.response_ubyte_get() result = (byte0 << 24) | (byte1 << 16) | (byte2 << 8) | byte3 trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.response_uinteger_get() result={1}". \ format(trace_pad, result)) return result def response_ushort_get(self): """ {Maker_Bus_Base}: Return next unsigned short from response in {self}. """ response = self.response trace = self.trace if trace: trace_pad = self.trace_pad self.trace_pad = trace_pad + " " print("{0}=>Maker_Bus.response_ushort_get() response={1}". \ format(trace_pad, response)) high_ubyte = self.response_ubyte_get() low_ubyte = self.response_ubyte_get() ushort = (high_ubyte << 8) | low_ubyte if trace: print("{0}<=Maker_Bus.response_ushort_get()=>{1}". \ format(trace_pad, ushort)) self.trace_pad = trace_pad return ushort ## @class Maker_Bus_Module # # Per module base class to interface with MakerBus modules. # # *Maker_Bus_Module* provides a base class from which sub-classes # can be specialized. The base class provides common communication # methods. The specialized sub-class provides the module specific # register and function access to the module. class Maker_Bus_Module: """ {Maker_Bus_Module}: This represents a single module on the bus: """ def __init__(self, maker_bus_base, address, offset): """ {Maker_Bus_Module}: Initialize {self} to contain {maker_bus_base} and {address}.""" assert isinstance(maker_bus_base, Maker_Bus_Base) assert isinstance(address, int) assert isinstance(offset, int) self.maker_bus_base = maker_bus_base self.address = address self.offset = offset def auto_flush_set(self, flush_mode): """ {Maker_Bus_Module}: This routine will set the auto flush mode for {self} to {flush_mode}. When {flush_mode} is {True}, each operation is immediately sent to the selected module. When {flush_mode} is {False}, the commands queue up until the request buffer is full or until {flush}() is explicitly called. """ self.maker_bus_base.auto_flush_set(flush_mode) def flush(self): """ {Maker_Bus_Module}: This routine will cause any queued commands to be flushed. """ self.maker_bus_base.flush() def request_begin(self, command): """ {Maker_Bus_Module}: """ self.maker_bus_base.request_begin(self.address, self.offset + command) def request_byte_put(self, byte): """ {Maker_Bus_Module}: """ self.maker_bus_base.request_ubyte_put(byte) def request_character_put(self, character): """ {Maker_Bus_Module}: """ self.maker_bus_base.request_ubyte_put(ord(character)) def request_end(self): """ {Maker_Bus_Module}: """ self.maker_bus_base.request_end() def request_integer_put(self, int32): """ {Maker_Bus_Module}: """ self.maker_bus_base.request_integer_put(int32) def request_logical_put(self, logical): """ {Maker_Bus_Module}: """ value = 0 if logical: value = 1 self.maker_bus_base.request_ubyte_put(value) def request_short_put(self, int16): """ {Maker_Bus_Module}: """ self.maker_bus_base.request_short_put(int16) def request_ubyte_put(self, ubyte): """ {Maker_Bus_Module}: """ self.maker_bus_base.request_ubyte_put(ubyte & 0xff) def request_uinteger_put(self, uint32): """ {Maker_Bus_Module}: """ # High byte first, followed by low byte: self.request_uinteger_put(uint32) def request_ushort_put(self, uint16): """ {Maker_Bus_Module}: """ # High byte first, followed by low byte: self.request_ushort_put(uint16) def response_begin(self): """ {Maker_Bus_Module}: """ self.maker_bus_base.response_begin() def response_byte_get(self): """ {Maker_Bus_Module}: """ return self.maker_bus_base.response_byte_get() def response_character_get(self): """ {Maker_Bus_Module}: """ return chr(self.maker_bus_base.response_ubyte_get()) def response_logical_get(self): """ {Maker_Bus_Module}: """ return self.maker_bus_base.response_ubyte_get() != 0 def response_byte_get(self): """ {Maker_Bus_Module}: """ return self.maker_bus_base.response_byte_get() def response_short_get(self): """ {Maker_Bus_Module}: """ return self.maker_bus_base.response_short_get() def response_integer_get(self): """ {Maker_Bus_Module}: """ return self.maker_bus_base.response_integer_get() def response_ubyte_get(self): """ {Maker_Bus_Module}: """ return self.maker_bus_base.response_ubyte_get() def response_ushort_get(self): """ {Maker_Bus_Module}: """ return self.maker_bus_base.response_ushort_get() def response_uinteger_get(self): """ {Maker_Bus_Module}: """ return self.maker_bus_base.response_uinteger_get() def response_end(self): """ {Maker_Bus_Module}: """ self.maker_bus_base.response_end()
TypeScript
UTF-8
3,419
3.65625
4
[ "MIT" ]
permissive
import { ComparableData } from '../interfaces/comparable-data-type'; import { valuesComparer } from '../_internals/valuesComparer.util'; /** * @description * Updates one or multiple items in an array T[]. * For comparison you can provide key, array of keys or a custom comparison function that should return true if items match. * If no comparison is provided, an equality check is used by default. * Returns a shallow copy of the array T[] and updated items, does not mutate the original array. * * @example * // Update with comparison function * * const creatures = [{id: 1, type: 'cat'}, {id: 2, type: 'dog'}]; * * const newCat = {id: 1, type: 'lion'}; * * const updatedCreatures = update(creatures, newCat, (a, b) => a.id === b.id); * * // updatedCreatures will be: * // [{id: 1, type: 'lion'}, {id: 2, type: 'dog'}]; * * @example * // Update with key * * const creatures = [{id: 1, type: 'cat'}, {id: 2, type: 'dog'}]; * * const newCat = {id: 1, type: 'lion'}; * * const updatedCreatures = update(creatures, newCat, 'id'); * * // updatedCreatures will be: * // [{id: 1, type: 'lion'}, {id: 2, type: 'dog'}]; * * @example * // Update with array of keys * * const creatures = [{id: 1, type: 'cat', name: 'Bella'}, {id: 2, type: 'dog', name: 'Sparky'}]; * * const newCat = {id: 1, type: 'lion', name: 'Bella'}; * * const updatedCreatures = update(creatures, newCat, ['id', 'name']); * * // updatedCreatures will be: * // [{id: 1, type: 'lion', name: 'Bella'}, {id: 2, type: 'dog', name: 'Sparky'}]; * * @example * // Usage with RxState * * export class ListComponent { * * readonly updateCreature$ = new Subject<Creature>(); * * constructor(private state: RxState<ComponentState>) { * // Reactive implementation * state.connect( * 'creatures', * this.updateCreature$, * ({ creatures }, creatureToUpdate) => { * return update(creatures, creatureToUpdate, (a, b) => a.id === b.id); * } * ); * } * * // Imperative implementation * updateCreature(creatureToUpdate: Creature): void { * this.state.set({ creatures: update(this.state.get().creatures, creatureToUpdate, (a, b) => a.id === b.id)}); * } * } * * @returns T[] * * @docsPage update * @docsCategory transformation-helpers */ export function update<T extends object>( source: T[], updates: Partial<T>[] | Partial<T>, compare?: ComparableData<T> ): T[] { const updatesDefined = updates != null; const updatesAsArray = updatesDefined ? Array.isArray(updates) ? updates : [updates] : []; const sourceDefined = source != null; const sourceIsNotArray = !Array.isArray(source); const invalidInput = sourceIsNotArray || source.length === 0 || updatesAsArray.length === 0; if (sourceDefined && sourceIsNotArray) { console.warn(`Update: Original value (${source}) is not an array.`); } if (invalidInput) { return source; } const x: T[] = []; for (const existingItem of source) { const match = customFind(updatesAsArray, (item) => valuesComparer(item as T, existingItem, compare) ); x.push(match ? { ...existingItem, ...match } : existingItem); } return x; } function customFind<T>(array: T[], fn: (item: T) => boolean): T | undefined { for (const item of array) { const x = fn(item); if (x) { return item; } } }
Shell
UTF-8
4,159
3.0625
3
[]
no_license
# Copyright (c) 2018 Serge Guex # Distributable under the terms of The New BSD License # that can be found in the LICENSE file. BLACK=$(tput setaf 0) RED=$(tput setaf 1) GREEN=$(tput setaf 2) YELLOW=$(tput setaf 3) LIME_YELLOW=$(tput setaf 190) POWDER_BLUE=$(tput setaf 153) BLUE=$(tput setaf 4) MAGENTA=$(tput setaf 5) CYAN=$(tput setaf 6) WHITE=$(tput setaf 7) BOLD=$(tput bold) NORMAL=$(tput sgr0) BLINK=$(tput blink) REVERSE=$(tput smso) UNDERLINE=$(tput smul) if [ $(whoami) != 'root' ]; then echo "${BOLD}${RED}This script must be executed as root, exiting...${WHITE}${NORMAL}" exit fi SCRIPTDIR="`pwd`" #set -e #outfile=setuplog #rm -f $outfile #exec > >(cat >> $outfile) #exec 2> >(cat >> $outfile) #### stdout and stderr to log file #exec > >(tee -a $outfile >&1) #exec 2> >(tee -a $outfile >&2) #### execute the script: bash stratux-setup.sh #### Revision numbers found via cat /proc/cpuinfo # [Labeled Section] [File] # Dependencies - stratux-setup.sh # Hardware check - stratux-setup.sh # Setup /etc/hostapd/hostapd.conf - wifi-ap.sh # Edimax WiFi check - stratux-wifi.sh # Boot config settings - rpi.sh # RPI3BxREV=a02082 RPI3ByREV=a22082 REVISION="$(cat /proc/cpuinfo | grep Revision | cut -d ':' -f 2 | xargs)" # Processor # [Labeled Section] [File] # Go bootstrap compiler installation - stratux-setup.sh # ARM6L=armv6l ARM7L=armv7l ARM64=aarch64 MACHINE="$(uname -m)" echo "${MAGENTA}" echo "******************************************" echo "**** Jessie Setup Starting... *****" echo "******************************************" echo "${WHITE}" if which ntp >/dev/null; then ntp -q -g fi ############################################################## ## Stop exisiting services ############################################################## echo echo "${YELLOW}**** Stop exisiting services... *****${WHITE}" service stratux stop echo "${MAGENTA}stratux service stopped...${WHITE}" if [ -f "/etc/init.d/stratux" ]; then # remove old file rm -f /etc/init.d/stratux echo "/etc/init.d/stratux file found and deleted...${WHITE}" fi if [ -f "/etc/init.d/hostapd" ]; then service hostapd stop echo "${MAGENTA}hostapd service found and stopped...${WHITE}" fi if [ -f "/etc/init.d/isc-dhcp-server" ]; then service isc-dhcp-server stop echo "${MAGENTA}isc-dhcp service found and stopped...${WHITE}" fi echo "${GREEN}...done${WHITE}" ############################################################## ## Dependencies ############################################################## echo echo "${YELLOW}**** Installing dependencies... *****${WHITE}" apt-get install -y rpi-update rpi-update apt-get purge -y sonic-pi apt-get purge -y wolfram-engine apt-get remove -y --purge libreoffice* apt-get purge -y minecraft-pi apt-get remove --purge python-minecraftpi apt-get remove -y libpam-chksshpwd rm /home/pi/python_games -rf apt-get autoremove -y apt-get update -y apt-mark hold plymouth apt-get dist-upgrade -y apt-get upgrade -y apt-get install -y git git config --global http.sslVerify false apt-get install -y iw lshw wget isc-dhcp-server tcpdump cmake libusb-1.0-0.dev build-essential apt-get install -y mercurial autoconf fftw3 fftw3-dev libtool automake apt-get remove -y hostapd apt-get install -y hostapd apt-get install -y pkg-config libjpeg-dev i2c-tools python-smbus python-pip python-dev python-pil python-daemon apt-get install -y libconfig-dev libfftw3-dev lynx telnet libjpeg-turbo-progs screen minicom procserv nano #pip install wiringpi #apt-get purge golang* apt-get upgrade -y apt-get autoremove -y echo "${GREEN}...done${WHITE}" ############################################################## ## Epilogue ############################################################## echo echo echo "${MAGENTA}**** Jessie complete, don't forget to reboot! *****${WHITE}" echo echo ${NORMAL}
PHP
UTF-8
657
3.046875
3
[]
no_license
<?php namespace libKML; /** * Location class */ require_once("KMLObject.php"); class Location extends KMLObject { private $longitude; private $latitude; private $altitude; public function setLongitude($longitude) { $this->longitude = $longitude; } public function getLongitude() { return $this->longitude; } public function setLatitude($latitude) { $this->latitude = $latitude; } public function getLatitude() { return $this->latitude; } public function setAltitude($altitude) { $this->altitude = $altitude; } public function getAltitude() { return $this->altitude; } } ?>
SQL
UTF-8
765
4.125
4
[]
no_license
create table ACCOUNT ( ACCOUNT_ID bigint IDENTITY not null, CREATE_TIME TIMESTAMP DEFAULT NOW(), BALANCE DECIMAL(16,2), primary key (ACCOUNT_ID) ); create table PAYMENT ( PAYMENT_ID bigint IDENTITY not null, CREATE_TIME TIMESTAMP DEFAULT NOW(), AMOUNT DECIMAL(16,2), LEFT_ACCOUNT_ID bigint not null, RIGHT_ACCOUNT_ID bigint not null, primary key (PAYMENT_ID) ); ALTER TABLE PAYMENT ADD FOREIGN KEY (LEFT_ACCOUNT_ID) REFERENCES ACCOUNT(ACCOUNT_ID); ALTER TABLE PAYMENT ADD FOREIGN KEY (RIGHT_ACCOUNT_ID) REFERENCES ACCOUNT(ACCOUNT_ID); ALTER TABLE PAYMENT ADD CONSTRAINT PMNT_AMNT CHECK (AMOUNT > 0); ALTER TABLE ACCOUNT ADD CONSTRAINT ACCNT_BLNC CHECK (BALANCE >= 0); ALTER TABLE PAYMENT ADD CHECK (LEFT_ACCOUNT_ID <> RIGHT_ACCOUNT_ID);
Python
UTF-8
1,698
3.015625
3
[]
no_license
# predict.py ini adalah uji coba model dalam menprediksi aktivitas pada video import cv2 import numpy as np from keras.models import load_model scenario = 1 # 1 (3D-CNN) / 2 (C-RNN) / 3 (Pose-RNN) frame_sequences = 20 actions = ['walking', 'handwaving', 'boxing'] # membuka data video cap = cv2.VideoCapture('dataset/walking/person01_walking_d1_uncomp.avi') # mendapatkan fps untuk memutar video fps = int(cap.get(cv2.CAP_PROP_FPS)) fps2 = int(1000/fps) # membuka model model = load_model('model-{}.hdf5'.format(scenario)) # inisiasi variabel frames = [] label = '' # memutar video while cap.isOpened(): ret, frame = cap.read() if ret: # mengubah ukuran resolusi video tempframe = cv2.resize(frame, (80, 45)) # mengumpulkan frame hingga 16 frame pada C3D, 8 frame pada R3D if len(frames) < frame_sequences: frames.append(tempframe) # memprediksi aktivitas pada video if len(frames) >= frame_sequences: data = np.array([frames]) output = model.predict_on_batch(data) del frames[:] # membuat label berisi nama kelas dan tingkat keyakinan label = actions[output[0].argmax()] + " " + str(max(output[0])) # memasang label di dalam video font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(frame, label, (30, 30), font, 0.8, (0, 255, 0), 2, cv2.LINE_AA) # menampilkan video cv2.imshow('frame', frame) if cv2.waitKey(fps2) & 0xFF == ord('q'): break # memutar ulang video else: cap.set(cv2.CAP_PROP_POS_FRAMES, 0) # menutup video if cap.isOpened(): cap.release() cv2.destroyAllWindows()
Markdown
UTF-8
2,120
3.4375
3
[]
no_license
# quickCourse_Blockchain Skills improvement course given by [SENAI](https://portalead.sp.senai.br/). In this 20h course, you will know what Blockchain is, how it works and the possibilities that this technology brings to the business world. You will see: 1. What is Blockchain. 2. What are cryptocurrencies. 3. The components and actors of the Blockchain. 4. How Blockchain works. 5. Blockchain applications. 6. The professions that have emerged due to this technology. ## Beyond cryptocurrencies Do you know what blockchain is? Surely you've heard of bitcoin, right? But did you also know that blockchain goes far beyond cryptocurrencies? Well, blockchain is the technology that allows peer-to-peer commercial transactions, that is, without intermediaries. In the blockchain you can exchange confidential information, sign contracts, transfer money, track products, all with the guarantee of veracity, security, privacy, in addition to reducing time and cost. For this reason, it has attracted the interest of large companies, banks and governments. That is, both individuals and companies and public and private networks are already adopting this technology. You know how? Do you know who is behind the scenes making blockchain happen? Every transaction you initiate is transferred to all nodes in the network, this network verifies your information and validates your transaction. This transaction is then combined with other transactions to create a new hash for the ledger. The new block encrypted by the miner is permanently added to a blockchain and the miner receives a reward. Ready! The finalization is finished, the data is safe and will not be changed, as simple as that! Well, more or less of it... * Did you know that blockchain involves cryptography? * What are the *nodes*, *hashes* and *ledger*? * That miners receive rewards? * Do you know what each of them is? Throughout this course you will find the answers to these and other questions that you have not even asked, and most importantly, you will understand why this technology is revolutionizing the business world. Let's mine knowledge!
Java
UTF-8
6,780
2.515625
3
[]
no_license
package com.finra.finraAssessment; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.servlet.http.*; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import java.io.IOException; import java.util.Properties; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author Sariph Shrestha * @since 04-24-2016 * @version 1.0 */ public class FinraAssessmentServlet extends HttpServlet { private int paginationSize = 10; private String[] lettersFromPhoneNumber = { "0", "1", "2abc", "3def", "4ghi", "5jkl", "6mno", "7pqrs", "8uvw", "9xyz" }; private int ZERO_INDEX = 0; private String EMPTY_STRING = ""; private final String PAGE_NUMBER = "pageNumber"; private final String PHONE_NUMBER = "phoneNumber"; @Override public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); httpServletResponse.setContentType("text/html"); //If user is not found then please log in if(user==null){ httpServletResponse.getWriter().println("Please Login to get the Combinations"); httpServletResponse.getWriter().println( "<a href='" + userService.createLoginURL(httpServletRequest.getRequestURI()) + "'>Login</a>"); //If user is found then proceed further } else if (user != null) { //If phone number is not present, it is the first time page is getting entry //This is the entry point if (httpServletRequest.getParameter(PHONE_NUMBER) == null) { httpServletResponse.getWriter() .println("<h1>Welcome to Finra Assessment!</h1> Hello, " + httpServletRequest.getUserPrincipal().getName()); httpServletResponse.getWriter().println("<p>Hey, " + user.getNickname() + "! You can <a href=\"" + userService.createLogoutURL(httpServletRequest.getRequestURI()) + "\">sign out</a>.</p>"); httpServletResponse.getWriter() .println("<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>" + "<script src=\"finraApplication.js\"></script>"); httpServletResponse.getWriter() .println("<div id=\"combination\"/>"); httpServletResponse.getWriter() .println("<form name=\"finraForm\" " + "onsubmit=\"return validatePhoneNumber()\" " + "method=\"get\"> Enter Phone Number: " + "<input type=\"text\" name=\"phoneNumber\">" + "<input type=\"submit\" value=\"Submit\"></form></div>"); } else { String pageNumberString = httpServletRequest.getParameter(PAGE_NUMBER); int pageNumber = (pageNumberString != null) ? Integer.parseInt(pageNumberString) : 0; String phoneNumber = httpServletRequest.getParameter(PHONE_NUMBER); //List<String> allLetterCombinations = letterCombinations(phoneNumber); List<String> allLetterCombinations = letterCombinationsUpdated(phoneNumber,0); httpServletResponse.getWriter() .println("<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>" + "<script src=\"finraApplication.js\"></script>"); httpServletResponse.getWriter() .println("<div><span>Total Number of Combinations are: " + allLetterCombinations.size()+"</span>"); StringBuilder stringHtmlBuilder = new StringBuilder(); //Begin Table Body stringHtmlBuilder.append("<table id=\"data\"><tr><td>Phone Numbers Combinations:</td></tr><tbody>"); for (int index = pageNumber; index < allLetterCombinations.size() && index < pageNumber + paginationSize; index++) { stringHtmlBuilder.append("<tr><td>" + allLetterCombinations.get(index) + "</td></tr>"); } //End Table Body stringHtmlBuilder.append("</tbody></table></div>"); httpServletResponse.getWriter().println(stringHtmlBuilder); httpServletResponse.getWriter().println("<input type=\"hidden\" value=\""+phoneNumber+"\" id=\"phoneNumber\">"); httpServletResponse.getWriter().println("<input type=\"hidden\" value=\""+pageNumber+"\" id=\"pageNumber\">"); httpServletResponse.getWriter().println("<input type=\"hidden\" value=\""+paginationSize+"\" id=\"paginationSize\">"); httpServletResponse.getWriter().println("<input type=\"hidden\" value=\""+allLetterCombinations.size()+"\" id=\"totalSize\">"); httpServletResponse.getWriter().println("<input id=\"previousPageButton\" type=\"button\" value=\"Previous Page\" />"); httpServletResponse.getWriter().println("<input id=\"nextPageButton\" type=\"button\" value=\"Next Page\" />"); } } } public List<String> letterCombinationsUpdated(String phoneNumber, int step) { if (phoneNumber.length() == step) return new ArrayList<String>(); int phoneDigit = Integer.parseInt(phoneNumber.charAt(step) + ""); List<String> allCombinations = new ArrayList<String>(); for (int j = 0; j < lettersFromPhoneNumber[phoneDigit].length(); j++) { String phoneNumberString = phoneNumber.substring(0, step) + lettersFromPhoneNumber[phoneDigit].charAt(j) + phoneNumber.substring(step + 1); List<String> allCombinationsSubList = letterCombinationsUpdated(phoneNumberString, step + 1); if (!allCombinationsSubList.contains(phoneNumberString)) allCombinationsSubList.add(phoneNumberString); allCombinations.addAll(allCombinationsSubList); } return allCombinations; } public List<String> letterCombinations(String phoneNumber) { if (phoneNumber.length() == 1) { List<String> allCombinations = new ArrayList<String>(); int phoneNumberDigit = Integer.parseInt(String.valueOf(phoneNumber.charAt(ZERO_INDEX))); allCombinations = new ArrayList<String>(Arrays.asList(lettersFromPhoneNumber[phoneNumberDigit].split(EMPTY_STRING))); return allCombinations; } else { char firstCharacter = phoneNumber.charAt(ZERO_INDEX); List<String> letterCombinations = letterCombinations(phoneNumber.substring((1))); List<String> allLetterCombinations = new ArrayList<String>(); int phoneNumberDigit = Integer.parseInt(String.valueOf(firstCharacter)); List<String> lettersForPhoneDigitList = new ArrayList<String>( Arrays.asList(lettersFromPhoneNumber[phoneNumberDigit].split(EMPTY_STRING))); for (String lettersForPhoneDigit : lettersForPhoneDigitList) { for (String combination : letterCombinations) { allLetterCombinations.add(lettersForPhoneDigit + combination); } } return allLetterCombinations; } } }
C++
UTF-8
634
2.890625
3
[ "Apache-2.0" ]
permissive
#ifndef __INC_LEDBOW_DISPLAYMODEISR_H #define __INC_LEDBOW_DISPLAYMODEISR_H class DisplayModeIsr { public: DisplayModeIsr() { interrupted = false; lastInterruptTime = 0; mode = 0; } void onInterrupt(unsigned long interruptTime) { if (interruptTime - lastInterruptTime > 200) { lastInterruptTime = interruptTime; interrupted = true; } } int currentMode(int modeCount) { if (interrupted) { interrupted = false; mode = (mode + 1) % modeCount; } return mode; } private: volatile bool interrupted; volatile unsigned long lastInterruptTime; int mode; }; #endif
Go
UTF-8
2,052
2.921875
3
[]
no_license
package main import ( "context" "encoding/json" "flag" "fmt" "log" "os" "github.com/google/go-github/v33/github" "golang.org/x/oauth2" ) var ( githubToken = flag.String("token", "", "GitHub API token.") ) func main() { flag.Parse() if *githubToken == "" { log.Fatal("Missing GitHub API token") } ctx := context.Background() client := NewGitHubClient(ctx, *githubToken) repos, err := GetAllRepos(ctx, client) if err != nil { log.Fatal("List user repositories:", err) } var alfredItems []*AlfredItem for _, r := range repos { item := NewAlfredItem(r) alfredItems = append(alfredItems, item) } items := AlfredItems{Items: alfredItems} bytes, err := json.Marshal(items) if err != nil { log.Fatal("Serialization:", err) } _, err = fmt.Fprintf(os.Stdout, "%s", string(bytes)) if err != nil { log.Fatal("Output:", err) } } func NewGitHubClient(ctx context.Context, token string) *github.Client { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) tc := oauth2.NewClient(ctx, ts) return github.NewClient(tc) } func GetAllRepos(ctx context.Context, client *github.Client) ([]*github.Repository, error) { opt := &github.RepositoryListOptions{ ListOptions: github.ListOptions{PerPage: 100}, } var allRepos []*github.Repository for { repos, resp, err := client.Repositories.List(ctx, "", opt) if err != nil { return nil, err } allRepos = append(allRepos, repos...) if resp.NextPage == 0 { break } opt.Page = resp.NextPage } return allRepos, nil } type AlfredItems struct { Items []*AlfredItem `json:"items"` } type AlfredItem struct { Uid string `json:"uid"` Arg string `json:"arg"` Title string `json:"title"` Subtitle string `json:"subtitle"` } func NewAlfredItem(r *github.Repository) *AlfredItem { var description string if r.Description == nil { description = "" } else { description = *r.Description } return &AlfredItem{ Uid: *r.NodeID, Arg: *r.HTMLURL, Title: *r.FullName, Subtitle: description, } }
Java
UTF-8
700
2.109375
2
[]
no_license
package com.example.tvshowapp.viewmodels; import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModel; import com.example.tvshowapp.repositories.MostPopularTVShowsRepositories; import com.example.tvshowapp.responses.TVShowsResponse; //ะฒั‹ะฒะพะด ะฟั€ะพะณั€ะฐะผะผ public class MostPopularTVShowsViewModel extends ViewModel { private MostPopularTVShowsRepositories mostPopularTVShowsRepositories; public MostPopularTVShowsViewModel (){ mostPopularTVShowsRepositories = new MostPopularTVShowsRepositories(); } public LiveData<TVShowsResponse> getMostPopularTVShows(int page){ return mostPopularTVShowsRepositories.getMostPopularTVShows(page); } }
Python
UTF-8
2,464
2.796875
3
[]
no_license
import gym import tensorflow as tf import re import numpy as np from skimage.color import rgb2gray from skimage.transform import resize from collections import Counter, deque from constants import FRAME_WIDTH_SIZE from constants import FRAME_HEIGHT_SIZE class GameWrapper: def __init__(self, game): self.env = gym.make(game) self.historic_frame_pack = deque() if re.search("Pong", game): self.action_set = [action for action in range(1, 4)] elif re.search("Breakout", game): self.action_set = [action for action in range(1, 4)] elif re.search("Freeway", game): self.action_set = [action for action in range(1, 4)] elif re.search("Enduro", game): self.action_set = [action for action in range(1, 5)] else: self.action_set = [action for action in range(1, self.env.action_space.n)] def start_game(self): frame = self.env.reset() self.historic_frame_pack = deque() frame = rgb2gray(frame) output_shape = (FRAME_WIDTH_SIZE, FRAME_HEIGHT_SIZE) frame = resize(image=frame, output_shape=output_shape, order=1, mode='constant') self.historic_frame_pack.append(frame) self.historic_frame_pack.append(frame) self.historic_frame_pack.append(frame) self.historic_frame_pack.append(frame) return np.stack((frame, frame, frame, frame), axis = 2) def next_step(self, action_index): new_states, reward, game_over = self.original_reward_step(action_index) return new_states, np.sign(reward), game_over def original_reward_step(self, action_index): action = self.action_set[int(action_index)] frame, reward, game_over, _ = self.env.step(action) frame = rgb2gray(frame) output_shape = (FRAME_WIDTH_SIZE, FRAME_HEIGHT_SIZE) frame = resize(image=frame, output_shape=output_shape, order=1, mode='constant') self.historic_frame_pack.popleft() self.historic_frame_pack.append(frame) new_states = np.stack((self.historic_frame_pack[0], self.historic_frame_pack[1], self.historic_frame_pack[2], self.historic_frame_pack[3]), axis = 2) return new_states, reward, game_over def get_actions(self): return self.action_set def render(self): self.env.render() def close(self): self.env.close() def reset(self): self.env.reset()
Java
UTF-8
1,467
2.78125
3
[ "MIT" ]
permissive
package com.example.lifecycle; import java.util.logging.Logger; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.LifecycleListener; import org.apache.catalina.core.StandardContext; /** * A broken listener that makes a context failed during its start event. Use system property * <tt>break.context</tt> to define which context you want to break. Example: * * <pre> * -Dbreak.context=demo * </pre> * * will break the web application "demo". * * <p>Don't forget to register this listener to <tt>context.xml</tt>. * * @author Mincong Huang */ @SuppressWarnings("unused") public class BrokenListener implements LifecycleListener { private static final Logger LOGGER = Logger.getLogger(BrokenListener.class.getName()); @Override public void lifecycleEvent(LifecycleEvent event) { Lifecycle lifecycle = event.getLifecycle(); String type = event.getType(); if (lifecycle instanceof StandardContext && Lifecycle.START_EVENT.equals(type)) { StandardContext context = (StandardContext) lifecycle; String expected = System.getProperty("break.context"); String actual = context.getName(); if (expected != null && expected.equals(actual)) { LOGGER.severe("Fail context '" + actual + "'."); throw new IllegalStateException("Context '" + actual + "' is broken."); } else { LOGGER.info("Skip context '" + actual + "'."); } } } }
Java
UTF-8
14,264
2.546875
3
[ "Apache-2.0" ]
permissive
package com.artechra.jcacalculator.impl; import com.artechra.jcacalculator.*; import javax.resource.spi.work.Work; import javax.resource.spi.work.WorkException; import javax.resource.spi.work.WorkEvent; import javax.resource.spi.*; import javax.resource.ResourceException; import javax.security.auth.Subject; import javax.transaction.xa.XAResource; import java.io.PrintWriter; import java.lang.IllegalStateException; import java.util.List; import java.util.ArrayList; /** * The implementation of the Calculator JCA Adapter's managed connection. The managed * connection is the "heavyweight" underlying connection to the resource the adapter * connects to (as opposed to the regular connection that is meant to be lightweight * so that it can be created and thrown away cheaply). * * The managed connection manages the connection contract with the container and in * this case provides the calculation ability too. * * @author Eoin Woods */ class CalculatorManagedConnectionImpl implements ManagedConnection, WorkCompletionCallback { CalculatorResourceAdapter owningAdapter; PrintWriter log; private boolean isOpen; CalculationType calcType; CalculatorConnectionImpl connHandle; ResultsCallback connHandleCallback; List<ConnectionEventListener> listeners; /** * Constructor to create an initialised managed connnection * @param resourceAdapter the resource adapter this belongs to */ public CalculatorManagedConnectionImpl(ResourceAdapter resourceAdapter) { if (!(resourceAdapter instanceof CalculatorResourceAdapter)) { throw new IllegalArgumentException("CalculatorManagedConnectionImpl must be used with CalculatorResourceAdapter (found " + resourceAdapter.getClass().getName() + ")"); } this.owningAdapter = (CalculatorResourceAdapter) resourceAdapter; this.isOpen = true; this.listeners = new ArrayList<ConnectionEventListener>(); } /** * Implementation of ManagedConnection#getConnection() * Called by the container's Connection Manager to retrieve a managed connection * @param subject the security principal (subject, contains "n" principals) in use * @param connectionRequestInfo the request info defining the request (from the connection factory originally) * @return a connection for this adapter matching the request info * @throws ResourceException if the connection can't be created * @throws IllegalStateException if the managed connection should not be used */ public Object getConnection(Subject subject, ConnectionRequestInfo connectionRequestInfo) throws ResourceException, IllegalStateException { log("getConnection(" + subject + ", " + connectionRequestInfo + ")"); if (this.connHandle != null) { throw new IllegalStateException("ManagedConnection " + this.hashCode() + " already in use"); } if (!this.isOpen) { throw new IllegalStateException("Cannot retrieve connection from closed managed connection"); } if (!(connectionRequestInfo instanceof SimpleConnectionRequestInfo)) { throw new IllegalArgumentException("Connection request info object is of the wrong type (was " + connectionRequestInfo.getClass().getName() + ")"); } this.calcType = ((SimpleConnectionRequestInfo) connectionRequestInfo).getCalculationType(); this.connHandle = new CalculatorConnectionImpl(this); return this.connHandle; } /** * Implementation of ManagedConnection#destroy() called when the container wants to * dispose of this connection entirely * @throws ResourceException if the connection can't be destroyed */ public void destroy() throws ResourceException { log("Managed connection " + this.toString() + " destroyed"); cleanup(); this.isOpen = false; } /** * Implementation of ManagedConnection#cleanup() called when the container wants to * reset a managed connection to its unused state so it can be returned to the * connection pool */ public void cleanup() { log("Managed connection " + this.toString() + " cleaned up"); if (this.connHandle != null) { this.connHandle.close(); notifyListenersOfClose(this.connHandle); } } /** * Implementation of ManagedConnection#associateConnection(), called by the * container to indicate that the specified connection should be associated * with this managed connection * @param o the connection to associate (should be CalculatorConnectionImpl in this case) * @throws ResourceException if the wrong sort of connection is specified */ public void associateConnection(Object o) throws ResourceException { if (!(o instanceof CalculatorConnectionImpl)) { throw new ResourceException("Calculator Managed Connection can only associate with Calculator Connections "+ "(found " + o.getClass().getName() + ")") ; } CalculatorConnectionImpl conn = (CalculatorConnectionImpl) o; conn.setOwner(this); this.connHandle = conn; } /** * Used to break the connection with this managed connection as part of its close operation * @param conn the connection that wishes to disassocate */ public void disassociateConnection(CalculatorConnection conn) { if (this.connHandle != conn) { throw new IllegalArgumentException("Connection " + conn + " is not associated with this managed connection"); } this.connHandle = null; } /** * Used by the Calculator Connection when it is closing, to notify the managed connection. * An important part of this is calling the registered listeners (which come from the container) * so that usage can be tracked and this reused if possible * @param conn the connection that is closing */ public void closeConnection(CalculatorConnection conn) { log("Managed connection closing connection " + conn); this.disassociateConnection(conn); this.notifyListenersOfClose(conn); } /** * Implementation of ManagedConnection#addConnectionEventListener(), called by the container * to register a listener so that it can keep track of who is using what * @param connectionEventListener the listener to call back when connections close */ public void addConnectionEventListener(ConnectionEventListener connectionEventListener) { this.listeners.add(connectionEventListener); } /** * Implementation of ManagedConnection#removeConnectionEventListener(), called by the container * to deregister a listener * @param connectionEventListener the listener to deregister */ public void removeConnectionEventListener(ConnectionEventListener connectionEventListener) { this.listeners.remove(connectionEventListener); } /** * Implementation of ManagedConnection#getXAResource() called by the container during * recovery to get the associated XA Resource Manager (if any) for transaction recovery * @return null from this class */ public XAResource getXAResource() { throw new UnsupportedOperationException("No transaction support implemented"); } /** * Implementation of ManagedConnection#getLocalTransaction() called by the container * when it wants to try to use local transactions with the adapter * @return null for this implementation */ public LocalTransaction getLocalTransaction() { throw new UnsupportedOperationException("No transaction support implemented"); } /** * Implementation of ManagedConnection#getMetaData() called by the container to find * out what sort of managed connection this is * @return a meta data object to describe this connection */ public ManagedConnectionMetaData getMetaData() { return new CalculatorManagedConnectionMetaData(); } /** * Implementation of ManagedConnection#setLogWriter() called by the container to * provide the connection with a log to write to * @param printWriter the log destination to use */ public void setLogWriter(PrintWriter printWriter) { this.log = printWriter; } /** * Implementation of ManagedConnection#setLogWriter(), no idea why this would be needed * (except perhaps for other adapter classes to use) * @return the log writer in use */ public PrintWriter getLogWriter() { return this.log; } /** * Implementation of our WorkCompletionCallback#onWorkCompletion, called by the resource * adapter when Work Manager threads which were started on our behalf complete. In response to * this, this managed connection calls back in turn to the Calculator Connection who initiated * the request. * @param completedWorkItem the item that completed * @param status the WorkEvent status indicator (WORK_COMPLETED, WORK_REJECTED) * @param workItemException the exception that the work item threw, if it failed, otherwise null */ public void onWorkCompletion(Work completedWorkItem, int status, Exception workItemException) { System.out.println("SimpleManagedConnection.onWorkCompletion(" + completedWorkItem + ", " + status + ", " + workItemException + ")"); if (status != WorkEvent.WORK_REJECTED && status != WorkEvent.WORK_COMPLETED) { throw new IllegalStateException("Unexpected work status of " + status + " received by managed connection"); } if (!(completedWorkItem instanceof CalculationWorkItem)) { throw new IllegalStateException("Unexpected work item type received by managed connection (found " + completedWorkItem.getClass().getName() + ")"); } if (workItemException != null) { this.connHandleCallback.onFailedCalculation(workItemException); } else { CalculationWorkItem calcItem = (CalculationWorkItem) completedWorkItem; this.connHandleCallback.onSuccessfulCalculation(calcItem.getResult()); } this.connHandleCallback = null; } /** * Override of java.lang.Object#equals() as part of Java Bean requirements * @param o the object to compare this one to * @return true if they can be considered equal, false otherwise */ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CalculatorManagedConnectionImpl that = (CalculatorManagedConnectionImpl) o; if (isOpen != that.isOpen) return false; if (calcType != that.calcType) return false; if (connHandle != null ? !connHandle.equals(that.connHandle) : that.connHandle != null) return false; if (connHandleCallback != null ? !connHandleCallback.equals(that.connHandleCallback) : that.connHandleCallback != null) return false; if (listeners != null ? !listeners.equals(that.listeners) : that.listeners != null) return false; if (log != null ? !log.equals(that.log) : that.log != null) return false; if (owningAdapter != null ? !owningAdapter.equals(that.owningAdapter) : that.owningAdapter != null) return false; return true; } /** * Override of java.lang.Object#hashCode() as part of Java Bean requirements * @return a hash value for this object */ public int hashCode() { int result; result = (owningAdapter != null ? owningAdapter.hashCode() : 0); result = 31 * result + (log != null ? log.hashCode() : 0); result = 31 * result + (isOpen ? 1 : 0); result = 31 * result + (calcType != null ? calcType.hashCode() : 0); result = 31 * result + (connHandle != null ? connHandle.hashCode() : 0); result = 31 * result + (connHandleCallback != null ? connHandleCallback.hashCode() : 0); result = 31 * result + (listeners != null ? listeners.hashCode() : 0); return result; } /** * Protected method used by the Calculator Connection to ask for a calculation to be * performed * @param operands the operands to calculate * @param completionCallback the object to call when done * @throws ResourceException if the operation can't be run (probably a Work Manager problem) * @throws IllegalStateException if this connection doesn't have a connection associated with it */ void performOperationOnResource(List<Integer> operands, ResultsCallback completionCallback) throws ResourceException, IllegalStateException { if (this.connHandleCallback != null) { throw new IllegalStateException("SimpleManagedConnection.performOperationOnResource() called " + "again when outstanding request is pending"); } Work item = new CalculationWorkItem(this.calcType, operands); this.connHandleCallback = completionCallback; try { this.owningAdapter.runWorkObject(item, this); } catch (WorkException e) { this.connHandleCallback = null; throw new ResourceException("Could not run work item", e); } } /** * Helper method used when connections are closed to notify all of the * registered listeners of the event * @param conn the connection that is closing */ private void notifyListenersOfClose(CalculatorConnection conn) { ConnectionEvent event = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED); event.setConnectionHandle(conn); for (ConnectionEventListener listener : this.listeners) { listener.connectionClosed(event); } } /** * Helper method to allow easy logging of simple messages * @param message the message to write */ private void log(String message) { if (this.log == null) { this.log = new PrintWriter(System.out); } this.log.println(message); } }
Markdown
UTF-8
4,865
2.796875
3
[]
no_license
## Aktueller Stand 2016-04-26 ## Hier ein kurzer รœberblick รผber den aktuellen Stand des Frรคsenprojektes. ### รœberblick รผber die Maschine ### Bei der Maschine handelt es sich um eine umgebaute Drehbank. Der Werkzeugschlitten wurde mit zwei Servo-Motoren versehen (X-Achse fรผr Bewegungen normal zur Spindelachse - Z-Achse parallel zur Spindelachse). Die Spindel ist mit einem Indexer versehen. Derzeit verwenden wir LinuxCNC via Parallel-Port um die Maschine zu steuern. ### Was funktioniert schon alles? ### * Alle Motoren und der Indexer sind in LinuxCNC konfiguriert und lassen sich ansprechen. * Wir haben einfache Drehkรถrper erzeugt (inkl. tool-compensation) * LinuxCNC kann die Spindelgeschwindigkeit (bei uns typischerweise etwa 26 Umdrehungen/min) anzeigen und einfache Bewegungen in relation dazu ausfรผhren (G33). * Die Beschleunigung und maximale Geschwindigkeit fรผr die X-Achse ist getestet (115mm/s bzw. 1200mm/sยฒ). ### Wie funktioniert G33? ### `G33` ist der G-Code fรผr spindelsynchronisierte Bewegungen. Die besonderheit dabei ist, dass die Bewegung nicht nur eine bestimmte Form hat (wie bei `G01`) sondern auch in einer bestimmten Zeit bzw. mit einer bestimmten Geschwindigkeit erfolgen muss. Beispiel (von X=0, Z=0 ausgehend) erzeugt `G33 X4 Z3 K5` eine gleichmรครŸige Bewegung in X- und Z-Richtung die eine Spindelumdrehung dauert. Es werden 5mm mit K=5mm/Umdrehung zurรผckgelegt. Wenn mehrere G33 Befehle mit unterschiedlicher Geschwindigkeit (oder Richtung) hintereinander ausgefรผhrt werden, dann kann die Maschine natรผrlich nicht sofort Beschleunigen. Dh. es ist vรถllig normal, dass die Maschine dem theoretischen Weg nicht ganz folgt. Den Weg im Rahmen der Mรถglichkeiten der Maschine zu planen ist Aufgabe des *Trajectory planner*. Dazu spรคter mehr. ### Unser Testprogramm ### Bei unserem Test-Programm ([Python script](https://github.com/torotil/caorle/blob/master/ellipse.py) / [generierter G-Code](https://github.com/torotil/caorle/blob/master/ellipse-30.ngc)) handelt es sich um ein einfaches Oval (ausgehend von einem zylindrischem Rohling). Mathematisch: X = C - A * (1 + sin(2ฯ†)) / 2 ฯ† โ€ฆ Winkel der Spindel (in Radianten) A โ€ฆ Amplitude (20mm) C โ€ฆ Der ursprรผngliche Durchmesser unseres Werkstรผckes, wenn X=0 genau die Drehachse der Spindel ist. Um kein Problem mit den Entry & Exit-Moves zu haben fangen wir immer mit dem รคuรŸersten Punkt des Ovals an bzw. hรถren damit auf. Natรผrlich kann man mit `G33` keine gekrรผmmten Pfade zurรผcklegen, deshalb wird das Oval in 30 Segmente zerlegt. Warum ausgerechnet das? * Es ist eine relativ Runde Form. Die auftretenden Beschleunigungen sind also relativ begrenzt (theoretisch wรคren es weniger als 640mm/sยฒ) * Es ist relativ leicht zu programmieren. ### Das Ergebnis ### Die ersten paar Schichten funktionieren: Wir erhalten ein schรถnes Werkstรผck mit einem Ovalen Querschnitt. Ab einer bestimmten Schicht verliert dann LinuxCNC gegenรผber dem Plan Zeit. Dh. jedes Oval ist im vergleich zu dem Vorher um einen Winkel versetzt. Da wir mit konstantem Z-Vorschub arbeiten entsteht eine Art Spirale. Es handelt sich also nicht um ein isoliertes Problem beim Beginn oder Ende einer Schicht - also liegt es nicht an den Entry- und Exit-Moves. ### Wo liegt das Problem? ### Bei dem Zeitverlust handelt es sich nicht um eine Differenz zwischen dem (unter Berรผcksichtigung der Maschinengrenzen) geplanten Weg und der Maschine (follow error) sondern bereits um einen Fehler im โ€žTrajectory plannerโ€œ. Wir kรถnnen das Phรคnomen nรคmlich bereits bei der Simulation beobachten: Fรผr jede Schicht wird Spiralfรถrmig mit konstantem Z-Vorschub Material abgetragen. Dafรผr wird immer eine bestimmte Anzahl an Umdrehungen benรถtigt. Dh. das Abtragen jeder Schicht mรผsste gleich lange dauern. Tatsรคchlich dauern die einzelnen Durchgรคnge ab einer bestimmten Schicht zu lange. Das Problem steckt also im *trajectory planner* der anstatt einen korrekten Weg zu wรคhlen (oder zu melden, dass ers nicht kann) einfach Zeit liegen lasst. Leider ist der [entsprechende Code](https://github.com/LinuxCNC/linuxcnc/blob/master/src/emc/tp/tp.c) (3000 Zeilen C) nicht gerade leicht nachzuvollziehen. Es gibt [eine relativ gute Erklรคrung fรผr die nicht-spindelsynchronisierten Modi](http://wiki.linuxcnc.org/cgi-bin/wiki.pl?TrajectoryControl), aber nicht fรผr die Spindelsynchronisierten. Bis jetzt habe ich es noch nicht geschafft, den Trajectory-Planner direkt(er) mit aufzurufen deshalb gibt es noch keinen einfacheren Test-Case. ### Wie kรถnnten mรถgliche Lรถsungen aussehen? ### * Hardware is cheap: Die Spindelachse zu einer gesteuerten Achse machen und das Problem so umgehen. * Das Problem in LinuxCNC (oder der Konfiguration) finden und fixen. * Einen eigenen spezialisierten trajectory planner basteln bzw. die Stepper direkt ansprechen.
Java
UTF-8
1,111
2.265625
2
[]
no_license
package bootcamp; import bootcamp.api.v1.model.ArtistDTO; import bootcamp.api.v1.model.ArtistListDTO; import bootcamp.api.v1.model.SongDTO; import bootcamp.api.v1.model.SongListDTO; import bootcamp.services.SongService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("api/songs") public class SongController { public SongController(SongService songService) { this.songService = songService; } private final SongService songService; @GetMapping("/getall") public ResponseEntity<SongListDTO> getAllSongs(){ return new ResponseEntity<SongListDTO>( new SongListDTO(songService.getAllSongs()), HttpStatus.OK); } @GetMapping("name") public ResponseEntity<SongDTO> getSongByName(String name){ return new ResponseEntity<SongDTO>( songService.getSongByName(name), HttpStatus.OK); } }
Markdown
UTF-8
965
3.046875
3
[]
no_license
### Background One of the most controversial issues in the U.S. educational system is the efficacy of standardized tests, and whether they're unfair to certain groups. Given our prior knowledge of this topic, investigating the correlations between SAT scores and demographics might be an interesting angle to take. We could correlate SAT scores with factors like race, gender, income, and more. The SAT, or Scholastic Aptitude Test, is an exam that U.S. high school students take before applying to college. Colleges take the test scores into account when deciding who to admit, so it's fairly important to perform well on it. ### Data This dataset was prepared by Dataquest.io as part of the **Data Scientist in Python** program track. New York City makes its data on high school SAT scores available online, as well as the demographics for each high school. The original source data can be found [here](https://data.cityofnewyork.us/browse?category=Education).
Java
UTF-8
617
1.921875
2
[]
no_license
package service; import javafx.collections.ObservableList; import model.Notification; import model.Product; import util.Constants; import util.DBConnection; import util.QueryUtil; /** * @author Fernando G.U.S * @author IT18027884 * <p> * This is ProductManagerService * @see DBConnection * @see QueryUtil * @see Constants */ public interface NotificationServiceInterface { public ObservableList<Notification> getNotifications(); public ObservableList<Notification> getUnreadNotifications(); public void updateNotification(Notification notification); public void deleteNotification(int nid); }
JavaScript
UTF-8
1,806
2.703125
3
[]
no_license
import React, { useEffect, useState } from "react"; import { useParams } from "react-router"; import { Link } from "react-router-dom"; import { createCard, readDeck } from "../../utils/api"; import { CardForm } from "./CardForm"; export function NewCard() { //set up hooks const { deckId } = useParams(); //create initial form state const initializeForm = { front: "", back: "", deckId, }; const [card, setCard] = useState({ ...initializeForm }); const [deck, setDeck] = useState({}); //load cards from API to determine new card ID useEffect(() => { async function loadDeck() { //get name from current deck const loadedDeck = await readDeck(deckId); setDeck(loadedDeck); } loadDeck(); }, [deckId]); //update the state as card info changes function changeFront(e) { setCard({ ...card, front: e.target.value }); } function changeBack(e) { setCard({ ...card, back: e.target.value }); } function submitHandler(e) { e.preventDefault(); async function updateData() { await createCard(deckId, card); setCard({ ...initializeForm }); } updateData(); } return ( <div> <nav aria-label="breadcrumb"> <ol className="breadcrumb"> <li className="breadcrumb-item"> <Link to="/">Home</Link> </li> <li className="breadcrumb-item"> <Link to={`/decks/${deckId}`}>{deck.name}</Link> </li> <li className="breadcrumb-item active" aria-current="page"> Add Card </li> </ol> </nav> <h4>{deck.name}: Add Card</h4> <CardForm submitHandler={submitHandler} card={card} changeFront={changeFront} changeBack={changeBack} /> </div> ); }
Java
UTF-8
1,084
3.03125
3
[ "MIT" ]
permissive
package com.github.sangalaa.facerecognitionapp; /** * {@link FaceData} represents a single face. * Each FaceData object has */ public class FaceData { private double height; private double width; private double left; private double top; private String gender; private long minAge; private long maxAge; public FaceData(double height, double width, double left, double top, String gender, long minAge, long maxAge) { this.height = height; this.width = width; this.left = left; this.top = top; this.gender = gender; this.minAge = minAge; this.maxAge = maxAge; } public double getHeight() { return height; } public double getWidth() { return width; } public double getLeft() { return left; } public double getTop() { return top; } public String getGender() { return gender; } public long getMinAge() { return minAge; } public long getMaxAge() { return maxAge; } }
TypeScript
UTF-8
858
3.484375
3
[]
no_license
interface Heroe { nombre: string; poder?: string; arma?: string; } let superman: Heroe = { nombre: 'Super man', poder: 'Super fuerza' } let ironman: Heroe = { nombre: "Iron man" poder: "Mark One" } let thor: Heroe = { nombre: 'Thor' poder: 'Rayo' arma: 'Martillo' } function getHeroe( heroe: Heroe) { let mensaje:string; if(heroe.poder && heroe.arma) { return mensaje = `${ heroe.nombre} tiene el poder de: ${ heroe.poder } y un arma: ${ heroe.arma }` } else if (heroe.arma) { return mensaje = `${ heroe.nombre} tiene un: ${heroe.arma}`} else if (heroe.poder) { return mensaje = `${ heroe.nombre } tiee un poder de : ${heroe.poder}` } } document.body.textContent = getHeroe( thor );
C++
UTF-8
2,538
3.015625
3
[]
no_license
// *** command: g++ -fopenmp -o 2.out -std=c++11 2.cpp #include <iostream> #include "omp.h" #include <ctime> #include <cstdlib> #include <string> #include <iomanip> #include <chrono> using namespace std; // ** Const ** const unsigned int matrixN = 500; const unsigned int threadsN = 8; void printMatrix(double** Mat) { for (int i = 0; i<matrixN; i++) { for (int j = 0; j<matrixN; j++) { cout << left << setw(5) << setfill(' ') << Mat[i][j]; } cout << endl; } } void initMatrixZeros(double** Mat) { for (int i = 0; i<matrixN; i++) { for (int j = 0; j<matrixN; j++) { Mat[i][j] = 0; } } } void initMatrix(double** Mat) { for (int i = 0; i<matrixN; i++) { for (int j = 0; j<matrixN; j++) { Mat[i][j] = rand() % 10; } } } void matrixNoParallelMult(double** A, double** B, double** C) { for (int i = 0; i<matrixN; i++) { for (int j = 0; j<matrixN; j++) { for (int k = 0; k<matrixN; k++) { C[i][j] += A[i][k]*B[k][j]; } } } } void matrixParallelMult(double** A, double** B, double** C) { # pragma omp parallel for for (int i = 0; i<matrixN; i++) { // # pragma omp parallel for - doesn't speed up for (int j = 0; j<matrixN; j++) { for (int k = 0; k<matrixN; k++) { C[i][j] += A[i][k]*B[k][j]; } } } } int main() { srand(time(NULL)); double** A; double** B; double** C; A = new double *[matrixN]; B = new double *[matrixN]; C = new double *[matrixN]; for(int i = 0; i < matrixN; i++) { A[i] = new double[matrixN]; B[i] = new double[matrixN]; C[i] = new double[matrixN]; } initMatrix(A); initMatrix(B); initMatrixZeros(C); auto begin = chrono::steady_clock::now(); matrixNoParallelMult(A, B, C); auto end = chrono::steady_clock::now(); cout << "Time difference no parallel = " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << " ms" << endl; // // cout << endl << "*** No parallel multiplication ***" << endl; // printMatrix(A); // cout << endl << " * " << endl << endl; // printMatrix(B); // cout << endl << " = " << endl << endl; // printMatrix(C); initMatrixZeros(C); begin = chrono::steady_clock::now(); matrixParallelMult(A, B, C); end = chrono::steady_clock::now(); cout << "Time difference parallel = " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << " ms" << endl; // cout << endl << "*** Parallel multiplication ***" << endl; // printMatrix(A); // cout << endl << " * " << endl << endl; // printMatrix(B); // cout << endl << " = " << endl << endl; // printMatrix(C); }
Markdown
UTF-8
9,767
2.875
3
[ "Apache-2.0" ]
permissive
# Create an Arch Linux utility machine NOTE: this document is not applicable to the current setup. We are not using Arch Linux. We are keeping this document here because it's a nice guide to setting up Arch Linux in general. ## Acquire a machine It should: * be capable of running on its own without a keyboard/mouse * have two network adapters, one set up for DHCP-fueled access to the Internet, one facing inward to the cluster it's managing * have a reasonably new Intel 64-bit multicore CPU * have a reasonably modern motherboard that supports UEFI boot * have a reasonable size/number of disk drives. SSDs are very nice. * have at least 4GB memory ## Installing Arch Linux Generally, follow the directions in the [Beginners' Guide](https://wiki.archlinux.org/index.php/Beginners'_guide) or the [Installation Guide](https://wiki.archlinux.org/index.php/Installation_guide). ### Create the install media 1. Download the Arch Linux ISO from [Rackspace](http://mirror.rackspace.com/archlinux/iso) or another [mirror site](https://wiki.archlinux.org/index.php/Mirrors). 2. If installing on a real machine, burn the ISO to a USB flash drive or CD-R disk. #### How to burn the .iso file to a USB flash drive using OS X 1. Run `diskutil list`, then insert the flast drive and run `diskutil list` again. 2. Figure out its device name by noting the differences in the lists. 3. Let's say its device name is `/dev/disk2`, adjust the following as needed. 4. `diskutil unmountDisk /dev/disk2` to unmount the mounted partitions. 5. NOTE THE USE OF `/dev/rdisk2` instead of `/dev/disk2` in the next step. 6. VERY CAREFULLY: MAKE SURE YOUR DEVICE NAME FOR `of=` IS CORRECT OR YOU MAY DESTROY YOUR SYSTEM: 7. `sudo dd if=~/Downloads/archlinux-2015.12.01-dual.so of=/dev/rdisk2 bs=1m` 8. `diskutil eject /dev/disk2` 9. Remove the drive. ### Install basic Arch Linux Connect (temporarily) a keyboard and display to your machine. Boot the machine into its BIOS settings. (Typically you press the Delete or F2 key several times after booting.) Or, many machines now support a special "boot override" mode which does a one-time boot from a specified device, without changing the BIOS defaults. Try F11 for this, or see the display on your screen from the BIOS for a hint. Adjust the machine's BIOS settings to boot from your media, selecting the UEFI boot if available. Select the 64-bit version to run, if you are given a choice. #### Initial setup `ping google.com` to ensure you have Internet connectivity. `timedatectl set-ntp true` to sync your clock. Run `lsblk` and decide which disk is going to be your boot drive. It will be completely overwritten. #### Partition and format the boot drive In this example the boot drive is `/dev/sda`, adjust accordingly. It will be completely overwritten, all existing data will be lost. We will create two partitions. Partition 1 is the EFI system partition for booting Arch Linux via UEFI boot. Partition 2 is a Linux partition where the system resides. to reset the disk and create the EFI system partition: ``` sgdisk --zap-disk /dev/sda gdisk /dev/sda o (overwrite partition table) n (create new partition) (enter) (accept default partiton 1) <enter> (accept default start) 512M (partition size 512 megabytes) ef00 (partition type EFI System) w (write to disk) y (proceed) mkfs.fat -F32 /dev/sda1 ``` to create the Linux partition: ``` gdisk /dev/sda n (create new partition) <enter> 4 times (accept all the defaults) w (write to disk) y (proceed) mkfs.ext4 /dev/sda2 ``` #### Set up mirror list The mirror list determines where Arch Linux installation will go to download packages. You can use the mirror list as is but it will probably use a very slow website. ``` cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.original (save original mirror list) vim /etc/pacman.d/mirrorlist %s:/Server =/#Server =/ (comment out all the servers) (now locate servers you like and uncomment those lines... rackspace is usually a good choice) :wq ``` #### Download packages ``` mount /dev/sda2 /mnt (adjust partition name as needed) mkdir /mnt/boot mount /dev/sda1 /mnt/boot pacstrap /mnt base base-devel (this will download and install a bunch of packages) ``` #### Basic configuration of the new system This sets up the disk mount table, clock, timezone, and locale. Then we set up the network adapter, and basic configuration of the UEFI boot partition. ``` genfstab -p /mnt >> /mnt/etc/fstab (generate initial mount table) arch-chroot /mnt (enter the new system's directory tree) echo utility > /etc/hostname (sub your desired hostname for "utility") ln -s /usr/share/zoneinfo/US/Central /etc/localtime (set local time zone, modify "Central" as appropriate) hwclock --systohc --utc (set hardware clock to system time in UTC) vi /etc/locale.gen (set default locale) (Uncomment line "# en_US.UTF-8 UTF-8", and save) locale-gen (generate the new locale information) echo LANG=en_US.UTF-8 > /etc/locale.conf (set the default locale) ip addr (list installed network adapters) (pick the adapter that's connected to the Internet, we use "enp4s0" in this example) systemctl enable dhcpcd@enp4s0.service (enable DHCP on adapter at boot) mkinitcpio -p linux (create Linux initial boot binary) passwd (set a root password) (enter a root password twice) bootctl install (install UEFI boot structure to /boot) exit (return to the base system) ``` #### Create boot configuration `vim /mnt/boot/loader/entries/arch.conf` to create a new boot configuration file with the following contents. Of course, adjust `/dev/sda2` to reflect your boot partition. ``` title Arch Linux linux /vmlinuz-linux initrd /initramfs-linux.img options root=/dev/sda2 rw ``` `vim /mnt/boot/loader/loader.conf` to point the EFO bootloader to the new `arch.conf`. Replace the line starting with `default` with: `default arch` #### Boot the new system Remove the USB drive and `systemctl reboot`. You may need to enter BIOS and adjust the boot settings to boot to the Linux bootloader. #### Alternative using old style disk partitioning Instead of the "Partition and format the boot drive" above, do this: ``` # partition and format the boot disk in old school fashion, use the appropriate device name throughout fdisk /dev/sda # n # (press enter several times) # w mkfs.ext4 /dev/sda1 mount /dev/sda1 /mnt ``` Instead of "Create book configuration" above, do this: ``` pacman -S grub os-prober grub-install --recheck /dev/sda grub-mkconfig -o /boot/grub/grub.cfg ``` ## Configuring Arch Linux 1. Login as `root`. ``` pacman -S pkgfile pkgfile --update (pkgfile is useful to find out what packages contains a command file) pacman -S vim (installs vim, also ruby, python2, and lua) ln -s /usr/bin/python2 /usr/bin/python (makes the "python" command use Python 2. We don't need no stinking Python 3.) useradd -m -G wheel -s /bin/bash admin (adds user admin, pick your own username if you want) passwd admin (enter password for admin user) EDITOR=vim visudo (uncomment the line "# %wheel ALL=(ALL) NOPASSWD: ALL") ``` ## Configuring the network As root: ``` systemctl enable systemd-networkd systemctl start systemd-networkd systemctl enable systemd-resolved systemctl start systemd-resolved ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf ``` ### Recycling DHCP lease after setting fixed IP address on DHCP server As root: ``` rm /var/lib/dhcpcd/dhcpcd-<link-name>.lease systemctl reboot ``` ## Setting up SSH access As root: ``` pacman -S openssh systemctl enable sshd systemctl start sshd ``` As user `admin`: `mkdir ~/.ssh` Now go to another machine: (can be OS X or Linux) ``` ssh-keygen -f ~/.ssh/utility -N "" (or whatever finename you wish besides "utility") scp ~/.ssh/utility.pub admin@<ip-address>:.ssh/authorized_keys ``` You can now login to the utility machine by running `ssh -i ~/.ssh/utility admin@<ip-address>`. Now lock down SSH on the machine by disabling root access, and password login: ``` sudo vim /etc/ssh/sshd_config # uncomment line #PasswordAuthentication and change "yes" to "no" # uncomment line #AllowAgentForwarding yes # uncomment line #PermitRootLogin and change parameter to "no" sudo systemctl restart sshd ``` ### Setting up a second adapter with a static IP As root, create a network unit called `internal.network` like this in `/etc/systemd/network`: (use the correct device name) ``` [Match] Name=enp2s0 [Network] Address=10.0.0.1/16 ``` Then, `systemctl restart systemd-networkd` to enable it. ## Mounting additional disks at boot As root, put a mount unit like this into `/etc/systemd/system`, and call it `disk1.mount`. Then `systemctl enable disk1.mount` and `systemctl start disk1.mount`. ``` [Unit] Description=Mount Disk 1 Before=local-fs.target umount.target Conflicts=umount.target DefaultDependencies=no [Mount] What=/dev/sdb1 Where=/disk1 [Install] WantedBy=local-fs.target ``` ## Setting up Wake On LAN for your utility machine [See here for advice]() on enabling Wake On Lan on the utility machine. I had to enable "PCIE Devices Power On" in one of the BIOS menus. Then, `brew install wakeonlan` on your Mac. Find the adapter MAC address from `ip addr`, and save it on your Mac. `wakeonlan <MAC address>` will then power up your machine from anywhere on the LAN. ## Updating your utility machine `sudo pacman -Syu` will update all packages on your machine. You will need to reboot if the Linux kernel is updated.
Python
UTF-8
374
2.90625
3
[ "MIT" ]
permissive
class Solution: def reverse(self, x: int) -> int: result = 0 num = abs(x) while num != 0: result = (result*10) + (num%10) num //= 10 if x<0 and (result*-1 > -1*(2**31)): return -1*result if x>0 and result < (2**31 - 1): return result return 0
Java
UTF-8
1,822
3.53125
4
[]
no_license
public class LRUCache { class DLinkedNode { int key; // This is required while addding new element when the cache is full int value; // Storing the actual value DLinkedNode prev, next; } DLinkedNode head; DLinkedNode tail; private void addNodeAthead(DLinkedNode node) { node.prev = head; node.next = head.next; head.next.prev = node; head.next = node; } private void removeNode(DLinkedNode node) { DLinkedNode prev = node.prev; DLinkedNode next = node.next; prev.next = next; next.prev = prev; } private void moveToHead(DLinkedNode node) { removeNode(node); addNodeAthead(node); } private DLinkedNode popTail() { DLinkedNode res = tail.prev; removeNode(res); return res; } Map<Integer, DLinkedNode> map; int capacity; public LRUCache(int capacity) { this.capacity = capacity; this.map = new HashMap<>(); // Head and tail are two dummy nodes all real nodes will be in-between them this.head = new DLinkedNode(); this.tail = new DLinkedNode(); this.head.next = this.tail; this.tail.prev = this.head; } public int get(int key) { if(!map.containsKey(key)) { return -1; } DLinkedNode node = map.get(key); moveToHead(node); return node.value; } public void put(int key, int value) { if(map.containsKey(key)) { DLinkedNode node = map.get(key); node.value = value; moveToHead(node); } else { DLinkedNode node = new DLinkedNode(); node.value = value; node.key = key; map.put(key, node); addNodeAthead(node); if(map.size() > capacity) { DLinkedNode nodeToEvict = popTail(); map.remove(nodeToEvict.key); } } } }
Python
UTF-8
3,682
2.671875
3
[]
no_license
import numpy as np import math import cv2 import os #Overlay_Tester.py #Test code for image placement, will place features and save them as an image # # # # # # def malt_overlay_path(multiplier, x_pos_mult, y_pos_mult, image_1, str_foreground, count): print(count) image_3 = cv2.imread(str_foreground, cv2.IMREAD_UNCHANGED) cv2.imwrite("test.jpg", image_3) if count == 1: ones = np.ones((image_1.shape[0], image_1.shape[1]))*255 image_1 = np.dstack([image_1, ones]) ## Smart resizing function h, w, c = image_1.shape start_h = math.floor(h*y_pos_mult) start_w = math.floor(w*x_pos_mult) ## Smart resizing function h3, w3, c3 = image_3.shape w4 = math.floor(w3*multiplier) h4 = math.floor(h3*multiplier) resized_image_3 = cv2.resize(image_3, dsize=(w4, h4)) h5, w5, c4 = resized_image_3.shape #image_1[150:250, 150:250] = resized_image_3 alpha_image_3 = resized_image_3[:, :, 3] / 255.0 alpha_image = 1 - alpha_image_3 for c in range(0, 3): image_1[start_h:start_h+h5, start_w:start_w+w5, c] = ((alpha_image*image_1[start_h:start_h+h5, start_w:start_w+w5, c]) + (alpha_image_3*resized_image_3[:, :, c])) # Filename filename = str(count) + 'savedImage.png' return image_1 if __name__ == '__main__': #Features are directly left_pupil = "images/pupil.png" left_spot = "images/spot.png" right_pupil = "images/pupil.png" right_spot = "images/spot.png" my_background = "images/background.jpg" l_6 = "images/6.png" l_5 = "images/5.png" l_4 = "images/4.png" l_3 = "images/3.png" l_2 = "images/2.png" l_1 = "images/1.png" r_6 = "images/right/6.png" r_5 = "images/right/5.png" r_4 = "images/right/4.png" r_3 = "images/right/3.png" r_2 = "images/right/2.png" r_1 = "images/right/1.png" #Mouth pieces neu = "images/Mouth/neutral.png" #upper 1 -------------- u_1 = "images/Mouth/upper/1.png" u_2 = "images/Mouth/upper/2.png" u_3 = "images/Mouth/upper/3.png" u_4 = "images/Mouth/upper/4.png" u_5 = "images/Mouth/upper/5.png" u_6 = "images/Mouth/upper/6.png" #lower 1 -------------- l_1 = "images/Mouth/lower/1.png" l_2 = "images/Mouth/lower/2.png" l_3 = "images/Mouth/lower/3.png" l_4 = "images/Mouth/lower/4.png" l_5 = "images/Mouth/lower/5.png" l_6 = "images/Mouth/lower/6.png" eye_motions = [l_1,l_2, l_3, l_4, l_5, l_6, r_1, r_2, r_3, r_4, r_5,r_6] pupils = [left_pupil, right_pupil] spots = [left_spot, right_spot] #Shift through iterations lid_array_1 = [pupils[0], eye_motions[5], spots[0], pupils[1], eye_motions[11], spots[1], neu, l_6] x_multiplier = [.6, .55, .65, .3, .25, .35, .4, .4] y_multiplier = [.3, .25, .35, .3, .25, .35, .5, .5] ##Set Parameters script_dir = os.path.dirname(os.path.abspath(__file__)) str_background = os.path.join(script_dir, "background1.jpg") str_foreground = os.path.join(script_dir, "4.png") print(str_background) print(str_foreground) count = 0 image_1 = cv2.imread(str_background) for x in lid_array_1: print(str(x)) x_pos_mult = x_multiplier[count] y_pos_mult = y_multiplier[count] count = count + 1 x = os.path.join(script_dir, x) if (count == 3 or count == 6): multiplier = .05 else: multiplier = .45 image_1 = malt_overlay_path(multiplier, x_pos_mult, y_pos_mult, image_1, str(x), count) # Filename filename = (str(count) + 'savedImage.png') image_1 = np.uint8(image_1) cv2.imwrite(filename, image_1)
C++
ISO-8859-1
3,178
3.375
3
[]
no_license
#include <iostream> #include <string> #include <ctime> using namespace std; int main(int argc, char* args[]) // funo principal do seu programa { bool sair = false; // usando o lao para sair string jog1, jog2; // salvando o nome dos jogadores int vida1 = 20, vida2 = 20; // quantidade de vida do jogador no inicio int A = 4, D = 2; // defesa e o ataque dos jogaderes cout << "Digite o nome do jogador 1:" << endl; // para o 1 primerio jogador digita o nome cin >> jog1; // salvando o nome do jogado // Mesma coisa do primeiro jogador cout << "Digite o nome do jogador 2:" << endl; cin >> jog2; // inicia a variavel while (sair == false) { // imprimindo os personagens, o nome e a vida, o ataque e a defesa cout << " o o" << endl; cout << ".T./ \\.T." << endl; cout << " ^ ^" << endl; cout << jog1 << " " << jog2 << endl; cout << "Vida:" << vida1 << " " << "Vida:" << vida2 << endl; cout << "A:" << A << " " << "A:" << A << endl; cout << "D:" << D << " " << "D:" << D << endl; // dar uma pausa para imprimir os personagem na tela system("pause"); // indica a quantidade o jogador deve jogar o dado int dado6; //Adiciona uma "semente" ao gerador de numeros srand((int)time(0)); //Gera um nmero aletorio dado6 = rand() % 6 + 1; //Execultando comandos, Gera um dano no jogador se o numero for > 4 if (dado6 > 4) { // a indicando o dano que o jogado causou, se ele acertou, e vai para a jogada vida1 = vida1 - dado6; cout << jog1 << "Dano:" << -dado6 << endl; // a vida do jogador cout << jog2 << "Acertou!" << endl; // se o jogador acertou cout << "Proxima jogada (Digite enter):" << endl; // imprimir na tela enter para o jogado ir para proxima jogada cin.get(); } else if (dado6 <= 4) // sequencia de execuo do programa { // indicando se o jogador errou e vai aperta enter para ir pra proxima jogada cout << jog2 << "Errou!" << endl; cout << "Proxima jogada (Digite enter):" << endl; cin.get(); } //Mesma coisa para o jogador 2, mesmo comentario do jogador 1 dado6 = rand() % 6 + 1; if (dado6 > 4) { vida2 = vida2 - dado6; cout << jog2 << "Dano:" << -dado6 << endl; cout << jog1 << "Acertou!" << endl; cout << "Proxima jogada (Digite enter):" << endl; cin.get(); } else if (dado6 <= 4) { cout << jog1 << "Errou!" << endl; cout << "Proxima jogada (Digite enter):" << endl; cin.get(); } //cout << "Vida:" << vida1 << " " << "Vida:" << vida2 << endl; system("cls"); // se sair no limpa a tela if (vida1 <= 0 || vida2 <= 0) { sair = true; } // se continuar entao limpa a tela else system("cls"); } cout << "Fim de jogo!" << endl; // mopstra na tela que o jogo acabou if (vida1 > 0) cout << jog1 << "Venceu!" << endl; // imprimir na tela se o jogador ganhou else if (vida2 > 0) cout << jog2 << "Venceu!" << endl; // a quantidade de vida else cout << "Os dois perderam!" << endl; // imprimir na tela que os dois jogadores perderam return 0; // retorna para o inicio }
PHP
UTF-8
1,210
2.5625
3
[]
no_license
<?php class TeacherController extends Controller { public function actionIndex() { $models=Teacher::model()->findAll(); $this->render('index',array('models'=>$models)); } public function actionView($id) { $model=Teacher::model()->findByPk($id); $id_p = null; $teacher = null; $teacherInc = null; $counter = 0; $result = null; if (! empty($model->pupils)) { foreach($model->pupils as $pupils) { $id_p .= $pupils->id.','; $counter++; } $str_id = rtrim($id_p,','); $result = $counter . '|' . $str_id; if ($counter == 0) { $result = null; } if ($result != null) { $teacherInc = Teacher::teacherByGroupInclusive($result); $teacher = Teacher::teacherStrictlyByGroup($result); } } $this->render('view',array('model'=>$model,'teacher'=>$teacher,'teacherInc'=>$teacherInc)); } public function count($id) { $count = TeacherPupil::model()->count('teacher_id = :teacher_id', array(':teacher_id' => $id)); return $count; } }
C#
UTF-8
1,859
2.65625
3
[]
no_license
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace SpaceProject { public class AutoSaveHandler { private readonly string AutoSaveMessage = "The game has been saved."; private readonly Color MessageColor = Color.LightGreen; private Game1 game; private SpriteFont font; private Vector2 position { get { return new Vector2(game.camera.Position.X + windowSize.X / 2 - textSize.X, game.camera.Position.Y - windowSize.Y / 2 + textSize.Y); } } private Vector2 windowSize; private Vector2 textSize; private static bool showText; private static float hideTime; public AutoSaveHandler(Game1 game) { this.game = game; } public void Initialize() { font = FontManager.GetFontStatic(14); textSize = font.MeasureString(AutoSaveMessage); windowSize = new Vector2(Game1.ScreenSize.X, Game1.ScreenSize.Y); } public void Update(GameTime gameTime) { if (showText && StatsManager.PlayTime.HasOverworldTimePassed(hideTime)) { showText = false; } } public void Draw(SpriteBatch spriteBatch) { if (showText) { spriteBatch.DrawString(font, AutoSaveMessage, position, MessageColor, 0f, Vector2.Zero, 1f, SpriteEffects.None, 1f); } } public static void DisplayAutoSaveMessage(int milliseconds) { hideTime = StatsManager.PlayTime.GetFutureOverworldTime(milliseconds); showText = true; } } }
Ruby
UTF-8
1,227
3.515625
4
[ "MIT" ]
permissive
class Anagram def initialize(word_one, word_two) @word_one = word_one @word_two = word_two @word_one = @word_one.gsub(/[\s[:punct:]]/, '').downcase.split('').sort @word_two = @word_two.gsub(/[\s[:punct:]]/, '').downcase.split('').sort @return_statement = "" def anagram_finder if @word_one == @word_two @return_statement = "These words are anagrams." else @return_statement = "These words not anagrams." end @return_statement end end def antigram_finder @word_one.each do |letter| if @word_two.include?(letter) @return_statement = "These are not antigrams." else @return_statement = "These are antigrams." end end @return_statement end def word_finder @word_one.each do |letter| if /W[aeiou]rd/.match(@word_one.to_s) && /W[aeiou]rd/.match(@word_2.to_s) @word_two.each do |letter| if @vowels.include?(letter) else @return_statement = "These do not contain vowells, and aren't words." end end else @return_statement = "These do not contain vowells, and aren't words." end end @return_statement end end
Java
UTF-8
1,284
1.640625
2
[]
no_license
package kotlin.reflect.jvm.internal.impl.resolve.constants; import java.util.ArrayList; import java.util.Collection; import java.util.List; import kotlin.reflect.jvm.internal.impl.builtins.g; import kotlin.reflect.jvm.internal.impl.descriptors.ao; import kotlin.reflect.jvm.internal.impl.descriptors.f; import kotlin.reflect.jvm.internal.impl.descriptors.v; import kotlin.reflect.jvm.internal.impl.types.an; import kotlin.reflect.jvm.internal.impl.types.w; /* compiled from: IntegerValueTypeConstructor.kt */ public final class o implements an { private final v fbz; private final ArrayList<w> ftF; private final long value; public Void bNc() { return null; } public boolean brS() { return false; } public /* synthetic */ f brQ() { return (f) bNc(); } public Collection<w> bup() { return this.ftF; } public List<ao> getParameters() { return m.emptyList(); } public g btw() { return this.fbz.btw(); } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("IntegerValueType("); stringBuilder.append(this.value); stringBuilder.append(')'); return stringBuilder.toString(); } }
C#
UTF-8
2,514
3.328125
3
[]
no_license
using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Exercise { class Program { static void Main(string[] args) { List<string> inputs = new List<string>(); List<string> messages = new List<string>(); List<string> broadcasts = new List<string>(); string input = string.Empty; while (!"Hornet is Green".Equals(input = Console.ReadLine())) { inputs.Add(input); } foreach (string line in inputs) { string[] queries = Regex.Split(line, @" <-> "); if (queries.Length != 2) continue; string firstQ = queries[0]; string secondQ = queries[1]; if (Regex.IsMatch(firstQ, @"^\d+$") && Regex.IsMatch(secondQ, @"^[a-zA-Z\d]+$")) { string firQnew = string.Empty; for (int i = firstQ.Length - 1; i >= 0; i--) { firQnew += firstQ[i]; } messages.Add($"{firQnew} -> {secondQ}"); } if (Regex.IsMatch(firstQ, @"^[^\d]+$") && Regex.IsMatch(secondQ, @"^[a-zA-Z\d]+$")) { string secQnew = string.Empty; for (int i = 0; i < secondQ.Length; i++) { if (Char.IsUpper(secondQ[i])) secQnew += Char.ToLower(secondQ[i]); else if (Char.IsLower(secondQ[i])) secQnew += Char.ToUpper(secondQ[i]); else secQnew += secondQ[i]; } broadcasts.Add($"{secQnew} -> {firstQ}"); } } Console.WriteLine("Broadcasts:"); if (broadcasts.Count > 0) { foreach (string broadcast in broadcasts) Console.WriteLine(broadcast); } else Console.WriteLine("None"); Console.WriteLine("Messages:"); if (messages.Count > 0) { foreach (string message in messages) Console.WriteLine(message); } else Console.WriteLine("None"); } } }
Python
UTF-8
2,953
2.9375
3
[]
no_license
filein = open('socdist1.in','r') fileout = open('socdist1.out','w') # scan input text = filein.readlines() N = int(text[0].strip()) del text[0] # make list of stalls and breaks text = text[0].strip() stalls = [] num1s = 0 for i in range(N): if int(text[i]): stalls.append(1) num1s += 1 else: stalls.append(0) filein.close() breaks = text.split('1') lenbreaks = [] for i in range(len(breaks)): breaks[i] = [int(j) for j in breaks[i]] while [] in breaks: breaks.remove([]) lenbreaks = [len(i)+1 for i in breaks] # find the leading and trailing zeroes beg = 0 end = 0 middle = False if len(lenbreaks) > 2: middle = True if text[0] == '0': beg = lenbreaks.pop(0)-1 if text[-1] == '0' and len(lenbreaks) != 0: end = lenbreaks.pop(-1)-1 # find the maximum d and the second max if len(lenbreaks) != 0: maxD = max(lenbreaks) lenbreaks.remove(maxD) if len(lenbreaks) != 0: smaxD = max(lenbreaks) else: smaxD = 0 lenbreaks.append(maxD) else: maxD = 0 # both cows if no beginning or end if not beg and not end: if maxD//3 >= smaxD//2: lenbreaks.remove(maxD) if not maxD % 3: for i in range(3): lenbreaks.append(maxD//3) elif maxD % 3 == 1: lenbreaks.append(maxD//3) lenbreaks.append(maxD//3) lenbreaks.append(maxD//3 + 1) else: for i in range(2): lenbreaks.append(maxD//3 + 1) lenbreaks.append(maxD//3) else: lenbreaks.remove(maxD) lenbreaks.remove(smaxD) if not maxD % 2: for i in range(2): lenbreaks.append(maxD//2) else: for i in range(2): lenbreaks.append(maxD//2+i) if not smaxD % 2: for i in range(2): lenbreaks.append(smaxD//2) else: for i in range(2): lenbreaks.append(smaxD//2+i) else: # first cow if beg >= maxD//2 and beg >= end: lenbreaks.append(beg) beg = 0 elif end >= maxD//2 and end >= beg: lenbreaks.append(end) end = 0 elif maxD//2 >= beg and maxD//2 >= end: lenbreaks.remove(maxD) for i in range(2): lenbreaks.append(maxD//2+i) # new max maxD = max(lenbreaks) # second cow if beg >= maxD//2 and beg >= end: lenbreaks.append(beg) beg = 0 elif end >= maxD//2 and end >= beg: lenbreaks.append(end) end = 0 elif maxD//2 >= beg and maxD//2 >= end: lenbreaks.remove(maxD) for i in range(2): lenbreaks.append(maxD//2+i) # output (only case where the above program does not work is when there are only # 0s, so include this possibility minimum = min(lenbreaks) if minimum == 0: minimum += 1 if not num1s: minimum = len(text)-1 fileout.write(str(minimum)+'\n') fileout.close()
TypeScript
UTF-8
2,077
2.6875
3
[ "Apache-2.0" ]
permissive
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import { spawn } from 'child_process' // TODO: rename this since we aren't actually spawning sh export async function sh( command: string, args: string[] = [], options?: object ): Promise<Output> { let resolve: (value: Output) => void, reject: (reason: Error & Output) => void const p = new Promise<Output>((res, rej) => { resolve = res reject = rej }) let stdout = '', stderr = '' const cp = spawn(command, args, options) cp.stdout.on('data', (data) => { stdout += data.toString() }) cp.stderr.on('data', (data) => { stderr += data.toString() }) cp.on('close', (code: number) => { if (!code) { resolve({ stdout, stderr }) } else { reject( makeError(`Process exited with code ${code}`, code, stdout, stderr) ) } }) cp.on('error', (error) => { reject(makeError(error.message, 1, stdout, stderr)) }) return await p } export function makeError( message: string, code: number, stdout: string, stderr: string ) { const err = new Error(message) as Error & Output & ErrorWithExitCode err.stdout = stdout err.stderr = stderr err.code = code return err } interface Output { stdout: string stderr: string } interface ErrorWithExitCode { code: number }
Python
UTF-8
1,369
4.09375
4
[]
no_license
def max_list_iter(int_list): # must use iteration not recursion """finds the max of a list of numbers and returns the value (not the index) If int_list is empty, returns None. If list is None, raises ValueError""" if int_list == None: raise ValueError("Must be list") else: if len(int_list) < 1: return None max = int_list[0] for val in int_list: if val > max: max = val return max def reverse_rec(int_list): # must use recursion """recursively reverses a list of numbers and returns the reversed list If list is None, raises ValueError""" if int_list == None: raise ValueError("Must be a list") else: if len(int_list) == 0: return int_list return reverse_rec(int_list[1:]) + [int_list[0]] def bin_search(target, low, high, int_list): # must use recursion """searches for target in int_list[low..high] and returns index if found If target is not found returns None. If list is None, raises ValueError """ if int_list == None: raise ValueError("Must be a list") middle = (low + high) // 2 if low > high: return None if int_list[middle] > target: return bin_search(target, low, middle - 1, int_list) if int_list[middle] < target: return bin_search(target, middle + 1, high, int_list) return middle
Python
UTF-8
2,652
3.75
4
[]
no_license
# take a typical RXC maze wehre S is the start and E is the end # rocks are indicated by # # the objective is to find the shortest path between S and E. graph = [ ['S', '.', '.', '#', '.', '.', '.'], ['.', '#', '.', '.', '.', '#', '.'], ['.', '#', '.', '.', '.', '.', '.'], ['.', '.', '#', '#', '.', '.', '.'], ['#', '.', '#', 'E', '.', '#', '.'] ] # can make a somewhat simple path trace by recreating ^ but empty class MazeSolver: def __init__(self, graph): self.graph = graph self.rows = len(graph) self.columns = len(graph[0]) self.visited = [[('Z','Z') for _ in range(len(graph[0]))] for y in range(len(graph))] #direction vectors self.dx = [1, 0, 0, -1] self.dy = [0, -1, 1, 0] # queues for BFS with start point self.qx = [0] self.qy = [0] def solve(self): # overall idea is to add direction vectors until the right graph is chosen. # might be able to just destructively mark them while len(self.qx) > 0: currentX = self.qx.pop(0) currentY = self.qy.pop(0) currentNode = graph[currentY][currentX] if currentNode == 'E': print(currentY) print(currentX) return 'found' # mark as visited graph[currentY][currentX] = 'X' # get neighbors that will get traversed self.get_neighbors(currentX,currentY) def get_neighbors(self, x, y): for num in range(len(self.dx)): testX = self.dx[num]+x testY = self.dy[num]+y if testX >= self.columns or testX < 0 or testY >=self.rows or testY < 0 : continue current = self.graph[testY][testX] if current == 'X' or current == '#': continue else: # add to queue self.qx.append(testX) self.qy.append(testY) # mark ancestor in visted for path reconstruction self.visited[testY][testX] = y,x def print_visited(self): print(self.visited) def reconstructPath(self, y, x): # given y and x and the visited array, keep printing out visiteds from y,x until you get to start or '' tempY = y tempX = x while tempY != 'Z' and tempX != 'Z': print(tempY, tempX) a,b = self.visited[tempY][tempX] tempY = a tempX = b maze = MazeSolver(graph) maze.solve() # maze.print_visited() maze.reconstructPath(4,3)
PHP
UTF-8
3,090
3
3
[]
no_license
<?php $method = $_SERVER['REQUEST_METHOD']; if ($method == 'GET') { // Handle GET request if ($_GET['load']) { // If I set load to false, this won't execute $jsonData = file_get_contents('../orders.json'); echo $jsonData; } } if ($method == 'POST') { // Handle POST request if (($_POST['name']) && ($_POST['drink'])) { $order = array('name' => $_POST['name'], 'drink' => $_POST['drink']); echo json_encode(createNewOrder($order)); } } if ($method == 'DELETE') { $id = explode("/", $_SERVER['PHP_SELF'])[3]; $data = file_get_contents('../orders.json'); // decode json to associative array $json_arr = json_decode($data, true); // get array index to delete $arr_index = array(); foreach ($json_arr as $key => $value) { if ($value['id'] == $id) { $arr_index = $key; } } // delete data unset($json_arr[$arr_index]); // rebase array $json_arr = array_values($json_arr); // encode array to json and save to file file_put_contents('../orders.json', json_encode($json_arr, JSON_PRETTY_PRINT)); echo $id; } if ($method == 'PUT') { $id = explode("/", $_SERVER['PHP_SELF'])[3]; $data = file_get_contents('../orders.json'); // decode json to associative array $json_arr = json_decode($data, true); // get array index to update $arr_index = array(); foreach ($json_arr as $key => $value) { if ($value['id'] == $id) { $arr_index = $key; } } // update data parse_str(file_get_contents("php://input"),$putVars); // Get data sent in $json_arr[$arr_index]['name'] = $putVars['name']; $json_arr[$arr_index]['drink'] = $putVars['drink']; // rebase array $json_arr = array_values($json_arr); // encode array to json and save to file file_put_contents('../orders.json', json_encode($json_arr, JSON_PRETTY_PRINT)); } // Add order to JSON file function createNewOrder(array $order) { $response = array(); // Create the response $response["id"] = getId(); $response['name'] = $order['name']; $response['drink'] = $order['drink']; // Get data from existing json file, convert it, and push data $jsonData = file_get_contents('../orders.json'); $arr_data = json_decode($jsonData, true); array_push($arr_data, $response); $jsonData = json_encode($arr_data, JSON_PRETTY_PRINT); file_put_contents('../orders.json', $jsonData); return $response; } // Get last id here function getId() { $arr = file_get_contents('../orders.json'); $arr = json_decode($arr, true); // decode the JSON into an associative array $lastId = $arr[count($arr) - 1]['id']; return $lastId + 1; // Increments id } ?>
PHP
UTF-8
1,007
3.046875
3
[ "MIT" ]
permissive
<?php namespace Tests\Unit; use App\Rules\AgeCalculator; use PHPUnit\Framework\TestCase; class ValidationTest extends TestCase { /** * A basic test example. * * @return void */ public function test_example() { $this->assertTrue(true); } public function test_CalculateAgeAbove18YearOld() { //GIVEN $ageCalc = new AgeCalculator(); $today = date("Y-m-d"); $dateOfBirth = '25-03-1989'; //THEN $result = $ageCalc->passes($today, $dateOfBirth); //WHEN self::assertEquals(true, $result, "You must be 18 years or older."); } public function test_CalculateAgeBellow18YearsOld() { //GIVEN $ageCalc = new AgeCalculator(); $today = date("Y-m-d"); $dateOfBirth = '01-10-2005'; //THEN $result = $ageCalc->passes($today, $dateOfBirth); //WHEN self::assertEquals(false, $result, "You must be 18 years or older."); } }
Java
ISO-8859-1
735
3.1875
3
[]
no_license
/*4 - Escreva um programa que informe se existe estoque para atender um pedido feito a uma fbrica. O programa dever receber como entradas o nmero de itens em estoque e o nmero de itens a serem fornecidos, e dar como sada o estoque atualizado (itens em estoque menos itens a ser fornecidos) ou uma mensagem indicando no haver itens suficientes em estoque para atender ao pedido. */ package br.edu.ifcvideira.Lista3; import java.util.Scanner; public class Exercicio4 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int estoque; int fornecidos; System.out.println("Digite o numero de produtos em estoque "); estoque=Integer.parseInt(in.nextLine()); } }
Python
UTF-8
942
3.234375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Jul 17 09:32:00 2015 @author: Keith J. Wojciechowski (KJW) """ from pylab import * font = {'family' : 'serif', 'weight' : 'normal', 'size' : 16} # Interval width, h = (b-a)/(n-1), given this grid spacing: # x[0] = -4, x[100] = -3, x[200] = -2, ..., x[700] = 3, x[800] = 4 n = 801 x = linspace(-4,4,n) # Normalized standard normal f = exp(-0.5*x**2) # Filled area function will be zero everywhere except indexed values indicated # below, e.g. xindx = range(400,500) will fill an area betwenn 0 and 1 fp = zeros(f.size) xindx = range(400,550) fp[xindx] = f[xindx] figure() plt = plot(x,f) + fill(x,fp,'r') title('Normal Distribution',fontdict = font) ## *** Set mu, sigma, 2sigma at x = 0, 1, 2 #xticks([0, 1, 2],['$\mu$','$\sigma$','$2\sigma$']) ## *** Set 0, x at x = 0, 1.5 so that the Erf graphic indicates the AUC for some ## *** unknown value of x #xticks([0,1.5],['$0$','$x$']) yticks([])
Java
UTF-8
2,327
2.1875
2
[]
no_license
package com.example.laundryapp; import androidx.appcompat.app.AppCompatActivity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; public class TambahActivity extends AppCompatActivity { protected Cursor cursor; DataHelper dbHelper; Button btn1, btn2; EditText nama, alamat, berat, paket; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tambah); dbHelper = new DataHelper(this); nama = (EditText) findViewById(R.id.tambah_nama); alamat = (EditText) findViewById(R.id.tambah_alamat); berat = (EditText) findViewById(R.id.tambah_berat); // paket = (EditText) findViewById(R.id.tambah_paket); btn1 = (Button) findViewById(R.id.btn_tambah_save); btn2 = (Button) findViewById(R.id.btn_tambah_back); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { final Spinner paket = findViewById(R.id.tambah_paket); SQLiteDatabase db = dbHelper.getWritableDatabase(); db.execSQL("insert into orderan(nama, alamat, berat, paket) values('" + nama.getText().toString() +"','" + alamat.getText().toString()+"','"+ berat.getText().toString() +"','" + paket.getSelectedItem() + "')"); Toast.makeText(getApplicationContext(), "Data Berhasil Ditambahkan", Toast.LENGTH_LONG).show(); finish(); } }); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub finish(); } }); } // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the main; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.main, menu); // return true; // } }
C++
UTF-8
2,712
3.53125
4
[]
no_license
#include <iostream> using namespace std; /** * ๅนถๆŸฅ้›†๏ผšๆ˜ฏไธ€็ง็ปดๆŠค้›†ๅˆ็š„ๆ•ฐๆฎ็ป“ๆž„ * ไป–็š„ๅๅญ—ไธญๅนถใ€ๆŸฅใ€้›†ๅˆ†ๅˆซๆ˜ฏๅˆๅนถใ€ๆŸฅๆ‰พใ€้›†ๅˆ่ฟ™3ไธชๅ•่ฏ,ๅนถๆŸฅ้›†็š„ๅฎž็Žฐไฝฟ็”จไธ€ไธชๆ•ฐ็ป„ๅณๅฏ: * int fath[N], father[i]่กจ็คบๅ…ƒ็ด i็š„็ˆถ่Š‚็‚น * father[1] = 1๏ผš1็š„็ˆถ่Š‚็‚นๆ˜ฏ1 * father[2] = 3๏ผš2็š„็ˆถ่Š‚็‚นๆ˜ฏ3 * father[3] = 1๏ผ›3็š„็ˆถ่Š‚็‚นๆ˜ฏ1 * ่ฏดๆ˜Ž1ๅ’Œ3็š„็ˆถ่Š‚็‚นๆ˜ฏ็›ธๅŒ็š„๏ผŒๅœจไธ€ไธช้›†ๅˆไธญใ€‚ * ๅˆๅง‹ๅŒ–๏ผš * for(int i=0;i<n;i++) * { * father[i] = i; ๆฏไธชๅ…ƒ็ด ็š„็ˆถ่Š‚็‚นๆ˜ฏ่‡ชๅทฑ * } * ๅนถๆŸฅ้›†ๆ”ฏๆŒ้›†ๅˆ็š„ไธคไธชๆ“ไฝœ๏ผš * 1 ๅˆๅนถไธคไธช้›†ๅˆ * ๅˆๅนถ้›†ๅˆๆ˜ฏๆŠŠไธคไธช้›†ๅˆๅˆๅนถๅˆฐไธ€ไธช้›†ๅˆไธญ๏ผŒๅ…ˆๅˆคๆ–ญๆ˜ฏๅฆไธคไธชๅ…ƒ็ด ๅฑžไบŽๅŒไธ€้›†ๅˆ๏ผŒๅฝ“ๅฑžไบŽไธๅŒ้›†ๅˆๆ‰ๅฏไปฅๅˆๅนถ๏ผŒๅˆๅนถ่ฟ‡็จ‹ๅฐฑๆ˜ฏ * ๆŠŠไธ€ไธช็ป“ๅˆ็š„ๆ น่Š‚็‚น็š„็ˆถ่Š‚็‚นๆŒ‡ๅ‘ๅฆไธ€ไธช้›†ๅˆ็š„ๆ น่Š‚็‚นใ€‚ * ไพ‹ๅฆ‚ไธคไธชๅ…ƒ็ด ็š„ๆ น่Š‚็‚นๅˆ†ๅˆซๆ˜ฏfaAๅ’ŒfaB๏ผŒๅช้œ€่ฆๆŠŠๅ…ถไธญ็š„ไธ€ไธช็ˆถ่Š‚็‚นๆŒ‡ๅ‘ๅฆไธ€ไธช่Š‚็‚น๏ผŒ * father[faA] = faB ๆˆ–่€… father[faB] = faA * void union(int a, int b) * { * int faA = findfather(a); * int faB = findfather(b); * if(faA != faB) father[faA] = faB; * } * * 2 ๅˆคๆ–ญไธคไธชๅ…ƒ็ด ๆ˜ฏๅฆๅœจไธ€ไธช้›†ๅˆๅฝ“ไธญ * ่ง„ๅฎšๅŒไธ€้›†ๅˆๅช่ƒฝๅญ˜ๅœจไธ€ไธชๆ น่Š‚็‚น๏ผŒๆ‰€ไปฅๆŸฅๆ‰พๆ“ไฝœๅฐฑๆ˜ฏๅฏน็ป™ๅฎš็š„่Š‚็‚นๅฏปๆ‰พๆ น่Š‚็‚น๏ผŒๅฎž็Žฐๆ–นๅผ็”จ้€’ๆŽจๆˆ–่€…ๆ˜ฏ้€’ๅฝ’๏ผŒๅฐฑๆ˜ฏๅๅคๅฏปๆ‰พ็ˆถ่Š‚็‚น * int findfather(int x) * { * while(x!=father[x]) * { * x = father[x]; * } * return x; * } * * int findfather(int x) * { * if(father[x]==x) return x; * else return findfather(father[x]); * } * * todo ่ฟ™็งๅ†™ๆณ•ๆ›ดๅŠ ็œๆ—ถ, ๆŸฅๆ‰พไธ€ไธช่Š‚็‚น็š„็ˆถ่Š‚็‚น๏ผŒๅฆ‚ๆžœ่ฟ™ไธช่Š‚็‚นไธๆ˜ฏๅฝ“ๅ‰่Š‚็‚น็š„็ˆถ่Š‚็‚น็š„ๆ—ถๅ€™๏ผŒ้‚ฃไนˆ้€’ๅฝ’ๆ‰พๅˆฐa็š„ๆ น่Š‚็‚น๏ผŒๆŠŠๆ น่Š‚็‚น่ต‹ๅ€ผ็ป™father[a] * int findfather(int a) * { * if(a != father[a]) father[a] = findfather(father[a]); * return father[a]; * } */ const int N = 1000010; int p[N]; int find(int x) { // ่ฟ™้‡Œๆฒกๆœ‰็”จๅˆฐ่ทฏๅพ„ๅŽ‹็ผฉ๏ผŒๆ‰€ไปฅๅฏ่ƒฝ่ถ…ๆ—ถ // while(x!=p[x]) // { // x = p[x]; // } if (x != p[x]) p[x] = find(p[x]); return p[x]; } int main() { int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) p[i] = i; while (m--) { string op; cin >> op; int x1, x2; cin >> x1 >> x2; if (op == "M") { p[find(x1)] = find(x2); } else { if (find(x1) == find(x2)) cout << "Yes" << endl; else cout << "No" << endl; } } }
TypeScript
UTF-8
652
2.59375
3
[]
no_license
import { Application, Router } from 'https://deno.land/x/oak/mod.ts'; let idSet: Array<number> = []; for (let i = 0; i < 100; i++) { idSet.push(i); } const router = new Router(); router.get('/', ctx => { ctx.response.body = 'Hello World!'; }).get('/ids', ctx => { ctx.response.body = idSet; }).get('/ids/:id', ctx => { ctx.response.body = idSet.find(id => ctx.params?.id) }) const app = new Application(); app.use(router.routes()); app.use(router.allowedMethods()); try { const PORT = 5000; console.log(`Listening on port ๐Ÿš€ ${PORT} ๐Ÿš€`); await app.listen({ port: PORT }); } catch(error) { console.log(`Uh Oh something went wrong!`); }
C#
UTF-8
2,348
2.515625
3
[ "MIT" ]
permissive
๏ปฟusing System.Collections.Generic; using System.Linq; using Inshapardaz.Desktop.Api.Model; using Inshapardaz.Desktop.Common.Models; namespace Inshapardaz.Desktop.Api.Renderers { public interface IRenderWordPage { PageView<WordView> Render(PageRendererArgs<WordModel> source); } public class PageRenderer : RendrerBase, IRenderWordPage { private readonly IRenderWord _wordIndexRenderer; public PageRenderer(IRenderLink linkRenderer, IRenderWord wordIndexRenderer) : base(linkRenderer) { _wordIndexRenderer = wordIndexRenderer; } public PageView<WordView> Render(PageRendererArgs<WordModel> source) { var page = new PageView<WordView>(source.Page.PageCount, source.RouteArguments.PageSize, source.RouteArguments.PageNumber) { Data = source.Page.Data.Select(x => _wordIndexRenderer.Render(x)) }; var links = new List<LinkView> { LinkRenderer.Render(source.RouteName, RelTypes.Self,CreateRouteParameters(source, page.CurrentPageIndex, page.PageSize)) }; if (page.CurrentPageIndex < page.PageCount) { links.Add(LinkRenderer.Render(source.RouteName, RelTypes.Next, CreateRouteParameters(source, page.CurrentPageIndex + 1, page.PageSize))); } if (page.CurrentPageIndex > 1) { links.Add(LinkRenderer.Render(source.RouteName, RelTypes.Previous, CreateRouteParameters(source, page.CurrentPageIndex - 1, page.PageSize))); } page.Links = links; return page; } private object CreateRouteParameters(PageRendererArgs<WordModel> source, int pageNumber, int pageSize) { var args = source.RouteArguments ?? new PagedRouteArgs(); args.PageNumber = pageNumber; args.PageSize = pageSize; return args; } } public class PageRendererArgs<T> { public string RouteName { get; set; } public PageModel<T> Page { get; set; } public PagedRouteArgs RouteArguments { get; set; } } public class PagedRouteArgs { public int PageNumber { get; set; } public int PageSize { get; set; } } }
SQL
UTF-8
5,495
3.359375
3
[]
no_license
create database dynasty; use dynasty; drop table manager; create table manager( `id` bigint(11) auto_increment, `name` VARCHAR(128) NOT NULL, PRIMARY KEY(`id`) ); alter table manager add column email varchar(128) NOT NULL; truncate manager; insert ignore into `manager` VALUES (1, "Mark", ""), (2, "Matty", ""), (3, "Ryan", ""), (4, "Bobby", ""), (5, "Adam", ""), (6, "Sammy", ""), (7, "Billy", ""), (8, "James", ""), (9, "Dave", ""), (10, "Erick", ""), (11, "Sam Landesberg", ""), (12, "Ryan Harris / Grant?", ""), (13, "Jason Austin", ""), (14, "John Vaughn", ""), (15, "Deke Shipp", ""), (16, "Joel Harrigan", ""), (17, "Ben Brunjes", ""), (18, "Chad Copeland", ""), (19, "Jared Groot", ""), (20, "Anuj Singh", ""), (21, "Austin Morris", ""), (22, "Ricky Randall", ""), (23, "Mike Harrington", ""), (24, "Dylan McKenzie", ""), (25, "Ed Bailey", ""), (26, "Stefan", ""), (27, "Seth Rogers", ""), (28, "Joe Gilbert", ""), (29, "Chris Quarterman", ""), (30, "Keith", ""), (31, "Cavin Keys", ""), (32, "Tucker", ""), (33, "Gene", ""); create table league_details ( `league_key` varchar(128) NOT NULL, `league_id` varchar(128) NOT NULL, `league_name` varchar(128) not null, `start_week` bigint(11) NOT NULL, `start_date` DATE NOT NULL, `end_week` bigint(11) NOT NULL, `end_date` DATE NOT NULL, `league_year` bigint(11) default 0, `team_count` bigint(11) default 0, PRIMARY KEY(`league_key`) ); create table team_manager ( `league_key` varchar(128) NOT NULL, `team_key` varchar(128) NOT NULL, `team_name` varchar(128) NOT NULL, `number_of_moves` bigint(11) default 0, `number_of_trades` bigint(11) default 0, `nickname` varchar(128), `guid` varchar(128) NOT NULL, `email` varchar(128) NOT NULL, PRIMARY KEY (`team_key`), FOREIGN KEY(league_key) REFERENCES league_details(league_key) ); create table manager_league_team_assignment( `manager_id` bigint(11) NOT NULL, `team_key` varchar(128) NOT NULL, PRIMARY KEY (`team_key`), FOREIGN KEY(manager_id) REFERENCES manager(id), FOREIGN KEY(team_key) REFERENCES team_manager(team_key) ); -- drop table `manager_league_team_assignment`; -- insert into `manager_league_team_assignment` VALUES -- ( 9, "359.l.302857.t.1"), -- ( 1, "359.l.302857.t.2"), -- ( 6, "359.l.302857.t.3"), -- ( 3, "359.l.302857.t.4"), -- ( 7, "359.l.302857.t.5"), -- ( 5, "359.l.302857.t.6"), -- ( 2, "359.l.302857.t.7"), -- ( 8, "359.l.302857.t.8"), -- ( 4, "359.l.302857.t.9"), -- ( 10, "359.l.302857.t.10"), -- ( 9, "371.l.15908.t.1"), -- ( 5, "371.l.15908.t.2"), -- ( 8, "371.l.15908.t.3"), -- ( 6, "371.l.15908.t.4"), -- ( 7, "371.l.15908.t.5"), -- ( 4, "371.l.15908.t.6"), -- ( 1, "371.l.15908.t.7"), -- ( 10, "371.l.15908.t.8"), -- ( 2, "371.l.15908.t.9"), -- ( 3, "371.l.15908.t.10"), -- ( 9, "380.l.11074.t.1"), -- ( 5, "380.l.11074.t.2"), -- ( 7, "380.l.11074.t.3"), -- ( 6, "380.l.11074.t.4"), -- ( 8, "380.l.11074.t.5"), -- ( 10, "380.l.11074.t.6"), -- ( 2, "380.l.11074.t.7"), -- ( 1, "380.l.11074.t.8"), -- ( 4, "380.l.11074.t.9"), -- ( 3, "380.l.11074.t.10") -- ; -- select manager_id, count(*) from `manager_league_team_assignment` group by manager_id; truncate league_week_matchup; drop table league_week_matchup; create table league_week_matchup( league_key varchar(128) NOT NULL, league_year bigint(11) default 0, week bigint(11), week_start DATE NOT NULL, status varchar(128), is_playoffs TINYINT(1), is_consolation TINYINT(1), is_matchup_recap_available TINYINT(1), is_tied TINYINT(1), winner_team_key varchar(128), team_key_1 varchar(128) NOT NULL, team_1_points DECIMAL(9,2) default '0.00', team_key_2 varchar(128) NOT NULL, team_2_points DECIMAL(9,2) default '0.00', PRIMARY KEY(league_year, week, team_key_1, team_key_2), FOREIGN KEY(league_key) REFERENCES league_details(league_key), FOREIGN KEY(team_key_1) REFERENCES team_manager(team_key), FOREIGN KEY(team_key_2) REFERENCES team_manager(team_key) ); create table player( `player_key` varchar(128) NOT NULL, `player_id` varchar(128) NOT NULL, `first_name` varchar(128) NOT NULL, `last_name` varchar(128) NOT NULL, `full_name` varchar(128) NOT NULL, `nfl_team` varchar(128) NOT NULL, `position` varchar(128) NOT NULL, `covid_status` varchar(128) DEFAULT 'none', PRIMARY KEY(`player_key`) ); create table transaction_audit( `year` bigint(11) DEFAULT 0, `transaction_key` VARCHAR(128) NOT NULL, `player_key` varchar(128) NOT NULL, `team_key` varchar(128) NOT NULL, `transaction_type` varchar(128) NOT NULL, `timestamp` DATETIME NOT NULL, PRIMARY KEY(`transaction_key`, `player_key`), FOREIGN KEY(player_key) REFERENCES player(player_key), FOREIGN KEY(team_key) REFERENCES manager_league_team_assignment(team_key) ); drop table current_roster; create table current_roster( `team_key` varchar(128) NOT NULL, `player_key` varchar(128) NOT NULL, PRIMARY KEY(`team_key`, `player_key`), FOREIGN KEY(team_key) REFERENCES manager_league_team_assignment(team_key), FOREIGN KEY(player_key) REFERENCES player(player_key) ); create table league_standings ( `team_key` varchar(128) NOT NULL, `league_year` bigint(11) DEFAULT 0, `playoff_seed` bigint(11) DEFAULT 0, `final_rank` bigint(11) DEFAULT 99, `is_clinched_playoff` TINYINT(1), `regular_season_wins` bigint(11), DEFAULT 0, `regular_season_losses` bigint(11) DEFAULT 0, `regular_season_ties` DEFAULT 0, `division_wins` DEFAULT 0, `division_losses` DEFAULT 0, `division_ties` DEFAULT 0, `points_for` DECIMAL(9,2) DEFAULT '0.00', `points_against` DECIMAL(9,2) DEFAULT '0.00', );
Java
UTF-8
891
3.609375
4
[]
no_license
package LinkedList; import LinkedList.HasCycle_E.ListNode; public class Insert_E { class ListNode { public int value; public ListNode next; public ListNode(int value) { this.value = value; next = null; } } public ListNode insert(ListNode head, int value) { // Write your solution here ListNode newNode = new ListNode(value); // 1. determine if the inserted node is before head if(head == null || head.value >= value){ newNode.next = head; return newNode; } // 2. insert the new node to the right position // using the curr node to traverse the linked list // because we need to preserve 'head' // the insert position of the new node should be between prev and prev.next ListNode curr = head; while(curr.next != null && curr.next.value < value){ curr = curr.next; } newNode.next = curr.next; curr.next = newNode; return head; } }
C
UTF-8
2,180
2.765625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: viroques <viroques@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/16 13:07:03 by viroques #+# #+# */ /* Updated: 2021/08/16 13:07:20 by viroques ### ########.fr */ /* */ /* ************************************************************************** */ #include "philo.h" int ft_atoi(const char *nptr) { int i; int negativ; int res; i = 0; negativ = 1; res = 0; while (nptr[i] == ' ' || nptr[i] == '\t' || nptr[i] == '\n' || nptr[i] == '\r' || nptr[i] == '\v' || nptr[i] == '\f') i++; if (nptr[i] == '-') negativ = -1; if (nptr[i] == '+' || nptr[i] == '-') i++; while (nptr[i] <= '9' && nptr[i] >= '0') { res = res * 10 + nptr[i] - '0'; i++; } return (res * negativ); } long long int ft_long_atoi(const char *nptr) { int i; int negativ; long long int res; i = 0; negativ = 1; res = 0; while (nptr[i] == ' ' || nptr[i] == '\t' || nptr[i] == '\n' || nptr[i] == '\r' || nptr[i] == '\v' || nptr[i] == '\f') i++; if (nptr[i] == '-') negativ = -1; if (nptr[i] == '+' || nptr[i] == '-') i++; while (nptr[i] <= '9' && nptr[i] >= '0') { res = res * 10 + nptr[i] - '0'; i++; } return (res * negativ); } long long int get_time(void) { static struct timeval tv; gettimeofday(&tv, NULL); return ((tv.tv_sec * (long long int)1000) + (tv.tv_usec / 1000)); } long long int get_time_log(t_info *info) { return (get_time() - info->h_zero); } void ft_bzero(void *s, size_t n) { int i; unsigned char *str; i = 0; str = (unsigned char *)s; while ((size_t)i < n) { str[i] = '\0'; i++; } }
Python
UTF-8
3,555
3.09375
3
[]
no_license
# file to run the simulation multiple times # a file name containg a bunch of configurations is expected as a command line argument # this file should be of the form # header line: max_iter,state,log,graphics,initial_state,pos_stdv,ang_stdv,num_agents,alpha,perceived_weight,threshold,velocity # <config 1> # <config 2> # : # : # <config k> import simulator # import class containing config file import datetime # import class with date import math # import math library import sys from sys import argv # import library for checking command line stuff import subprocess # function to return output directory name def outDir(flag, input_file, dir_time): # begin output directory name name = "../data/" # check if this run is a temporary run if ("t" in flag): subprocess.run(["mkdir", "../data/tmp/"]) name += "tmp/" print("Output going to temporary directory", flush=True) # compute date and time now = datetime.datetime.now().strftime("d-%m.%d.%Y_t-%H.%M.%S") # add batch file name name += input_file.split("/")[-1][:-4] + "_" + dir_time + "/" subprocess.run(["mkdir", name]) # construct directory name name += "n-" + str(num_agents) + "_" name += "a-" + str(alpha)[0:5] + "_" name += "p-" + str(perceived_weight)[0:5] + "_" name += "t-" + str(threshold) + "_" name += "v-" + str(velocity) + "_" name += now # return directory name return name # set pi variable pi = math.pi # configuration variables (null until lines are read from file) # ---------------------------------------- max_iter = " " state = " " log = " " graphics = " " initial_state = " " pos_stdv = " " ang_stdv = " " num_agents = " " alpha = " " perceived_weight = " " threshold = " " velocity = " " # ---------------------------------------- # check command line inputs if (len(argv) != 3): print("command should be of the form \"python sim-batch.py -<flag> <input file path>\"") sys.exit(1) script, flag, input_file = argv # check that flag is valid if ("t" not in flag and "p" not in flag): print("invalid flag for output mode (must be '-t' or '-p')") sys.exit(1) display_graphics = ("g" in flag) # compute directory time dir_time = datetime.datetime.now().strftime("d-%m.%d.%Y_t-%H.%M.%S") # open input file fin = open(input_file, "r") fin.readline() for line in fin: # split the line split = line.rstrip().split(",") # configuration variables # ---------------------------------------- max_iter = split[0] state = split[1] log = split[2] graphics = split[3] initial_state = split[4] pos_stdv = split[5] ang_stdv = split[6] num_agents = split[7] alpha = split[8] perceived_weight = split[9] threshold = split[10] velocity = split[11] # ---------------------------------------- # compute output directory out_dir = outDir(flag, input_file, dir_time) # create config object sim = simulator.Simulator(max_iter, state, log, graphics, initial_state, pos_stdv, ang_stdv, num_agents, alpha, perceived_weight, threshold, velocity, out_dir) # write the configuation file sim.writeConfigFile() # run simulate sim.runSimulation(display_graphics) fin.close()
Ruby
UTF-8
1,410
4.875
5
[]
no_license
#Mammal > Cat (everything mammal has cat also has) #Mammal > Dog > Beagle >... #Dog and Cat are siblings, inheriting from Mammal but different #Beagle is a grandchild of mammal, it inherits from mammal and dog #parent can also be called ROOT class Mammal #with attr_accessor able to read and write ie. see the name and age and change them attr_accessor :name, :age #if want to read not write (ie. see not change) # attr_reader :name, :age (can list just one variable this way) #if want to write (ie. change) and not read (ie.see) #attr_writer :age def initialize(name, age) #initially whatever user puts in is name/age @name = name @age = age end def breathe #this is what ALL mammals should do puts 'inhale and exhale' end def speak raise "you must override this method" #will raise an error everytime you pick this end end class Cat < Mammal def initialize(name, age) #can initialize here super(name, age) #bringing down the mammals name and age from above end def speak #overriding the speak method in mammal puts 'meow' end end keesa = Cat.new('keesa', 4) # keesa.breathe # keesa.speak class Dog < Mammal def initialize(name, age) super(name, age) end def speak puts 'woof' end end nora = Dog.new('nora', 1) #if don't do .new it will assume dog is a method #with .new ruby knows Dog is a class nora.breathe nora.speak
Python
UTF-8
884
3.0625
3
[]
no_license
import sys sys.stdin = open('input.txt', 'r') def DFS(v, visited): stack = [] stack.append(v) while stack: v = stack.pop() if not visited[v]: visited[v] = 1 print(v, end=' ') for w in edges[v]: if not visited[w]: stack.append(w) def BFS(v, visited): queue = [] queue.append(v) while queue: v = queue.pop(0) if not visited[v]: visited[v] = 1 print(v, end=' ') for i in edges[v]: if not visited[i]: queue.append(i) num_list = list(map(int, input().split())) edges = [[] for _ in range(len(num_list)//2)] for k in range(len(num_list)//2): edges[num_list[2*k]].append(num_list[2*k+1]) edges[num_list[2 * k+1]].append(num_list[2 * k]) DFS(1, [0]*8) print() BFS(1, [0]*8)
Markdown
UTF-8
3,628
3.140625
3
[]
no_license
--- layout: php breadcrumb: - "basic" - "code" - "semicolon" --- # ์„ธ๋ฏธ์ฝœ๋ก (;) --- PHP๋Š” `C์–ธ์–ด`๋‚˜ `์ž๋ฐ”`์ฒ˜๋Ÿผ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด ์ค‘์—์„œ๋„ `๊ณ ๊ธ‰ ์–ธ์–ด`์— ์†ํ•ฉ๋‹ˆ๋‹ค. <br> ## ๊ณ ๊ธ‰์–ธ์–ด --- ๊ณ ๊ธ‰ ์–ธ์–ด๋ž€ ์ปดํ“จํ„ฐ๊ฐ€ ์ดํ•ดํ•˜๋Š” ๊ธฐ๊ณ„์–ด ๋‚˜ ์–ด์…ˆ๋ธ”๋ฆฌ์–ด์ฒ˜๋Ÿผ ๋งˆ์ดํฌ๋กœํ”„๋กœ์„ธ์„œ ์ค‘์‹ฌ์˜ ์–ธ์–ด๋กœ ์ž‘์„ฑ๋˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ, ์‚ฌ๋žŒ์ด ์ผ๋ฐ˜์ ์ธ ์–ธ์–ด์ฒ˜๋Ÿผ ์‰ฝ๊ฒŒ ๋ฌธ์žฅ์„ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ํ˜•ํƒœ์˜ ์–ธ์–ด ๊ตฌ์กฐ๋ฅผ ๋งํ•ฉ๋‹ˆ๋‹ค. ๋Œ€ํ‘œ์ ์ธ ๊ณ ๊ธ‰ ์–ธ์–ด๋กœ๋Š” C ์–ธ์–ด, ๋ฒ ์ด์ง, PHP, ์ž๋ฐ” ๋“ฑ์ด ์ด์— ์†ํ•ฉ๋‹ˆ๋‹ค. <br> ## ๋ช…๋ น์–ด์˜ ๊ตฌ๋ถ„ --- ๊ธฐ๋ณธ์ ์œผ๋กœ ํ”„๋กœ๊ทธ๋žจ์€ ์†Œ์Šค์ƒ์˜ ํ•œ ์ค„ ๋‹จ์œ„๋กœ ๋ช…๋ น์–ด๋ฅผ ์ฝ์–ด์„œ ์ปดํ“จํ„ฐ์—์„œ ํ•ด์„ํ•˜๊ณ  ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด๊ฐ€ ๊ณ ๊ธ‰ ์–ธ์–ด๋กœ ๋„˜์–ด์˜ค๋ฉด์„œ ํ•œ ์ค„๋กœ ๋‹ค ํ‘œํ˜„ํ•  ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งŽ์•„์ง€๊ณ , ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ง€๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฐ ๊ฒฝ์šฐ ํ•œ ์ค„ ๋‹จ์œ„ ๋ช…๋ น์ฒ˜๋Ÿผ ํ•˜๋‚˜์˜ ๋ช…๋ น์˜ ๋์„ ํ‘œ๊ธฐํ•ด์•ผ๋งŒ ์ปดํ“จํ„ฐ๊ฐ€ ํ•œ ๊ฐœ์˜ ๋ช…๋ น๋ฌธ์„ ์ดํ•ดํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฐ ํ‘œ๊ธฐ๋ฅผ ๋Œ€๋ถ€๋ถ„์˜ ์–ธ์–ด์—์„œ๋Š” `์„ธ๋ฏธ์ฝœ๋ก (;)`์„ ์ด์šฉํ•˜์—ฌ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. ์ฆ‰ ํ•˜๋‚˜์˜ ํ”„๋กœ๊ทธ๋žจ ๋ฌธ์žฅ์ด ์‹œ์ž‘ํ•˜์—ฌ ์„ธ๋ฏธ์ฝœ๋ก ์„ ๋งŒ๋‚˜๊ฒŒ ๋˜๋ฉด ์ปดํ“จํ„ฐ๋Š” ํ•˜๋‚˜์˜ ๋ช…๋ น๋ฌธ์œผ๋กœ ์ธ์‹์„ ํ•˜๊ณ  ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. <br> ## ์ฝœ๋ก  --- ์—ฌ๊ธฐ์„œ ์ฃผ์˜ํ•  ์ ์€ ๋งŽ์€ ์ดˆ๋ณด์ž ๊ฐœ๋ฐœ์ž๋“ค์ด `์„ธ๋ฏธ์ฝœ๋ก (;)`๊ณผ `์ฝœ๋ก (:)`์„ ํ—ท๊ฐˆ๋ฆฐ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๋งŒ์ผ ์†Œ์Šค์ƒ์—์„œ ์„ธ๋ฏธ์ฝœ๋ก ์„ ๋นผ๋จน๊ฑฐ๋‚˜ ์ž˜๋ชป ์ž…๋ ฅํ–ˆ์„ ๊ฒฝ์šฐ์—๋Š” ํ”„๋กœ๊ทธ๋žจ ์˜ค๋ฅ˜๋กœ ๋™์ž‘์„ ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋˜๋Š”, ํ”„๋กœ๊ทธ๋žจ ์ „์ฒด๊ฐ€ ๋™์ž‘ํ•˜์ง€ ์•Š์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. <br> ## ์‹ค์Šต์˜ˆ์ œ --- ๋‹ค์Œ์€ Hello World!๋ผ๋Š” ๋ฌธ์žฅ์„ ์„ธ ๋ฒˆ ์ถœ๋ ฅ์„ ํ•˜๋Š” ๊ฐ„๋‹จํ•œ PHP ํ”„๋กœ๊ทธ๋žจ์ž…๋‹ˆ๋‹ค. ๊ฐ๊ฐ์˜ ๋ช…๋ น์–ด ๋ฌธ์žฅ ๋’ค์—๋Š” ์„ธ๋ฏธ์ฝœ๋ก (;)์ด ๋ถ™์–ด์„œ ํ•œ ๊ฐœ์˜ ๋ช…๋ น๋ฌธ์„ ๊ตฌ๋ถ„ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ์ œํŒŒ์ผ:hello-04.php ```html <!DOCTYPE html> <html> <body> <?php ECHO "Hello World!<br>"; echo "Hello World!<br>"; ecHo "Hello World! <br>"; ?> </body> </html> ``` ์ฒซ ๋ฒˆ์งธ Hello World!๋Š” ํ•œ ์ค„์— ๋ชจ๋‘ ์“ฐ์—ฌ ์žˆ์–ด์„œ ํ•œ ์ค„ ๋ช…๋ น๊ณผ ํ—ท๊ฐˆ๋ฆด ์ˆ˜๋„ ์žˆ์„ ๊ฒƒ์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋‘ ๋ฒˆ์งธ์™€ ์„ธ ๋ฒˆ์งธ ๋ช…๋ น์„ ๋ณด๋ฉด ํ•˜๋‚˜์˜ ๋ช…๋ น์„ ๋‘ ์ค„์ด๋‚˜ ์„ธ ์ค„๋กœ ํ‘œ์‹œํ•ด์„œ ์ถœ๋ ฅํ•  ๋•Œ ๋ช…๋ น์˜ ๋์„ ์„ธ๋ฏธ์ฝœ๋ก (`;`)์„ ํ†ตํ•ด ๋‹ค์ˆ˜์˜ ๋ผ์ธ์œผ๋กœ ๋ช…๋ น์„ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. <br> ## ๋ช…๋ น ๊ตฌ๋ถ„์ž --- ๋ช…๋ น์˜ ๊ตฌ๋ถ„์ž๋Š” ์™œ ์ค‘์š”ํ• ๊นŒ์š”? ๊ทธ๋ฆฌ๊ณ  ๋ช…๋ น ๊ตฌ๋ถ„์ž ์„ธ๋ฏธ์ฝœ๋ก (`;`)์„ ๋„ฃ์ง€ ์•Š์œผ๋ฉด ์™œ ํ”„๋กœ๊ทธ๋žจ์ด ์‹คํ–‰๋˜์ง€ ์•Š์„๊นŒ์š”? ๊ณ ๊ธ‰ ์–ธ์–ด์˜ ๊ฒฝ์šฐ ์ปดํŒŒ์ผ/์ธํ„ฐํ”„๋ฆฌํ„ฐ๋ผ๋Š” ์ฒ˜๋ฆฌ ํ›„์— ์ปดํ“จํ„ฐ๊ฐ€ ์ธ์ง€๋˜๋Š” ํ”„๋กœ๊ทธ๋žจ์œผ๋กœ ๋ณ€๊ฒฝ๋˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ๊ณ ๊ธ‰ ์–ธ์–ด๋Š” ์•ž์—์„œ ์–ธ๊ธ‰ํ•œ ๊ฒƒ๊ณผ ๊ฐ™์ด ์ปดํ“จํ„ฐ๊ฐ€ ์ดํ•ด๋ฅผ ํ•˜์ง€ ๋ชปํ•˜๋Š” ์–ธ์–ด ๊ตฌ์กฐ์ž…๋‹ˆ๋‹ค. ์‚ฌ๋žŒ์ด ์ข€ ๋” ์‰ฝ๊ฒŒ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋„๋ก ๋งŒ๋“  ๊ฐ€์ƒ์˜ ์–ธ์–ด์ž…๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ๊ณ ๊ธ‰ ์–ธ์–ด๋Š” ์‹คํ–‰ ์ „์— ์ปดํŒŒ์ผ๋Ÿฌ/์ธํ„ฐํ”„๋ฆฌํ„ฐ๋ผ๋Š” ํ”„๋กœ๊ทธ๋žจ์ด ๊ณ ๊ธ‰ ์–ธ์–ด๋กœ ์ž‘์„ฑ๋œ ์†Œ์Šค๋ฅผ ์ฝ์–ด ์„ธ๋ฏธ์ฝœ๋ก (;)์œผ๋กœ ๊ตฌ๋ถ„์„ ํ•˜๊ณ  ๊ฐ๊ฐ์˜ ์ž‘์„ฑ๋œ ๋‚ด์šฉ์„ ๋ถ„์„ํ•˜์—ฌ ๊ธฐ๊ณ„์–ด๋กœ ๋งŒ๋“ญ๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ๋ช…๋ น์–ด์˜ ๊ตฌ๋ถ„์ž์ธ ์„ธ๋ฏธ์ฝœ๋ก (;)์„ ์ž…๋ ฅํ•˜์ง€ ๋ชปํ•˜๋ฉด ์ปดํŒŒ์ผ๋Ÿฌ/์ธํ„ฐํ”„๋ฆฌํ„ฐ๊ฐ€ ์ž‘์„ฑ๋œ ์†Œ์Šค๋ฅผ ๊ตฌ๋ถ„ํ•  ์ˆ˜ ์—†๊ณ , ์ž˜๋ชป ๋ถ„์„ํ•˜์—ฌ ์ฒ˜๋ฆฌํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ”„๋กœ๊ทธ๋žจ์ด ๋™์ž‘์„ ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. <br> ## Quiz --- ํ€ด์ฆˆ๋ฅผ ํ†ตํ•˜์—ฌ ํ•™์Šตํ•œ ๋‚ด์šฉ์„ ๋‹ค์‹œํ•œ๋ฒˆ ์ƒ๊ฐํ•ด ๋ด…๋‹ˆ๋‹ค. <br> <br>
TypeScript
UTF-8
1,025
2.828125
3
[]
no_license
import { Reducer } from 'redux' import { ActionsTypes as ProfileActionsTypes} from './profileActions' import { ActionsTypes as AuthActionsTypes } from '../../auth/authActions' export interface ProfileState { messageEdit: { threadId: string, messageId: string } | null, } export const getInitialState = () => ({ messageEdit: null, }) const initialState = getInitialState() const reducer: Reducer<ProfileState> = (state = initialState, action) => { switch (action.type) { case ProfileActionsTypes.APP_PROFILE_THREAD_MESSAGE_EDIT: { const { threadId, messageId } = action.payload state.messageEdit = { threadId, messageId, } return { ...state } } case ProfileActionsTypes.APP_PROFILE_THREAD_MESSAGE_RELEASE: { state.messageEdit = null return { ...state } } // DELETE /auth case AuthActionsTypes.AUTH_DELETE_SUCCESS: { return getInitialState() } default: { return state } } } export default reducer
Java
UTF-8
2,680
2.671875
3
[ "MIT" ]
permissive
package gaarason.database.contract.model; import gaarason.database.contract.eloquent.Record; /** * ไบ‹ไปถ * ๆŸฅ่ฏข : retrieving -> retrieved * ๆ–ฐๅขž : saving -> creating -> created -> saved * ๆ›ดๆ–ฐ : saving -> updating -> updated -> saved * ๅˆ ้™ค : deleting -> deleted * ๆขๅค : restoring -> restored * <p> * ๅ…ถไธญไปฅ record ไธบๅ‚ๆ•ฐ็š„ไบ‹ไปถ, ไป…ๅœจไฝฟ็”จORM้ฃŽๆ ผๆ—ถ, ไผš่งฆๅ‘ * ๅ…ถไธญไปฅ builder ไธบๅ‚ๆ•ฐ็š„ไบ‹ไปถ, ้™คไบ†ไฝฟ็”จๅŽŸๅง‹SQLๆ–นๅผๆ—ถไธไผš่งฆๅ‘, ORM้ฃŽๆ ผไปฅๅŠnewQuery้ฃŽๆ ผ, ้ƒฝไผš่งฆๅ‘ * ๅฝ“ๅŒๆ—ถๅฃฐๆ˜Žไบ† record ไธŽ builder ไธบๅ‚ๆ•ฐ็š„็›ธๅŒไบ‹ไปถๆ—ถ, ๅ…ˆ่งฆๅ‘ record * log ๆ€ปๆ˜ฏๅœจๆ‰ง่กŒๅ‰่งฆๅ‘ * @param <T> ๅฎžไฝ“็ฑป * @param <K> ไธป้”ฎ็ฑปๅž‹ * @author xt */ public interface ORMEvent<T, K> { /** * ไบ‹ไปถไผšๅฝ“ไธ€ไธชๆ–ฐๆจกๅž‹่ขซ้ฆ–ๆฌกไฟๅญ˜็š„ๆ—ถๅ€™่งฆๅ‘ * ไป…ORMๅœบๆ™ฏๆœ‰ๆ•ˆ * @param record ็ป“ๆžœ้›† * @return ็ปง็ปญๆ“ไฝœ */ default boolean creating(Record<T, K> record) { return true; } /** * ไบ‹ไปถไผšๅฝ“ไธ€ไธชๆ–ฐๆจกๅž‹่ขซ้ฆ–ๆฌกไฟๅญ˜ๅŽ่งฆๅ‘ * ไป…ORMๅœบๆ™ฏๆœ‰ๆ•ˆ * @param record ็ป“ๆžœ้›† */ default void created(Record<T, K> record) { } /** * ไธ€ไธชๆจกๅž‹ๅทฒ็ปๅœจๆ•ฐๆฎๅบ“ไธญๅญ˜ๅœจๅนถ่ฐƒ็”จsave * ไป…ORMๅœบๆ™ฏๆœ‰ๆ•ˆ * @param record ็ป“ๆžœ้›† * @return ็ปง็ปญๆ“ไฝœ */ default boolean updating(Record<T, K> record) { return true; } /** * ไธ€ไธชๆจกๅž‹ๅทฒ็ปๅœจๆ•ฐๆฎๅบ“ไธญๅญ˜ๅœจๅนถ่ฐƒ็”จsave * ไป…ORMๅœบๆ™ฏๆœ‰ๆ•ˆ * @param record ็ป“ๆžœ้›† */ default void updated(Record<T, K> record) { } /** * ๆ— ่ฎบๆ˜ฏๅˆ›ๅปบ่ฟ˜ๆ˜ฏๆ›ดๆ–ฐ * ไป…ORMๅœบๆ™ฏๆœ‰ๆ•ˆ * @param record ็ป“ๆžœ้›† * @return ็ปง็ปญๆ“ไฝœ */ default boolean saving(Record<T, K> record) { return true; } /** * ๆ— ่ฎบๆ˜ฏๅˆ›ๅปบ่ฟ˜ๆ˜ฏๆ›ดๆ–ฐ * ไป…ORMๅœบๆ™ฏๆœ‰ๆ•ˆ * @param record ็ป“ๆžœ้›† */ default void saved(Record<T, K> record) { } /** * ๅˆ ้™คๆ—ถ * ไป…ORMๅœบๆ™ฏๆœ‰ๆ•ˆ * @param record ็ป“ๆžœ้›† * @return ็ปง็ปญๆ“ไฝœ */ default boolean deleting(Record<T, K> record) { return true; } /** * ๅˆ ้™คๅŽ * ไป…ORMๅœบๆ™ฏๆœ‰ๆ•ˆ * @param record ็ป“ๆžœ้›† */ default void deleted(Record<T, K> record) { } /** * ๆขๅคๆ—ถ * ไป…ORMๅœบๆ™ฏๆœ‰ๆ•ˆ * @param record ็ป“ๆžœ้›† * @return ็ปง็ปญๆ“ไฝœ */ default boolean restoring(Record<T, K> record) { return true; } /** * ๆขๅคๅŽ * ไป…ORMๅœบๆ™ฏๆœ‰ๆ•ˆ * @param record ็ป“ๆžœ้›† */ default void restored(Record<T, K> record) { } }
PHP
UTF-8
1,143
2.9375
3
[]
no_license
<?php namespace App; require __DIR__ . '/vendor/autoload.php'; use src\{ Validate, Search, TreatApiReturn }; class App { private $verifyPost; public $result; public function __construct(){ $this->verifyPost = isset($_POST['action']) AND !empty($_POST['cep']) ? $this->MainController($_POST['cep']) : null; } public function MainController($cep) { $validate = new \src\Validate; $response = $validate->validateCep($cep); if($response === true) { $search = new Search; $return = $search->callApi($cep); $treatReturn = new TreatApiReturn; $result = $treatReturn->treat($return); $this->displayResult($result); }else { echo 'Verifique o cep'; } } public function displayResult($results) { foreach ($results as $key => $value) { echo $key . ': ' . $value. '<br>'; } } } new App();
TypeScript
UTF-8
6,023
3.453125
3
[ "MIT" ]
permissive
enum BlockPhraseType { CONTAIN = 0, EXACTWORD, WORDCONTAINING, REGEX } enum BlockPhraseScope { URL= 0, BODY, ANY } export interface PhraseFilter { Scope : BlockPhraseScope, Type : BlockPhraseType, Phrase: string } let BlockedPhrases : Array<PhraseFilter> = []; export function setBlockedPhrases(phrases: PhraseFilter[]) { BlockedPhrases = phrases; } function isLetter(char:string) : boolean { //https://stackoverflow.com/a/22075070/1997873 let c = char.charAt(0); return /[a-zA-Z]/.test(c) || /[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]/.test(c) } function getWords(text:string) : string[] { if (!text || text == "") return []; text = text.toLowerCase(); let words : string[] = []; let insideWord : Boolean = isLetter(text.charAt(0)) let currentWord : string[] = []; // instead of StringBuilder for (let i=0; i<text.length;i++) { if (isLetter(text.charAt(i))) { if (insideWord) {} else { insideWord = true; } currentWord.push(text.charAt(i)); } else { if (insideWord) { insideWord = false; if (currentWord.length > 0) words.push(currentWord.join("")); currentWord = []; } else {/*Nothing*/} } } if (insideWord) { if (currentWord.length > 0) { words.push(currentWord.join("")) } } return words; } function getWordSurrounding(content:string, index:number, tryLength:number, expand:number=10) : string { if (!content || content == "") return ""; let before = Math.max(index-expand, 0); let after = Math.min(index + tryLength + expand, content.length) return content.substr(before, (index - before)) + "_<" + content.substr(index, tryLength) + ">_" + content.substr(index + tryLength, (after - (index + tryLength)) ); } function checkPhraseFoundSimple(Content:string, filter:PhraseFilter, context: (c:string)=>void) : boolean { context(""); if (filter.Phrase == "") return false; let found :boolean = false; Content = Content.toLowerCase(); switch(filter.Type) { case BlockPhraseType.CONTAIN: var index = Content.indexOf(filter.Phrase); if (index > -1) context( getWordSurrounding(Content, index, filter.Phrase.length) ) found = index > -1; break; case BlockPhraseType.REGEX: var match =new RegExp(filter.Phrase).exec(Content); var matchIndex = match.index; if (matchIndex > -1) context(getWordSurrounding(Content, match.index, match[0].length)); found = matchIndex > -1 ; break; } return found; } function checkPhraseFoundWord(words : string[], filter: PhraseFilter, context: (c:string)=>void) : boolean { context(""); if (filter.Phrase == "") return false; let _local_context= ""; let found : boolean = false; let index : number = 0; switch (filter.Type) { case BlockPhraseType.EXACTWORD: index = words.indexOf(filter.Phrase.toLowerCase()); if (index > -1) _local_context= (words[index]); found = index > -1; break; case BlockPhraseType.WORDCONTAINING: index = words.findIndex((word) => word.indexOf(filter.Phrase.toLowerCase())>-1) ; if (index > -1) _local_context = (words[index]); found = index > -1; break; } context("_<" + _local_context + ">_"); return found; } /// <summary> /// Find the phrase that the content is blocked from using. /// </summary> /// <param name="Content">string chunk</param> /// <returns>Null if no phrase rule is applicabalbe (allowed)</returns> function findBlockingPhrase(Content:string, scope:BlockPhraseScope ,context: (c:string)=>void) : PhraseFilter { let result : PhraseFilter = null; let Words : string[] = getWords(Content); context(""); for (let i=0;i<BlockedPhrases.length && result == null; i++) { if ( scope == BlockPhraseScope.ANY || BlockedPhrases[i].Scope == BlockPhraseScope.ANY || BlockedPhrases[i].Scope == scope ) { switch(BlockedPhrases[i].Type) { case BlockPhraseType.CONTAIN: case BlockPhraseType.REGEX: if (checkPhraseFoundSimple(Content, BlockedPhrases[i], context)) { result = BlockedPhrases[i]; } break; case BlockPhraseType.EXACTWORD: case BlockPhraseType.WORDCONTAINING: if (checkPhraseFoundWord(Words, BlockedPhrases[i], context)) { result = BlockedPhrases[i]; } break; } } } return result; } /// <summary> /// Check if content clean of bad words /// </summary> /// <param name="Content"></param> /// <returns>True if content is allowed under policy</returns> function isContentAllowed(Content:string, scope:BlockPhraseScope, reason: (r:string)=>void) : boolean { let phraseContext = ""; let phrase = findBlockingPhrase(Content, scope, (c)=>{phraseContext=c}); if (phrase == null) { reason("content allowed, no phrase found in scope " + scope) return true; } else { reason ("content blocked because scope <*" + scope + "*> equal phrase <*" + phrase.Phrase + "*>, context: " + phraseContext); return false; } } export function isHTMLAllowed(Content:string, reason: (r:string)=>void) : boolean { return isContentAllowed(Content, BlockPhraseScope.BODY, reason); }
Java
UTF-8
1,314
2.875
3
[]
no_license
package com.tieto.training; import com.tieto.training.person.Person; import com.tieto.training.person.PersonComparatorNameOnly; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import static com.tieto.training.ArrayHandlerTestPersonValues.PERSONS; class ArrayHandlerTestPersonCompareComparator { private PersonComparatorNameOnly comparator; @BeforeEach void init() { comparator = new PersonComparatorNameOnly(); } @Test @DisplayName("any to any") void compareElements() { for (int i = 0; i < PERSONS.length; i++) { for (int j = i + 1; j < PERSONS.length - 1; j++) { assertTrue(comparator.compare(PERSONS[i], PERSONS[j + 1]) > 0, "expected p[" + i + "] bigger than p[" + (j + 1) + "]"); assertTrue(comparator.compare(PERSONS[j], PERSONS[i]) < 0, "expected p[" + j + "] smaller than p[" + i + "]"); } } } @Test @DisplayName("equal elements") void compareElementsSomeEquial() { for (int i = 0; i < PERSONS.length; i++) { assertEquals(0, comparator.compare(PERSONS[i], PERSONS[i]), "expected p[" + i + "] equal to p[" + i + "]"); } } }
Java
UTF-8
1,832
2.59375
3
[]
no_license
package uk.ac.ucl.servlets; import uk.ac.ucl.model.Model; import uk.ac.ucl.model.ModelFactory; import uk.ac.ucl.model.dataframes.FrameException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; @WebServlet("/patientfirstnamesByAlphabet.html") public class patientNamesByAlphabetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { char c = request.getParameter("char").charAt(0); Model model = null; try { model = ModelFactory.getModel(); } catch ( FrameException e) { e.printStackTrace(); } ArrayList<String> names = new ArrayList<>(); try { assert model != null; names = model.getPartitionResult("FIRST").get(c); } catch (FrameException e) { e.printStackTrace(); } // Then add the data to the request object that will be sent to the Java Server Page, so that // the JSP can access the data (a Java data structure). request.setAttribute("charcter", c); request.setAttribute("firstnamesByAlphabet", names); // Invoke the JSP. // A JSP page is actually converted into a Java class, so behind the scenes everything is Java. ServletContext context = getServletContext(); RequestDispatcher dispatch = context.getRequestDispatcher("/patientfirstnamesByAlphabet.jsp"); dispatch.forward(request, response); } }
Markdown
UTF-8
676
2.828125
3
[]
no_license
**Classes** - An abstract class Bee is added to be inherited by othery Bee type classes - Chose abstract class instead of interface so that method implementations could be shared. - Health property's set section is set as private so that it is not accessible from outside of the class and only be manipulated using Bee class methods. - Death is a boolean variable that denotes the death status - DeathFactor is the death threshold for each bee type and is an abstract member in the Bee class - Each bee type implements its own death factor **Application** - Added a windows form to display the bee and its health - Added a button to call the damage function of bee class.
C#
UTF-8
939
3.171875
3
[]
no_license
๏ปฟusing System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; namespace ObservableCollectionWithRange { partial class Program { public class ObservableCollectionWithRange<T> : ObservableCollection<T> { #region Constructors public ObservableCollectionWithRange() : base() { } public ObservableCollectionWithRange(List<T> list) : base(list) { } public ObservableCollectionWithRange(IEnumerable<T> collection) : base(collection) { } #endregion Constructors public void AddRange(IEnumerable<T> items) { foreach (var item in items) { Items.Add(item); } OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } } }
JavaScript
UTF-8
1,038
2.921875
3
[]
no_license
export const initialState = { active: [], completed: [], others: [], currentNote: '', currentStatus: '', showList:false } const getObjWithId = (payload) => { let obj = { ...payload, id: new Date().getTime() } return obj; } export const NotesReducer = (state, action) => { switch (action.type.toLowerCase()) { case 'load_new': { return {...action.payload} } case 'active': { const { active, completed, others } = state; active.push(getObjWithId(action.payload)) return { 'active': [...active], 'completed': [...completed], 'others': [...others], showList: true }; } case 'completed': { const { active, completed, others } = state; completed.push(getObjWithId(action.payload)) return { 'active': [...active], 'completed': [...completed], 'others': [...others], showList: true }; } default: { const { active, completed, others } = state; others.push(getObjWithId(action.payload)) return { 'active': [...active], 'completed': [...completed], 'others': [...others], showList: true }; } } }
C
UTF-8
10,270
2.59375
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
/* vi:set ts=4 sw=4 expandtab: * * Copyright 2016, Chris Leishman (http://github.com/cleishm) * * 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. */ #include "../../config.h" #include "../../lib/src/cypher-parser.h" #include <check.h> #include <errno.h> #include <unistd.h> #define MAX_SEGMENTS 8 static FILE *in; static FILE *out; static unsigned int nsegments; static bool is_statement[MAX_SEGMENTS]; static char *segments[MAX_SEGMENTS]; static struct cypher_input_range ranges[MAX_SEGMENTS]; static bool eofs[MAX_SEGMENTS]; static void setup(void) { int fds[2]; ck_assert(pipe(fds) == 0); in = fdopen(fds[0], "r"); ck_assert_ptr_ne(in, NULL); out = fdopen(fds[1], "w"); ck_assert_ptr_ne(out, NULL); nsegments = 0; memset(is_statement, 0, sizeof(is_statement)); memset(segments, 0, sizeof(segments)); memset(ranges, 0, sizeof(ranges)); memset(eofs, 0, sizeof(eofs)); } static void teardown(void) { if (out != NULL) { fclose(out); } fclose(in); for (unsigned int i = 0; i < nsegments; ++i) { free(segments[i]); } } static void fill_stream(const char *content) { fputs(content, out); fclose(out); out = NULL; } static int segment_callback(void *data, const cypher_quick_parse_segment_t *segment) { ck_assert(nsegments < MAX_SEGMENTS); is_statement[nsegments] = cypher_quick_parse_segment_is_statement(segment); size_t n; const char *s = cypher_quick_parse_segment_get_text(segment, &n); segments[nsegments] = strndup(s, n); ck_assert(segments[nsegments] != NULL); ranges[nsegments] = cypher_quick_parse_segment_get_range(segment); eofs[nsegments] = cypher_quick_parse_segment_is_eof(segment); ++nsegments; return 0; } START_TEST (fparse_none) { fill_stream(""); int result = cypher_quick_fparse(in, segment_callback, NULL, 0); ck_assert_int_eq(result, 0); ck_assert_int_eq(nsegments, 0); } END_TEST START_TEST (fparse_empty_statement) { fill_stream(";"); int result = cypher_quick_fparse(in, segment_callback, NULL, 0); ck_assert_int_eq(result, 0); ck_assert_int_eq(nsegments, 1); ck_assert(is_statement[0]); ck_assert_str_eq(segments[0], ""); ck_assert_int_eq(ranges[0].start.line, 1); ck_assert_int_eq(ranges[0].start.column, 1); ck_assert_int_eq(ranges[0].start.offset, 0); ck_assert_int_eq(ranges[0].end.line, 1); ck_assert_int_eq(ranges[0].end.column, 1); ck_assert_int_eq(ranges[0].end.offset, 0); } END_TEST START_TEST (fparse_whitespace_statement) { fill_stream(" ; "); int result = cypher_quick_fparse(in, segment_callback, NULL, 0); ck_assert_int_eq(result, 0); ck_assert_int_eq(nsegments, 2); ck_assert(is_statement[0]); ck_assert_str_eq(segments[0], ""); ck_assert_int_eq(ranges[0].start.line, 1); ck_assert_int_eq(ranges[0].start.column, 3); ck_assert_int_eq(ranges[0].start.offset, 2); ck_assert_int_eq(ranges[0].end.line, 1); ck_assert_int_eq(ranges[0].end.column, 3); ck_assert_int_eq(ranges[0].end.offset, 2); ck_assert(is_statement[1]); ck_assert_str_eq(segments[1], ""); ck_assert_int_eq(ranges[1].start.line, 1); ck_assert_int_eq(ranges[1].start.column, 5); ck_assert_int_eq(ranges[1].start.offset, 4); ck_assert_int_eq(ranges[1].end.line, 1); ck_assert_int_eq(ranges[1].end.column, 5); ck_assert_int_eq(ranges[1].end.offset, 4); } END_TEST START_TEST (fparse_single) { fill_stream("return 1;"); int result = cypher_quick_fparse(in, segment_callback, NULL, 0); ck_assert_int_eq(result, 0); ck_assert_int_eq(nsegments, 1); ck_assert(is_statement[0]); ck_assert_str_eq(segments[0], "return 1"); ck_assert_int_eq(ranges[0].start.line, 1); ck_assert_int_eq(ranges[0].start.column, 1); ck_assert_int_eq(ranges[0].start.offset, 0); ck_assert_int_eq(ranges[0].end.line, 1); ck_assert_int_eq(ranges[0].end.column, 9); ck_assert_int_eq(ranges[0].end.offset, 8); ck_assert(!eofs[0]); } END_TEST START_TEST (fparse_multiple) { fill_stream("return 1; return 2;\n return 3 ;"); int result = cypher_quick_fparse(in, segment_callback, NULL, 0); ck_assert_int_eq(result, 0); ck_assert_int_eq(nsegments, 3); ck_assert(is_statement[0]); ck_assert_str_eq(segments[0], "return 1"); ck_assert_int_eq(ranges[0].start.line, 1); ck_assert_int_eq(ranges[0].start.column, 1); ck_assert_int_eq(ranges[0].start.offset, 0); ck_assert_int_eq(ranges[0].end.line, 1); ck_assert_int_eq(ranges[0].end.column, 9); ck_assert_int_eq(ranges[0].end.offset, 8); ck_assert(!eofs[0]); ck_assert(is_statement[1]); ck_assert_str_eq(segments[1], "return 2"); ck_assert_int_eq(ranges[1].start.line, 1); ck_assert_int_eq(ranges[1].start.column, 11); ck_assert_int_eq(ranges[1].start.offset, 10); ck_assert_int_eq(ranges[1].end.line, 1); ck_assert_int_eq(ranges[1].end.column, 19); ck_assert_int_eq(ranges[1].end.offset, 18); ck_assert(!eofs[1]); ck_assert(is_statement[2]); ck_assert_str_eq(segments[2], "return 3"); ck_assert_int_eq(ranges[2].start.line, 2); ck_assert_int_eq(ranges[2].start.column, 4); ck_assert_int_eq(ranges[2].start.offset, 23); ck_assert_int_eq(ranges[2].end.line, 2); ck_assert_int_eq(ranges[2].end.column, 12); ck_assert_int_eq(ranges[2].end.offset, 31); ck_assert(!eofs[2]); } END_TEST START_TEST (fparse_commands) { fill_stream(":foo bar\"baz\"\n"); int result = cypher_quick_fparse(in, segment_callback, NULL, 0); ck_assert_int_eq(result, 0); ck_assert_int_eq(nsegments, 1); ck_assert(!is_statement[0]); ck_assert_str_eq(segments[0], ":foo bar\"baz\""); ck_assert_int_eq(ranges[0].start.line, 1); ck_assert_int_eq(ranges[0].start.column, 1); ck_assert_int_eq(ranges[0].start.offset, 0); ck_assert_int_eq(ranges[0].end.line, 1); ck_assert_int_eq(ranges[0].end.column, 14); ck_assert_int_eq(ranges[0].end.offset, 13); ck_assert(!eofs[0]); } END_TEST START_TEST (fparse_statements_only) { fill_stream("return 1; :foo bar\"baz\"\n return 2;"); int result = cypher_quick_fparse(in, segment_callback, NULL, CYPHER_PARSE_ONLY_STATEMENTS); ck_assert_int_eq(result, 0); ck_assert_int_eq(nsegments, 2); ck_assert(is_statement[0]); ck_assert_str_eq(segments[0], "return 1"); ck_assert_int_eq(ranges[0].start.line, 1); ck_assert_int_eq(ranges[0].start.column, 1); ck_assert_int_eq(ranges[0].start.offset, 0); ck_assert_int_eq(ranges[0].end.line, 1); ck_assert_int_eq(ranges[0].end.column, 9); ck_assert_int_eq(ranges[0].end.offset, 8); ck_assert(!eofs[0]); ck_assert(is_statement[1]); ck_assert_str_eq(segments[1], ":foo bar\"baz\"\n return 2"); ck_assert_int_eq(ranges[1].start.line, 1); ck_assert_int_eq(ranges[1].start.column, 11); ck_assert_int_eq(ranges[1].start.offset, 10); ck_assert_int_eq(ranges[1].end.line, 2); ck_assert_int_eq(ranges[1].end.column, 10); ck_assert_int_eq(ranges[1].end.offset, 33); ck_assert(!eofs[1]); } END_TEST START_TEST (fparse_eof_statement) { fill_stream("return 1; return 2"); int result = cypher_quick_fparse(in, segment_callback, NULL, 0); ck_assert_int_eq(result, 0); ck_assert_int_eq(nsegments, 2); ck_assert(is_statement[0]); ck_assert_str_eq(segments[0], "return 1"); ck_assert_int_eq(ranges[0].start.line, 1); ck_assert_int_eq(ranges[0].start.column, 1); ck_assert_int_eq(ranges[0].start.offset, 0); ck_assert_int_eq(ranges[0].end.line, 1); ck_assert_int_eq(ranges[0].end.column, 9); ck_assert_int_eq(ranges[0].end.offset, 8); ck_assert(!eofs[0]); ck_assert(is_statement[1]); ck_assert_str_eq(segments[1], "return 2"); ck_assert_int_eq(ranges[1].start.line, 1); ck_assert_int_eq(ranges[1].start.column, 11); ck_assert_int_eq(ranges[1].start.offset, 10); ck_assert_int_eq(ranges[1].end.line, 1); ck_assert_int_eq(ranges[1].end.column, 19); ck_assert_int_eq(ranges[1].end.offset, 18); ck_assert(eofs[1]); } END_TEST START_TEST (fparse_eof_command) { fill_stream(":bar\n:foo bar\"baz\""); int result = cypher_quick_fparse(in, segment_callback, NULL, 0); ck_assert_int_eq(result, 0); ck_assert_int_eq(nsegments, 2); ck_assert(!is_statement[0]); ck_assert_str_eq(segments[0], ":bar"); ck_assert_int_eq(ranges[0].start.line, 1); ck_assert_int_eq(ranges[0].start.column, 1); ck_assert_int_eq(ranges[0].start.offset, 0); ck_assert_int_eq(ranges[0].end.line, 1); ck_assert_int_eq(ranges[0].end.column, 5); ck_assert_int_eq(ranges[0].end.offset, 4); ck_assert(!eofs[0]); ck_assert(!is_statement[1]); ck_assert_str_eq(segments[1], ":foo bar\"baz\""); ck_assert_int_eq(ranges[1].start.line, 2); ck_assert_int_eq(ranges[1].start.column, 1); ck_assert_int_eq(ranges[1].start.offset, 5); ck_assert_int_eq(ranges[1].end.line, 2); ck_assert_int_eq(ranges[1].end.column, 14); ck_assert_int_eq(ranges[1].end.offset, 18); ck_assert(eofs[1]); } END_TEST TCase* quick_fparse_tcase(void) { TCase *tc = tcase_create("quick_fparse"); tcase_add_checked_fixture(tc, setup, teardown); tcase_add_test(tc, fparse_none); tcase_add_test(tc, fparse_empty_statement); tcase_add_test(tc, fparse_whitespace_statement); tcase_add_test(tc, fparse_single); tcase_add_test(tc, fparse_multiple); tcase_add_test(tc, fparse_commands); tcase_add_test(tc, fparse_statements_only); tcase_add_test(tc, fparse_eof_statement); tcase_add_test(tc, fparse_eof_command); return tc; }
Java
UTF-8
714
2.328125
2
[ "MIT" ]
permissive
package mage.cards.w; import java.util.UUID; import mage.MageInt; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; /** * * @author Loki */ public final class WanderingOnes extends CardImpl { public WanderingOnes (UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{U}"); this.subtype.add(SubType.SPIRIT); this.power = new MageInt(1); this.toughness = new MageInt(1); } private WanderingOnes(final WanderingOnes card) { super(card); } @Override public WanderingOnes copy() { return new WanderingOnes(this); } }
Rust
UTF-8
1,634
2.5625
3
[ "MIT" ]
permissive
use { anyhow::Result, crate::{ app::{ NewCampaignCommand, PackCampaignCommand, }, persist::{ self, Bag, SerdeFormat, }, }, }; mod campaign; mod loaded_campaign; pub use { campaign::Campaign, loaded_campaign::*, }; pub fn create(ncc: &NewCampaignCommand) -> Result<()> { let mut c = Campaign::default(); c.name = "Unnamed Campaign".to_string(); let bag = Bag::from(c); let format = ncc.output_format.as_ref() .and_then(|key| SerdeFormat::from_key(&key)) .unwrap_or(SerdeFormat::Json); persist::write_file( &bag, &ncc.path, Some(format), true, ) } /// write a bag containing a campaign and its levels /// (which are found preferably in external files and /// in the initial bag if not found externally) pub fn pack(pcc: &PackCampaignCommand) -> Result<()> { let in_bag: Bag = persist::read_file(&pcc.unpacked_path)?; if !in_bag.is_campaign() { Err(anyhow!("no campaign found in bag"))? } let loaded_campaign = LoadedCampaign::load( &pcc.unpacked_path, in_bag, LoadOrigin::External, )?; let mut out_bag = Bag::from(loaded_campaign.campaign.clone()); let len = loaded_campaign.campaign.levels.len(); for i in 0..len { out_bag.levels.insert( loaded_campaign.campaign.levels[i].to_string(), loaded_campaign.levels[i].level.clone(), ); } persist::write_file( &out_bag, &pcc.packed_path, None, false, ) }
Markdown
UTF-8
2,121
2.9375
3
[]
no_license
+++ title = "Timelapse" date = 2020-09-05T21:01:22-07:00 tags = ["programming", "time", "video", "long-now", "diy"] +++ I have a fascination with time. Two years ago, our family planted a tree in our back yard. A few months prior, my dad and I built an overhang that provides shade. {{<img "img/overhang.jpg">}} I used a pillar supporting the overhang to point this [timelapse camera](https://www.amazon.com/gp/product/B01FJZQONW/) at the tree. I bought that camera because of it's low battery usage, and how it uses standard JPEGs on a standard SD card. That gives me raw material to compress a large amount of time into a nice video. Trees are reminders of different time scales. They are our ambassadors to the [Long Now](/posts/long-now/). The raw emotion of seeing two years fly by in a few seconds is a decent approximation of the experience of seeing your child grow up. It's a good reminder of the finitness of your life. It's call to action to do those things you have been putting off. Time is finite. It's the only thing that can't be manufactured. Now to the technical stuff, I wrote [this code](https://github.com/tlehman/timelapse-cam) to extract jpegs from the timelapse camera's SD card. It uses the jpeg's [EXIF metadata](https://en.wikipedia.org/wiki/Exif) to get the `created_at` date from the file. After copying the files to a temporary directory, it uses `ffmpeg` to turn the jpegs into frames of a video. Here is a sample from October 2018 to September 2020: <video controls width="100%"><source src="/posts/timelapse/timelapse-tree.mp4" type="video/mp4" /></video> The music is by Hans Zimmer, it was edited in iMovie for iOS, and I am happy with the result. It conveys the feeling of growth, change, and rebirth. But I also can't help but feel it's incompleteness. This is only day 1 of this tree's life. This tree is just getting started. It will cast a shadow for people I don't know, and for people who don't exist yet. It is my connection to the future. I always appreciate feedback on my code, or videos, or posts. Mail your comments to <a href="mailto:mail@tobilehman.com">mail@tobilehman.com</a>
Java
UTF-8
58,932
2.359375
2
[]
no_license
package wordmatch; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; /** * * @author Tasnim Akther, ID: 150103020027 * @author Monira Enam Heya, ID: 150103020045 * @author Md Mahadi Hasan Nahid, nahid@neub.edu.bd */ public class StepThree extends javax.swing.JFrame implements ActionListener { /** * Creates new form game1 */ int answer1 = 5, burg=0, c = 0, love=0, lol=0, japan=0; public StepThree() { initComponents(); setTitle("Word Matching"); setLocationRelativeTo(null); addingAction(); } private void addingAction() { homeButton.addActionListener(this); nextButton.addActionListener(this); // buttonA.addActionListener(this); // buttonP.addActionListener(this); // buttonP1.addActionListener(this); // buttonL.addActionListener(this); // buttonE.addActionListener(this); // buttonLOL.addActionListener(this); // buttonLOL1.addActionListener(this); // buttonLOL2.addActionListener(this); // buttonLove1.addActionListener(this); // buttonLove2.addActionListener(this); // buttonLove3.addActionListener(this); // buttonLove4.addActionListener(this); // burgB.addActionListener(this); // burgU.addActionListener(this); // burgR.addActionListener(this); // burgG.addActionListener(this); // burgE.addActionListener(this); // burgR1.addActionListener(this); // countryJ.addActionListener(this); // countryA.addActionListener(this); // countryP.addActionListener(this); // countryA1.addActionListener(this); // countryN.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == homeButton) { this.dispose(); WordMatching ob = new WordMatching(); ob.setVisible(true); } if (e.getSource() == nextButton) { this.dispose(); StepThree ob = new StepThree(); ob.setVisible(true); } if (e.getSource() == quitMenuItem) { int answer = JOptionPane.showConfirmDialog(null, "Do you really want to quit?", "Confirm", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.NO_OPTION) { this.setVisible(true); } else { System.exit(0); } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton10 = new javax.swing.JButton(); jButton11 = new javax.swing.JButton(); jButton14 = new javax.swing.JButton(); jButton15 = new javax.swing.JButton(); jButton17 = new javax.swing.JButton(); jButton18 = new javax.swing.JButton(); jButton19 = new javax.swing.JButton(); jButton20 = new javax.swing.JButton(); jButton21 = new javax.swing.JButton(); jButton24 = new javax.swing.JButton(); jButton27 = new javax.swing.JButton(); jButton28 = new javax.swing.JButton(); jButton30 = new javax.swing.JButton(); jButton33 = new javax.swing.JButton(); jButton34 = new javax.swing.JButton(); jButton35 = new javax.swing.JButton(); jButton36 = new javax.swing.JButton(); jButton37 = new javax.swing.JButton(); jButton39 = new javax.swing.JButton(); jButton41 = new javax.swing.JButton(); jButton43 = new javax.swing.JButton(); jButton44 = new javax.swing.JButton(); jButton46 = new javax.swing.JButton(); jButton47 = new javax.swing.JButton(); jButton48 = new javax.swing.JButton(); jButton49 = new javax.swing.JButton(); jButton51 = new javax.swing.JButton(); jButton53 = new javax.swing.JButton(); jButton54 = new javax.swing.JButton(); jButton55 = new javax.swing.JButton(); jButton56 = new javax.swing.JButton(); jButton62 = new javax.swing.JButton(); jButton64 = new javax.swing.JButton(); jButton65 = new javax.swing.JButton(); jButton66 = new javax.swing.JButton(); jButton67 = new javax.swing.JButton(); jButton50 = new javax.swing.JButton(); jButton52 = new javax.swing.JButton(); jButton57 = new javax.swing.JButton(); jButton58 = new javax.swing.JButton(); jButton59 = new javax.swing.JButton(); jButton60 = new javax.swing.JButton(); jButton61 = new javax.swing.JButton(); jButton63 = new javax.swing.JButton(); jButton45 = new javax.swing.JButton(); jButton68 = new javax.swing.JButton(); jButton69 = new javax.swing.JButton(); jButton70 = new javax.swing.JButton(); jButton71 = new javax.swing.JButton(); jButton72 = new javax.swing.JButton(); jButton73 = new javax.swing.JButton(); jButton74 = new javax.swing.JButton(); jButton75 = new javax.swing.JButton(); jButton76 = new javax.swing.JButton(); jButton77 = new javax.swing.JButton(); jButton78 = new javax.swing.JButton(); jButton79 = new javax.swing.JButton(); jButton80 = new javax.swing.JButton(); jButton81 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); resultLvl2 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); resultLvl1 = new javax.swing.JLabel(); resultLvl3 = new javax.swing.JLabel(); resultLvl5 = new javax.swing.JLabel(); resultLvl4 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); homeButton = new javax.swing.JButton(); nextButton = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); quitMenuItem = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel3.setBackground(new java.awt.Color(51, 0, 153)); jPanel3.setPreferredSize(new java.awt.Dimension(700, 500)); jPanel1.setPreferredSize(new java.awt.Dimension(450, 450)); jButton1.setBackground(new java.awt.Color(153, 0, 0)); jButton1.setText("K"); jButton4.setBackground(new java.awt.Color(153, 0, 0)); jButton4.setText("T"); jButton5.setBackground(new java.awt.Color(153, 0, 0)); jButton5.setText("D"); jButton6.setBackground(new java.awt.Color(153, 0, 0)); jButton6.setText("N"); jButton7.setBackground(new java.awt.Color(153, 0, 0)); jButton7.setText("E"); jButton10.setBackground(new java.awt.Color(153, 0, 0)); jButton10.setText("G"); jButton11.setBackground(new java.awt.Color(153, 0, 0)); jButton11.setText("E"); jButton14.setBackground(new java.awt.Color(153, 0, 0)); jButton14.setText("F"); jButton15.setBackground(new java.awt.Color(153, 0, 0)); jButton15.setText("T"); jButton17.setBackground(new java.awt.Color(153, 0, 0)); jButton17.setText("N"); jButton18.setBackground(new java.awt.Color(153, 0, 0)); jButton18.setText("U"); jButton19.setBackground(new java.awt.Color(153, 0, 0)); jButton19.setText("I"); jButton20.setBackground(new java.awt.Color(153, 0, 0)); jButton20.setText("Q"); jButton21.setBackground(new java.awt.Color(153, 0, 0)); jButton21.setText("J"); jButton24.setBackground(new java.awt.Color(153, 0, 0)); jButton24.setText("D"); jButton27.setBackground(new java.awt.Color(153, 0, 0)); jButton27.setText("I"); jButton28.setBackground(new java.awt.Color(153, 0, 0)); jButton28.setText("B"); jButton30.setBackground(new java.awt.Color(153, 0, 0)); jButton30.setText("M"); jButton33.setBackground(new java.awt.Color(153, 0, 0)); jButton33.setText("Z"); jButton34.setBackground(new java.awt.Color(153, 0, 0)); jButton34.setText("W"); jButton35.setBackground(new java.awt.Color(153, 0, 0)); jButton35.setText("O"); jButton36.setBackground(new java.awt.Color(153, 0, 0)); jButton36.setText("G"); jButton37.setBackground(new java.awt.Color(153, 0, 0)); jButton37.setText("L"); jButton39.setBackground(new java.awt.Color(153, 0, 0)); jButton39.setText("J"); jButton41.setBackground(new java.awt.Color(153, 0, 0)); jButton41.setText("K"); jButton43.setBackground(new java.awt.Color(153, 0, 0)); jButton43.setText("K"); jButton44.setBackground(new java.awt.Color(153, 0, 0)); jButton44.setText("I"); jButton46.setBackground(new java.awt.Color(153, 0, 0)); jButton46.setText("X"); jButton47.setBackground(new java.awt.Color(153, 0, 0)); jButton47.setText("F"); jButton48.setBackground(new java.awt.Color(153, 0, 0)); jButton48.setText("V"); jButton49.setBackground(new java.awt.Color(153, 0, 0)); jButton49.setText("D"); jButton51.setBackground(new java.awt.Color(153, 0, 0)); jButton51.setText("V"); jButton53.setBackground(new java.awt.Color(153, 0, 0)); jButton53.setText("C"); jButton54.setBackground(new java.awt.Color(153, 0, 0)); jButton54.setText("O"); jButton55.setBackground(new java.awt.Color(153, 0, 0)); jButton55.setText("S"); jButton56.setBackground(new java.awt.Color(153, 0, 0)); jButton56.setText("M"); jButton62.setBackground(new java.awt.Color(153, 0, 0)); jButton62.setText("Z"); jButton64.setBackground(new java.awt.Color(153, 0, 0)); jButton64.setText("L"); jButton65.setBackground(new java.awt.Color(153, 0, 0)); jButton65.setText("O"); jButton66.setBackground(new java.awt.Color(153, 0, 0)); jButton66.setText("C"); jButton67.setBackground(new java.awt.Color(153, 0, 0)); jButton67.setText("R"); jButton50.setBackground(new java.awt.Color(153, 0, 0)); jButton50.setText("D"); jButton52.setBackground(new java.awt.Color(153, 0, 0)); jButton52.setText("D"); jButton57.setBackground(new java.awt.Color(153, 0, 0)); jButton57.setText("D"); jButton58.setBackground(new java.awt.Color(153, 0, 0)); jButton58.setText("D"); jButton59.setBackground(new java.awt.Color(153, 0, 0)); jButton59.setText("D"); jButton60.setBackground(new java.awt.Color(153, 0, 0)); jButton60.setText("D"); jButton61.setBackground(new java.awt.Color(153, 0, 0)); jButton61.setText("D"); jButton63.setBackground(new java.awt.Color(153, 0, 0)); jButton63.setText("D"); jButton45.setBackground(new java.awt.Color(153, 0, 0)); jButton45.setText("I"); jButton68.setBackground(new java.awt.Color(153, 0, 0)); jButton68.setText("I"); jButton69.setBackground(new java.awt.Color(153, 0, 0)); jButton69.setText("I"); jButton70.setBackground(new java.awt.Color(153, 0, 0)); jButton70.setText("I"); jButton71.setBackground(new java.awt.Color(153, 0, 0)); jButton71.setText("I"); jButton72.setBackground(new java.awt.Color(153, 0, 0)); jButton72.setText("I"); jButton73.setBackground(new java.awt.Color(153, 0, 0)); jButton73.setText("I"); jButton74.setBackground(new java.awt.Color(153, 0, 0)); jButton74.setText("I"); jButton75.setBackground(new java.awt.Color(153, 0, 0)); jButton75.setText("I"); jButton76.setBackground(new java.awt.Color(153, 0, 0)); jButton76.setText("I"); jButton77.setBackground(new java.awt.Color(153, 0, 0)); jButton77.setText("I"); jButton78.setBackground(new java.awt.Color(153, 0, 0)); jButton78.setText("I"); jButton79.setBackground(new java.awt.Color(153, 0, 0)); jButton79.setText("I"); jButton80.setBackground(new java.awt.Color(153, 0, 0)); jButton80.setText("I"); jButton81.setBackground(new java.awt.Color(153, 0, 0)); jButton81.setText("I"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton51, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton55, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton56, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton78, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton53, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton54, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton66, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton65, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton64, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton62, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton67, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton63, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton79, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton80, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton81, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton61, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton74, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton73, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton76, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton60, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton14, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton15, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton71, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton17, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton27, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton77, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton24, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton58, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton72, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton21, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton20, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton19, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton18, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(jButton44, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton68, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton46, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton47, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton48, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton52, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton49, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton28, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton75, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton30, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton43, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton45, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton69, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton70, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton59, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton33, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton34, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton39, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton41, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton57, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton37, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton36, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton35, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton50, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(14, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton73, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton74, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton14, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton15, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton17, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton18, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton60, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton71, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton76, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton19, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton20, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton21, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton24, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton27, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton58, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton72, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton77, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton28, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton30, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton33, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton34, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton35, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton59, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton70, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton75, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton36, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton37, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton39, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton41, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton43, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton57, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton45, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton69, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton44, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton46, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton47, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton48, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton49, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton50, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton52, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton68, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton51, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton55, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton56, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton61, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton78, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton79, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton80, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton81, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton53, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton54, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton62, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton64, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton65, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton66, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton67, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton63, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(20, Short.MAX_VALUE)) ); jPanel2.setBackground(new java.awt.Color(153, 0, 0)); jLabel1.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("1. A fruit."); jLabel2.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("2. Laughing out loudly"); jLabel3.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("3. Heart"); jLabel4.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("5. A country"); jLabel5.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("4. Fast Food"); jLabel6.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("HINTS:"); resultLvl2.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N resultLvl2.setForeground(new java.awt.Color(255, 255, 255)); jLabel8.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N jLabel8.setForeground(new java.awt.Color(255, 255, 255)); jLabel8.setText("RESULT: "); resultLvl1.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N resultLvl1.setForeground(new java.awt.Color(255, 255, 255)); resultLvl3.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N resultLvl3.setForeground(new java.awt.Color(255, 255, 255)); resultLvl5.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N resultLvl5.setForeground(new java.awt.Color(255, 255, 255)); resultLvl4.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N resultLvl4.setForeground(new java.awt.Color(255, 255, 255)); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(resultLvl2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(resultLvl1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(resultLvl3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(resultLvl5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(resultLvl4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap())) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(3, 3, 3) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(56, 56, 56) .addComponent(resultLvl1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(resultLvl2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(resultLvl3, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(resultLvl4, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(resultLvl5, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(244, Short.MAX_VALUE) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(194, 194, 194))) ); jButton2.setBackground(new java.awt.Color(255, 255, 255)); jButton2.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N jButton2.setForeground(new java.awt.Color(0, 0, 102)); jButton2.setText("PREVIOUS"); homeButton.setBackground(new java.awt.Color(255, 255, 255)); homeButton.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N homeButton.setForeground(new java.awt.Color(0, 0, 102)); homeButton.setText("HOME"); nextButton.setBackground(new java.awt.Color(255, 255, 255)); nextButton.setFont(new java.awt.Font("Consolas", 1, 18)); // NOI18N nextButton.setForeground(new java.awt.Color(0, 0, 102)); nextButton.setText("NEXT"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 466, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(156, 156, 156) .addComponent(homeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 12, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(homeButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nextButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); jMenu1.setText("File"); jMenuItem1.setText("Instruction"); jMenu1.add(jMenuItem1); jMenuItem2.setText("About"); jMenu1.add(jMenuItem2); quitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK)); quitMenuItem.setText("Quit"); jMenu1.add(quitMenuItem); jMenuBar1.add(jMenu1); jMenu2.setText("Edit"); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 738, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(StepThree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(StepThree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(StepThree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(StepThree.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new StepThree().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton homeButton; private javax.swing.JButton jButton1; private javax.swing.JButton jButton10; private javax.swing.JButton jButton11; private javax.swing.JButton jButton14; private javax.swing.JButton jButton15; private javax.swing.JButton jButton17; private javax.swing.JButton jButton18; private javax.swing.JButton jButton19; private javax.swing.JButton jButton2; private javax.swing.JButton jButton20; private javax.swing.JButton jButton21; private javax.swing.JButton jButton24; private javax.swing.JButton jButton27; private javax.swing.JButton jButton28; private javax.swing.JButton jButton30; private javax.swing.JButton jButton33; private javax.swing.JButton jButton34; private javax.swing.JButton jButton35; private javax.swing.JButton jButton36; private javax.swing.JButton jButton37; private javax.swing.JButton jButton39; private javax.swing.JButton jButton4; private javax.swing.JButton jButton41; private javax.swing.JButton jButton43; private javax.swing.JButton jButton44; private javax.swing.JButton jButton45; private javax.swing.JButton jButton46; private javax.swing.JButton jButton47; private javax.swing.JButton jButton48; private javax.swing.JButton jButton49; private javax.swing.JButton jButton5; private javax.swing.JButton jButton50; private javax.swing.JButton jButton51; private javax.swing.JButton jButton52; private javax.swing.JButton jButton53; private javax.swing.JButton jButton54; private javax.swing.JButton jButton55; private javax.swing.JButton jButton56; private javax.swing.JButton jButton57; private javax.swing.JButton jButton58; private javax.swing.JButton jButton59; private javax.swing.JButton jButton6; private javax.swing.JButton jButton60; private javax.swing.JButton jButton61; private javax.swing.JButton jButton62; private javax.swing.JButton jButton63; private javax.swing.JButton jButton64; private javax.swing.JButton jButton65; private javax.swing.JButton jButton66; private javax.swing.JButton jButton67; private javax.swing.JButton jButton68; private javax.swing.JButton jButton69; private javax.swing.JButton jButton7; private javax.swing.JButton jButton70; private javax.swing.JButton jButton71; private javax.swing.JButton jButton72; private javax.swing.JButton jButton73; private javax.swing.JButton jButton74; private javax.swing.JButton jButton75; private javax.swing.JButton jButton76; private javax.swing.JButton jButton77; private javax.swing.JButton jButton78; private javax.swing.JButton jButton79; private javax.swing.JButton jButton80; private javax.swing.JButton jButton81; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel8; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JButton nextButton; private javax.swing.JMenuItem quitMenuItem; private javax.swing.JLabel resultLvl1; private javax.swing.JLabel resultLvl2; private javax.swing.JLabel resultLvl3; private javax.swing.JLabel resultLvl4; private javax.swing.JLabel resultLvl5; // End of variables declaration//GEN-END:variables }
Python
UTF-8
239
2.5625
3
[]
no_license
import numpy as np import math import sys sys.setrecursionlimit(10000000) def main(): K, X = map(int, input().split()) for i in range(X - K + 1, K + X): print(i, end=" ") print() if __name__ == '__main__': main()
Python
UTF-8
1,072
2.6875
3
[]
no_license
from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer,TfidfVectorizer from sklearn.pipeline import Pipeline from sklearn.linear_model import SGDClassifier from sklearn.svm import LinearSVC import re import numpy as np x_train=[] y_train=[] def words(text): return re.findall(r'(?:[a-zA-Z]+[a-zA-Z\'\-]?[a-zA-Z]|[a-zA-Z]+)',text) count=0 with open('training.txt', 'r') as f: for line in f: count+=1 if count==1: continue x=[a for a in line.rstrip().split("\t")] sen=" ".join(word for word in words(x[0])) x_train.append(sen) y_train.append(x[1]) x=np.array(x_train) y=np.array(y_train) text_clf=Pipeline([('vect',CountVectorizer()), ('tfidf',TfidfTransformer()), ('clf', LinearSVC())]) text_clf.fit(x,y) test=[] for i in range(int(input())): x=input() sen=" ".join(word for word in words(x)) test.append(x) predicted=text_clf.predict(np.array(test)) for i in predicted: print(i)
Python
UTF-8
13,420
2.890625
3
[]
no_license
import discord from discord.ext import commands from asyncio import sleep import os me = commands.Bot(command_prefix='.', self_bot=True) @me.event async def on_ready(): print("----------") print("Logged in as:") print(" "+str(me.user.name)) print(" "+str(me.user.id)) print("----------") def makeEmbed(*, name=None, icon=None, colour=0xDEADBF, values={}): '''Creates an embed messasge with specified inputs''' embedObj = discord.Embed(colour=colour) embedObj.set_author(name=name, icon_url=icon) for i in values: if values[i] == '': values[i] = 'None' embedObj.add_field(name=i, value='{}'.format(values[i])) return embedObj @me.event async def on_message(message): if message.author.id != me.user.id: return if len(message.embeds) > 0: return if message.content == "/์†Œํ†ต1": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_1", description="์ฒซ ๋ฒˆ์งธ ์งˆ๋ฌธ์ž…๋‹ˆ๋‹ค!\n์ƒˆ๋กœ ์ƒ๊ธด <#590852771125788699> ์‹œ์Šคํ…œ์— ๋Œ€ํ•ด ๋ณธ์ธ์˜ ์ƒ๊ฐ์„ ์•„๋ฌด๋ ‡๊ฒŒ๋‚˜ ์ ์–ด์ฃผ์„ธ์š”!", color=0x738adb) embed.set_footer(text="2019_06_19") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต2": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_2", description="๋ณธ์ธ์ด ํ•  ์ผ ์—†์„ ๋•Œ ํ‰์†Œ์— ํ•˜๋Š” ๊ฒƒ์„ ์ ์–ด์ฃผ์„ธ์š”!\n์˜ˆ๋ฅผ ๋“ค์–ด์„œ ์ˆจ์‰ฌ๊ธฐ๋ผ๋˜๊ฐ€ ์ˆจ์‰ฌ๊ธฐ๋ผ๋˜๊ฐ€...?", color=0x738adb) embed.set_footer(text="2019_06_20") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต3": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_3", description="๋”์šด ์—ฌ๋ฆ„์„ ๋‚ ๋ ค๋ฒ„๋ฆด ๊ฐ€์žฅ ์ข‹์€ ๊ฒƒ์„ ๋งํ•ด๋ด์š”!", color=0x738adb) embed.set_footer(text="2019_06_21") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต4": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_4", description="์ธ์ƒ์— ๊ผญ ๋‹ด๊ณ ์‹ถ์€ ๊ฐ€์žฅ ์ข‹์•„ํ•˜๋Š” ๋ช…์–ธ๊ฐ™์€ ๊ฒƒ์ด ์žˆ๋‚˜์š”?\n์žˆ๋‹ค๋ฉด ๊ทธ๊ฒƒ์€ ๋ฌด์—‡์ธ๊ฐ€์š”?", color=0x738adb) embed.set_footer(text="2019_06_22") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต5": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_5", description="์ด ์„œ๋ฒ„์˜ ์ด๋ฆ„์ธ [๋“ค์–ด์˜ค๋ฉด ํ›„ํšŒํ•จ]์„ ๋ณด๋ฉด ์–ด๋–ค ์ƒ๊ฐ์ด ๋“œ๋Š” ์ง€ ๋งํ•ด๋ณด์•„์š”!", color=0x738adb) embed.set_footer(text="2019_06_23") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต6": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_6", description="๋งํ•  ์›”์š”์ผ์ด ๋Œ์•„์™”์Šต๋‹ˆ๋‹ค!\n๋Œ์•„์˜จ ์›”์š”์ผ์„ ์œ„ํ•ด(?) ํ•œ ๋งˆ๋””์”ฉ ๋‚จ๊ฒจ์ฃผ์„ธ์š”!", color=0x738adb) embed.set_footer(text="2019_06_24") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต7": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_7", description="**๊ฐ•์•„์ง€ vs ๊ณ ์–‘์ด** | ๋ณธ์ธ์ด ๊ฐ€์žฅ ์ข‹์•„ํ•˜๋Š” ๊ฒƒ์€?", color=0x738adb) embed.set_footer(text="2019_06_25") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต8": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_8", description="๋น„๊ฐ€ ์˜ค๋Š” ๋‚ ์”จ์— ๊ฐ€์žฅ ํ•˜๊ณ  ์‹ถ์€ ์ผ์€ ๋ฌด์—‡์ผ๊นŒ์š”?", color=0x738adb) embed.set_footer(text="2019_06_26") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต9": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_9", description="์—ฌ๋Ÿฌ๋ถ„์˜ ํ‰๊ท  ํƒ€์ž ์†๋„๋Š” ์–ผ๋งˆ๋‚˜ ๋˜๋‚˜์š”?", color=0x738adb) embed.set_footer(text="2019_06_27") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต10": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_10", description="<@311791989681291264> vs <@150577293981515776>\n๋‘˜ ์ค‘ ๋” ๊ท€์—ฌ์šด ์‚ฌ๋žŒ์„ ์„ ํƒํ•œ๋‹ค๋ฉด? ||~~๋‚œ์ฃฝํƒ~~||", color=0x738adb) embed.set_footer(text="2019_06_28") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต11": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_11", description="๊ณผ์˜Œ ๋งˆ์ถค๋ปก์„ ์•Š์ง€ํ‚ˆ๋ฉด ๋ถˆใ…กํŽธํ•˜๊นŒ???", color=0x738adb) embed.set_footer(text="2019_06_29") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต12": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_12", description="6์›”์˜ ๋งˆ์ง€๋ง‰ ๋‚ ์ž…๋‹ˆ๋‹ค!\n์˜ฌํ•ด ํ•˜๋ฐ˜๊ธฐ์˜ ๋ชฉํ‘œ๋Š” ๋ฌด์—‡์ธ๊ฐ€์š”?", color=0x738adb) embed.set_footer(text="2019_06_30") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต13": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_13", description="๊ธฐ๋ง๊ณ ์‚ฌ์— ๋Œ€ํ•œ ์‘์›์˜ ๋ฉ”์‹œ์ง€๋ฅผ ๋‚จ๊ฒจ๋ณด์•„์š”!\n~~๋ฌผ๋ก  ๋‚œ ์‹œํ—˜ ์•ˆ๋ณด๋‹ˆ๊นŒ ํƒˆ์ฃผ~~", color=0x738adb) embed.set_footer(text="2019_07_01") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต14": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_14", description="[๋“ค์–ด์˜ค๋ฉด ํ›„ํšŒํ•จ] ์„œ๋ฒ„์— ๊ฑด์˜๋ฅผ ํ•ด๋ณธ๋‹ค๋ฉด?", color=0x738adb) embed.set_footer(text="2019_07_02") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต15": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_15", description="<#548571647947309076>์— ์žˆ๋Š” ์ง์—… ์ค‘ ์ž์‹ ์ด ๊ฐ€์žฅ ์ข‹์•„ํ•˜๋Š” ์ง์—…์€ ๋ฌด์—‡์ธ๊ฐ€์š”?", color=0x738adb) embed.set_footer(text="2019_07_03") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต16": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_16", description="๋‹ค์Œ ์†Œํ†ตํ•ด์š” ์ฃผ์ œ๋ฅผ ์˜ˆ์ธกํ•ด๋ด…์‹œ๋‹ค!\n||~~์ ˆ๋Œ€ ํ• ๋งŒํ•œ ์ฃผ์ œ ์•„์ด๋””์–ด๊ฐ€ ์•ˆ๋– ์˜ค๋ฅด๋Š”๊ฒŒ ์•„๋‹ˆ๋ผ๊ตฌ์š”!!~~||", color=0x738adb) embed.set_footer(text="2019_07_04") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต17": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_17", description="์ž์‹ ์˜ ์ธ์ƒ์—์„œ ์ ˆ๋Œ€ ์žŠ์ง€ ๋ชปํ•  ์ˆœ๊ฐ„์€?", color=0x738adb) embed.set_footer(text="2019_07_05") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต19": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_19", description="์ฒซ๋ฒˆ์งธ๋กœ ๋ณ€๊ฒฝ ๋œ ๋ฐธ๋Ÿฐ์Šค ํŒจ์น˜์— ๋Œ€ํ•œ ์ƒ๊ฐ์„ ์ ์–ด์ฃผ์„ธ์š”!\n์˜๊ฒฌ์€ ๋‚˜์ค‘์— ์ฐธ๊ณ ํ•˜๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.", color=0x738adb) embed.set_footer(text="2019_07_07") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต20": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_20", description="๋งํ•  ์›”์š”์ผ ์ปด ๋ฐฑ Again.\n์›”์š”์ผ์— ๋Œ€ํ•œ ์ €์ฃผ๋ฅผ ํ•œ๋‹ค๋ฉด?", color=0x738adb) embed.set_footer(text="2019_07_08") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต21": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_21", description="์ด ์„œ๋ฒ„์—์„œ ์ œ์ผ ๋ฏธX๋†ˆ์€ ๋ˆ„๊ตฌ์ธ๊ฐ€์š”?", color=0x738adb) embed.set_footer(text="2019_07_09") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต22": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_22", description="์ƒŒ์ฆˆ๊ฐ€ ppap ์ถ”๋ฉด์„œ ์•ก์ฒด๊ดด๋ฌผ์„ 1000๋„์นผ๋กœ ์ž๋ฅด๋Š”๊ฒŒ ๊ฐœ๊ฟ€์žผ ๋ชฐ์นด์˜€๋‹ค๋Š”๊ฒŒ ํ•™๊ณ„์˜ ์ •์„ค์ด๋ผ๋Š” ์–˜๊ธฐ๋ฅผ ๋“ฃ๋‹ค๋‹ˆ ์ƒ์ƒ๋„ ๋ชปํ•œ ์ •์ฒด์ž…๋‹ˆ๊นŒ human?\n||~~๋Œ€์ฒด ๋ญ” ๊ฐœ์†Œ๋ฆฌ์ธ์ง€ ๋‚˜๋„ ๋ชจ๋ฅด๊ฒŒ๋”ฐ~~||", color=0x738adb) embed.set_footer(text="2019_07_10") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต23": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_23", description="๋งŒ์•ฝ ๋‚ด๊ฐ€ [๋“ค์–ด์˜ค๋ฉด ํ›„ํšŒํ•จ] ์„œ๋ฒ„๋ฅผ ๋œฏ์–ด๊ณ ์นœ๋‹ค๋ฉด ๊ฐ€์žฅ ๋จผ์ € ํ•  ๊ฒƒ ๊ฐ™์€ ์ผ์€?", color=0x738adb) embed.set_footer(text="2019_07_11") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต24": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_24", description="[๋“ค์–ด์˜ค๋ฉด ํ›„ํšŒํ•จ] ์„œ๋ฒ„์—์„œ ์ถ”๊ฐ€ํ•˜๊ณ  ์‹ถ๊ฑฐ๋‚˜ ํ‡ด์ถœํ•˜๊ณ  ์‹ถ์€ ๋ด‡์€?\n(์˜๊ฒฌ ๋งŽ์œผ๋ฉด ๋ฐ˜์˜ํ• ๊ฒŒ์š”!)", color=0x738adb) embed.set_footer(text="2019_07_12") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต25": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_25", description="<@311791989681291264>์™€(๊ณผ) <@150577293981515776>(์ด)๊ฐ€ ์‹ธ์šฐ๋ฉด ๋ˆ„๊ฐ€ ์ด๊ธธ๊ฑฐ๊ฐ€ํ‹ˆ?\n||~~๋‚˜~~||", color=0x738adb) embed.set_footer(text="2019_07_13") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต26": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_26", description="๋ˆ„๊ตฐ๊ฐ€ ๋‚˜์—๊ฒŒ ํŒจ๋“œ๋ฆฝ์ด๋ผ๋Š” ์Šคํ‚ฌ์„ ์„ ์‚ฌํ–ˆ์„ ๋•Œ ๋‹น์‹ ์ด ํ•  ๋ฐ˜์‘์œผ๋กœ ๊ฐ€์žฅ ์ ์ ˆํ•œ ๊ฒƒ์€ ๋ฌด์—‡์ผ๊นŒ์š”?", color=0x738adb) embed.set_footer(text="2019_07_14") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต27": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_27", description="๋ฒŒ์จ 7์›”์ด ๋ฐ˜์ด๋‚˜ ์ง€๋‚˜๊ฐ”์–ด์š”!\nwa! ๊ณง ๋ฐฉํ•™์ด๋Œœ์•„ใ…ใ…!!", color=0x738adb) embed.set_footer(text="2019_07_15") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต28": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_28", description="๊ฐ€์žฅ ์ข‹์•„ํ•˜๋Š” ์Œ์•…์„ ๋งํ•ด์ฃผ์„ธ์š”!\n~~์‹ฌ์‹ฌํ• ๋•Œ ๋“ค์–ด๋ด„~~", color=0x738adb) embed.set_footer(text="2019_07_16") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต29": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_29", description="์‹œ๊ณต์˜ ํญํ’์€ ์ •๋ง ์ตœ๊ณ ์ผ๊นŒ์š”? ์•„๋‹ˆ๋ผ๋ฉด ๊ทธ ์ด์œ ๋Š” ๋ฌด์—‡์ผ๊นŒ์š”?\n||~~์‚๋น…- ์ด๋ฏธ ์ฃฝ์€ ๊ฒŒ์ž„์ž…๋‹ˆ๋‹ค.~~||", color=0x738adb) embed.set_footer(text="2019_07_17") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต30": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_30", description="๋ณธ์ธ์ด ์ข‹์•„ํ•˜๋Š” ๊ฒŒ์ž„์€?\n~~๋‹น์—ฐํžˆ ๋Š‘์ธ ์•„๋‹™๋‹ˆ๊นŒ์•„ใ…~~", color=0x738adb) embed.set_footer(text="2019_07_18") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต32": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_32", description="์˜ค๋Š˜ ๋Š‘์ธ๊ฒŒ์ž„์„ ํ•˜๊ธฐ ๊ฐ€์žฅ ์ข‹์€ ํƒ€์ด๋ฐ(์‹œ๊ฐ„๋Œ€)๋Š”?", color=0x738adb) embed.set_footer(text="2019_07_20") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต33": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_33", description="์ง€๊ธˆ ์—ฌ๋Ÿฌ๋ถ„์ด ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋Š” ํ‚ค๋ณด๋“œ๋Š” ๋ฌด์—‡์ธ๊ฐ€์š”?", color=0x738adb) embed.set_footer(text="2019_07_21") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต34": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_34", description="๋Š‘๋Œ€์ธ๊ฐ„ vs ์—ฐ์‡„์‚ด์ธ๋งˆ\n๋‹น์‹ ์˜ ์„ ํƒ์€?", color=0x738adb) embed.set_footer(text="2019_07_22") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต35": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_35", description="๊ฑด์˜ ์ฑ„๋„์„ ์ƒˆ๋กœ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ์— ๋Œ€ํ•ด์„œ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?", color=0x738adb) embed.set_footer(text="2019_07_23") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต36": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_36", description="๋‹น์‹ ์ด ์ƒ๊ฐํ•˜๋Š” ๊ฐ€์žฅ ๋˜ฅ๋ง๊ฒœ์„ ๊ณ ๋ฅด์ž๋ฉด?", color=0x738adb) embed.set_footer(text="2019_07_24") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต37": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_37", description="๋ชจ๋“ ๊ฒƒ์ด ๊ท€์ฐฎ์•„์„œ ์•„๋ฌด๊ฒƒ๋„ ํ•˜๊ธฐ ์‹ซ์„ ๋•Œ ๋‹น์‹ ์˜ ๋Œ€์ฒ˜๋ฒ•์€?", color=0x738adb) embed.set_footer(text="2019_07_25") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต38": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_38", description="๋ณธ์ธ์ด ๊ฐ€์žฅ ๋งŽ์ด ํ•˜๋Š” ํ—›์†Œ๋ฆฌ๋Š” ๋ฌด์—‡์ธ๊ฐ€์š”?", color=0x738adb) embed.set_footer(text="2019_07_26") await me.send_message(message.channel, embed=embed) if message.content == "/์†Œํ†ต39": embed = discord.Embed(title="#์†Œํ†ตํ•ด์š”_39", description="<@311791989681291264>๋Š” ์ง€๊ธˆ ๋ฌด์—‡์„ ํ•˜๊ณ  ์žˆ์„ ์ง€ ์˜ˆ์ธกํ•ด๋ด…์‹œ๋‹ค!", color=0x738adb) embed.set_footer(text="2019_07_27") await me.send_message(message.channel, embed=embed) if not message.content.startswith('/e '): return actualDict = {} name = message.clean_content[3:] print(message.clean_content) actualObj = makeEmbed(name=name, icon=me.user.avatar_url, values=actualDict) await me.edit_message(message, ' ', embed=actualObj) token = os.environ["USER_TOKEN"] me.run(token, bot=False)
Python
UTF-8
1,515
3.9375
4
[]
no_license
from collections import deque def hanoi(piles): deplacements = [] # (Notation sous pseudocode avec indices ร  partir de 1) # # Prรฉ-condition: - les trois piles sont valides (c.-ร -d. ordonnรฉes) # - |piles[src]| โ‰ฅ k # - piles[src][1:k] est empilable par-dessus piles[dst] # et par-dessus piles[tmp] # # Post-condition: - piles[dst]' = piles[src][1:k] + piles[dst] # - piles[src]' = piles[src][k+1:] # - piles[tmp]' = piles[tmp] def rec(k, src, dst, tmp): if k > 0: # Dรฉplacer k - 1 disques de piles[src] vers piles[tmp] rec(k - 1, src, tmp, dst) # Dรฉplacer un disque de piles[src] vers piles[dst] piles[dst].appendleft(piles[src].popleft()) deplacements.append((src, dst)) # Dรฉplacer k - 1 disques de piles[tmp] vers piles[dst] rec(k - 1, tmp, dst, src) # Dรฉplacer piles[0] vers piles[1] n = len(piles[0]) rec(n, 0, 1, 2) return deplacements # Exemple if __name__ == "__main__": n = 3 piles = (deque(range(1, n + 1)), deque(), deque()) print("Piles avant:", piles) deplacements = hanoi(piles) print("Piles aprรจs:", piles) print("Obtenu avec ces dรฉplacements:") print() for (x, y) in deplacements: print(" Pile {} โ†’ Pile {}".format(x + 1, y + 1)) print()
Python
UTF-8
3,222
3.265625
3
[]
no_license
import sys import numpy as np import seaborn as sns import scipy.io as scyio from functions import find_closest_centroid from functions import compute_centroids from functions import run_kmean_algo from scipy.misc import imread from numpy import double from functions import kmeans_init_centroids import matplotlib.pyplot as plt import matplotlib as mpl #Loading the sample data. data = scyio.loadmat('ex7data2.mat') #Here we are applying K-Means algorithm. K = 3 # We have to initialize centroids. initial_centroids = np.matrix([[3,3],[6,2],[8,5]]) #Initializing Data X to make clusters X = np.matrix(data['X']) print("Printing Closest Centroids....\n\n\n") #Finding the nearest centroids. idx = find_closest_centroid(X,initial_centroids) print('Closest centroids for the first 3 examples: \n') print(idx[0:3]); # Now, we will calculate means. print('\nComputing centroids means.\n\n') # Compute means based on closest centroids found in the previous part. centroids = compute_centroids(X,idx,K) print('Centroids computed after initial finding of closest centroids: \n') print(centroids) #Now, we will apply K-means clustering algorithm. # We will use same dataset for clustering. max_iters = 10 #Runs K-means algorithm # The 'true' at the end tells our function to plot the progress of K-Means. centroids,idx = run_kmean_algo(X,initial_centroids,max_iters,True) print('\nK-Means Done.\n\n') # Applying K-means algorithm on Pixels. print('\nRunning K-Means clustering on pixels from an image.\n\n') #Loading my image. img = plt.imread('universe.png') # Deviding by 255 to Normalize A = img/255 # Size of image img_size = A.shape # Reshape the image into Nx3 matrix where N = number of pixels X = A.reshape(img_size[0]*img_size[1],3) #print(X.shape) # Running the K-means algorithm on this data K = 16 max_iters = 10 # When using K-means, it is important to initialize the centroids randomly initial_centroids = kmeans_init_centroids(X,K) #print(initial_centroids.shape) # Run K-Means centroids,idx = run_kmean_algo(X,initial_centroids,max_iters,False) # Now we will apply image compression. print('\nApplying K-Means to compress an image.\n\n') # Find the closest cluster members idx = find_closest_centroid(X,centroids) #print(idx.shape) #print(centroids.shape) # Now, we have represented image X as in terms of the indices in idx # We can recover the image from indices by mapping each pixel by centroid value. #X_recovered = centroids[idx,:] X_recovered = np.zeros(shape=(idx.shape[0],centroids.shape[1])) #for i in range(0,idx.shape[0]): # X_recovered[i,:] = centroids[int(idx[i,0]),:] id = [] for i in range(0,idx.shape[0]): id.append(int(idx[i,0])) idx = id X_recovered = centroids[idx,:] #print(X_recovered.shape) # Reshape the recovered image into proper dimensions. X_recovered = X_recovered.reshape(img_size) # Display the original image. fig, (ax1, ax2) = plt.subplots(1,2, figsize=(13,9)) ax1.imshow(img) ax1.set_title('Original') ax2.imshow(X_recovered*255) ax2.set_title('Compressed, with 16 colors') for ax in fig.axes: ax.axis('off') plt.show()