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 |
|---|---|---|---|---|---|---|---|
JavaScript | UTF-8 | 668 | 3.9375 | 4 | [] | no_license | // If life was easy, we could just do things the easy way:
// var getElementsByClassName = function (className) {
// return document.getElementsByClassName(className);
// };
// But instead we're going to implement it from scratch:
var getElementsByClassName = function(className
) {
// your code here
var result =[];
var searchNodes = function(nodes) {
if (nodes.classList && nodes.classList.contains(className)) {
result.push(nodes);
};
if (nodes.childNodes) {
var children = nodes.childNodes;
children.forEach(function(item) {
searchNodes(item);
});
}
};
searchNodes(document.body);
return result;
};
|
Java | UTF-8 | 16,084 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.
*/
package org.netbeans.jellytools;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.swing.text.JTextComponent;
import junit.framework.Test;
import org.netbeans.jellytools.actions.DockWindowAction;
import org.netbeans.jellytools.actions.OpenAction;
import org.netbeans.jellytools.actions.UndockWindowAction;
import org.netbeans.jellytools.nodes.Node;
import org.netbeans.jemmy.JemmyException;
import org.netbeans.jemmy.Waitable;
import org.netbeans.jemmy.Waiter;
import org.netbeans.jemmy.operators.AbstractButtonOperator;
/**
* Test of org.netbeans.jellytools.EditorOperator.
* Order of tests is important.
* @author Jiri Skrivanek
*/
public class EditorOperatorTest extends JellyTestCase {
private static EditorOperator eo;
private static final String SAMPLE_CLASS_1 = "SampleClass1";
public static final String[] tests = new String[]{
"testTxtEditorPane",
"testUndockWindow",
"testLblRowColumn",
"testLblStatusBar",
"testLblInputMode",
"testDockWindow",
"testGetText",
"testContains",
"testSelect",
"testGetLineNumber",
"testPushHomeKey",
"testPushEndKey",
"testPushDownArrowKey",
"testPushUpArrowKey",
"testFolding",
"testSetCaretPositionRelative",
"testSetCaretPositionToLine",
"testSetCaretPosition",
"testGetToolbarButton",
"testReplace",
"testInsert",
// annotations have to be tested after testInsert because of parser annotations
"testGetAnnotations",
"testGetAnnotationType",
"testGetAnnotationShortDescription",
"testDelete",
"testPushTabKey",
"testCloseDiscard",};
/** Constructor required by JUnit.
* @param testName method name to be used as testcase
*/
public EditorOperatorTest(java.lang.String testName) {
super(testName);
}
/** Method used for explicit testsuite definition
* @return created suite
*/
public static Test suite() {
return createModuleTest(EditorOperatorTest.class, tests);
}
/** Opens sample class and finds EditorOperator instance */
@Override
protected void setUp() throws IOException {
openDataProjects("SampleProject");
System.out.println("### " + getName() + " ###");
if (eo == null) {
Node sourcePackagesNode = new Node(new ProjectsTabOperator().getProjectRootNode("SampleProject"), "Source Packages");
Node sample1 = new Node(sourcePackagesNode, "sample1"); // NOI18N
Node sampleClass1 = new Node(sample1, SAMPLE_CLASS_1);
new OpenAction().perform(sampleClass1);
eo = new EditorOperator(SAMPLE_CLASS_1);
}
}
/** Test of txtEditorPane method. */
public void testTxtEditorPane() throws IOException {
String text = eo.txtEditorPane().getText();
assertTrue("Wrong editor pane found.", text.indexOf(SAMPLE_CLASS_1) != -1);
}
/**
* More than a test this is here, because the following three tests (testLblRowColumn(),
* testLblInputMode() and testLblStatusBar()) fail if the editor window is docked. When docked,
* these three labels are a part of MainWindow. *
*/
public void testUndockWindow() {
(new UndockWindowAction()).perform();
}
/** Test of lblRowColumn method. */
public void testLblRowColumn() {
assertEquals("1:1", eo.lblRowColumn().getText());
}
/** Test of lblInputMode method. */
public void testLblInputMode() {
String expected = Bundle.getString("org.netbeans.editor.Bundle", "status-bar-insert");
assertEquals(expected, eo.lblInputMode().getText());
}
/** Test of lblStatusBar method. */
public void testLblStatusBar() {
String expected = "Status bar text";
// set text to status bar
try {
String className = "org.netbeans.editor.Utilities";
Class<?> clazz = Class.forName(className);
Method setStatusTextMethod = clazz.getDeclaredMethod("setStatusText", new Class[]{
JTextComponent.class,
String.class
});
setStatusTextMethod.invoke(null, new Object[]{
(JTextComponent) eo.txtEditorPane().getSource(),
expected
});
} catch (Exception e) {
e.printStackTrace(getLog());
fail("Error in reflection operations: " + e.getMessage());
}
assertEquals("Wrong label found.", expected, eo.lblStatusBar().getText());
}
/**
* Dock after testing the previous three labels.
*/
public void testDockWindow() {
new DockWindowAction().perform(eo);
}
/** Test of getText method. */
public void testGetText() {
String text = eo.getText();
String expected = SAMPLE_CLASS_1;
assertTrue("Found \"" + text + "\" but expected \"" + expected + "\".",
text.indexOf(expected) != -1);
expected = "public static void main";
eo.setCaretPosition(expected, true);
text = eo.getText(eo.getLineNumber());
assertTrue("Found \"" + text + "\" but expected \"" + expected + "\".",
text.indexOf(expected) != -1);
}
/** Test of contains method. */
public void testContains() {
assertTrue("Editor should contain \"" + SAMPLE_CLASS_1 + "\".",
eo.contains(SAMPLE_CLASS_1));
String dummy = "Dummy string @#$%^&";
assertTrue("Editor should not contain \"" + dummy + "\".", !eo.contains(dummy));
}
/** Test of select method. */
public void testSelect() {
eo.setCaretPosition("public static void main", true);
int line = eo.getLineNumber();
eo.select(line);
String expected = eo.getText(line);
String selected = eo.txtEditorPane().getSelectedText() + "\n";
assertEquals("Wrong selection.", expected.trim(), selected.trim());
eo.select(line, line + 1);
expected = eo.getText(line) + eo.getText(line + 1);
selected = eo.txtEditorPane().getSelectedText() + "\n";
assertEquals("Wrong selection.", expected.trim(), selected.trim());
eo.select(line, 5, 10);
expected = eo.getText(line).substring(4, 10);
selected = eo.txtEditorPane().getSelectedText();
assertEquals("Wrong selection.", expected, selected);
expected = "public static void main";
eo.select(expected);
selected = eo.txtEditorPane().getSelectedText();
assertEquals("Wrong selection.", expected, selected);
eo.select("public", 2);
assertEquals("Second occurence of word \"public\" on line " + line
+ " should be selected.", line, eo.getLineNumber());
}
/** Test of getLineNumber method. */
public void testGetLineNumber() {
eo.setCaretPosition(0);
assertEquals("Wrong line number.", 1, eo.getLineNumber());
}
/** Test of pushHomeKey method. */
public void testPushHomeKey() {
eo.setCaretPosition(eo.getText(1).length() - 1);
eo.pushHomeKey();
assertEquals("Wrong position after key pushed.", 0,
eo.txtEditorPane().getCaretPosition());
}
/** Test of pushEndKey method. */
public void testPushEndKey() {
eo.setCaretPosition(0);
eo.pushEndKey();
assertEquals("Wrong position after key pushed.", eo.getText(1).length() - 1,
eo.txtEditorPane().getCaretPosition());
}
/** Test of pushDownArrowKey method. */
public void testPushDownArrowKey() {
eo.setCaretPosition(0);
eo.pushDownArrowKey();
assertEquals("Wrong line after key pushed.", 2, eo.getLineNumber());
}
/** Test of pushUpArrowKey method. */
public void testPushUpArrowKey() {
eo.setCaretPositionToLine(2);
eo.pushUpArrowKey();
assertEquals("Wrong line after key pushed.", 1, eo.getLineNumber());
}
/** Test of setCaretPositionRelative method. */
public void testSetCaretPositionRelative() {
eo.setCaretPosition(0);
int expected = 20;
eo.setCaretPositionRelative(expected);
assertEquals("Wrong caret position.", expected, eo.txtEditorPane().getCaretPosition());
}
/** Test of setCaretPositionToLine method. */
public void testSetCaretPositionToLine() {
int expected = 10;
eo.setCaretPositionToLine(10);
assertEquals("Wrong line.", expected, eo.getLineNumber());
}
/** Test of setCaretPosition method. */
public void testSetCaretPosition() {
eo.setCaretPosition(0);
assertEquals("Wrong caret position.", 0, eo.txtEditorPane().getCaretPosition());
String expected = "public static void main";
eo.setCaretPosition(expected, true);
int position = eo.txtEditorPane().getCaretPosition();
String text = eo.txtEditorPane().getText(position, expected.length());
assertEquals("Wrong caret position before text.", expected, text);
eo.setCaretPosition(position);
int newPosition = eo.txtEditorPane().getCaretPosition();
assertEquals("Wrong caret position.", position, newPosition);
eo.setCaretPosition(expected, false);
position = eo.txtEditorPane().getCaretPosition();
text = eo.txtEditorPane().getText(position - expected.length(), expected.length());
assertEquals("Wrong caret position after text.", expected, text);
eo.setCaretPosition("public", 2, true);
position = eo.txtEditorPane().getCaretPosition();
text = eo.txtEditorPane().getText(position, expected.length());
assertEquals("Wrong caret position before text.", expected, text);
eo.setCaretPosition("public", 2, false);
position = eo.txtEditorPane().getCaretPosition();
text = eo.txtEditorPane().getText(position - "public".length(), expected.length());
assertEquals("Wrong caret position after text.", expected, text);
eo.setCaretPositionToEndOfLine(eo.getLineNumber());
position = eo.txtEditorPane().getCaretPosition();
text = eo.txtEditorPane().getText(position - 1, 1);
assertEquals("Caret not at the end of line.", "{", text);
}
/** Test of getToolbarButton method. Uses "Toggle bookmark button". */
public void testGetToolbarButton() {
String tooltip = Bundle.getStringTrimmed("org.netbeans.lib.editor.bookmarks.actions.Bundle", "bookmark-toggle");
AbstractButtonOperator button1 = eo.getToolbarButton(tooltip);
button1.push();
AbstractButtonOperator button2 = eo.getToolbarButton(12);
assertEquals("Toggle Bookmark button should have index 12",
button1.getToolTipText(), button2.getToolTipText());
}
/** Test of replace method. */
public void testReplace() {
String oldText = "public static void main";
String newText = "XXXXXXXXXXXXXXXXXX";
eo.replace(oldText, newText);
assertTrue("Replace of \"" + oldText + "\" by \"" + newText + "\" failed.",
eo.contains(newText));
// replace back
eo.replace(newText, oldText);
}
/** Test of insert method. */
public void testInsert() {
eo.setCaretPosition(0);
eo.insert("111 First line\n");
eo.insert("222 Second line\n");
eo.insert("333 Third line\n");
assertEquals("Insertion failed on first line.", "111 First line\n", eo.getText(1));
eo.insert(" addendum", 3, 15);
assertEquals("Insertion failed on third line.", "333 Third line addendum\n",
eo.getText(3));
}
/** Test of getAnnotations method. Expects bookmark
* created in test testGetToolbarButton() and parser annotations on
* inserted lines (testInsert).
* @throws java.lang.InterruptedException
*/
public void testGetAnnotations() throws InterruptedException {
// wait parser annotations
new Waiter(new Waitable() {
@Override
public Object actionProduced(Object oper) {
return eo.getAnnotations().length > 1 ? Boolean.TRUE : null;
}
@Override
public String getDescription() {
return ("Wait parser annotations."); // NOI18N
}
}).waitAction(null);
}
/** Test of getAnnotationType method. */
public void testGetAnnotationType() {
Object[] an = eo.getAnnotations();
String type = EditorOperator.getAnnotationType(an[0]);
assertNotNull("getAnnotationType return null.", type);
assertTrue("getAnnotationType return empty string.", type.length() > 0);
}
/** Test of getAnnotationShortDescription method. */
public void testGetAnnotationShortDescription() {
Object[] an = eo.getAnnotations();
String desc = EditorOperator.getAnnotationShortDescription(an[0]);
assertNotNull("getAnnotationShortDescription return null.", desc);
assertTrue("getAnnotationShortDescription return empty string.", desc.length() > 0);
}
/** Test of folding methods. */
public static void testFolding() {
eo.waitFolding();
assertFalse("Initial comment at line 2 should be expanded.", eo.isCollapsed(2));
eo.setCaretPositionToLine(3);
assertFalse("Initial comment at line 3 should be expanded.", eo.isCollapsed(3));
try {
eo.setCaretPosition("package sample1;", true); // NOI18N
int line = eo.getLineNumber();
eo.isCollapsed(line);
fail("JemmyException should be thrown because no fold is at line " + line);
} catch (JemmyException e) {
// OK.
}
eo.setCaretPositionToLine(2);
eo.collapseFold();
assertTrue("Initial comment should be collapsed now.", eo.isCollapsed(2));
eo.expandFold();
eo.collapseFold(5);
eo.expandFold(5);
}
/** Test of delete method. */
public void testDelete() {
eo.delete(3, 15, 23);
assertEquals("Delete on third line failed.", "333 Third line\n", eo.getText(3));
// delete third line
eo.deleteLine(3);
assertTrue("Delete of third line failed.", !eo.contains("333 Third line"));
// delete second line
eo.delete("111 First line\n".length(), "222 Second line\n".length());
assertTrue("Delete of second line failed.", !eo.contains("222 Second line"));
// delete first line
eo.setCaretPosition(0);
eo.delete("111 First line\n".length());
assertTrue("Delete of first line failed.", !eo.contains("111 First line"));
}
/** Test of pushTabKey method. */
public void testPushTabKey() {
int length1 = eo.getText(1).length();
eo.setCaretPosition(0);
eo.pushTabKey();
int length2 = eo.getText(1).length();
assertTrue("Tab key not pushed.", length2 > length1);
}
/** Test of closeDiscard method. */
public void testCloseDiscard() {
eo.closeDiscard();
eo = null;
}
}
|
Java | UTF-8 | 17,649 | 1.929688 | 2 | [] | no_license | package org.require.core;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import javax.xml.parsers.ParserConfigurationException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.require.core.engine.RequireProjectEngine;
import org.require.core.model.RequireProject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class ShowAllDependencies {
public static void generateDependenties(String searchRoot, Document repository, final List<String> filters) throws ParserConfigurationException {
List<RequireProject> projects = RequireProjectEngine.findDotProjects(searchRoot, new NullProgressMonitor(), false);
projects = projects.stream().filter(e -> {
String path = e.getParentPath();
for (String s : filters) {
if (path.contains(s)) {
return false;
}
}
return true;
}).collect(Collectors.toList());
Map<String, RequireProject> projectNames = new HashMap<>();
for (RequireProject prj : projects) {
projectNames.put(prj.getName(), prj);
}
Map<String, List<RequireProject>> projectDeps = new HashMap<>();
List<DepInfo> allDeps = new ArrayList<>();
for (RequireProject prj : projects) {
// From source check
String fullPath = prj.getPath();
boolean skip = false;
for (String s : filters) {
if (s.startsWith("+")) {
if (!fullPath.contains(s.substring(1))) {
skip = true;
break;
}
}
}
if (skip) {
continue;
}
if (prj.getJars().size() > 0) {
for (String j : prj.getJars()) {
allDeps.addAll(processJarFile(prj, j));
}
}
for (String dep : prj.getDependencies()) {
if (projectNames.containsKey(dep)) {
continue;
}
List<RequireProject> deps = projectDeps.get(dep);
if (deps == null) {
deps = new ArrayList<RequireProject>();
projectDeps.put(dep, deps);
}
deps.add(prj);
}
}
// Print JAR deps
System.err.println("Bundled JARS");
printUsedJars(allDeps, repository);
// printClean(allDeps);
System.err.println("Eclipse platform deps");
// allDeps = calcDependencies(projectDeps, repository);
// printUsedDeps(allDeps);
// printClean(allDeps);
}
private static List<DepInfo> processJarFile(RequireProject prj, String j) {
File jarFile = new File(prj.getFullPath(), j);
List<DepInfo> deps = new ArrayList<>();
if (!jarFile.exists()) {
System.err.println("Jar file doesn't exists: " + jarFile.getAbsolutePath());
} else {
try (JarFile jarJarFile = new JarFile(jarFile)) {
Manifest manifest = jarJarFile.getManifest();
if (manifest != null) {
Attributes mainAttributes = manifest.getMainAttributes();
DepInfo dep = new DepInfo();
dep.name = new Path(jarFile.getName()).lastSegment();
dep.path = prj.getPath() + "/" + j;
dep.providerName = "unknown";
dep.prj = prj;
dep.size = jarFile.length();
processAttributes(dep, mainAttributes);
deps.add(dep);
for (Map.Entry<String, Attributes> attr : manifest.getEntries().entrySet()) {
DepInfo cdep = new DepInfo();
cdep.name = dep.name;
cdep.path = prj.getPath() + "/" + j + "#/" + attr.getKey();
cdep.providerName = null;
if (cdep.path.contains("org/eclipse") && !cdep.path.endsWith(".class")) {
cdep.providerName = "Eclipse";
}
processAttributes(cdep, attr.getValue());
if (cdep.providerName != null) {
deps.add(cdep);
// deps.remove(dep);
}
}
JarCorrector.correctJarFile(dep);
}
} catch (Exception e) {
} finally {
}
}
return deps;
}
private static void processAttributes(DepInfo dep, Attributes mainAttributes) {
dep.license = mainAttributes.getValue("Bundle-License");
// String bundleSymName = mainAttributes.getValue("Bundle-SymbolicName");
// if (bundleSymName != null) {
// dep.name = bundleSymName;
// }
String fullName = mainAttributes.getValue("Implementation-Title");
if (fullName != null) {
dep.fullName = fullName;
}
fullName = mainAttributes.getValue("Bundle-Name");
if (fullName != null) {
dep.fullName = fullName;
}
fullName = mainAttributes.getValue("Specification-Title");
if (fullName != null) {
dep.fullName = fullName;
}
String prName = mainAttributes.getValue("Implementation-Vendor");
if (prName != null) {
dep.providerName = prName;
}
prName = mainAttributes.getValue("Implementation-Vendor-Id");
if (prName != null) {
dep.providerName = prName;
}
prName = mainAttributes.getValue("Bundle-Vendor");
if (prName != null) {
dep.providerName = prName;
}
prName = mainAttributes.getValue("Specification-Vendor");
if (prName != null) {
dep.providerName = prName;
}
if (dep.fullName != null && dep.fullName.contains("Google") || dep.name.toLowerCase().contains("google")) {
dep.providerName = "Google";
}
if (dep.providerName == null && dep.license != null && dep.license.startsWith("http")) {
dep.providerName = dep.fullName;
}
dep.sourceUri = mainAttributes.getValue("Implementation-URL");
}
static class DepInfo {
String name;
String providerName;
String fullName;
String sourceUri;
String version;
long size;
List<String> bundleDeps;
RequireProject prj;
String path;
String license;
public void addDep(String dep) {
if (bundleDeps == null) {
bundleDeps = new ArrayList<>();
}
bundleDeps.add(dep);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
// if (name != null) {
// sb.append(name);
// }
if (fullName != null) {
sb.append(" fn: ").append(fullName);
}
if (path != null) {
sb.append(" path:").append(path);
}
// if (license != null) {
// sb.append(" license: " + license);
// }
if (size != 0) {
sb.append(" size: " + size);
}
return sb.toString();
}
public String toString2() {
StringBuilder sb = new StringBuilder();
if (fullName != null) {
sb.append(fullName);
}
if (license != null) {
sb.append("\n* license: " + license);
}
return sb.toString();
}
}
private static List<DepInfo> calcDependencies(Map<String, List<RequireProject>> projectDeps, Document repository) {
Map<String, DepInfo> infos = calcRepositoryInfo(repository);
Map<String, DepInfo> used = new HashMap<>();
for (String depName : projectDeps.keySet()) {
DepInfo info = infos.get(depName);
if (info != null) {
used.put(info.name, info);
fillDeps(used, info, infos);
}
}
return new ArrayList<>(used.values());
}
private static Map<String, DepInfo> calcRepositoryInfo(Document repository) {
NodeList elementsByTagName = repository.getElementsByTagName("unit");
Map<String, DepInfo> infos = new HashMap<>();
for (int i = 0; i < elementsByTagName.getLength(); i++) {
Element el = (Element) elementsByTagName.item(i);
DepInfo info = new DepInfo();
info.path = "*update-site*";
info.name = el.getAttribute("id");
info.version = el.getAttribute("version");
// Parse properties
NodeList properties = el.getElementsByTagName("property");
Map<String, String> namedProps = new HashMap<>();
for (int j = 0; j < properties.getLength(); j++) {
Element prop = (Element) properties.item(j);
String name = prop.getAttribute("name");
String value = prop.getAttribute("value");
namedProps.put(name, value);
}
String provider = namedProps.get("org.eclipse.equinox.p2.provider");
String fullName = namedProps.get("org.eclipse.equinox.p2.name");
if (provider != null && provider.startsWith("%")) {
provider = findPropertyName(namedProps, provider);
}
if (fullName != null && fullName.startsWith("%")) {
fullName = findPropertyName(namedProps, fullName);
}
info.providerName = provider;
info.fullName = fullName;
// Parse bundles deps if have ones.
NodeList required = el.getElementsByTagName("required");
for (int j = 0; j < required.getLength(); j++) {
Element prop = (Element) required.item(j);
String namespace = prop.getAttribute("namespace");
if ("osgi.bundle".equals(namespace)) {
info.addDep(prop.getAttribute("name"));
}
}
infos.put(info.name, info);
}
return infos;
}
private static void fillDeps(Map<String, DepInfo> used, DepInfo info, Map<String, DepInfo> infos) {
if (info.bundleDeps != null) {
for (String dep : info.bundleDeps) {
DepInfo depInfo = infos.get(dep);
if (depInfo != null && !used.containsKey(depInfo.name)) {
used.put(depInfo.name, depInfo);
fillDeps(used, depInfo, infos);
}
}
}
}
static String getN(String val) {
if (val == null) {
return "";
}
return val;
}
static String getN1(String val) {
if (val == null) {
return " ";
}
return val;
}
private static void printUsedDeps(List<DepInfo> used) {
Map<String, List<DepInfo>> byProvider = used.stream().collect(Collectors.groupingBy(e -> getUnifiedProvider(e.providerName, e.name)));
for (Map.Entry<String, List<DepInfo>> e : byProvider.entrySet()) {
System.out.println("Provider: " + e.getKey());
Map<String, List<DepInfo>> byName = e.getValue().stream().sorted((a, b) -> a.name.compareToIgnoreCase(b.name))
.collect(Collectors.groupingBy(eee -> getBundleName(eee.name)));
for (Map.Entry<String, List<DepInfo>> infoE : byName.entrySet()) {
StringBuilder sb = new StringBuilder();
sb.append("\t").append(infoE.getKey());
if (infoE.getValue().size() > 1) {
sb.append("\n\t\t");
sb.append(infoE.getValue().stream().map(ee -> ee.toString()).collect(Collectors.joining("\n\t\t")));
} else {
DepInfo de = infoE.getValue().get(0);
sb.append(" " + de);
}
System.out.println(sb.toString());
}
}
}
private static void printUsedJars(List<DepInfo> used, Document repository) {
Map<String, DepInfo> info = calcRepositoryInfo(repository);
long waste = 0;
long total = 0;
Map<String, List<DepInfo>> byProvider = used.stream().collect(Collectors.groupingBy(e -> getUnifiedProvider(e.providerName, e.name)));
for (Map.Entry<String, List<DepInfo>> e : byProvider.entrySet()) {
System.out.println("Provider: " + e.getKey());
Map<String, List<DepInfo>> byName = e.getValue().stream().sorted((a, b) -> a.name.compareToIgnoreCase(b.name))
.collect(Collectors.groupingBy(eee -> getBundleName(eee.name)));
for (Map.Entry<String, List<DepInfo>> infoE : byName.entrySet()) {
StringBuilder sb = new StringBuilder();
String bName = getBundleName2(infoE.getKey());
DepInfo di = info.get(bName);
sb.append("\t").append(infoE.getKey());
if( di != null) {
sb.append("***ORBIT MODULE EXISTS***");
}
if (infoE.getValue().size() > 1) {
sb.append("\n\t\t");
sb.append(infoE.getValue().stream().map(ee -> ee.toString()).collect(Collectors.joining("\n\t\t")));
total += infoE.getValue().stream().mapToLong(e33 -> e33.size).sum();
waste += infoE.getValue().stream().skip(1).mapToLong(e33 -> e33.size).sum();
} else {
DepInfo de = infoE.getValue().get(0);
sb.append(" " + de);
total += de.size;
}
System.out.println(sb.toString());
}
}
System.err.println("Wasted space:" + waste + " total:" + total );
}
private static void printClean(List<DepInfo> used) {
Map<String, List<DepInfo>> byProvider = used.stream().collect(Collectors.groupingBy(e -> getUnifiedProvider(e.providerName, e.name)));
List<DepInfo> unknown = null;
for (Map.Entry<String, List<DepInfo>> e : byProvider.entrySet()) {
if (e.getKey().equals("unknown")) {
unknown = e.getValue();
break;
}
System.out.print("|" + e.getKey() + "|");
Map<String, List<DepInfo>> names = e.getValue().stream().collect(Collectors.groupingBy(ee -> ee.name));
System.out.print("* " + names.keySet().stream().sorted().collect(Collectors.joining("\n* ")) + "|");
// System.out.print("* " +e.getValue().stream().map(e1 -> getN(e1.fullName)).collect(Collectors.joining("\n* ")) + "|");
System.out.print("* " + e.getValue().stream().map(e1 -> e1.license).filter(l -> l != null).limit(1).collect(Collectors.joining("\n* ")));
System.out.println("|");
}
System.err.println("Unidentified jars");
if (unknown != null) {
for (DepInfo di : unknown) {
System.out.println("|" + di.name + "|" + getN1(di.fullName) + "|" + getN1(di.license) + "|");
}
}
}
private static String getBundleName(String name) {
int pos = name.lastIndexOf("-");
if (pos != -1 && (pos + 1 < name.length()) && Character.isDigit(name.charAt(pos + 1))) {
// Versioned jar name
return name.substring(0, pos) + ".jar";
}
return name;
}
private static String getBundleName2(String name) {
int pos = name.lastIndexOf("-");
if (pos != -1 && (pos + 1 < name.length()) && Character.isDigit(name.charAt(pos + 1))) {
// Versioned jar name
return name.substring(0, pos);
}
return name;
}
private static String getUnifiedProvider(String provider, String name) {
if (provider.toLowerCase().contains("sun microsystems".toLowerCase()) || provider.contains("com.sun")) {
return "Sun Microsystems, Inc., Oracle Corp";
}
if (provider.contains("Eclipse")) {
return "Eclipse.org";
}
if (provider.toLowerCase().contains("apache")) {
return "Apache Software Foundation";
}
if (provider.contains("FasterXML")) {
return "http://fasterxml.com";
}
if (provider.contains("Google")) {
return "Google";
}
return provider.trim();
}
private static String findPropertyName(Map<String, String> namedProps, String provider) {
String varName = provider.substring(1);
String value = namedProps.get(varName);
if (value != null) {
return value;
}
value = namedProps.get("df_LT." + varName);
if (value != null) {
return value;
}
return provider;
}
}
|
JavaScript | UTF-8 | 2,984 | 2.5625 | 3 | [] | no_license | const User = require("../model/user");
module.exports = {
async store(req, res) {
const { email, password, name, lastname, latitude, longitude } = req.body;
try {
const user = await User.findOne({ email });
if (user) {
return res.json({
error: true,
message: "Usuário já cadastrado"
});
}
const lat = latitude ? latitude : 0;
const lon = longitude ? longitude : 0;
const location = {
type: "Point",
coordinates: [lon, lat]
};
const newUser = await User.create({
email,
password,
name,
lastname,
location
});
return res.status(201).json(newUser);
} catch (error) {
return res.status(500).json(error);
}
},
async index(req, res) {
try {
const { email } = req.query;
const user = await User.findOne({ email }).select("-password");
return res.status(200).json({
user
});
} catch (error) {
return res.status(500).json(error);
}
},
async searchUserByLocation(req, res) {
try {
const { latitude, longitude } = req.body;
const users = await User.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [longitude, latitude]
},
$maxDistance: 1000000
}
},
symptom: true
}).select("-password");
return res.json({ users });
} catch (error) {
return res.status(500).json(error);
}
},
async delete(req, res) {
try {
const { email } = req.body;
const user = await User.findOneAndRemove({ email });
if (!user) {
return res.json({
error: true,
message: "Usuário não encontrado"
});
}
return res.status(200).json({
user,
deleted: true
});
} catch (error) {
return res.status(500).json(error);
}
},
async editAddress(req, res) {
try {
const {
postalCode,
email,
logradouro,
complemento,
bairro,
localidade,
uf,
number
} = req.body;
const address = {
postalCode,
logradouro,
complemento,
bairro,
localidade,
uf,
number
};
User.findOneAndUpdate({ email }, { address }).then(async () => {
const newUser = await User.findOne({ email });
return res.status(201).json(newUser);
});
} catch (error) {
return res.status(500).json(error);
}
},
async changeSymptom(req, res) {
try {
const { email } = req.body;
User.findOneAndUpdate({ email }, { symptom: true }).then(async () => {
const newUser = await User.findOne({ email });
return res.status(201).json(newUser);
});
} catch (error) {
return res.status(500).json(error);
}
}
};
|
Python | UTF-8 | 285 | 2.59375 | 3 | [] | no_license | """Refresh the Database to make sure it's accepting connections again."""
import arcpy
# connect to the database as the dba admin
arcpy.env.overwriteOutput = True
arcpy.AcceptConnections(r'<path_to_connection_file>\<file_name>.sde', True)
print("\tDatabase accepting Connections.")
|
Markdown | UTF-8 | 4,343 | 2.984375 | 3 | [] | no_license | ---
description: "Easiest Way to Prepare Favorite Poached Eggs 🍞🍳"
title: "Easiest Way to Prepare Favorite Poached Eggs 🍞🍳"
slug: 33-easiest-way-to-prepare-favorite-poached-eggs
date: 2021-05-21T11:01:18.746Z
image: https://img-global.cpcdn.com/recipes/5505025128792064/680x482cq70/poached-eggs-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/5505025128792064/680x482cq70/poached-eggs-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/5505025128792064/680x482cq70/poached-eggs-recipe-main-photo.jpg
author: Marvin Morrison
ratingvalue: 4
reviewcount: 21934
recipeingredient:
- "2 Eggs"
- "1 Water"
- "1 tsp Vinegar"
recipeinstructions:
- "Fill pan with 2-3 inches of water."
- "Bring the water to a slight boil and add vinegar."
- "Crack eggs into a small custard dish or ramekin."
- "Dump eggs in very close to the water very gently so it does not break."
- "I was panicky about this but it all works out in the end haha."
- "Use a slotted spoon to drain water and take them out when they are done. Serve with toast and bacon or sausage! Yum!"
categories:
- Recipe
tags:
- poached
- eggs
katakunci: poached eggs
nutrition: 210 calories
recipecuisine: American
preptime: "PT17M"
cooktime: "PT40M"
recipeyield: "2"
recipecategory: Dinner
---

Hey everyone, I hope you are having an amazing day today. Today, I will show you a way to prepare a special dish, poached eggs 🍞🍳. One of my favorites food recipes. For mine, I'm gonna make it a little bit tasty. This will be really delicious.
So I've literally never made poached eggs before 😳 but I wanted to give it a shot because I love breakfast so much!! Poached Eggs 🍞🍳 Hello everybody, it is Drew, welcome to my recipe site. Today, I will show you a way to make a special dish, poached eggs 🍞🍳. It is one of my favorites.
Poached Eggs 🍞🍳 is one of the most popular of current trending foods in the world. It's simple, it's quick, it tastes yummy. It is enjoyed by millions daily. Poached Eggs 🍞🍳 is something that I've loved my whole life. They are nice and they look wonderful.
To begin with this recipe, we must prepare a few ingredients. You can cook poached eggs 🍞🍳 using 3 ingredients and 6 steps. Here is how you can achieve that.
<!--inarticleads1-->
##### The ingredients needed to make Poached Eggs 🍞🍳:
1. Take 2 Eggs
1. Get 1 Water
1. Take 1 tsp Vinegar
Amy W: They have some of the best sandwiches! Tex's Festive Feast Dog 🍗🐷🍲🍞🎄. 陋 陋 陋 陋 Poached eggs with smashed avocado & tomatoes 陋 陋 陋 陋 Good morning everybody ! Keep yourself full until lunchtime with this. Go to Home:. 🥑 🍅 🍞 🍳 🥑 🍅 🍞 🍳 .
<!--inarticleads2-->
##### Instructions to make Poached Eggs 🍞🍳:
1. Fill pan with 2-3 inches of water.
1. Bring the water to a slight boil and add vinegar.
1. Crack eggs into a small custard dish or ramekin.
1. Dump eggs in very close to the water very gently so it does not break.
1. I was panicky about this but it all works out in the end haha.
1. Use a slotted spoon to drain water and take them out when they are done. Serve with toast and bacon or sausage! Yum!
Keep yourself full until lunchtime with this. Go to Home:. 🥑 🍅 🍞 🍳 🥑 🍅 🍞 🍳 . Kicking things off with Turkish Eggs for brunch! 👌🏼🤩. Free range poached eggs on whipped garlic yogurt & hot chilli butter, w/ @lovinglyartisan Sourdough for dunking. BRUNCH Yesterday's Manchester brunch at @thesmithfieldsocialnq 陋 Smashed Organic Avocado Pico De Gallo 讀 Poached Eggs Fresh Chilli, Coriander & House Pickles Sourdough Added n'duja Pre-Christmas Brunch ☕️ 🥑 🍞 #rebites---Pictured above: avocado toast with poached egg 🥚 🥑 🍞, salmon scrambled eggs 🍳 , and a cappuccino ☕️.
So that is going to wrap this up for this special food poached eggs 🍞🍳 recipe. Thanks so much for your time. I'm sure you will make this at home. There is gonna be more interesting food in home recipes coming up. Remember to bookmark this page on your browser, and share it to your loved ones, friends and colleague. Thanks again for reading. Go on get cooking!
|
Markdown | UTF-8 | 452 | 2.65625 | 3 | [] | no_license | ## August/September 2019 Puzzle
Examine the lines below.
1. Write the first letter
2. Skip 3 letters (3 is the "key")
3. Write the next letter.
4. Repeat steps 2 and 3 until you run out of letters
```
WJVIENCFLA
LQCVKPOLQQ
MIIWEWZFBZ
WAAEVNCATX
KNCMUMMYMF
```
Bring Mr. Purdy the message found at [here](2019_08_09_puzzle.txt)
that was encoded with a key of 27.
[Solution](SOLUTION.md)
## Puzzle Solvers
Devin Schwartz,
Alex Billiot,
Aaron Vera,
Anthony Ciardelli,
Egor Mikhaylov
|
Markdown | UTF-8 | 983 | 2.875 | 3 | [] | no_license | # Restoring an Automatic Backup (Recovering from Data Loss)
Sometimes your collection may become very damaged. For instance:
- You accidentally deleted a card type or hundreds of cards and didn't notice in time to undo it.
- Your collection has become corrupted.
- There was a syncing error and you accidentally overwrote a large number of reviews that you did on another device.
- ...or anything else that leaves you with lost data.
Anki automatically backs up your collection every time you close Anki or sync (AnkiMobile backs up after fixed time intervals and before syncs), and by default it stores 30 backups. For information on restoring an automatic backup, please visit the relevant page:
- Restore a [backup made by Anki 2.1 on your computer](https://docs.ankiweb.net/files.html#backups)
- Restore a [backup made by AnkiMobile](https://docs.ankimobile.net/preferences.html#backups)
- Restore a [backup made by AnkiDroid](https://ankidroid.org/docs/manual.html#backups)
|
Java | UTF-8 | 458 | 2.09375 | 2 | [] | no_license | package br.tsi.daw.bd;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class FabricaConexao {
public static Connection getConnection() {
try {
Class.forName("org.postgresql.Driver");
return DriverManager.getConnection("jdbc:postgresql://localhost/agenda", "aluno", "aluno");
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
}
|
Java | UTF-8 | 264 | 1.625 | 2 | [
"BSD-3-Clause"
] | permissive | package edu.ucdenver.ccp.nlp.pipelines.runner.serialization;
import java.util.List;
import edu.ucdenver.ccp.nlp.core.annotation.TextAnnotation;
public interface AnnotationSerializer {
public List<String> toString(TextAnnotation ta, String documentText);
}
|
JavaScript | UTF-8 | 739 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | // var chart = new SmoothieChart({interpolation:'bezier', labels: {disabled:false}}),
// canvas = document.getElementById('smoothie-chart'),
// audioChart = new TimeSeries(),
// videoChart = new TimeSeries();
//
// setInterval(function() {
// //console.log('statistiche: ' +_statistics.audio+' '+_statistics.video );
// audioChart.append(new Date().getTime(), _statistics.instant_audio);
// videoChart.append(new Date().getTime(), _statistics.instant_video);
// }, 1000);
//
// chart.addTimeSeries(audioChart, {lineWidth:2, strokeStyle:'#98BD29', fillStyle: 'rgba(152,189,41,0.30)'});
// chart.addTimeSeries(videoChart, {lineWidth:2, strokeStyle:'#37ABDA', fillStyle: 'rgba(55,171,218,0.30)'});
// chart.streamTo(canvas, 500);
|
Java | UTF-8 | 1,931 | 3.34375 | 3 | [] | no_license | import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class DocumentIterator implements Iterator<String> {
// set up several private variables and object
private int n;
private Reader r;
private int c = -1;
// constructor setup
public DocumentIterator(Reader r, int n) {
this.n = n;
this.r = r;
skipNonLetters();
}
private void skipNonLetters() {
try {
this.c = this.r.read();
while (!Character.isLetter(this.c) && this.c != -1) {
this.c = this.r.read();
}
} catch (IOException e) {
this.c = -1;
}
}
@Override
public boolean hasNext() {
return (c != -1);
}
/**
* Get the content
*/
@Override
public String next() {
// set up variables
int num = n;
String ans = "";
String tmp = "";
// check if there is more content or not
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
//get the n-word sequence
while (num > 0 && hasNext()) {
tmp = ans;
while (Character.isLetter(this.c)) {
ans = ans + (char)this.c;
this.c = this.r.read();
}
if (!tmp.equals(ans)) {
num = num - 1;
}
if (num == n - 1) {
this.r.mark(1000);
}
skipNonLetters();
}
//no more words
if (this.c == -1) {
this.r.mark(1000);
}
this.r.reset();
this.c = this.r.read();
} catch (IOException e) {
throw new NoSuchElementException();
}
return ans;
}
}
|
Java | UTF-8 | 16,303 | 1.648438 | 2 | [] | no_license | /**
*
*/
package edu.ku.cete.batch.kelpa.auto;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import edu.ku.cete.configuration.TestStatusConfiguration;
import edu.ku.cete.domain.StudentsTests;
import edu.ku.cete.domain.TestSession;
import edu.ku.cete.domain.TestType;
import edu.ku.cete.domain.common.Assessment;
import edu.ku.cete.domain.common.Category;
import edu.ku.cete.domain.common.Organization;
import edu.ku.cete.domain.content.ContentArea;
import edu.ku.cete.domain.content.GradeCourse;
import edu.ku.cete.domain.content.Test;
import edu.ku.cete.domain.content.TestCollection;
import edu.ku.cete.domain.enrollment.Enrollment;
import edu.ku.cete.domain.studentsession.StudentSessionRule;
import edu.ku.cete.domain.studentsession.TestCollectionsSessionRules;
import edu.ku.cete.model.studentsession.TestCollectionsSessionRulesDao;
import edu.ku.cete.report.domain.BatchRegistrationReason;
import edu.ku.cete.service.CategoryService;
import edu.ku.cete.service.StudentsTestsService;
import edu.ku.cete.service.TestService;
import edu.ku.cete.service.TestSessionService;
import edu.ku.cete.service.exception.DuplicateTestSessionNameException;
import edu.ku.cete.util.AARTCollectionUtil;
import edu.ku.cete.util.SourceTypeEnum;
import edu.ku.cete.util.studentsession.StudentSessionRuleConverter;
/**
* @author ktaduru_sta
*
*/
public class KELPABatchRegistrationProcessor implements ItemProcessor<Enrollment, KELPAContext> {
protected final Log logger = LogFactory.getLog(this.getClass());
@Autowired
protected TestSessionService testSessionService;
@Autowired
protected CategoryService categoryService;
@Autowired
protected TestService testService;
@Autowired
protected TestStatusConfiguration testStatusConfiguration;
@Autowired
protected StudentSessionRuleConverter studentSessionRuleConverter;
@Autowired
protected TestCollectionsSessionRulesDao testCollectionsSessionRulesDao;
@Autowired
private StudentsTestsService studentsTestsService;
@Value("${testsession.status.unused}")
private String TEST_SESSION_STATUS_UNUSED;
@Value("${testsession.status.closed}")
private String TEST_SESSION_STATUS_COMPLETE;
@Value("${testsession.status.type}")
private String TEST_SESSION_STATUS_TYPE;
@Value("${autoregistration.varianttypeid.code.eng}")
protected String AUTO_REGISTRATION_VARIANT_TYPEID_CODE_ENG;
protected GradeCourse gradeCourse;
protected TestType testType;
protected List<TestCollection> testCollections;
protected ContentArea contentArea;
protected Long batchRegistrationId;
private Category unusedSession;
private Category completedTestSession;
private StepExecution stepExecution;
protected String enrollmentMethod;
protected String assessmentProgramCode;
private Organization contractingOrganization;
private Assessment assessment;
@Override
public KELPAContext process(Enrollment enrollment) throws Exception {
logger.debug("--> process");
KELPAContext processCtx = new KELPAContext();
processCtx.setEnrollment(enrollment);
unusedSession = categoryService.selectByCategoryCodeAndType(TEST_SESSION_STATUS_UNUSED,
TEST_SESSION_STATUS_TYPE);
completedTestSession = categoryService.selectByCategoryCodeAndType(TEST_SESSION_STATUS_COMPLETE,
TEST_SESSION_STATUS_TYPE);
for (TestCollection testCollection : testCollections) {
List<Test> tests = getTests(testCollection);
if(CollectionUtils.isNotEmpty(tests)){
boolean hasCompletedTestInPreviousSchool = false;
//Check if the test session already exists or not.
List<TestSession> existingTestSessions = testSessionService.getAutoRegisteredSessions(assessment.getId(), testType.getId(),
contentArea == null ? testCollection.getContentAreaId() : contentArea.getId(),
gradeCourse == null ? testCollection.getGradeCourseId() : gradeCourse.getId(),
enrollment.getAttendanceSchool().getId(),
new Long(enrollment.getCurrentSchoolYear()), testCollection.getStage().getId(),
SourceTypeEnum.BATCHAUTO, testCollection.getOperationalTestWindowId());
if (enrollment.isPreviousEnrollmentExists()){
List<StudentsTests> completeTests = getCompletedStageTests(enrollment, testCollection);
if(completeTests == null || completeTests.isEmpty()){
hasCompletedTestInPreviousSchool = false;
}else{
hasCompletedTestInPreviousSchool = true;
/**
DE15115
Where there are no active existingtestsessions for the studentstests records with all completed testsessions that need to get transferred
are not getting the transferredtessionsid, transferredenrollmentid, previousstudentstestsid columns updated.
1. create new testsessions (or get the inactivated test sessions --> Not doing this because the testsession name is also getting changed. Do not want to change the legacy code. So creating new)
2. update new studentstests records and to-be-transferring studentstests records with the transferredtessionsid, transferredenrollmentid, previousstudentstestsid
*/
/**
* CURRENT CODE:
if(existingTestSessions != null && !existingTestSessions.isEmpty() && completeTests.get(0) != null
&& (completeTests.get(0).getTransferedTestSessionId() == null
|| completeTests.get(0).getTransferedTestSessionId() == 0
|| existingTestSessions.get(0).getId() != completeTests.get(0).getTransferedTestSessionId())){
studentsTestsService.updateTransferedTestSessionId(completeTests.get(0).getId(),existingTestSessions.get(0).getId(), enrollment.getId());
}
*/
Long enrollmentId = enrollment.getId();
if(completeTests.get(0) != null){
if(existingTestSessions != null && !existingTestSessions.isEmpty()){
if(
(completeTests.get(0).getTransferedTestSessionId() == null || completeTests.get(0).getTransferedTestSessionId() == 0
|| (existingTestSessions.get(0).getId() != completeTests.get(0).getTransferedTestSessionId()
&& !existingTestSessions.get(0).getId().equals(completeTests.get(0).getTransferedTestSessionId()))
) &&
(enrollmentId!= completeTests.get(0).getEnrollmentId() && !enrollmentId.equals(completeTests.get(0).getEnrollmentId()))
){
if(existingTestSessions.get(0).getId()!=completeTests.get(0).getTestSessionId() && !existingTestSessions.get(0).getId().equals(completeTests.get(0).getTestSessionId())){
studentsTestsService.updateTransferedTestSessionId(completeTests.get(0).getId(),existingTestSessions.get(0).getId(), enrollment.getId());
}
else
studentsTestsService.updateTransferedTestSessionId(completeTests.get(0).getId(),null, enrollment.getId());
}
}
else{
//For the schools which do not have active testsessions, creating new ones to update the studentstests
//These new testsessions will be in unused state
TestSession testSession = null;
logger.debug("Adding enrollment - " + enrollment.getId() + " with completed tests to new Test Session");
testSession = createNewTestSession(testCollection, enrollment, unusedSession.getId(), tests, completedTestSession.getId(), null);
if (testSession != null && testSession.getId() != null) {
logger.debug("Added enrollment - " + enrollment.getId() + " to new Test Session with id - "
+ testSession.getId());
processCtx.getTestSessions().add(testSession);
//If not update existing records for transferredtessionsid, transferredenrollmentid, previousstudentstestsid
logger.debug("**********************st.id: "+completeTests.get(0).getId()+" ***** transTSID: "+testSession.getId()+" ***** transEID: "+enrollment.getId());
if(completeTests.get(0).getEnrollmentId()!=null && enrollment.getId() != completeTests.get(0).getEnrollmentId()){
studentsTestsService.updateTransferedTestSessionId(completeTests.get(0).getId(),testSession.getId(), enrollment.getId());
studentsTestsService.inactivateStudentsTestsTestBytestSessionId(testSession.getId());
}
}
//If studentstests records not available for the new enrollment, create new sessions
//Get the studentstests records from the previous enrollment -->Already available in completedTests object: previousStudentsTestId = completeTests.get(0).getId()
}
}
/** DE15115 End of Code change **/
}
}
if (!hasCompletedTestInPreviousSchool) {
TestSession testSession = null;
if(CollectionUtils.isNotEmpty(existingTestSessions)) {
testSession = existingTestSessions.get(0);
logger.debug("Found session "+testSession.getId());
studentsTestsService.addStudentExistingSession(enrollment, testSession, testCollection, tests, null);
processCtx.getTestSessions().add(testSession);
}else{
logger.debug("Adding enrollment - " + enrollment.getId() + " to new Test Session");
testSession = createNewTestSession(testCollection, enrollment, unusedSession.getId(), tests, null, null);
if (testSession != null && testSession.getId() != null) {
logger.debug("Added enrollment - " + enrollment.getId() + " to new Test Session with id - "
+ testSession.getId());
processCtx.getTestSessions().add(testSession);
}
}
}
}else{
String logMsg = String.format(
"No tests found with this criteria - grade: %s(%d), testtype: %s(%d), contentarea: %s(%d), testcollection: %d.",
gradeCourse.getAbbreviatedName(), gradeCourse.getId(), testType.getTestTypeCode(),
testType.getId(), contentArea.getAbbreviatedName(), contentArea.getId(),
testCollection.getId());
logger.debug(logMsg);
writeReason(enrollment.getStudentId(), logMsg);
}
}
return processCtx;
}
private TestSession createNewTestSession(TestCollection testCollection, Enrollment enrollment, Long testSessionStatus, List<Test> tests, Long studentsTestsStatusId, Long previousstudentstestid) throws DuplicateTestSessionNameException{
TestSession testSession = null;
String testSessioName = prepareTestSessionName(testCollection, enrollment);
logger.debug("Looking for test session:"+testSessioName);
Long otwId = testCollection.getOperationalTestWindowId();
List<TestCollectionsSessionRules> sessionsRulesList = testCollectionsSessionRulesDao.selectByOperationalTestWindowId(otwId);
StudentSessionRule studentSessionRule = studentSessionRuleConverter.convertToStudentSessionRule(sessionsRulesList);
// If the test session does not exists, create a new test session.
testSession = new TestSession();
testSession.setSource(SourceTypeEnum.BATCHAUTO.getCode());
testSession.setName(testSessioName);
testSession.setStatus(testSessionStatus);
testSession.setActiveFlag(true);
testSession.setAttendanceSchoolId(enrollment.getAttendanceSchoolId());
testSession.setTestTypeId(testType.getId());
testSession.setGradeCourseId(gradeCourse.getId());
testSession.setSchoolYear(contractingOrganization.getCurrentSchoolYear());
if (testCollection.getStage() != null) {
testSession.setStageId(testCollection.getStage().getId());
}
testSession.setTestCollectionId(testCollection.getTestCollectionId());
testSession.setOperationalTestWindowId(otwId);
testSession.setSubjectAreaId(enrollment.getSubjectAreaId());
testSession = studentsTestsService.addNewTestSession(enrollment, testSession, testCollection,
AARTCollectionUtil.getIds(tests), studentSessionRule, studentsTestsStatusId, previousstudentstestid);
return testSession;
}
private String prepareTestSessionName(TestCollection testCollection, Enrollment enrollment) {
return String.format("%d_%s_%s_%s_%s", contractingOrganization.getCurrentSchoolYear(),
enrollment.getAttendanceSchool().getDisplayIdentifier(), gradeCourse.getName(), contentArea.getName(),
testCollection.getStage().getName());
}
private List<Test> getTests(TestCollection testCollection) {
logger.debug("--> getTests" );
List<Test> tests = null;
tests = testService.findQCTestsByTestCollectionAndStatusAndAccFlags(testCollection.getId(),
testStatusConfiguration.getPublishedTestStatusCategory().getId(),
AUTO_REGISTRATION_VARIANT_TYPEID_CODE_ENG, null, null);
logger.debug("<-- getTests" );
return tests;
}
private List<StudentsTests> getCompletedStageTests(Enrollment enrollment, TestCollection testCollection){
Long caId = contentArea == null ? testCollection.getContentArea().getId() : contentArea.getId();
Long gcId = gradeCourse == null ? testCollection.getGradeCourse().getId() : gradeCourse.getId();
List<StudentsTests> completedTests = studentsTestsService.getCompletedStudentsTestsForKELPAStudent(assessment.getId(), testType.getId(), caId,
gcId, enrollment.getStudentId(), new Long(enrollment.getCurrentSchoolYear()), testCollection.getStage().getId(),
SourceTypeEnum.BATCHAUTO, testCollection.getOperationalTestWindowId());
return completedTests;
// if(completedTests != null && !completedTests.isEmpty()){
// return true;
// }else{
// return false;
// }
}
@SuppressWarnings("unchecked")
private void writeReason(Long studentId, String msg) {
logger.debug(msg);
BatchRegistrationReason brReason = new BatchRegistrationReason();
brReason.setBatchRegistrationId(batchRegistrationId);
brReason.setStudentId(studentId);
brReason.setReason(msg);
((CopyOnWriteArrayList<BatchRegistrationReason>) stepExecution.getJobExecution().getExecutionContext()
.get("jobMessages")).add(brReason);
}
public GradeCourse getGradeCourse() {
return gradeCourse;
}
public void setGradeCourse(GradeCourse gradeCourse) {
this.gradeCourse = gradeCourse;
}
public TestType getTestType() {
return testType;
}
public void setTestType(TestType testType) {
this.testType = testType;
}
public List<TestCollection> getTestCollections() {
return testCollections;
}
public void setTestCollections(List<TestCollection> testCollections) {
this.testCollections = testCollections;
}
public ContentArea getContentArea() {
return contentArea;
}
public void setContentArea(ContentArea contentArea) {
this.contentArea = contentArea;
}
public Long getBatchRegistrationId() {
return batchRegistrationId;
}
public void setBatchRegistrationId(Long batchRegistrationId) {
this.batchRegistrationId = batchRegistrationId;
}
public Category getUnusedSession() {
return unusedSession;
}
public void setUnusedSession(Category unusedSession) {
this.unusedSession = unusedSession;
}
public StepExecution getStepExecution() {
return stepExecution;
}
public void setStepExecution(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
public String getEnrollmentMethod() {
return enrollmentMethod;
}
public void setEnrollmentMethod(String enrollmentMethod) {
this.enrollmentMethod = enrollmentMethod;
}
public String getAssessmentProgramCode() {
return assessmentProgramCode;
}
public void setAssessmentProgramCode(String assessmentProgramCode) {
this.assessmentProgramCode = assessmentProgramCode;
}
public Organization getContractingOrganization() {
return contractingOrganization;
}
public void setContractingOrganization(Organization contractingOrganization) {
this.contractingOrganization = contractingOrganization;
}
public Assessment getAssessment() {
return assessment;
}
public void setAssessment(Assessment assessment) {
this.assessment = assessment;
}
}
|
Markdown | UTF-8 | 472 | 2.8125 | 3 | [] | no_license | # Express-TypeScript-API-Template
An express server built with a variety of tools such as [TypeScript](https://www.typescriptlang.org/) and [Rollup](https://rollupjs.org/).
## Running Locally
Once you have cloned the repo down, you will need to run the following commands to setup the build.
- `npm i` - Install all required dependencies
- `npm run dev` - Compiles the project with [Rollup](https://rollupjs.org/) and starts the [Express](https://expressjs.com/) server.
|
PHP | UTF-8 | 904 | 2.59375 | 3 | [] | no_license | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of RequestTypeController
*
* @author Jake Valino
*/
require 'Model/RequestTypeModel.php';
class RequestTypeController {
//Insert a new request type
function InsertARequestType($name)
{
$requestTypeModel = new RequestTypeModel();
$requestTypeModel->InsertARequestType($name);
}
//Get Request Type.
function GetRequestTypes()
{
$requestTypeModel = new RequestTypeModel();
return $requestTypeModel->GetRequestTypes();
}
//Get A Request Type By Id.
function GetARequestTypeById($id)
{
$requestTypeModel = new RequestTypeModel();
return $requestTypeModel->GetARequestTypeById($id);
}
}
|
JavaScript | UTF-8 | 1,515 | 3.453125 | 3 | [] | no_license | " use strict ";
var entries = [];
function PhoneBook(){
};
function listAllNames() {
display.innerHTML = null;
for (var i = 0;i < entries.length;i++){
display.innerHTML += entries[i].name + "<br>";
}
};
function listAllNumbers() {
display.innerHTML = null;
for (var i = 0;i < entries.length;i++){
display.innerHTML += entries[i].number + "<br>";
}
};
function showAdd() {
var name = prompt("Enter full name");
var number = prompt("Enter phone number");
entries.push({name:name.toUpperCase(), number:number});
};
function showRemove() {
var remove = prompt("Enter name to remove");
var search = remove.toUpperCase();
for (var j = 0;j < entries.length;j++){
if(entries[j].name === search){
entries.splice(j,1);
break;
}
}
};
function showLookup() {
display.innerHTML = null;
var lookupName = prompt("Enter name to lookup");
for (var e = 0;e < entries.length;e++){
if(entries[e].name == lookupName){
display.innerHTML += entries[e].name + " " + entries[e].number;break;
}
}
};
function reverseLookup() {
display.innerHTML = null;
var lookup = prompt("Enter number to lookup");
for (var o = 0;o < entries.length;o++){
if(entries[o].number == lookup){
display.innerHTML += entries[o].name + " " + entries[o].number;break;
}
}
};
function check (arrel){
return arrel
}
var display = document.getElementById("display");
|
TypeScript | UTF-8 | 1,429 | 4.3125 | 4 | [] | no_license | /* -------------------------------------------------------------------------- */
/* Functions types - Void */
/* -------------------------------------------------------------------------- */
function add(n1: number, n2: number) {
return n1 + n2;
}
function printAns(num: number): void {
console.log('Result 10 + 10 = ', num);
}
printAns(add(10, 10));
/* -------------------------------------------------------------------------- */
/* Function type */
/* -------------------------------------------------------------------------- */
// This accepts any function, this may lead to runtime errors
// let combineValues: Function;
// combineValues = add;
// console.log(combineValues(8, 8));
//Making this more specific by giving types to parameters
let combineValues: (a: number, b: number) => number;
combineValues = add;
console.log(combineValues(8, 8));
/* -------------------------------------------------------------------------- */
/* Function with callbacks */
/* -------------------------------------------------------------------------- */
function addAndHandle(n1: number, n2: number, cb: (num: number) => void) {
const result = n1 + n2;
cb(result);
}
addAndHandle(10, 20, (result) => {
console.log('Result from callback: ', result);
});
|
PHP | UTF-8 | 1,907 | 2.84375 | 3 | [] | no_license | <?php
date_default_timezone_set('UTC');
header("Content-Type:text/html; charset=UTF-8");
class image{
private $info;
private $image;
/*打开一张图片压缩到内存中*/
public function __construct($src)
{
$info=getimagesize($src);
$this->info=array(
'width'=>$info[0],
'height'=>$info[1],
'type'=>image_type_to_extension($info[2],false),
'mime'=>$info['mime']
);
$fun="imagecreatefrom{$this->info['type']}";
$this->image=$fun($src);
}
/*操作图片压缩*/
public function thumb($width,$height)
{
$image_thumb=imagecreatetruecolor($width,$height);
imagecopyresampled($image_thumb,$this->image,0,0,0,0,$width,$height,$this->info['width'],$this->info['height']);
imagedestroy($this->image);
$this->image=$image_thumb;
}
/*操作图片(添加文字水印)*/
public function fontMark($content,$font_url,$size,$color,$local,$angle)
{
$col=imagecolorallocatealpha($this->image,$color[0],$color[1],$color[2],$color[3]);
imagettftext($this->image,$size,$angle,$local['x'],$local['y'],$col,$font_url,$content);
}
/*操作图片(添加图片水印)*/
public function imageMark($source,$local,$alpha)
{
$info2=getimagesize($source);
$type2=image_type_to_extension($info2[2],false);
$fun2="imagecreatefrom{$type2}";
$water=$fun2($source);
imagecopymerge($this->image,$water,$local['x'],$local['y'],0,0,$info2[0],$info2[1],$alpha);
imagedestroy($water);
}
/*浏览器中输出图片*/
public function show()
{
header("Content-type:".$this->info['mime']);
$funs="image{$this->info['type']}";
$funs($this->image);
}
/*把图片保存在硬盘里*/
public function save($newname)
{
$funs="image{$this->info['type']}";
$funs($this->image,$newname.'.'.$this->info['type']);
}
/*销毁图片*/
public function __destruct()
{
imagedestroy($this->image);
}
}
?> |
TypeScript | UTF-8 | 1,259 | 2.828125 | 3 | [
"MIT"
] | permissive | import { RANDOM_INT } from '../factories/Base.factory';
import { COLORS } from './constants';
export const getArrayLimits = (
claimedStart: number,
claimedEnd: number,
collectionLength: number,
): { start: number; end: number } => ({
start: claimedStart < 0 ? 0 : claimedStart,
end: claimedEnd > collectionLength ? collectionLength : claimedEnd,
});
export const randomColor = () => {
const i = RANDOM_INT.getOne(0, COLORS.length);
return COLORS[i];
};
export const pickSome = (collection = [], picked = [], picksCount = 0) => {
if (!collection?.length || picksCount <= 0) {
return picked;
}
const [current, rest] = pickOne(collection);
const newPicked = [...picked, current];
return picksCount > 1 ? pickSome(rest, newPicked, picksCount - 1) : newPicked;
};
const randomIndex = (max: number) => {
return RANDOM_INT.getOne(0, max);
};
const pickOne = (collection: any[]) => {
const i = randomIndex(collection.length - 1);
const rest = [...collection.slice(0, i), ...collection.slice(i + 1)];
return [collection[i], rest];
};
export const fuzzyMatch = (str: string, pattern: string) => {
pattern = pattern.split('').reduce(function (a, b) {
return a + '.*' + b;
});
return new RegExp(pattern).test(str);
};
|
C | UTF-8 | 1,271 | 2.5625 | 3 | [] | no_license | /*
** ld.c for ld in /home/duhieu_b/CPE/CPE_2015_corewar/vm/parsing
**
** Made by benjamin duhieu
** Login <duhieu_b@epitech.net>
**
** Started on Mon Mar 21 22:50:12 2016 benjamin duhieu
** Last update Sun Mar 27 00:49:29 2016 marc brout
*/
#include "vm.h"
#include "my.h"
void execute_ld_direct(t_data *data, t_pc *i)
{
unsigned int dir;
dir = RUIFM(data->ram, MM(i->reg[0] + 2));
if (dir == 0)
i->carry = 1;
else
i->carry = 0;
i->reg[(int)data->ram[MM(i->reg[0] + 6)]] = dir;
}
void execute_ld_indirect(t_data *data, t_pc *i)
{
unsigned int indir;
int value;
value = IDX(RSFM(data->ram, MM(i->reg[0] + 2)));
indir = RUIFM(data->ram, MM(i->reg[0] + value));
if (indir == 0)
i->carry = 1;
else
i->carry = 0;
i->reg[(int)data->ram[MM(i->reg[0] + 4)]] = indir;
}
int ld(t_data *data, t_pc *i)
{
unsigned first;
unsigned second;
if (can_i_run(i, 5))
return (0);
first = (data->ram[MM(i->reg[0] + 1)] >> 6) & (char)3;
second = (data->ram[MM(i->reg[0] + 1)] >> 4) & (char)3;
if ((first != 2 && first != 3) || second != 1)
return (0);
if (check_integrety_ld(first, data->ram, i->reg[0]))
return (0);
if (first == 2)
execute_ld_direct(data, i);
else
execute_ld_indirect(data, i);
move_pc_ld(first, i);
return (0);
}
|
PHP | UTF-8 | 1,117 | 2.65625 | 3 | [] | no_license | <?php
Class A201508161439761386
{
public function up(PDO $db)
{
$db->query("INSERT INTO `course_table` (`title`, `code`, `unit`, `department`, `semester`, `class`) VALUES
('Clinical Psychology', 'PSY.472', 2, 'dental_therapy', 1, 'HND II')");
$courseId = $db->lastInsertId();
$stmtFirstEverSemester = $db->query("SELECT id FROM semester ORDER BY start_date LIMIT 1");
$semesterId = $stmtFirstEverSemester->fetch()['id'];
$stmtStudents = $db->query("SELECT personalno FROM freshman_profile WHERE course = 'dental_therapy'");
$students = $stmtStudents->fetchAll();
$stmtInsert = $db->prepare("INSERT INTO student_courses (reg_no, course_id, level, created_at,
updated_at, semester_id, publish) VALUES
(:regNo, '{$courseId}', 'HND II', NOW(), NOW(), '{$semesterId}', '0')");
$regNo = '';
$stmtInsert->bindParam('regNo', $regNo);
foreach ($students as $student) {
$regNo = $student['personalno'];
$stmtInsert->execute();
}
}
public function down(PDO $db)
{
}
}
|
C++ | UTF-8 | 743 | 2.78125 | 3 | [] | no_license | // Run a A4998 Stepstick from an Arduino UNO.
int en = 8 ;
int dirPinX = 5 ;
int stepPinX = 2 ;
int endPinX = 9;
bool dirX = LOW;
int lastEndX = 1;
void setup()
{
Serial.begin(9600);
pinMode(en,OUTPUT); // Enable
pinMode(stepPinX,OUTPUT); // Step
pinMode(dirPinX,OUTPUT); // Dir
pinMode(endPinX,INPUT_PULLUP);
digitalWrite(en,LOW); // Set Enable low
digitalWrite(dirPinX,dirX);
}
void loop() {
Serial.println(digitalRead(endPinX));
if (digitalRead(endPinX)!= lastEndX){
if(digitalRead(endPinX)==0){
lastEndX = 0;
dirX = !dirX;
digitalWrite(dirPinX,dirX);
} else {
lastEndX = 1;
}
}
digitalWrite(stepPinX,HIGH);
delay(1);
digitalWrite(stepPinX,LOW);
delay(1);
}
|
C++ | UTF-8 | 1,358 | 3.28125 | 3 | [] | no_license | #include"ch07.h"
Sales_data& Sales_data::combine(const Sales_data& rhs) {
unit_sold += rhs.unit_sold;
revenue += rhs.revenue;
return *this;
}
double Sales_data::avg_price() const{
if (unit_sold)
return revenue / unit_sold;
else
return 0;
}
Sales_data add(const Sales_data& lhs, const Sales_data& rhs) {
Sales_data Sum = lhs;
Sum.combine(rhs);
return Sum;
}
std::ostream& print(std::ostream& os, const Sales_data& item) {
os << item.isbn() << " " << item.unit_sold << " " << item.revenue << " " << item.avg_price();
return os;
}
std::istream& read(std::istream& is, Sales_data& item) {
double price = 0;
is >> item.bookNo >> item.unit_sold >> price;
item.revenue = price*item.unit_sold;
return is;
}
Sales_data::Sales_data(std::istream& is) {
read(is, *this);
}
char Screen::get(pos r, pos c) const {
return contents[r*width + c];
}
Screen& Screen::move(pos r, pos c) {
pos row = r*width;
cursor = row + c;
return *this;
}
Screen& Screen::set(char c) {
contents[cursor] = c;
return *this;
}
Screen& Screen::set(pos r, pos col, char ch) {
contents[r*width + col] = ch;
return *this;
}
void Window_mgr::clear(ScreenIndex i) {
Screen& s = screens[i];
s.contents = std::string(s.height*s.width, ' ');
}
Window_mgr::ScreenIndex
Window_mgr::addScreen(const Screen& s) {
screens.push_back(s);
return screens.size() - 1;
}
|
Java | UTF-8 | 2,574 | 2.453125 | 2 | [] | no_license |
package com.crio.warmup.stock.quotes;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.SECONDS;
import com.crio.warmup.stock.dto.AlphavantageDailyResponse;
import com.crio.warmup.stock.dto.Candle;
import com.crio.warmup.stock.exception.StockQuoteServiceException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.web.client.RestTemplate;
public class AlphaVantageService implements StockQuotesService {
private final RestTemplate restTemplate;
protected AlphaVantageService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Override
public List<Candle> getStockQuote(String symbol, LocalDate startDate, LocalDate endDate)
throws JsonProcessingException , StockQuoteServiceException
{
//CHECKSTYLE:ON
String response = restTemplate.getForObject(buildUri(symbol), String.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
try {
AlphavantageDailyResponse result =
objectMapper.readValue(response, AlphavantageDailyResponse.class);
return result.getCandles().entrySet().stream()
.filter(entry -> between(entry.getKey(), startDate, endDate))
.map(entry -> {
try {
entry.getValue().setDate(entry.getKey());
} catch (Exception e) {
e.printStackTrace();
}
return entry.getValue();
})
.sorted(Comparator.comparing(Candle::getDate))
.collect(Collectors.toList());
} catch (Exception ex) {
if (ex instanceof RuntimeException) {
throw new StockQuoteServiceException("Alphavantage returned invalid response", ex);
}
throw ex;
}
}
private boolean between(LocalDate date, LocalDate startDate, LocalDate endDate) {
return startDate.atStartOfDay().minus(1, SECONDS).isBefore(date.atStartOfDay())
&& endDate.plus(1, DAYS).atStartOfDay().isAfter(date.atStartOfDay());
}
protected String buildUri(String symbol) {
String uri = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED"
+ "&symbol=$SYMBOL&apikey=$APIKEY&outputsize=full";
return uri.replace("$APIKEY", "9ILGFAZ7HNYOJ96T")
.replace("$SYMBOL", symbol);
}
}
|
C++ | UTF-8 | 2,394 | 3.25 | 3 | [] | no_license | /******************************************************************************
Mux_Analog_Input
SparkFun Multiplexer Analog Input Example
Jim Lindblom @ SparkFun Electronics
August 15, 2016
https://github.com/sparkfun/74HC4051_8-Channel_Mux_Breakout
This sketch demonstrates how to use the SparkFun Multiplexer
Breakout - 8 Channel (74HC4051) to read eight, separate
analog inputs, using just a single ADC channel.
Hardware Hookup:
Mux ------------------- Arduino
S0 ------------------- 36
S1 ------------------- 37
S2 ------------------- 38
Y1 ------------------- 39
Y2 ------------------- 40
VCC ------------------- 5V
GND ------------------- GND
The multiplexers independent I/O (Y0-Y7) can each be wired
up to a potentiometer or any other analog/digital signal-producing
component.
******************************************************************************/
// Pin Definitions
const int selectPins[3] = {43, 45, 47}; // S0~2, S1~3, S2~4
const int Y1Input = 44; // Connect output Y1 to 5
const int Y2Input = 46; // Connect output Y2 to 6
void setup()
{
Serial.begin(9600); // Initialize the serial port
// Set up the select pins as outputs:
for (int i=0; i<3; i++)
{
pinMode(selectPins[i], OUTPUT);
digitalWrite(selectPins[i], HIGH);
}
pinMode(Y1Input, INPUT); // Set up Y1 as an input
pinMode(Y2Input, INPUT); // Set up Y2 as an input
pinMode(selectPins[1], OUTPUT);
pinMode(selectPins[2], OUTPUT);
pinMode(selectPins[3], OUTPUT);
// Print the header:
Serial.println("Y1.0\tY2.0\tY1.1\tY2.1\tY1.2\tY2.2\tY1.3\tY2.3\tY1.4\tY2.4\tY1.5\tY2.5\tY1.6\tY2.6\tY1.7\tY2.7");
Serial.println("---\t---\t---\t---\t---\t---\t---\t---\t---\t---\t---\t---\t---\t---\t---\t---");
}
void loop()
{
// Loop through all eight pins
for (byte pin=0; pin<=7; pin++)
{
selectMuxPin(pin); // Select one at a time
int inputY1Value = digitalRead(44); // and read Y1
int inputY2Value = digitalRead(46); // and read Y2
Serial.print(String(inputY1Value) + "\t" + String(inputY2Value)+ "\t");
}
Serial.println();
delay(1000);
}
// The selectMuxPin function sets the S0, S1, and S2 pins
// accordingly, given a pin from 0-7.
void selectMuxPin(byte pin)
{
for (int i=0; i<3; i++)
{
if (pin & (1<<i))
digitalWrite(selectPins[i], HIGH);
else
digitalWrite(selectPins[i], LOW);
}
}
|
JavaScript | UTF-8 | 2,717 | 2.65625 | 3 | [] | no_license | 'use strict';
(function (onLoad, onError) {
var downloadedAdverts;
var URL = 'https://js.dump.academy/keksobooking/data';
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', function () {
downloadedAdverts = JSON.parse(xhr.responseText);
console.log(downloadedAdverts); // не забыть убрать
var typeOfHouse = document.getElementById('housing-type');
var houses = [];
for (var y=0; y<downloadedAdverts.length; y++) {
houses.push(downloadedAdverts[y].offer.type);
}
console.log(houses); // не забыть убрать
typeOfHouse.onchange = function() {
for (var x = 0; x<downloadedAdverts.length; x++) {
buttons[x].className = 'map__pin';
}
console.log(typeOfHouse.value); // не забыть убрать
var filteredHouses = houses.filter(function(num) {
return num === typeOfHouse.value;
});
for (var z = 0; z<downloadedAdverts.length; z++) {
if (houses[z] != typeOfHouse.value) {
buttons[z].className = 'map__pin--disabled';
}
if (typeOfHouse.value == 'any') {
buttons[z].className = 'map__pin';
}
}
console.log(filteredHouses); // не забыть убрать
}
/**
* Функция открытия карточки объявления
*/
function openCard(n){
return function (e) {
var filledAdvertCard = fillAdvert(downloadedAdverts[n]);
var mapFiltersContainer = document.querySelector('.map__filters-container');
if (!document.querySelector('.map__card')) {
document.querySelector('.map').insertBefore(filledAdvertCard, mapFiltersContainer);
}
};
}
/**
* Функция закрытия карточки объявления
*/
function closeCard(n){
return function (e) {
var setupClose = document.querySelector('.popup__close');
setupClose.onclick = function() {
var mapCard = document.querySelector('.map__card');
mapCard.parentNode.removeChild(mapCard);
};
};
}
for (var n=0; n<Object.keys(downloadedAdverts).length; n++){
buttons[n] = document.querySelector('template').content.querySelector('button.map__pin').cloneNode(true);
buttons[n].setAttribute('style', 'left: ' + (downloadedAdverts[n].location.x ) + 'px; top:' + (downloadedAdverts[n].location.y) + 'px;');
buttons[n].querySelector('img').setAttribute('src', downloadedAdverts[n].author.avatar);
}
window.backend = {
openCard: openCard,
closeCard: closeCard,
downloadedAdverts: downloadedAdverts
};
});
xhr.open('GET', URL);
xhr.send();
})();
// (function () {
// var onLoad = function (data) {
// console.log(data);
// };
// var onError = function (message) {
// console.log(message);
// }
// })(); |
SQL | UTF-8 | 277 | 2.65625 | 3 | [] | no_license | create table if not exists market.productproperties
(
id bigserial primary key,
categoryid int references market.productcategories(id) on delete restrict on update cascade,
name varchar not null,
code varchar not null,
datatype int not null,
isenum int default 0
); |
Java | UTF-8 | 3,378 | 1.515625 | 2 | [] | no_license | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package kik.android.b;
import com.kik.g.as;
import com.kik.g.p;
import com.kik.g.s;
import com.kik.n.a.c.e;
import com.kik.n.a.c.i;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import kik.a.e.v;
import kik.a.i.h;
import kik.a.j.m;
// Referenced classes of package kik.android.b:
// b, c, s, e,
// d
public final class kik.android.b.a
{
private static final class a
{
boolean a;
boolean b;
String c;
byte d[];
byte e[];
private a()
{
}
a(byte byte0)
{
this();
}
}
private final m a;
private final v b;
private final h c;
private final kik.android.b.s d;
private final as e = new b(this);
private final as f = new c(this);
public kik.android.b.a(m m1, v v1, h h)
{
a = m1;
b = v1;
c = h;
d = new kik.android.b.s(a);
}
static kik.android.b.s a(kik.android.b.a a1)
{
return a1.d;
}
protected static byte[] a(kik.a.i.h.a a1)
{
if (a1 == null || a1.b() == null)
{
return null;
}
MessageDigest messagedigest;
try
{
messagedigest = MessageDigest.getInstance("SHA-1");
}
// Misplaced declaration of an exception variable
catch (kik.a.i.h.a a1)
{
return null;
}
return messagedigest.digest(a1.b().getBytes());
}
static v b(kik.android.b.a a1)
{
return a1.b;
}
private boolean b()
{
return b.p("XDATA_CARD_HISTORY_MIGRATED").booleanValue();
}
static h c(kik.android.b.a a1)
{
return a1.c;
}
private boolean c()
{
return b.p("XDATA_CARD_PERMISSIONS_MIGRATED").booleanValue();
}
public final void a()
{
p p1;
p p2;
label0:
{
if (!b() || !c())
{
p1 = a.a("enc_card_list", com/kik/n/a/c/e);
p2 = new p();
if (b())
{
p2.a(Boolean.valueOf(true));
} else
{
s.b(p1, s.a(e)).a(new kik.android.b.e(this, a.b("enc_card_pinned", com/kik/n/a/c/i), p2));
}
p2 = new p();
if (!c())
{
break label0;
}
p2.a(Boolean.valueOf(true));
}
return;
}
s.b(p1, s.a(f)).a(new d(this, p2));
}
// Unreferenced inner class kik/android/b/a$1
/* anonymous class */
static final class _cls1
{
static final int a[];
static
{
a = new int[com.kik.n.a.c.g.a.values().length];
try
{
a[com.kik.n.a.c.g.a.a.ordinal()] = 1;
}
catch (NoSuchFieldError nosuchfielderror1) { }
try
{
a[com.kik.n.a.c.g.a.b.ordinal()] = 2;
}
catch (NoSuchFieldError nosuchfielderror)
{
return;
}
}
}
}
|
Markdown | UTF-8 | 4,944 | 3.3125 | 3 | [
"MIT"
] | permissive | dbmapper
========
`dbmapper` provides DSL for mapping database result set into specific field/variable `programmatically` and it also provide DSL to help developer create a query with named parameter. `dbmapper` was inspired by Scala's [Anorm](https://www.playframework.com/documentation/latest/ScalaAnorm) package. With mapping done on a per-column basis, adding new columns into existing table will not break existing code as long as it is not modified.
Query Usage
===========
1. Import the package
`import "github.com/ncrypthic/dbmapper"`
2. Import database dialect. Currently only `mysql` and `cassandra` are supported
```go
// import "github.com/ncrypthic/dbmapper/dialects/cassandra"
// or
import "github.com/ncrypthic/dbmapper/dialects/mysql"
```
3. Create database query with named parameter
```go
query := "SELECT col_a, col_b FROM a_table WHERE col_a = :a_parameter)
```
4. You can convert the parameterized query to native driver query using `dbmapper.Prepare` api
```go
queryString := "SELECT col_a, col_b FROM a_table WHERE col_a = :a_parameter)
query := dbmapper.Prepare(queryString).With(
mysql.Param("a_parameter", "some_value"),
)
if query.Error() != nil {
// handle parameter error
}
resultSet, err := driver.Query(query.SQL(), query.Params()...)
```
or
```go
queryString := "SELECT col_a, col_b FROM a_table WHERE col_a = :a_parameter)
query := dbmapper.Prepare(queryString).With(
cassandra.Param("a_parameter", "some_value"),
)
if query.Error() != nil {
// handle parameter error
}
resultSet, err := driver.Query(query.SQL(), query.Params()...)
```
Result Mapping Usage
====================
1. Import the package
`import "github.com/ncrypthic/dbmapper"`
2. Import database dialect. Currently only `mysql` and `cassandra` are supported
```go
import "github.com/ncrypthic/dbmapper/dialects/cassandra"
```
or
```go
import "github.com/ncrypthic/dbmapper/dialects/mysql"
```
2. Prepare variables to hold the mapped row results `result := make([]SomeStruct, 0)`
3. Create `RowMapper` interface instance, and use `MappedColumns.Then` to
collect the result
```go
func rowMapper(result []SomeStruct) dbmapper.RowMapper {
return func() *dbmapper.MappedColumns {
// Either create new object to hold row result or use existing
row := SomeStruct{}
dbmapper.Columns(
dbmapper.Column("column_name").As(&row.SomeField),
).Then(func() error {
// Append the row to a result slice
result = append(result, row)
// When error returned, it will stop the mapping process
return nil
})
}
}
```
5. Pass query result from native database driver to `<dialect_package>.Parse` method then pass instance of `RowMapper` to map the result
```go
mysql.Parse(sql.Query("SELECT col_1, col_2 FROM some_table")).Map(rowMapper(result))
```
Or
```go
cassandra.Parse(gocql.Query("SELECT col_1, col_2 FROM some_table")).Map(rowMapper(result))
```
Example
=======
```go
// ...
import (
"database/sql"
"github.com/ncrypthic/dbmapper"
"github.com/ncrypthic/dbmapper/dialects/mysql"
)
type User struct {
ID string
Name string
Active bool
PhoneNumber sql.NullString
}
// userMapper map a single row from table 'user'. This way it can be reused anywhere
func userMapper(result []User) dbmapper.RowMapper {
return func() *dbmapper.MappedColumns {
row := User{}
return dbmapper.Columns(
dbmapper.Column("id").As(&row.ID),
dbmapper.Column("name").As(&row.Name),
dbmapper.Column("active").As(&row.Active),
dbmapper.Column("phone_number").As(&row.OptField),
).Then(func() error {
result = append(result, row)
return nil
})
}
}
// usersMapper map rows of query result from table 'user' using `userMapper` function to map every row
func usersMapper(result []User) dbmapper.RowMapper {
return userMapper(result)
}
func main() {
// db := sql.Open()
sql := "SELECT id, name, active, phone_number FROM user"
users := make([]User, 0)
query := dbmapper.Prepare("SELECT id, name, active, phone_number FROM user")
if query.Error() != nil {
// handle parameter error
}
dbmapper.Parse(db.Query(query.SQL(), query.Params()...)).Map(usersMapper(result))
for _, r := range result {
// Do something with the result
}
}
```
LICENSE
-------
MIT
|
C# | UTF-8 | 2,179 | 3.40625 | 3 | [] | no_license | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace MakeASalad
{
class Program
{
static void Main(string[] args)
{
var vegetables = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.ToArray();
var saladsCalories = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
Stack<int> stackOfSaladsCalories = new Stack<int>(saladsCalories);
Queue<string> queueOfVegetables = new Queue<string>(vegetables);
List<int> finishedSaladsCalories = new List<int>();
while (stackOfSaladsCalories.Count > 0 && queueOfVegetables.Count > 0)
{
int currSalad = stackOfSaladsCalories.Peek();
while (currSalad > 0 && queueOfVegetables.Count > 0)
{
string currVegetable = queueOfVegetables.Dequeue();
if (currVegetable == "tomato")
{
currSalad -= 80;
}
else if (currVegetable == "carrot")
{
currSalad -= 136;
}
else if (currVegetable == "lettuce")
{
currSalad -= 109;
}
else if (currVegetable == "potato")
{
currSalad -= 215;
}
//currVegetable = queueOfVegetables.Dequeue();
}
finishedSaladsCalories.Add(stackOfSaladsCalories.Pop());
}
Console.WriteLine(string.Join(" ", finishedSaladsCalories));
if (stackOfSaladsCalories.Count>0)
{
Console.WriteLine(string.Join(" ", stackOfSaladsCalories));
}
if (queueOfVegetables.Count>0)
{
Console.WriteLine(string.Join(" ", queueOfVegetables));
}
}
}
}
|
C# | UTF-8 | 456 | 2.703125 | 3 | [
"MIT"
] | permissive | using System;
using System.Runtime.Serialization;
namespace TurtleChallenge.Core.Exceptions
{
[Serializable]
public class IndexOutOfBoardException : Exception
{
public IndexOutOfBoardException(string type, int x, int y) : base($"{type} is out of board: x({x}) y({y})")
{
}
protected IndexOutOfBoardException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
} |
Markdown | UTF-8 | 830 | 3.421875 | 3 | [] | no_license | ---
authors: [ "Geoffrey Hunter" ]
date: 2014-01-24
draft: false
title: Local Jumps (goto)
type: page
---
## Overview
The label operator (`:`) and `goto` statement in C allows you to perform local jumps. A local jump is a jump in code execution within the same function. This is opposed to non-local jumps, which can jump between functions (`setjmp()` and `longjmp()`). The reason jumps are split into two categories is that local jumps are "easier" for the user/compiler to handle, because the stack does not need to be saved/switched.
## C Supports URL's, Wait What?
Did you know that:
```c
http://www.google.com
```
is valid syntax in C? Wait, what? O.K., I was lying, C doesn't support URLs, but the syntax is still valid! What it actually represents is a label (`http:`), followed by a single-line comment (`//www.google.com`).
|
Java | UTF-8 | 127 | 1.867188 | 2 | [] | no_license | package p.parser;
import p.lexer.Terminal;
public interface Actor {
public void act(Terminal token, Builder builder);
}
|
Shell | UTF-8 | 957 | 3.890625 | 4 | [] | no_license | #!/bin/bash
bamboo_cmd_usage="./docker-build.sh <build_number> [<property_file>:default=build-deploy.properties]"
build_number=
if [ ! -z $1 ]; then build_number=$1; else log ERROR "No build number specified as var-args! Usage: ${bamboo_cmd_usage}" 1; fi
properties="./config/build-deploy.properties"
if [ ! -z $2 ]; then properties=$2; else log INFO 'Using default property file: ./config/build-deploy.properties ...'; fi
app_name="$(cat ${properties} | grep "app.name" | cut -d'=' -f2)"
registry=$(cat ${properties} | grep "docker.registry" | cut -d'=' -f2)
docker_build(){
docker build -t ${registry}/${app_name}:${build_number} . || return $?
}
docker_tag(){
docker tag ${registry}/${app_name}:${build_number} ${registry}/${app_name}:latest || return $?
}
docker_push(){
docker push ${registry}/${app_name}:${build_number} || return $?
docker push ${registry}/${app_name}:latest || return $?
}
docker_build && \
docker_tag && \
docker_push
|
Ruby | UTF-8 | 416 | 3.390625 | 3 | [] | no_license | #!/usr/bin/env ruby
# https://www.hackerrank.com/challenges/sock-merchant
def sockMerchant(n, ar)
socks = Hash.new
pairs_count = 0
ar.each do |item|
if socks.has_key?(item) then
pairs_count = pairs_count + 1
socks.delete(item)
else
socks[item] = item
end
end
return pairs_count
end
puts sockMerchant(9, [10,20,20,10,10,30,50,10,20])
|
Java | UTF-8 | 557 | 2.578125 | 3 | [] | no_license | @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName();
if ("equals".equals(name)) {
return (proxy == args[0]);
}
else if ("hashCode".equals(name)) {
return hashCode();
}
else if ("toString".equals(name)) {
return toString();
}
else if ("transformClass".equals(name)) {
return transform((String) args[0], (byte[]) args[1], (CodeSource) args[2], (ClassLoader) args[3]);
}
else {
throw new IllegalArgumentException("Unknown method: " + method);
}
}
|
Markdown | UTF-8 | 13,986 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | # Blueprint - Kubernetes on the Mesosphere DCOS
## Contents
1. [Terminology](#1-terminology)
1. [Use Cases](#2-use-cases)
1. Case study 1: Financial Industry
1. Case study 2: Gaming
1. [Solution](#3-solution)
1. [Components](#4-components)
1. Prerequisites
1. Bill of Materials
1. [Example Deployment](#5-example-deployment)
1. [Resources](#6-resources)
[Kubernetes on DCOS](http://mesosphere.com/kubernetes) adds Kubernetes to Mesosphere’s Datacenter Operating System (DCOS) in order to help enterprises unlock the next generation of datacenter scale, efficiency and automation. [Kubernetes](http://kubernetes.io/) and the Mesosphere [DCOS](http://mesosphere.com/learn/) together provide a powerful platform for building and deploying microservice-based applications and operate containerized (e.g., using Docker) applications in a scalable, elastic and secure manner. The Mesosphere DCOS, which is based on Apache Mesos, is integrating Kubernetes as a standard component which will be made available as part of the Mesosphere DCOS Community Edition (free) and the Mesosphere DCOS Enterprise Edition (paid).
In this document, you'll learn how to use Kubernetes on the Mesosphere DCOS in order to build scalable, resilient and secure application architectures. You'll see how these principles apply to real-world scenarios through an example deployment.
## 1. Terminology
**Docker**, [docker.com](https://www.docker.com/): is a popular container solution that enables deployable apps to be quickly assembled from components and eliminates the friction between development, QA and production environments. It consists of 1. the Docker Engine, a portable, lightweight runtime and packaging tool, and 2. Docker Hub, a cloud service for sharing applications and automating workflows. For on-premise deployments, a private registry can be used to serve the Docker images.
**Kubernetes**, [kubernetes.io](http://kubernetes.io/): is an open source orchestration system for Docker containers. It actively manages workloads to ensure that their state matches the users declared intentions. Kubernetes provides declarative primitives—such as pods, labels and services—to group the Docker containers that make up an application into logical units, for easy management and discovery.
**Mesosphere DCOS**, [mesosphere.com](http://mesosphere.com/product/): provides a highly-portable, operations-driven environment that is fault-tolerant, scalable, elastic and supports multi-service deployments. It seamlessly supports both Docker (isolation-level) and Kubernetes (service-level) in an enterprise-grade, [multi-services](http://www.slideshare.net/timothysc/apache-coneu) environment.
**Multi-service**. The ability of a platform to run multiple operational and analytical workloads on the same cluster, resulting in resource-efficiency, while providing elasticity and isolation capabilities. For example, Web servers (like nginx), App servers (such as node.js) using relational databases (e.g., MySQL) for the operational part can be used together with Hadoop/HDFS, Spark, Kafka, etc. for the analytics part, in one cluster.
## 2. Use Cases
Kubernetes on DCOS delivers the most value for those use cases that share one or more of the following characteristics:
* Production systems employing very large clusters, in the 1000s of nodes.
* Applications that run on-premise, in a private datacenter.
* The need for a multi-service setup, on the same cluster, is a given.
* A requirement to easily migrate parts or all of the distributed application from a private cloud to a public cloud setup, including Amazon Web Services, Google Compute and Microsoft Azure.
* Run apps in a highly-automated environment in order to reduce operational burden.
* Reliability and fault-tolerance for all workloads.
* Enterprise-grade security.
* Elastic scaling of resources between Kubernetes and other apps.
In the following we will have a look at two real-world case studies in greater detail.
### 2.1 Case study 1: Financial Industry
A leading, multi-national investment bank has a number of applications—from fraud detection to trading and marketing—running on the Mesosphere DCOS and decides to leverage Kubernetes on DCOS in order to better manage their workloads. The majority of the datasets reside on-premise due to various legislative requirements (Sarbanes-Oxley, Dodd-Frank, etc.). However, especially for targeted marketing and sentiment analysis use cases, said investment bank has a 500 node cluster in a public cloud, in addition to their on-premise machines. Kubernetes on DCOS in this scenario is used to enable them to build and run multiple services—stream processing of public news and social media feeds, machine learning to detect fraudulent behavior, recommendations for customers and reaching out to prospects—on both their private and public cloud machines.
### 2.2 Case study 2: Gaming
In this case study, we look at a Web 2.0 property which has its main line of business in online games deployed through Web sites and mobile applications. The two main challenges the gaming company faced was to ensure a high utilization of their on-premise cluster and being flexible concerning deployment options. Essentially, they wanted to have game engines built in Kubernetes and also run analytics (Spark, Hadoop, Storm) together on the same cluster in order to lower their TCO (Total Cost of Ownership) and increase their RoI (Return on Investment). As they rolled out the system, Kubernetes on DCOS helped them to create a reliable and flexible architecture, allowing them to triple their compute utilization.
## 3. Solution
Let us now have a look at how Kubernetes is integrated with the Mesosphere DCOS from a 50,000 ft. view:

Kubernetes on DCOS begins with a Mesosphere DCOS cluster built atop bare metal or virtual machines running any modern version of Linux. The nodes can either be on-premise or in a public cloud/IaaS setting, such as Google Compute Platform. The Mesosphere DCOS is built around Apache Mesos forms the distributed systems kernel that abstracts away all of the underlying nodes so that they combine to form what looks like one big machine.
The orchestration of apps and services can be done using Kubernetes installed on the DCOS. These Kubernetes workloads can run on the same cluster, and even co-reside on the same machines, as other DCOS workloads, such as those launched with the Marathon or Chronos services.
The DCOS UI and CLI offer a broad range of functionality for end-to-end application lifecycle management and operations including monitoring, upgrading, decommissioning and SLA-related service tasks.
From a technical point of view the [Kubernetes on DCOS](https://github.com/mesosphere/kubernetes-mesos/blob/master/docs/README.md) integration looks as follows:

Comparing the standard Kubernetes deployment with the Kubernetes on DCOS deployment gives the following:
| Aspect | Standard Kubernetes | Kubernetes on DCOS |
| ----------------------- | ------------------- | ------------------ |
| **multi-service** | Kubernetes only | Yes. Kubernetes co-exists with multiple services on the same cluster, including Spark, Cassandra, Marathon, Chronos, Hadoop, Kafka, Jenkins and many others. |
| **hybrid cloud** | via workload portability | via workload portability and multi-datacenter scheduling |
| **business continuity** | fault-tolerance | fault-tolerance, High Availability, SLAs guaranteed |
| **container** | Docker | pluggable incl. Docker and cgroups |
| **scheduler** | monolithic | pluggable two-level, multi-services resource arbitration |
| **support** | community, on a best effort basis| community and premium (SLA-based) through Mesosphere |
| **security** | basic | extended |
Note that the Mesosphere DCOS comes in two versions: a **Community Edition** (CE), which is available (today) for cloud-only deployments, and the **Enterprise Edition** (EE), which can be used in a cloud setup, on-premise or in a hybrid setup. Some of the above listed features, incl. premium support, extended security and monitoring are exclusively available through the EE.
## 4. Components
### 4.1 Prerequisites
The only prerequisite to use Kubernetes on DCOS is one of the following environments (physical and/or VM):
1. Instances in a public-cloud, IaaS infrastructure such as [Google Compute](http://cloud.google.com/), AWS [EC2](http://aws.amazon.com/ec2/), and Microsoft [Azure](https://azure.microsoft.com/).
1. An on-premise cluster of machines.
1. A combination of 1. and 2., above.
In **any case** above the physical or virtual machines **must not** be pre-installed with a local operating system—such as from the GNU/Linux or Windows family—as during the setup phase Mesosphere DCOS will install [CoreOS](https://coreos.com/). In future, other GNU/Linux flavors will be supported.
### 4.2 Bill of Materials
Core:
* Cloud provisioning (AWS, Azure, GCE)
* CoreOS
* Mesos
* Zookeeper, Exhibitor
* Mesos-DNS
* DCOS Distribution Package
* DCOS Package Repository
* DCOS CLI
* DCOS GUI
Included Services:
* Kubernetes
* Marathon
* Chronos
Installable Services:
* HDFS
* Kafka
* Jenkins
* Spark
* Cassandra
* Hadoop
* YARN (via Myriad)
* and many others
## 5. Example Deployment
In order to try out the example deployment described in the following, you first want to visit [mesosphere.com/install](http://mesosphere.com/install) and set up a cluster of machines with the Mesosphere DCOS installed.
*Note that in the example deployment below you can use the native Kubernetes CLI commands and the respective DCOS sub-commands interchangeably. This means that the following two commands are semantically equivalent:*
```bash
$ bin/kubectl get pods
```
and
```bash
$ dcos k8s get pods
```
Install Kubernetes on DCOS:
```bash
$ dcos package install kubernetes
```
Now, start the kubernetes-mesos API server, controller manager, and scheduler on a Mesos master node:
```bash
$ ./bin/km apiserver \
--address=${servicehost} \
--mesos_master=${mesos_master} \
--etcd_servers=http://${servicehost}:4001 \
--portal_net=10.10.10.0/24 \
--port=8888 \
--cloud_provider=mesos \
--v=1 >apiserver.log 2>&1 &
$ ./bin/km controller-manager \
--master=$servicehost:8888 \
--mesos_master=${mesos_master} \
--v=1 >controller.log 2>&1 &
$ ./bin/km scheduler \
--address=${servicehost} \
--mesos_master=${mesos_master} \
--etcd_servers=http://${servicehost}:4001 \
--mesos_user=root \
--api_servers=$servicehost:8888 \
--v=2 >scheduler.log 2>&1 &
```
Also on the master node, start up a proxy instance to act as a public-facing service router:
```bash
$ sudo ./bin/km proxy \
--bind_address=${servicehost} \
--etcd_servers=http://${servicehost}:4001 \
--logtostderr=true >proxy.log 2>&1 &
```
Disown your background jobs so that they'll stay running if you log out.
```bash
$ disown -a
```
Now you can interact with the Kubernetes via `kubectl`:
```bash
$ bin/kubectl get pods
POD IP CONTAINER(S) IMAGE(S) HOST LABELS STATUS
```
```bash
$ bin/kubectl get services # your service IPs will likely differ
NAME LABELS SELECTOR IP PORT
kubernetes component=apiserver,provider=kubernetes <none> 10.10.10.2 443
kubernetes-ro component=apiserver,provider=kubernetes <none> 10.10.10.1 80
```
Lastly, use the Mesos CLI tool to validate the Kubernetes scheduler framework has been registered and running:
```bash
$ mesos state | grep "Kubernetes"
"name": "Kubernetes",
```
Alternatively you can find Kubernetes in the DCOS GUI, under the services tab.
In order to spin up a pod, you write a JSON pod description to a local file:
```bash
$ cat <<EOPOD >nginx.json
{ "kind": "Pod",
"apiVersion": "v1beta1",
"id": "nginx-id-01",
"desiredState": {
"manifest": {
"version": "v1beta1",
"containers": [{
"name": "nginx-01",
"image": "nginx",
"ports": [{
"containerPort": 80,
"hostPort": 31000
}],
"livenessProbe": {
"enabled": true,
"type": "http",
"initialDelaySeconds": 30,
"httpGet": {
"path": "/index.html",
"port": "8081"
}
}
}]
}
},
"labels": {
"name": "foo"
} }
EOPOD
```
Then, send the pod description to Kubernetes using the `kubectl` CLI:
```bash
$ bin/kubectl create -f nginx.json
nginx-id-01
```
Wait a minute or two while `dockerd` downloads the image layers from the internet. You can again use the `kubectl` interface to monitor the status of your pod:
```bash
$ bin/kubectl get pods
POD IP CONTAINER(S) IMAGE(S) HOST LABELS STATUS
nginx-id-01 172.17.5.27 nginx-01 nginx 10.72.72.178/10.72.72.178 cluster=gce,name=foo Running
```
Last but not least you may want to verify that the pod task is running, through the DCOS UI.
## 6. Resources
* Kubernetes blog: [Kubernetes and the Mesosphere DCOS](http://blog.kubernetes.io/2015/04/kubernetes-and-mesosphere-dcos.html)
* Mesosphere blog: [Making Kubernetes a first-class citizen on the DCOS](https://mesosphere.com/blog/2015/04/22/making-kubernetes-a-first-class-citizen-on-the-dcos/)
* [Getting started with Kubernetes on Mesos](https://github.com/GoogleCloudPlatform/kubernetes/blob/master/docs/getting-started-guides/mesos.md)
* Via Mesosphere:
* [DCOS getting started](https://docs.mesosphere.com/getting-started/)
* [Kubernetes on Mesos tutorial](https://mesosphere.com/blog/2014/12/12/kubernetes-on-mesos/)
[1]: http://mesosphere.com/docs/tutorials/run-hadoop-on-mesos-using-installer
|
C++ | UTF-8 | 460 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <string>
int main()
{
std::map<int, std::string> is_map;
is_map[0] = "abc";
is_map[1] = "def";
is_map[2] = "hij";
for (auto &iter : is_map)
{
std::cout << "Before change: first: " << iter.first << " second: " << iter.second << "\n";
iter.second = "ddd";
}
for (auto &iter : is_map)
std::cout << "After change: first: " << iter.first << " second: " << iter.second << "\n";
return 0;
}
|
Markdown | UTF-8 | 7,568 | 3.734375 | 4 | [] | no_license | ---
title: 正则表达式——语法篇
date: 2018-08-16
tags:
- js
categories:
- js
---
## 1 正则是什么?
:::tip
正则就是用有限的符号,表达无限的序列,殆已!
:::
```js
// 匹配数字后面以英文逗号隔开 这里会有一个问题导致内存泄漏
// 就是d$这个¥符 如果不是英文逗号 比如输入一个空格 这会导致回溯过多 然后直接卡死
const regExpRull = /^(\d+,?)*(?=\d$)/;
if (!value || regExpRull.test(value)) {
return Promise.resolve();
}
```
  正则表达式的语法一般如下,两条斜线中间是正则主体,这部分可以有很多字符组成;<font color="#2E6CEA">i 部分是修饰符,i 的意思表示忽略大小写</font>
```
/^abc/i
```
## 2 正则定义了很多特殊意义的字符,有名词,量词,谓词等,下面逐一介绍
### 1 简单字符
  没有特殊意义的字符都是简单字符,简单字符就代表自身,绝大部分字符都是简单字符,举个例子
```
/cmd/ // 匹配 cmd
/123/ // 匹配 123
/-_-/ // 匹配 -_-
/中文/ // 匹配 中文
```
### 2 转义字符
\是转义字符,其后面的字符会代表不同的意思,转义字符主要有三个作用:
:::tip
第一种,是为了匹配不方便显示的特殊字符,比如换行,tab 符号等
第二种,正则中预先定义了一些代表特殊意义的字符,比如\w 等
第三种,在正则中某些字符有特殊含义(比如下面说到的),转义字符可以让其显示自身的含义
:::
  下面是常用转义字符列表:
| 规则 | 说明 |
| ------ | :------------------------------------------: |
| \n | 匹配换行符 |
| \r | 匹配回车符 |
| \t | 匹配制表符,也就是 tab 键 |
| \v | 匹配垂直制表符(表示几个换行符) |
| \x20 | 20 是 2 位 16 进制数字,代表对应的字符 |
| \u002B | 002B 是 4 位 16 进制数字,代表对应的字符 |
| \w | 匹配任何一个字母或者数字或者下划线 |
| \W | 匹配任何一个字母或者数字或者下划线以外的字符 |
| \s | 匹配空白字符,如空格,tab 等 |
| \S | 匹配非空白字符 |
| \d | 匹配数字字符,0~9 |
| \D | 匹配非数字字符 |
| \b | 匹配单词的边界 |
| \B | 匹配非单词边界 |
| \\ | 匹配\本身 |
### 3 字符集和
  有时我们需要匹配一类字符,字符集可以实现这个功能,字符集的语法用[]分隔,下面的代码能够匹配 g 或 a 或 d
```
[gad]
```
  如果要表示字符很多,可以使用-表示一个范围内的字符,下面两个功能相同
```
[0123456789]
[0-9]
```
  在前面添加^,可表示非的意思,下面的代码能够匹配 gad 之外的任意字符
```
[^gad]
```
  其实正则还内置了一些字符集,在上面的转义字符有提到,下面给出内置字符集对应的自定义字符集
.匹配除了换行符(\n)以外的任意一个字符 = [^\n]
. \w = [0-9a-zA-Z_]
. \W = [^0-9a-za-z_]
. \s = [ \t\n\v]
. \S = [^ \t\n\v]
. \d = [0-9]
. \D = [^0-9]
## 4 量词
  如果我们有三个苹果,我们可以说自己有个 3 个苹果,也可以说有一个苹果,一个苹果,一个苹果,每种语言都有量词的概念
  如果需要匹配多次某个字符,正则也提供了量词的功能,正则中的量词有多个,如?、+、\*、{n}、{m,n}、{m,}
  {n}匹配 n 次,比如 a{2},匹配 aa
  {m, n}匹配 m-n 次,优先匹配 n 次,比如 a{1,3},可以匹配 aaa、aa、a
  {m,}匹配 m-∞ 次,优先匹配 ∞ 次,比如 a{1,},可以匹配 aaaa...
  ?匹配 0 次或 1 次,优先匹配 1 次,相当于{0,1}
  +匹配 1-n 次,优先匹配 n 次,相当于{1,}
  \*匹配 0-n 次,优先匹配 n 次,相当于{0,}
  正则默认和人心一样是贪婪的,也就是常说的贪婪模式,凡是表示范围的量词,都优先匹配上限而不是下限
## 5 字符边界
  有时我们会有边界的匹配要求,比如以 xxx 开头,以 xxx 结尾
  ^在[]外表示匹配开头的意思
:::tip
^abc // 可以匹配 abc,但是不能匹配 aabc
:::
  $表示匹配结尾的意思
:::tip
abc$ // 可以匹配 abc,但是不能匹配 abcc
:::
  上面提到的\b 表示单词的边界
:::tip
abc\b // 可以匹配 abc ,但是不能匹配 abcc
:::
## 6 选择表达式
有时我们想匹配 x 或者 y,如果 x 和 y 是单个字符,可以使用字符集,[abc]可以匹配 a 或 b 或 c,如果 x 和 y 是多个字符,字符集就无能为力了,此时就要用到分组
正则中用|来表示分组,a|b 表示匹配 a 或者 b 的意思
:::tip
123|456|789 // 匹配 123 或 456 或 789
:::
## 7 分组与引用
分组是正则中非常强大的一个功能,可以让上面提到的量词作用于一组字符,而非单个字符,分组的语法是圆括号包裹(xxx)
:::tip
(abc){2} // 匹配 abcabc
分组不能放在[]中,但分组中还可以使用选择表达式
(123|456){2} // 匹配 123123、456456、123456、456123
:::
和分组相关的概念还有一个捕获分组和非捕获分组,分组默认都是捕获的,在分组的(后面添加?:可以让分组变为非捕获分组,非捕获分组可以提高性能和简化逻辑
:::tip
'123'.match(/(?:123)/) // 返回 ['123']
'123'.match(/(123)/) // 返回 ['123', '123']
:::
和分组相关的另一个概念是引用,比如在匹配 html 标签时,通常希望<xxx></xxx>后面的 xxx 能够和前面保持一致
引用的语法是\数字,数字代表引用前面第几个捕获分组,注意非捕获分组不能被引用
:::tip
<([a-z]+)><\/\1> // 可以匹配 `<span></span>` 或 `<div></div>`等
:::
## 8 预搜索
如果你想匹配 xxx 前不能是 yyy,或者 xxx 后不能是 yyy,那就要用到预搜索
js 只支持正向预搜索,也就是 xxx 后面必须是 yyy,或者 xxx 后面不能是 yyy
:::tip
1(?=2) // 可以匹配 12,不能匹配 22
1(?!2) // 可有匹配 22,不能匹配 12
:::
修饰符
默认正则是区分大小写,这可能并不是我们想要的,正则提供了修饰符的功能,修复的语法如下
:::tip
/xxx/gi // 最后面的 g 和 i 就是两个修饰符
g 正则遇到第一个匹配的字符就会结束,加上全局修复符,可以让其匹配到结束
i 正则默认是区分大小写的,i 可以忽略大小写
m 正则默认情况下,^和$只能匹配字符串的开始和结尾,m修饰符可以让^和$匹配行首和行尾,不理解就看例子
/jing$/ // 能够匹配 'yanhaijing,不能匹配 'yanhaijing\n'
/jing$/m // 能够匹配 'yanhaijing, 能够匹配 'yanhaijing\n'
/^jing/ // 能够匹配 'jing',不能匹配 '\njing'
/^jing/m // 能够匹配 'jing',能够匹配 '\njing'
:::
|
TypeScript | UTF-8 | 260 | 2.78125 | 3 | [] | no_license | export function hex2String(buffer: Buffer): string {
const hexParts = buffer.reduce((strAcc: string[], current): string[] => {
strAcc.push('0x' + ('0' + current.toString(16)).slice(-2));
return strAcc
}, [])
return `[${hexParts.join(', ')}]`
} |
Markdown | UTF-8 | 1,091 | 2.625 | 3 | [
"MIT"
] | permissive | # DJANGO LMS
_Sistema de gestión de aprendizaje._
## Pasos para la instalación
_Estas instrucciones te permitirán obtener una copia del proyecto en
funcionamiento en tu máquina local para propósitos de desarrollo y pruebas._
### Pre-requisitos 📋
- Tener instalado [Python 3.7](https://www.python.org/downloads/release/python-370/)
y un entorno virtual con el mismo.
### Instalación 🔧
- Activar su entorno virtual e instalar los requerimientos:
```
pip install -r requirements.txt
```
- Hacer las migraciones:
```
python manage.py makemigrations
```
```
python manage.py migrate
```
- Crear un superusuario
```
python manage.py createsuperuser
```
- Correr el proyecto localmente
```
python manage.py runserver
```
## Wiki 📖
Puedes encontrar mucho más de cómo utilizar este proyecto en nuestra [Wiki](https://github.com/django-lms/LMS/wiki)
## Autores ✒️
_Espacio reservado para los genios._
## Licencia 📄
Este proyecto está bajo la Licencia MIT - mira el archivo [LICENSE](LICENSE) para detalles.
|
Python | UTF-8 | 738 | 3.53125 | 4 | [] | no_license | from dzien12.kalkulator import *
from unittest import TestCase
from dzien12.testredirect import get_print_output
class TestsKalkulator(TestCase):
#tu pisze metody jakie chce tesotwac
#jedna klasa odpowiada jednemu testowi
def test_dodaj(self):
#trzy A
#arrange przypisz
a = 4
b = 7
wynik_oczekiwany = 11
#act - dzialaj
wynik_rzeczywisty = dodaj(a, b)
#assest sprawdzenie czy oczwikwany rowna sie rzecywistemu
self.assertEqual(wynik_oczekiwany, wynik_rzeczywisty, 'tescik dziala')
def test_pomnoz(self):
a = 2
b = 10
wynik1 = '20\n'
wynik2 = get_print_output(pomnoz, a, b)
self.assertEqual(wynik1, wynik2) |
TypeScript | UTF-8 | 4,291 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | import {
HassEntityAttributeBase,
HassEntityBase,
} from "home-assistant-js-websocket";
import { temperature2rgb } from "../common/color/convert-light-color";
export const enum LightEntityFeature {
EFFECT = 4,
FLASH = 8,
TRANSITION = 32,
}
export const enum LightColorMode {
UNKNOWN = "unknown",
ONOFF = "onoff",
BRIGHTNESS = "brightness",
COLOR_TEMP = "color_temp",
HS = "hs",
XY = "xy",
RGB = "rgb",
RGBW = "rgbw",
RGBWW = "rgbww",
WHITE = "white",
}
const modesSupportingColor = [
LightColorMode.HS,
LightColorMode.XY,
LightColorMode.RGB,
LightColorMode.RGBW,
LightColorMode.RGBWW,
];
const modesSupportingBrightness = [
...modesSupportingColor,
LightColorMode.COLOR_TEMP,
LightColorMode.BRIGHTNESS,
LightColorMode.WHITE,
];
export const lightSupportsColorMode = (
entity: LightEntity,
mode: LightColorMode
) => entity.attributes.supported_color_modes?.includes(mode) || false;
export const lightIsInColorMode = (entity: LightEntity) =>
(entity.attributes.color_mode &&
modesSupportingColor.includes(entity.attributes.color_mode)) ||
false;
export const lightSupportsColor = (entity: LightEntity) =>
entity.attributes.supported_color_modes?.some((mode) =>
modesSupportingColor.includes(mode)
) || false;
export const lightSupportsBrightness = (entity: LightEntity) =>
entity.attributes.supported_color_modes?.some((mode) =>
modesSupportingBrightness.includes(mode)
) || false;
export const lightSupportsFavoriteColors = (entity: LightEntity) =>
lightSupportsColor(entity) ||
lightSupportsColorMode(entity, LightColorMode.COLOR_TEMP);
export const getLightCurrentModeRgbColor = (
entity: LightEntity
): number[] | undefined =>
entity.attributes.color_mode === LightColorMode.RGBWW
? entity.attributes.rgbww_color
: entity.attributes.color_mode === LightColorMode.RGBW
? entity.attributes.rgbw_color
: entity.attributes.rgb_color;
interface LightEntityAttributes extends HassEntityAttributeBase {
min_color_temp_kelvin?: number;
max_color_temp_kelvin?: number;
min_mireds?: number;
max_mireds?: number;
brightness?: number;
xy_color?: [number, number];
hs_color?: [number, number];
color_temp?: number;
color_temp_kelvin?: number;
rgb_color?: [number, number, number];
rgbw_color?: [number, number, number, number];
rgbww_color?: [number, number, number, number, number];
effect?: string;
effect_list?: string[] | null;
supported_color_modes?: LightColorMode[];
color_mode?: LightColorMode;
}
export interface LightEntity extends HassEntityBase {
attributes: LightEntityAttributes;
}
export type LightColor =
| {
color_temp_kelvin: number;
}
| {
hs_color: [number, number];
}
| {
rgb_color: [number, number, number];
}
| {
rgbw_color: [number, number, number, number];
}
| {
rgbww_color: [number, number, number, number, number];
};
const COLOR_TEMP_COUNT = 4;
const DEFAULT_COLORED_COLORS = [
{ rgb_color: [127, 172, 255] }, // blue #7FACFF
{ rgb_color: [215, 150, 255] }, // purple #D796FF
{ rgb_color: [255, 158, 243] }, // pink #FF9EF3
{ rgb_color: [255, 110, 84] }, // red #FF6E54
] as LightColor[];
export const computeDefaultFavoriteColors = (
stateObj: LightEntity
): LightColor[] => {
const colors: LightColor[] = [];
const supportsColorTemp = lightSupportsColorMode(
stateObj,
LightColorMode.COLOR_TEMP
);
const supportsColor = lightSupportsColor(stateObj);
if (supportsColorTemp) {
const min = stateObj.attributes.min_color_temp_kelvin!;
const max = stateObj.attributes.max_color_temp_kelvin!;
const step = (max - min) / (COLOR_TEMP_COUNT - 1);
for (let i = 0; i < COLOR_TEMP_COUNT; i++) {
colors.push({
color_temp_kelvin: Math.round(min + step * i),
});
}
} else if (supportsColor) {
const min = 2000;
const max = 6500;
const step = (max - min) / (COLOR_TEMP_COUNT - 1);
for (let i = 0; i < COLOR_TEMP_COUNT; i++) {
colors.push({
rgb_color: temperature2rgb(Math.round(min + step * i)),
});
}
}
if (supportsColor) {
colors.push(...DEFAULT_COLORED_COLORS);
}
return colors;
};
export const formatTempColor = (value: number) => `${value} K`;
|
JavaScript | UTF-8 | 3,913 | 2.53125 | 3 | [
"MIT"
] | permissive | /// <reference types="@altv/types" />
/// <reference types="@altv/native-types" />
import * as alt from 'alt-client'
import * as game from 'natives';
let chatActive = false;
let inputActive = false;
let scrollActive = false;
const webview = new alt.WebView('http://resource/client/html/index.html');
webview.focus();
webview.on('chat:onLoaded', () => {
activateChat(true);
push('Connected to the server', 'limegreen', [0, 190, 0], 'check')
});
webview.on('chat:onInputStateChange', state => {
inputActive = state;
alt.showCursor(state);
alt.toggleGameControls(!state);
});
webview.on('chat:onChatStateChange', state => {
chatActive = state;
});
webview.on('chat:onInput', text => {
alt.emitServer('chat:onInput', (text[0] === '/') ? true : false, text);
});
alt.onServer('chat:sendMessage', (sender, text) => {
push(`${sender} says: ${text}`);
});
alt.onServer('chat:showMessage', (text, color, gradient, icon) => {
push(text, color, gradient, icon);
});
alt.onServer('chat:activateChat', state => {
activateChat(state);
});
export function clearMessages() {
webview.emit('chat:clearMessages');
}
// Backwards compatibility until next update
export function clearChat(...args) {
alt.logWarning('Chat function "clearChat" is deprecated. Consider using "clearMessages" as old one will be removed after next update.');
clearMessages(...args);
}
export function push(text, color = 'white', gradient = false, icon = false) {
webview.emit('chat:pushMessage', text, color, gradient, icon);
}
// Backwards compatibility until next update
export function addChatMessage(...args) {
alt.logWarning('Chat function "addChatMessage" is deprecated. Consider using "push" as old one will be removed after next update.');
push(...args);
}
export function activateChat(state) {
webview.emit('chat:activateChat', state);
}
// Backwards compatibility until next update
export function showChat() {
alt.logError('Chat function "showChat" is deprecated. Consider using "activateChat" as old one will be removed after next update. Function was not called!');
push('Check you console!', 'red');
}
// Backwards compatibility until next update
export function hideChat() {
alt.logError('Chat function "hideChat" is deprecated. Consider using "activateChat" as old one will be removed after next update. Function was not called!');
push('Check you console!', 'red');
}
alt.on('keyup', key => {
// Keys working only when chat is not active
if (!chatActive) {
switch (key) {
}
}
// Keys working only when chat is active
if (chatActive) {
switch (key) {
// PageUp
case 33: return scrollMessagesList('up');
// PageDown
case 34: return scrollMessagesList('down');
}
}
// Keys working only when chat is active and input is not active
if (chatActive && !inputActive) {
switch (key) {
// KeyT
case 84: return activateInput(true);
}
}
// Keys working only when chat is active and input is active
if (chatActive && inputActive) {
switch (key) {
// Enter
case 13: return sendInput();
// ArrowUp
case 38: return shiftHistoryUp();
// ArrowDown
case 40: return shiftHistoryDown();
}
}
});
function scrollMessagesList(direction) {
if (scrollActive) return;
scrollActive = true;
alt.setTimeout(() => scrollActive = false, 250 + 5);
webview.emit('chat:scrollMessagesList', direction);
}
function activateInput(state) {
webview.emit('chat:activateInput', state);
}
function sendInput() {
webview.emit('chat:sendInput');
}
function shiftHistoryUp() {
webview.emit('chat:shiftHistoryUp');
}
function shiftHistoryDown() {
webview.emit('chat:shiftHistoryDown');
} |
Markdown | UTF-8 | 5,910 | 2.796875 | 3 | [] | no_license | ---
title: AndroidAnnotations (六) - Resources
tags:
- Android
- AndroidAnnotations
date: 2015-11-24 22:51:50
---
> 对应Android本身各种资源标签,没什么探究的了,实在记不住用得时候查一下就好了。
All @XXXRes annotations indicate that an activity field should be injected with the corresponding Android resource from your res folder. The resource id can be set in the annotation parameter, ie @StringRes(R.string.hello).
### @StringRes
* * *
<figure class="highlight scala"><table><tr><td class="code"><pre><span class="line"><span class="annotation">@EActivity</span></span>
<span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">MyActivity</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">Activity</span> {</span></span>
<span class="line"></span>
<span class="line"> <span class="annotation">@StringRes</span>(<span class="type">R</span>.string.hello)</span>
<span class="line"> <span class="type">String</span> myHelloString;</span>
<span class="line"></span>
<span class="line"> <span class="annotation">@StringRes</span></span>
<span class="line"> <span class="type">String</span> hello;</span>
<span class="line"></span>
<span class="line">}</span>
</pre></td></tr></table></figure>
### @ColorRes
* * *
<figure class="highlight scala"><table><tr><td class="code"><pre><span class="line"><span class="annotation">@EActivity</span></span>
<span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">MyActivity</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">Activity</span> {</span></span>
<span class="line"></span>
<span class="line"> <span class="annotation">@ColorRes</span>(<span class="type">R</span>.color.backgroundColor)</span>
<span class="line"> int someColor;</span>
<span class="line"></span>
<span class="line"> <span class="annotation">@ColorRes</span></span>
<span class="line"> int backgroundColor;</span>
<span class="line"></span>
<span class="line">}</span>
</pre></td></tr></table></figure>
### @AnimationRes
* * *
<figure class="highlight scala"><table><tr><td class="code"><pre><span class="line"><span class="annotation">@EActivity</span></span>
<span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">MyActivity</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">Activity</span> {</span></span>
<span class="line"></span>
<span class="line"> <span class="annotation">@AnimationRes</span>(<span class="type">R</span>.anim.fadein)</span>
<span class="line"> <span class="type">XmlResourceParser</span> xmlResAnim;</span>
<span class="line"></span>
<span class="line"> <span class="annotation">@AnimationRes</span></span>
<span class="line"> <span class="type">Animation</span> fadein;</span>
<span class="line"></span>
<span class="line">}</span>
</pre></td></tr></table></figure>
### @DimensionRes
* * *
<figure class="highlight scala"><table><tr><td class="code"><pre><span class="line"><span class="annotation">@EActivity</span></span>
<span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">MyActivity</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">Activity</span> {</span></span>
<span class="line"></span>
<span class="line"> <span class="annotation">@DimensionRes</span>(<span class="type">R</span>.dimen.fontsize)</span>
<span class="line"> float fontSizeDimension;</span>
<span class="line"></span>
<span class="line"> <span class="annotation">@DimensionRes</span></span>
<span class="line"> float fontsize;</span>
<span class="line"></span>
<span class="line">}</span>
</pre></td></tr></table></figure>
### @DimensionPixelOffsetRes
* * *
<figure class="highlight scala"><table><tr><td class="code"><pre><span class="line"><span class="annotation">@EActivity</span></span>
<span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">MyActivity</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">Activity</span> {</span></span>
<span class="line"></span>
<span class="line"> <span class="annotation">@DimensionPixelOffsetRes</span>(<span class="type">R</span>.string.fontsize)</span>
<span class="line"> int fontSizeDimension;</span>
<span class="line"></span>
<span class="line"> <span class="annotation">@DimensionPixelOffsetRes</span></span>
<span class="line"> int fontsize;</span>
<span class="line"></span>
<span class="line">}</span>
</pre></td></tr></table></figure>
### @DimensionPixelSizeRes
* * *
<figure class="highlight scala"><table><tr><td class="code"><pre><span class="line"><span class="annotation">@EActivity</span></span>
<span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">MyActivity</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">Activity</span> {</span></span>
<span class="line"></span>
<span class="line"> <span class="annotation">@DimensionPixelSizeRes</span>(<span class="type">R</span>.string.fontsize)</span>
<span class="line"> int fontSizeDimension;</span>
<span class="line"></span>
<span class="line"> <span class="annotation">@DimensionPixelSizeRes</span></span>
<span class="line"> int fontsize;</span>
<span class="line"></span>
<span class="line">}</span>
</pre></td></tr></table></figure>
### Other @XXXRes
* * *
Here is the list of other supported resource annotations:
* `@BooleanRes`
* `@ColorStateListRes`
* `@DrawableRes`
* `@IntArrayRes`
* `@IntegerRes`
* `@LayoutRes`
* `@MovieRes`
* `@TextRes`
* `@TextArrayRes`
* `@StringArrayRes` |
TypeScript | UTF-8 | 450 | 2.5625 | 3 | [] | no_license | import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { filter } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class Notifier {
private notifier$ = new Subject<any>();
constructor() {}
notify<T>(data: T): void {
this.notifier$.next(data);
}
on<T>(type: { new (...args: any[]): T }): Observable<T> {
return this.notifier$.pipe(filter(i => i instanceof type));
}
}
|
JavaScript | UTF-8 | 1,784 | 2.921875 | 3 | [] | no_license | let input = document.querySelectorAll('input')
let surface = document.querySelector('.surface')
let code_text = document.querySelector('#code')
let input_array = [0, 0, 0, 0, 0, 0, 0, 0]
input.forEach((e, k, n) => {
e.addEventListener('input', (event) => {
if (e.getAttribute('id') == 'input_tl') {
input_array[0] = e.value
} else if (e.getAttribute('id') == 'input_tlt') {
input_array[1] = e.value
} else if (e.getAttribute('id') == 'input_tr') {
input_array[2] = e.value
} else if (e.getAttribute('id') == 'input_trt') {
input_array[3] = e.value
} else if (e.getAttribute('id') == 'input_bl') {
input_array[4] = e.value
} else if (e.getAttribute('id') == 'input_blb') {
input_array[5] = e.value
} else if (e.getAttribute('id') == 'input_br') {
input_array[6] = e.value
} else {
input_array[7] = e.value
}
input_array.map((v, i) => {
if (v == '') {
input_array[i] = '0'
}
})
surface.style = `
border-top-left-radius: ${input_array[0]}px ${input_array[1]}px;
border-top-right-radius: ${input_array[2]}px ${input_array[3]}px;
border-bottom-left-radius: ${input_array[4]}px ${input_array[5]}px;
border-bottom-right-radius: ${input_array[6]}px ${input_array[7]}px;
`
code_text.value = `-moz-border-radius: ${surface.style.cssText.slice(15)}
-webkit-border-radius: ${surface.style.cssText.slice(15)}
${surface.style.cssText}`
})
})
function isNumber(event) {
let keycode = event.keyCode;
if (keycode > 47 && keycode < 59) {
return true
} else {
return false
}
} |
Java | UTF-8 | 1,046 | 2.515625 | 3 | [] | no_license | package com.abc.message.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.math.BigInteger;
/**
* @author aravind
*/
@ApiModel(description = "DTO for read Comment information")
public class CommentQueryDTO {
@ApiModelProperty(notes = "Unique Id of the Comment")
private BigInteger id;
@ApiModelProperty(notes = "Comment for the post", example = "Awesomee!!")
private String comment;
public CommentQueryDTO(BigInteger id, String comment) {
this.id = id;
this.comment = comment;
}
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public String toString() {
return "CommentQueryDTO{" +
"id=" + id +
", comment='" + comment + '\'' +
'}';
}
}
|
Java | UTF-8 | 963 | 3.3125 | 3 | [] | no_license | package com.weizhi.common.util;
/**
* ProjectName:common-wei
* Decription:输出相应的参数
* Created By:weizhi
* Created Date:2015/11/15
* Updated By:
* Updated Date:
* Copyright@2014-2015 weizhi2018
* Version:V1.0
*/
public class PrintUtil {
/**
* 输出数组
* @param arr
*/
public static void printArr(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i] + " ");
}
System.out.println();
}
/**
* 输出字符串,且不换行
* @param msg
*/
public static void printMsgWithoutNewline(String msg){
System.out.print(msg);
}
/**
* 输出字符串,且不换行
* @param msg
*/
public static void printMsgWithNewline(String msg){
System.out.print(msg);
}
/**
* 输出整数
* @param i
*/
public static void printIntWithNewline(int i){
System.out.println(i);
}
}
|
Java | UTF-8 | 151 | 2.125 | 2 | [] | no_license | package org.learn.java.继承;
/**
* @description:
*/
public class ABC {
protected int a;
protected int getA() {
return 1;
}
}
|
Shell | UTF-8 | 1,253 | 3.34375 | 3 | [] | no_license | #!/bin/bash
# author: Charles Joly Beauparlant
# date: 2012-02-13
# based on BlueTsunami: github.com/sebhtml/NGS-Pipelines/blob/master/BlueTsunami
source $DARK_FISH_TECHNOLOGY
source $BENCHMARKTOOLS
# Process arguments
# The arguments must not be absolute paths.
processors=$1
output=$2
fileFormat=$3
options=$4
if [ $fileFormat = "txt" ]
then
fileName=$5
BenchmarkTools_extractFileInfos $fileName
else
fileFormats[0]=$fileFormat
treatmentFiles[0]=$5
controlFiles[0]=$6
fi
# Prepare analysis
mkdir $output
cd $output
DarkFishTechnology_initializeDirectory
DarkFishTechnology_runCommand 0 "eland2bed --version &> meta/eland2bed.version"
# Note: There is no --version or equivalent with sissrs, this have to be hardcoded
# and manually changed when a new version is used.
DarkFishTechnology_runCommand 0 "echo \"sissrs v1.4\" &> meta/sissrs.version"
# Prepare samples
BenchmarkTools_prepareSamples
# Convert sample for analysis
BenchmarkTools_convertSamples "SISSRs"
# Do the actual analysis
BenchmarkTools_getRawSISSRsResults
DarkFishTechnology_purgeGroupCache "FormatedSamples"
# Trim results
BenchmarkTools_trimSISSRsResults
DarkFishTechnology_purgeGroupCache "RawResults"
# Link peak list for subsequent analysis
BenchmarkTools_linkSISSRsPeakList
|
C# | UTF-8 | 2,889 | 2.84375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;
namespace HtmlHelper
{
internal class WebReqState
{
public byte[] Buffer;
public MemoryStream ms;
public const int BufferSize = 1024;
public Stream OrginalStream;
public HttpWebResponse WebResponse;
public WebReqState()
{
Buffer = new byte[1024];
ms = new MemoryStream();
}
}
public delegate void ReadDataComplectedEventHandler(byte[] data);
public class HtmlFromWebReq
{
private Uri url;
public event ReadDataComplectedEventHandler OnReadDataComplected;
private string p;
private ReadDataComplectedEventHandler readDataComplectedEventHandler;
public HtmlFromWebReq(string absoluteUrl,ReadDataComplectedEventHandler hendler)
{
if (hendler != null)
{
OnReadDataComplected += hendler;
}
url = new Uri(absoluteUrl);
}
protected void readDataCallback(IAsyncResult ar)
{
WebReqState rs = ar.AsyncState as WebReqState;
int read = rs.OrginalStream.EndRead(ar);
if (read > 0)
{
rs.ms.Write(rs.Buffer, 0, read);
rs.OrginalStream.BeginRead(rs.Buffer, 0, WebReqState.BufferSize,
new AsyncCallback(readDataCallback), rs);
}
else
{
rs.OrginalStream.Close();
rs.WebResponse.Close();
if (OnReadDataComplected != null)
{
OnReadDataComplected(rs.ms.ToArray());
}
}
}
protected void responseCallback(IAsyncResult ar)
{
HttpWebRequest req = ar.AsyncState as HttpWebRequest;
if (req == null)
return;
HttpWebResponse response =
req.EndGetResponse(ar) as HttpWebResponse;
if (response.StatusCode != HttpStatusCode.OK)
{
response.Close();
return;
}
WebReqState st = new WebReqState();
st.WebResponse = response;
Stream repsonseStream = response.GetResponseStream();
st.OrginalStream = repsonseStream;
repsonseStream.BeginRead(st.Buffer, 0,
WebReqState.BufferSize,
new AsyncCallback(readDataCallback), st);
}
public void BeginCreateHtml()
{
HttpWebRequest req =
HttpWebRequest.Create(url.AbsoluteUri) as HttpWebRequest;
req.BeginGetResponse(new AsyncCallback(responseCallback), req);
}
}
} |
JavaScript | UTF-8 | 209 | 2.546875 | 3 | [] | no_license |
// APPLY FUNCTIONALITY TO THE CENTRAL BUTTON
$("#insider a").on("click", function(){
// CHANGE THE TEXT IN THE PARAGHAPH ABOVE THE BUTTON
$("#insider h1").text("This is SUPER SUPER SUPER TERRICFIC!");
}); |
Go | UTF-8 | 672 | 3.359375 | 3 | [] | no_license | package main
func main() {
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func findTarget(root *TreeNode, k int) bool {
return dfs(root, root, k)
}
func dfs(root, searchRoot *TreeNode, k int) bool {
if root == nil {
return false
}
found := findNode(searchRoot, k-root.Val)
if found != nil && found != root {
return true
}
return dfs(root.Left, searchRoot, k) ||
dfs(root.Right, searchRoot, k)
}
func findNode(root *TreeNode, target int) *TreeNode {
if root == nil {
return nil
}
if root.Val == target {
return root
}
if root.Val < target {
return findNode(root.Right, target)
}
return findNode(root.Left, target)
}
|
C# | UTF-8 | 2,638 | 2.75 | 3 | [] | no_license | using Antlr4.Runtime;
namespace ParsingTools
{
public partial class LatteParser
{
public partial class TypeContext {
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
if (obj is TTypeNameContext context)
{
return (this as TTypeNameContext).ID().GetText() == context.ID().GetText();
}
return true;
}
public override int GetHashCode()
{
throw new System.NotImplementedException();
}
}
public partial class TStringContext
{
public TStringContext() {}
public override string GetText()
{
return "string";
}
public override string ToString()
{
return "string";
}
}
public partial class TIntContext
{
public TIntContext() {}
public override string GetText()
{
return "int";
}
public override string ToString()
{
return "int";
}
}
public partial class TBoolContext
{
public TBoolContext() {}
public override string GetText()
{
return "bool";
}
public override string ToString()
{
return "bool";
}
}
public partial class TVoidContext
{
public TVoidContext() {}
public override string GetText()
{
return "void";
}
public override string ToString()
{
return "void";
}
}
public partial class TTypeNameContext
{
private readonly string _typeName;
public TTypeNameContext(string typeName)
{
_typeName = typeName;
}
public override string GetText()
{
return _typeName ?? base.GetText();
}
public override string ToString()
{
return _typeName ?? base.GetText();
}
}
}
} |
C# | UTF-8 | 5,945 | 3.484375 | 3 | [] | no_license | using System;
using System.Security.Cryptography.X509Certificates;
namespace TicTacToe
{
class Program
{
public static void Main(string[] args)
{
char[,] board = new char[3, 3] { { ' ', ' ', ' ' },
{ ' ', ' ', ' ' },
{ ' ', ' ', ' ' } };
Console.WriteLine("Let' play Tic Tac Toe!");
PrintArr(board);
for (int i = 0; i < board.Length; i++)
{
if (i % 2 == 0)
{
playerTurn("Player1", 'X', board);
bool player1Won = CheckForWin(board, 'X', "Player1");
if (player1Won == true)
break;
else
continue;
}
else
{
playerTurn("Player2", 'O', board);
bool player2Won = CheckForWin(board, 'O', "Player2");
if (player2Won == true)
break;
else
continue;
}
}
}
static bool CheckForWin(char[,] board, char c, string player)
{
bool playerWins = false;
if ((board[0, 0] == c && board[1, 0] == c && board[2, 0] == c) ||
(board[0, 0] == c && board[0, 1] == c && board[0, 2] == c) ||
(board[0, 2] == c && board[1, 2] == c && board[2, 2] == c) ||
(board[2, 0] == c && board[2, 1] == c && board[2, 2] == c) ||
(board[2, 0] == c && board[1, 1] == c && board[0, 2] == c) ||
(board[0, 0] == c && board[1, 1] == c && board[2, 2] == c) ||
(board[0, 1] == c && board[1, 1] == c && board[2, 1] == c) ||
(board[1, 0] == c && board[1, 1] == c && board[1, 2] == c))
{
Console.WriteLine(player + " Wins!");
playerWins = true;
}
return playerWins;
}
static void playerTurn(string player, char c, char[,] board)
{
bool spaceTaken = true;
while (spaceTaken == true)
{
Console.Write("\n" + player + ", Where would you like to move? ");
string location = Console.ReadLine();
spaceTaken = LocationAssig(board, location, c);
PrintArr(board);
}
}
static void PrintArr(char[,] arr)
{
Console.WriteLine(" ");
Console.WriteLine("\t 1 2 3");
Console.WriteLine("\ta" + "[" + arr[0, 0] + "]" + "[" + arr[0, 1] + "]" + "[" + arr[0, 2] + "]");
Console.WriteLine("\tb" + "[" + arr[1, 0] + "]" + "[" + arr[1, 1] + "]" + "[" + arr[1, 2] + "]");
Console.WriteLine("\tc" + "[" + arr[2, 0] + "]" + "[" + arr[2, 1] + "]" + "[" + arr[2, 2] + "]\n");
}
static bool LocationAssig(char[,] arr, string location, char c)
{
bool spaceTaken = false;
if (location == "a1" || location == "1a")
{
if (arr[0, 0] == ' ')
arr[0, 0] = c;
else
{
Console.WriteLine("\nThis space is filled, choose another.");
spaceTaken = true;
}
}
else if (location == "a2" || location == "2a")
{
if (arr[0, 1] == ' ')
arr[0, 1] = c;
else
{
Console.WriteLine("\nThis space is filled, choose another.");
spaceTaken = true;
}
}
else if (location == "a3" || location == "3a")
{
if (arr[0, 2] == ' ')
arr[0, 2] = c;
else
{
Console.WriteLine("\nThis space is filled, choose another.");
spaceTaken = true;
}
}
else if (location == "b1" || location == "1b")
{
if (arr[1, 0] == ' ')
arr[1, 0] = c;
else
{
Console.WriteLine("\nThis space is filled, choose another.");
spaceTaken = true;
}
}
else if (location == "b2" || location == "2b")
{
if (arr[1, 1] == ' ')
arr[1, 1] = c;
else
{
Console.WriteLine("\nThis space is filled, choose another.");
spaceTaken = true;
}
}
else if (location == "b3" || location == "3b")
{
if (arr[1, 2] == ' ')
arr[1, 2] = c;
else
{
Console.WriteLine("\nThis space is filled, choose another.");
spaceTaken = true;
}
}
else if (location == "c1" || location == "1c")
{
if (arr[2, 0] == ' ')
arr[2, 0] = c;
else
{
Console.WriteLine("\nThis space is filled, choose another.");
spaceTaken = true;
}
}
else if (location == "c2" || location == "2c")
{
if (arr[2, 1] == ' ')
arr[2, 1] = c;
else
{
Console.WriteLine("\nThis space is filled, choose another.");
spaceTaken = true;
}
}
else if (location == "c3" || location == "3c")
{
if (arr[2, 2] == ' ')
arr[2, 2] = c;
else
{
Console.WriteLine("\nThis space is filled, choose another.");
spaceTaken = true;
}
}
else
{
Console.WriteLine("\nNot a valid entry.\nKey the letter of the desired row: a, b, or c \n" +
"followed by the number of the desired column: 1, 2 or 3 \nwith no space in between. " +
"For example, row \"a\" and column \"1\" is: a1 .");
spaceTaken = true;
}
return spaceTaken;
}
}
}
|
Java | UTF-8 | 6,505 | 2.328125 | 2 | [] | no_license | package ru.akotov.event;
import org.bukkit.Bukkit;
import org.bukkit.event.*;
import org.bukkit.plugin.Plugin;
import ru.akotov.utils.PrivateLookup;
import java.lang.invoke.CallSite;
import java.lang.invoke.LambdaMetafactory;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
public abstract class FilteredEventBus<T> {
private final Plugin plugin;
private final Listener fakeListener = new Listener() {
};
private final Map<Class<? extends Event>, THandler<? extends Event, T>> handlers = new HashMap<>();
private final MethodHandles.Lookup lookup = PrivateLookup.get();
public FilteredEventBus(Plugin plugin) {
this.plugin = plugin;
}
public void register(T key, Object listener) {
for (Method method : listener.getClass().getDeclaredMethods()) {
EventHandler annotation = method.getAnnotation(EventHandler.class);
if (annotation == null || method.isBridge() || method.isSynthetic())
continue;
if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(method.getParameterTypes()[0])) {
plugin.getLogger().severe(plugin.getDescription().getFullName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass());
continue;
}
Class<? extends Event> eventClass = method.getParameterTypes()[0].asSubclass(Event.class);
THandler<? extends Event, T> handler = handlers.computeIfAbsent(eventClass, this::createHandler);
EventPriority priority = annotation.priority();
Map<T, List<EventConsumer>> listeners = handler.priorityMap.get(priority);
if (listeners == null) {
handler.priorityMap.put(priority, listeners = new HashMap<>());
Bukkit.getPluginManager().registerEvent(eventClass, fakeListener, priority, (unused, event) -> {
if (eventClass.isAssignableFrom(event.getClass())) {
handler.handle(priority, event);
}
}, plugin, false);
}
try {
Consumer<Event> executor = createExecutor(eventClass, listener, method);
listeners.computeIfAbsent(key, a -> new ArrayList<>())
.add(new EventConsumer(listener, executor, annotation.ignoreCancelled()));
} catch (Throwable ex) {
ex.printStackTrace();
}
}
}
abstract THandler<? extends Event, T> createHandler(Class<? extends Event> eventClass);
public void unregister(T key, Object listener) {
for (Method method : listener.getClass().getDeclaredMethods()) {
EventHandler annotation = method.getAnnotation(EventHandler.class);
if (annotation == null || method.isBridge() || method.isSynthetic())
continue;
if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(method.getParameterTypes()[0]))
continue;
Class<? extends Event> eventClazz = method.getParameterTypes()[0].asSubclass(Event.class);
THandler<? extends Event, T> handler = handlers.get(eventClazz);
if (handler == null)
continue;
Map<T, List<EventConsumer>> listeners = handler.priorityMap.get(annotation.priority());
if (listeners == null)
continue;
List<EventConsumer> list = listeners.get(key);
if (list == null)
continue;
Iterator<EventConsumer> it = list.iterator();
while (it.hasNext())
if (it.next().listener == listener)
it.remove();
if (list.isEmpty())
listeners.remove(key);
}
}
@SuppressWarnings("unchecked")
private Consumer<Event> createExecutor(Class eventClass, Object listener, Method method) throws Throwable {
method.setAccessible(true);
CallSite factory = LambdaMetafactory.metafactory(
lookup.in(listener.getClass()),
"accept",
MethodType.methodType(Consumer.class, listener.getClass()),
MethodType.methodType(void.class, Object.class),
lookup.unreflect(method),
MethodType.methodType(void.class, eventClass)
);
return (Consumer<Event>) factory.getTarget().invoke(listener);
}
protected static class THandler<T extends Event, M> {
private final Map<EventPriority, Map<M, List<EventConsumer>>> priorityMap = new EnumMap<>(EventPriority.class);
private final Function<T, M> worldGetter;
THandler(Function<T, M> worldGetter) {
this.worldGetter = worldGetter;
}
@SuppressWarnings({"unchecked", "ForLoopReplaceableByForEach"})
void handle(EventPriority priority, Event event) {
Map<M, List<EventConsumer>> map = priorityMap.get(priority);
if (map == null || map.isEmpty())
return;
M object = worldGetter.apply((T) event);
if (object == null)
return;
List<EventConsumer> list = map.get(object);
if (list != null) {
for (int i = 0; i < list.size(); i++)
list.get(i).execute(event);
}
}
}
private static class EventConsumer {
private final Consumer<Event> consumer;
private final boolean ignoreCancelled;
private final Object listener;
EventConsumer(Object listener, Consumer<Event> consumer, boolean ignoreCancelled) {
this.consumer = consumer;
this.listener = listener;
this.ignoreCancelled = ignoreCancelled;
}
void execute(Event event) {
if (ignoreCancelled && event instanceof Cancellable && ((Cancellable) event).isCancelled())
return;
try {
consumer.accept(event);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
|
Go | UTF-8 | 1,940 | 3.171875 | 3 | [
"Apache-2.0"
] | permissive | package customer
import (
"context"
"errors"
"fmt"
"time"
"golang.org/x/crypto/bcrypt"
"github.com/fwiedmann/ezb/domain/entity"
)
// birthdateLayout represents a birthdate in this format: day-month-year
const birthdateLayout = "02-01-2006"
var (
ErrorEmptyUserInput = errors.New("user input contains empty fields")
ErrorInvalidBirthdate = errors.New("users birthdate is invalid. It should be in the format of day-month-year")
)
func NewManager(r repository) Manager {
return manager{repo: r}
}
type manager struct {
repo repository
}
func (m manager) Create(ctx context.Context, c Customer) (entity.ID, error) {
if err := validateCustomer(c); err != nil {
return [16]byte{}, err
}
c.ID = entity.NewID()
timestamp := time.Now()
c.creationTimestamp, c.lastUpdateTimestamp = timestamp, timestamp
if err := m.repo.Create(ctx, c); err != nil {
return [16]byte{}, err
}
return c.ID, nil
}
func (m manager) Update(ctx context.Context, c Customer) error {
if err := validateCustomer(c); err != nil {
return err
}
c.lastUpdateTimestamp = time.Now()
if err := m.repo.Update(ctx, c); err != nil {
return err
}
return nil
}
func (m manager) Get(ctx context.Context, id entity.ID) (Customer, error) {
return m.repo.Get(ctx, id)
}
func validateCustomer(c Customer) error {
if c.FirstName == "" {
return ErrorEmptyUserInput
}
if c.LastName == "" {
return ErrorEmptyUserInput
}
if c.Gender == "" {
return ErrorEmptyUserInput
}
if c.Birthdate == "" {
return ErrorEmptyUserInput
}
if err := validateBirthdate(c.Birthdate); err != nil {
return err
}
return nil
}
func hashPin(pin string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(pin), 14)
return string(bytes), err
}
func validateBirthdate(date string) error {
if _, err := time.Parse(birthdateLayout, date); err != nil {
return fmt.Errorf("%w, error: %s", ErrorInvalidBirthdate, err)
}
return nil
}
|
C | UTF-8 | 386 | 3.28125 | 3 | [] | no_license | #include <stdio.h>
int sub5(void)
{
int a = 10;
int b = 12;
printf("a & b : %d\n", a & b);
printf("a ^ b : %d\n", a ^ b);
printf("a | b : %d\n", a | b);
printf("~a : %d\n", ~a);
printf("a<<1:%d\n", a << 1);
printf("a>>2:%d\n", a >> 2);
printf("\n");
char ch = 128;
unsigned char ch1 = 128;
printf("ch>>1 : %d\n", ch >> 1);
printf("ch>>1 : %d\n", ch1 >> 1);
return 0;
} |
C | UTF-8 | 4,389 | 2.84375 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
double randomNumber(int ubound, int lbound){
double s;
s = ((double)rand()/(RAND_MAX))*(ubound-lbound);
return s;
}
void copyMatrix(double *a, double *b, int n){
int i;
for(i=0; i< n*n;i++){
b[i]=a[i];
}
}
double* assignMatVal(double *a, int n, int ubound, int lbound){
int i;
for(i=0;i<n*n;i++){
a[i] = randomNumber(ubound, lbound);
}
return a;
}
void calcPerformance(clock_t start, clock_t end,int n){
printf("Matrix Size = %d\n",n);
double time = ((double)(end-start))/CLOCKS_PER_SEC;
printf("Time taken in seconds = %f s\n",time);
double perfomance = 2*((double)pow(n,3))/(time*pow(10,9));
printf("Performance in GFLOPS = %e\n",perfomance);
}
void calcExecutionTime(clock_t start, clock_t end,int n, char s[]){
printf("Matrix Size = %d\n",n);
printf("Matrix Config = %s\n", s);
double time = ((double)(end-start))/CLOCKS_PER_SEC;
printf("Time taken in seconds = %.10f s\n",time);
}
void findCorrectness(double *a, double *b,int n){
double error = 0.0000000;
int i;
for(i=0;i<n*n;i++){
if(error < abs(a[i]-b[i]))
error = abs(a[i]-b[i]);
}
printf("Error = %f\n",error);
printf("\n");
}
void regCacheMat(double *a, double *b, double *c, int n, int B){
int i,j,k,i1,j1,k1;
clock_t start,end;
start = clock();
for (i = 0; i < n; i+=B){
for (j = 0; j < n; j+=B){
for (k = 0; k < n; k+=B){
/* B x B mini matrix multiplications */
for (i1 = i; i1 < i+B; i1+=2){
for (j1 = j; j1 < j+B; j1+=2){
register int t = i1*n+j1; register int tt = t+n;
register double c00 = c[t]; register double c01 = c[t+1]; register double c10 = c[tt]; register double c11 = c[tt+1];
for (k1 = k; k1 < k+B; k1+=2){
register int ta = i1*n+k1; register int tta = ta+n; register int tb = k1*n+j1; register int ttb = tb+n;
register double a00 = a[ta]; register double a10 = a[tta]; register double b00 = b[tb]; register double b01 = b[tb+1];
c00 += a00*b00 ; c01 += a00*b01 ; c10 += a10*b00 ; c11 += a10*b01 ;
a00 = a[ta+1]; a10 = a[tta+1]; b00 = b[ttb]; b01 = b[ttb+1];
c00 += a00*b00 ; c01 += a00*b01 ; c10 += a10*b00 ; c11 += a10*b01 ;
}
c[t] = c00;
c[t+1] = c01;
c[tt] = c10;
c[tt+1] = c11;
}
}
}
}
}
end = clock();
printf("Alogrithm: Register Cache Blocking\n");
printf("Block size: %d\n",B);
calcPerformance(start,end,n);
}
void dgemm0(double *a, double *b, double *c, int n){
clock_t start,end;
int i,j,k;
start = clock();
for (i=0; i<n; i++ ){
for (j=0; j<n; j++ ){
for (k=0; k<n; k++ ){
c[i*n+j]+=a[i*n+k]*b[k*n+j];
}
}
}
end = clock();
printf("Algorithm: dgemm0\n");
calcPerformance(start,end,n);
}
int main(){
int i,n;
double *arrA,*arrB,*arrC0, *arrC1, * arrC2;
int arrN[] = {2,4,8,16,32,64,128,256,512,1024};
srand((double)time(NULL));
int ubound = 100, lbound = 1;
int len = sizeof(arrN)/sizeof(arrN[0]);
n=2048;
for(i=0;i<len;i++){
int B = arrN[i];
arrA = (double *)calloc(sizeof(double), n*n);
arrB = (double *)calloc(sizeof(double), n*n);
arrC0 = (double *)calloc(sizeof(double), n*n);
arrC1 = (double *)calloc(sizeof(double), n*n);
arrC2 = (double *)calloc(sizeof(double), n*n);
arrA = assignMatVal(arrA,n,ubound,lbound);
arrB = assignMatVal(arrB,n,ubound,lbound);
arrC0 = assignMatVal(arrC0,n,ubound,lbound);
copyMatrix(arrC0,arrC1,n);
copyMatrix(arrC0,arrC2,n);
dgemm0(arrA,arrB,arrC1,n);
regCacheMat(arrA,arrB,arrC0,n,B);
findCorrectness(arrC0,arrC1,n);
free(arrA);
free(arrB);
free(arrC0);
free(arrC1);
free(arrC2);
}
return 0;
}
|
Markdown | UTF-8 | 4,592 | 3.34375 | 3 | [] | no_license | # Task 2
- [x] Which customer has made the most rentals at store 2?
Karl Seal
```SQL
WITH customers AS (
SELECT * FROM customer
WHERE store_id = 2
)
SELECT
COUNT(rental.customer_id) AS rentals,
customers.first_name,
customers.last_name
FROM rental JOIN customers
ON rental.customer_id = customers.customer_id
GROUP BY
customers.customer_id,
customers.first_name,
customers.last_name
ORDER BY rentals DESC
LIMIT 10;
```
- [x] A customer tried to rent 'Image Princess' from store 1 on 29/07/2005 at 3pm
but it was sold out. would he be able to rent it from store 2 if he tried?
Yes
```SQL
WITH image_princess AS (
SELECT film.title, inventory.store_id, inventory.inventory_id
FROM film JOIN inventory
ON film.film_id = inventory.film_id
WHERE title = 'Image Princess' AND store_id = 2
)
SELECT
image_princess.inventory_id,
image_princess.store_id,
rental.rental_date,
rental.return_date
FROM image_princess JOIN rental
ON image_princess.inventory_id = rental.inventory_id;
```
- [x] How many customers are active at any given month per year? We define active
as perfoming at least one rental during that month.
month | customers
------|----------
June 2005 | 2311
```SQL
WITH month_rental AS (
SELECT * FROM rental
WHERE EXTRACT(MONTH FROM rental_date) = 6 AND EXTRACT(YEAR FROM rental_date) = 2005
)
SELECT COUNT(month_rental.customer_id)
FROM month_rental JOIN customer
ON month_rental.customer_id = customer.customer_id;
```
- [x] Which film category is the most popular among our customers?
Sports => 1179 rentals
```SQL
WITH categorized_film AS (
SELECT category.name, film.film_id
FROM category
JOIN film_category
ON category.category_id = film_category.category_id
JOIN film
ON film_category.film_id = film.film_id
),
inventory_rental AS (
SELECT * FROM rental
JOIN inventory
ON rental.inventory_id = inventory.inventory_id
)
SELECT
COUNT(inventory_rental.rental_id) AS rentals,
categorized_film.name
FROM inventory_rental
JOIN categorized_film
ON categorized_film.film_id = inventory_rental.film_id
GROUP BY categorized_film.name
ORDER BY rentals DESC;
```
- [x] which film is the most popular in category 'Sports'?
title | total_rentals
------|--------------
'Gleaming Jawbreaker' | 29 rentals
```SQL
WITH sports_film AS (
SELECT film.film_id, film.title
FROM film
JOIN film_category
ON film_category.film_id = film.film_id
JOIN category
ON film_category.category_id = category.category_id
WHERE category.name = 'Sports'
),
inventory_rental AS (
SELECT * FROM rental
JOIN inventory
ON rental.inventory_id = inventory.inventory_id
)
SELECT
COUNT(inventory_rental.rental_id) AS rentals,
sports_film.title
FROM sports_film
JOIN inventory_rental
ON sports_film.film_id = inventory_rental.film_id
GROUP BY sports_film.title
ORDER BY rentals DESC;
```
- [x] Are there any other insights that you can gather from the data that would be helpful to the owner of the business?
- What are genres are bringing in the most income?
category | total_payments
---------|---------------
Sports | $4892.19
Sci-Fi | $4336.01
Animation | $4245.31
Drama | $4118.46
```SQL
WITH categorized_film AS (
SELECT category.name, film.film_id
FROM category
JOIN film_category
ON category.category_id = film_category.category_id
JOIN film
ON film.film_id = film_category.film_id
),
rental_payment AS (
SELECT payment.amount, inventory.film_id
FROM payment
JOIN rental
ON rental.rental_id = payment.rental_id
JOIN inventory
ON rental.inventory_id = inventory.inventory_id
)
SELECT
categorized_film.name,
SUM(rental_payment.amount) AS total_payments
FROM categorized_film
JOIN rental_payment
ON categorized_film.film_id = rental_payment.film_id
GROUP BY categorized_film.name
ORDER BY total_payments DESC;
```
This reveals that Sci-Fi films, for example, are bringing in more money than Action or Animation, despite being less popular. The owner of the business might use this data to inform future pricing decisions.
|
Python | UTF-8 | 614 | 3.140625 | 3 | [] | no_license | import threading
from threading import Thread
from time import sleep
nums = 0
def work1(num):
global nums
for x in range(num):
lock.acquire()
nums+=1
lock.release()
print("work1:"+str(nums))
def work2(num):
global nums
for x in range(num):
lock.acquire()
nums+=1
lock.release()
print("work2:"+str(nums))
# 创建锁
lock = threading.Lock()
t1 = Thread(target=work1,args=(1000000,))
t1.start()
t2 = Thread(target=work2,args=(1000000,))
t2.start()
while len(threading.enumerate()) !=1:
sleep(1)
print("最终的结果:"+str(nums)) |
PHP | UTF-8 | 1,015 | 3.53125 | 4 | [] | no_license | <?php
require_once 'base\AlgorithmBase.php';
//重复的子字符串-双指针
class Solution extends \algorithm\base\AlgorithmBase
{
function repeatedSubstringPattern($s) {
$len = strlen($s);
$l = 0;
$r = $len -1;
while($l < $r){
$left = substr($s,0,$l + 1);
$right = substr($s,$r);
if($left == $right){
echo $left.PHP_EOL;
if($len % ($l + 1) == 0){
$time = $len / ($l + 1);
$sub = '';
while($time > 0){
$sub .= $left;
$time--;
}
echo $sub.PHP_EOL;
if($sub == $s)
return true;
}
}
$l++;
$r--;
}
return false;
}
function test(){
echo($this->repeatedSubstringPattern('abab') ? '1':'0').PHP_EOL;
}
}
(new Solution())->test(); |
Java | UTF-8 | 6,827 | 1.5625 | 2 | [
"LGPL-3.0-only",
"Apache-2.0"
] | permissive | /*
* citygml4j - The Open Source Java API for CityGML
* https://github.com/citygml4j
*
* Copyright 2013-2020 Claus Nagel <claus.nagel@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.citygml4j.model.module;
import org.citygml4j.model.module.ade.ADEModule;
import org.citygml4j.model.module.ade.ADEModuleType;
import org.citygml4j.model.module.citygml.AppearanceModule;
import org.citygml4j.model.module.citygml.BridgeModule;
import org.citygml4j.model.module.citygml.BuildingModule;
import org.citygml4j.model.module.citygml.CityFurnitureModule;
import org.citygml4j.model.module.citygml.CityGMLModule;
import org.citygml4j.model.module.citygml.CityGMLModuleType;
import org.citygml4j.model.module.citygml.CityObjectGroupModule;
import org.citygml4j.model.module.citygml.CoreModule;
import org.citygml4j.model.module.citygml.GenericsModule;
import org.citygml4j.model.module.citygml.LandUseModule;
import org.citygml4j.model.module.citygml.ReliefModule;
import org.citygml4j.model.module.citygml.TexturedSurfaceModule;
import org.citygml4j.model.module.citygml.TransportationModule;
import org.citygml4j.model.module.citygml.TunnelModule;
import org.citygml4j.model.module.citygml.VegetationModule;
import org.citygml4j.model.module.citygml.WaterBodyModule;
import org.citygml4j.model.module.gml.GMLCoreModule;
import org.citygml4j.model.module.gml.GMLModule;
import org.citygml4j.model.module.gml.GMLModuleType;
import org.citygml4j.model.module.gml.XLinkModule;
import org.citygml4j.model.module.xal.XALCoreModule;
import org.citygml4j.model.module.xal.XALModule;
import org.citygml4j.model.module.xal.XALModuleType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Modules {
private static Map<String, Module> modules = new ConcurrentHashMap<>();
static {
for (Module module : CoreModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : AppearanceModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : BridgeModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : BuildingModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : CityFurnitureModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : CityObjectGroupModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : GenericsModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : LandUseModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : ReliefModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : TransportationModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : TunnelModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : VegetationModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : WaterBodyModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : TexturedSurfaceModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : GMLCoreModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : XLinkModule.getInstances()) modules.put(module.getNamespaceURI(), module);
for (Module module : XALCoreModule.getInstances()) modules.put(module.getNamespaceURI(), module);
}
private Modules() {
// just to thwart instantiation
}
public static Module getModule(String namespaceURI) {
return modules.get(namespaceURI);
}
public static List<Module> getModules() {
return new ArrayList<>(modules.values());
}
public static List<CityGMLModule> getCityGMLModules() {
return getModules(CityGMLModule.class);
}
public static CityGMLModule getCityGMLModule(String namespaceURI) {
return getModule(CityGMLModule.class, namespaceURI);
}
public static List<CityGMLModule> getCityGMLModules(CityGMLModuleType type) {
return getModules(CityGMLModule.class, type);
}
public static List<GMLModule> getGMLModules() {
return getModules(GMLModule.class);
}
public static List<GMLModule> getGMLModules(GMLModuleType type) {
return getModules(GMLModule.class, type);
}
public static List<XALModule> getXALModules() {
return getModules(XALModule.class);
}
public static List<XALModule> getXALModules(XALModuleType type) {
return getModules(XALModule.class, type);
}
public static void registerADEModule(ADEModule module) {
modules.put(module.getNamespaceURI(), module);
}
public static void unregisterADEModule(ADEModule module) {
modules.remove(module.getNamespaceURI());
}
public static List<ADEModule> getADEModules() {
return getModules(ADEModule.class);
}
public static List<ADEModule> getADEModules(ADEModuleType type) {
return getModules(ADEModule.class, type);
}
public static ADEModule getADEModule(String namespaceURI) {
return getModule(ADEModule.class, namespaceURI);
}
public static boolean isCityGMLModuleNamespace(String namespaceURI) {
return namespaceURI != null && namespaceURI.startsWith("http://www.opengis.net/citygml");
}
public static boolean isModuleNamespace(String namespaceURI, ModuleType type) {
Module module = modules.get(namespaceURI);
return module != null && module.getType().equals(type);
}
private static <T extends Module> T getModule(Class<T> moduleClass, String namespaceURI) {
Module module = modules.get(namespaceURI);
return moduleClass.isInstance(module) ? moduleClass.cast(module) : null;
}
private static <T extends Module> List<T> getModules(Class<T> moduleClass) {
List<T> result = new ArrayList<>();
for (Module module : modules.values()) {
if (moduleClass.isInstance(module))
result.add(moduleClass.cast(module));
}
return result;
}
private static <T extends Module> List<T> getModules(Class<T> moduleClass, ModuleType type) {
List<T> result = new ArrayList<>();
for (Module module : modules.values()) {
if (module.getType().equals(type) && moduleClass.isInstance(module))
result.add(moduleClass.cast(module));
}
return result;
}
}
|
Java | UTF-8 | 1,323 | 2.703125 | 3 | [] | no_license |
import consolaAdministracion.controlador.ControladorAS;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Fernando
*/
public class HiloServidor extends Thread {
ServerSocket servidor;
boolean parar;
ControladorAS cas;
public HiloServidor(ControladorAS cas) throws IOException {
this.servidor = new ServerSocket(6000);
parar = false;
this.cas = cas;
}
@Override
public void run() {
try {
while (!parar) {
Socket cliente = new Socket();
cliente = servidor.accept();
System.out.println("cliente conectado");
HiloCliente hilo = new HiloCliente(cliente,cas);
hilo.start();
}
} catch (IOException ex) {
Logger.getLogger(HiloServidor.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void Parar(boolean parar) {
this.parar = parar;
}
}
|
Python | UTF-8 | 997 | 2.859375 | 3 | [] | no_license | N, A, B, C, D = map(int, input().split())
S = '$' + input() + '$'
def isOk(fr, to):
if S[fr: to + 1].count('##') > 0:
return False
return True
if not (isOk(A, C) and isOk(C, D)):
print('No')
exit()
def canSwitch():
if A + 1 == B and D < C and S[A: A + 3] == '...':
return True
if B + 1 == A and C < D and S[B: B + 3] == '...':
return True
if C + 1 == D and B < A and S[C - 1: D + 1] == '...':
return True
if D + 1 == C and A < B and S[D - 1: C + 1] == '...':
return True
if A < B and S[B - 1: B + 2] == '...':
return True
if B < A and S[A - 1: A + 2] == '...':
return True
if C < D and S[C - 1: C + 2] == '...':
return True
if D < C and S[D - 1: D + 2] == '...':
return True
if S[max(A, B): min(C, D) + 1].count('...'):
return True
return False
if A < B and D < C or B < A and C < D:
if not canSwitch():
print('No')
exit()
print('Yes')
|
Java | UTF-8 | 893 | 2.71875 | 3 | [] | no_license | package GameView;
import javax.sound.sampled.*;
import java.io.File;
public class BackgroundMusic {
private Clip clip;
public BackgroundMusic(String filepath) {
try {
AudioInputStream audio = AudioSystem.getAudioInputStream(new File(filepath).getAbsoluteFile());
clip = AudioSystem.getClip();
clip.open(audio);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void play() {
if (clip == null) {
return;
}
stop();
clip.setFramePosition(0);
clip.start();
}
public void stop() {
if (clip.isRunning()) {
clip.stop();
}
}
public void close() {
stop();
clip.close();
}
public Clip getClip() {
return clip;
}
}
|
C++ | UTF-8 | 1,065 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include "product.h"
using namespace std;
AbstractProduct::AbstractProduct()
{
}
AbstractProduct::~AbstractProduct()
{
}
std::string AbstractProduct::GetProductName()
{
return name;
}
AbstractProduct1::AbstractProduct1()
{
}
AbstractProduct1::~AbstractProduct1()
{
}
AbstractProduct2::AbstractProduct2()
{
}
AbstractProduct2::~AbstractProduct2()
{
}
ConcreteProduct1A::ConcreteProduct1A()
{
name = "ConcreteProduct1A";
cout<<"create ConcreteProduct1A"<<endl;
}
ConcreteProduct1A::~ConcreteProduct1A()
{
}
ConcreteProduct1B::ConcreteProduct1B()
{
name = "ConcreteProduct1B";
cout<<"create ConcreteProduct1B"<<endl;
}
ConcreteProduct1B::~ConcreteProduct1B()
{
}
ConcreteProduct2A::ConcreteProduct2A()
{
name = "ConcreteProduct2A";
cout<<"create ConcreteProduct2A"<<endl;
}
ConcreteProduct2A::~ConcreteProduct2A()
{
}
ConcreteProduct2B::ConcreteProduct2B()
{
name = "ConcreteProduct2B";
cout<<"create ConcreteProduct2B"<<endl;
}
ConcreteProduct2B::~ConcreteProduct2B()
{
} |
Python | UTF-8 | 196 | 3.25 | 3 | [] | no_license | class cilent:
def __init__(self):
print('-- class demotations with constructor --')
# variables
x =100
y ='string'
obj = cilent()
print(obj.x)
print(obj.y)
|
C++ | UTF-8 | 1,261 | 3.390625 | 3 | [] | no_license | #include "Country.h"
#include <cassert>
Country::Country(){
}
Country::~Country(){
}
int Country::get_id() {
return this->id;
}
Country Country::set_id(int id) {
this->id = id;
return *this;
}
int Country::get_emperor() {
return this->emperor;
}
Country Country::set_emperor(int emperor) {
this->emperor = emperor;
return *this;
}
string Country::get_name() {
return this->name;
}
Country Country::set_name(const string& name) {
this->name = name;
return *this;
}
CommonSet<int> Country::get_citys() {
return this->citys;
}
Country Country::set_citys(const CommonSet<int>& citys) {
this->citys = citys;
return *this;
}
int Country::add_city(int city) {
assert(!(this->citys.contains(city)));
this->citys.add(city);
return this->citys.size();
}
int Country::add_citys(const CommonSet<int>& citys) {
for(auto city : citys) {
assert(!(this->citys.contains(city)));
this->citys.add(city);
}
return this->citys.size();
}
int Country::remove_city(int city) {
assert(this->citys.contains(city));
this->citys.remove(city);
return this->citys.size();
}
int Country::remove_citys(const CommonSet<int>& citys) {
for(auto city : citys) {
assert(this->citys.contains(city));
this->citys.add(city);
}
return this->citys.size();
} |
Python | UTF-8 | 21,961 | 2.75 | 3 | [] | no_license | '''
Byron C Wallace
Tufts Medical Center: Computational and Analytic Evidence Sythensis
tuftscaes.org/curious_snake
Curious Snake: Active Learning in Python
co_feature_learning.py
---
This class implements a co-testing algorithm based on labeled features.
In particular, it maintains a list of features designated as
+ or -; these are then used in AL. Specifically, the examples picked for
labeling are those for which the feature labels disagree with the current
model's prediction.
'''
import pdb
import simple_svm_learner
from simple_svm_learner import *
import math
import os
from operator import itemgetter
class CoFeatureLearner(SimpleLearner):
def __init__(self, pos_terms_f, neg_terms_f, wlist_index, raw_abstract_text_dir, raw_title_text_dir,
unlabeled_datasets = None, models=None, undersample_before_eval = False, beta=.01, r=100, pc=.2):
#
# call the SimpleLearner constructor to initialize various globals
SimpleLearner.__init__(self, unlabeled_datasets=unlabeled_datasets, models=models,
undersample_before_eval = undersample_before_eval)
self.name = "CoFeature"
print "assuming pc is %s!!!" % pc
self.pc = pc
# read
print "assuming compound terms are first!!!"
self.pos_terms = eval(open(pos_terms_f, 'r').readline())
self.neg_terms = eval(open(neg_terms_f, 'r').readline())
self.raw_abs_dir = raw_abstract_text_dir
self.raw_titles_dir = raw_title_text_dir
self.beta= beta
print "reading word list: %s" % wlist_index
self.w_index = eval(open(wlist_index, 'r').readline())
self.m = len(self.w_index) # count terms
print "BAM"
self.query_function= self.cotest
# for memoization
self.texts = {}
self.psuedo_lbls = {} # as determined by feature voting
self.feature_votes={}
self.feature_scores={}
self.np= None
self.pp= None
# better way to estimate these?
# just using uniform weights...
self.alpha_n = None
self.alpha_p = None
self.r = r
self.compute_ps()
def cofl_al(self, k):
unlabeled_dataset = self.unlabeled_datasets[0]
k_ids_to_scores = {}
for x_id in unlabeled_dataset.instances.keys()[:k]:
k_ids_to_scores[x_id] = self.score(x_id)
# now iterate over the rest
for x_id in unlabeled_dataset.instances.keys()[k:]:
cur_min_id, cur_min_score = self._get_min_val_key_tuple(k_ids_to_scores)
x_score= self.score(x_id)
if x_score > cur_min_score:
# then x is closer to the hyperplane than the farthest currently observed
# remove current max entry from the dictionary
k_ids_to_scores.pop(cur_min_id)
k_ids_to_scores[x_id] = x_score
return k_ids_to_scores.keys()
def cotest(self, k):
unlabeled_dataset = self.unlabeled_datasets[0]
# the scores can be the magnitude of the feature vote, given
# the disagreement.
k_ids_to_scores = {}
count = 0
min_max_mag = 0
min_max_id = None
for x_id in unlabeled_dataset.instances.keys()[k:]:
fvote, mag = self.feature_vote(x_id)
if fvote != self.predict(x_id) and self.get_N(x_id) != 0 and not self.not_sure(x_id):
if count < k:
k_ids_to_scores[x_id] = mag
count+=1
elif mag > min_max_mag:
k_ids_to_scores.pop(min_max_id)
k_ids_to_scores[x_id] = mag
min_max_id, min_max_mag = self._get_min_val_key_tuple(k_ids_to_scores)
disagreements = k_ids_to_scores.keys()
print "\n\ntotal disagreements: %s" % count
print "magnitude of disagreements: %s" % " ".join([str(x) for x in k_ids_to_scores.values()])
if count == k:
return disagreements
print "using SIMPLE for %s examples" % (k-count)
disagreements.extend(self.SIMPLE(k-count, do_not_pick=list(disagreements)))
return disagreements
def score(self, x_id):
return self.feature_score(x_id)
def get_N(self, x_id):
text = self.texts[x_id]
neg_score, text, terms = self.count_terms(text, self.neg_terms)
pos_score, text, terms = self.count_terms(text, self.pos_terms)
N = pos_score + neg_score
return N
def has_a_term(self, x_id):
if not self.texts.has_key(x_id):
self.load_text(x_id)
text = self.texts[x_id]
neg_score, text, terms = self.count_terms(text, self.neg_terms)
pos_score, text, terms = self.count_terms(text, self.pos_terms)
return (pos_score > 0 or neg_score > 0)
def not_sure(self, x_id):
text = self.texts[x_id]
neg_score, text, terms = self.count_terms(text, self.neg_terms)
pos_score, text, terms = self.count_terms(text, self.pos_terms)
return (pos_score == neg_score)
def feature_score(self, x_id):
# vote based on labeled features
# note, if a token is part of a negative phrase (e.g., 'beam' in
# 'photon beam'), this shouldn't be counted as positive
# only need to feature vote once. do it at the start.
if not x_id in self.feature_scores.keys():
if not self.texts.has_key(x_id):
self.load_text(x_id)
text = self.texts[x_id]
neg_score, text = self.count_terms(text, self.neg_terms)
pos_score, text = self.count_terms(text, self.pos_terms)
N = pos_score + neg_score
self.feature_scores[x_id] = N - abs(pos_score - neg_score)
return self.feature_scores[x_id]
def uncertainty(self, k):
unlabeled_dataset = self.unlabeled_datasets[0]
# the scores can be the magnitude of the feature vote, given
# the disagreement.
k_ids_to_scores = {}
count = 0
max_min_mag = 0
max_min_id = None
for x_id in unlabeled_dataset.instances.keys()[k:]:
if self.has_a_term(x_id):
fvote, odds_ratio = self.feature_vote(x_id)
score = abs(1-odds_ratio)
if count < k:
k_ids_to_scores[x_id] = score
count+=1
elif score <= max_min_mag:
k_ids_to_scores.pop(max_min_id)
k_ids_to_scores[x_id] = score
max_min_id, max_min_mag = self._get_max_val_key_tuple(k_ids_to_scores)
print "values: "
#pdb.set_trace()
print k_ids_to_scores.values()
return k_ids_to_scores.keys()
def doc_length(self, x_id):
if not self.texts.has_key(x_id):
self.load_text(x_id)
text = self.texts[x_id]
return len(text.split(" "))
def feature_vote(self, x_id, include_direction=True, scaled=True):
# returns vote, odds ratio
# note, if a token is part of a negative phrase (e.g., 'beam' in
# 'photon beam'), this shouldn't be counted as positive
# only need to feature vote once. do it at the start.
if not x_id in self.feature_votes.keys():
if not self.texts.has_key(x_id):
self.load_text(x_id)
text = self.texts[x_id]
neg_score, text, neg_terms_found = self.count_terms(text, self.neg_terms)
pos_score, text, pos_terms_found = self.count_terms(text, self.pos_terms)
#pdb.set_trace()
# psuedo counts
neg_score+=1
pos_score+=1
total_terms_found = len(neg_terms_found) + len(pos_terms_found)
odds_ratio = 0
if pos_score >= neg_score:
odds_ratio = float(pos_score)/float(neg_score)
self.feature_votes[x_id] = (1, odds_ratio)
else:
odds_ratio = float(neg_score)/float(pos_score)
self.feature_votes[x_id] = (-1, odds_ratio)
if not include_direction:
if neg_score==1 and pos_score == 1:
# no terms
#return None
return 0
odds_ratio = float(pos_score)/float(neg_score)
if not scaled:
self.feature_votes[x_id] = abs(math.log(odds_ratio))
else:
# scale by the feature count
self.feature_votes[x_id] =total_terms_found *abs(math.log(odds_ratio))
return self.feature_votes[x_id]
def count_terms(self, doc, term_list, count_terms_only_once=True):
t_count = 0
terms_found = []
#doc_sp = doc.split(" ")
for t in term_list:
if t in doc:
if count_terms_only_once:
t_count += 1
else:
t_count += doc.count(t)
doc.replace(t, "")
terms_found.append(t)
return [t_count, doc, terms_found]
def lpool(self, x_id):
if not x_id in self.feature_votes.keys():
if not self.texts.has_key(x_id):
self.load_text(x_id)
text = self.texts[x_id]
neg_score, text, neg_terms_found = self.count_terms(text, self.neg_terms)
pos_score, text, pos_terms_found = self.count_terms(text, self.pos_terms)
unlabeled_terms = len(text.split(" "))
# p1_pos = sum([math.log(self.alpha_p*self.pp) for w_i in pos_terms_found])
# p1_neg = sum([self.alpha_n*self.pn for w_i in neg_terms_found])
# need also to add in the remaining (unlabeled) terms
# This is how they compute the p in Melville, et. al
#(math.log(self.pc) +\
p_pos = -1.0*sum([math.log(self.pp) for w_i in pos_terms_found] +\
[math.log(self.n_given_p) for w_i in neg_terms_found] +\
[math.log(self.pp_unknown) for w_i in xrange(unlabeled_terms)])
#*(math.log(1-self.pc) +\
p_neg = -1.0*sum([math.log(self.pn) for w_i in neg_terms_found] +\
[math.log(self.p_given_n) for w_i in pos_terms_found] +\
[math.log(self.pn_unknown) for w_i in xrange(unlabeled_terms)])
'''
# this does poorly -- huge accuracy, terrible sensitivity
p_pos = -1.0* sum([math.log(self.alpha_p*self.pp) for w_i in pos_terms_found] +\
[math.log(self.alpha_n*self.n_given_p) for w_i in neg_terms_found]) #+\
#[math.log(self.pp_unknown) for w_i in xrange(unlabeled_terms)])
p_neg = -1.0 * sum([math.log(self.alpha_n*self.pn) for w_i in neg_terms_found] +\
[math.log(self.alpha_p*self.p_given_n) for w_i in pos_terms_found]) #+\
#[math.log(self.pn_unknown) for w_i in xrange(unlabeled_terms)])
'''
#p_pos = -1.0* (sum([math.log(self.pp) for w_i in pos_terms_found] +\
# [math.log(self.n_given_p) for w_i in neg_terms_found]))
#p_neg = -1.0 * (sum([math.log(self.pn) for w_i in neg_terms_found] +\
# [math.log(self.p_given_n) for w_i in pos_terms_found]))
# meanwhile, this seems to do well... why?
# p_pos = -1.0*sum([math.log(self.alpha_p*self.pp) for w_i in pos_terms_found])
# p_neg = -1.0*sum([math.log(self.alpha_n*self.pn) for w_i in neg_terms_found])
if p_pos > p_neg:
#pdb.set_trace()
#print "(+)"
self.feature_votes[x_id] = (1, abs(p_pos-p_neg))
else:
self.feature_votes[x_id] = (-1, abs(p_pos-p_neg))
return self.feature_votes[x_id]
def linear_pool(self, k):
# co-testing with linear pooling basically
unlabeled_dataset = self.unlabeled_datasets[0]
# the scores can be the magnitude of the feature vote, given
# the disagreement.
k_ids_to_scores = {}
count = 0
min_max_mag = 0
min_max_id = None
for x_id in unlabeled_dataset.instances.keys()[k:]:
fvote, mag = self.lpool(x_id)
if fvote != self.predict(x_id) and self.get_N(x_id) != 0 and not self.not_sure(x_id):
if count < k:
k_ids_to_scores[x_id] = mag
count+=1
elif mag > min_max_mag:
k_ids_to_scores.pop(min_max_id)
k_ids_to_scores[x_id] = mag
min_max_id, min_max_mag = self._get_min_val_key_tuple(k_ids_to_scores)
disagreements = k_ids_to_scores.keys()
#print ""
print "\n\ntotal disagreements: %s" % count
print "magnitude of disagreements: %s" % " ".join([str(x) for x in k_ids_to_scores.values()])
if count == k:
return disagreements
print "using SIMPLE for %s examples" % (k-count)
disagreements.extend(self.SIMPLE(k-count, do_not_pick=list(disagreements)))
return disagreements
def compute_ps(self):
p = float(len(self.pos_terms))
n = float(len(self.neg_terms))
self.pp = 1.0/float(p + n)
self.pn = 1.0/float(p + n)
# probability of a positive term appearing in a negative doc
self.p_given_n = self.pp * 1/self.r
# and vice versa
self.n_given_p = self.pn * 1/self.r
self.alpha_n = 1/float(n)
self.alpha_p = 1/float(p)
#
# This says the probability of seeing an unlabeled term
# in the respective documents is different, which I don't like.
# In particular, p is larger than n (more + than - terms) so
# problem: p(w_u | +) is << p(w_u | -). This strongly affects
# the probability -- so even when there are more terms
self.pp_unknown = (n*(1-1/self.r))/ ((p + n) * (self.m-p-n))
self.pn_unknown = (p*(1-1/self.r))/ ((p + n) * (self.m-p-n))
def multi_nom(self, doc):
pass
def load_text(self, x_id):
ti_text = open(os.path.join(self.raw_titles_dir, str(x_id)), 'r').readline().lower()
ab_text = open(os.path.join(self.raw_abs_dir, str(x_id)), 'r').readline().lower()
self.texts[x_id] = " ".join([ti_text, ab_text])
def co_train(self):
#psuedo_pos=[]
#psuedo_neg=[]
psuedo_pos_d={}
psuedo_neg_d={}
print "Co-training?"
pdb.set_trace()
for x_id in self.unlabeled_datasets[0].instances.keys():
direction, mag = self.feature_vote(x_id)
#if mag > self.beta:
if direction > 0:
#psuedo_pos.append(x_id)
psuedo_pos_d[x_id] = mag
else:
psuedo_neg_d[x_id] = mag
#psuedo_neg.append(x_id)
psuedo_pos = [x[0] for x in sorted(psuedo_pos_d.items(), key=itemgetter(1), reverse=True)]
psuedo_neg = [x[0] for x in sorted(psuedo_neg_d.items(), key=itemgetter(1), reverse=True)]
p = self.beta#/2.0
this_many = int(p*len(self.unlabeled_datasets[0]))
psuedo_pos = psuedo_pos[:this_many]
#psuedo_neg = psuedo_neg[:this_many]
# First, set the labels to the prediction from the naive
# stump -- i.e., feature voting
print "psuedo labeling %s positives, %s negatives" % (len(psuedo_pos), len(psuedo_neg))
for d in self.unlabeled_datasets:
d.set_labels(psuedo_pos, 1)
#d.set_labels(psuedo_neg, -1)
# Next, 'label' all of the instances -- but note that
# the label that will be used is the predicted label, *not*
# the true label (necessarily) so this isn't cheating
all_instances = psuedo_pos #+ psuedo_neg
self.label_instances(all_instances)
return all_instances
def rebuild_models(self, for_eval=False, verbose=True, undersample_these=None,
do_grid_search=False, beta=10):
'''
Rebuilds all models over the current labeled datasets. If for_eval is true,
we undersample if this learner is set to undersample before evaluation.
Returns a list of the undersampled ids (if any).
'''
dataset = None
undersampled_ids = []
# here we label the examples we're most confident about
# -- i.e., we co-train
if for_eval and False:
psuedo_labeled = self.co_train()
if self.undersample_before_eval and for_eval:
if verbose:
print "%s: undersampling (using %s) before building models.." % (self.name, self.undersample_function.func_name)
#
# @experimental 9/23
# Here we're assuming the undersample function accepts an 'undersample_these'
# parameter. You should implement a diffferent, more flexible strategy to allow this
#
if self.undersample_function.__name__ == "undersample_labeled_datasets":
print ">> warning -- we're making assumptions about the undersample function being used here"
datasets = self.undersample_function(undersample_these=undersample_these)
else:
datasets = self.undersample_function()
undersampled_ids = list(set(self.labeled_datasets[0].instances.keys()) - set(datasets[0].instances.keys()))
else:
datasets = self.labeled_datasets
if verbose:
print "training model(s) on %s instances" % datasets[0].size()
self.models = []
for dataset, param in zip(datasets, self.params):
samples, labels = dataset.get_samples_and_labels()
try:
problem = svm_problem(labels, samples)
except:
pdb.set_trace()
#
# @TODO if an rbf kernel is being used for this param
# we should do a grid search here for parameters (maybe if only for_eval)
#
param = svm_parameter(kernel_type = self.kernel_type, weight = self.weights)
if do_grid_search:
print "running grid search..."
C, gamma = grid_search(problem, param, linear_kernel=(self.kernel_type==LINEAR), beta=beta)
print "done. best C, gamma: %s, %s" % (C, gamma)
param = svm_parameter(kernel_type = self.kernel_type, weight = self.weights,
C=C, gamma=gamma)
else:
print "not doing grid search."
model = svm_model(problem, param)
self.models.append(svm_model(problem, param))
if for_eval and False:
# now, 'unlabel' the examples psuedo-labeled during co-training
self.unlabel_instances(psuedo_labeled)
# and, finally, now that they're unlabeled again, revert their label
# back to the true label
for d in self.unlabeled_datasets:
d.revert_to_true_labels(psuedo_labeled)
#
# Return the ids of the instances that were undersampled,
# i.e., thrown away. This is in case you want to undersample
# the same examples in every learner (you undersample for one
# learner then throw the same majority examples away for the
# others.
return undersampled_ids
def SIMPLE(self, k, do_not_pick=None):
'''
Returns the instance numbers for the k unlabeled instances closest the hyperplane.
'''
# randomly flip an m-sided coin (m being the number of feature spaces)
# and pick from this space
feature_space_index = random.randint(0, len(self.models)-1)
model = self.models[feature_space_index]
dataset = self.unlabeled_datasets[feature_space_index]
return self._SIMPLE(model, dataset, k, do_not_pick=do_not_pick)
|
Markdown | UTF-8 | 392 | 2.5625 | 3 | [] | no_license | # BERT-Emotion-Classifier
This code uses a pretrained BERT model to learn how to classify text by emotions. In this specific case it will be tweets, but it can be used with any series of texts. The training, validation and test data has been attached, but the tweets file was too large to attach. The end result of the analysis is a chart representing the percentage of each emotion by time.
|
C++ | UTF-8 | 3,097 | 2.9375 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <iostream>
#include <vector>
#include "gameOfLifeLib.h"
TEST(TestGameOfLife, isAliveExpectTrue) {
EXPECT_TRUE(isAlive('*'));
}
TEST(TestGameOfLife, isAliveExpectFalse) {
EXPECT_FALSE(isAlive('.'));
}
TEST(TestGameOfLife, getLiveRowNeighborsExpectTwo) {
std::vector<char> row = {'*', '*', '*'};
EXPECT_EQ(2, getLiveRowNeighbors(row, 1));
}
TEST(TestGameOfLife, getLiveRowNeighborsExpectZero) {
std::vector<char> row = {'.', '*', '.'};
EXPECT_EQ(0, getLiveRowNeighbors(row, 1));
}
TEST(TestGameOfLife, getAboveLiveRowNeighborsExpectThree) {
std::vector<std::vector<char>> grid = {{'.', '*', '*', '*'},
{'.', '.', '*', '.'},
{'*', '*', '.', '.'}};
EXPECT_EQ(3, getAboveLiveRowNeighbors(grid, 2, 1));
}
TEST(TestGameOfLife, getAboveLiveRowNeighborsExpectZero) {
std::vector<std::vector<char>> grid = {{'.', '.', '.', '.'},
{'.', '.', '*', '.'},
{'*', '*', '.', '.'}};
EXPECT_EQ(0, getAboveLiveRowNeighbors(grid, 2, 1));
}
TEST(TestGameOfLife, getBelowLiveRowNeighborsExpectThree) {
std::vector<std::vector<char>> grid = {{'.', '.', '.', '.'},
{'.', '.', '*', '.'},
{'*', '*', '*', '*'}};
EXPECT_EQ(3, getBelowLiveRowNeighbors(grid, 2, 1));
}
TEST(TestGameOfLife, getBelowLiveRowNeighborsExpectZero) {
std::vector<std::vector<char>> grid = {{'.', '.', '.', '.'},
{'.', '.', '*', '.'},
{'*', '.', '.', '.'}};
EXPECT_EQ(0, getBelowLiveRowNeighbors(grid, 2, 1));
}
TEST(TestGameOfLife, getLiveNeighborsExpectEight) {
std::vector<std::vector<char>> grid = {{'.', '*', '*', '*'},
{'.', '*', '*', '*'},
{'*', '*', '*', '*'}};
EXPECT_EQ(8, getLiveNeighbors(grid, 2, 1));
}
TEST(TestGameOfLife, getLiveNeighborsExpectZero) {
std::vector<std::vector<char>> grid = {{'.', '.', '.', '.'},
{'.', '.', '*', '.'},
{'*', '.', '.', '.'}};
EXPECT_EQ(0, getLiveNeighbors(grid, 2, 1));
}
TEST(TestGameOfLife, getNextIterationExpectOneNewLivingCell) {
std::vector<std::vector<char>> grid0 = {{'.', '.', '.', '.'},
{'.', '*', '*', '.'},
{'.', '*', '.', '.'}};
std::vector<std::vector<char>> grid1 = getNextIteration(grid0);
std::vector<std::vector<char>> expectedGrid1 = {{'.', '.', '.', '.'},
{'.', '*', '*', '.'},
{'.', '*', '*', '.'}};
for (int i=0; i < (expectedGrid1.size()-1); i++) {
for (int j=0; j < (expectedGrid1[i].size()-1); j++) {
EXPECT_EQ(expectedGrid1[i][j], grid1[i][j]);
}
}
}
|
Python | UTF-8 | 902 | 2.84375 | 3 | [
"MIT"
] | permissive | import argparse
import os
import torch
import torchaudio
from tqdm import tqdm
from utils import find_files, print_metadata
def process_file(f):
"""
Simple but effective method to remove audio files that are silence.
Check the sum of the absolute value of the Tensor, delete the file if its sum is 0.
"""
try:
audio, original_sr = torchaudio.load(f)
if audio.abs().sum() == 0:
os.remove(f)
return 1
return 0
except Exception as e:
print_metadata(f)
raise e
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--dataset_path", required=True)
args = ap.parse_args()
files = list(find_files(args.dataset_path))
total_removed = 0
for f in tqdm(files):
total_removed += process_file(f)
print(f"Removed {total_removed} files from {args.dataset_path}")
|
C++ | UTF-8 | 2,893 | 3.375 | 3 | [] | no_license | #include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
struct Student
{
int id;
int c;
int m;
int e;
int a; // average
int best; // best rank
char bestCourse;
};
bool compA(const Student&l, const Student& r)
{
return l.a > r.a;
}
bool compC(const Student&l, const Student& r)
{
return l.c > r.c;
}
bool compM(const Student&l, const Student& r)
{
return l.m > r.m;
}
bool compE(const Student&l, const Student& r)
{
return l.e > r.e;
}
int main()
{
int n, m;
scanf("%d%d", &n, &m);
vector<Student>v;
v.resize(n);
for (int i = 0; i < n; i ++)
{
Student student;
scanf("%d%d%d%d",
&student.id, &student.c,
&student.m, &student.e);
student.a = (student.c + student.m + student.e) / 3;
student.best = 1000;
student.bestCourse = '0';
v[i] = student;
}
// by average
sort(v.begin(), v.end(), compA);
int curGrade = 1;
int curScore = v[0].a;
for (int i = 0; i < n; i++)
{
if (v[i].a < curScore)
{
curGrade = i + 1;
curScore = v[i].a;
}
if (v[i].best > curGrade)
{
v[i].best = curGrade;
v[i].bestCourse = 'A';
}
}
// by c programming
sort(v.begin(), v.end(), compC);
curGrade = 1;
curScore = v[0].c;
for (int i = 0; i < n; i++)
{
if (v[i].c < curScore)
{
curGrade = i + 1;
curScore = v[i].c;
}
if (v[i].best > curGrade)
{
v[i].best = curGrade;
v[i].bestCourse = 'C';
}
}
// by math
sort(v.begin(), v.end(), compM);
curGrade = 1;
curScore = v[0].m;
for (int i = 0; i < n; i++)
{
if (v[i].m < curScore)
{
curGrade = i + 1;
curScore = v[i].m;
}
if (v[i].best > curGrade)
{
v[i].best = curGrade;
v[i].bestCourse = 'M';
}
}
// by English
sort(v.begin(), v.end(), compE);
curGrade = 1;
curScore = v[0].e;
for (int i = 0; i < n; i++)
{
if (v[i].e < curScore)
{
curGrade = i + 1;
curScore = v[i].e;
}
if (v[i].best > curGrade)
{
v[i].best = curGrade;
v[i].bestCourse = 'E';
}
}
while (0 < m--)
{
int obj;
scanf("%d", &obj);
int i;
for (i = 0; i < n; i ++)
{
if (obj == v[i].id)
{
printf("%d %c\n", v[i].best,
v[i].bestCourse);
break;
}
}
// not found
if(i == n)
{
printf("N/A\n");
}
}
return 0;
}
|
Markdown | UTF-8 | 758 | 2.8125 | 3 | [] | no_license | # RD5-Assignment
## 註冊
1. 欄位不得為空
1. 身份證字號不可與其他使用者相同
1. 網銀密碼大於8個字元,需含大小寫與數字

## 登入
1. 欄位不得為空
1. 所有欄位需完全符合才可登入

## 首頁
1. 顯示使用者代號與餘額
1. 點擊餘額可隱藏金額

## 提款
1. 欄位只能為數字,否則會報錯
1. 若提款超出存款會提款失敗並跳出提示

## 存款
欄位只能為數字,否則會報錯

## 查詢明細
1. 可查看存款與提款的歷史紀錄
2. 若超過10筆會自動新增頁數

|
Swift | UTF-8 | 2,880 | 2.6875 | 3 | [] | no_license | //
// YouTube.swift
// Quipo
//
// Created by Mikhail Yakushin on 11/4/15.
// Copyright © 2015 Mikhail Yakushin. All rights reserved.
//
import Foundation
import SwiftyJSON
import Bolts
import Alamofire
struct YouTube {
static var sharedInstance = YouTube()
var currentTrailerId: String?
var currentThumbnailURL: String?
var currenVideoDuration: String?
private func getReformattedVideoDuration(rawVideoDuration: String) -> String {
let dateFormatter = NSDateFormatter()
if rawVideoDuration.characters.contains("M") {
dateFormatter.dateFormat = "'PT'm'M'ss'S'"
let date = dateFormatter.dateFromString(rawVideoDuration)
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Minute, .Second], fromDate: date!)
return ("\(comp.minute):\(comp.second)")
} else {
dateFormatter.dateFormat = "'PT'ss'S'"
let date = dateFormatter.dateFromString(rawVideoDuration)
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Second], fromDate: date!)
return ("0:\(comp.second)")
}
}
func getMovieTrailerWithMovieTitle(movieName: String, releasedIn: String) -> BFTask {
let mainTask = BFTaskCompletionSource()
Alamofire.request(.GET, "https://www.googleapis.com/youtube/v3/search", parameters: [
"key": "AIzaSyDRxPGszcdOWx4BgtzSUhQ0F31_CqT4bXY",
"part" : "snippet",
"maxResults" : 1,
"type" : "video",
// "videoCategoryId" : "44", // 44 - restricts search results to trailers only
"regionCode" : "US",
"q" : movieName + " " + releasedIn + "trailer"
]
).responseJSON { (response: Response<AnyObject, NSError>) -> Void in
if let responseValue = response.result.value {
let json = JSON(responseValue)
let trailerId = json["items"][0]["id"]["videoId"].stringValue
let thumbnailURL = json["items"][0]["snippet"]["thumbnails"]["default"]["url"].stringValue
Alamofire.request(.GET, "https://www.googleapis.com/youtube/v3/videos", parameters: [
"key": "AIzaSyDRxPGszcdOWx4BgtzSUhQ0F31_CqT4bXY",
"part" : "contentDetails",
"maxResults" : 1,
"type" : "video",
"videoCategoryId" : "44",
"regionCode" : "US",
"id" : trailerId
]
).responseJSON { (response: Response<AnyObject, NSError>) -> Void in
if let responseValue = response.result.value {
let contentDetailsJSON = JSON(responseValue)
let videoDuration = contentDetailsJSON["items"][0]["contentDetails"]["duration"].stringValue
let reformattedVideoDuration = self.getReformattedVideoDuration(videoDuration)
mainTask.setResult([trailerId, thumbnailURL, reformattedVideoDuration])
}
}
}
}
return mainTask.task
}
} |
PHP | UTF-8 | 6,260 | 2.9375 | 3 | [] | no_license | <?php
/**
* On vérifie la présence du $_GET['formMailUsernameValue'], si il existe on stocke dans la
* variable $responseAjaxMessage le retour que l'on va renvoyé au javascript
*/
if (isset($_GET['formMailUsernameValue'])) {
$responseAjaxMessage = '';
/**
* ON vérifie que les données récupérées ne sont pas vide, si elle ne sont pas vide,
* on include les fichier dont on va avoir besoin pour faire notre requête.
* Puis on instancie un objet $user à partir de notre class users.
* On donne ensuite aux attributs username et mail la valeur entrée par l'utilisateur
* On stocke ensuite dans une variable $mailExist le retour de notre méthode checkmail
* de notre objet $user et dans une variable $usernameExist le retour de notre méthode
* checkUsername de notre objet user. Si les données récupérer sont vide on stocke dans
* notre variable de réponse un message.
*/
if (!empty($_GET['formMailUsernameValue'])) {
include_once '../helpers/const.php';
include_once '../models/database.php';
include_once '../models/users.php';
$user = new users();
$user->username = $user->mail = htmlspecialchars($_GET['formMailUsernameValue']);
$mailExist = $user->checkMail();
$usernameExist = $user->checkUsername();
/**
* Si l'envoie de données saisies par l'utilisateur ne correspondent ni à un mail ou a un
* nom d'utilisateur on stocke un autre message dans notre variable de réponse.
*/
if (!$usernameExist->usernameExist && !$mailExist->mailExist) {
$responseAjaxMessage = 'Nom d\'utilisateur ou adresse mail non valide.';
}
} else {
$responseAjaxMessage = 'Veulliez remplir un nom d\'utilisateur ou une adresse mail.';
}
//On envoie le message stocké dans notre variable de réponse via un echo à notre javascript.
echo $responseAjaxMessage;
//Sinon si il n'y a pas d'ajax
} else {
/**
* Si le formulaire de connection a bien été envoyé(si $_GET['submitForm'] existe bien).
* On instancie un nouvel objet $user à partir de notre class users
*/
if (isset($_POST['submitForm'])) {
$user = new users();
/**
* Si notre champ mailUsername n'est pas vide lors de l'envoie alors on stocke
* dans nos attribut username et mail la valeur de la donnée saisie par l'utilisateur.
* Sinon on associe un message d'erreur à la clé mailUsername de notre tableau $formErrors.
*/
if (!empty($_POST['mailUsername'])) {
$user->mail = $user->username = htmlspecialchars($_POST['mailUsername']);
} else {
$formErrors['mailUsername'] = 'Veulliez remplir un nom d\'utilisateur ou une adresse mail.';
}
/**
* On vérifie que l'utilisateur a bien rempli le champ mot de passe.
* Si il ne l'as pas fait on associe un message d'erreur à la clé password de notre tableau $formErrors.
*/
if (empty($_POST['password'])) {
$formErrors['password'] = 'Veulliez remplir votre mot de passe.';
}
/**
* Si jamais l'utilisateur n'as pas commis une des erreur ci-dessus.
* On stocke dans la variable $userInfo le retour de notre méthode getInfoUserWithMailOrusername
*/
if (!isset($formErrors)) {
$userInfo = $user->getInfoUserWithMailOrusername();
/**
* Si le retour n'est pas un objet alors l'utilisateur a rentrée une valeur qui n'existe pas
* dans la base de données donc on associe un message d'erreur à la clé mailUsername de notre tableau $formErrors.
* Sinon on passe aux instructions suivantes.
*/
if (is_object($userInfo)) {
/**
* On vérifie que le mot de passe de l'utilisateur correspond bien avec celui qu'il a entré lors de
* son inscription à l'aide de la fonction password_verif qui nous permet de comparer une donnée
* hashé(mot de passe enregistrer dans notre base de données) et une donnée non hashé(la valeur entré par l'utilisateur).
* Si les mots de passe correspondent on génère un hash en appelant une méthode statique de notre class randomHash
* grâce au "::". On stocke dans l'attribut tokenHash de notre objet $user le hash créé plus tôt.
* On stocke dans l'attribut id de $user et dans la variable de session "userId" l'attribut id de l'objet $userInfo.
* On stocke dans la variable de session "username" l'attribut username de l'objet $userInfo.
* On stocke dans la variable de session "tokenHash" la valeur de l'attibut tokenHash de l'objet $user donc
* du hash généré précèdemment. Sinon on associe un message d'erreur à la clé password de notre tableau $formErrors.
*/
if (password_verify($_POST['password'], $userInfo->password)) {
$user->tokenHash = randomHash::generateHash();
$user->id = $userInfo->id;
$_SESSION['userId'] = $userInfo->id;
$_SESSION['username'] = $userInfo->username;
$_SESSION['tokenHash'] = $user->tokenHash;
/**
* Si la méthode uptadeTokenHash de l'objet $user renvoie true alors on redirige
* l'utilisateur vers notre page d'accueil.
* Sinon on associe un message d'erreur à la clé password de notre tableau $formErrors
*/
if($user->uptadeTokenHash()){
header('location: ../index.php');
}else{
$formErrors['password'] = 'Problème lors de la connexion.';
}
} else {
$formErrors['password'] = 'Mot de passe incorrect.';
}
} else {
$formErrors['mailUsername'] = 'Nom d\'utilisateur ou adresse mail incorrect.';
}
}
}
}
|
Java | UTF-8 | 1,245 | 2.59375 | 3 | [] | no_license | package service;
import datetime.DateServer;
import exceptions.ParseServeException;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@Path( "/server" )
public class Services {
@POST
@Path( "/date" )
@Produces(MediaType.APPLICATION_JSON)
public Response setDate(@QueryParam("time") String dateTime,@QueryParam("timezone") String format)
{
String DATE_FORMAT = "HH:mm:ss";
DateServer dateServer = new DateServer(dateTime,format);
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
try {
dateServer.changeDate(sdf);
} catch (ParseException e){
throw new WebApplicationException( Response.status( Response.Status.NOT_ACCEPTABLE ).entity( e ).build() );
} catch (ParseServeException e){
throw new WebApplicationException( Response.status( Response.Status.NOT_ACCEPTABLE ).entity( e ).build() );
} catch (Exception e){
throw new WebApplicationException( Response.status( Response.Status.INTERNAL_SERVER_ERROR ).entity( e ).build() );
}
return Response.ok( dateServer ).build() ;
}
}
|
Python | UTF-8 | 546 | 4.40625 | 4 | [] | no_license | #Contains User Inputs and numbers
from math import *
x = input("Enter value of x ")
y = input("Enter value of y ")
decimal = input("Enter a decimal number : ")
print("Product = "+str(int(x)*int(y)))#To print messages with number encapsulate the numbers within the function str()
print("Product = "+(int(x)*int(y)).__str__())#This also works the same as above
#Maths functions
print("Floor value : "+str(floor(float(decimal))))
print("Ceiling value : "+str(ceil(float(decimal))))
print("Round value : "+str(round(float(decimal))))
|
Java | UTF-8 | 724 | 1.9375 | 2 | [] | no_license | package com.lamaknyo.api.common;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ResComponent {
public static String productUrl;
public static String productDir;
public static String productImgDef;
@Value("${res.product-url}")
public void setProductUrl(String productUrl) {
this.productUrl = productUrl;
}
@Value("${res.product-dir}")
public void setProductDir(String productDir) {
this.productDir = productDir;
}
@Value("${res.product-img-default}")
public static void setProductImgDef(String productImgDef) {
ResComponent.productImgDef = productImgDef;
}
}
|
Java | UTF-8 | 943 | 3 | 3 | [] | no_license | package com.xue.nettyserver.nettytest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import java.util.List;
/**
* 出站测试类
* 编码器将从传入的 ByteBuf 中读取每个负整数,并将会调用 Math.abs()方法来获取
* 其绝对值;
* 编码器将会把每个负整数的绝对值写到 ChannelPipeline 中。
*/
public class AbsIntegerEncoder extends
MessageToMessageEncoder<ByteBuf> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext,
ByteBuf in, List<Object> out) throws Exception {
while (in.readableBytes() >= 4) {
Integer inValue = in.readInt();
System.out.println("传入值为:"+inValue);
int value = Math.abs(inValue);
System.out.println("传出值为:"+value);
out.add(value);
}
}
}
|
Java | UTF-8 | 1,123 | 2.578125 | 3 | [] | no_license | package com.github.miro662.blazejsim.gui.circuit.entity_views;
import com.github.miro662.blazejsim.circuits.entities.Entity;
import com.github.miro662.blazejsim.gui.Parameters;
import com.github.miro662.blazejsim.simulation.SimulationState;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.IOException;
public final class ImageEntityView extends EntityView {
Image img;
@Override
public void draw(Graphics2D g2d, int centerX, int centerY, SimulationState state) {
g2d.setColor(Color.BLACK);
// draw entity itself
g2d.drawImage(img, centerX - 16, centerY - 16, null);
drawPins(g2d, centerX, centerY);
}
public ImageEntityView(Entity entity, String resourceLocation) {
super(entity);
try {
img = ImageIO.read(getClass().getResource(resourceLocation));
} catch (IOException e) {
try {
img = ImageIO.read(getClass().getResource("/entity/unknown.png"));
} catch (IOException e1) {
System.err.println("Cannot load fallback image");
}
}
}
}
|
C++ | UTF-8 | 1,395 | 2.59375 | 3 | [] | no_license | #ifndef PLANET_H
#define PLANET_H
#include <SFML/Graphics.hpp>
#include "include.h"
using namespace sf;
int randint(int low, int high);
class Planet
{
public:
Planet(PlanetData data);
void setData(PlanetData data);
void update(double simtime, double timeSpeed);
void draw(RenderWindow* window, double zoom, Vector2i viewPos);
Vector2i getPosition() { return Vector2i(x, y); }
double getMass() { return mass; }
int getRadius() { return radius; }
Vector2f getVelocity() { return velocity; }
void setOrbitCenter(Vector2i pos) { orbitCenter = pos; }
int getOrbitingPlanet() { return orbitingPlanetIndex; }
protected:
private: // Mars example values
double mass = 0; // 641,710,000,000,000,000,000,000 kg
int aphelion = 0; // 249,200,000 km
int perihelion = 0; // 206,700,000 km
int radius = 0; // 3,389 km
double orbitalSpeed = 0; // 24.007 km/s
Vector2i orbitCenter;
int orbitalPeriod = 0; // 59,353,534 seconds
int x = 0; // <-- position relative to the sun
int y = 0; // <--/
int phase = 0;
Color color;
Vector2f velocity;
Vector2i prevPos;
int orbitingPlanetIndex = -1;
};
#endif // PLANET_H
|
Markdown | UTF-8 | 9,280 | 2.984375 | 3 | [
"MIT"
] | permissive | ---
hrs_structure:
division: '5'
volume: '14'
title: '37'
chapter: '706'
section: 706-660
type: hrs_section
tags:
- Crime
- Criminal Proceeding
menu:
hrs:
identifier: HRS_0706-0660
parent: HRS0706
name: 706-660 Sentence of imprisonment for class B and C felonies;
weight: 20270
title: Sentence of imprisonment for class B and C felonies;
full_title: 706-660 Sentence of imprisonment for class B and C felonies;
---
**§706-660 Sentence of imprisonment for class B and C felonies; ordinary terms; discretionary terms.** (1) Except as provided in subsection (2), a person who has been convicted of a class B or class C felony may be sentenced to an indeterminate term of imprisonment except as provided for in section 706-660.1 relating to the use of firearms in certain felony offenses and section 706-606.5 relating to repeat offenders. When ordering such a sentence, the court shall impose the maximum length of imprisonment which shall be as follows:
(a) For a class B felony--ten years; and
(b) For a class C felony--five years.
The minimum length of imprisonment shall be determined by the Hawaii paroling authority in accordance with section 706-669.
(2) A person who has been convicted of a class B or class C felony for any offense under part IV of chapter 712 may be sentenced to an indeterminate term of imprisonment; provided that this subsection shall not apply to sentences imposed under sections 706-606.5, 706-660.1, 712-1240.5, 712-1240.8 as that section was in effect prior to July 1, 2016, 712-1242, 712-1245, 712-1249.5, 712-1249.6, 712-1249.7, and 712-1257.
When ordering a sentence under this subsection, the court shall impose a term of imprisonment, which shall be as follows:
(a) For a class B felony--ten years or less, but not less than five years; and
(b) For a class C felony--five years or less, but not less than one year.
The minimum length of imprisonment shall be determined by the Hawaii paroling authority in accordance with section 706-669\. [L 1972, c 9, pt of §1; am L 1976, c 92, §8 and c 204, §2; am L 1980, c 294, §2; am L 1986, c 314, §38; am L 2013, c 280, §2; am L 2016, c 231, §29]
COMMENTARY ON §706-660
This section embodies three important policy determinations of the Code.
With the exception of special problems calling for extended terms of incarceration as provided in subsequent sections, it provides for only one possible maximum length of imprisonment for each class of felony. Assuming care is used in designating the grade and class of each offense, this should go a long way in ameliorating the variety of inconsistent sentences previously authorized.
In 1965, the legislature enacted a law designed to end judicially imposed inconsistent sentences of imprisonment.[1] This policy known as true indeterminate sentencing is continued. The court's discretion is limited to choosing between imprisonment and other modes of sentencing. Once the court has decided to sentence a felon to imprisonment, the actual time of release is determined by parole authorities. Having decided on imprisonment, the court must then impose the maximum term authorized.[2] The concept is accepted in California[3] and is being proposed in Michigan.[4] This policy is also in substantial accord with the proposed A.B.A. Standards on sentencing.[5]
Inevitably, there will remain some disparity arising from the fact that some judges will be more strongly inclined toward granting probation (or other non-imprisonment disposition) than others. The criteria set forth in part II of this chapter, for withholding a sentence of imprisonment, are intended to alleviate this disparity somewhat. Moreover, §706-669, governing the procedure for determining the actual minimum time to be served, provides that the parole board must make an initial determination as soon as practicable but, in any event, no later than six months following commitment. Thus, "[g]rossly inappropriate denial[s] of probation can in most instances be cured fairly promptly through parole, if the circumstances favoring release are evident...."[6]
Finally, this section embodies a policy of differentiating exceptional problems calling for extended terms of imprisonment[7] from the problems which the vast majority of offenders present. Most of the felony sentences previously authorized in Hawaii were clearly intended to encompass the most dangerous offender. The uniform application of a sentence designed to encompass exceptional cases seems clearly unwarranted in the cases presented by the vast majority of offenders. This is borne out by the A.B.A.'s recent study:
...[M]any sentences authorized by statute in this country are, by comparison to other countries and in terms of the needs of the public, excessively long for the vast majority of cases. Their length is undoubtedly the product of concern for protection against the most exceptional cases, most notably the particularly dangerous offender and the professional criminal. It would be more desirable for the penal code to differentiate explicitly between most offenders and such exceptional cases, by providing lower, more realistic sentences for the former and authorizing a special term for the latter.[8]
The sentences provided in this section, when compared to the extended sentences authorized in subsequent sections, seek to achieve the recommended explicit differentiation.
SUPPLEMENTAL COMMENTARY ON §706-660
Act 204, Session Laws 1976, amended the first sentence by adding the exception excluding persons convicted of felonies involving firearms. In its report, the Conference Committee states that it "intends to require the court in cases of felonies where a firearm was used to impose a mandatory term of imprisonment" and that nothing contained in the bill "should be construed as precluding (a) the court from imposing an indeterminate sentence or an extended indeterminate sentence, or (b) the Hawaii paroling authority from fixing the minimum term of imprisonment at a length greater than the term of imprisonment provided for in this bill [706-660.1]." Conference Committee Report Nos. 34 and 35.
Act 294, Session Laws 1980, restricted this section to sentences for class B and C felonies, eliminating provisions relating to class A felonies. For class A felonies, see §706-659.
Act 280, Session Laws 2013, amended this section by granting a sentencing court the discretion to sentence a defendant convicted of a class B or class C felony drug offense to a prison sentence of a length appropriate to the defendant's particular offense and underlying circumstances. Specifically, this Act allows a court to impose a sentence of imprisonment for certain class B felonies for not less than five years, and a sentence of imprisonment for certain class C felonies for not less than one year. The legislature found that state mandatory minimum sentencing laws are being challenged across the nation because these laws mandate longer prison sentences regardless of whether the sentencing court believes the punishment is appropriate based on the circumstances and facts of the case. Studies have shown that mandatory minimum sentencing of drug users causes an increase in incarceration costs and have a disproportionate impact on women and certain racial and ethnic groups. Senate Standing Committee Report No. 496, House Standing Committee Report No. 1464.
Act 231, Session Laws 2016, amended subsection (2) to implement recommendations made by the Penal Code Review Committee convened pursuant to House Concurrent Resolution No. 155, S.D. 1 (2015).
Case Notes
Because criminal solicitation to commit first degree murder is a crime declared to be a felony without specification of class within meaning of §706-610, it is a class C felony for sentencing purposes, subject to the sentencing provisions of this section. 84 H. 229, 933 P.2d 66 (1997).
For sentencing purposes, conspiracy to commit second degree murder is a class C felony under §706-610 and subject to the sentencing provisions of this section, not §706-656\. 84 H. 280, 933 P.2d 617 (1997).
Where defendant was convicted by the jury of five first-degree thefts, each of which defendant was sentenced to ten years' incarceration, and pursuant to this section and §706-668.5, five ten-year terms running consecutively was the statutory maximum, defendant's sentence did not deprive defendant of defendant's right to a jury trial as interpreted by the U.S. Supreme Court in Apprendi and Blakely. 111 H. 267, 141 P.3d 440 (2006).
Upon revocation of probation pursuant to §706-625(3), in light of the record, §706-621 and this section, trial court did not abuse its discretion in sentencing defendant to imprisonment "for a term of not more than ten years with credit for time served". 97 H. 135 (App.), 34 P.3d 1034 (2001).
Cited: 56 H. 628, 548 P.2d 632 (1976).
**__________**
**§706-660** **Commentary:**
1\. See H.R.S. §711-76.
2\. It must, however, be remembered that the Code grants the court the power to impose an extended term of imprisonment (see §706-661).
3\. Cal. Pen. Code §1168.
4\. Prop. Mich. Rev. Cr. Code §1401.
5\. A.B.A. Standards §3.2.
6\. Prop. Mich. Rev. Cr. Code, comments at 130.
7\. Cf. §706-661.
8\. A.B.A. Standards §2.5. |
Java | UTF-8 | 8,645 | 2.25 | 2 | [] | no_license | package com.hci.happycaster.ServerComunication;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.*;
import java.util.ArrayList;
import java.lang.reflect.Field;
public class WebServiceManager extends Thread {
private String requestMessageBody;
private String requestMessageBody1;
private String requestMessageBody2;
private static final String startBody="<env:Body>"+"\n";
private static final String endBody="</env:Body>"+"\n";
private static final String endEnvelope="</env:Envelope>" +"\n";
private String startOperationName;
private String endOperationName;
private ArrayList<String> parameters;
private ArrayList<String> parametersRef;
private String requestMessage ;
private String contentType;
private String serviceURL;
private URL url;
private HttpURLConnection connection;
private FileInputStream attachFile;
private boolean existFile;
private String filename;
private Element rootNode;
private DataHandler handler;
private ArrayList<DataObject> objectList;
public WebServiceManager() {
requestMessageBody1=
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+ "\n\n"+
"<env:Envelope" +
" xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"" + "\n" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + "\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + "\n" +
" xmlns:enc=\"http://schemas.xmlsoap.org/soap/encoding/\"" + "\n";
requestMessageBody2=
" env:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "\n\n" +
" <env:Header/>" + "\n";
parameters = new ArrayList<String>();
parametersRef = new ArrayList<String>();
}
public void setHandler(DataHandler handler) {
this.handler=handler;
}
public void setServiceNamespace(String serviceNamespace) {
String namespaceURL="";
if(serviceNamespace!=null)
namespaceURL=" xmlns:ns0=\""+serviceNamespace+"\"" +"\n";
else
namespaceURL=" xmlns:ns0=\"http://platform.silla.ac.kr/smartad/default\"" +"\n";
requestMessageBody = requestMessageBody1+namespaceURL+requestMessageBody2;
}
public void setServiceURL(String serviceURL) throws Exception {
this.serviceURL=serviceURL;
url = new URL(serviceURL);
connection = (HttpURLConnection)url.openConnection();
}
public void setOperationName(String opName) {
startOperationName="<ns0:"+opName+">" +"\n";
endOperationName="</ns0:"+opName+">" +"\n";
contentType="text/xml; charset=\"UTF-8\"";
existFile=false;
}
public void setParameter(String sequence, String value) throws Exception {
parameters.add("<arg"+sequence+">"+value+"</arg"+sequence+">\n");
}
public void setParameterWithArrayList(String sequence, ArrayList<String> value) throws Exception {
for(int i=0;i<value.size();i++)
this.setParameter(sequence,value.get(i));
}
public void setParameterWithObject(String sequence, Object object) throws Exception {
String fullObjectNames [] = object.getClass().getName().split("\\.");
String objectName = fullObjectNames[fullObjectNames.length-1];
String parameter = "<arg"+sequence+" xsi:type=\"ns0:"+objectName+"\">";
Field[] fields = object.getClass().getDeclaredFields();
String fieldName = "";
String fieldValue = "";
for (int i = 0; i < fields.length; i++) {
fieldName = fields[i].getName();
fieldValue = fields[i].get(object).toString();
parameter=parameter+"<"+fieldName+">"+fieldValue+"</"+fieldName+">";
}
parameter=parameter+"</arg"+sequence+">\n";
parameters.add(parameter);
}
public void setParameterWithObjectArrayList(String sequence, ArrayList list) throws Exception{
for(int i=0; i<list.size(); i++) {
this.setParameterWithObject(sequence,list.get(i));
}
}
public void setAttachmentFile(String filename) throws Exception {
this.setAttachmentFile(new File(filename));
}
public void setAttachmentFile(File file) throws Exception {
attachFile = new FileInputStream(file);
this.filename=file.getName();
contentType="multipart/related; type=\"text/xml\"; boundary=\"----=_Part_1_12546448.1291107845663\"";
existFile=true;
}
public String getRequestMessage() throws Exception {
requestMessage=requestMessageBody + startBody;
if(startOperationName!=null)
requestMessage=requestMessage+startOperationName;
if(parameters.size()!=0)
for(int i=0;i<parameters.size();i++)
requestMessage=requestMessage+parameters.get(i);
requestMessage=requestMessage+endOperationName;
if(parametersRef.size()!=0)
for(int i=0;i<parametersRef.size();i++)
requestMessage=requestMessage+parametersRef.get(i);
requestMessage=requestMessage+endBody+endEnvelope;
return requestMessage;
}
public void run() {
try {
this.getRequestMessage();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",contentType);
connection.setRequestProperty("Target-Host",serviceURL);
OutputStream out = connection.getOutputStream();
if(existFile) {
out.write((new String("\n------=_Part_1_12546448.1291107845663\n")).getBytes());
out.write((new String("Content-Type: text/xml; charset=UTF-8\n")).getBytes());
out.write(requestMessage.getBytes());
out.write((new String("------=_Part_1_12546448.1291107845663\n")).getBytes());
out.write((new String("Content-Type: application/octet-stream\n")).getBytes());
out.write((new String("Content-ID: "+filename+"\n\n")).getBytes("UTF-8"));
byte buff[] = new byte[1024];
int size;
while((size=attachFile.read(buff))!=-1)
out.write(buff,0,size);
out.write((new String("\n------=_Part_1_12546448.1291107845663--\n")).getBytes());
attachFile.close();
}
else {
out.write(requestMessage.getBytes("UTF-8"));
}
out.flush();
out.close();
soapMessageParser(connection.getInputStream());
}catch(Exception e) {}
}
private void soapMessageParser(InputStream in) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse(in); //�����ߴ°�
rootNode=doc.getDocumentElement();
Node returnNode = this.getNode("return");
objectList = new ArrayList<DataObject>();
while(returnNode!=null) {
if(returnNode.getNodeType()==Node.ELEMENT_NODE) {
objectList.add(new DataObject(returnNode));
}
returnNode=returnNode.getNextSibling();
}
handler.handler(objectList);
}
private Node getNode(String nodeName) {
Node node = rootNode;
while((node=getFirstChildNodeTypeNode(node))!=null) {
if(node.getNodeName().equals(nodeName))
return node;
}
return null;
}
private Node getFirstChildNodeTypeNode(Node node) {
if(node.getChildNodes().getLength()<1)
return null;
node=node.getFirstChild();
while(node.getNodeType()!=Node.ELEMENT_NODE)
node=node.getNextSibling();
return node;
}
public String getResponse() throws Exception {
this.getRequestMessage();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",contentType);
connection.setRequestProperty("Target-Host",serviceURL);
OutputStream out = connection.getOutputStream();
if(existFile) {
out.write((new String("\n------=_Part_1_12546448.1291107845663\n")).getBytes());
out.write((new String("Content-Type: text/xml; charset=UTF-8\n")).getBytes());
out.write(requestMessage.getBytes());
out.write((new String("------=_Part_1_12546448.1291107845663\n")).getBytes());
out.write((new String("Content-Type: application/octet-stream\n")).getBytes());
out.write((new String("Content-ID: "+filename+"\n\n")).getBytes("UTF-8"));
byte buff[] = new byte[1024];
int size;
while((size=attachFile.read(buff))!=-1)
out.write(buff,0,size);
out.write((new String("\n------=_Part_1_12546448.1291107845663\n")).getBytes());
attachFile.close();
}
else {
out.write(requestMessage.getBytes("UTF-8"));
}
out.flush();
out.close();
int size;
byte buff[] = new byte[10240];
InputStream in = connection.getInputStream();
String responseMessage="";
while((size=in.read(buff))!=-1)
responseMessage = responseMessage + new String(buff,0,size,"UTF-8");
responseMessage = responseMessage.replaceAll("xmlns","\n xmlns");
responseMessage = responseMessage.replaceAll("<","\n<");
return responseMessage;
}
} |
Markdown | UTF-8 | 2,349 | 2.6875 | 3 | [
"CC-BY-4.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ---
title: "Using OData with Queries That are Set with a Top Number of Rows"
description: Learn about using queries that are set with a top number of rows.
ms.custom: na
ms.date: 05/26/2021
ms.reviewer: na
ms.suite: na
ms.tgt_pltfrm: na
ms.topic: conceptual
---
# Using OData with Queries That are Set with a Top Number of Rows
[!INCLUDE[prod_short](../developer/includes/prod_short.md)] queries include the [TopNumberOfRows Property](../developer/properties/devenv-TopNumberOfRows-Property.md) and [TopNumberOfRows Method](../developer/methods-auto/query/queryinstance-topnumberofrows-method.md) that can be used to specify the maximum number of rows to include in the resulting dataset. The [!INCLUDE[server](../developer/includes/server.md)] includes the **Max Page Size** setting for OData that specifies the maximum number of entities returned per page of OData results. The default value is 20,000.
To ensure that the OData results include the correct number of entities when you are using a query that is set with a top number of rows, you should set the **Max Page Size** value greater than the value that is set by the **TopNumberOfRows** property and **TopNumberOfRows** method. Otherwise, the **TopNumberOfRows** property and **TopNumberOfRows** method are ignored and the query dataset will be returned in the OData results.
Typically, the **TopNumberOfRows** property or **TopNumberOfRows** method are used to return a relatively small number of entities, such as the top five, ten, or 100 entities. Therefore, in most cases, the value of the **TopNumberOfRows** property and **TopNumberOfRows** method will be less than the **Max Page Size**, so that you will not have to change the **Max Page Size** setting.
> [!TIP]
> In HTTP requests, it can be beneficial to use `odata.maxpagesize` instead of the system query options `$top` and `$skip`. For instance, `odata.maxpagesize` automatically includes `nextlink` in the response, which lets you continuously retrieve a large dataset in limited chunks.
For information about how to change the **Max Page Size** setting, see [Configuring Business Central Server](../administration/configure-server-instance.md) and [Server-Driven Paging in OData Web Services](Server-Driven-Paging-in-OData-Web-Services.md).
## See Also
[Basic Page Operations](Basic-Page-Operations.md)
|
C++ | UTF-8 | 1,078 | 3.109375 | 3 | [] | no_license | #include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
#include <iostream>
#include <string.h>
double getWinProbabilityCircleUpdate(double leftStrength, int cntLeft, double rightStrength, int cntRight) {
std::vector<double> winProbs(cntLeft);
std::fill(winProbs.begin(), winProbs.end(), 1.0);
auto sumStrength = leftStrength + rightStrength;
for (int r = 0; r < cntRight; r++) {
winProbs[0] = leftStrength * winProbs[0] / sumStrength;
for (int l = 1; l < cntLeft; l++)
winProbs[l] = (rightStrength * winProbs[l - 1] + leftStrength * winProbs[l]) / sumStrength;
}
return winProbs[cntLeft - 1];
}
int main(int argc, char *argv[]) {
const double leftStrength = atof(argv[1]);
const int cntLeft = atof(argv[2]);
const double rightStrength = atof(argv[3]);
const int cntRight = atof(argv[4]);
auto winLeftProb = getWinProbabilityCircleUpdate(leftStrength, cntLeft, rightStrength, cntRight);
std::cout << "Win left probability: " << winLeftProb << std::endl;
// return min_n;
}
|
Rust | UTF-8 | 2,095 | 2.734375 | 3 | [] | no_license |
use crate::vector::*;
use crate::lstm::*;
pub fn init_lstm<const N: usize, const M: usize, I>(mut iter: I) -> Box<Lstm<N, M>>
where
[u8; simd(N)]: Sized,
[u8; simd(M)]: Sized,
I: Iterator<Item=f32>
{
let mut lstm = zero_box::<Lstm<N, M>>();
lstm.b_i.as_mut_slice().iter_mut().for_each(|v| v.fill(&mut iter));
lstm.b_h.as_mut_slice().iter_mut().for_each(|v| v.fill(&mut iter));
lstm.w_i.as_mut_slice().iter_mut().for_each(|m| m.fill(&mut iter));
lstm.w_h.as_mut_slice().iter_mut().for_each(|m| m.fill(&mut iter));
lstm
}
pub struct Lstm100x1024 {
lstm: Box<Lstm<100, 1024>>,
state: Box<LstmState<1024>>,
x: Box<Vector<100>>,
}
impl Lstm100x1024 {
pub fn new() -> Self {
use rand::distributions::{Distribution, Standard};
let rng = rand::thread_rng();
let dist = Standard;
let mut iter = dist.sample_iter(rng);
let lstm = init_lstm::<100, 1024, _>(&mut iter);
let mut x = Box::new(Vector::null());
x.fill(&mut iter);
Lstm100x1024 {
lstm,
state: Box::new(LstmState::null()),
x
}
}
pub fn step(&mut self) {
self.lstm.step(&mut self.state, &self.x);
}
}
#[cfg(feature="gpu")]
#[test]
fn test_cuda() {
use std::iter::once;
use cuda::*;
const MODULE: &[u8] = include_bytes!("../../ptx_linalg/ptx_linalg.cubin");
let context = Device::get(0).unwrap().create_context().unwrap();
let module = context.create_module(MODULE).unwrap();
let mut input = Vector::from(&[0.0; 2148]);
input[1] = 1.0;
let mut output_gpu = zero::<Vector<4>>();
let mut linear = zero::<Linear<2148, 4>>();
linear.bias[0] = 1.0;
linear.weight[1][1] = 2.0;
let mut cuda_linear = CudaLinear::new(&linear, &context, &module).unwrap();
cuda_linear.run_ptx(once((input, &mut output_gpu)));
let output_cpu = linear.transform(&input);
let delta = output_gpu - output_cpu;
assert!(delta.dot(&delta) < 1e-3, "incorrect result:\ngpu: {}\ncpu: {}", output_gpu, output_cpu);
} |
Java | UTF-8 | 1,334 | 3.265625 | 3 | [] | no_license | /**
* grades
*/
public class Grades {
String course;
int grades[];
Grades(String course, int grades[]) {
this.course = course;
this.grades = grades;
}
public void gradeReport() {
String report[] = new String[11];
for (int i = 0; i < report.length; i++) {
report[i] = "";
}
for (int i : this.grades) {
if (i >= 0 && i < 10) {
report[1] += "*";
} else if (i >= 10 && i < 20) {
report[2] += "*";
} else if (i >= 20 && i < 30) {
report[3] += "*";
} else if (i >= 30 && i < 40) {
report[4] += "*";
} else if (i >= 40 && i < 50) {
report[5] += "*";
} else if (i >= 50 && i < 60) {
report[6] += "*";
} else if (i >= 60 && i < 70) {
report[7] += "*";
} else if (i >= 80 && i < 90) {
report[8] += "*";
} else if (i >= 90 && i < 100) {
report[9] += "*";
} else if (i == 100) {
report[10] += "*";
}
}
for (int j = 1; j < report.length; j++) {
System.out.println((10 * (j - 1)) + "-" + (10 * (j) - 1) + " : " + report[j]);
}
}
} |
Java | UTF-8 | 1,029 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package com.doggogram.backendsvc.util;
import com.doggogram.backendsvc.domain.Image;
import com.doggogram.backendsvc.util.exceptions.ImageCorruptedException;
import com.google.common.io.ByteStreams;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Util {
public static String getJwtToken(String auth) {
return auth.split("\\s+")[1];
}
public static String getEncodedImage(MultipartFile image) throws ImageCorruptedException {
try {
return Base64Utils.encodeToString(ByteStreams.toByteArray(image.getInputStream()));
} catch (IOException e) {
throw new ImageCorruptedException(e.getMessage());
}
}
public static List<Image> sortImages(List<Image> images) {
Collections.sort(images, Comparator.comparingLong(image -> image.getId()));
return images;
}
}
|
Python | UTF-8 | 2,431 | 2.96875 | 3 | [] | no_license | #!/usr/bin/python
#coding:utf-8
#Author:renlu.xu
#URL:http://www.162cm.com/
#date:2009.05.21
import MySQLdb
def escape(st):
'''escape for security reason'''
return MySQLdb.escape_string(str(st))
def select(table ,columns="*",condition="",order="",limit="",group=""):
if condition != "":
condition = " WHERE %s" % condition
if order != "":
order = " ORDER BY %s" % order
if limit != "":
limit = " LIMIT %s" % limit
if group != "":
group = " GROUP BY %s" % group
sql = "SELECT %s FROM %s %s %s %s %s" % ( columns, table, condition,group,order,limit )
return sql
def update(table,columns,condition=None,limit=1):
'''generate update sql
columns: like '*' ,'id,username,password' and so on
condition: like ' id=1 ' or ' pid>7 ' and so on
'''
if isinstance(columns,dict):
sql="UPDATE `%s` SET " % table
comm=""
for col in columns:
sql = sql + comm+ "`"+col+"`='"+escape(columns[col])+"' "
comm=","
if condition:
sql = sql + "WHERE " + condition
sql = sql + " LIMIT " + limit
return sql
else:
return None
def remove(table,columns,limit="1"):
'''
generate delete sql statement
'''
if isinstance(columns,dict):
sql="DELETE FROM `%s` WHERE " % table
comm=""
for col in columns:
sql = sql + comm+ "`"+col+"`='"+escape(columns[col])+"' "
comm="AND "
sql = sql + " LIMIT " + limit
return sql
else:
return None
def create(table,columns,method="INSERT"):
'''
parameter method could be 'INSERT' or 'UPDATE'
'''
method=method.upper()
if isinstance(columns,dict):
sql=method + " INTO `%s` (" % table
comm=""
for col in columns:
sql = sql + comm + "`"+col+"`"
comm=","
sql = sql + ") VALUES ("
comm=""
for col in columns:
sql = sql + comm + "'"+escape(columns[col])+"'"
comm=","
sql = sql + ")"
return sql
else:
return None
def testfunc():
table="mytable"
columns={
"id":1,
"name":"xuren'lu"
}
condition="id=2"
print update(table,columns,condition)
print create(table,columns)
print select(table,"id,username","id=7" ,"pid DESC",1000)
if __name__=="__main__":
testfunc()
|
TypeScript | UTF-8 | 299 | 2.609375 | 3 | [] | no_license | export class AltInputEventModel {
public static EVENT_TYPES = {
'DATA': 'DATA',
'DELETE': 'DELETE',
'APPLY' : 'APPLY'
};
public eventType: string;
public data?: string;
constructor(eventType: string, data?: string) {
this.eventType = eventType;
this.data = data;
}
}
|
Java | UTF-8 | 3,767 | 3.75 | 4 | [] | no_license | /***************************************************************************************************
* @file ListCursor.java
* @author Sergey Stepanenko (sergey.stepanenko.27@gmail.com)
* @description Contains implementation of the ListCursor class.
**************************************************************************************************/
package com.gmail.stepanenko.sergey27.elephant_from_fly;
import java.util.List;
import java.util.NoSuchElementException;
/** Represents list cursor which keeps position of element in List<T> and used for iteration through list.
* This class was implemented because Java Iterator<T> class doesn't allow getting reference to current element
* at which it is pointed to.
* @param <T> Type of element in list.
* */
public final class ListCursor<T> {
// Private fields.
private List<T> mList; // List.
private int mPosition; // Current position (should be inside valid range).
private T mElement; // Element in current position.
// Public methods.
/** Constructor.
* @param list List of elements of T type.
* @param position Valid position of element in list.
* @exception IllegalArgumentException List is null or position is out of range.
* */
public ListCursor(List<T> list, int position){
// Check list.
if(list == null){
throw new IllegalArgumentException("list");
}
// Check position.
if(position < 0 || position >= list.size()){
throw new IllegalArgumentException("position");
}
mList = list;
mPosition = position;
mElement = mList.get(mPosition);
}
/** Gets current position. */
public synchronized int getPosition(){
return mPosition;
}
/** Gets current element from list */
public synchronized T getElement(){
return mElement;
}
/** Gets element at given position.
* @param position Position of element in list.
* @exception IndexOutOfBoundsException Position is out of valid range.
* */
public synchronized T getElementAt(int position){
return mList.get(position); // exception
}
/** Checks if current element is not the last. */
public synchronized boolean hasNext(){
boolean result = _validatePosition(mPosition + 1);
return result;
}
/** Checks if current element is not the first. */
public synchronized boolean hasPrevious(){
boolean result = _validatePosition(mPosition - 1);
return result;
}
/** Sets cursor to the next element and returns reference to this element.
* @return Reference to next element.
* @exception NoSuchElementException Current element is the last element in list.
*/
public synchronized T next(){
if(!hasNext()){
throw new NoSuchElementException();
}
mPosition++;
mElement = mList.get(mPosition);
return mElement;
}
/** Sets cursor to the previous element and returns reference to this element.
* @return Reference to the previous element.
* @exception NoSuchElementException Current element is the first element in list.
*/
public synchronized T previous(){
if(!hasPrevious()){
throw new NoSuchElementException();
}
mPosition--;
mElement = mList.get(mPosition);
return mElement;
}
// Private methods.
/** Checks if position is valid.
* @param position Position to be checked.
* @return True - if position is valid, otherwise - false.
* */
private boolean _validatePosition(int position){
boolean result = (position >=0 && position < mList.size());
return result;
}
} // class ListCursor<T>
|
Shell | UTF-8 | 811 | 2.5625 | 3 | [] | no_license | VOICE=voice_kal_diphone
TEMPO=1.7
PITCH=500
PROFILE=$1
if [ $PROFILE -eq 1 ]; then
VOICE=voice_kal_diphone
TEMPO=1.7
PITCH=500
elif [ $PROFILE -eq 2 ]; then
VOICE=voice_kal_diphone
TEMPO=1.6
PITCH=300
elif [ $PROFILE -eq 3 ]; then
VOICE=voice_kal_diphone
TEMPO=1.8
PITCH=700
elif [ $PROFILE -eq 4 ]; then
VOICE=voice_kal_diphone
TEMPO=1.7
PITCH=400
elif [ $PROFILE -eq 5 ]; then
VOICE=voice_kal_diphone
TEMPO=1.9
PITCH=200
fi
echo $2 > tts.txt
cat tts.txt | text2wave -o tts.wav -eval "($VOICE)" -scale 5
#play tts.wav overdrive 70 100 sinc -4k
#play tts.wav overdrive 30 30
#play tts.wav
#play tts.wav tempo $TEMPO pitch $PITCH pad 0 0.2 vol 1 amplitude 0.15 contrast 30 overdrive 30 30 vol 0.7
play tts.wav pad 0 0.2 vol 1 amplitude 0.15 contrast 30 overdrive 30 10 vol 0.7
#play tts.wav
|
Java | UTF-8 | 521 | 1.9375 | 2 | [] | no_license | package api.erp.banqueservice.model;
import lombok.*;
import lombok.experimental.FieldDefaults;
import javax.persistence.*;
import java.io.Serializable;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
@FieldDefaults(level = AccessLevel.PRIVATE)
@Entity
public class Contract implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
int id;
Boolean active;
@OneToOne
Abonne abonne;
@ManyToOne
Agent agent;
}
|
C | GB18030 | 249 | 3.984375 | 4 | [] | no_license | //ʮе
#include <stdio.h>
int main(){
int arr[10] = { 0, 50, 2, 3, 4, 5, 6, 7, 8, 9 };
int Max = arr[0];
int i = 1;
for (; i < 10; i++){
if (arr[i] > Max){
Max = arr[i];
}
}printf("Max=%d\n", Max);
return 0;
} |
JavaScript | UTF-8 | 3,303 | 2.5625 | 3 | [] | no_license | // import { createStore, applyMiddleware } from 'redux'
// import { myLoggerMiddleware } from './my-logger-middleware';
// import { composeWithDevTools } from 'redux-devtools-extension';
// import * as actionCreators from './action-creators';
// let store = createStore(catsReducer);
// let store = createStore(catsReducer, applyMiddleware(thunk));
// let store = createStore(catsReducer, applyMiddleware(myLoggerMiddleware));
// let store = createStore(catsReducer, composeWithDevTools(applyMiddleware(thunk)));
// import * as generators from './generators';
/*
store.subscribe(() =>
console.log(store.getState())
);
*/
// ---------------------- Thunk -----------------------
// import thunk from 'redux-thunk';
// let store = createStore(catsReducer, applyMiddleware(thunk));
/*
export const startFetching = () => ({ type: 'START_FETCHING' });
/*
export function catsReducer(state = initialState, action) {
switch (action.type) {
case 'NEWBORN_CAT':
return Object.assign({} , state, { cats: [...state.cats, action.payload] });
case 'SELL_CAT':
return Object.assign({}, state, { cats: [...state.cats, state.filter(cat => cat !== action.payload)] });
case 'LOAD_CATS':
return Object.assign({}, { cats: action.payload, isBusy: false });
case 'START_FETCHING':
return Object.assign({}, state, { isBusy: true });
default:
return state;
}
};
export const fetchCats = () => {
return (dispatch, getState) => {
return getCats().then(
cats => dispatch(loadCats(cats))
);
};
};
/*
export const fetchCats = () => {
return (dispatch, getState) => {
dispatch(startFetching());
return getCats().then(
cats => {
dispatch(loadCats(cats));
}
);
};
};
*/
/*
let initialState = {
cats: ['cinamon', 'mrlopez'],
isBusy: false
};
*/
// ---------------------- Saga ----------------------
// import createSagaMiddleware from 'redux-saga'
/*
const sagaMiddleware = createSagaMiddleware();
let store = createStore(catsReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(mySaga);
export const fetchCats = cats => ({ type: 'FETCH_CATS' });
export function catsReducer(state = initialState, action) {
switch (action.type) {
case 'NEWBORN_CAT':
return Object.assign({} , state, { cats: [...state.cats, action.payload] });
case 'SELL_CAT':
return Object.assign({}, state, { cats: [...state.cats, state.filter(cat => cat !== action.payload)] });
case 'LOAD_CATS':
return Object.assign({}, { cats: action.payload, isBusy: false });
case 'FETCH_CATS':
return Object.assign({}, state, { isBusy: true });
default:
return state;
}
};
*/
// ---------------------- Vanjilla Store ----------------------
/*
function myStore(state = {}, action) {
return {
cats: catsReducer(state.cats, action),
counter: counterReducer(state.counter, action)
}
}
*/
// store.dispatch()
// store.getstate()
// store.dispatch({ type: 'NEWBORN_CAT', payload: 'nancy'});
// store.dispatch({ type: 'SELL_CAT', payload: 'mrlopez'});
// let state1 = myStore({}, { type: 'NEWBORN_CAT', payload: 'nancy'});
// let state2 = myStore(state1, { type: 'INCREMENT'});
|
Markdown | UTF-8 | 2,847 | 4.1875 | 4 | [] | no_license | # 题目描述
给定一个包含红色、白色和蓝色,一共 *n* 个元素的数组,**原地**对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
**注意:**
不能使用代码库中的排序函数来解决这道题。
**示例:**
```
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
```
**进阶:**
- 一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
- 你能想出一个仅使用常数空间的一趟扫描算法吗?
----
# 解题思路
这一题实际上就是经典的**荷兰国旗问题**:
> 我们将乱序的红白蓝三色小球排列成有序的红白蓝三色的同颜色在一起的小球组。这个问题之所以叫荷兰国旗,是因为我们可以将红白蓝三色小球想象成条状物,**有序**排列后正好组成荷兰国旗。
注意,这个问题最后要求最后的结果是有序排列的,就这一题来说,最后的结果必须是`[0,0,1,1,2,2]`这种形式的,而不能是`[1,1,0,0,2,2]`这种顺序不对的。
从左到右遍历一遍数组,使用三个指针,`left`,`right`和`current`,其中`left`使得`nums[l0...left-1]`中的元素都小于`v`,`right`使得`nums[right+1...hi]`中的元素都大于`v`,`current`使得`nums[left...current-1]`中的元素都等于`v`。在遍历过程中:
- `nums[current] < v`,将`nums[left]`和`nums[current]`交换,将`left`和`current`加一
- `nums[current] > v`,将`nums[right]`和`nums[current]`交换,将`right`减一
- `nums[current] = v`,将`i`加一
## Java 实现
```java
class Solution {
public void sortColors (int[] nums) {
sort(nums, 0, nums.length - 1);
}
private static void sort (int[] nums, int lo, int hi) {
if (hi <= lo) return;
int left = lo, current = lo + 1, right = hi;
int v = nums[lo];
while (current <= right) {
if (nums[current] < v) exch(nums, left++, current++);
else if (nums[current] > v) exch(nums, current, right--);
else current++;
}
sort(nums, lo, left - 1);
sort(nums, right + 1, hi);
}
private static void exch (int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
```
# 心得体会
- 这一题结合快速排序中的相关知识就比较好理解了
- 一个集合中含有大量重复元素时,使用三向切分快速排序比经典的快速排序更有效率,因为它避免将一个有很多重复的子集继续切分为更小的子集
---
**参考:**《算法》第四版,第187页,2.3.3.3 熵最优的排序 |
Shell | UTF-8 | 2,209 | 2.875 | 3 | [] | no_license | #!/usr/bin/bash
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (the "License"). You may not use this file except in compliance
# with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2011-2013 OmniTI Computer Consulting, Inc. All rights reserved.
# Use is subject to license terms.
#
# Load support functions
. ../../lib/functions.sh
PROG=php-memcached
VER=2.1.0
VERHUMAN=$VER
PHPVER=53
PKG=omniti/library/php-$PHPVER/memcached
SUMMARY="memcache extension for PHP using libmemcached"
DESC="talk to memcache using libmemcached"
BUILD_DEPENDS_IPS="omniti/library/libmemcached"
DEPENDS_IPS=$BUILD_DEPENDS_IPS
BUILDARCH=64
NO_PARALLEL_MAKE=true
PREFIX=/opt/php$PHPVER
reset_configure_opts
CFLAGS='-I/opt/omni/include/amd64'
LDFLAGS='-L/opt/omni/lib/amd64 -R/opt/omni/lib/amd64'
CONFIGURE_OPTS_64="
--prefix=$PREFIX
--with-php-config=/opt/php$PHPVER/bin/php-config
--with-libmemcached-dir=/opt/omni
"
CFLAGS="-I/opt/omni/include"
BUILDDIR=memcached-$VER
make_install() {
logmsg "--- make install"
logcmd $MAKE INSTALL_ROOT=${DESTDIR} install || \
logerr "--- Make install failed"
}
build64() {
pushd $TMPDIR/$BUILDDIR > /dev/null
logmsg "Building 64-bit"
make_clean
logmsg "--- Running phpize"
logcmd /opt/php$PHPVER/bin/phpize || \
logerr "--- phpize failed"
configure64
make_prog64
make_install64
popd > /dev/null
}
init
download_source memcached memcached $VER
patch_source
prep_build
build
make_isa_stub
make_package
clean_up
# Vim hints
# vim:ts=4:sw=4:et:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.