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
|
|---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 1,185
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
using System;
using HotChocolate.Types.Helpers;
namespace HotChocolate.Types.Descriptors
{
internal class EnumTypeNameDependencyDescriptor
: IEnumTypeNameDependencyDescriptor
{
private readonly IEnumTypeDescriptor _descriptor;
private readonly Func<INamedType, NameString> _createName;
public EnumTypeNameDependencyDescriptor(
IEnumTypeDescriptor descriptor,
Func<INamedType, NameString> createName)
{
_descriptor = descriptor
?? throw new ArgumentNullException(nameof(descriptor));
_createName = createName
?? throw new ArgumentNullException(nameof(createName));
}
public IEnumTypeDescriptor DependsOn<TDependency>()
where TDependency : IType
{
TypeNameHelper.AddNameFunction(
_descriptor, _createName, typeof(TDependency));
return _descriptor;
}
public IEnumTypeDescriptor DependsOn(Type schemaType)
{
TypeNameHelper.AddNameFunction(
_descriptor, _createName, schemaType);
return _descriptor;
}
}
}
|
Markdown
|
UTF-8
| 3,138
| 3.890625
| 4
|
[
"MIT"
] |
permissive
|
#### C++ Arrays and Vectors
---
# Vectors are Array++
A **[[C++ Include vector|vector]]** is an ordered list of items of a given data type.
Each item in a vector is called an **element**.
```cpp
#include <vector>
// vector<dataType> identifier(numElements);
vector<int> myVector(5); // an integer vector with 5 elements
/*
Though if you assign a vector a size of 5 the true size is still using the 0..n array indexing. so if you say:
*/
vector<int> myVector(5);
/*
and then try to access element 5:
*/
myVector.at(5); // <-- ERROR! 5 elements at index 0..4
```
## Iterating Through a Vector
Using [[C++ For Loops]] on a vector can be a little irritating at first with the size declaration but usage of array indexing:
```cpp
// These give a variable to reference the size of the vector
const int NUM_ELEMENTS = 3;
vector<int> userVals(NUM_ELEMENTS);
// test case
userVals.at(0) = 2;
userVals.at(1) = 7;
userVals.at(2) = 4;
/*
where i < NUM_ELEMENTS is to say it quits if it is larger than 2
i.e. 3. NUM_ELEMENTS goes up to 3, but because of the array indexing
the true values are 0, 1, & 2 as shown above in the test case
*/
for (int i = 0; i < NUM_ELEMENTS; ++i) {
cout << userVals.at(i) << endl;
}
//#> 2, 7, 4
```
An even easier way of doing the same thing without an unnecessary `const` variable is to use `.size()`
```cpp
vector<int> userVals(3);
// test case
userVals.at(0) = 2;
userVals.at(1) = 7;
userVals.at(2) = 4;
/*
the size is 3 so if i < 3 which is what the prior example also showed
*/
for (int i = 0; i < userVals.size(); ++i) {
cout << userVals.at(i) << endl;
}
//#> 2, 7, 4
```
## Reversing a vector
```cpp
const int NUM_ELEMENTS = 8; // Number of elements
vector<int> revVctr(NUM_ELEMENTS); // User values
unsigned int i; // Loop index
int tmpValue; // Placeholder
// User populates the vector
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < revVctr.size(); ++i) {
cout << "Value: ";
cin >> revVctr.at(i);
}
// Reverse the vector (this doesnt take into account an odd # of vals)
// Size returns the amount of values in a vector, the exact number of
// indexes is really -1 but to rever a vector we really only need to
// pivot around a mid point or in this case a middle value or half of
// the vector's size hence .size() / 2 below
for (i = 0; i < (revVctr.size() / 2); ++i) {
// temp value holds the values one by one starting from the left i=1
tmpValue = revVctr.at(i);
// .size() - 1 as that is the true last index of the vector and -i
// so we can begin to move towards the center values right to left
// i starts off at 0 so the first iteration is in reality swapping
// the first and last elements of a vector
revVctr.at(i) = revVctr.at(revVctr.size() - 1 - i);
// Referring again to the true last element of the vector receiving
// the true last index of the vector receiving the value of the first
// this is the end of the swap
revVctr.at(revVctr.size() - 1 - i) = tmpValue;
}
```
---
Related:
- [[Python Data Structures]]
- [[Bash Variables#Double Parentheses]]
|
Markdown
|
UTF-8
| 1,386
| 2.953125
| 3
|
[
"Apache-2.0"
] |
permissive
|
## nginx缓存
```shell
# 设置缓存保存的目录
#levels ⽬录分级
#keys_zone 设置共享内存以及占用的空间大小,开启的keys空间名字:空间⼤⼩(1m可以存放8000个key)
# max_size 设置缓存大小,⽬录最⼤⼤⼩(超过时,不常⽤的将被删除)
# inactive 超过此时间,没有被访问的缓存将清理
# use_temp_path 设置临时目录。 off关闭临时目录
proxy_cache_path /usr/local/nginx/upstearm_cache
levels=1:2 #⽬录分级
keys_zone=mycache:5m
max_size=1G
inactive=30s
use_temp_path=off;
server {
listen 80;
server_name localhost;
# 开启并且使用缓存
proxy_cache mycache;
# 针对200和304状态码的缓存设置过期时间
proxy_cache_valid 200 304 8h;
proxy_cache_valid any 10m; #其他状态缓存10⼩时
proxy_cache_key $host$uri$is_args$args; #设置key值
add_header Nginx-Cache "$upstream_cache_status";
location / {
root /home;
# 设置缓存过期时间
expires 10s;
}
}
```
### 命令
* expires [time] : 设置缓存过期时间
* expires @[time] : 设置缓存刷新时间。
* `expires @22h30m` : 每天22点30分刷新。
* expires -[time]: 缓存在多少时间前已经失效了。
* expires epoch : 不使用缓存。
* expires off : 默认配置,关闭nginx 缓存配置。
* expires max : 设置缓存最大过期时间。
|
JavaScript
|
UTF-8
| 1,961
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
import React from 'react'
const updaters = new Set()
let time = Date.now(),
hash = 10,
delta = 0.017
requestAnimationFrame(function loop() {
let newTime = Date.now()
delta = (newTime - time) / 1000
time = newTime
hash = (hash + 1) % 1024
updaters.forEach((updater) => updater(hash))
requestAnimationFrame(loop)
})
export function registerUpdate(callback: (hash: number) => any) {
updaters.add(callback)
}
export function withAnimation<T>(component: React.Component<T>) {
class Animated extends React.Component<T> {
shouldComponentUpdate(nextState) {
return this.state.hash != hash || nextState.hash == hash
}
componentWillMount() {
this.state.hash = hash - 1
this.state.updater = (hash) => {
this.setState({ hash })
}
updaters.add(this.state.updater)
}
componentWillUnmount() {
updaters.delete(this.state.updater)
}
render(props) {
return component({ ...props, delta: delta })
}
}
return (props: any) => <Animated {...props} />
}
let frameEdits = new Set()
registerUpdate((hash) => {
frameEdits.forEach((edit) => {
edit()
})
frameEdits = new Set()
})
// TODO: redo this cleaner, potentially actually passing update through
export const overStream = <P: Object, S: Object>(
stream: any,
propName: string,
initial?: any
) => (component: Component<P>): Component<P> => {
let value = initial
let valueStream = stream.skipDuplicates()
valueStream.onValue((v) => (value = v))
class Stream extends React.Component<P, S> {
componentDidMount() {
this.forceUpdateHandler = (v) =>
frameEdits.add((hash) => this.setState({ [propName]: v }))
valueStream.onValue(this.forceUpdateHandler)
}
componentWillUnmount() {
valueStream.offValue(this.forceUpdateHandler)
}
render(props) {
return component({ ...props, [propName]: value })
}
}
return (props) => <Stream {...props} />
}
|
Java
|
UTF-8
| 1,689
| 2.421875
| 2
|
[] |
no_license
|
package com.instagram_sample;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
public static final String INSTAGRAM_PACKAGE = "com.instagram.android";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
openInstagramApp();
}
});
}
public void openInstagramApp() {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/*");
// String imageurl = "file:///storage/emulated/0/Android/data/com.styl.android/cach
String imageurl = "file:///storage/emulated/0/Styl/Insta.jpg";
i.putExtra(Intent.EXTRA_STREAM, Uri.parse(imageurl));
i.putExtra(Intent.EXTRA_TEXT, "Hello Caption");
i.setPackage(INSTAGRAM_PACKAGE);
startActivity(i);
}
}
|
TypeScript
|
UTF-8
| 890
| 2.609375
| 3
|
[] |
no_license
|
const { ApolloServer, gql } = require("apollo-server");
const books = [
{
title: "Harry Potter and the Chamber of Secrets",
author: "J.K. Rowling"
},
{
title: "Jurassic Park",
author: "Michael Crichton"
}
];
const resolvers = {
Query: {
books: () => books
},
Mutation: {
addBook: (_: any, { title }: { title: string }) => {
books.push({ title, author: "qwewrefefew" });
return { success: true, books };
}
}
};
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
type Mutation {
addBook(title: String!): Res
}
type Res {
success: Boolean!
books: [Book]
}
`;
const server = new ApolloServer({ typeDefs, resolvers });
// The `listen` method launches a web server.
server.listen().then(({ url }: { url: URL }) => {
console.log(`🚀 Server ready at ${url}`);
});
|
JavaScript
|
UTF-8
| 182
| 2.5625
| 3
|
[] |
no_license
|
export const getRandomNumber = (min, max) => Math.round(Math.random() * (max - min) + min);
export const getRandomArrayItem = (array) => array[getRandomNumber(0, array.length - 1)];
|
Java
|
UTF-8
| 616
| 2.4375
| 2
|
[] |
no_license
|
package rd.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AppUtil {
public static String getStatus(String source) {
List<String> newQualifier = new ArrayList<String>(Arrays.asList("name card", "advertisement"));
List<String> preQualifiedQualifier = new ArrayList<String>(Arrays.asList("conference", "trade show", "web", "personal contact"));
String status = "";
if (newQualifier.contains(source.toLowerCase())) {
status = "New";
} else if (preQualifiedQualifier.contains(source.toLowerCase())) {
status = "Pre-qualified";
}
return status;
}
}
|
Markdown
|
UTF-8
| 75,414
| 3.46875
| 3
|
[] |
no_license
|
# 0401. Sample Surveys in the Real World
In this chapter you will:
Discover that sampling errors occur in even the best samples.
Learn that nonsampling errors may occur.
See how question wording may impact survey responses.
Understand that the results that are reported from samples are typically not from a simple random sample.
Case Study: Obtaining a Sample for a Survey
Consider an opinion poll that reports the results, along with a margin of error, from a recent question asked of 1000 randomly selected American adults. Should we be happy? Perhaps not. For example, how many people did the polling company have to contact to get the 1000 to participate?
Many polls don’t tell the whole truth about their samples. However, the Pew Research Center for the People and the Press did tell the whole truth about its sampling methods to get the 1507 American adults for a particular survey. Here it is.
Landline Cell
Noncontacts 2464 3114
Not eligible 18,427 6084
Other 104 56
Unknown eligibility 3305 361
Refusals, breakoffs, and partials 4719 4836
Complete interview 902 605
Total called 29,921 15,056
Most polls are taken by telephone (both landline and cell), dialing numbers at random (to get both listed and unlisted telephone numbers) to get a random sample of households. It may be reasonable to consider a landline telephone number to represent a household, but a cell number typically represents one person and may represent a person whose residence has a landline telephone. According to Pew,「landline and cell phone numbers were sampled to yield a ratio of approximately two completed landline interviews to each cell phone interview.」In addition to the balance of landline and cell numbers, Pew made sure to contact telephone numbers that would be representative of the United States geographically.
Once the collection of telephone numbers was identified, each sampled landline and cell phone number was called a minimum of seven times (assuming the phone was not answered the first six times). Calls were「staggered over times of day and days of the week (including at least one daytime call) to maximize the chances of making contact with a potential respondent.」The Pew Research Center interviewers had to call a total of 44,977 telephone numbers (29,921 landline and 15,056 cell) to get its sample of 1507 (902 landline and 605 cell) respondents.
The calculation to get the response rate is more complicated than taking the number of completed interviews for landline and cell phone numbers divided by the total number of calls. The combined response rate for the poll netting 1507 respondents was 9% (10% of landline numbers and 7% of cell numbers). A higher-effort survey conducted by the Pew Research Center during the same time period resulted in a 22% combined response rate.
We know from Chapter 3 that a sample of 1507 people will give us an approximate margin of error of percentage points. Although Pew did obtain a sample of reasonable size, can we trust the results of this poll to make conclusions about all American adults? Can the results of the poll be extended to people who only have cell phones?
How Sample Surveys Go Wrong
Random sampling eliminates bias in choosing a sample and allows control of variability. So once we see the magic words「randomly selected」and「margin of error,」do we know we have trustworthy information before us? It certainly beats voluntary response, but not always by as much as we might hope. Sampling in the real world is more complex and less reliable than choosing a simple random sample (SRS) from a list of names in a textbook exercise. Confidence statements do not reflect all the sources of error that are present in practical sampling.
Most sample surveys are afflicted by errors other than random sampling errors. These errors can introduce bias that makes a confidence statement meaningless. Good sampling technique includes the art of reducing all sources of error. Part of this art is the science of Statistics, with its random samples and confidence statements. In practice, however, good statistics isn’t all there is to good sampling. Let’s look at sources of errors in sample surveys and at how samplers combat them.
Sampling Errors
Random sampling error is one kind of sampling error. The margin of error tells us how serious random sampling error is, and we can control it by choosing the size of our random sample. Another source of sampling error is the use of bad sampling methods, such as voluntary response. We can avoid bad methods. Unfortunately, nonsampling errors are not so easy to handle.
Errors in sampling
Sampling errors are errors caused by the act of taking a sample. They cause sample results to be different from the results of a census of the population.
Random sampling error is the deviation between the statistic and the parameter caused by chance in selecting a random sample. The margin of error in a confidence statement includes only random sampling error.
Nonsampling errors are errors not related to the act of selecting a sample from the population. They can be present even in a census.
Undercoverage occurs when some groups in the population have no chance of being included the sample.
Nonsampling Errors
Nonsampling errors are those that can plague even a census. Sampling begins with a list of individuals from which we will draw our sample. This list is called the sampling frame. Ideally, the sampling frame should list every individual in the population of interest. Because a list of the entire population is rarely available, the sampling frame is often not an accurate or complete representation of the population. This leads to errors known as frame errors. A common frame error is undercoverage.
If the sampling frame leaves out certain groups of people, even random samples from that frame will be biased. Using telephone directories as the frame for a telephone survey, for example, would miss everyone with an unlisted landline telephone number, everyone who cannot afford a landline phone, everyone who has a voice over Internet Protocol (VoIP) phone, and everyone who has only a cell phone. Recall from the Case Study that the Pew Research Center tries to balance its calls geographically, but both cell and VoIP numbers may betray the region the person with the number is actually in. For example, consider a household in Michigan that has no landline but has two cell phone numbers associated with its residents, one a 614 (Columbus, Ohio) area code and one a 602 (Phoenix, Arizona) area code.
Example 1
Did we miss anyone?
Most opinion polls can’t afford to even attempt full coverage of the population of all adult residents of the United States. The interviews are done by telephone, thus missing the 2% of households without phones, either landline, VoIP, or cell. Additionally, those without regular access to phones, like prison inmates, or to reliable cell service, like many deployed members of the armed forces, are left out. In addition, many polls in the United States interview only in English and Spanish, which leaves some immigrants with telephone numbers out of their samples. Those left out of these polls include a growing number of people who speak Arabic or Asian languages.
The kinds of undercoverage found in most sample surveys are most likely to leave out people who are young or poor or who move often. Nonetheless, random digit dialing comes close to producing a random sample of households with phones. Sampling errors in careful sample surveys are usually quite small. The real problems start when someone picks up (or doesn’t pick up) the phone.
Frame errors can also arise from erroneous inclusions and multiple inclusions. Erroneous inclusions can occur if the frame includes units that are not in the population of interest so that invalid units have a chance of being in the sample. Multiple inclusions occur if some population members appear multiple times in the sampling frame so that they have a higher chance of being sampled. For example, if the sampling frame is a telephone book, some members of the population may have multiple listings because they have multiple telephone lines.
Nonsampling errors also include processing errors—mistakes in mechanical tasks such as doing arithmetic or entering responses into a computer. Fortunately, the wide availability and adoption of computers has made processing errors less common than in the past.
Example 2
Computer-assisted interviewing
The days of the interviewer with a clipboard are gone. Contemporary interviewers carry a laptop computer for face-to-face interviews or watch a computer screen as they carry out a telephone interview. Computer software manages the interview. The interviewer reads questions from the computer screen and uses the keyboard to enter the responses. The computer skips irrelevant items—once a respondent says that she has no children, further questions about her children never appear. The computer can check that answers to related questions are consistent with each other. It can even present questions in random order to avoid any bias due to always asking questions in the same order.
Computer software also manages the record keeping. It keeps records of who has responded and prepares a file of data from the responses. The tedious process of transferring responses from paper to computer, once a source of processing errors, has disappeared. The computer even schedules the calls in telephone surveys, taking account of the respondent’s time zone and honoring appointments made by people who were willing to respond but did not have time when first called.
Another type of nonsampling error is response error, which occurs when a subject gives an incorrect response. A subject may lie about her age or income or about whether she has used illegal drugs. She may remember incorrectly when asked how many packs of cigarettes she smoked last week. A subject who does not understand a question may guess at an answer rather than appear ignorant. Questions that ask subjects about their behavior during a fixed time period are notoriously prone to response errors due to faulty memory. For example, the National Health Survey asks people how many times they have visited a doctor in the past year. Checking their responses against health records found that they failed to remember 60% of their visits to a doctor. A survey that asks about sensitive issues can also expect response errors, as the next example illustrates.
Example 3
The effect of race
In 1989, New York City elected its first black mayor and the state of Virginia elected its first black governor. In both cases, samples of voters interviewed as they left their polling places predicted larger margins of victory than the official vote counts. The polling organizations were certain that some voters lied when interviewed because they felt uncomfortable admitting that they had not voted for the black candidate. This phenomenon is known as「social desirability bias」and「the Bradley effect,」after Tom Bradley, the former black mayor of Los Angeles who lost the 1982 California gubernatorial election despite leading in final-day preelection polls.
This effect attracted media attention during the 2008 presidential election. A few weeks before the election, polls predicted a victory, possibly a big one, for Barack Obama. Even so, Democrats worried that these polls might be overly optimistic because of the Bradley effect. In this case their fears were unfounded, but some political scientists claimed to detect the Bradley effect in polls predicting outcomes in primary races between Barack Obama and Hillary Clinton (for example, in the New Hampshire primary, polls predicted an 8 percentage point Obama victory but Clinton won by 3 percentage points).
Even the 2016 presidential election included effects due to race, despite both major party candidates being white. According to The Washington Post,「whites were more divided based on their perceptions of discrimination against whites than they were in 2012.」As early as the primary election of 2016, The Washington Post reported「both white racial identity and beliefs that whites are treated unfairly are powerful predictors of support for Donald Trump in the Republican primaries.」Unlike the Bradley effect, this racial divide was less about social desirability and more about white voters fearing for their rights.
Technology and attention to detail can minimize processing errors. Skilled interviewers greatly reduce response errors, especially in face-to-face interviews. There is no simple cure, however, for the most serious kind of nonsampling error, nonresponse.
Key Terms
Nonresponse is the failure to obtain data from an individual selected for a sample. Most nonresponse happens because some subjects can’t be contacted or because some subjects who are contacted refuse to cooperate.
Nonresponse is the most serious problem facing sample surveys. People are increasingly reluctant to answer questions, particularly over the phone. The rise of telemarketing, voicemail, caller ID, and spoofed phone numbers drives down response to telephone surveys. Gated communities and buildings guarded by doormen prevent face-to-face interviews. Nonresponse can bias sample survey results because different groups have different rates of nonresponse. Refusals are higher in large cities and among the elderly, for example. Bias due to nonresponse can easily overwhelm the random sampling error described by a survey’s margin of error.
Example 4
How bad is nonresponse?
The U.S. Census Bureau’s American Community Survey (ACS) is a monthly survey of almost 300,000 housing units and replaced the U.S. Census Bureau’s「long form」that in the past was sent to some households in the decennial national census. Participation in the ACS is mandatory, and the U.S. Census Bureau follows up by telephone and then in person if a household fails to return the mail questionnaire.
The ACS has the lowest nonresponse rate of any poll we know: in 2016, only about 2.1% of the households in the sample refused to respond; the overall nonresponse rate, including「never at home」and other causes, was only 5.3%. This is a stark contrast in nonresponse from 2013 when overall response rate was 10.1%. What happened in October 2013? There was a government shutdown. During that time, there were no follow-ups by mail, phone, or in person, and the overall panel response rate was about 7 percentage points lower than is usual for the ACS. If October 2013 is excluded from the ACS when considering nonresponse, the nonresponse rate for 2013 was only 2.9%, similar to previous years.
Another survey that has a remarkable response rate is the University of Chicago’s General Social Survey (GSS), the nation’s most important social survey. The GSS (Example 7 in Chapter 1) contacts its sample in person, and it is run by a university. Despite these advantages, its recent surveys have a 30% rate of nonresponse.
What about polls done by the media and by market research and opinion-polling firms? We often don’t know their rates of nonresponse because they won’t say. That itself is a bad sign. The Pew Poll we looked at in the Case Study suggests how bad things are. Pew got 1507 responses and 15,293 who were never at home, refused, or would not finish the interview. That’s a nonresponse rate of 15,293 out of 16,800, or 91%. We should keep in mind that Pew researchers are more thorough than many pollsters.
Sample surveyors know some tricks to reduce nonresponse. Carefully trained interviewers can keep people on the line if they answer at all. Calling back over longer time periods helps. So do letters sent in advance. Letters and many callbacks slow down the survey, so opinion polls that want fast answers to satisfy the media don’t use them. Even the most careful surveys find that nonresponse is a problem that no amount of expertise can fully overcome. That makes the reminder in the box to the right even more important.
What the margin of error doesn’t say
The announced margin of error for a sample survey covers only random sampling error. Undercoverage, nonresponse, and other practical difficulties can cause large bias that is not covered by the margin of error.
Careful sample surveys warn us about the other kinds of error. The Pew Research Center, for example, says,「In addition to sampling error, one should bear in mind that question wording and practical difficulties in conducting surveys can introduce error or bias into the findings of opinion polls.」How true it is.
Statistics in Your World
He started it! A study of deaths in bar fights showed that in 90% of the cases, the person who died started the fight. You shouldn’t believe this. If you killed someone in a fight, what would you say when the police asked you who started the fight? After all, dead men tell no tales. Now that’s nonresponse!
Does nonresponse make many sample surveys useless? Maybe not. We began this chapter with an account of a「standard」telephone survey done by the Pew Research Center. The Pew researchers also carried out a「rigorous」survey, with letters sent in advance, unlimited calls over eight weeks, letters by priority mail to people who refused, and so on. All this drove the rate of nonresponse down to 78%, compared with 91% for the standard survey. Pew then compared the answers to the same questions from the two surveys. The two samples were quite similar in age, sex, and race, though the rigorous sample was a bit more prosperous. The two samples also held similar opinions on all issues except one: race. People who at first refused to respond were less sympathetic toward the plights of blacks and other minorities than those who were willing to respond when contacted the first time. Overall, it appears that standard polls give reasonably accurate results. But, as in Example 3, race is again an exception.
Wording of Questions
A final influence on the results of a sample survey is the exact wording of questions. It is surprisingly difficult to word the questions so that they are completely clear. A survey that asks「Do you enjoy watching football?」will generate different answers based on the respondent’s understanding of「football」(American football or soccer).
Example 5
Words make a big difference
In May 2013, the Pew Research Center and the Washington Post/ABC News conducted polls asking whether people felt the U.S. Department of Justice had the right to subpoena Associated Press reporters’ phone records. Each survey phrased the question differently, and each survey found different results.
When the Pew Research Center asked,「Do you approve or disapprove of the Justice Department’s decision to subpoena the phone records of AP journalists as part of an investigation into the disclosure of classified information,」36% of respondents approved. The Washington Post/ABC News survey said,「The AP reported classified information about U.S. anti-terrorism efforts and prosecutors have obtained AP’s phone records through a court order. Do you think this action by federal prosecutors is or is not justified?」Fifty-two percent (52%) of respondents to this survey said that the action of federal prosecutors was justified.
Before asking about approval or disapproval of the Justice Department’s actions, Pew asked how closely respondents had followed the issues that led up to the subpoena, and 64% reported not following the news story too closely. Additionally, the difference in wording—「decision to subpoena」in the Pew Research survey versus「obtained... through a court order」used by the Washington Post/ABC News survey—could have led to legitimizing the actions of the Department of Justice and thus a higher「approval」for the Justice Department’s actions. Or, was the higher justification based on the inclusion of the mention of U.S. anti-terrorism efforts? Or, perhaps the difference is due to Pew using「the Justice Department」and the Washington Post/ABC News using「federal prosecutors.」We cannot begin to determine which part of the wording impacted the responses. As the Pew Research Center said in its article comparing the results of these two surveys,「each polling organization made good-faith efforts to describe the facts of the situation as accurately as possible, but the word choices and context make it impossible to identify one particular phrase or concept that tipped the public’s thinking.」
The wording of questions always influences the answers. If the questions are slanted to favor one response over others, we have another source of nonsampling error. A favorite trick is to ask if the subject favors some policy as a means to a desirable end:「Do you favor banning private ownership of handguns in order to reduce the rate of violent crime?」and「Do you favor imposing the death penalty in order to reduce the rate of violent crime?」are loaded questions that draw positive responses from people who are worried about crime. Here is another example of the influence of question wording.
Example 6
Paying taxes
In April 2018, a Gallup Poll asked two questions about the amount one pays in federal income taxes. Here are the two questions:
Do you consider the amount of federal income tax you have to pay as too high, about right, or too low?
Do you regard the income tax which you will have to pay this year as fair?
The first question had 48% of respondents say「about right」(45% said「too high」) while the second question resulted in 61% of respondents saying that the taxes they paid were「fair.」There appears to be a definite difference in opinions about taxes when people are asked about the amount they have to pay or whether it is fair.
Now it’s your turn
4.1 Should we recycle? Is the following question slanted toward a desired response? If so, how?
In view of escalating environmental degradation and incipient resource depletion, would you favor economic incentives for recycling of resource-intensive consumer goods?
How to Live with Nonsampling Errors
Nonsampling errors, especially nonresponse, are always with us. What should a careful sample survey do about this? First, substitute other households for the nonresponders. Because nonresponse is higher in cities, replacing nonresponders with other households in the same neighborhood may reduce bias. Once the data are in, all professional surveys use statistical methods to weight the responses in an attempt to correct sources of bias. If many urban households did not respond, the survey gives more weight to those that did respond. If too many women are in the sample, the survey gives more weight to the men. Here, for example, is part of a statement in the New York Times describing one of its sample surveys:
The results have been weighted to take account of household size and number of telephone lines into the residence and to adjust for variations in the sample relating to geographic region, sex, race, age and education.
The goal is to get results「as if」the sample matched the population in age, gender, place of residence, and other variables.
The practice of weighting creates job opportunities for statisticians. It also means that the results announced by a sample survey are rarely as simple as they seem to be. In April 2018, Gallup announced that it interviewed 1509 adults and found that 56% of them have a Facebook account. It would seem that because 56% of 1509 is 845, Gallup found that 845 people in its sample had a Facebook account. Not so. Gallup no doubt used some quite fancy statistics to weight the actual responses: 56% is Gallup’s best estimate of what it would have found in the absence of nonresponse. Weighting does help correct bias. It usually also increases variability. The announced margin of error must take this into account, creating more work for statisticians.
Sample Design in the Real World
The basic idea of sampling is straightforward: take an SRS from the population and use a statistic from your sample to estimate a parameter of the population. We now know that the statistic is altered behind the scenes to partly correct for nonresponse. The statisticians also have their hands on our beloved SRS. In the real world, most sample surveys use more complex designs.
Example 7
The Current Population Survey
The population that the Current Population Survey (CPS) is interested in consists of all households in the United States. The scientifically chosen sample of about 60,000 occupied households is chosen in stages. The U.S. Census Bureau divides the nation into 2025 geographic areas called Primary Sampling Units (PSUs). These are generally groups of neighboring counties. At the first stage, 824 PSUs are chosen. This isn’t an SRS. If all PSUs had the same chance to be chosen, the sample might miss Chicago and Los Angeles. So 446 highly populated PSUs are automatically in the sample. The other 1579 are divided into 378 groups, called strata, by combining PSUs that are similar in various ways. One PSU is chosen at random to represent each stratum.
U.S. Census Bureau/Photo by Syda Productions/Shutterstock
Each of the 824 PSUs in the first-stage sample is divided into census blocks (smaller geographic areas). The blocks are also grouped into strata, based on such things as housing types and minority population. The households in each block are arranged in order of their location and divided into groups, called clusters, of about four households each. The final sample consists of samples of clusters (not of individual households) from each stratum of blocks. Interviewers go to all households in the chosen clusters. The samples of clusters within each stratum of blocks are also not SRSs. To be sure that the clusters spread out geographically, the sample starts at a random cluster and then takes, for example, every 10th cluster in the list.
The design of the CPS illustrates several ideas that are common in real-world samples that use face-to-face interviews. Taking the sample in several stages with clusters at the final stage saves travel time for interviewers by grouping the sample households first in PSUs and then in clusters. Note that clustering is not an aspect of all sampling strategies but can be quite helpful in situations like the CPS.
The most important refinement mentioned in Example 7 is stratified sampling, which is described in the box to the right.
Stratified sample
To choose a stratified random sample:
Step 1. Divide the sampling frame into distinct groups of individuals, called strata. Choose the strata according to any special interest you have in certain groups within the population or because the individuals in each stratum resemble each other.
Step 2. Take a separate SRS in each stratum and combine these to make up the complete sample.
We must of course choose the strata using facts about the population that are known before we take the sample. You might group a university’s students into undergraduate and graduate students or into those who live on campus and those who commute. Stratified samples have some advantages over an SRS. First, by taking a separate SRS in each stratum, we can set sample sizes to allow separate conclusions about each stratum. Second, a stratified sample usually has a smaller margin of error than an SRS of the same size. The reason is that the individuals in each stratum are more alike than the population as a whole, so working stratum-by-stratum eliminates some variability in the sample.
It may surprise you that stratified samples can violate one of the most appealing properties of the SRS—stratified samples need not give all individuals in the population the same chance to be chosen. Some strata may be deliberately overrepresented in the sample.
Example 8
Stratifying a sample of students
A large university has 30,000 students, of whom 3000 are graduate students. An SRS of 500 students gives every student the same chance to be in the sample. That chance is
We expect an SRS of 500 to contain only about 50 grad students—because grad students make up 10% of the population, we expect them to make up about 10% of an SRS. A sample of size 50 isn’t large enough to estimate grad student opinion with reasonable accuracy. We might prefer a stratified random sample of 200 grad students and 300 undergraduates.
You know how to select such a stratified sample. Label the graduate students 0001 to 3000 and use Table A to select an SRS of 200. Then label the undergraduates 00001 to 27000 and use Table A a second time to select an SRS of 300 of them. These two SRSs together form the stratified sample.
In the stratified sample, each grad student has chance
to be chosen. Each of the undergraduates has a smaller chance,
Because we have two SRSs, it is easy to estimate opinions in the two groups separately. The quick and approximate method (page 43) tells us that the margin of error for a sample proportion will be about
for grad students and about
for undergraduates.
Because the sample in Example 8 deliberately overrepresents graduate students, the final analysis must adjust for this to get unbiased estimates of overall student opinion. Remember that our quick method works only for an SRS. In fact, a professional analysis would also take account of the fact that the population contains「only」30,000 individuals—more job opportunities for statisticians.
Now it’s your turn
4.2 A stratified sample. The statistics department at Cal Poly, San Luis Obispo, has 18 faculty members and 80 undergraduate majors. Use the Simple Random Sample applet, other software, or Table A, starting at line 111, to choose a stratified sample of 1 faculty member and 1 student to attend a reception being held by the university president.
Example 9
The woes of telephone samples
In principle, it would seem that a telephone survey that dials numbers at random could be based on an SRS. Telephone surveys have little need for clustering. Stratifying can still reduce variability, however, and so telephone surveys often take samples in two stages: a stratified sample of telephone number prefixes (area code plus first three digits) followed by individual numbers (last four digits) dialed at random in each prefix.
The real problem with an SRS of telephone numbers is that too few numbers lead to households. Blame technology. Fax numbers, cell phones, and Voice over Internet Protocols (VoIP) demand new phone numbers. Between 1997 and 2017, the number of households in the United States grew by 25%, but the number of possible phone numbers continues to grow as more individuals have access to cell phones. Some analysts believe that in the near future we may have to increase the number of digits for telephone numbers from 10 (including the area code) to 12. This will further exacerbate this problem. Telephone surveys now use「list-assisted samples」that check electronic telephone directories to eliminate prefixes that have no listed numbers before random sampling begins. Fewer calls are wasted, but anyone living where all numbers are unlisted is missed. Prefixes with no listed numbers are therefore separately sampled (stratification again), perhaps with a smaller sample size than if included in the list-assisted sample, to fill the gap.
The proliferation of cell phones has created additional problems for telephone samples. As of December 2017, about 53.9% of households had cell phones only. Random digit dialing using a machine is not allowed for cell phone numbers. Phone numbers assigned to cell phones are determined by the location of the cell phone company providing the service and need not coincide with the actual residence of the user. This makes it difficult to implement sophisticated methods of sampling, such as stratified sampling by geographic location.
It may be that the woes of telephone sampling prompted the Gallup Organization, in recent years, to drop the phrase「random sampling」from the description of their survey methods at the end of most of their polls. This presumably prevents misinterpreting the results as coming from simple random samples. In their detailed description of survey methods used for the Gallup World Poll and the Gallup Well-Being Index (available online at the Gallup website), the samples are described as involving random sampling.
This might be a good place to read the「What’s the verdict?」story on page 85, and to answer the questions. These questions involve material from this chapter and Chapter 3 to assess some puzzling results from the National Longitudinal Study of Adolescent Health.
The Challenge of Internet Surveys
The Internet is having a profound effect on many things people do, and this includes surveys. Using the Internet to conduct「Web surveys」is becoming increasingly popular. Web surveys have several advantages over more traditional survey methods. It is possible to collect large amounts of survey data at lower costs than traditional methods allow. Anyone can put survey questions on dedicated sites offering free services; thus, large-scale data collection is available to almost every person with access to the Internet. Furthermore, Web surveys allow one to deliver multimedia survey content to respondents, opening up new realms of survey possibilities that would be extremely difficult to implement using traditional methods. Some argue that eventually Web surveys will replace traditional survey methods.
Statistics in Your World
New York, New York New York City, they say, is bigger, richer, faster, and ruder. Maybe there’s something to that. The sample survey firm Zogby International says that as a national average, it takes 5 calls to reach a live person. When trying to reach respondents in New York City, it takes 12 calls. Survey firms assign their best interviewers to make calls to New York City and often pay them bonuses to cope with the stress.
Although Web surveys are easy to do, they are not easy to do well. The reasons include many of the issues we have discussed in this chapter. Three major problems are voluntary response, undercoverage, and nonresponse. Voluntary response appears in several forms. Some Web surveys invite visitors to a particular website to participate in a poll. Misterpoll.com is one such example. Visitors to this site can participate in several ongoing polls, create their own poll, and respond multiple times to the same poll. Other Web surveys solicit participation through announcements in newsgroups, email invitations, and banner ads on high-traffic sites. An example is a series of 10 polls conducted by Georgia Tech University’s Graphic, Visualization, and Usability Center (GVU) in the 1990s.
Although misterpoll.com indicates that the surveys on the site are primarily intended for entertainment, the GVU polls appear to claim some measure of legitimacy. The website www.cc.gatech.edu/gvu/user_surveys/ states that the information from these surveys「is valued as an independent, objective view of developing Web demographics, culture, user attitudes, and usage patterns.」
A third and more sophisticated example of voluntary response occurs when the polling organization creates what it believes to be a representative panel consisting of volunteers and uses panel members as a sampling frame. A random sample is selected from this panel, and those selected are invited to participate in the poll. A very sophisticated version of this approach is used by the Harris Poll Online.
Web surveys, such as the Harris Poll Online, in which a random sample is selected from a well-defined sampling frame, are reasonable when the sampling frame clearly represents some larger population or when interest is only in the members of the sampling frame. An example are Web surveys that use systematic sampling to select every th visitor to a site and the target population is narrowly defined as visitors to the site. Another example are some Web surveys on college campuses. All students may be assigned email addresses and have Internet access. A list of these email addresses serves as the sampling frame, and a random sample is selected from this list. If the population of interest is all students at this particular college, these surveys can potentially yield very good results. Here is an example of this type of Web survey.
Example 10
Doctors and placebos
A placebo is a dummy treatment like a salt pill that has no direct effect on a patient but may bring about a response because patients expect it to. Do academic physicians who maintain private practices sometimes give their patients placebos? A Web survey of doctors in internal medicine departments at Chicago-area medical schools was possible because almost all doctors had listed email addresses.
Send an email to each doctor explaining the purpose of the study, promising anonymity, and giving an individual a Web link for response. Result: 45% of respondents said they sometimes use placebos in their clinical practice.
Several other Web survey methods have been employed to eliminate problems arising from voluntary response. One is to use the Web as one of many alternative ways to participate in the survey. The Bureau of Labor Statistics and the U.S. Census Bureau have used this method. Another method is to select random samples from panels, but instead of relying on volunteers to form the panels, members are recruited using random sampling (for example, random digit dialing). Telephone interviews can be used to collect background information, identify those with Internet access, and recruit eligible persons to the panel. If the target population is current users of the Internet, this method should also potentially yield reliable results. The Pew Research Center has employed this method.
Perhaps the most ambitious approach, and one that attempts to obtain a random sample from a more general population, is the following. Take a probability sample (defined on the next page) from the population of interest. Provide all those selected with the necessary equipment and tools to participate in subsequent Web surveys. This methodology is similar in spirit to that used for the Nielsen TV ratings. It was employed by one company, InterSurvey, several years ago, although InterSurvey is no longer in business.
Several challenges remain for those who employ Web surveys. Even though Internet and email use is growing (according to a February 2018 Pew Research Center report, 89% of American adults aged 18 and older have Internet access), there is still the problem of undercoverage if Web surveys are used to draw conclusions about all American adults aged 18 and older. Weighting responses to correct for possible biases does not solve the problem because studies indicate that Internet users differ in many ways that traditional methods of weighting do not account for.
In addition, even if 100% of Americans had Internet access, there is no list of Internet users that we can use as a sampling frame, nor is there anything comparable to random digit dialing that can be used to draw random samples from the collection of all Internet users.
Finally, Web surveys often have very high rates of nonresponse. Methods that are used in phone and mail surveys to improve response rates can help, but they make Web surveys more expensive and difficult, offsetting some of their advantages.
Statistical controversies
The Harris Online Poll
The Harris Poll Online has created an online research panel of over 6 million volunteers. According to the Harris Poll Online website, the「panel consists of a diverse cross-section of people residing in the United States, as well as in over 200 countries around the world,」and「this multimillion member panel consists of potential respondents who have been recruited through online, telephone, mail, and in-person approaches to increase population coverage and enhance representativeness.」One can join the panel at https://www.harrispollonline.com/#homepage.
When the Harris Poll Online conducts a survey, this panel serves as the sampling frame. A probability sample is selected from it, and statistical methods are used to weight the responses. In particular, the Harris Poll Online uses propensity score weighting, a proprietary Harris Interactive technique, which is also applied (when applicable) to adjust for respondents’ likelihood of being online. They claim that「this procedure provides added assurance of accuracy and representativeness.」
Are you convinced that the Harris Poll Online provides accurate information about well-defined populations such as all American adults? Why or why not?
For more information about the Harris Poll Online and Web surveys in general, see https://theharrispoll.com/ and in a special issue of Public Opinion Quarterly available online at https://academic.oup.com/poq/issue/72/5.
Probability Samples
It’s clear from Examples 7, 8, and 9, and from the challenges of using the Internet to conduct surveys, that designing samples is a business for experts. Even most statisticians don’t qualify. We won’t worry about such details. The big idea is that good sample designs use chance to select individuals from the population. That is, all good samples are probability samples.
Key Terms
A probability sample is a sample chosen by chance. We must know what samples are possible and what chance, or probability, each possible sample has. Some probability samples, such as stratified samples, don’t allow all possible samples from the population and may not give an equal chance to all the samples they do allow. As such, not all probability samples are random samples.
A stratified sample of 300 undergraduate students and 200 graduate students, for example, allows only samples with exactly that makeup. An SRS would allow any 500 students. Both are probability samples. We need only know that estimates from any probability sample share the nice properties of estimates from an SRS. Confidence statements can be made without bias and have smaller margins of error as the size of the sample increases. Nonprobability samples such as voluntary response samples do not share these advantages and cannot give trustworthy information about a population. Now that we know that most nationwide samples are more complicated than an SRS, we will usually go back to acting as if good samples were SRSs. That keeps the big idea and hides the messy details.
Questions to Ask before You Believe a Poll
Opinion polls and other sample surveys can produce accurate and useful information if the pollster uses good statistical techniques and also works hard at preparing a sampling frame, wording questions, and reducing nonresponse. Many surveys, however, especially those designed to influence public opinion rather than just record it, do not produce accurate or useful information. Here are some questions to ask before you pay much attention to poll results.
Who carried out the survey? Even a political party should hire a professional sample survey firm whose reputation demands that they follow good survey practices.
What was the population? That is, whose opinions were being sought?
How was the sample selected? Look for mention of random sampling.
How large was the sample? Even better, find out both the sample size and the margin of error within which the results of 95% of all samples drawn as this one was would fall.
What was the response rate? That is, what percentage of the original subjects actually provided information?
How were the subjects contacted? By telephone? Mail? Face-to-face interview?
When was the survey conducted? Was it just after some event that might have influenced opinion?
What were the exact questions asked?
Academic survey centers and government statistical offices answer these questions when they announce the results of a sample survey. National opinion polls usually don’t announce their response rate (which is often low) but do give us the other information. Editors and newscasters have the bad habit of cutting out these dull facts and reporting only the sample results. Many sample surveys by interest groups and local newspapers and TV stations don’t answer these questions because their polling methods are in fact unreliable. If a politician, an advertiser, or your local TV station announces the results of a poll without complete information, be skeptical.
Chapter 4 Summary and Exercises
Chapter 4: Statistics in Summary
Sampling in the real world is complex. Even professional sample surveys don’t give exactly correct information about the population.
There are many potential sources of error in sampling. The margin of error announced by a sample survey covers only random sampling error, the variation due to chance in choosing a random sample.
Sampling errors come from the act of choosing a sample. Random sampling error or the use of bad sampling methods are common types of sampling error.
The most serious errors in most careful surveys, however, are nonsampling errors. These have nothing to do with choosing a sample—they are present even in a census.
Frame errors can occur because the sampling frame, the list from which the sample is actually chosen, is not an accurate representation of the population. One such error is undercoverage. Undercoverage occurs when some members of the population are left out of the sampling frame. Other frame errors occur if the frame includes units not in the population of interest and if the frame lists units multiple times.
The most challenging problem for sample surveys is nonresponse: subjects can’t be contacted or refuse to answer.
Mistakes in handling the data (processing errors) and incorrect answers by respondents (response errors) are other examples of nonsampling errors.
Finally, the exact wording of questions has a big influence on the answers.
People who design sample surveys use statistical techniques that help correct nonsampling errors, and they also use probability samples more complex than simple random samples, such as stratified samples.
You can assess the quality of a sample survey quite well by just looking at the basics: use of random samples, sample size and margin of error, the rate of nonresponse, and the wording of the questions.
This chapter summary will help you evaluate the Case Study.
Link It
In Chapter 3 we saw that random samples can provide a sound basis for drawing conclusions about a parameter. In this chapter, we learn that even when we take a random sample, our conclusions can be weakened by undercoverage, processing errors, response error, nonresponse, and wording of questions. We must pay careful attention to every aspect of how we collect data to ensure that the conclusions we make are valid. In some cases, more complex probability samples, such as stratified samples, can help correct nonsampling errors. This chapter provides a list of questions you can ask to help you assess the quality of the results of samples collected by someone else.
Case Study Evaluated
Use what you have learned in this chapter to evaluate the Case Study that opened the chapter. Start by reviewing the Chapter Summary. Then communicate clearly enough for any of your classmates to understand what you are saying.
Use what you have learned about what sampling errors are, how nonsampling errors and question wording may impact survey results, and how the results reported from samples are typically not from an SRS to evaluate the Case Study that opened the chapter. In particular, answer the questions given in the section「Questions to Ask before You Believe a Poll」on page 75. Are the results of the Pew poll useless? You may want to refer to the discussion on pages 59–60.
In this chapter you have:
Discovered that sampling errors occur in even the best samples.
Learned that nonsampling errors may occur.
Saw how question wording may impact survey responses.
Understood that the results that are reported from samples are typically not from a simple random sample.
Online Resources
The video technology manuals explain how to select an SRS using JMP, Excel, R, Minitab, CrunchIt!, SPSS, and the TI 83/84.
The Statistical Applet, Simple Random Sample, can be used to select a simple random sample when the number of labels is 144 or less.
Check the Basics
For Exercise 4.1, see page 67; for Exercise 4.2, see page 71.
4.3 What does the margin of error include? When a margin of error is reported for a survey, it includes
random sampling error and other practical difficulties like undercoverage and non-response.
random sampling error, but not other practical difficulties like undercoverage and nonresponse.
practical difficulties like undercoverage and nonresponse, but not random sampling error.
None of the above is correct.
4.4 What kind of sample? Archaeologists plan to examine a sample of 2-meter square plots near an ancient Greek city for artifacts visible in the ground. They choose separate samples of plots from floodplain, coast, foothills, and high hills. What kind of sample is this?
A simple random sample
A voluntary response sample
A stratified sample
A cluster sample
4.5 Sampling issues. A sample of households in a community is selected at random from the telephone directory. In this community, 4% of households have no telephone, 10% have only cell phones, and another 25% have unlisted telephone numbers. The sample will certainly suffer from
nonresponse.
undercoverage.
false responses.
all of the above.
4.6 Question wording. Which of the following represents wording that will most likely not influence the answers?
Do you think that all instances of academic misconduct should be reported to the dean?
Academic misconduct undermines the integrity of the university and education in general. Do you believe that all instances of academic misconduct should be reported to the dean?
Academic misconduct can range from something as minor as using one’s own work in two courses to major issues like cheating on exams and plagiarizing. Do you believe that all instances of academic misconduct should be reported to the dean?
None of the above will influence the answers.
4.7 Sampling considerations. A Statistics class has 10 graduate students and 40 undergraduate students. You want to randomly sample 10% of the students in the class. One graduate student and four undergraduate students are selected at random. Which of the following is not correct?
Because each student has a 10% chance of being selected, this is a simple random sample.
Because each sample includes exactly one graduate student and four undergraduate students, this is not a random sample.
It is possible to get a sample that contains only graduate students.
It is possible to get a sample that contains only undergraduate students.
Chapter 4 Exercises
4.8 What kind of error? Which of the following are sources of sampling error and which are sources of nonsampling error? Explain your answers.
The subject lies about past illegal drug use.
A typing error is made in recording the data.
Data are gathered by asking people to go to a website and answer questions online.
4.9 What kind of error? Each of the following is a source of error in a sample survey. Label each as sampling error or nonsampling error, and explain your answers.
The telephone directory is used as a sampling frame.
The subject cannot be contacted in five calls.
Interviewers choose people on the street to interview.
4.10 Not in the margin of error. According to a December 2017 Gallup Poll, 7% of American adults report soccer as their favorite sport, up from 4% in June 2013 and just 2% in April 1997. This may seem low to you, but the United States is catching up to the rest of the world in its interest in soccer. The survey methods section of the poll states:
For results based on the total sample of national adults, the margin of sampling error is ±4 percentage points at the 95% confidence level. All reported margins of sampling error include computed design effects for weighting.
Give one example of a source of error in the poll result that is not included in this margin of error.
4.11 Not in the margin of error. According to an April 2018 survey, a majority of employed American adults (59%) are confident about their job security, stating it is not at all likely for them to lose their job or be laid off in the next 12 months. The survey methods section of the poll states:
For results based on the total sample of employed adults, the margin of sampling error is ±5 percentage points at the 95% confidence level. All reported margins of sampling error include computed design effects for weighting.
Give one example of a source of error in the poll result that is not included in this margin of error.
4.12 College parents. An online survey of college parents was conducted during February and March 2007. Emails were sent to 41,000 parents who were listed in either the College Parents of America database or the Student Advantage database. Parents were invited to participate in the online survey. Out of those invited, 1727 completed the online survey. The survey protected the anonymity of those participating in the survey but did not allow more than one response from an individual IP address.
One of the survey results was that 33% of mothers communicate at least once a day with their child while at school.
What was the response rate for this survey? (The response rate is the percentage of the planned sample—that is, those invited to participate—who responded.)
Use the quick method (page 43) to estimate the margin of error for a random sample of size 1727.
Do you think that the margin of error is a good measure of the accuracy of the survey’s results? Explain your answer.
4.13 Polling customers. An online store chooses an SRS of 100 customers from its list of all people who have bought something from the store in the last year. It asks those selected how satisfied they are with the store’s website. If it selected two SRSs of 100 customers at the same time, the two samples would give somewhat different results. Is this variation a source of sampling error or of nonsampling error? Would the survey’s announced margin of error take this source of error into account?
4.14 Ring-no-answer. A common form of non-response in telephone surveys is「ring-no-answer.」That is, a call is made to an active number but no one answers. The Italian National Statistical Institute looked at nonresponse to a government survey of households in Italy during the periods January 1 to Easter and July 1 to August 31. All calls were made between 7 and 10 P.M., but 21.4% gave「ring-no-answer」in one period versus 41.5%「ring-no-answer」in the other period. Which period do you think had the higher rate of no answers? Why? Explain why a high rate of nonresponse makes sample results less reliable.
4.15 Race relations. Here are two recent opinion poll questions asked about race relations in the United States.
Would you say relations between whites and blacks are very good, somewhat good, somewhat bad, or very bad?
Do you think race relations in the United States are generally good or generally bad?
In response to the first question, 72% of non-Hispanic whites and 66% of blacks answered that relations between blacks and whites are「very good」or「somewhat good.」Sixty-one (61%) of those answering the second question responded「generally bad.」
The first question came from a poll that was conducted in March 2015. The second question came from a poll that was conducted between April 30 and May 3 of that same year. Between the two polls, a man named Freddie Gray died after being in the custody of the Baltimore police. In what ways do you think this event may have impacted the responses to the two different polls? Do you think the results would be different if the question from the second poll had been worded like the question from the first poll?
4.16 The environment and the economy. Here are two opinion poll questions asked about protecting the environment versus protecting the economy.
Often there are trade-offs or sacrifices people must make in deciding what is important to them. Generally speaking, when a trade-off has to be made, which is more important to you: stimulating the economy or protecting the environment?
Which worries you more: that the U.S. will NOT take the actions necessary to prevent the catastrophic effects of global warming because of fears those actions would harm the economy, or that the U.S. WILL take actions to protect against global warming and those actions will cripple the U.S. economy?
In response to the first question, 61% said stimulating the economy was more important. But only 46% of those asked the second question said they were afraid that the United States will take actions to protect against global warming and that those actions will cripple the U.S. economy. Why do you think the second wording discouraged more people from expressing more concern about the economy than about the environment?
4.17 Amending the Constitution. You are writing an opinion poll question about a proposed amendment to the Constitution. You can ask if people are in favor of「changing the Constitution」or「adding to the Constitution」by approving the amendment.
Why do you think the responses to these two questions will produce different percentages in favor?
One of these choices of wording will produce a much higher percentage in favor. Which one? Why?
4.18 Legal marijuana use. Recently, the issue of the legalization of marijuana has been appearing on more state ballots. In April 2018, a Quinnipiac University poll asked two questions about legal marijuana use. Here are the two questions:
Do you think that the use of marijuana should be made legal in the United States, or not?
Do you support or oppose allowing adults to legally use marijuana for medical purposes if their doctor prescribes it?
One of these questions drew 63% saying that marijuana use is okay; the other drew 93% with the same response. Which wording produced the higher percentage? Why?
4.19 Wording survey questions. Comment on each of the following as a potential sample survey question. Is the question clear? Is it slanted toward a desired response? (Survey questions on issues that one might regard as inflammatory are often prone to slanted wording.)
Which of the following best represents your opinion on gun control? The government should take away our guns.
We have the right to keep and bear arms.
In light of skyrocketing gasoline prices, we should consider opening up a very small amount of Alaskan wilderness for oil exploration as a way of reducing our dependence on foreign oil. Do you agree or disagree?
Do you think that the excessive restrictions placed on U.S. law enforcement agencies hampered their ability to detect the 9/11 terrorist plot before it occurred?
Do you use drugs?
4.20 Bad survey questions. Write your own examples of bad sample survey questions.
Write a biased question designed to get one answer rather than another.
Write a question that is confusing, so that it is hard to answer.
4.21 Appraising a poll. In May 2018, an NBC News/SurveyMonkey poll asked about racism in American society and American politics. The question asked respondents to choose one of the following:「racism remains a major problem in our society, racism exists today but is not a major problem, racism once existed but no longer exists in our society, racism has never been a major problem in our society」The article noted 64% of Americans think racism is still a major problem in society today. News articles tend to be brief in describing sample surveys. NBC’s description of this poll explained that the poll was conducted in May 2018 and included 6,518 American adults from all adults (about 3 million!) who take SurveyMonkey polls each day. Note that this was not a probability sample. Polls of this size have a margin of error of plus or minus 1.5 percentage points.
Pages 75–76 list several「questions to ask」about an opinion poll. What answers does NBC News give to each of these questions?
4.22 Appraising a poll. In May–June 2018, an NBC News/GenForward poll asked the question「Do you personally know someone who has dealt with an opioid addiction?」The article noted 42% of millennials know someone who has dealt with opioid addiction. The description of this poll on the main article page explained that the poll was conducted in May 2018 and included 1,886 American adults between the ages of 18 and 34 who were recruited by NORC at the University of Chicago. Polls of this size and type have a margin of error of plus or minus 3.78 percentage points.
More specific information about the poll methodology was available by clicking a link. That information stated that the 1,886 respondents represented all 50 U.S. states and the District of Columbia. The respondents included 525 African Americans, 256 Asian Americas, 502 Latinx Americans, and 553 white Americans (another 50 young adults had other racial and ethnic backgrounds). Additionally, the methodology stated that the survey was conducted in either English or Spanish and through the web (93%) or telephone (7%). Also of note was that only 26% of surveys were completed.
Pages 75–76 list several「questions to ask」about an opinion poll. What answers does NBC/GenForward give to each of these questions?
4.23 Closed versus open questions. Two basic types of questions are closed questions and open questions. A closed question asks the subject for one or more of a fixed set of responses. An open question allows the subject to answer in his or her own words; the interviewer writes down the responses and classifies them later. An example of an open question is
What do you believe about the afterlife?
An example of a closed question is
What do you believe about the afterlife? Do you believe
there is an afterlife and entrance depends only on your actions?
there is an afterlife and entrance depends only on your beliefs?
there is an afterlife and everyone lives there forever?
there is no afterlife?
I don’t know.
What are the advantages and disadvantages of open and closed questions?
4.24 Telling the truth? Many subjects don’t give honest answers to questions about activities that are illegal or sensitive in some other way. One study divided a large group of white adults into thirds at random. All were asked if they had ever used cocaine. The first group was interviewed by telephone: 21% said「Yes.」In the group visited at home by an interviewer, 25% said「Yes.」The final group was interviewed at home but answered the question on an anonymous form that they sealed in an envelope. Of this group, 28% said they had used cocaine.
Which result do you think is closest to the truth? Why?
Give two other examples of behavior you think would be underreported in a telephone survey.
4.25 Did you vote? When the Current Population Survey asked the adults in its sample of 60,000 households if they voted in the 2016 presidential election, 56% said they had. The margin of error was less than 0.3%. In fact, only 55% of the adult population voted in that election. Why do you think the CPS result missed by 3 times the margin of error?
4.26 A party poll. At a party there are 20 students over age 21 and 40 students under age 21. You choose at random 2 of those over 21 and separately choose at random 4 of those under 21 to interview about attitudes toward alcohol. You have given every student at the party the same chance to be interviewed: what is that chance? Why is your sample not an SRS?
4.27 A stratified sample. A club has 30 student members and 10 faculty members. The students are
Aguirre Cooper Kemp Peralta Stankiewicz
Butterfield Dobbs Kessler Risser Steele
Caporuscio Freeman Koepnick Rodriguez Tong
Carlson Girard Macha Ryndak White
Chilson Gonzales Makis Soria Williams
Clement Grebe Palacios Spiel Zhang
The faculty members are
Atchade Everson Hansen Nair Romero
Craigmile Fink Murphy Nguyen Turkmen
The club can send 3 students and 2 faculty members to a convention. It decides to choose those who will go by random selection.
Use the Simple Random Sample applet, other technology, or Table A to choose a stratified random sample of 3 students and 2 faculty members.
What is the chance that the student named White is chosen? What is the chance that faculty member Romero is chosen?
4.28 A stratified sample. A state university has 4900 in-state students and 2100 out-of-state students. A financial aid officer wants to poll the opinions of a random sample of students. In order to give adequate attention to the opinions of out-of-state students, the financial aid officer decides to choose a stratified random sample of 200 in-state students and 200 out-of-state students. The officer has alphabetized lists of in-state and out-of-state students.
Explain how you would assign labels and use random digits to choose the desired sample. Use the Simple Random Sample applet, other technology, or Table A at line 122 and give the first 5 in-state students and the first 5 out-of-state students in your sample.
What is the chance that any one of the 4900 in-state students will be in your sample? What is the chance that any one of the 2100 out-of-state students will be in your sample?
4.29 Sampling by accountants. Accountants use stratified samples during audits to verify a company’s records of such things as accounts receivable. The stratification is based on the dollar amount of the item and often includes 100% sampling of the largest items. One company reports 5000 accounts receivable. Of these, 100 are in amounts over $50,000; 500 are in amounts between $1000 and $50,000; and the remaining 4400 are in amounts under $1000. Using these groups as strata, you decide to verify all of the largest accounts and to sample 5% of the midsize accounts and 1% of the small accounts. How would you label the two strata from which you will sample? Use the Simple Random Sample applet, other technology, or Table A, starting at line 115, to select only the first 5 accounts from each of these strata.
4.30 A sampling paradox? Example 8 compares two SRSs of a university’s undergraduate and graduate students. The sample of undergraduates contains a smaller fraction of the population, 1 out of 90, versus 1 out of 15 for graduate students. Yet sampling 1 out of 90 undergraduates gives a smaller margin of error than sampling 1 out of 15 graduate students. Explain to someone who knows no Statistics why this happens.
4.31 Appraising a poll. Exercise 4.22 gives part of the description of a sample survey from the NBC News|GenForward. It appears that the sample was taken in several stages. Why can we say this? The first stage no doubt used a stratified sample, though the NBC survey does not say this. Explain why it would be bad practice to use an SRS from all possible telephone numbers and impossible to use an SRS of all possible Internet users rather than a stratified sample of telephone and Internet users.
4.32 Multistage sampling. An article in the journal Science looks at differences in attitudes toward genetically modified foods between Europe and the United States. This calls for sample surveys. The European survey chose a sample of 1000 adults in each of 17 European countries. Here’s part of the description:「The Eurobarometer survey is a multistage, random-probability face-to-face sample survey.」
What does「multistage」mean?
You can see that the first stage was stratified. What were the strata?
What does「random-probability sample」mean?
4.33 Online courses in high schools? What do adults believe about requiring online courses in high schools? Are opinions different in urban, suburban, and rural areas? To find out, researchers wanted to ask adults this question:
It has become common for education courses after high school to be taken online. In your opinion, should public high schools in your community require every student to take at least one course online while in high school?
Because most people live in heavily populated urban and suburban areas, an SRS might contain few rural adults. Moreover, it is too expensive to choose people at random from a large region. We should start by choosing school districts rather than people. Describe a suitable sample design for this study, and explain the reasoning behind your choice of design.
4.34 Systematic random samples. The last stage of the Current Population Survey (Example 7) uses a systematic random sample. The following example will illustrate the idea of a systematic sample. Suppose that we must choose 4 rooms out of the 100 rooms in a dormitory. Because , we can think of the list of 100 rooms as four lists of 25 rooms each. Choose 1 of the first 25 rooms at random, using Table A. The sample will contain this room and the rooms 25, 50, and 75 places down the list from it. If 13 is chosen, for example, then the systematic random sample consists of the rooms numbered 13, 38, 63, and 88. Use Table A to choose a systematic random sample of 5 rooms from a list of 200. Enter the table at line 120.
4.35 Systematic isn’t simple. Exercise 4.34 describes a systematic random sample. Like an SRS, a systematic sample gives all individuals the same chance to be chosen. Explain why this is true, then explain carefully why a systematic sample is nonetheless not an SRS.
4.36 Planning a survey of students. The student government plans to ask a random sample of students their opinions about on-campus parking. The university provides a list of the 20,000 enrolled students to serve as a sampling frame.
How would you choose an SRS of 200 students?
How would you choose a systematic sample of 200 students? (See Exercise 4.34 to learn about systematic samples.)
The list shows whether students live on campus (8000 students) or off campus (12,000 students). How would you choose a stratified sample of 50 on-campus students and 150 off-campus students?
4.37 Sampling students. You want to investigate the attitudes of students at your school toward the school’s policy on extra fees for lab courses. You have a grant that will pay the costs of contacting about 500 students.
Specify the exact population for your study. For example, will you include part-time students?
Describe your sample design. For example, will you use a stratified sample with student majors as strata?
Briefly discuss the practical difficulties that you anticipate. For example, how will you contact the students in your sample?
4.38 Mall interviews. Example 1 in Chapter 2 (page 22) describes mall interviewing. This is an example of a convenience sample. Why do mall interviews not produce probability samples?
4.39 Minorities and police. Here are three questions from an April 2018 Quinnipiac University Poll that deal with similar issues, along with the poll results:
Do you think the police in the United States are generally tougher on whites than on blacks, tougher on blacks than on whites, or do the police treat them both the same? Result: 1% tougher on whites, 48% tougher on blacks, 44% treat them the same.
When faced with a possible criminal situation, do you think police in the United States are more likely to shoot someone who is black, more likely to shoot someone who is white, or do you think police are equally likely to shoot someone of either race? website Result: 40% blacks, 2% whites, 53% either race
Is being the victim of police brutality something you personally worry about, or not? Result who worry about: 9% Republicans, 31% Democrats, 21% Independents; 12% whites, 64% blacks, 37% Hispanics
Using this example, discuss the difficulty of using responses to opinion polls to understand public opinion and come up with an overall conclusion.
Exploring the Web
Access these exercises on the text website: macmillanlearning.com/scc10e.
What’s the Verdict?
The following「What’s the verdict?」story explores unexpected results from a well-known mid-1990s survey and from a follow-up survey, as well as subsequent attempts by researchers to understand these results. The material in this chapter and Chapter 3 will help you appreciate issues discussed in these research papers.
In a well-known National Longitudinal Study of Adolescent Health in the mid-1990s, teenagers responded to survey questions about their health, including their sexual identity and behavior. When the results of this study were analyzed, researchers were surprised that 5 to 7% of teens were reporting that they identified as homosexual or bisexual, which was an increase from the 1% researchers had previously estimated.
Questions
WTV4.1. Researchers recognized that questions about sexuality are sensitive and thus worded their question in the study in terms of both-sex or same-sex romantic attraction. In general, what could be some challenges in asking teenagers about their sexual identity and behavior?
WTV4.2. How would you get a nationally representative sample of U.S. teenagers?
WTV4.3. How would you collect data about sexual behavior and identity to get the most accurate answers?
WTV4.4. Does your answer to the question above change if you want to follow up with these same teenagers as they become adults?
In follow-up surveys, researchers noticed that when these same teenagers were surveyed again as adults, over 70% of those teens (mostly males) who were identified as homosexual or bisexual replied that they were only heterosexual as adults. The researchers wondered why there would be such a large decrease. This would be the opposite of what other sexual development research had shown because people are more (not less) likely to be open about their non heterosexual identity as they get older.
A 2014 research paper (see Notes and Data Sources) discussed this issue. The authors of this paper proposed three explanations for the apparent inconsistency. First, perhaps gay adolescents went into the closet as young adults. Second, perhaps the teenagers were confused about the use of the phrase「romantic attraction」as a substitute for sexual orientation. Third, perhaps some of the teenagers「played a ‘jokester’ role by reporting same-sex attraction when none was present.」The authors of the paper believed that the first explanation was very unlikely but did not dismiss the other two explanations as possible.
WTV4.5. What type of error is it when the survey question is worded in a confusing way?
The researchers did look at some of the other health questions that the same teenagers (and later adults) were asked in the surveys, and they found something else interesting:「Most of the kids who first claimed to have artificial limbs [as teenagers] miraculously regrew arms and legs when researchers came back to interview them [as adults].」
WTV4.6. Based on this additional piece of evidence, what is a possible explanation for the sudden decrease in the number of people who identify as homosexual or bisexual from teenagers to adulthood in this survey?
What’s the verdict? Response errors can undermine the results of otherwise well-designed surveys.
CHAPTER 5 Experiments, Good and Bad
In this chapter you will:
Apply the language of experiments.
Apply the logic of experiments.
|
Java
|
UTF-8
| 2,427
| 3.234375
| 3
|
[] |
no_license
|
package it.alex.lab9.operation;
import java.util.Stack;
public class Multiplication extends AbstractOperation {
public final String getOperationSymbol() {
String symbol = "*";
return symbol;
}
public String getName() {
return "Multiplication";
}
public String operate(String... number) {
String firstNumber = number[0];
String secondNumber = number[1];
String[] array = arrayString(firstNumber, secondNumber);
String result = "0";
for (int i = 0; i < array.length; i++) {
Addition addition = new Addition();
result = addition.operate(result, array[i]);
}
return checkResultStringNumber(true, result);
}
private String[] arrayString(String firstNumber, String secondNumber) {
boolean valid = comparisonOperation(firstNumber, secondNumber);
int length;
Stack<Integer> stackLargeNumber;
Stack<Integer> stackLessNumber;
if (valid) {
length = secondNumber.length();
stackLargeNumber = createStack(firstNumber);
stackLessNumber = createStack(secondNumber);
} else {
length = firstNumber.length();
stackLargeNumber = createStack(secondNumber);
stackLessNumber = createStack(firstNumber);
}
String[] arrayString = new String[length];
for (int i = 0; i < arrayString.length; i++) {
arrayString[i] = multiply(stackLargeNumber, stackLessNumber, i);
stackLessNumber.pop();
}
return arrayString;
}
private String multiply(Stack<Integer> stackLargeNumber, Stack<Integer> stackLessNumber, int numberLineArray) {
StringBuilder builder = new StringBuilder();
Stack<Integer> number = new Stack<>();
number.addAll(stackLargeNumber);
int residue = 0;
int result = 0;
for (int i = 0; i < stackLargeNumber.size(); i++) {
result = number.pop() * stackLessNumber.peek() + residue;
int digit = result % 10;
residue = (int) (result / Math.pow(10, 1)) % 10;
builder.insert(0, digit);
}
if (residue > 0) {
builder.insert(0, residue);
}
for (int i = 0; i < numberLineArray; i++) {
builder.insert(builder.length(), "0");
}
return builder.toString();
}
}
|
Markdown
|
UTF-8
| 1,450
| 3.21875
| 3
|
[] |
no_license
|
# Pype
Pipe files to python.
## Tutorial
Pype has mainly two modes of operations: command line and interactive (`-i`).
It's mode of operation is very simple you need to pipe the output of the file
you need to manipulate to pype's input:
```
cat myfile.txt | pype
```
You will then be apply to apply transformations to the file directly from the
command line. If for example you wish to split on tab and convert the first
entry to uppercase you can do like so:
```
cat myfile.txt | pype '.split(" ")[0].upper()'
```
Any method that applies to strings is allowed.
For more powerful textual manipulations pype also supports interactive mode.
This will spawn an interactive python environment in which you will be given
the first line of the file as input. You will then be able to interact with
such line and then repeat the operation on every other line of the file.
```
cat myfile.txt | pype -i > output.txt
```
Will give you an interactive prompt like so:
```
The current input line available as "i".
Set the transformed line equal to "o".
>>>
```
All you need to do is set the value you want output to stdout (that will end
into output.txt) to be the value of variable `o` then hit `CTRL-d` and the
operation will be repeated for every other line of the file.
# TODO
* Add support for tokenizing on something different than a line (i.e. add
support for YAML entries and JSON documents).
* Use bpython for the interactive shell.
|
Java
|
UTF-8
| 2,926
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
/**
* Somos a equipe "Agente junto e a gente separado", formados pelos integrantes Alex Sandro Zarpelon e Bruna Gabriela Disner
*/
package br.uffs.cc.jarena;
import javax.net.ssl.TrustManagerFactorySpi;
public class AgenteJuntoEAGenteSeparado extends Agente
{
int contador;
int time = 20;
int tempo = 0;
boolean teste;
int recebeX = getX();
int recebeY = getY();
int contaVitoria = 0;
boolean lutando = false;
public AgenteJuntoEAGenteSeparado(Integer x, Integer y, Integer energia) {
super(400, 500, energia);
setDirecao(geraDirecaoAleatoria());
contador = 0;
}
public void DirecaoContraria() {
if ((contador % time) == 0) {
if (getX() > recebeX) {
podeMoverPara(ESQUERDA);
} else {
podeMoverPara(DIREITA);
}
}
if ((contador % time) == 1) {
if (getY() > recebeY) {
podeMoverPara(BAIXO);
} else {
podeMoverPara(CIMA);
}
}
}
public void pensa() {
contador++;
if(!podeMoverPara(getDirecao()) || (isParado() && !teste)) {
setDirecao(geraDirecaoAleatoria());
}
if ((contador % time) == 0) {
setDirecao(geraDirecaoAleatoria());
}
if ((getEnergia() < 130) && !lutando) {
para();
} else {
lutando = false;
}
}
public void recebeuEnergia() {
enviaMensagem("Estou no cogumelo");
tempo++;
teste = true;
para();
tempo++;
if((podeDividir() && getEnergia() >= 800) && (tempo > 35)) {
divide();
tempo = 0;
System.out.println("me dividi");
}
}
public void tomouDano(int energiaRestanteInimigo) {
if (getEnergia() < 10) {
morre();
}
lutando = true;
enviaMensagem("Estou tomando dano aqui");
if (getEnergia() < 300) {
podeMoverPara(ESQUERDA);
if (getEnergia() < 280) {
podeMoverPara(CIMA);
}
}
}
public void ganhouCombate() {
setDirecao(geraDirecaoAleatoria());
enviaMensagem("matei esse bagaceira");
System.out.print("Matamos um total de " + contaVitoria + " inimigos");
}
public void recebeuMensagem(String msg) {
if(msg.equals("Estou no cogumelo")) {
DirecaoContraria();
}
if(msg.equals("Estou tomando dano aqui")) {
DirecaoContraria();
}
if(msg.equals("matei esse bagaceira")) {
contaVitoria++;
}
}
public String getEquipe() {
return "AgenteJuntoEAGenteSeparado";
}
}
|
C#
|
UTF-8
| 1,052
| 3.109375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ORM.Models
{
public class Order_Delivery_Method
{
private decimal _price;
public int Id { get; set; }
public string MethodName { get; set; }
public decimal Price
{
get { return _price; }
set
{
if(value <= 99999999 && value >= 0)
{
_price = Math.Round(value, 2);
}
else
{
throw new ArgumentOutOfRangeException();
}
}
}
public Order_Delivery_Method() { }
public Order_Delivery_Method( string methodname, decimal price)
{
MethodName = methodname;
Price = price;
}
public Order_Delivery_Method(int id, string methodname, decimal price)
{
Id = id;
MethodName = methodname;
Price = price;
}
}
}
|
C#
|
UTF-8
| 494
| 2.8125
| 3
|
[] |
no_license
|
<#@ import namespace="System.IO" #>
<#@ template debug="false" hostspecific="true" language="C#" #>
<#
string path = this.Host.ResolvePath(@"PocoClass.cs");
var PocoLines= File.ReadLines(path).ToArray();
List<string> usingStatements = new List<string>();
foreach (var line in pocoLines)
{
if(Regex.Match(line, "RegexForUsings") //or use String.Contains("using");
usingStatements.Add(line);
}
//insert lines again in PocoLines
#>
|
PHP
|
UTF-8
| 4,055
| 2.859375
| 3
|
[] |
no_license
|
<?php
require_once $_SERVER["DOCUMENT_ROOT"]."/_code/includes/_config.php";
require_once $_SERVER["DOCUMENT_ROOT"]."/_code/includes/_conexion.php";
require_once $_SERVER["DOCUMENT_ROOT"]."/_code/modelos/Clase.php";
class ClaseMatriz {
private $matriz = array();
public function set_matriz($matriz)
{
$this->matriz = ($matriz);
}
public function get_matriz()
{
return $this->matriz;
}
public function to_matriz(Clase $clase){
$matriz = array(
"id_clase" => $clase->get_id_clase(),
"run_profesor" => $clase->get_run_profesor(),
"id_curso" => $clase->get_id_curso(),
"id_asignatura" => $clase->get_id_asignatura(),
"id_bloque" => $clase->get_id_bloque(),
"estado" => $clase->get_estado()
);
array_push($this->matriz, $matriz);
}
public function to_json(){
$json = json_encode($this->matriz, JSON_UNESCAPED_UNICODE);
return $json;
}
public function db_get_clases_by_id_curso($id_curso){
global $myPDO;
$sentencia = $myPDO->prepare("CALL get_clases_by_id_curso(?)");
$sentencia->bindParam(1, $id_curso, \PDO::PARAM_INT);
$sentencia->execute();
$data = $sentencia->fetchAll(0);
foreach($data as $row){
$clase = new Clase();
$clase->set_id_clase($row["id_clase"]);
$clase->set_identidad(
$row["id_curso"],
$row["id_asignatura"],
$row["id_bloque"]
);
$clase->set_run_profesor($row["run_profesor"]);
$this->to_matriz($clase);
}
return $sentencia->rowCount();
}
public function db_upd_clases_run_profesor_and_id_asignatura_by_id(){
$matriz = $this->get_matriz();
$result = true;
foreach($matriz as $row){
$clase = new Clase();
$clase->set_id_clase($row["id_clase"]);
$clase->set_run_profesor($row["run_profesor"]);
$clase->set_id_asignatura($row["id_asignatura"]);
if(!$clase->db_upd_clase_run_profesor_and_id_asignatura_by_id()){
$result = false;
}
}
return $result;
}
public function db_get_clases_by_run_profe_and_id_cur_and_id_asig_and_id_dia($run_profesor, $id_curso, $id_asignatura, $id_dia){
global $myPDO;
$sentencia = $myPDO->prepare("CALL get_clases_by_run_profe_and_id_cur_and_id_asig_and_id_dia(?,?,?,?)");
$sentencia->bindParam(1, $run_profesor, \PDO::PARAM_STR, 9);
$sentencia->bindParam(2, $id_curso, \PDO::PARAM_INT);
$sentencia->bindParam(3, $id_asignatura, \PDO::PARAM_INT);
$sentencia->bindParam(4, $id_dia, \PDO::PARAM_INT);
$sentencia->execute();
$data = $sentencia->fetchAll(0);
foreach($data as $row){
$clase = new Clase();
$clase->set_id_clase($row["id_clase"]);
$clase->set_identidad(
$row["id_curso"],
$row["id_asignatura"],
$row["id_bloque"]
);
$clase->set_run_profesor($row["run_profesor"]);
$this->to_matriz($clase);
}
$sentencia->rowCount();
}
function db_get_clases_by_id_curso_group_by_id_asignatura($id_curso){
global $myPDO;
$sentencia = $myPDO->prepare("CALL get_clases_by_id_curso_group_by_id_asignatura(?)");
$sentencia->bindParam(1, $id_curso, \PDO::PARAM_INT);
$sentencia->execute();
$data = $sentencia->fetchAll(0);
foreach($data as $row){
$clase = new Clase();
$clase->set_id_clase($row["id_clase"]);
$clase->set_identidad(
$row["id_curso"],
$row["id_asignatura"],
$row["id_bloque"]
);
$clase->set_run_profesor($row["run_profesor"]);
$this->to_matriz($clase);
}
$sentencia->rowCount();
}
}
?>
|
Python
|
UTF-8
| 811
| 3.359375
| 3
|
[] |
no_license
|
"""
Generate stats.txt in which each location is used as the key in the created dictionary.
The content of each item in the dictionary is a count number, which counts the frequency of each location
author: Haitao Wang
date: 3/8/2018
"""
import json
import os
path = os.path.dirname(os.path.realpath(__file__))
data = []
with open(path+'/data/tweets_#superbowl.txt') as f:
for line in f:
data.append(json.loads(line))
loc_dict = {}
for dat in data:
if dat['tweet']['user']['location'] not in loc_dict:
loc_dict[dat['tweet']['user']['location']] = 1
else:
loc_dict[dat['tweet']['user']['location']] += 1
with open(path+'/data/stats.txt', 'w') as f:
f.write(json.dumps(loc_dict))
print 'number of locations:'
print len(loc_dict)
print 'number of tweets:'
print len(data)
|
TypeScript
|
UTF-8
| 294
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
export class PhoneModel {
phone: string;
code: string;
number: string;
length: number;
constructor(code: string, number: string) {
this.code = code;
this.number = number;
this.phone = code + number;
this.length = this.phone.length;
}
}
|
Java
|
UTF-8
| 540
| 1.984375
| 2
|
[] |
no_license
|
package com.example.secondtravelapp.Models;
import androidx.lifecycle.LiveData;
import java.util.List;
public interface IHistoryDataSource {
public List<Travel> getTravels() throws Exception;
public Travel getTravel(String id) throws Exception;
public void addTravel(Travel p) throws Exception;
public void addTravel(List<Travel> travelList) throws Exception;
public void editTravel(Travel p) throws Exception;
public void deleteTravel(Travel p) throws Exception;
public void clearTable() throws Exception;
}
|
SQL
|
UTF-8
| 137
| 2.671875
| 3
|
[] |
no_license
|
-- Query the difference between the maximum and minimum populations in CITY.
select max(population) - min(population) as diff
from city;
|
Java
|
UTF-8
| 2,781
| 1.945313
| 2
|
[] |
no_license
|
package com.marcarndt.morsemonkey.telegram.alerts.command;
import com.marcarndt.morsemonkey.services.ConfigureService;
import com.marcarndt.morsemonkey.services.HttpChecker;
import com.marcarndt.morsemonkey.services.StateService;
import com.marcarndt.morsemonkey.services.StateService.State;
import com.marcarndt.morsemonkey.services.UserService.Role;
import com.marcarndt.morsemonkey.telegram.alerts.MorseBot;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.inject.Inject;
import org.telegram.telegrambots.api.objects.Chat;
import org.telegram.telegrambots.api.objects.User;
import org.telegram.telegrambots.bots.AbsSender;
/**
* Created by arndt on 2017/04/17.
*/
;
@Stateless
public class ConfigureCommand extends BaseCommand {
public static final String setGroup = "Set group to this group";
public static final String application = "Applications";
public static final String httpEndpoints = "HTTP Endpoint monitoring";
public static final String manageUsers = "Manage Users";
public static final String addHttpEndpoint = "Add a new HTTP Endpoint";
public static final String deleteHttpEndpoint = "Delete an existing http endpoint";
public static final String httpGetRequest = "GET";
public static final String httpPostRequest = "POST";
public static final String addApplication = "Add a new application";
public static final String deleteApplication = "Delete an application";
public static String editApplication = "Update Application";
public static final String addUserToRole = "Add user to role";
public static final String removeUserFromRole = "Remove user from role";
public static final String deleteUser = "Delete User";
public static final String authDetails = "Authentication Details";
public static final String command = "Commands";
public static final String file = "Files";
public static final String chef = "Chef";
public static Logger LOG = Logger.getLogger(ConfigureCommand.class.getName());
@Inject
ConfigureService configureService;
@Inject
MorseBot morseBot;
@Inject
StateService stateService;
@Inject
HttpChecker httpChecker;
@Override
protected Role getRole() {
return Role.ADMINISTRATOR;
}
@Override
protected void performCommand(AbsSender absSender, User user, Chat chat, String[] arguments) {
morseBot
.sendReplyKeyboardMessage(user, chat, "Select an item to configure", setGroup,
httpEndpoints,
application, manageUsers, authDetails, command, file, chef);
stateService.setState(user.getId(), chat.getId(), State.CONFIGURE);
}
@Override
public String getCommandIdentifier() {
return "configure";
}
@Override
public String getDescription() {
return "Configure the bot.";
}
}
|
Java
|
UTF-8
| 2,307
| 2.1875
| 2
|
[] |
no_license
|
package com.practice.work.films.dtos;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import static com.practice.work.films.constants.FilmsConstants.NAME_REGEX;
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FilmDTO {
@Id
@ApiModelProperty(hidden = true)
private String id;
@NotBlank
@ApiModelProperty(
name = "title",
example = "string",
position = 1
)
private String title;
@NotEmpty
@ApiModelProperty(
name = "genre",
example = "['string', 'string']",
position = 2
)
private List<String> genre;
@NotBlank
@Pattern(regexp = NAME_REGEX)
@ApiModelProperty(
name = "director",
example = "string",
position = 3
)
private String director;
@NotBlank
@Pattern(regexp = NAME_REGEX)
@ApiModelProperty(
name = "cinematographer",
example = "string",
position = 4
)
private String cinematographer;
@NotEmpty
@ApiModelProperty(
name = "writer",
example = "['string', 'string']",
position = 5
)
private List<@Pattern(regexp = NAME_REGEX) String> writers;
@NotBlank
@Pattern(regexp = NAME_REGEX)
@ApiModelProperty(
name = "composer",
example = "string",
position = 6
)
private String composer;
@NotNull
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
@Past
@ApiModelProperty(
name = "releaseDate",
example = "1999-01-31",
position = 7)
private LocalDate releaseDate;
@NotEmpty
@ApiModelProperty(
name = "actors",
example = "['string', 'string']",
position = 8)
@Size(min = 1, max = 10)
private List<@Pattern(regexp = NAME_REGEX) String> actors;
@ApiModelProperty(hidden = true)
@CreatedDate
private LocalDateTime dateAdded;
}
|
Java
|
UTF-8
| 472
| 2.40625
| 2
|
[] |
no_license
|
package demosim1;
/**
* A sample application used as a starting point for implementing a timed petri net simulator.
* SSATR / IASIC & ICAF / Master / An 1 / 2017
* @author evo
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
Simulator s =
new Simulator(ModelFactory.loadDummyModelFromJSONFile("model1.json"));
s.start();
}
}
|
Shell
|
UTF-8
| 323
| 3.78125
| 4
|
[] |
no_license
|
#! /bin/bash/ -x
read -p "Enter any number : " num;
if [ $num -ge 1 ]
then
check=0;
for (( i=2;i<$num;i++ ))
do
if [ $(( num%i )) -eq 0 ]
then
check=1;
fi
done
if [ $check -eq 1 ]
then
echo "$num is not a Prime number ";
else
echo "$num is a Prime number ";
fi
fi
|
Python
|
UTF-8
| 511
| 3.5
| 4
|
[] |
no_license
|
def pangrams(s):
alphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
alpha = ''
for i in s:
if i.isalpha() and i.lower() not in alpha:
if s.count(i) <= 0:
return 'not pangram'
alpha += i.lower()
if len(alpha) != 26:
return 'not pangram'
else:
return 'pangram'
s = 'We promptly judged antique Ivory Buckles for the nexxt prize'
print(pangrams(s))
|
Java
|
UTF-8
| 2,999
| 2.1875
| 2
|
[] |
no_license
|
package com.springboot.mvc.login.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import com.springboot.mvc.login.ProjectManagementAppApplicationTests;
import com.springboot.mvc.login.model.Project;
import com.springboot.mvc.login.repository.ProjectRepository;
public class ProjectServiceImplTest extends ProjectManagementAppApplicationTests {
@InjectMocks
private ProjectServiceImpl projservice;
@Mock
private ProjectRepository projrepository;
private Project project;
Optional<Project> projectopt;
private List<Project> projectlist;
private long projectid = 1;
@Before
public void datasetup() {
MockitoAnnotations.initMocks(this);
project = new Project(1, "Project1", new Date(2019,04,04), new Date(2019,04,06), 10);
projectopt = Optional.of(project);
projectlist = new ArrayList<Project>();
projectlist.add(project);
Mockito.when(projrepository.save(any())).thenReturn(project);
Mockito.when(projrepository.findById(any())).thenReturn(projectopt);
Mockito.when(projrepository.findByProjectname(any())).thenReturn(project);
projservice.saveProject(project);
}
@SuppressWarnings("deprecation")
@Test
public void testsaveProject() {
project = new Project(2, "Project2", new Date(2019,06,04), new Date(2019,06,06), 11);
projservice.saveProject(project);
Optional<Project> projectlist1 = projrepository.findById((long) 2);
assertTrue(projectlist1 != null);
}
@Test
public void testfindAllProjects() {
List<Project> projectlist = projservice.findAllProjects();
assertTrue(projectlist != null);
}
@Test
public void testdeleteProject() {
// project = new Project(2, "Project2", new Date(2019,06,04), new Date(2019,06,06), 11);
projservice.deleteProject(projectid);
Optional<Project> projectlist1 = projrepository.findById((long) 1);
assertTrue(projectlist1 != null);
}
@Test
public void testfindByProjectId() {
Project project = projservice.findByProjectId((long) 1);
assertEquals(1, project.getProjectid());
}
@Test
public void testfindByProjectName() {
Project project = projservice.findByProjectName("Project1");
assertEquals("Project1", project.getProjectname());
}
@Test
public void testsortByProjectStartdateAsc() {
projectlist = projservice.sortByProjectStartdateAsc();
assertTrue(projectlist != null);
}
@Test
public void testsortByProjectEnddateAsc() {
projectlist = projservice.sortByProjectEnddateAsc();
assertTrue(projectlist != null);
}
@Test
public void testsortByProjectPriorityAsc() {
projectlist = projservice.sortByProjectPriorityAsc();
assertTrue(projectlist != null);
}
}
|
Shell
|
UTF-8
| 1,310
| 3.546875
| 4
|
[] |
no_license
|
#!/bin/sh
if ! INSTALL_DIR="$(dirname $(dirname $(realpath "${0}")))"
then
echo "Cannot locate installation dir relative to ${0}"
exit -2
fi
SIGNER_DIR="${INSTALL_DIR}/authorities/${1}"
if [ ! -d ${SIGNER_DIR} ]
then
echo "${SIGNER_DIR} does not exist as a directory"
exit -3
fi
SIGNED_DIR="${INSTALL_DIR}/authorities/${2}"
if [ ! -d ${SIGNED_DIR} ]
then
echo "${SIGNED_DIR} does not exist as a directory"
exit -4
fi
if ! DAYS_SIGNED="$(cat "${SIGNER_DIR}/certExpiryDays")"
then
echo "Problem reading certExpiryDays from signer"
exit -5
fi
openssl req -config "${SIGNED_DIR}/openssl.cnf" -new -sha256 \
-newkey rsa:2048 -key "${SIGNED_DIR}/private/ca.key.pem" \
-out "${SIGNED_DIR}/csr/ca.csr.pem"
openssl ca -config "${SIGNER_DIR}/openssl.cnf" \
-extensions v3_intermediate_ca \
-days ${DAYS_SIGNED} -notext -md sha256 \
-in "${SIGNED_DIR}/csr/ca.csr.pem" \
-keyfile "${SIGNED_DIR}/private/ca.key.pem" \
-out "${SIGNED_DIR}/certs/ca.cert.pem"
chmod 644 "${SIGNED_DIR}/certs/ca.cert.pem"
openssl x509 -noout -text -in "${SIGNED_DIR}/certs/ca.cert.pem"
cat "${SIGNER_DIR}/certs/ca.cert.pem" \
"${SIGNER_DIR}/certs/ca-chain.cert.pem" > \
"${SIGNED_DIR}/certs/ca-chain.cert.pem"
chmod 644 "${SIGNED_DIR}/certs/ca-chain.cert.pem"
|
Rust
|
UTF-8
| 4,056
| 3.71875
| 4
|
[] |
no_license
|
// macro
pub fn first() {
// “宏”(macro)是 Rust 的一个重要特性。
// Rust 的“宏”(macro 是一种编译器扩展,它的调用方式为 some_macro!(…)。
// 宏调用与普通函数调用的区别可以一眼区分开来,凡是宏调用后面都跟着一个感叹号。
// 宏也可以通过 some_macro![…]和 some_macro!{…}两种语法调用,只要括号能正确匹配即可
// 与 C/C++ 中的宏的区别
// 首先,Rust 的宏在调用的时候跟函数有明显的语法区别;
// 其次,宏的内部实现和外部调用者处于不同名字空间,它的访问范围严格受限,
// 是通过参数传递进去的,不能随意在宏内访问和改变外部的代码。
// C/C++ 中的宏只在预处理阶段起作用,只能实现类似文本替换的功能。
// Rust 中的宏在语法解析之后起作用,可以获取更多的上下文信息,而且更加安全。
// 可以把“宏”视为“元编程”的一种方式。它是一种“生成程序的程序”
// 实现编译阶段检查
fn test1() {
// 下面的代码会编译失败。就是通过宏实现的编译阶段检查
// println!("number {} number {}");
// 使用宏,可以在编译阶段分析这个字符串常量和对应参数,确保它符合约定。
// 另外一个常见的场景是,利用宏来检查正则表达式的正确性。
}
test1();
// 实现编译器计算
fn test2() {
// 打印出当前源代码的文件名,以及当前代码的行数。这些信息是纯编译阶段的信息
println!("file {} line {}", file!(), line!());
}
test2();
// 实现自动代码生成
// 实现语法扩展
// 可以使用宏来设计比较方便的“语法糖”
fn test3() {
let v = vec![1, 2, 3, 4, 5];
println!("{:?}", v);
}
test3();
}
// 示范型宏
pub fn second() {
// 自定义宏的两种方式
// 1. 通过标准库提供的 macro_rules! 宏实现
// 2. 通过提供编译器扩展来实现
// macro_rules! 是标准库中提供的一个编写简单宏的小工具,
// 它本身也是用编译器扩展来实现的。它可以提供一种“示范型”(by example)宏编写方式
// let counts = hashmap!['A' => 0, 'C' => 0];
// 在大括号里面,定义宏的使用语法,以及它展开后的形态。
// 定义方式类似 match 语句的语法, expander => { transcriber }。
// 左边的是宏扩展的语法定义,后面是宏扩展的转换机制。
// 语法定义的标识符以 $ 开头,类型支持 item、block、stmt、pat、expr、ty、itent、path、tt。
// 在宏里面,可以支持重复多个语法元素。类似正则表达式的概念,+ 模式代表一个或者多个重复,
// * 模式代表零个或者多个重复。要把需要重复的部分用括号括起来,并加上逗号分隔符
// 需求是需要一个表达式,一个“=>”标识符,再跟一个表达式
macro_rules! hashmap {
($( $key: expr => $val: expr ), *) => {{
{
let mut map = std::collections::HashMap::new();
// 在语法扩展的部分也使用 * 符号,将输入部分扩展为多条 insert 语句
$( map.insert($key, $val); ) *;
map
}
}}
}
let counts = hashmap!['A' => 0, 'C' => 0, 'G' => 0, 'T' => 0];
println!("{:?}", counts);
// 确定宏展开是否正确:需要在 nightly compiler 中使用
// rustc -Z unstable-options --pretty=expanded scr/ch09/first.rs temp.rs
}
// 过程宏
pub fn third() {
// 它直接用 Rust 语言编写相当于一个编译器插件。
// 但是编译器插件的最大问题是,它依赖于编译器的内部实现方式。
// 一旦编译器内部有所变化,那么对应的宏就有可能出现编译错误
// 因此 Rust 中的“宏”一直难以稳定
// ...
}
|
Java
|
UTF-8
| 1,961
| 2.09375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package nl.futureedge.simple.jta.store.jdbc.sql;
import org.junit.Assert;
import org.junit.Test;
public class JdbcSqlTemplateTest {
@Test
public void testHsqldb() {
final JdbcSqlTemplate result = JdbcSqlTemplate.determineSqlTemplate("jdbc:hsqldb:hsql:localhost/jta");
Assert.assertNotNull(result);
Assert.assertTrue(result instanceof HsqldbSqlTemplate);
}
@Test
public void testHsqldbInMemory() {
final JdbcSqlTemplate result = JdbcSqlTemplate.determineSqlTemplate("jdbc:hsqldb:mem/jta");
Assert.assertNotNull(result);
Assert.assertTrue(result instanceof HsqldbSqlTemplate);
}
@Test
public void testMysql() {
final JdbcSqlTemplate result = JdbcSqlTemplate.determineSqlTemplate("jdbc:mysql:localhost/jta");
Assert.assertNotNull(result);
Assert.assertTrue(result instanceof MysqlSqlTemplate);
}
@Test
public void testMariadb() {
final JdbcSqlTemplate result = JdbcSqlTemplate.determineSqlTemplate("jdbc:mariadb:localhost/jta");
Assert.assertNotNull(result);
Assert.assertTrue(result instanceof MysqlSqlTemplate);
}
@Test
public void testPostgresql() {
final JdbcSqlTemplate result = JdbcSqlTemplate.determineSqlTemplate("jdbc:postgresql:localhost/jta");
Assert.assertNotNull(result);
Assert.assertTrue(result instanceof PostgresqlSqlTemplate);
}
@Test
public void testDefault() {
final JdbcSqlTemplate result = JdbcSqlTemplate.determineSqlTemplate("jdbc:oracle:thin:@localhost:1521:jta");
Assert.assertNotNull(result);
Assert.assertEquals(DefaultSqlTemplate.class, result.getClass());
}
@Test
public void testUnknown() {
final JdbcSqlTemplate result = JdbcSqlTemplate.determineSqlTemplate("ILLEGAL!?");
Assert.assertNotNull(result);
Assert.assertEquals(DefaultSqlTemplate.class, result.getClass());
}
}
|
Markdown
|
UTF-8
| 667
| 2.640625
| 3
|
[] |
no_license
|
---
layout: work
title: Lead Frontend Developer at Nabbesh
tech_stack: React.js, JavaScript, Python, Django, Elasticsearch, Sass, py.test, AWS, Docker, Terraform
work_type: Remote, Full time
work_period: November 2015 - December 2016
image: nabbesh.jpg
order: 10
type_tags: full_time, remote
link: https://www.nabbesh.com/
---
Lead Frontend Developer in [nabbesh.com](https://www.nabbesh.com){:target="_blank"}, the leading freelance marketplace in Middle-East and North Africa. Led the redesign project, launched a new style-guide, built product features, automated tests, marketing pages. Also contributed as a DevOps Engineer by moving our infrastructure to AWS.
|
C#
|
UTF-8
| 547
| 2.578125
| 3
|
[] |
no_license
|
using UnityEngine;
public class ScreenResizer : MonoBehaviour {
Camera cam;
public int ppu = 128;
public int scale = 1;
void Start () {
Resize();
}
public void Resize()
{
cam = gameObject.GetComponent<Camera>();
//Debug.Log("Screen Resolution: " + cam.pixelWidth + " x " + cam.pixelHeight + ".");
float maxTileHeight = (float)cam.pixelHeight / (float)(ppu * scale);
//Debug.Log("unit height: " + maxTileHeight);
cam.orthographicSize = maxTileHeight * 0.5f;
}
}
|
Java
|
UTF-8
| 1,909
| 3.484375
| 3
|
[] |
no_license
|
package day09;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
// Table -> Class
class StudentVO {
// field -> property
private String stId = null;
private String name = null;
private String addr = null;
public String getStId() {
return stId;
}
public void setStId(String stId) {
this.stId = stId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
@Override
public String toString() {
return this.stId + "\t" + this.name + "\t" + this.addr;
}
}
public class Test100 {
static String url = "jdbc:mysql://127.0.0.1:3306/study?serverTimezone=UTC";
static String user = "root";
static String pw = "root1234";
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, pw);
Statement stmt = conn.createStatement();
String sql = "SELECT stId, name, addr from studentt";
ResultSet rs = stmt.executeQuery(sql);
// 데이터 단순 쌓기 -> ArrayList 가 빠르다!
List<StudentVO> rl = new ArrayList<StudentVO>();
while ( rs.next() ) {
StudentVO vo = new StudentVO();
vo.setStId( rs.getString("stId") );
vo.setName( rs.getString("name") );
vo.setAddr( rs.getString("addr") );
rl.add(vo);
}
rs.close();
stmt.close();
conn.close();
for ( StudentVO vo : rl ) {
System.out.println(vo.toString());
}
}
}
|
Python
|
UTF-8
| 2,306
| 2.953125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
from nltk.stem.lancaster import LancasterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
from collections import Counter
import re
import xml.etree.ElementTree as ET
######################################################
# global variables
######################################################
glob_Lucene = ["a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with"];
def parse_supervised(train_filename, windowsize):
traindata = {}
trainfile = open(train_filename,'r')
#TODO:
#Provide a sentence-level API that takes a single
#entry as input and output (word, senseID, lemma_stem_sentence(" ".join(example))
#see 'inference.py' line 31-37
for line in trainfile.readlines():
entry = parse_entry(line, windowsize)
# output dictionary: {word:[example1, example2,..]}
if (entry[0], entry[1]) in traindata:
traindata[(entry[0], entry[1])].append(entry[2])
else:
traindata[(entry[0], entry[1])] = []
traindata[(entry[0], entry[1])].append(entry[2])
return traindata
def parse_entry(line, windowsize):
# given an original tuple in the train.data, parse it into an entry (word, senseID, context)
entry = []
words = line.split()
# only want the sentence starting from the 5th word in an entry
example = words[4:]
useful = lemma_stem_sentence(" ".join(example))
# find the target word
index = useful.index('%%')
fv = useful[index-windowsize:index] + useful[index+3:index+windowsize+3]
entry.append(words[0])
entry.append(words[2])
entry.append(fv)
return entry
def lemma_stem_sentence(sentence):
lmtzr = WordNetLemmatizer()
ls = LancasterStemmer()
word_list = []
# only keeps words aA-zZ0-9_ and %%
single_words = re.findall("\w+|%%",sentence)
for single_word in single_words:
lemmed = lmtzr.lemmatize(single_word)
if not lemmed in glob_Lucene:
word_list.append(lemmed)
return word_list
if __name__ == '__main__':
## parse_supervised("training_data.data")
parse_supervised("sample.data", 3)
|
C++
|
UTF-8
| 9,140
| 3.234375
| 3
|
[] |
no_license
|
/**
* @file DrawHeartCommand.cpp
* @brief DrawHeartCommand implementation, a command for drawing with the heart brush
* @author Mike and created by Lunden and refactored by team van_doesnt_go
* @date 2020-08-02
***********************************************/
#include "App.hpp"
#include "command/DrawHeartCommand.hpp"
/*! \brief This constructor is used to create a DrawHeartCommand Command
*
*/
DrawHeartCommand::DrawHeartCommand(const CommandDescription & commandDescription, App* mainApp):
AbstractCommand(commandDescription, mainApp) {
}
/*! \brief This constructor adds all the pixels of a heart to a vector and then returns it
*
*/
std::vector<Pixel> DrawHeartCommand::getHeartPixels() {
unsigned int x = _pixelData.getX();
unsigned int y = _pixelData.getY();
std::vector<Pixel> data;
//First Row of Hearts Pixels
auto* frOne = new Pixel(x + 1, y + 1,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*frOne);
auto* frTwo = new Pixel(x + 2, y + 1,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*frTwo);
auto* frThre = new Pixel(x + 6, y + 1,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*frThre);
auto* frFour = new Pixel(x + 7, y + 1,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*frFour);
delete frOne;
delete frTwo;
delete frThre;
delete frFour;
//Second Row of Heart Pixels
auto* srOne = new Pixel(x, y + 2,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*srOne);
auto* srTwo = new Pixel(x + 1, y + 2,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*srTwo);
auto* srThree = new Pixel(x + 2, y + 2,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*srThree);
auto* srFour = new Pixel(x + 3, y + 2,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*srFour);
auto* srFive = new Pixel(x + 5, y + 2,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*srFive);
auto* srSix = new Pixel(x + 6, y + 2,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*srSix);
auto* srSeven = new Pixel(x + 7, y + 2,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*srSeven);
auto* srEight = new Pixel(x + 8, y + 2,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*srEight);
delete srOne;
delete srTwo;
delete srThree;
delete srFour;
delete srFive;
delete srSix;
delete srSeven;
delete srEight;
//Third Row of Heart Pixels
auto* trOne = new Pixel(x, y + 3,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*trOne);
auto* trTwo = new Pixel(x + 1, y + 3,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*trTwo);
auto* trThree = new Pixel(x + 2, y + 3,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*trThree);
auto* trFour = new Pixel(x + 3, y + 3,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*trFour);
auto* trFive = new Pixel(x + 5, y + 3,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*trFive);
auto* trSix = new Pixel(x + 6, y + 3,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*trSix);
auto* trSeven = new Pixel(x + 7, y + 3,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*trSeven);
auto* trEight = new Pixel(x + 8, y + 3,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*trEight);
delete trOne;
delete trTwo;
delete trThree;
delete trFour;
delete trFive;
delete trSix;
delete trSeven;
delete trEight;
//Fourth Row of Heart Pixels
auto* froOne = new Pixel(x, y + 4,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*froOne);
auto* froTwo = new Pixel(x + 1, y + 4,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*froTwo);
auto* froThree = new Pixel(x + 2, y + 4,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*froThree);
auto* froFour = new Pixel(x + 3, y + 4,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*froFour);
auto* froFive = new Pixel(x + 5, y + 4,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*froFive);
auto* froSix = new Pixel(x + 6, y + 4,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*froSix);
auto* froSeven = new Pixel(x + 7, y + 4,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*froSeven);
auto* froEight = new Pixel(x + 8, y + 4,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*froEight);
auto* froNine = new Pixel(x + 4, y + 4,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*froNine);
delete froOne;
delete froTwo;
delete froThree;
delete froFour;
delete froFive;
delete froSix;
delete froSeven;
delete froEight;
delete froNine;
//Fifth Row of Heart Pixels
auto* fioOne = new Pixel(x + 1, y + 5,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*fioOne);
auto* fioTwo = new Pixel(x + 2, y + 5,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*fioTwo);
auto* fioThree = new Pixel(x + 3, y + 5,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*fioThree);
auto* fioFour = new Pixel(x + 4, y + 5,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*fioFour);
auto* fioFive = new Pixel(x + 5, y + 5,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*fioFive);
auto* fioSix = new Pixel(x + 6, y + 5,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*fioSix);
auto* fioSeven = new Pixel(x + 7, y + 5,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*fioSeven);
delete fioOne;
delete fioTwo;
delete fioThree;
delete fioFour;
delete fioFive;
delete fioSix;
delete fioSeven;
//Sixth Row of Heart Pixels
auto* sioOne = new Pixel(x + 2, y + 6,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*sioOne);
auto* sioTwo = new Pixel(x + 3, y + 6,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*sioTwo);
auto* sioThree = new Pixel(x + 4, y + 6,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*sioThree);
auto* sioFour = new Pixel(x + 5, y + 6,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*sioFour);
auto* sioFive = new Pixel(x + 6, y + 6,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*sioFive);
delete sioOne;
delete sioTwo;
delete sioThree;
delete sioFour;
delete sioFive;
//Seventh Row of Heart Pixels
auto* sevOne = new Pixel(x + 3, y + 7,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*sevOne);
auto* sevTwo = new Pixel(x + 4, y + 7,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*sevTwo);
auto* sevThree = new Pixel(x + 5, y + 7,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*sevThree);
delete sevOne;
delete sevTwo;
delete sevThree;
//Eight Row of Heart Pixels
auto* eiOne = new Pixel(x + 4, y + 8,
_pixelData.getBrushColor(), _pixelData.getCanvasColor());
data.push_back(*eiOne);
delete eiOne;
return data;
}
/*! \brief This method draws a pixel on the canvas
*
*/
bool DrawHeartCommand::execute() {
std::vector<Pixel> data = getHeartPixels();
pixelVector.push(data);
std::vector<Pixel>::iterator iterator;
for(iterator = data.begin(); iterator != data.end(); ++iterator){
if ((iterator->getX() <= app->canvasWidth) &&
(iterator->getY() <= app->canvasHeight)) {
app->GetImage().setPixel(iterator->getX(), iterator->getY(), iterator->getBrushColor());
}
}
return true;
}
|
Markdown
|
UTF-8
| 13,694
| 3.203125
| 3
|
[] |
no_license
|
# Reproducible Research: Peer Assessment 1
Lucas Roesler
In this analysis we are working with measurement data collected from a personal
activity monitoring device. This analysis is only an exploration of the data from
a single person. We will see that the dataset has many missing values, entire days
are missing, and that how we treat this missing data can drastically affect the
resulting statistics. Our primary focus is on descriptive statics of the mean
and median steps taken.
## Data description
The dataset contains measurements data from a personal activity monitoring device. This device collects data at 5 minute intervals through out the day. The data consists of two months of data from an anonymous individual collected during the months of October and November, 2012 and include the number of steps taken in 5 minute intervals each day.
The dataset includes three variables:
* __steps__: Number of steps taking in a 5-minute interval (missing values are coded as `NA`)
* __date__: The date on which the measurement was taken in YYYY-MM-DD format
* __interval__: Identifier for the 5-minute interval in which measurement was taken
The dataset is stored in a comma-separated-value (CSV) file and there are a total of 17,568 observations in this dataset.
## Loading and preprocessing the data
The data for this analysis can be downloaded from the Coursera Reproducible Research website. We are using the [Activity monitoring dataset](https://d396qusza40orc.cloudfront.net/repdata%2Fdata%2Factivity.zip)
The following code will download and extract the dataset into the current folder.
```r
dataset_url <- "https://d396qusza40orc.cloudfront.net/repdata%2Fdata%2Factivity.zip"
if (!file.exists("activity.zip")) {
download.file(
url = dataset_url,
destfile = "activity.zip", method = "curl")
}
if(!file.exists("activity.csv")){
unzip("activity.zip")
}
```
This data analysis will use the `data.table` library.
```r
if(!require(data.table)) {
install.packages(data.table)
}
library(data.table)
```
We can then read in and preview the dataset
```r
activity <- fread('activity.csv', sep=",", header=T)
head(activity)
```
```
## steps date interval
## 1: NA 2012-10-01 0
## 2: NA 2012-10-01 5
## 3: NA 2012-10-01 10
## 4: NA 2012-10-01 15
## 5: NA 2012-10-01 20
## 6: NA 2012-10-01 25
```
```r
str(activity)
```
```
## Classes 'data.table' and 'data.frame': 17568 obs. of 3 variables:
## $ steps : int NA NA NA NA NA NA NA NA NA NA ...
## $ date : chr "2012-10-01" "2012-10-01" "2012-10-01" "2012-10-01" ...
## $ interval: int 0 5 10 15 20 25 30 35 40 45 ...
## - attr(*, ".internal.selfref")=<externalptr>
```
## What is mean total number of steps taken per day?
In this section we investigate the general shape of the dataset. We start by
investigating the total steps take on each day. Note that will ignore any
missing values, for now.
```r
daily_step_total <- activity[, sum(steps, na.rm=T), by=date]
setnames(daily_step_total, c("date", "total"))
head(daily_step_total)
```
```
## date total
## 1: 2012-10-01 0
## 2: 2012-10-02 126
## 3: 2012-10-03 11352
## 4: 2012-10-04 12116
## 5: 2012-10-05 13294
## 6: 2012-10-06 15420
```
```r
summary(daily_step_total$total)
```
```
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0 6780 10400 9350 12800 21200
```
We can see that there is a very wide variety in the total number of steps taken
per day. In particular, there are some very small values with the minimum being
0 and the total number of steps on 2012-10-02 being 126, but most days have well
over 6000 steps since the 1st quarterly is 6778. The zeros are likely due to
missing data.
We can use a histogram to see the general shape of the data. I increased the
number of bins in the histogram to 15 because we can see that there is a wide
variety in the totals mentioned above.
```r
hist(daily_step_total$total, breaks=15,
xlab="Total Steps", main="Historgram of steps taken per day")
```

The mean and median total number of steps taken per day are 9354.23 and 10395
respectively.
```r
data.frame(
mean=mean(daily_step_total$total),
median=median(daily_step_total$total)
)
```
```
## mean median
## 1 9354 10395
```
These values match well with the shape of the histogram, due to the noticeable
spike around 10000 steps.
## What is the average daily activity pattern?
To see how activity changes throughout the day, we can calculate the
average steps during each measurement period, 5-minute interval.
```r
interval_step_avg<- activity[, mean(steps, na.rm=T), by=interval]
setnames(interval_step_avg, c("interval", "steps_avg"))
```
To more easily plot this data, we convert the interval column into proper time
values. The original values are integers of the format `HHMM`. Note that the
resulting time objects include the current date, but this extraneous data is
ignored while plotting.
```r
times <- as.POSIXct(paste(as.integer(interval_step_avg$interval / 100),
interval_step_avg$interval %% 100, sep=":"),
format="%H:%M")
plot(interval_step_avg$steps_avg ~ times,
type="l",
xlab="Time (24hr format)",
ylab="Average Number of Steps",
main="Step Count throughout the Day\n 2012-10-01 -- 2012-11-30")
```

From the graph, we might estimate that the maximum average number steps occurs
between 8 AM and 9 AM (intervals 800 and 900). A quick calculation reveals
that the max occurs at 8:35 AM (interval 835).
```r
interval_step_avg$interval[which.max(interval_step_avg$steps_avg)]
```
```
## [1] 835
```
## Imputing missing values
The previous analysis ignored any missing values. In this dataset there are
2304 missing values out of a 17568 total measurements, roughly 13% of the data
is missing. A quick investigation of the data suggests that this missing data
comes from days in which the step counting device was not worn.
```r
# calculate the number of missing values
sum(is.na(activity$steps))
```
```
## [1] 2304
```
```r
# The total number of values
length(activity$steps)
```
```
## [1] 17568
```
When we calculate when those missing values occurred, we see that it is
restricted to a small subset of the data, 8 days in total:
```r
unique(activity[is.na(activity$steps)]$date)
```
```
## [1] "2012-10-01" "2012-10-08" "2012-11-01" "2012-11-04" "2012-11-09"
## [6] "2012-11-10" "2012-11-14" "2012-11-30"
```
Further, those days are missing data for the entire day. Note that there are
288 5-minute intervals in a day.
```r
missing_data <- activity[is.na(activity$steps)]
missing_data[, list(missing_count=length(steps)), by=date]
```
```
## date missing_count
## 1: 2012-10-01 288
## 2: 2012-10-08 288
## 3: 2012-11-01 288
## 4: 2012-11-04 288
## 5: 2012-11-09 288
## 6: 2012-11-10 288
## 7: 2012-11-14 288
## 8: 2012-11-30 288
```
This leads us to conclude that the counting device was not worn on those days.
These missing values could skew the previous calculations. In particular, the
behavior on those days with missing data could be drastically different from the
other days, hence biasing toward the values on the other days
([1][Gelman], [2][Margolis]).
[comment]: Devise a strategy for filling in all of the missing values in the dataset. The strategy does not need to be sophisticated. For example, you could use the mean/median for that day, or the mean for that 5-minute interval, etc.
One of the simplest ways to deal with these missing values would be to replace
the missing values with a related mean value. For example, we could replace the
value with the mean of the corresponding 5-minute interval. We will actually
use the rounded mean value because steps is integer valued.
[comment]: Create a new dataset that is equal to the original dataset but with the missing data filled in.
```r
interval_means <- activity[, list(steps=round(mean(steps, na.rm=T))), by=interval]
imputed_activity <- activity
# note that this particular line works because of how R repeats vectors
# and the distribution of missing values occuring in whole day intervals.
imputed_activity$steps[is.na(imputed_activity$steps)] <- interval_means$steps
```
[comment]: Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day. Do these values differ from the estimates from the first part of the assignment?
Having replaced the missing values with their corresponding mean values, we
reconsider the previous descriptive statistics of the data set. Not
surprisingly, ([1][Gelman], [2][Margolis]), we immediately see that the dataset
has been pulled toward the original mean. In fact, it is centeredy higher than
the original dataset.
```r
imputed_step_total <- imputed_activity[, sum(steps, na.rm=T), by=date]
setnames(imputed_step_total, c("date", "total"))
hist(daily_step_total$total, breaks=15, xlab="Total Steps",
main="Historgram of steps taken per day\n original data")
```

```r
hist(imputed_step_total$total, breaks=15, xlab="Total Steps",
main="Historgram of steps taken per day\n imputed data")
```

[comment]: What is the impact of imputing missing data on the estimates of the total daily number of steps?
More specifically, the mean has increased by 1411.41 and the median has
increased by 367.
```r
stats <- data.frame(
original=c(mean(daily_step_total$total),
median(daily_step_total$total)),
imputed=c(mean(imputed_step_total$total),
median(imputed_step_total$total)),
row.names=c("mean", "median")
)
stats
```
```
## original imputed
## mean 9354 10766
## median 10395 10762
```
```r
stats$imputed - stats$original
```
```
## [1] 1411 367
```
Note that this strategy of imputing the data using means can generally distort
the distribution of the data, skewing the calculation of summary statistics,
most notably underestimating the standard deviation ([1][Gelman]). This could
lead to overfitting models on the dataset ([2][Margolis]). Because people
commonly have similar schedules from week to week, a potential method to
improving the mean imputation, is to one use the mean of 5-minute intervals
for the same day of the week. Or even more simply, for weekdays use weekday
means and for weekends use means from weekends.
## Are there differences in activity patterns between weekdays and weekends?
[comment]:For this part the weekdays() function may be of some help here. Use the dataset with the filled-in missing values for this part.
[comment]: Create a new factor variable in the dataset with two levels – “weekday” and “weekend” indicating whether a given date is a weekday or weekend day.
How does the activity data for the weekend compare to the weekday?
```r
daynames <- weekdays(as.POSIXct(imputed_activity$date))
daynames[daynames %in% c("Saturday", "Sunday")] <- "weekend"
daynames[daynames != "weekend"] <- "weekday"
imputed_activity$day_type <- factor(daynames)
```
Viewed as a time series plot, we see that this person is, on average, more active during the weekend. There are more high peeks in average steps taken. This activity starts slightly later in the day versus weekdays. Also, noticable, the steps activity starts and increases very suddenly early in the morning. On the weekends, the activity builds up more slowly.
```r
interval_avgs <- imputed_activity[, mean(steps), by=list(interval, day_type)]
setnames(interval_avgs, c("interval", "day_type", "steps_avg"))
interval_avgs$times <- as.POSIXct(paste(as.integer(interval_avgs$interval / 100), interval_avgs$interval %% 100, sep=":"), format="%H:%M")
head(interval_avgs)
```
```
## interval day_type steps_avg times
## 1: 0 weekday 2.28889 2014-09-14 00:00:00
## 2: 5 weekday 0.40000 2014-09-14 00:05:00
## 3: 10 weekday 0.15556 2014-09-14 00:10:00
## 4: 15 weekday 0.17778 2014-09-14 00:15:00
## 5: 20 weekday 0.08889 2014-09-14 00:20:00
## 6: 25 weekday 1.57778 2014-09-14 00:25:00
```
```r
par(mfrow=c(1,2))
with(interval_avgs[interval_avgs$day_type == "weekday"],
plot(steps_avg ~ times,
type="l",
xlab="Time (24hr format)",
ylab="Average Number of Steps",
main="Step Count Weekdays\n 2012-10-01 -- 2012-11-30"))
with(interval_avgs[interval_avgs$day_type == "weekend"],
plot(steps_avg ~ times,
type="l",
xlab="Time (24hr format)",
ylab="Average Number of Steps",
main="Step Count Weekends\n 2012-10-01 -- 2012-11-30")
)
```

---
## References
1. [Gelman, Andrew. Missing-data Imputation. http://www.stat.columbia.edu/~gelman/arm/missing.pdf (2014-09-07)][Gelman]
1. [Margolis, Rachel. Dealing with Missing Data: Strategies for Beginners to Data Analysis. http://rdc.uwo.ca/Slides1/MargolisMissingData.pdf (2014-09-07)][Margolis]
[Gelman]: http://www.stat.columbia.edu/~gelman/arm/missing.pdf
[Margolis]: http://rdc.uwo.ca/Slides1/MargolisMissingData.pdf
|
Swift
|
UTF-8
| 3,780
| 2.578125
| 3
|
[] |
no_license
|
//
// UserInitialViewController.swift
// NiteLyfe
//
// Created by Jonah Zukosky on 10/13/17.
// Copyright © 2017 Jonah Zukosky. All rights reserved.
//
import UIKit
import MapKit
class UserInitialViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
let regionRadius:CLLocationDegrees = 5000
let initialLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(38.946047, -92.330131)
//var artworks = [pinAnnotation]()
// Flat Branch, Shakespeares, Seoul taco, Tropical
var latitudes = [38.950148, 38.948679, 38.951276, 38.951848]
var longtitudes = [-92.332041, -92.327943, -92.3256, -92.331157]
// 1000 meters: alittle more than half a mile
mapView.setRegion(MKCoordinateRegionMakeWithDistance(initialLocation, regionRadius, regionRadius), animated: true)
mapView.delegate = self
for index in 1...4{
if(index<5){
let my_latitude: Double = latitudes[index-1]
let my_longitude: Double = longtitudes[index-1]
// show artwork on map
let artwork = pinAnnotation(title: "King David Kalakaua",
locationName: "Waikiki Gateway Park",
discipline: "Sculpture",
coordinate: CLLocationCoordinate2D(latitude: my_latitude, longitude: my_longitude))
//artworks.append(artwork)
mapView.addAnnotation(artwork)
}
}
//mapView.addAnnotations(artworks)
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// func loadInitialData() {
// // 1
// guard let fileName = Bundle.main.path(forResource: "PublicArt", ofType: "json")
// else { return }
// let optionalData = try? Data(contentsOf: URL(fileURLWithPath: fileName))
//
// guard
// let data = optionalData,
// let json = try? JSONSerialization.jsonObject(with: data),
// let dictionary = json as? [String: Any],
// let works = dictionary["data"] as? [[Any]]
// else { return }
// // 5
// let validWorks = works.flatMap { pinAnnotation(json: $0) }
// artworks.append(contentsOf: validWorks)
// }
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension UserInitialViewController: MKMapViewDelegate {
// 1
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// 2
guard let annotation = annotation as? pinAnnotation else { return nil }
// 3
let identifier = "marker"
var view: MKMarkerAnnotationView
// 4
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKMarkerAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
// 5
view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
return view
}
}
|
Java
|
UTF-8
| 1,269
| 1.835938
| 2
|
[] |
no_license
|
package com.epoch.cc.utils.newform;
import java.io.Serializable;
/**
* @author songxl
* @version 创建时间:2012-8-6 上午11:42:57
* @discription
*/
public class InitFieldVo implements Serializable{
private String billid;
private String deptId;
private String billName;
private String deptName;
private String userid;
private String username;
private String billNumber;
public String getBillid() {
return billid;
}
public void setBillid(String billid) {
this.billid = billid;
}
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
public String getBillName() {
return billName;
}
public void setBillName(String billName) {
this.billName = billName;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getBillNumber() {
return billNumber;
}
public void setBillNumber(String billNumber) {
this.billNumber = billNumber;
}
}
|
Python
|
UTF-8
| 2,735
| 3.34375
| 3
|
[] |
no_license
|
'''
Created on Nov 12, 2018
@author: Matthew Peek
@change: 12 November 2018
'''
import sys
from matplotlib import pyplot as plt
from queryPackage.SDSSQuery import SDSSQuery
class HRDiagram:
def __init__(self, longitude, latitude, radiusMultiplier):
self.query = SDSSQuery(longitude, latitude, radiusMultiplier)
self.result = self.query.querySpectra()
self.objectColor = []
self.gFilter = []
self.rFilter = []
"""
GetGFilter function looks in query result and gets modelMag_g column.
@return: list of g filter values.
"""
def getGFilter(self):
for i in range(0, len(self.result)):
if (self.result[i]['type'] == 'STAR'):
self.gFilter.append(self.result[i]['modelMag_g'])
return self.gFilter
#End getGFilter function
"""
GetRFilter function looks in query result and gets modelMag_r column.
@return: list of r filter values.
"""
def getRFilter(self):
for i in range(0, len(self.result)):
if (self.result[i]['type'] == 'STAR'):
self.rFilter.append(self.result[i]['modelMag_r'])
return self.rFilter
#End getRFilter function
"""
GetObjectColors function subtracts every value in g filter list from every value
in r filter list to obtain an objects color.
@return: list of object's color in magnitude.
"""
def getObjectColors(self):
self.getGFilter()
self.getRFilter()
for i in range(0, len(self.gFilter)):
objColor = (self.gFilter[i] - self.rFilter[i])
self.objectColor.append(objColor)
return self.objectColor
#End getObjectColors function
"""
MakeDiagram function makes a scatter plot using objectColor and
rFilter lists. X-axis = filters g-r for temperature.
Y-axis = luminosity.
This diagram plots star types, as x increases, temperature increases.
As y increases brightness of star decreases.
"""
def makeDiagram(self):
self.getObjectColors()
numStars = len(self.rFilter)
plt.scatter(self.getObjectColors(), self.getRFilter(), label="Stars: %i" %numStars)
plt.xlabel("Temperature")
plt.ylabel("Luminosity")
plt.legend()
plt.show()
#End makeDiagram function
"""
RunHRDiagram function calls makeDiagram function.
sys.stdout.flush() sends output to node.js for html display.
"""
def runHRDiagram(self):
self.makeDiagram()
sys.stdout.flush()
#End runHRDiagram function
"""
Test HRDiagram Implementation
target1 = HRDiagram(143.50993, 03.239775, 20)
target1.makeDiagram()
"""
|
Java
|
UTF-8
| 6,807
| 2.390625
| 2
|
[] |
no_license
|
package eu.clarussecure.dataoperations.encryption;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import static com.mongodb.client.model.Filters.eq;
import com.mongodb.client.model.UpdateOptions;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bson.Document;
public class KeyStore {
private static KeyStore instance = null;
private final MongoDatabase db;
private final MongoClient mongoClient;
private final MongoCollection<Document> keystoreCollection;
private int instancesNumber;
private String confFile = "/etc/clarus/clarus-keystore.conf";
private String mongoDBHostname = "localhost"; // Default server
private int mongoDBPort = 27017; // Default port
private String clarusDBName = "CLARUS"; // Default DB name
private KeyStore() {
// Initiate the basic connections to the database
// Correctly configure the log level
Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
mongoLogger.setLevel(Level.SEVERE);
// Open the configuraiton file to extract the information from it.
this.processConfigurationFile();
// Create a new client connecting to "localhost" on port
this.mongoClient = new MongoClient(this.mongoDBHostname, this.mongoDBPort);
// Get the database (will be created if not present)
this.db = mongoClient.getDatabase(this.clarusDBName);
this.keystoreCollection = this.db.getCollection("keystore");
this.instancesNumber++;
}
public static KeyStore getInstance() {
if (KeyStore.instance == null) {
KeyStore.instance = new KeyStore();
}
return KeyStore.instance;
}
public void deleteInstance() {
this.instancesNumber--;
if (this.instancesNumber <= 0) {
this.mongoClient.close();
KeyStore.instance = null;
}
}
public SecretKey retrieveKey(String dataID) {
SecretKey key = null;
String stringKey;
// Check if there is an entry for this data ID
if (this.keystoreCollection.count(eq("dataID", dataID)) <= 0) {
// There is not a Key-IV pair, generate one
this.generateSecurityParameters(dataID);
}
// At this point, a Key-IV pair EXISTS in the DB for this dataID
// Retrieve the key
MongoCursor<Document> keys = this.keystoreCollection.find(eq("dataID", dataID)).iterator();
if (keys.hasNext()) {
// A key was found, retrieve it
Document doc = keys.next();
stringKey = doc.getString("enckey");
// Create the Key Object
byte[] bytesKey = Base64.getDecoder().decode(stringKey);
key = new SecretKeySpec(bytesKey, 0, bytesKey.length, "AES");
}
return key;
}
public byte[] retrieveInitVector(String dataID) {
byte[] bytesIV = new byte[16];
// Check if there is an entry for this data ID
if (this.keystoreCollection.count(eq("dataID", dataID)) <= 0) {
// There is not a Key-IV pair, generate one
this.generateSecurityParameters(dataID);
}
// At this point, a Key-IV pair EXISTS in the DB for this dataID
// Retrieve the IV
MongoCursor<Document> ivs = this.keystoreCollection.find(eq("dataID", dataID)).iterator();
if (ivs.hasNext()) {
// An IV was found, retrieve it
Document doc = ivs.next();
String stringIV = doc.getString("initvector");
// Decode the IV from the string
bytesIV = Base64.getDecoder().decode(stringIV);
}
return bytesIV;
}
protected boolean generateSecurityParameters(String dataID) {
SecretKey key = null;
String stringKey;
byte[] bytesIV = new byte[16];
String stringIV;
try {
// Generate new Key for AES algorithm
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(this.getKeyLength());
key = keygen.generateKey();
// Encode it into a String
stringKey = Base64.getEncoder().encodeToString(key.getEncoded());
// Generate a Random Init Vector
SecureRandom randomGen = new SecureRandom();
randomGen.nextBytes(bytesIV);
// Encode it into a String
stringIV = Base64.getEncoder().encodeToString(bytesIV);
// Prepare the document into the dabase
Document doc = new Document("dataID", dataID);
doc.append("enckey", stringKey);
doc.append("initvector", stringIV);
// Store the encoded key into the database
boolean ack = this.keystoreCollection
.replaceOne(eq("dataID", dataID), doc, new UpdateOptions().upsert(true)).wasAcknowledged();
return ack;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
System.exit(1);
}
return false;
}
private int getKeyLength() {
// This method should retrieve the key length (in bits) from the DB
MongoCursor<Document> cursor = this.keystoreCollection.find(eq("conf", "simple-keylength")).iterator();
int keyLength = 128; // Default value is 128 bits
while (cursor.hasNext()) {
keyLength = cursor.next().getDouble("keylength").intValue();
}
return keyLength;
}
private void processConfigurationFile() throws RuntimeException {
// Open the file in read-only mode. This will avoid any permission problem
try {
// Read all the lines and join them in a single string
List<String> lines = Files.readAllLines(Paths.get(this.confFile));
String content = lines.stream().reduce("", (a, b) -> a + b);
// Use the bson document parser to extract the info
Document doc = Document.parse(content);
this.mongoDBHostname = doc.getString("CLARUS_keystore_db_hostname");
this.mongoDBPort = doc.getInteger("CLARUS_keystore_db_port");
this.clarusDBName = doc.getString("CLARUS_keystore_db_name");
} catch (IOException e) {
throw new RuntimeException("CLARUS configuration file could not be processed", e);
}
}
}
|
Java
|
UTF-8
| 719
| 2.421875
| 2
|
[] |
no_license
|
package id.application.mvpapp.presenter;
import id.application.mvpapp.contract.MainContract;
import id.application.mvpapp.interactor.MainInteractorImpl;
import id.application.mvpapp.model.Friend;
public class MainPresenterImpl implements MainContract.Presenter {
private MainContract.View mainView;
private MainContract.Interactor mainInteractor;
public MainPresenterImpl(MainContract.View mainView) {
this.mainView = mainView;
this.mainInteractor = new MainInteractorImpl();
}
@Override
public void saveFriend(Friend friend) {
mainInteractor.saveFriend(friend);
mainView.showFriend(mainInteractor.getAllFriendList());
mainView.clearInput();
}
}
|
Java
|
UTF-8
| 1,053
| 2.0625
| 2
|
[] |
no_license
|
package cn.fintecher.file.server.fileservice.fastdfs.service;
import cn.fintecher.common.utils.basecommon.message.Message;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
/**
* Created by wangquan on 2018/5/11.
*/
public interface FileService {
/**
* 文件上传至服务器
* @param multipartFile
* @return
*/
@ResponseBody
ResponseEntity<Message> fileUpload(MultipartFile multipartFile);
/**
* 文件下载
* @param fullPath fastDFS返回的完整文件路径
* @param fileName 文件名
* @return
*/
@ResponseBody
ResponseEntity fileDownLoad(@RequestParam("fullPath") String fullPath, @RequestParam("fileName") String fileName);
/**
* 文件删除
* @param fullPath
* @return
*/
ResponseEntity <Message> fileDelete (@RequestParam("fullPath") String fullPath);
}
|
Python
|
UTF-8
| 1,164
| 3.375
| 3
|
[] |
no_license
|
"""
N = 4
Player #0 ~ #(N-1)
0 1 2 3
4 0 5 6
7 1 0 2
3 4 5 0
한 팀당 N/2 = 2명
Player #0이 포함된 팀을 A, 아닌 팀을 팀 B라 하면 (pivoting)
A -> Player #0 + ((N - 1)명 중 (N/2 - 1)명 뽑기)
"""
import itertools
N = int(input())
grid = [list(map(int, input().split())) for _ in range(N)]
# N = 6
# grid = [[0, 1, 2, 3, 4, 5], \
# [1, 0, 2, 3, 4, 5], \
# [1, 2, 0, 3, 4, 5], \
# [1, 2, 3, 0, 4, 5], \
# [1, 2, 3, 4, 0, 5], \
# [1, 2, 3, 4, 5, 0]]
for i in range(N):
for j in range(i):
grid[j][i] += grid[i][j]
grid[i][j] = 0
answer = 1 << 30
for members in itertools.combinations(range(1, N), N//2 - 1):
teamAList = [0] + list(members)
teamAStat = 0
for i, j in itertools.combinations(teamAList, 2):
teamAStat += grid[i][j]
teamBList = []
teamBStat = 0
for member in range(N):
if member not in teamAList:
teamBList.append(member)
for i, j in itertools.combinations(teamBList, 2):
teamBStat += grid[i][j]
val = abs(teamAStat - teamBStat)
if val < answer:
answer = val
print(answer, end="")
|
Java
|
UTF-8
| 1,199
| 3.78125
| 4
|
[] |
no_license
|
package 第724题_寻找数组的中心下标.解法2;
public class Solution {
public int pivotIndex(int[] nums) {
// 计算nums数组中所有元素的总和
int totalSum = 0;
for (int num : nums) {
totalSum += num;
}
// 前缀和
int preSum = 0;// 存储前i个元素(不包括i)的总和
for (int i = 0; i < nums.length; i++) {
if (2 * preSum + nums[i] == totalSum) {
return i;
}
preSum += nums[i];
}
return -1;
}
}
/*
解题思路:
0.前缀和
1.先统计数组全部元素和为totalSum,当遍历到第i个元素时,前面i个元素(不包括i)的和为preSum
2.则i后面(也不包括i)的元素之和为totalSum-preSum-nums[i]
3.如果totalSum-preSum-nums[i]等于preSum就表示找到了数组的中心下标,其实思路和解法1是一样的
4.totalSum-preSum-nums[i]=preSum -> 2 * preSum + nums[i] == totalSum
*/
/*
执行用时:1 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:39.2 MB, 在所有 Java 提交中击败了47.16% 的用户
*/
|
Markdown
|
UTF-8
| 1,131
| 2.625
| 3
|
[] |
no_license
|
# GPUGraphVisualization
Visualizing community detection after processed by a new graph processing system in GPUs
2016年小组年会演示多GPU图处理系统,其中主要演示的社区发现算法,实现的是LPA算法(社区发现中比较简单一个算法)。
页面主要这么几个部分:
- 社区发现:简单社区发现的例子,为了结合实际说明社区发现在实际中的应用
- 性能对比:GPUs和CPU系统的性能对比
- 大图效果:动态显示社区发现的过程,使用工具主要是linkurious.js。Ps:其他部分都是采用d3实现的。
- 数据结果:图表形式显示GPUs系统和CPU系统性能差异
- 清晰大图:用不同形式显示大图社区发现的动态效果
开始界面如下:

说明:
1. 下载之后,需要解压dataset.zip,把dataset里面的*.txt都拷贝到./linkurious/下。
(原因:dataset里面的数据太大了,超过Github要求文件大小100M,很难上传成功。)
2. 运行的时候,需要打开tomcat。
|
C#
|
UTF-8
| 2,334
| 2.5625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace HackTrainCompany.Windows
{
/// <summary>
/// Interaction logic for DeleteCity.xaml
/// </summary>
public partial class DeleteCity : Window
{
private AdminLoggedIn parent;
public DeleteCity()
{
this.InitializeComponent();
this.CmbCityName.ItemsSource = DataAccess.DataAccess.GetAllCities().Select(x => x.Name);
}
public DeleteCity(ref AdminLoggedIn parent)
{
this.InitializeComponent();
this.parent = parent;
this.CmbCityName.ItemsSource = DataAccess.DataAccess.GetAllCities().Select(x => x.Name);
}
private void BtnCancel_OnClick(object sender, RoutedEventArgs e)
{
this.Close();
}
private void BtnDelete_OnClick(object sender, RoutedEventArgs e)
{
if (this.CmbCityName.SelectedItem == null)
{
MessageBox.Show("Select a city to delete!");
}
else
{
try
{
var cityToDel =
DataAccess.DataAccess.GetAllCities()
.FirstOrDefault(x => x.Name == this.CmbCityName.SelectedItem.ToString());
if (DataAccess.DataAccess.DeleteCity(cityToDel))
{
this.parent.RefreshCityGrid();
MessageBox.Show(string.Format("Successfully deleted {0}", this.CmbCityName.SelectedItem));
this.CmbCityName.ItemsSource = DataAccess.DataAccess.GetAllCities().Select(x => x.Name);
}
else
{
MessageBox.Show("Something went wrong");
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
}
}
}
|
Java
|
UTF-8
| 4,103
| 2.5625
| 3
|
[] |
no_license
|
package com.bitsend.evogene.agents;
import java.util.ArrayList;
import java.util.HashMap;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Vector3;
import com.bitsend.evogene.Direction;
import com.bitsend.evogene.Environment;
import com.bitsend.evogene.Place;
import com.bitsend.evogene.World;
public class Bug extends Agent {
public float speed = 15; // moves per second
protected float totalDelta = 0f;
protected float waitTime = 0f;
int energyUsedPerTurn = 1;
int energy = 20;
public Bug(float x, float y, float z, int speed) {
super(x, y, z);
create();
}
@Override
public void update(World world, float delta) {
totalDelta += delta;
Gdx.app.log("Bug render", "this: " + this.toString() );
energy -= energyUsedPerTurn;
if (totalDelta > waitTime) {
boolean searching = true;
while (searching) {
Direction dir = Direction.RandomDirection();
int nextX = (int) position.x + dir.getXDelta();
int nextY = (int) position.y + dir.getYDelta();
if (world.inWorld(nextX, nextY)) {
Agent agent = world.getContents(nextX, nextY);
if (agent instanceof Food) {
eat(world,agent);
moveTo(nextX, nextY);
searching = false;
}
else if (agent==null) {
moveTo(nextX, nextY);
searching = false;
}
}
/*
HashMap<Direction, Agent> surroundings = world.getSurroundings((int)position.x, (int)position.y, 1);
Direction dir = bestMove(surroundings);
int nextX = (int) position.x + dir.getXDelta();
int nextY = (int) position.y + dir.getYDelta();
if (world.inWorld(nextX, nextY)
&& world.getContents(nextX, nextY) == null) {
moveTo(nextX, nextY);
searching = false;
}
*/
}
totalDelta = 0f;
}
}
public void die(World world) {
Gdx.app.log("Bug.die", "");
world.resetContents((int)this.position.x, (int)this.position.y);
}
public void eat(World world, Agent agent) {
energy += agent.energy;
world.resetContents((int)agent.position.x, (int)agent.position.y);
}
protected Direction bestMove(HashMap<Direction, Agent> surroundings) {
Direction dir = Direction.E;
ArrayList<Direction> food = new ArrayList<Direction>();
ArrayList<Direction> empty = new ArrayList<Direction>();
ArrayList<Direction> predator = new ArrayList<Direction>();
for(Direction d : Direction.values()) {
Agent agent = surroundings.get(dir);
if (agent==null) {
empty.add(d);
}
else if(agent instanceof Bug) {
predator.add(d);
}
else if(agent instanceof Agent) {
food.add(d);
}
}
if (food.get(0) != null) {
dir = food.get(0);
}
else if (empty.size() > 0) {
int i = (int)Math.floor(Math.random() * empty.size());
dir = empty.get(i);
}
return dir;
}
@Override
public void create() {
super.create();
waitTime = 1/speed;
sprite = new Sprite(com.bitsend.evogene.Assets.cell);
sprite.setPosition(0f, 0f);
}
@Override
public String toString() {
return "How Many: " + Bug.HOW_MANY + " Type: " + this.getClass().getName() + " Energy: " + energy;
}
@Override
public void act(Environment environment) {
for(Direction dir : Direction.values()) {
Place place = environment.get(dir);
if (place.contents != null) {
Agent thing = place.contents;
if (thing instanceof Food) {
eat(thing);
}
else if(thing instanceof Bug) {
continue;
}
}
}
}
@Override
public void eat(Agent agent) {
this.energy += agent.energy;
this.position.x = agent.position.x;
this.position.y = agent.position.y;
agent.kill(agent);
}
@Override
public void kill(Agent agent) {
// TODO Auto-generated method stub
}
@Override
public Agent[] reproduce(Agent mate) {
// TODO Auto-generated method stub
return null;
}
@Override
public Vector3 move(int x, int y) {
// TODO Auto-generated method stub
return null;
}
}
|
C++
|
UHC
| 3,069
| 2.859375
| 3
|
[] |
no_license
|
#include "PurchaseManager.hpp"
// ȸ
RM_errcode PurchaseManager::retrieve(std::vector<Purchase>& view)
{
return RecordManager::retrieve(view);
}
// Ž
RM_errcode PurchaseManager::search(const Purchase& source, Purchase& result)
{
return RecordManager::search(source, result);
}
//
RM_errcode PurchaseManager::update(const Purchase& source, int recaddr)
{
refreshRedundant();
Purchase dest;
if (findRedundant(source, dest, seed_both))
{
if(strcmp(source.getKey(0), dest.getKey(0)))
return RM_redundant;
}
return RecordManager::update(source, recaddr);
}
// ߰
RM_errcode PurchaseManager::insert(const Purchase& source)
{
refreshRedundant();
Purchase dest;
if (findRedundant(source, dest, seed_both))
return RM_redundant;
setLastKey();
dest = source;
dest.setKey(lastid, 0);
return RecordManager::insert(dest);
}
//
RM_errcode PurchaseManager::remove(const Purchase& source, int recaddr)
{
return RecordManager::remove(source, recaddr);
}
RM_errcode PurchaseManager::cascade_remove(const Member& m)
{
bool result;
RM_errcode errcode;
Purchase p, dest;
p.setKey(m.getKey(), seed_member);
while (result = findRedundant(p, dest, seed_member))
{
errcode = this->remove(dest, this->find_addr);
refreshRedundant();
if (errcode != RM_valid)
return errcode;
}
return RM_valid;
}
RM_errcode PurchaseManager::cascade_remove(const Lecture& l)
{
bool result;
RM_errcode errcode;
Purchase p, dest;
p.setKey(l.getKey(), seed_lecture);
while (result = findRedundant(p, dest, seed_lecture))
{
errcode = this->remove(dest, this->find_addr);
refreshRedundant();
if (errcode != RM_valid)
return errcode;
}
return RM_valid;
}
RM_errcode PurchaseManager::my_retrieve(const Member& profile, std::vector<Purchase>& view)
{
bool result;
RM_errcode errcode;
view.clear();
Purchase source, dest;
source.setKey(profile.getKey(), seed_member);
refreshRedundant();
while (result = findRedundant(source, dest, seed_member))
{
view.push_back(dest);
}
return RM_valid;
}
RM_errcode PurchaseManager::my_search(const Member& profile, const Lecture& lecture, Purchase& dest)
{
bool result;
RM_errcode errcode;
Purchase source;
source.setKey(profile.getKey(), seed_member);
source.setKey(lecture.getKey(), seed_lecture);
refreshRedundant();
if (!findRedundant(source, dest, seed_both))
return RM_not_found;
return RM_valid;
}
RM_errcode PurchaseManager::my_update(const Member& profile, const Purchase& purchase, int recaddr)
{
if (strcmp(profile.getKey(0), purchase.getKey(seed_member)))
return RM_not_match;
return this->update(purchase);
}
RM_errcode PurchaseManager::my_insert(const Member& profile, const Purchase& purchase, int recaddr)
{
if (strcmp(profile.getKey(0), purchase.getKey(seed_member)))
return RM_not_match;
return this->insert(purchase);
}
RM_errcode PurchaseManager::my_remove(const Member& profile, const Purchase& purchase, int recaddr)
{
if (strcmp(profile.getKey(0), purchase.getKey(seed_member)))
return RM_not_match;
return this->remove(purchase);
}
|
C#
|
UTF-8
| 7,393
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Runtime.InteropServices;
using Hell.LastCircle.Database;
using Hell.LastCircle.System;
namespace Hell.FirstCircle
{
/// <summary>
/// Event from Miranda history.
/// </summary>
public class HistoryItem
{
/// <summary>
/// Event type.
/// </summary>
public enum HistoryItemType : ushort
{
/// <summary>
/// Regular message.
/// </summary>
Message = DBEventInfo.EVENTTYPE_MESSAGE,
/// <summary>
/// URL.
/// </summary>
Url = DBEventInfo.EVENTTYPE_URL,
/// <summary>
/// Contacts data.
/// </summary>
Contacts = DBEventInfo.EVENTTYPE_CONTACTS,
/// <summary>
/// "Contact added you" event.
/// </summary>
Added = DBEventInfo.EVENTTYPE_ADDED,
/// <summary>
/// Authentication request.
/// </summary>
AuthRequest = DBEventInfo.EVENTTYPE_AUTHREQUEST,
/// <summary>
/// File.
/// </summary>
File = DBEventInfo.EVENTTYPE_FILE
}
/// <summary>
/// Event direction: incoming, outgoing.
/// </summary>
public enum HistoryItemDirection : int
{
/// <summary>
/// This is (sort of) message that has been recieved from contact.
/// </summary>
Incoming,
/// <summary>
/// This is (sort of) message that has been sent to contact.
/// </summary>
Outgoing
}
#region Data fields and properties
/// <summary>
/// Contact to whom event is assigned.
/// </summary>
public Contact Contact { get; set; }
/// <summary>
/// Type of this event.
/// </summary>
public HistoryItemType Type { get; private set; }
/// <summary>
/// Direction of this event.
/// </summary>
public HistoryItemDirection Direction { get; private set; }
/// <summary>
/// Text of message (if this event is message).
/// </summary>
public string MessageText { get; set; }
/// <summary>
/// Date and time of an event.
/// </summary>
public DateTime DateTime { get; set; }
#endregion
#region Equality stuff
/// <summary>
/// Compares this object with other. Overrides Object method.
/// </summary>
/// <param name="obj">
/// Object to be compared to.
/// </param>
/// <returns>
/// true if objects are equal.
/// </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (HistoryItem)) return false;
return Equals((HistoryItem)obj);
}
/// <summary>
/// Compares this history item with other.
/// </summary>
/// <param name="other">
/// History item to be compared to
/// </param>
/// <returns>
/// true if objects are equal.
/// </returns>
public bool Equals(HistoryItem other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Contact, Contact) &&
Equals(other.Type, Type) &&
Equals(other.MessageText, MessageText) &&
other.DateTime.Equals(DateTime);
}
/// <summary>
/// Calculates hash code for object.
/// </summary>
/// <returns>
/// Value of hash code.
/// </returns>
public override int GetHashCode()
{
unchecked
{
int result = (Contact != null ? Contact.GetHashCode() : 0);
result = (result * 397) ^ Type.GetHashCode();
result = (result * 397) ^
(MessageText != null ? MessageText.GetHashCode() : 0);
result = (result * 397) ^ DateTime.GetHashCode();
return result;
}
}
/// <summary>
/// An operator tests for equality of two objects.
/// </summary>
public static bool operator ==(HistoryItem left, HistoryItem right)
{
return Equals(left, right);
}
/// <summary>
/// An operator tests for inequality of two objects.
/// </summary>
public static bool operator !=(HistoryItem left, HistoryItem right)
{
return !Equals(left, right);
}
#endregion
/// <summary>
/// Creates new in-memory history item.
/// </summary>
/// <param name="type">
/// Type of created item.
/// </param>
/// <param name="direction">
/// Direction of created item.
/// </param>
public HistoryItem(HistoryItemType type, HistoryItemDirection direction)
{
Type = type;
Direction = direction;
}
/// <summary>
/// Creates instance of history item and loads its content from
/// database.
/// </summary>
/// <param name="contact">
/// Contact with whom history this item is associated.
/// </param>
/// <param name="hEvent">
/// Miranda event handle.
/// </param>
internal static HistoryItem Load(Contact contact,
IntPtr hEvent)
{
if (hEvent == IntPtr.Zero)
throw new ArgumentException("hEvent cannot be zero.");
// Miranda interface for freeing strings:
var mmi = MMInterface.GetMMI();
using (var pDbEventInfo = new AutoPtr(Marshal.AllocHGlobal(
Marshal.SizeOf(typeof (DBEventInfo)))))
{
var result = Plugin.m_CallService(
"DB/Event/Get",
hEvent,
pDbEventInfo);
if (result != IntPtr.Zero)
throw new DatabaseException();
var eventInfo =
(DBEventInfo)
Marshal.PtrToStructure(pDbEventInfo, typeof (DBEventInfo));
var type = (HistoryItemType)eventInfo.eventType;
var direction = (eventInfo.flags & DBEventInfo.DBEF_SENT) != 0
? HistoryItemDirection.Outgoing
: HistoryItemDirection.Incoming;
var historyItem = new HistoryItem(type, direction);
if (type == HistoryItemType.Message)
{
// Get message text:
using (var pDbEventGetText = new AutoPtr(
Marshal.AllocHGlobal(Marshal.SizeOf(
typeof (DBEventGetText)))))
{
var getText = new DBEventGetText();
getText.dbei = pDbEventInfo;
getText.datatype = Utils.DBVT_WCHAR;
Marshal.StructureToPtr(getText, pDbEventGetText, false);
var pString = Plugin.m_CallService(
"DB/Event/GetText",
IntPtr.Zero,
pDbEventGetText);
mmi.mmi_free(pString);
var message = Marshal.PtrToStringUni(pString);
historyItem.MessageText = message;
}
}
historyItem.Contact = contact;
historyItem.DateTime = new DateTime(1970, 1, 1)
.AddSeconds(eventInfo.timestamp);
return historyItem;
}
}
/// <summary>
/// Saves this history item to database for selected contact.
/// </summary>
public void Save()
{
var eventInfo = new DBEventInfo();
eventInfo.eventType = (ushort)Type;
eventInfo.flags = DBEventInfo.DBEF_SENT;
eventInfo.szModule = Contact.Protocol;
eventInfo.timestamp = (int)(DateTime -
new DateTime(1970, 1, 1)).TotalSeconds;
using (var pDbEventInfo = new AutoPtr(
Marshal.AllocHGlobal(Marshal.SizeOf(typeof (DBEventInfo)))))
{
if (MessageText != null)
{
using (var pString =
new AutoPtr(Marshal.StringToHGlobalAnsi(MessageText)))
{
eventInfo.cbBlob = (uint)MessageText.Length + 1;
eventInfo.pBlob = pString;
}
}
Marshal.StructureToPtr(eventInfo, pDbEventInfo, false);
Plugin.m_CallService(
"DB/Event/Add",
Contact.hContact,
pDbEventInfo);
}
}
}
}
|
Java
|
UTF-8
| 1,011
| 2.359375
| 2
|
[] |
no_license
|
/**
*
*/
package sk.seges.sesam.fork.shared.domain;
import java.io.Serializable;
/**
* @author ladislav.gazo
*/
public class RemoteProcessResponse implements Serializable {
private static final long serialVersionUID = -1712521545357800632L;
private String output;
private String error;
private int exitStatus;
public RemoteProcessResponse(String output, String error, int exitStatus) {
super();
this.output = output;
this.error = error;
this.exitStatus = exitStatus;
}
public String getOutput() {
return output;
}
public void setOutput(String output) {
this.output = output;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public int getExitStatus() {
return exitStatus;
}
public void setExitStatus(int exitStatus) {
this.exitStatus = exitStatus;
}
@Override
public String toString() {
return "RemoteProcessResponse [output=" + output + ", error=" + error
+ ", exitStatus=" + exitStatus + "]";
}
}
|
C
|
UTF-8
| 229
| 3.625
| 4
|
[] |
no_license
|
#include <stdio.h>
void main(void)
{
int count, sum, day;
count = 0;
sum = 0;
printf("Enter a day:");
scanf("%d", &day);
while (count++ < day)
{
sum = sum + count * count;
}
printf("%d day = %d\n", day, sum);
}
|
Python
|
UTF-8
| 1,018
| 3.46875
| 3
|
[] |
no_license
|
from Functions import *
import random as rnd
def main():
file_name = "or.txt"
training_x, training_y, m, num_atrib = load_data(file_name)
mu = 0.1
num_iterations = 50
umbral = lambda x: 0.0 if x < 0.0 else 1.0
# pesos iniciales aleatorios
rnd.seed(1000)
#w = [random.uniform(-1,1) for i in range(num_atrib)]
w = [rnd.random()] * num_atrib
#repetir hasta que se cumpla la condición de fin
for i in range(num_iterations):
# para cada x,y del conjunto de entrenamiento
for x, y in zip(training_x, training_y):
# calcular o
product = dot(w,x)
o = umbral(product)
# para cada peso w_i hacer: w_i ← w_i + η(y − o)x_i
for j in range(num_atrib):
w[j] += mu * (y - o) * x[j]
print("Los pesos son:", w)
x = [-1.0,0.0,0.0]
product = dot(w,x)
output = umbral(product)
print("Para la entrada ", x," la salida es ", output)
if __name__ == '__main__':
main()
|
Java
|
UTF-8
| 352
| 2.078125
| 2
|
[] |
no_license
|
package com.one.model;
import org.springframework.stereotype.Component;
@Component
public class Product {
private Integer prdId;
public Integer getPrdId() {
return prdId;
}
public void setPrdId(Integer prdId) {
this.prdId = prdId;
}
@Override
public String toString() {
return "Product [prdId=" + prdId + "]";
}
}
|
Markdown
|
UTF-8
| 7,835
| 2.859375
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
## Raw callee
WampSharp provides a lower level api that allows to deal with rpc operations as they're sent/received, which is called Raw callee.
Actually, the reflection based callee api is built above the Raw callee api.
In order to use the raw callee api, implement IWampRpcOperation. A IWampFormatter is passed to your methods in order to allow you to deserialize the method parameters. In order to return a result or an error, call the corresponding caller method.
After that, register it using Register method of RpcOperationCatalog property of IWampRealm/IWampRealmProxy interfaces.
### Registration samples
#### Client side
```csharp
internal class Program
{
public static void Main(string[] args)
{
const string location = "ws://127.0.0.1:8080/";
DefaultWampChannelFactory channelFactory = new DefaultWampChannelFactory();
IWampChannel channel = channelFactory.CreateJsonChannel(location, "realm1");
Task openTask = channel.Open();
// await openTask;
openTask.Wait();
ArgLenOperation operation = new ArgLenOperation();
IWampRealmProxy realm = channel.RealmProxy;
RegisterOptions registerOptions = new RegisterOptions();
Task<IAsyncDisposable> registrationTask = realm.RpcCatalog.Register(operation, registerOptions);
// await registrationTask;
registrationTask.Wait();
Console.ReadLine();
}
}
```
#### Router side
```csharp
internal class Program
{
public static void Main(string[] args)
{
const string location = "ws://127.0.0.1:8080/";
using (IWampHost host = new DefaultWampHost(location))
{
ArgLenOperation operation = new ArgLenOperation();
IWampHostedRealm realm = host.RealmContainer.GetRealmByName("realm1");
Task<IAsyncDisposable> registrationTask = realm.Services.RegisterCallee(operation);
// await registrationTask;
registrationTask.Wait();
host.Open();
Console.WriteLine("Server is running on " + location);
Console.ReadLine();
}
}
}
```
### IWampRpcOperation implementation sample
```csharp
public class Add2Operation : IWampRpcOperation
{
public string Procedure
{
get
{
return "com.arguments.add2";
}
}
public void Invoke<TMessage>(IWampRawRpcOperationRouterCallback caller, IWampFormatter<TMessage> formatter, InvocationDetails details)
{
Dictionary<string, object> dummyDetails = new Dictionary<string, object>();
caller.Error(WampObjectFormatter.Value, dummyDetails, "wamp.error.runtime_error",
new object[] { "Expected parameters" });
}
public void Invoke<TMessage>(IWampRawRpcOperationRouterCallback caller, IWampFormatter<TMessage> formatter, InvocationDetails details,
TMessage[] arguments)
{
InnerInvoke(caller, formatter, arguments);
}
public void Invoke<TMessage>(IWampRawRpcOperationRouterCallback caller, IWampFormatter<TMessage> formatter, InvocationDetails details,
TMessage[] arguments, IDictionary<string, TMessage> argumentsKeywords)
{
InnerInvoke(caller, formatter, arguments);
}
private static void InnerInvoke<TMessage>(IWampRawRpcOperationRouterCallback caller, IWampFormatter<TMessage> formatter,
TMessage[] arguments)
{
int x = formatter.Deserialize<int>(arguments[0]);
int y = formatter.Deserialize<int>(arguments[1]);
int result = x + y;
YieldOptions dummyDetails = new YieldOptions();
caller.Result(WampObjectFormatter.Value, dummyDetails, new object[] { result });
}
}
```
### SyncLocalRpcOperation and AsyncLocalRpcOperation.
WampSharp defines some base-classes that make it easier to implement IWampRpcOperation, named SyncLocalRpcOperation and AsyncLocalRpcOperation.
In these classes, we define the parameters we expect to receive and let WampSharp deserialize them for us.
#### Static parameters example
```csharp
public class Add2Operation : SyncLocalRpcOperation
{
private readonly RpcParameter[] mParameters = new RpcParameter[]
{
new RpcParameter(name: "x", type: typeof (int), position: 0),
new RpcParameter(name: "y", type: typeof (int), position: 1)
};
public Add2Operation()
: base("com.arguments.add2")
{
}
public override RpcParameter[] Parameters
{
get
{
return mParameters;
}
}
public override bool HasResult
{
get
{
return true;
}
}
public override CollectionResultTreatment CollectionResultTreatment
{
get
{
return CollectionResultTreatment.SingleValue;
}
}
protected override object InvokeSync<TMessage>(IWampRawRpcOperationRouterCallback caller,
IWampFormatter<TMessage> formatter,
InvocationDetails details,
TMessage[] arguments,
IDictionary<string, TMessage> argumentsKeywords,
out IDictionary<string, object> outputs)
{
object[] parameters = UnpackParameters(formatter, arguments, argumentsKeywords);
int x = (int) parameters[0];
int y = (int) parameters[1];
outputs = null;
return (x + y);
}
}
```
This handles lookups for parameters named x and y (or positioned at 0, 1), and handles exception throw if not both present.
Note that you can return an array and return CollectionResultTreatment.Multivalued from CollectionResultTreatment if you want to return an array with more than one item as the ARGUMENTS of the YIELD/RESULT message.
Note that you can also set outputs to a dictionary with keywords arguments parameters that will be sent as ARGUMENTSKWS of the YIELD/RETURN message.
#### Dynamic parameters example
```csharp
public class ArgLenOperation : SyncLocalRpcOperation
{
private readonly RpcParameter[] mParameters = new RpcParameter[0];
public ArgLenOperation()
: base("com.arguments.arglen")
{
}
protected override object InvokeSync<TMessage>(IWampRawRpcOperationRouterCallback caller,
IWampFormatter<TMessage> formatter,
InvocationDetails details,
TMessage[] arguments,
IDictionary<string, TMessage> argumentsKeywords,
out IDictionary<string, object> outputs)
{
outputs = null;
int argumentsLength = 0;
if (arguments != null)
{
argumentsLength = arguments.Length;
}
int argumentKeyWordsLength = 0;
if (argumentsKeywords != null)
{
argumentKeyWordsLength = argumentsKeywords.Count;
}
return new int[] { argumentsLength, argumentKeyWordsLength };
}
public override RpcParameter[] Parameters
{
get { return mParameters; }
}
public override bool HasResult
{
get { return true; }
}
public override CollectionResultTreatment CollectionResultTreatment
{
get { return CollectionResultTreatment.Multivalued; }
}
}
```
>Note: This sample is based on [this](https://github.com/tavendo/AutobahnPython/tree/master/examples/twisted/wamp/rpc/arguments) AutobahnJS sample
|
Swift
|
UTF-8
| 481
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// TTSegmentedControlBounceOptions.swift
// TTSegmentedControl
//
// Created by Igor Dumitru on 27.01.2023.
//
import UIKit
public struct TTSegmentedControlBounceOptions {
public let springDamping: CGFloat
public let springInitialVelocity: CGFloat
public init(
springDamping: CGFloat = 0.7,
springInitialVelocity: CGFloat = 0.2
) {
self.springDamping = springDamping
self.springInitialVelocity = springInitialVelocity
}
}
|
TypeScript
|
UTF-8
| 2,376
| 4.09375
| 4
|
[] |
no_license
|
// 1. 通过关键字 class 定义
// class Person{
// name:string; //属性 前面省略了public关键词
// constructor(n:string){ // 构造函数, 实例化类的时候触发的方法
// this.name = n;
// }
// run():void{
// alert(this.name);
// }
// getName():string{
// return this.name;
// }
// setName(name:string):void{
// this.name = name;
// }
// }
// var p = new Person('张三');
// p.run();
// alert(p.getName());
// p.setName('lizi');
// alert(p.getName());
// 2. ts中实现继承 extends, super
class Person{
name:string;
constructor(name:string){
this.name = name;
}
run():string{
return `${this.name}在运动`;
}
}
var p = new Person('王五');
console.log(p.run());
// Web 继承 Person类
class Web extends Person{
constructor(name:string){
super(name); // 初始化父类的构造函数
}
work():void{
console.log(`${this.name}在工作`)
}
run():string{
return '我是子类web中重构的run方法'
}
}
var w = new Web('李四');
console.log(w.run());
w.work();
// 3. 类里面的修饰符, ts里面定义属性的时候给我们提供了三种修饰符
// public, 在类里面, 子类, 类外面都可以访问
// protected, 在类里面和子类里面可以访问, 在类外部没法访问
// private, 在类里面可以访问, 子类和类外部没法访问
// 属性如果不加修饰符, 默认为public
class Person2{
public name:string;
protected sex:boolean;
private age:number;
constructor(name:string, sex:boolean, age:number){
this.name = name;
this.sex = sex;
this.age = age;
}
getInfo():string{
return `姓名:${this.name}, 性别:${this.sex}, 年龄:${this.age}`;
}
}
var p2 = new Person2('zz', true, 28);
console.log(p2.getInfo());
class Web2 extends Person2{
constructor(name:string, sex:boolean, age:number){
super(name, sex, age);
}
work():void{
console.log(`子类中姓名:${this.name}`);
console.log(`子类中性别:${this.sex}`);
// console.log(`子类中年龄:${this.age}`); // age, private 子类中无法访问
}
}
var w2 = new Web2('ww', false, 20);
w2.getInfo();
w2.work();
// console.log(w2.sex); // protected 外部访问不了, 报错
|
C
|
UTF-8
| 245
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
#define DIM 10
#include <stdio.h>
int main() {
int valor[DIM], num, i=0;
scanf("%d", &num);
for (i=0; i < DIM; i++) {
valor[i] = num;
printf("N[%d] = %d\n", i, valor[i]);
num += num;
}
return 0;
}
|
Markdown
|
UTF-8
| 3,489
| 3.140625
| 3
|
[] |
no_license
|
# Orbital2020---ClassroomCompanion
ClassroomCompanion is an educational mobile game to allow lower secondary students to learn anywhere and anytime in a fun and engaging manner. This is a project for Orbital2020 and I worked on it with my partner, Chloe.
## Overview of Project
ClassroomCompanion is a 2D educational mobile game that allows players (lower-secondary students) to learn on-the-go and have their very own virtual room and a virtual pet. The mobile game acts as an educational resource as there would be daily bite-sized quizzes for students to attempt or a collection of summaries of the topics taught in class for the students to access. The game would make learning interesting and engaging for the players because their furry companions will be accompanying and motivating them along the way. By completing the daily quizzes, players can unlock the mini-game feature, where they can then play a mini-game to earn in-game money and pet experience. In-game money can be used to buy items to decorate their room as they like, and pet experience will enable their pets to level up and acquire new tricks.
## Motivation
When students learn concepts in classroom settings, there might be a lack of opportunities for them to directly apply what they have learnt quickly in order to solidify their understanding. Since studies have shown that understanding of concepts are better retained if students revise them within a 24-hour period after being taught, the traditional weekly school homework might not be the most effective way of learning. Furthermore, doing homework is widely regarded as a mundane activity, hence students often find themselves procrastinating on them or not completing them at all.
Many students also tend to struggle to focus in class and might miss out crucial information during lessons. While textbooks help explain the topics in a detailed manner, students may not be able to identify the main points and summarise a topic in an effective manner.
So, why do students have to find themselves being forced to complete uninteresting and unsatisfying tasks when these tasks could be turned into a fun, rewarding and appealing method of learning and applying concepts taught in class?
## Aim
We aim to come up with a virtual mobile platform for lower-secondary students to attempt questions related to the concepts taught in class, via the means of daily bite-sized quizzes, anywhere and anytime on their smartphone. Students would also be able to revise with the summaries of the various topics accessible on this platform. To appeal to students, the platform would come in the form of a game and would make use of a reward system to provide instant gratification.
## Awards
ClassroomCompanion was awarded Artemis Level for Orbital2020, the highest attainable level possible!
### The Game
Try out the game on an Android phone! APK File: https://drive.google.com/drive/folders/1uthK5jg5emcXINII-U5zL_bTpbL8KwSJ?usp=sharing
### Poster
<img src="https://imgur.com/bEV0rYV.jpg" width="480" height="650"/>
[Poster's Link](https://imgur.com/bEV0rY)
### Project's Trailer
https://youtu.be/KksSw3pkGGI
### Project's Demo
https://youtu.be/Oh-d-NiGHdE
### Project's README
https://docs.google.com/document/d/1QBq_rM6RhQcd412Appb2bYSi_EsQtZH1S6iZjKuhnUM/edit?usp=sharing
### Others
Full unity project in 'Orbital v1.0'
ClassroomCompanion is created on Unity. We had no prior Unity knowledge and had picked it up over our year 1 summer break.
|
PHP
|
UTF-8
| 814
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Wcms\Flywheel;
class Repository extends \JamesMoss\Flywheel\Repository
{
/**
* Get an array containing the path of all files in this repository
*
* @return array An array, item is a file
*/
public function getAllFiles()
{
$ext = $this->formatter->getFileExtension();
$files = glob($this->path . DIRECTORY_SEPARATOR . '*.' . $ext);
return $files;
}
/**
* Get an array containing the id of all files in this repository
*
* @return array An array, item is a id
*/
public function getAllIds()
{
$ext = $this->formatter->getFileExtension();
return array_map(function($path) use ($ext) {
return $this->getIdFromPath($path, $ext);
}, $this->getAllFiles());
}
}
|
TypeScript
|
UTF-8
| 377
| 2.53125
| 3
|
[] |
no_license
|
// third party imports
import { Guid } from 'guid-typescript';
// local imports
import { IModel } from "./models.index";
export class Question implements IModel {
id: string;
text: string;
answer: string;
constructor(id: string, text: string, answer: string) {
this.id = !id ? Guid.create().toString() : id;
this.answer = answer;
this.text = text;
}
}
|
Swift
|
UTF-8
| 591
| 2.578125
| 3
|
[] |
no_license
|
//
// Response.swift
// Json example
//
// Created by tawanda chandiwana on 2021/07/27.
//
import Foundation
import UIKit
struct Response: Codable {
let id = UUID()
let results: MyResults
let status: String = ""
}
struct MyResults {
let sunrise: String
let sunset: String
let solar_noon: String
let day_length: Int
let civil_twighlight_begin: String
let civil_twighlight_end: String
let naughtical_twighlight_begin: String
let naughtical_twighlight_end: String
let astronomical_twighlight_begin: String
let astronomical_twighlight_end: String
}
|
Java
|
UTF-8
| 2,316
| 2.28125
| 2
|
[] |
no_license
|
import io.restassured.RestAssured;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
public class LoggingResponseDetails extends TestBase{
@Order(1)
@Test
public void printResponseHeaders()
{
System.out.println("-------------Printing Response Headers---------------");
RestAssured.given()
.when()
.get(RestAssured.baseURI+RestAssured.port+RestAssured.basePath+"/list")
.then()
.log()
.headers()
.statusCode(200);
}
@Order(2)
@Test
public void printResponseStatus()
{
System.out.println("-------------Printing Response Status---------------");
RestAssured.given()
.queryParams("firstName","Vernon","programme","Financial Analysis")
.when()
.get(RestAssured.baseURI+RestAssured.port+RestAssured.basePath+"/list")
.then()
.log()
.status()
.statusCode(200);
}
@Order(3)
@Test
public void printResponseBody()
{
System.out.println("-------------Printing Response Body---------------");
RestAssured.given()
.pathParam("id",1)
.when()
.get(RestAssured.baseURI+RestAssured.port+RestAssured.basePath+"/{id}")
.then()
.log()
.body()
.statusCode(200);
}
@Order(4)
@Test
public void printAResponseWhenValidationFails()
{
System.out.println("-------------Printing Response---------------");
RestAssured.given()
.queryParams("programme","Financial Analysis","limit",1)
.when()
.get(RestAssured.baseURI+RestAssured.port+RestAssured.basePath+"/list")
.then()
.log()
.ifValidationFails()
.statusCode(201);
}
@Order(5)
@Test
public void printAResponseIfError()
{
RestAssured.given()
.pathParam("id",-1)
.when()
.get(RestAssured.baseURI+RestAssured.port+RestAssured.basePath+"/{id}")
.then()
.log()
.ifError();
}
}
|
JavaScript
|
UTF-8
| 569
| 3.96875
| 4
|
[] |
no_license
|
var sayHi = function(name)
{
return `hi ${name}`
}
// if only one param and one line in body
var sayHi = name => `hi ${name}`
// if no params
var sayHi = () => `hi kang`
var sayHi = (firstname, lastname) =>
{
var number = 1 + 1
return `hi ${firstname} ${lastname}`
}
const languages = ['ruby', 'php', 'js', 'es6']
// es5
const languagesUpcase = languages.map(function(language)
{
return language.toUpperCase()
})
console.log(languagesUpcase)
// es6
const languagesUpcased = languages.map(language => language.toUpperCase())
console.log(languagesUpcased);
|
JavaScript
|
UTF-8
| 1,110
| 2.5625
| 3
|
[] |
no_license
|
var mongoose = require('mongoose');
var Question = mongoose.model('Question');
module.exports = {
getAll: function(req, res) {
console.log('Get all was called');
Question.find({}, function(err, questions) {
console.log('Looking for stuff!');
if(err) {
console.log('Error retrieving data');
return handleError(err);
} else {
console.log(questions);
res.status(200).json({data: questions});
}
});
},
postNew: function(req, res) {
console.log('trying to find the data' + req.formData);
var question = new Question({
body: req.body.body,
description: req.body.description
// description: req.body.description
});
question.save(function(err) {
if(err) {
console.log('Something went wrong while trying to add this user: \n\n' + err);
} else {
console.log('Question added to DB!');
}
});
res.redirect('/');
}
};
|
Markdown
|
UTF-8
| 6,506
| 3.421875
| 3
|
[] |
no_license
|
二六
“那为什么他们会没办法?”王振也搞不懂小邪所言何意。
小邪憋住笑意道:“有人——有人专门负责吃他们做的菜,他们当然没办法啦!”
小顺子和皇上都露出笑容,那人不就是小邪?
王振厉道:“谁那么大的胆子,敢专门负责吃菜?”
小邪摇头道:“不晓得,不过他,吃得好凶,能留下这几片,已是万幸的了!”
王振瞄向桌上那几两不到的珍馐,亦觉想笑——果真是万幸?
小邪指着去了五爪的螃蟹,道:“那螃蟹,好像一半是空的!”
皇上已忍不住笑出声音,道:“这人,实在太大胆了——凉鞋,你可知道他是谁?朕要斩了他!”
小邪睨眼道:“回皇上,奴才不知他是谁,不过奴才想那人还会去吃,皇上只要等上三天,一定有所收获!”
“要那么久?朕觉得他随时部会去愉吃惊”
小邪道:“既是随时都能去吃,就不能算是偷吃了!”
王振喝道:“凉鞋,你也太大胆,竟敢将此呈给皇上,你不要命了!”
小邪面有难色道:“公公您不知,要是奴才不准时送上来,受连累的恐怕就更多人了!”
“你端此不成样的早膳,无端冒渎皇上,仍是死罪难免!”王振说话口气已放软。
小邪哭丧着脸,道:“奴才只能遵照皇上旨意将菜弄来,以免皇上吃不到早餐,并无冒渎皇上之意,至于生死之间,奴才早就想通,死就死吧,能为皇上而死,奴才并不害怕!”
王振突然冷狡目光直盯小邪,似乎想看穿他心意,亦似在盘算心中决定,他冷道:“你自知必死,所以才出言不逊?”
小邪苦笑道:“该死就要死,总该把事情说清楚,否则害了别人更不好,公公请见谅!”
皇上听他能为自已死,虽然明知是开玩笑的话,心中仍受用无穷——真以为已找到了知己。他道:“你可知那人如何潜入御膳房?”
小邪道:“奴才不知,但奴才和小顺子一起守夜,突然飞入一位黑衣如魔鬼的脸孔
好像是戴了面具,对我和小顺子冷笑,然后就点了我们两人穴道,开始吃起东西,他还弄了一团糟,然后就走了。”
王振似乎也想饶过小邪,洪手道:“皇上,那人可能是刺客,虽然凉鞋守膳房,但根本不是其对手,而此时凉鞋明知会死,竟不愿连累他人,不逃脱,此忠心,实属难得,祈皇上能赦其死罪 ,让他仍有机会为皇上效忠。”
“先生说得极是!”皇上没想到他会替小邪说话,这倒省了自已不少嘛烦。
道,“如何处置他,就由先生发落好了!”
王振转向小邪,冷道:“还不快谢皇上隆恩!”
小邪气忙下跪,膜拜,甚而激动道:“谢皇上大赦之恩,奴才鞠躬尽瘁,以报
以报骰子隆恩!”
皇上冷笑道:“起来吧——只要你对朕忠心,朕自会奖赏你!”
“谢皇上!”小邪再拜三拜,方自站起。
王振冷道:“你方才所说什么‘骰子隆恩’?是指何意?'小邪闻言,急忙道:“是‘来世隆恩’奴才太激动,所以说错了,奴才来生也要报答皇上恩惠!”
皇上闻言已哈哈直笑:“好,很好!”一方面是笑小邪得“骰子隆恩”,另一方面却以认来世能相互为友,何尝不是一大乐事。
王振通:“死罪已免,但终究有错,就罚你三月不得请薪,你可心服?”
此惩罚不重,但也不轻,因为太监本已非正常人,最喜爱者,乃归于金银珠宝,被扣薪资,对太监来说,较为吃重,尤其又是年轻太监。
小邪本就没薪水,扣个三十年也无关痛痒,当下连连道谢。
王振道:“好好给我呆在御膳房,我随时会去找你!”他已有心将小邪收为心腹。
小邪又是一阵告谢,应“是”。
王振转向皇上,拱手道:“皇上,事出突然,不妨先进食小许,以能温饱,再叫御膳房重新作菜,如何?”
“也好,先生一起用吧!”
“奴才不敢!”
皇上只好自行喝碗八宝粥,已起驾离去,临行还送了小邪一个会心微笑。王振仍是一番告诫的话,方自随皇上进入天机宫,锦衣卫也随之撤去。
小顺子这才嘘口气,叫道:“好险——凉鞋你的命是捡回来的!”
小邪瞅眼睨向他,道:“不是捡回来,而是他们根本要不去!废话少说!赶快收拾收拾,找那常公公,卡啦(赌骰子)去!”
小顺子实佩服得五体投地,心想要是有小邪一半运气就好了。三两手已将餐具收拾妥善,道:“现在白天,他们可能不玩——”
“那有好赌的人会选时间,走就走!”小邪道,“别忘了我的薪水被扣了,不捞一点回来,怎么过?”
小顺子也很想看他是如何赢了“龙袍”,道:“好吧——我带你去,他们赌不赌,就看你自己了。”
小邪突然想到了什么,问:“你知道王公公的住处在哪里?”“你想干什么?”小顺子惊愕问。
小邪道:“没啦!他救我一命,我总得送点礼物去孝敬他!”
“哦——看你还满懂规矩的?”小顺子道,“在丹阳宫左侧,黄石地面的宫殿,王统领也住在他隔壁。”
小邪频频点头,道:“要送,两人一起送 !”邪邪一笑,道,“要是知道他们的秘密藏宝库就好了——我将礼物偷偷放在宝库门口,王公公一定会大吃一这效果一定比亲自送给他要好得多!”
小顺子那有小邪那般诈?真以为小邪是为了送礼,立时道:“你也帮我送一份如何?听他们说,要是王公公收了礼,马上就可飞黄腾后达了!”
小邪笑在心里,道:“好——你的礼物,我也替你准备,保证王公公不会失望!”
小顺子道:“真实地方我不清楚,但听他们时常说‘要是有王公公寝宫财宝的一半就心甘情愿了’,我想王公公宝藏可能在寝官里。”
小邪不时拍打他肩头,笑道:“有你的——礼物就送到他寝宫好了!怎么走?”
小顺子很快将地点告诉他,甚至守卫在何处,都详细说清。
|
PHP
|
UTF-8
| 2,158
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* This file is part of the Fakerino package.
*
* (c) Nicola Pietroluongo <nik.longstone@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Fakerino\DataSource\File;
use Fakerino\DataSource\File\Exception\FileEmptyException;
use Fakerino\DataSource\File\Exception\FileLineNotFoundException;
use Fakerino\DataSource\File\Exception\FileNotFoundException;
/**
* Class File
*
* @author Nicola Pietroluongo <nik.longstone@gmail.com>
*/
class File extends \SplFileInfo
{
/**
* Constructor
*
* @param string $path
*
* @throws FileNotFoundException
*/
public function __construct($path)
{
if (!file_exists($path)) {
throw new FileNotFoundException($path);
}
parent::__construct($path);
}
/**
* @return string
*/
public function getFileName()
{
return basename($this->getRealPath());
}
/**
* @return mixed
*/
public function getMimeType()
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
return finfo_file($finfo, $this->getRealPath());
}
/**
* @return string
*/
public function getExtension()
{
return pathinfo($this->getBasename(), PATHINFO_EXTENSION);
}
/**
* @return string
* @throws Exception\FileEmptyException
*/
public function getContent()
{
if ($content = file_get_contents($this->getRealPath())) {
return $content;
} else {
throw new FileEmptyException($this->getRealPath());
}
}
/**
* @param int $lineNumber
*
* @return string
* @throws Exception\FileLineNotFoundException
*/
public function readLine($lineNumber)
{
$content = $this->getContent();
if (count($content) > $lineNumber) {
return $content[$lineNumber];
} else {
throw new FileLineNotFoundException($this->getRealPath(), $lineNumber);
}
}
/**
* @return string
*/
public function getPath()
{
return $this->getRealPath();
}
}
|
C++
|
UTF-8
| 1,110
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
#ifndef CONST_SKIP_ITERATOR_HPP
#define CONST_SKIP_ITERATOR_HPP
#include <iterator>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/assert.hpp>
namespace Stg
{
template<typename _InputIterator,
typename __T = typename std::iterator_traits<_InputIterator>::value_type>
struct ConstSkipIterator : public boost::iterator_facade<ConstSkipIterator<_InputIterator>, __T const, boost::forward_traversal_tag>
{
using It = _InputIterator;
constexpr ConstSkipIterator(It i) : _i(i), _s(SIZE_MAX) { }
ConstSkipIterator(size_t s, It i) : _i(i), _s(s)
{
BOOST_ASSERT_MSG(_s, "Infinite cycle detected");
}
void increment()
{
std::advance(_i, _s);
}
__T const& dereference() const
{
return *_i;
}
bool equal(ConstSkipIterator o) const
{
if(std::distance(_i, o._i) < 0) return true;
return _i == o._i;
}
private:
size_t _s;
It _i;
};
} // namespace Stg
#endif //CONST_SKIP_ITERATOR_HPP
|
Python
|
UTF-8
| 659
| 2.640625
| 3
|
[] |
no_license
|
from utilz.const import limit as LIMIT
from hw3.search import read_index
from math import log
def compute_idf():
documents_number = LIMIT
token_document_map = dict()
index = read_index("../hw3/index.txt")
for element, pages in index.items():
token_document_map[element] = round(log(documents_number / len(pages)), 6)
return token_document_map
def write_idf(idf_map):
file = open("idf.txt", "w")
for word, idf in idf_map.items():
file_string = word + " " + str(idf)
file_string += "\n"
file.write(file_string)
file.close()
if __name__ == '__main__':
tf = compute_idf()
write_idf(tf)
|
Java
|
UTF-8
| 4,410
| 3.234375
| 3
|
[] |
no_license
|
package inf112.app.board;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import inf112.app.player.Direction;
import inf112.app.player.Position;
import java.util.Map;
public class BoardObjects {
private final Map<String, TiledMapTileLayer> board;
public BoardObjects(Map<String, TiledMapTileLayer> board) {
this.board = board;
}
/**
* Returns true if the tile has a wall.
*
* @param pos position of the player
* @param newPos the position the player would have if he moves
* @param dir direction of the player
* @return true or false depending on if there is a wall or not
*/
public boolean tileHasWall(Position pos, Position newPos, Direction dir) {
if (board.get("wall" + dir.getName())
.getCell(pos.getX(), pos.getY()) != null)
return true;
return board.get("wall" + dir.reverseDirection().getName())
.getCell(newPos.getX(), newPos.getY()) != null;
}
/**
* Returns true if the tile has an actor
*
* @param pos position of the actor
* @return true or false
*/
public boolean tileHasActor(Position pos) {
return board.get("actor").getCell(pos.getX(), pos.getY()) != null;
}
/**
* Returns true if the tile has a flag.
*
* @param pos position of the player
* @return true or false
*/
public boolean tileHasFlag(Position pos) {
return board.get("flag").getCell(pos.getX(), pos.getY()) != null;
}
/**
* Returns true if the tile has a spawn.
*
* @param pos position of the player
* @return true or false
*/
public boolean tileHasSpawn(Position pos) {
return board.get("spawn").getCell(pos.getX(), pos.getY()) != null;
}
/**
* Returns true if the tile has a wheel.
*
* @param pos position of the player
* @param dir direction of the player
* @return true or false
*/
public boolean tileHasTurnWheel(Position pos, Direction dir) {
return board.get("turnwheel").getCell(pos.getX(), pos.getY()) != null;
}
/**
* Returns true if the tile is a hole.
*
* @param pos position of the player
* @return true or false
*/
public boolean tileHasHole(Position pos) {
return board.get("hole").getCell(pos.getX(), pos.getY()) != null;
}
/**
* Checks if the current tile has a laser.
*
* @param pos Position of the player
* @return true or false
*/
public boolean tileHasLaser(Position pos) {
return board.get("laser").getCell(pos.getX(), pos.getY()) != null;
}
/**
* Checks if the current tile has a repair kit.
*
* @param pos position of the player
* @return boolean true or false
*/
public boolean tileHasRepair(Position pos) {
return board.get("repair kit").getCell(pos.getX(), pos.getY()) != null;
}
/**
* Checks if the current tile has a conveyor belt.
*
* @param pos position of the player
* @return boolean true or false
*/
public boolean hasConveyor(Position pos) {
for (Direction dir : Direction.values()) { // Checks for a conveyor tile in all directions
TiledMapTileLayer.Cell currentCell = board
.get("conveyor" + dir.getName())
.getCell(pos.getX(), pos.getY());
if (currentCell != null)
return true;
}
return false;
}
/**
* Checks the direction of the conveyor belt
*
* @param pos position of the player
* @return direction of the conveyor
*/
public Direction conveyorDirection(Position pos) {
for (Direction dir : Direction.values()) { // Checks for a conveyor tile in all directions
TiledMapTileLayer.Cell currentCell = board
.get("conveyor" + dir.getName())
.getCell(pos.getX(), pos.getY());
if (currentCell != null)
return dir;
}
return null;
}
/**
* Checks if the current tile has a express conveyor belt.
*
* @param pos position of the player
* @return boolean true or false
*/
public boolean hasExpressConveyor(Position pos) {
return board.get("expressconveyor").getCell(pos.getX(), pos.getY()) != null;
}
}
|
PHP
|
UTF-8
| 2,201
| 3.15625
| 3
|
[] |
no_license
|
<?php
/**
* FTP client class
*
* @package LSF
* @version $Id$
* @copyright 2011
*/
class LSF_Utils_FTP_Client
{
private
$_stream;
public function __construct()
{
}
/**
* Connect and login to an ftp server
*
* @param string $host
* @param string $user
* @param string $password
* @param int $port
* @param int $timeout
* @throws LSF_Exception_FTP
*
* @return void
*/
public function connect($host, $user, $password, $port=21, $timeout=90)
{
$this->_stream = ftp_connect(LSF_Config::get('ftp_host'));
if (!$this->_stream) {
throw new LSF_Exception_FTP('Unable to connect server');
}
if (!ftp_login($this->_stream, $user, $password)) {
throw new LSF_Exception_FTP('Login failed');
}
}
/**
* Disconnect from the ftp server
*/
public function disconnect()
{
if ($this->_stream) {
ftp_close($this->_stream);
}
}
/**
* Changes the current directory
*
* @param string $dir
* @return bool
*/
public function cd($dir)
{
$return = ftp_chdir($this->_stream, $dir);
if (!$return) {
throw new LSF_Exception_FTP('Unable to change dir');
}
return $return;
}
/**
* Returns the current directory
*
* @return string
*/
public function pwd($dir)
{
return ftp_pwd($this->_stream);
}
/**
* Gets an array of file names in the current dir
*
* @param string $directory
* @return array
*/
public function ls($directory=".")
{
return ftp_nlist($this->_stream, $directory);
}
/**
* Upload a file to the server
*
* @param string $remoteFileName
* @param string $localFileName
* @param int $mode
*/
public function upload($remoteFileName, $localFileName, $mode=FTP_BINARY)
{
$return = false;
if (file_exists($localFileName))
{
$file = fopen($localFileName, 'r');
$return = ftp_fput($this->_stream, $remoteFileName, $file, $mode);
fclose($file);
}
return $return;
}
/**
* Gets a filesize
*
* @param string $fileName
* @return int
*/
public function size($fileName)
{
return ftp_size($this->_stream, $fileName);
}
/**
* Close the steam if left open
*/
public function __destruct()
{
$this->disconnect();
}
}
|
TypeScript
|
UTF-8
| 1,053
| 2.53125
| 3
|
[] |
no_license
|
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import {AuthService} from '../services/auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuardGuard implements CanActivate {
constructor(private router: Router, private authService: AuthService) {}
/**
*
* @param next
* @param state
* @returns {boolean}
*/
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
let isLogged: boolean = this.authService.isLogged();
if (!isLogged) {
this.router.navigate(['login']);
return false;
}
return isLogged;
}
/**
* On child route activated
*
* @returns {boolean}
*/
public canActivateChild(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.canActivate(next, state);
}
}
|
C++
|
UTF-8
| 637
| 2.671875
| 3
|
[] |
no_license
|
/*************************************************************************
> File Name: 174.cpp
> Author: liqiang
> Mail: 1398690148@163.com
> Created Time: 2019年07月31日 星期三 13时49分38秒
************************************************************************/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main() {
string str;
char c = 32;
cin >> [^\n]str;
cout << str.length() << endl;
for (int i = 0; str[i]; i++) {
int pos = str.find(c);
cout << "i: "<< pos << endl;
if(pos == -1) break;
str.replace(pos - 1, pos, "%");
}
cout << str << endl;
return 0;
}
|
Python
|
UTF-8
| 3,942
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
# Postgres
import pandas as pd
import psycopg2
import sqlalchemy
import matplotlib as plt
from sqlalchemy import create_engine
# Postgres username, password, and database name
POSTGRES_ADDRESS = 'db.panoply.io' ## INSERT YOUR DB ADDRESS IF IT'S NOT ON PANOPLY
POSTGRES_PORT = '5439'
POSTGRES_USERNAME = 'username' ## CHANGE THIS TO YOUR PANOPLY/POSTGRES USERNAME
POSTGRES_PASSWORD = '*****' ## CHANGE THIS TO YOUR PANOPLY/
POSTGRES_DBNAME = 'database' ## CHANGE THIS TO YOUR DATABASE NAME
# A long string that contains the necessary Postgres login information
postgres_str = ('postgresql://{username}:{password}@{ipaddress}:{port}/{dbname}'.format(username=POSTGRES_USERNAME,
password=POSTGRES_PASSWORD,
ipaddress=POSTGRES_ADDRESS,
port=POSTGRES_PORT,
dbname=POSTGRES_DBNAME))
# Create the connection
cnx = create_engine(postgres_str)
#Read
pd.read_sql_query('''SELECT * FROM pokemon LIMIT 5;''', cnx)
poke_weights = pd.read_sql_query('''SELECT _pk as pokemon, weight_kg as weight FROM pokemon''', cnx)
poke_weights.head()
{
"database": "db_name",
"schema": "schema_name",
"user": "user_name",
"host": "host_url",
"port": "port_num",
"passw": "user_password"
}
import json
with open('config.json') as f:
conf = json.load(f)
conn_str = "host={} dbname={} user={} password={}".format(host, database, user, passw)
conn = psycopg2.connect(conn_str)
import pandas as pd
df = pd.read_sql('select * from table_name', con=conn)
df = pd.DataFrame()
for chunk in pd.read_sql('select * from table_name', con=conn, chunksize=5000):
df = df.append(chunk)
import psycopg2 as pg
import pandas.io.sql as psql
conn = pg.connect(database="abcd",user="postgres", password="xxxx")
df = pd.read_sql('SELECT * FROM "xyz"', conn)
df.head()
#MySQL
import os
import pymysql
import pandas as pd
host = os.getenv('MYSQL_HOST')
port = os.getenv('MYSQL_PORT')
user = os.getenv('MYSQL_USER')
password = os.getenv('MYSQL_PASSWORD')
database = os.getenv('MYSQL_DATABASE')
conn = pymysql.connect(
host=host,
port=int(port),
user=user,
passwd=password,
db=database,
charset='utf8mb4')
df = pd.read_sql_query(
"SELECT DATE(created_at) AS date, COUNT(*) AS count FROM user GROUP BY date HAVING date >= '2017-04-01' ",
conn)
df.tail(10)
#MariaDB
matplotlib inline
import MySQLdb as mariadb
import getpass # so we don't need to store passwords on disk
import pandas as pd
# importing via mariadb directly into pandas dataframe:
password = getpass.getpass() # asks for password in the console window so we don't store it here
conn = mariadb.connect('localhost','myusername',password,'dbname');
data = pd.io.sql.read_sql('select * from ipython_out', conn)
conn.close()
data.shape
#MongoDB
import os
import pandas as pd
import numpy as np
from IPython.core.display import display, HTML
import pymongo
from pymongo import MongoClient
print 'Mongo version', pymongo.__version__
client = MongoClient('localhost', 27017)
db = client.test
collection = db.people
#Import Data
collection.drop()
os.system('mongoimport -d swarm-roles -c people dummyData.json')
#Check Access
cursor = collection.find().sort('Age',pymongo.ASCENDING).limit(3)
for doc in cursor:
print doc
#Aggregation in MongoDB
pipeline = [
{"$group": {"_id":"$Country",
"AvgAge":{"$avg":"$Age"},
"Count":{"$sum":1},
}},
{"$sort":{"Count":-1,"AvgAge":1}}
]
aggResult = collection.aggregate(pipeline) # returns a cursor
df1 = pd.DataFrame(list(aggResult)) # use list to turn the cursor to an array of documents
df1 = df1.set_index("_id")
df1.head()
|
C#
|
UTF-8
| 1,784
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library.ThinkOrSwim.Adapter
{
class Queue : IEnumerator, IEnumerator<Tuple<int, double>>
{
public int Timeout { get; set; }
BlockingCollection<Tuple<int, double>> bc = new BlockingCollection<Tuple<int, double>>(new ConcurrentQueue<Tuple<int, double>>());
Tuple<int, double> current;
internal Queue()
{
}
internal void Disconnect()
{
this.bc.CompleteAdding();
}
internal void Push(Tuple<int, double> quote)
{
this.bc.Add(quote);
}
public Tuple<int, double> Current
{
get
{
return this.current;
}
}
object IEnumerator.Current
{
get
{
return this.current;
}
}
public void Dispose()
{
this.bc.Dispose();
}
public bool MoveNext()
{
if (this.bc.IsCompleted)
{
return false;
}
this.current = this.bc.Take();
return true;
}
public bool TryTake(out Tuple<int, double> tuple)
{
bool succesful;
succesful = this.bc.TryTake(out tuple, timeout: TimeSpan.FromSeconds(Timeout));
if (succesful)
current = tuple;
return succesful;
}
public void Reset()
{
}
}
}
|
Python
|
UTF-8
| 7,154
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
import numpy as np
import tensorflow as tf
from PIL import Image
batch_size = 128
decay = 0.99
input_dim = (32, 32, 3)
iteration = 100000
learning_rate = 0.0001
noise_dim = 100
is_training = tf.placeholder(tf.bool)
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
x_train = x_train.reshape([x_train.shape[0]] + list(input_dim)).astype('float32') / 255
x_train = 2 * x_train - 1
# input placeholders
X = tf.placeholder(tf.float32, [None] + list(input_dim))
Z = tf.placeholder(tf.float32, [None, noise_dim])
# variable & model
with tf.variable_scope('generator'):
W1 = tf.get_variable(name="W1", shape=[noise_dim, 4 * 4 * 256], initializer=tf.keras.initializers.he_normal())
b1 = tf.get_variable(name="b1", shape=[4 * 4 * 256], initializer=tf.zeros_initializer())
W2 = tf.get_variable(name="W2", shape=[5, 5, 128, 256], initializer=tf.keras.initializers.he_normal())
b2 = tf.get_variable(name="b2", shape=[128], initializer=tf.zeros_initializer())
W3 = tf.get_variable(name="W3", shape=[5, 5, 64, 128], initializer=tf.keras.initializers.he_normal())
b3 = tf.get_variable(name="b3", shape=[64], initializer=tf.zeros_initializer())
W4 = tf.get_variable(name="W4", shape=[5, 5, 3, 64], initializer=tf.glorot_uniform_initializer())
b4 = tf.get_variable(name="b4", shape=[3], initializer=tf.zeros_initializer())
with tf.variable_scope('discriminator'):
W5 = tf.Variable(tf.random_uniform([5, 5, 3, 64], minval=-0.01, maxval=0.01))
b5 = tf.Variable(tf.zeros([64]))
W6 = tf.Variable(tf.random_uniform([5, 5, 64, 128], minval=-0.01, maxval=0.01))
b6 = tf.Variable(tf.zeros([128]))
W7 = tf.Variable(tf.random_uniform([5, 5, 128, 256], minval=-0.01, maxval=0.01))
b7 = tf.Variable(tf.zeros([256]))
W8 = tf.Variable(tf.random_uniform([4 * 4 * 256, 1], minval=-0.01, maxval=0.01))
b8 = tf.Variable(tf.zeros([1]))
def generator(Z):
with tf.variable_scope('generator'):
L1 = tf.matmul(Z, W1) + b1
L1 = tf.contrib.layers.batch_norm(L1, center=True, decay=decay, scale=True, is_training=is_training)
L1 = tf.nn.relu(L1)
L1 = tf.reshape(L1, [-1, 4, 4, 256])
# 4, 4, 256 /
L2 = tf.nn.conv2d_transpose(L1, W2, strides=[1, 2, 2, 1], output_shape=[batch_size, 8, 8, 128], padding='SAME')
L2 = tf.nn.bias_add(L2, b2)
L2 = tf.contrib.layers.batch_norm(L2, center=True, decay=decay, scale=True, is_training=is_training)
L2 = tf.nn.relu(L2)
# 8, 8, 128 /
L3 = tf.nn.conv2d_transpose(L2, W3, strides=[1, 2, 2, 1], output_shape=[batch_size, 16, 16, 64], padding='SAME')
L3 = tf.nn.bias_add(L3, b3)
L3 = tf.contrib.layers.batch_norm(L3, center=True, decay=decay, scale=True, is_training=is_training)
L3 = tf.nn.relu(L3)
# 16, 16, 64 /
L4 = tf.nn.conv2d_transpose(L3, W4, strides=[1, 2, 2, 1], output_shape=[batch_size, 32, 32, 3], padding='SAME')
L4 = tf.nn.bias_add(L4, b4)
L4 = tf.tanh(L4)
# 32, 32, 3 /
return L4
def discriminator(X):
with tf.variable_scope('discriminator'):
L1 = tf.nn.conv2d(X, W5, strides=[1, 2, 2, 1], padding='SAME')
L1 = tf.nn.bias_add(L1, b5)
L1 = tf.contrib.layers.batch_norm(L1, center=True, decay=decay, reuse=tf.AUTO_REUSE, scale=True, scope='BN1', is_training=is_training)
L1 = tf.nn.relu(L1)
# 16, 16, 64 /
L2 = tf.nn.conv2d(L1, W6, strides=[1, 2, 2, 1], padding='SAME')
L2 = tf.nn.bias_add(L2, b6)
L2 = tf.contrib.layers.batch_norm(L2, center=True, decay=decay, reuse=tf.AUTO_REUSE, scale=True, scope='BN2', is_training=is_training)
L2 = tf.nn.relu(L2)
# 8, 8, 128 /
L3 = tf.nn.conv2d(L2, W7, strides=[1, 2, 2, 1], padding='SAME')
L3 = tf.nn.bias_add(L3, b7)
L3 = tf.contrib.layers.batch_norm(L3, center=True, decay=decay, reuse=tf.AUTO_REUSE, scale=True, scope='BN3', is_training=is_training)
L3 = tf.nn.relu(L3)
# 4, 4, 256 /
L4 = tf.reshape(L3, [-1, 4 * 4 * 256])
L4 = tf.matmul(L4, W8) + b8
return L4, tf.nn.sigmoid(L4)
G = generator(Z)
D, D_output = discriminator(X)
DG, DG_output = discriminator(G)
# accuracy & loss & optimizer
d_fake_acc = tf.reduce_mean(tf.cast(tf.equal(tf.round(DG_output), tf.zeros_like(DG_output)), tf.float32))
d_fake_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=DG, labels=tf.zeros_like(DG)))
d_real_acc = tf.reduce_mean(tf.cast(tf.equal(tf.round(D_output), tf.ones_like(D_output)), tf.float32))
d_real_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D, labels=tf.ones_like(D)))
g_acc = tf.reduce_mean(tf.cast(tf.equal(tf.round(DG_output), tf.ones_like(DG_output)), tf.float32))
g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=DG, labels=tf.ones_like(DG)))
t_var = tf.trainable_variables()
d_var = [var for var in t_var if 'discriminator' in var.name]
g_var = [var for var in t_var if 'generator' in var.name]
u_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
d_ops = [var for var in u_ops if 'discriminator' in var.name]
g_ops = [var for var in u_ops if 'generator' in var.name]
with tf.control_dependencies(d_ops):
d_train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(0.5 * d_fake_loss + 0.5 * d_real_loss, var_list=d_var)
with tf.control_dependencies(g_ops):
g_train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(g_loss, var_list=g_var)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(iteration):
index = (i * batch_size) % (len(x_train) - batch_size)
loss = [None] * 3
noise = np.random.uniform(-1, 1, size=(batch_size, noise_dim))
score = [None] * 3
x_batch = x_train[index:index + batch_size]
loss[0], loss[1], score[0], score[1], _ = sess.run([d_fake_loss, d_real_loss, d_fake_acc, d_real_acc, d_train], feed_dict={X: x_batch, Z: noise, is_training: True})
loss[2], score[2], _ = sess.run([g_loss, g_acc, g_train], feed_dict={Z: noise, is_training: True})
print(i, 'D_fake:', [loss[0], score[0]], '\tD_real:', [loss[1], score[1]], '\tG:', [loss[2], score[2]])
if i % 10000 == 9999:
array = sess.run(G, feed_dict={Z: noise, is_training: False})
batch = []
for h in range(0, batch_size, 16):
if h + 16 <= batch_size:
batch.append(array[h:h + 16])
array = np.array(batch)
array = array.reshape((array.shape[0], array.shape[1]) + input_dim)
array = np.transpose(array, (0, 2, 1, 3, 4))
array = array.reshape((array.shape[0] * input_dim[0], array.shape[2] * input_dim[1], input_dim[2]))
array = np.uint8((array + 1) * 255 / 2)
image = Image.fromarray(array)
image.save('{}.png'.format(i + 1))
|
Java
|
UTF-8
| 773
| 2.390625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.intervalos.intervalos.data;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.time.LocalTime;
/**
*
* @author Víctor
*/
public class LocalTimeDeserializer extends JsonDeserializer<LocalTime> {
@Override
public LocalTime deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
JsonNode node=jp.readValueAsTree();
return LocalTime.of(node.get("horas").asInt(), node.get("minutos").asInt());
}
}
|
Shell
|
UTF-8
| 280
| 2.671875
| 3
|
[] |
no_license
|
#!/usr/bin/bash
#SBATCH -p short
VERSION=46
PREFIX=https://fungidb.org/common/downloads/release-${VERSION}
FILE=CimmitisRS_Broad.mRNA.fasta
if [ ! -f data/$FILE ]; then
curl -o data/$FILE $PREFIX/CimmitisRS/fasta/data/FungiDB-${VERSION}_CimmitisRS_AnnotatedTranscripts.fasta
fi
|
Java
|
UTF-8
| 443
| 1.914063
| 2
|
[] |
no_license
|
package com.jrosetim.testearw.service;
import com.jrosetim.testearw.model.PessoaModel;
import java.util.List;
import java.util.Optional;
public interface PessoaService {
PessoaModel salvar(PessoaModel pessoaModel);
PessoaModel editar(PessoaModel pessoaModel);
void deletar(Long id);
Optional<PessoaModel> filtrarPorId(Long id);
List<PessoaModel> getAll();
List<PessoaModel> buscar(PessoaModel pessoaFiltro);
}
|
JavaScript
|
UTF-8
| 4,036
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
'use strict';
var app = angular.module('halfLife', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'static/partials/main.html',
controller: 'MainCtrl'
});
$routeProvider.otherwise({
redirectTo: '/'
});
}
]);
app.controller('MainCtrl', ['$scope', '$log', function($scope, $log) {
$scope.data = {
// Checkboxes
'avoidWeekends' : false,
'startFirstDay': false,
// Sample data
'firstDay': 100,
'lastDay': 10,
'totalDays': 14,
// Results
'decayRate': null,
'halfLife': null,
'emailPlan': null};
// Apparently we can only get a number
var months =
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
/*
* Trigger updates
*/
$scope.$watch('data.firstDay', function(newValue, oldValue, scope) {
$scope.updateExponentialDecay();
});
$scope.$watch('data.lastDay', function(newValue, oldValue, scope) {
$scope.updateExponentialDecay();
});
$scope.$watch('data.totalDays', function(newValue, oldValue, scope) {
$scope.updateExponentialDecay();
});
$scope.onAvoidWeekendsChange = function() {
$scope.updateExponentialDecay();
};
$scope.onStartFirstDayChange = function() {
$scope.updateExponentialDecay();
};
/*
* Equation
*/
$scope.getDecayRate = function(totalDays, lastDay, firstDay) {
return (-1.0 / totalDays) * Math.log(1.0 * lastDay / firstDay);
};
$scope.getExponentialDecay = function(initialQuantity, decayRate, day) {
return 1.0 * initialQuantity * Math.exp(-1.0 * decayRate * day);
};
$scope.getHalfLife = function(decayRate) {
return 1.0 * Math.log(2.0) / decayRate;
};
/*
* Utils
*/
$scope.isWeekend = function(today) {
// Check for Saturday and Sunday
return (
today.getDay() === 6 ||
today.getDay() === 0);
};
/*
* Main method
*/
$scope.updateExponentialDecay = function() {
// Decay rate
$scope.data.decayRate = $scope.getDecayRate(
$scope.data.totalDays,
$scope.data.lastDay,
$scope.data.firstDay);
// Half life
$scope.data.halfLife = Math.ceil(
$scope.getHalfLife($scope.data.decayRate));
// Move the day one day up if we want to start on the first day.
// Also, if we want to avoid weekends, we need to move that day
// out of the weekend.
var today = new Date();
if ($scope.data.startFirstDay) {
do {
today.setDate(today.getDate() - 1);
} while ($scope.data.avoidWeekends && $scope.isWeekend(today));
}
// Plan
$scope.data.emailPlan = [];
for (var day = 0; day < $scope.data.totalDays + 1; day++) {
var remaining = Math.ceil(
$scope.getExponentialDecay(
$scope.data.firstDay, $scope.data.decayRate, day));
// Avoid weekends
if ($scope.data.avoidWeekends) {
while ($scope.isWeekend(today)) {
today.setDate(today.getDate() + 1);
}
}
// Format the date
var formattedDate = today.getUTCDate() + ' ' + months[today.getUTCMonth()];
// Total emails to answer that day
var totalDay = ($scope.data.emailPlan.length > 0 ?
$scope.data.emailPlan[day-1].remaining - remaining : - 1);
var dayPlan = {
'day': day,
'formattedDate': formattedDate,
'remaining': remaining,
'totalDay': totalDay};
$scope.data.emailPlan.push(dayPlan);
today.setDate(today.getDate() + 1);
}
};
}]);
|
Java
|
UTF-8
| 1,371
| 2.109375
| 2
|
[] |
no_license
|
package de.tbosch.tools.googleapps.controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Hyperlink;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import jfxtras.labs.dialogs.MonologFX.Type;
import jfxtras.labs.dialogs.MonologFXBuilder;
import org.springframework.stereotype.Controller;
import de.tbosch.tools.googleapps.utils.MessageHelper;
@Controller
public class AuthorizeController implements Initializable {
@FXML
private Hyperlink hyperlink;
private String url;
@FXML
public void clickOkButton() {
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
hyperlink.setText(url);
hyperlink.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
content.putString(url);
clipboard.setContent(content);
MonologFXBuilder.create().modal(true).type(Type.INFO)
.message(MessageHelper.getMessage("authorize.clipboard")).build().showDialog();
}
});
}
public void setUrl(String url) {
this.url = url;
}
}
|
Markdown
|
UTF-8
| 164
| 2.75
| 3
|
[] |
no_license
|
## Good machines have parts you can swap out.
In order to build a machine this way, you have to think about each part's inputs and outputs, its role, its purpose.
|
Java
|
UTF-8
| 422
| 1.5625
| 2
|
[] |
no_license
|
package com.westwell.backend.modules.generator.dao;
import com.westwell.backend.modules.generator.entity.StudentBaseInfoEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 学生基本信息
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2021-02-08 10:15:59
*/
@Mapper
public interface StudentBaseInfoDao extends BaseMapper<StudentBaseInfoEntity> {
}
|
Python
|
UTF-8
| 797
| 3.328125
| 3
|
[] |
no_license
|
import random
MIN0 = 0
MIN5 = -(10 ** 5)
MIN9 = -(10 ** 9)
MAX5 = 10 ** 5
MAX9 = 10 ** 9
MAX18 = 10 ** 18
def int_generator(min_value: int = MIN0, max_value: int = MAX5) -> int:
return random.randint(min_value, max_value)
def pair_generator(
x_min: int = MIN0, x_max: int = MAX5, y_min: int = MIN0, y_max: int = MAX5
) -> tuple:
return (int_generator(x_min, x_max), int_generator(y_min, y_max))
if __name__ == "__main__":
f = open("sample.txt", "w", encoding="UTF-8")
datalist = []
n = int_generator(1, 5 * 10 ** 5)
k = int_generator(1, n)
q = int_generator(1, 5 * 10 ** 5)
datalist.append(f"{n} {k} {q}\n")
for _ in [0] * q:
x, y = pair_generator(1, n, 0, MAX9)
datalist.append(f"{x} {y}\n")
f.writelines(datalist)
f.close()
|
PHP
|
UTF-8
| 2,268
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
<?php
$err_msg=$success="";
if(isset($_POST['add_dept'])){
$dept=$_POST['department'];
if(empty(trim($dept))){
$err_msg="PLEASE FILL IN THIS FIELD";
}else{
$sql="INSERT INTO tbl_department(department) VALUES(?)";
$stmt=$conn->prepare($sql);
$stmt->bind_param('s',$dept);
$dept=$_POST['department'];
$stmt->execute();
$stmt->close();
$success="NEW DEPARTMENET INSERTED";
}
}
if(isset($_POST["add_course"])){
$department=$_POST['tbl_department'];
$courses=$_POST['course'];
$sql="INSERT INTO tbl_courses(department,courses) VALUES(?,?)";
$stmt=$conn->prepare($sql);
$stmt->bind_param('ss',$department,$courses);
if($stmt->execute()){
$success="new record inserted";
}else{
$err_msg="Oops , something went wrong".$conn->error;
}
}
if(isset($_POST["change"])){
$old=$_POST['old'];
$new=$_POST['new'];
$sql="SELECT password FROM admin WHERE password=?";
$stmt=$conn->prepare($sql);
$stmt->bind_param('s',$old);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == false){
$err_msg="Old password is not correct";
}else{
$update="UPDATE admin SET password={$new}";
if($conn->query($update)){
$success="PASSWORD HAVE BEEN SUCCESSFULLY UPDATED";
}else {
$err_msg= "Please fill all fields";
}
}
}
if(isset($_POST['allocate'])){
$courses=$_POST['courses'];
$sql="SELECT regno, course FROM tbl_allocate WHERE course=? AND regno=?";
$stmt=$conn->prepare($sql);
$stmt->bind_param('ss',$courses,$file_no);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows >0){
$err_msg= "subject already exist! Please choose another";
}else{
$sql="INSERT INTO tbl_allocate(department,regno,course) VALUES(?,?,?)";
$stmt=$conn->prepare($sql);
$stmt->bind_param('sss',$department,$file_no,$courses);
if($stmt->execute()){
$success= "Inserted";
}
}
}
$conn->close();
?>
|
Markdown
|
UTF-8
| 1,955
| 2.875
| 3
|
[] |
no_license
|
# Tamagotchi
## How to install
### Pre-requisite
* Install PHP5.6+ (see https://launchpad.net/~ondrej/+archive/ubuntu/php)
* Install Laravel (see https://laravel.com/docs/5.3)
* Install Composer (https://getcomposer.org/download/)
* Install Node.js (Stable version) (https://github.com/creationix/nvm)
* Install Gulp (http://gulpjs.com/)
* Install a Mysql Server
### Setting up the app
Installing some libraries needed
```
sudo apt-get install php5.6-mbstring php5.6-xml php5.6-mysql
```
Download the code
```
git clone https://github.com/wuilliam321/tamagotchi_laravel.git
```
Move to the `tamagotchi_laravel` folder
```
cd tamagotchi_laravel/
```
Install composer dependencies, you have to go to pre-requisite link and see how to enable composer
```
composer install
```
This step is for nvm users only (stable)
```
nvm use stable
```
Install node dependencies
```
npm install
npm install --global gulp-cli # Ensure you have gulp installed
```
Create a mysql database named `tamadb`. First log into the mysql shell
```
$ mysql # Use your custom credentials ex: mysql -u root -proot
```
In the mysql shell run:
```
mysql> create database tamadb;
```
Prepare `.env` file
```
cp .env.example .env
php artisan key:generate
```
Open the `.env` file and change these values with the yours
```
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tamadb # < HERE GOES YOUR MYSQL DATABASE
DB_USERNAME=root # < HERE GOES YOUR MYSQL USERNAME
DB_PASSWORD=root # HERE GOES YOUR MYSQL PASSWORD
```
Save and close the file
After install all dependencies you have to run migrations
```
php artisan migrate
```
Fill database with data values
```
php artisan db:seed
```
If you want to clean all data and seed database again use:
```
php artisan migrate:refresh --seed
```
Run:
```
gulp # Every time you change the javascript files
```
And run:
```
php artisan serve
```
Now you can go to:
```
http://localhost:8000/
```
And see the app working
|
C#
|
UTF-8
| 384
| 2.546875
| 3
|
[] |
no_license
|
using System;
using System.IO.Compression;
namespace _6._Zip_and_Extract
{
class Program
{
static void Main(string[] args)
{
ZipFile.CreateFromDirectory(@"C:\ZipFileDemo", @"C:\ZipFileDemoOutput/MyZipFile.zip");
ZipFile.ExtractToDirectory(@"C:\ZipFileDemoOutput/MyZipFile.zip", @"C:\ZipFileResult");
}
}
}
|
Java
|
UTF-8
| 1,981
| 2.453125
| 2
|
[] |
no_license
|
package com.school.controllers.WebControllers.student;
import com.school.controllers.WebControllers.UserSessionController;
import com.school.models.Student;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.*;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
public class ArtifactWebController extends UserSessionController implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
String method = httpExchange.getRequestMethod();
String response = "";
Headers requestHeaders = httpExchange.getRequestHeaders();
Integer userID = getIdFromExistingCookies(requestHeaders);
if (userID == null) {
httpExchange.getResponseHeaders().set("Location", "/loginForm");
httpExchange.sendResponseHeaders(302, response.length());
}
else if (method.equals("GET")) {
Student student = loadStudent(userID);
setupStudentBalance(student);
setupStudentBasket(student);
setupStudentArtifacts(student);
if (student != null) {
String cookie = setupCookies(student);
httpExchange.getResponseHeaders().add("Set-Cookie", cookie);
}
JtwigTemplate template = JtwigTemplate.classpathTemplate("static/StudentTemplates/myartifacts.html");
JtwigModel model = JtwigModel.newModel();
model.with("student_artifacts", student.getArtifacts());
model.with("students", student);
response = template.render(model);
final byte[] finalResponseBytes = response.getBytes("UTF-8");
httpExchange.sendResponseHeaders(200, finalResponseBytes.length);
}
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
|
JavaScript
|
UTF-8
| 1,877
| 2.6875
| 3
|
[] |
no_license
|
const importLogo = (div) => {
let h1 = (document.createElement("h1").innerHTML = "HealthyFood");
div.append(h1);
};
const importSearch = (div) => {
let searchcomp = document.createElement("div");
searchcomp.classList.add("searchcomp");
let input = document.createElement("input");
input.placeholder = "Write to Search";
let btn = document.createElement("button");
let i = document.createElement("i");
i.classList.add("fa-search");
i.classList.add("fa");
btn.append(i);
searchcomp.append(input, btn);
div.append(searchcomp);
};
const importNav = (div) => {
const SignIn = document.createElement("button");
if (sessionStorage.id) {
SignIn.innerText = "Profile";
} else {
SignIn.innerText = "SignIn";
}
SignIn.onclick = SignInForm;
SignIn.classList.add("btn");
const SignUp = document.createElement("button");
SignUp.innerText = "SignUp";
SignUp.classList.add("btn");
SignUp.onclick = RegisterForm;
const Cart = document.createElement("button");
Cart.innerText = "Cart";
Cart.classList.add("btn");
div.append(SignIn, SignUp, Cart);
};
function showItems(div) {
if (Item.getItems()) {
let items = Item.getItems();
items.map((elm) => {
let item = document.createElement("div");
item.className = "itemToShow";
let imgDiv = document.createElement("div");
imgDiv.className = "imgDiv";
let img = document.createElement("img");
img.src = elm.img;
imgDiv.append(img);
let title = document.createElement("p");
title.innerText = "Title` " + elm.title;
title.className = "showTitle";
let price = document.createElement("p");
price.innerText = "Price" + elm.price;
let qnt = document.createElement("p");
qnt.innerText = "Qnt` " + elm.qnt;
item.append(imgDiv, title, price, qnt);
div.append(item);
});
} else {
}
}
|
C++
|
UTF-8
| 559
| 3.578125
| 4
|
[] |
no_license
|
#include<string>
#include<vector>
using namespace std;
template<typename T>
class HashTable {
public:
HashTable(int size) {
arr = new T[size];
size_ = size;
};
void hashAdd(string key_val, T item) {
int key = calculateKey(key_val);
arr[key % size] = item;
}
T getItem(string key_val) {
int key = calculateKey(key_val);
return arr[key % size];
}
private:
T* arr = NULL;
int size_ = 0;
int calculateKey(string key_val) {
int key = 0;
for (int i = 0; i < key_val.length(); i++) {
key += (int)key_val[i];
}
return key;
}
};
|
Python
|
UTF-8
| 4,318
| 2.640625
| 3
|
[] |
no_license
|
from pyspark.sql import SparkSession
from collections import defaultdict
import sys, math, time
def main():
start = time.time()
spark = SparkSession.builder.appName("assign2_task1").master("local[*]").getOrCreate()
sc = spark.sparkContext
sc.setLogLevel("OFF")
sc.setSystemProperty('spark.driver.memory', '4g')
sc.setSystemProperty('spark.executor.memory', '4g')
args = sys.argv
case_no,support,inp_file,out_file = int(args[1]),int(args[2]),str(args[3]),str(args[4])
input_rdd = sc.textFile(inp_file).map(lambda x : x.split(","))
son(input_rdd,support,case_no, out_file)
end = time.time()
print("Duration: ",round(end - start,2))
def son(input_rdd,support,case_no, out_file):
header = input_rdd.first()
if case_no == 1:
baskets = input_rdd.filter(lambda x: x != header).map(lambda x : (x[0],frozenset( [x[1]] ) )).reduceByKey(lambda x,y : x | y).map(lambda x: x[1])
elif case_no == 2:
baskets = input_rdd.filter(lambda x: x != header).map(lambda x : (x[1],frozenset([x[0]]))).reduceByKey(lambda x,y : x | y).map(lambda x: x[1])
total_items = baskets.count()
candidate_itemsets = baskets.mapPartitions(lambda x: apriori(x,support,total_items)).groupByKey().map(lambda x: x[0]).collect()
frequent_itemsets = baskets.mapPartitions(lambda x : get_item_count(x,candidate_itemsets)).reduceByKey(lambda x,y: x + y).filter(lambda x: x[1] >= support).map(lambda x :list(x[0]))
frequent_itemsets = frequent_itemsets.collect()
display_format(candidate_itemsets,frequent_itemsets, out_file)
def display_format(candidate_itemsets,frequent_itemsets, out_file):
f = open(out_file,"w+")
f.write("Candidates:\n")
format_data(candidate_itemsets,f)
f.write("Frequent Itemsets:\n")
format_data(frequent_itemsets,f)
f.close()
def format_data(itemset,f):
length_map = defaultdict(lambda : [])
for i in itemset:
length_map[len(i)].append(sorted(tuple(i)))
for items in length_map.values():
items.sort()
f.write(",".join(list(map(lambda x: str(tuple(x)).replace(',)',')'),items))))
f.write("\n\n")
def get_item_count(input_data,candidate_itemsets):
counts_map = defaultdict(int)
input_data = list(input_data)
for item in candidate_itemsets:
for data in input_data:
if item.issubset(data):
counts_map[item] += 1
return counts_map.items()
def get_candidate_items(frequent_items,k):
candidate_items = set()
for i in range(len(frequent_items)-1):
for j in range(i+1,len(frequent_items)):
candidate = frequent_items[i].union(frequent_items[j])
if len(candidate) == k:
candidate_items.add(candidate)
return candidate_items
def get_frequent_items(candidate_items, baskets_arr,partial_support, all_frequent_items):
counts_map = defaultdict(int)
for i in candidate_items:
for j in baskets_arr:
if i.issubset(j):
counts_map[i] += 1
frequent_items = []
for key,value in counts_map.items():
if value >= partial_support:
frequent_items.append(key)
all_frequent_items.append((key,1))
return frequent_items,all_frequent_items
def apriori(baskets, support, total_items):
baskets_arr = []
all_frequent_items = []
counts_map = defaultdict(int)
frequent_items = []
for basket in baskets:
baskets_arr.append(basket)
for item in basket:
counts_map[ frozenset( (item,) ) ] += 1
partial_support = support * (len(baskets_arr) / total_items)
for key,value in counts_map.items():
if value >= partial_support:
all_frequent_items.append((key,1))
frequent_items.append(key)
k = 2
while True:
candidate_items = get_candidate_items(frequent_items,k)
print("CANDIDATE ITEM LENGTH = ", len(candidate_items))
frequent_items, all_frequent_items = get_frequent_items(candidate_items, baskets_arr,partial_support, all_frequent_items)
print("FREQUENT ITEM LENGTH = ", len(frequent_items))
if len(candidate_items) == 0 or len(frequent_items) == 0:
break
k += 1
return all_frequent_items
if __name__ == "__main__":
main()
|
Java
|
UTF-8
| 10,854
| 2.15625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.mykey.sdk.common.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.mykey.sdk.R;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
/**
* Created by zero on 2018/9/1.
*/
public class StatusBarUtil {
private static float DEFAULT_ALPHA = Build.VERSION.SDK_INT >= Build
.VERSION_CODES.LOLLIPOP ? 0.2f : 0.3f;
/**
* tint for status bar above OS Version 4.4 on Android
*
* @param activity
* @param statusBarColor
* @param alpha [0.0-1.0]
*/
public static void tintStatusBar(Activity activity, int
statusBarColor, float alpha) {
tintStatusBar(activity.getWindow(), statusBarColor, alpha);
}
/**
* tint for status bar above OS Version 4.4 on Android
*
* @param window
* @param statusBarColor
* @param alpha [0.0-1.0]
*/
public static void tintStatusBar(Window window, int statusBarColor, float alpha) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
// if OS Version below 4, not support
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// OS Version above 5.0
View decorView = window.getDecorView();
int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
decorView.setSystemUiVisibility(option);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
} else {
// OS Version below 5.0
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
/**
* Immersive full screen mode above Android 4.4
*
* @param activity
* @param alpha [0.0-1.0]
*/
public static void immersiveStatusBar(Activity activity, float alpha) {
immersiveStatusBar(activity.getWindow(), alpha);
}
/**
* Immersive full screen mode above Android 4.4
*
* @param window
* @param alpha [0.0-1.0]
*/
private static void immersiveStatusBar(Window window, float alpha) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
// if OS Version below 4.4, not support
return;
}
ViewGroup decorView = (ViewGroup) window.getDecorView();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.clearFlags(WindowManager.LayoutParams
.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams
.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
int systemUiVisibility = decorView.getSystemUiVisibility();
systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
decorView.setSystemUiVisibility(systemUiVisibility);
} else {
window.addFlags(WindowManager.LayoutParams
.FLAG_TRANSLUCENT_STATUS);
}
ViewGroup contentView = (ViewGroup) decorView.findViewById(Window
.ID_ANDROID_CONTENT);
View rootView = contentView.getChildAt(0);
if (rootView != null) {
rootView.setFitsSystemWindows(true);
int statusBarHeight = getStatusBarHeight(window.getContext());
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)
rootView.getLayoutParams();
lp.topMargin = -statusBarHeight;
rootView.setLayoutParams(lp);
}
setTranslucentView(decorView, alpha);
}
public static void setStatusBarDarkMode(Activity activity) {
setStatusBarDarkMode(activity.getWindow());
}
private static void setStatusBarDarkMode(Window window) {
if (isFlyme4Later()) {
setStatusBarDarkModeForFlyme4(window, true);
} else if (isMIUI6Later()) {
setStatusBarDarkModeForMIUI6(window, true);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
setStatusBarDarkModeForM(window);
}
}
/**
* set font color above android 6.0
*/
@TargetApi(Build.VERSION_CODES.M)
private static void setStatusBarDarkModeForM(Window window) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams
.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
int systemUiVisibility = window.getDecorView().getSystemUiVisibility();
systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
window.getDecorView().setSystemUiVisibility(systemUiVisibility);
}
/**
* set Flyme4+ darkMode, when set darkMode, font color and icon to be black http://open-wiki.flyme.cn/index.php?title=Flyme%E7%B3%BB%E7%BB%9FAPI
*/
private static boolean setStatusBarDarkModeForFlyme4(Window window, boolean dark) {
boolean result = false;
if (window != null) {
try {
WindowManager.LayoutParams e = window.getAttributes();
Field darkFlag = WindowManager.LayoutParams.class
.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
Field meizuFlags = WindowManager.LayoutParams.class
.getDeclaredField("meizuFlags");
darkFlag.setAccessible(true);
meizuFlags.setAccessible(true);
int bit = darkFlag.getInt(null);
int value = meizuFlags.getInt(e);
if (dark) {
value |= bit;
} else {
value &= ~bit;
}
meizuFlags.setInt(e, value);
window.setAttributes(e);
result = true;
} catch (Exception var8) {
Log.e("StatusBar", "setStatusBarDarkIcon: failed");
}
}
return result;
}
/**
* set MIUI6+ darkMode, when set darkMode, font color and icon to be black http://dev.xiaomi.com/doc/p=4769/
*/
private static void setStatusBarDarkModeForMIUI6(Window window, boolean darkmode) {
Class<? extends Window> clazz = window.getClass();
try {
int darkModeFlag = 0;
Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
extraFlagField.invoke(window, darkmode ? darkModeFlag : 0, darkModeFlag);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void setStatusBar(ViewGroup container, int statusBarColor, boolean visible, boolean addToFirst) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
View statusBarView = container.findViewById(R.id.statusbar_view);
if (statusBarView == null) {
statusBarView = new View(container.getContext());
statusBarView.setId(R.id.statusbar_view);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(container.getContext()));
if (addToFirst) {
container.addView(statusBarView, 0, lp);
} else {
container.addView(statusBarView, lp);
}
}
statusBarView.setBackgroundColor(statusBarColor);
statusBarView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
private static void setStatusBar(ViewGroup container, int statusBarColor, boolean visible) {
setStatusBar(container, statusBarColor, visible, false);
}
private static void setTranslucentView(ViewGroup container, float alpha) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
View translucentView = container.findViewById(R.id.translucent_view);
if (translucentView == null) {
translucentView = new View(container.getContext());
translucentView.setId(R.id.translucent_view);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(container.getContext()));
container.addView(translucentView, lp);
}
translucentView.setBackgroundColor(Color.argb((int) (alpha * 255), 0, 0, 0));
}
}
public static int getStatusBarHeight(Context context) {
int result = 0;
int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
result = context.getResources().getDimensionPixelSize(resId);
}
return result;
}
/**
* is above Flyme4
*/
public static boolean isFlyme4Later() {
return Build.FINGERPRINT.contains("Flyme_OS_4")
|| Build.VERSION.INCREMENTAL.contains("Flyme_OS_4")
|| Pattern.compile("Flyme OS [4|5]", Pattern
.CASE_INSENSITIVE).matcher(Build.DISPLAY).find()
|| Pattern.compile("Flyme [4|5|6]", Pattern.CASE_INSENSITIVE)
.matcher(Build.DISPLAY).find();
}
/**
* is above MIUI6
*/
public static boolean isMIUI6Later() {
try {
Class<?> clz = Class.forName("android.os.SystemProperties");
Method mtd = clz.getMethod("get", String.class);
String val = (String) mtd.invoke(null, "ro.miui.ui.version.name");
val = val.replaceAll("[vV]", "");
int version = Integer.parseInt(val);
return version >= 6;
} catch (Exception e) {
return false;
}
}
public static void setHeightAndPadding(Context context, View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(context),
view.getPaddingRight(), view.getPaddingBottom());
}
}
}
|
SQL
|
UTF-8
| 3,049
| 2.90625
| 3
|
[] |
no_license
|
/*
SQLyog Trial v10.2
MySQL - 5.6.11 : Database - myshop
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`myshop` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `myshop`;
/*Table structure for table `s_managers` */
DROP TABLE IF EXISTS `s_managers`;
CREATE TABLE `s_managers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`logid` varchar(100) NOT NULL,
`pwd` varchar(100) NOT NULL,
`name` varchar(100) DEFAULT NULL,
`super_flg` enum('1','0') NOT NULL DEFAULT '0',
`type` int(11) DEFAULT NULL,
`status` enum('1','0') DEFAULT '0',
`created` int(11) DEFAULT NULL,
`modified` int(11) DEFAULT NULL,
`author` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*Data for the table `s_managers` */
insert into `s_managers`(`id`,`logid`,`pwd`,`name`,`super_flg`,`type`,`status`,`created`,`modified`,`author`) values (1,'admin','9d8f28301969c9725dadfe0c44f1420dc4480c41','张三','1',NULL,'0',NULL,NULL,NULL);
/*Table structure for table `s_userinfos` */
DROP TABLE IF EXISTS `s_userinfos`;
CREATE TABLE `s_userinfos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`logid` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`msn` varchar(100) DEFAULT NULL,
`qq` varchar(30) DEFAULT NULL,
`office_tel` varchar(50) DEFAULT NULL,
`home_tel` varchar(50) DEFAULT NULL,
`mobile` varchar(50) DEFAULT NULL,
`created` int(11) DEFAULT NULL,
`modified` int(11) DEFAULT NULL,
`author` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*Data for the table `s_userinfos` */
insert into `s_userinfos`(`id`,`logid`,`email`,`msn`,`qq`,`office_tel`,`home_tel`,`mobile`,`created`,`modified`,`author`) values (1,'admin','admin@163.com','2123123131','12131313','','','',1413182297,1413182297,NULL),(2,'test','test@123.com','','','','','',1413186838,1413186838,NULL);
/*Table structure for table `s_users` */
DROP TABLE IF EXISTS `s_users`;
CREATE TABLE `s_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`logid` varchar(255) NOT NULL,
`pwd` varchar(100) NOT NULL,
`status` enum('0','1','2') NOT NULL DEFAULT '1',
`last_login` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*Data for the table `s_users` */
insert into `s_users`(`id`,`logid`,`pwd`,`status`,`last_login`) values (1,'admin','9d8f28301969c9725dadfe0c44f1420dc4480c41','0','2014-10-14 16:44:10'),(2,'test','ae50d58f53b84987c7716535ddea9f881753b212','0','2014-10-13 16:56:21');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
|
Go
|
UTF-8
| 929
| 3.25
| 3
|
[] |
no_license
|
package Week_03
import "fmt"
//https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
//[ 根节点, [左子树的前序遍历结果], [右子树的前序遍历结果] ]
//[ [左子树的中序遍历结果], 根节点, [右子树的中序遍历结果] ]
//且len[左子树的中序遍历结果] == len[左子树的前序遍历结果]
func buildTree(preorder []int, inorder []int) *TreeNode {
if len(preorder) == 0 {
return nil
}
node := &TreeNode{Val: preorder[0]}
i := 0
for ; i < len(inorder); i++ {
if inorder[i] == preorder[0] {
break
}
}
node.Left = buildTree(preorder[1:i+1],inorder[:i])
node.Right = buildTree(preorder[i+1:], inorder[i+1:])
return node
}
func main() {
a := []int{0,1,2,3,4}
fmt.Println(a[1:2])
}
|
Java
|
UTF-8
| 461
| 1.804688
| 2
|
[] |
no_license
|
package com.hcl.mortgage.repository;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.hcl.mortgage.entity.Transaction;
@Repository
public interface TransactionRepository extends JpaRepository<Transaction, Integer> {
public List<Transaction> findByAccountNumber(String accountNumber, Pageable pageable);
}
|
Markdown
|
UTF-8
| 1,350
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
# three-screenshake
a screen shake tool for three.js
example here : https://jsfiddle.net/e4h931co/
# how to use it
instantiate it :
```javascript
var screenShake = ScreenShake();
```
update the camera in the loop :
```javascript
function loop() {
screenShake.update(camera);
renderer.render(scene, camera);
requestAnimationFrame(loop);
};
```
if you indend to do something else with the camera, you can check for screenShake.enabled like this :
```javascript
if (screenShake.enabled == true) {
// Then a screenshake is in progress
}
```
in an event listener or any part of your code that must create a screen shake :
```javascript
screenShake.shake( camera, new THREE.Vector3(0.1, 0, 0), 300 /* ms */ );
```
The second argument is the offset at the climax of the screen-shake.
The third argument is the duration of the shake in milliseconds.
# install via npm
`npm i https://github.com/felixmariotto/three-screenshake`
Because this is no ES6 Module, add this Shim to your bundler / `webpack.js`:
```javascript
module.exports = {
module: {
rules: [
{
test: require.resolve("three-screenshake"),
use: ['imports-loader?THREE=three', 'exports-loader?ScreenShake']
}
]
}
}
```
Import and use as described:
```javascript
import * as ScreenShake from "three-screenshake";
...
```
|
Java
|
UTF-8
| 6,300
| 1.875
| 2
|
[] |
no_license
|
package com.cts.outreach.email.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix="email")
public class ReportMailConfig {
private String reportinsightsubject;
private String reportinsightmailLine1;
private String reportinsightmailLine2;
private String reportinsightmailLine3;
private String reportinsightmailLine4;
private String reportinsightmailLine5;
private String reportinsightmailLine6;
private String reportinsightmailLine7;
private String reportinsightmailLine8;
private String reportinsightmailLine9;
private String reportinsightmailLine10;
private String reportinsightmailLine11;
private String reportinsightmailLine12;
private String reportinsightmailLine13;
private String reportinsightmailLine14;
private String reportinsightmailLine15;
private String reportinsightmailLine16;
private String reportinsightmailLine17;
private String reportinsightmailLine18;
private String reportinsightmailLine19;
private String reportinsightmailLine20;
private String reportinsightmailLine21;
private String reportinsightmailLine22;
public String getReportinsightsubject() {
return reportinsightsubject;
}
public void setReportinsightsubject(String reportinsightsubject) {
this.reportinsightsubject = reportinsightsubject;
}
public String getReportinsightmailLine1() {
return reportinsightmailLine1;
}
public void setReportinsightmailLine1(String reportinsightmailLine1) {
this.reportinsightmailLine1 = reportinsightmailLine1;
}
public String getReportinsightmailLine2() {
return reportinsightmailLine2;
}
public void setReportinsightmailLine2(String reportinsightmailLine2) {
this.reportinsightmailLine2 = reportinsightmailLine2;
}
public String getReportinsightmailLine3() {
return reportinsightmailLine3;
}
public void setReportinsightmailLine3(String reportinsightmailLine3) {
this.reportinsightmailLine3 = reportinsightmailLine3;
}
public String getReportinsightmailLine4() {
return reportinsightmailLine4;
}
public void setReportinsightmailLine4(String reportinsightmailLine4) {
this.reportinsightmailLine4 = reportinsightmailLine4;
}
public String getReportinsightmailLine5() {
return reportinsightmailLine5;
}
public void setReportinsightmailLine5(String reportinsightmailLine5) {
this.reportinsightmailLine5 = reportinsightmailLine5;
}
public String getReportinsightmailLine6() {
return reportinsightmailLine6;
}
public void setReportinsightmailLine6(String reportinsightmailLine6) {
this.reportinsightmailLine6 = reportinsightmailLine6;
}
public String getReportinsightmailLine7() {
return reportinsightmailLine7;
}
public void setReportinsightmailLine7(String reportinsightmailLine7) {
this.reportinsightmailLine7 = reportinsightmailLine7;
}
public String getReportinsightmailLine8() {
return reportinsightmailLine8;
}
public void setReportinsightmailLine8(String reportinsightmailLine8) {
this.reportinsightmailLine8 = reportinsightmailLine8;
}
public String getReportinsightmailLine9() {
return reportinsightmailLine9;
}
public void setReportinsightmailLine9(String reportinsightmailLine9) {
this.reportinsightmailLine9 = reportinsightmailLine9;
}
public String getReportinsightmailLine10() {
return reportinsightmailLine10;
}
public void setReportinsightmailLine10(String reportinsightmailLine10) {
this.reportinsightmailLine10 = reportinsightmailLine10;
}
public String getReportinsightmailLine11() {
return reportinsightmailLine11;
}
public void setReportinsightmailLine11(String reportinsightmailLine11) {
this.reportinsightmailLine11 = reportinsightmailLine11;
}
public String getReportinsightmailLine12() {
return reportinsightmailLine12;
}
public void setReportinsightmailLine12(String reportinsightmailLine12) {
this.reportinsightmailLine12 = reportinsightmailLine12;
}
public String getReportinsightmailLine13() {
return reportinsightmailLine13;
}
public void setReportinsightmailLine13(String reportinsightmailLine13) {
this.reportinsightmailLine13 = reportinsightmailLine13;
}
public String getReportinsightmailLine14() {
return reportinsightmailLine14;
}
public void setReportinsightmailLine14(String reportinsightmailLine14) {
this.reportinsightmailLine14 = reportinsightmailLine14;
}
public String getReportinsightmailLine15() {
return reportinsightmailLine15;
}
public void setReportinsightmailLine15(String reportinsightmailLine15) {
this.reportinsightmailLine15 = reportinsightmailLine15;
}
public String getReportinsightmailLine16() {
return reportinsightmailLine16;
}
public void setReportinsightmailLine16(String reportinsightmailLine16) {
this.reportinsightmailLine16 = reportinsightmailLine16;
}
public String getReportinsightmailLine17() {
return reportinsightmailLine17;
}
public void setReportinsightmailLine17(String reportinsightmailLine17) {
this.reportinsightmailLine17 = reportinsightmailLine17;
}
public String getReportinsightmailLine18() {
return reportinsightmailLine18;
}
public void setReportinsightmailLine18(String reportinsightmailLine18) {
this.reportinsightmailLine18 = reportinsightmailLine18;
}
public String getReportinsightmailLine19() {
return reportinsightmailLine19;
}
public void setReportinsightmailLine19(String reportinsightmailLine19) {
this.reportinsightmailLine19 = reportinsightmailLine19;
}
public String getReportinsightmailLine20() {
return reportinsightmailLine20;
}
public void setReportinsightmailLine20(String reportinsightmailLine20) {
this.reportinsightmailLine20 = reportinsightmailLine20;
}
public String getReportinsightmailLine21() {
return reportinsightmailLine21;
}
public void setReportinsightmailLine21(String reportinsightmailLine21) {
this.reportinsightmailLine21 = reportinsightmailLine21;
}
public String getReportinsightmailLine22() {
return reportinsightmailLine22;
}
public void setReportinsightmailLine22(String reportinsightmailLine22) {
this.reportinsightmailLine22 = reportinsightmailLine22;
}
}
|
Python
|
UTF-8
| 496
| 2.9375
| 3
|
[
"CC0-1.0"
] |
permissive
|
#!/usr/bin/env python
import re, sys
def main():
phone_number = sys.argv[1]
regex_str = r'''0 # area code starts with 0
[1-9]\d? # area code has 1 or 2 digits
/ # separator
[1-9]\d{5,6} # 6 or 7 digit number'''
if re.match(regex_str, phone_number, re.VERBOSE):
print 'ok'
else:
print 'not ok'
return 0
if __name__ == '__main__':
status = main()
sys.exit(status)
|
Java
|
UTF-8
| 3,860
| 3.53125
| 4
|
[] |
no_license
|
package net.halalaboos.mcwrapper.api.util.math;
/**
* Represents a three-dimensional point.
*/
public class Vector3d {
/** The x-coordinate of the point */
private final double x;
/** The y-coordinate of the point */
private final double y;
/** The z-coordinate of the point */
private final double z;
public static final Vector3d ZERO = new Vector3d(0, 0, 0);
public Vector3d(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Helps simplify the process of adding a value to only one of the points of the Vector, rather
* than having to use {@link #add(double)}.
*
* @param x The amount to add to the {@link #x}
* @return The {@link Vector3d} with the given {@code x} added to the current {@link #x}
*/
public Vector3d addX(double x) {
return new Vector3d(this.x + x, this.y, this.z);
}
/**
* Helps simplify the process of adding a value to only one of the points of the Vector, rather
* than having to use {@link #add(double)}.
*
* @param y The amount to add to the {@link #y}
* @return The {@link Vector3d} with the given {@code y} added to the current {@link #y}
*/
public Vector3d addY(double y) {
return new Vector3d(this.x, this.y + y, this.z);
}
/**
* Helps simplify the process of adding a value to only one of the points of the Vector, rather
* than having to use {@link #add(double)}.
*
* @param z The amount to add to the {@link #z}
* @return The {@link Vector3d} with the given {@code z} added to the current {@link #z}
*/
public Vector3d addZ(double z) {
return new Vector3d(this.x, this.y, this.z + z);
}
public Vector3d add(double amount) {
return new Vector3d(this.x + amount, this.y + amount, this.z + amount);
}
public Vector3d add(Vector3d vec) {
return add(vec.x, vec.y, vec.z);
}
public Vector3d add(double x, double y, double z) {
return new Vector3d(this.x + x, this.y + y, this.z + z);
}
public Vector3d sub(double amount) {
return new Vector3d(this.x - amount, this.y - amount, this.z - amount);
}
public Vector3d sub(Vector3d vec) {
return new Vector3d(this.x - vec.x, this.y - vec.y, this.z - vec.z);
}
public Vector3d scale(double amount) {
return new Vector3d(this.x * amount, this.y * amount, this.z * amount);
}
public Vector3d div(double amount) {
return new Vector3d(this.x / amount, this.y / amount, this.z / amount);
}
public double distanceTo(Vector3d target) {
double dX = this.x - target.x;
double dY = this.y - target.y;
double dZ = this.z - target.z;
return MathUtils.sqrt(dX * dX + dY * dY + dZ * dZ);
}
public Vector3d rotatePitch(float pitch) {
float cos = MathUtils.cos(pitch);
float sin = MathUtils.sin(pitch);
return new Vector3d(this.x, this.y * (double)cos + this.z * (double)sin,
this.z * (double)cos - this.y * (double)sin);
}
public Vector3d rotateYaw(float yaw) {
float cos = MathUtils.cos(yaw);
float sin = MathUtils.sin(yaw);
return new Vector3d(this.x * (double)cos + this.z * (double)sin, this.y,
this.z * (double)cos - this.x * (double)sin);
}
public Vector3d copy() {
return new Vector3d(x, y, z);
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getZ() {
return z;
}
public Vector3d setX(double x) {
return new Vector3d(x, this.y ,this.z);
}
public Vector3d setY(double y) {
return new Vector3d(this.x, y, this.z);
}
public Vector3d setZ(double z) {
return new Vector3d(this.x, this.y, z);
}
public Vector3d set(double x, double y, double z) {
return new Vector3d(x, y, z);
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof Vector3d)) return false;
Vector3d other = (Vector3d)o;
return other.x == this.x && other.y == this.y && other.z == this.z;
}
public Vector3i toInt() {
return new Vector3i(this);
}
}
|
C++
|
UTF-8
| 1,719
| 2.765625
| 3
|
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
vector<long long> fact(1e5 + 1);
int modInverse(int a, int m)
{
int m0 = m;
int y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1)
{
// q is quotient
int q = a / m;
int t = m;
// m is remainder now, process same as
// Euclid's algo
m = a % m, a = t;
t = y;
// Update y and x
y = x - q * y;
x = t;
}
// Make x positive
if (x < 0)
x += m0;
return x;
}
long long dfs(int cur, int par, vector<vector<int> >& adj, int k){
long long res = 1;
int kk = k - 1;
if(par != -1) kk--;
if(kk < adj[cur].size() - 1 ) return 0;
long long mul = (fact[kk] * modInverse(fact[kk - adj[cur].size() + 1], MOD)) % MOD;
if(adj[cur].size() == 1 && par != -1){
//cout << cur << ": " << res << endl;
return res;
}
for(int i = 0; i < adj[cur].size(); i++){
int nxt = adj[cur][i];
if(nxt == par){
kk++;
continue;
}
res *= dfs(nxt, cur, adj, k);
res %= MOD;
}
//cout << cur << ": " << res << endl;
return (res * mul) % MOD;
}
int main(){
int n, k;
cin >> n >> k;
fact[0] = 1;
for(int i = 1; i <= 1e5; i++) fact[i] = (i * fact[i - 1]) % MOD;
vector<vector<int> > adj(n);
for(int i = 0; i < n - 1; i++){
int u, v;
cin >> u >> v;
u--; v--;
adj[u].push_back(v);
adj[v].push_back(u);
}
cout << k * dfs(0, -1, adj, k) << endl;
}
|
Java
|
UTF-8
| 4,464
| 2.359375
| 2
|
[
"Apache-2.0",
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.entitySystem.sectors;
import org.joml.Vector3f;
import org.joml.Vector3i;
import org.joml.Vector3ic;
import org.terasology.engine.entitySystem.entity.EntityRef;
import org.terasology.engine.logic.location.LocationComponent;
import org.terasology.gestalt.module.sandbox.API;
import org.terasology.engine.world.chunks.Chunk;
import org.terasology.engine.world.chunks.ChunkProvider;
import org.terasology.engine.world.chunks.Chunks;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A utility class for the {@link SectorSimulationSystem} and related components and events.
*/
@API
public final class SectorUtil {
private SectorUtil() {
}
/**
* Create a new {@link SectorRegionComponent} with the given chunks, from a collection of chunk positions.
*
* @param chunks the positions of the chunks to add
* @return the newly created SectorRegionComponent
*/
public static SectorRegionComponent createSectorRegionComponent(Collection<Vector3i> chunks) {
SectorRegionComponent regionComponent = new SectorRegionComponent();
regionComponent.chunks.addAll(chunks);
return regionComponent;
}
/**
* Add the given collection of chunks to the given component, converting the chunks to their positions.
*
* @param regionComponent the component to add the chunks to
* @param chunks the chunks to add
*/
public static void addChunksToRegionComponent(SectorRegionComponent regionComponent, Collection<Chunk> chunks) {
regionComponent.chunks.addAll(chunks.stream()
.map(k -> new Vector3i(k.getPosition()))
.collect(Collectors.toSet()));
}
/**
* Add the given collection of chunk positions to the {@link SectorRegionComponent} of the entity, creating it if
* needed.
*
* @param entity the entity to which the chunks will be added
* @param chunks the positions of the chunks to add
*/
public static void addChunksToRegionComponent(EntityRef entity, Collection<Vector3i> chunks) {
SectorRegionComponent regionComponent = entity.getComponent(SectorRegionComponent.class);
if (regionComponent == null) {
regionComponent = new SectorRegionComponent();
}
regionComponent.chunks.addAll(chunks);
entity.addOrSaveComponent(regionComponent);
}
/**
* Watched chunks are defined as the union of:
* <ul>
* <li>The chunk in which the {@link LocationComponent#getWorldPosition(Vector3f)} resides, if any</li>
* <li>The set of chunks in {@link SectorRegionComponent#chunks}, if any</li>
* </ul>
*
* @param entity the entity to query the watched chunks of
* @return the set of positions of this entity's watched chunks
*/
public static Set<Vector3i> getWatchedChunks(EntityRef entity) {
Set<Vector3i> chunks = new HashSet<>();
LocationComponent loc = entity.getComponent(LocationComponent.class);
Vector3f position = loc.getWorldPosition(new Vector3f());
if (position.isFinite()) {
chunks.add(Chunks.toChunkPos(position, new Vector3i()));
}
SectorRegionComponent regionComponent = entity.getComponent(SectorRegionComponent.class);
if (regionComponent != null) {
chunks.addAll(regionComponent.chunks); // potential leaky abstraction. component exposes its internal vectors
}
return chunks;
}
/**
* Calculate whether the entity is watching no loaded chunks, or only the given chunk is loaded.
*
* @param entity the sector-scope entity to query
* @param chunkPos the position of the chunk to check
* @param chunkProvider the chunkProvider, so that it can check which chunks are loaded
* @return whether the entity is watching no loaded chunks, or only the given chunk is loaded
*/
public static boolean onlyWatchedChunk(EntityRef entity, Vector3ic chunkPos, ChunkProvider chunkProvider) {
Set<Vector3i> readyChunks = getWatchedChunks(entity).stream()
.filter(chunkProvider::isChunkReady)
.collect(Collectors.toSet());
return readyChunks.isEmpty() || (readyChunks.size() == 1 && readyChunks.contains(chunkPos));
}
}
|
Python
|
MacCentralEurope
| 2,739
| 3.703125
| 4
|
[] |
no_license
|
'''
Created on Mar 20, 2014
@author: vatsa
'''
'''
#################
Tetris
#################
Implement the drop piece function for tetris. Tetris has a 10 column x 20 row grid.
Your job is to implement the following function/method
void drop_piece(string[][] piece , column_num)
The function will accept moves from a player and save them into a data structure of your design. After accepting a move, the piece will drop straight down until it collides with another piece. The drop is instantaneous - you dont have to simulate time.
For examples, see: https://gist.github.com/kcen/51c743d30d4e74f94981
A picture of the pieces can be found here: http://media.tumblr.com/tumblr_l95u91VHHR1qcs0z8.bmp
Example:
http://i.imgur.com/GGec7zh.png
'''
m = [[0 for i in range(10)] for i in range(20)]
def gettop(col, l):
tops = []
for x in range(len(m)):
for y in range(l):
if m[len(m)-1-x][col+y] != 0:
tops.append(len(m)-1-x)
if len(tops) == 0:
return 0
return max(tops)+1
def fitPiece(piece, col, top, clear):
for x in range(len(piece)):
for y in range(len(piece[0])):
if not clear and m[top+len(piece)-x-1][col+y]==1:
continue
else:
m[top+len(piece)-x-1][col+y] = piece[x][y]
def drop_piece(piece, col):
if col<0 or col+len(piece[0]) >= len(m[0]):
print "Invalid Insertion!"
return
top = gettop(col, len(piece[0]))
if len(piece)+top >=len(m):
print "Game Over!"
return
fitPiece(piece,col,top,False)
for x in range(len(piece)):
flag = True
for y in range(len(piece[0])):
if top+x >= 0 and top+x-1 >= 0:
if (m[top+x][col+y]!= 0 or m[top+x-1][col+y]!= 0) and \
(m[top+x][col+y] == 0 or m[top+x-1][col+y] == 0):
continue
else:
flag = False
break
else:
flag = False
if flag:
blank = [[0 for i in range(len(piece[0]))] for j in range(len(piece))]
fitPiece(blank,col,top,True)
top -= 1
fitPiece(piece,col,top, False)
else:
break
drop_piece([[1,1],[1,1]],2)
drop_piece([[0,1,1],[1,1,0]],2)
drop_piece([[0,1,1],[1,1,0]],4)
drop_piece([[0,1],[1,1],[1,0]],2)
drop_piece([[0,1],[1,1],[1,0]],9)
drop_piece([[0,1],[1,1],[1,0]],2)
drop_piece([[0,1],[1,1],[1,0]],2)
drop_piece([[0,1],[1,1],[1,0]],2)
drop_piece([[0,1],[1,1],[1,0]],2)
drop_piece([[0,1],[1,1],[1,0]],2)
drop_piece([[0,1],[1,1],[1,0]],2)
drop_piece([[0,1],[1,1],[1,0]],2)
m.reverse()
for x in m:
print x
|
Ruby
|
UTF-8
| 1,042
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
require 'open-uri'
require 'hpricot'
class Twitter < Linkbot::Plugin
def initialize
@config = Linkbot::Config["plugins"]["twitter"]
# Set the following in config.json to have linkbot retrieve and display
# tweet content for chat services that don't do that already.
# { "plugins": {
# "twitter": {
# "expand_content": true
# }
# }
# }
if @config && @config["expand_content"]
register :regex => /(https:\/\/twitter.com\/[\w\/]*)/
end
end
def on_message(message, matches)
url = matches[0]
doc = Hpricot(open(url).read)
msg = doc.at(".opened-tweet .tweet-text").inner_text
# images we want to display have a "src" and match pbs.twimg.com/media
images = doc.search("img").select {|x| x.attributes.to_hash.has_key?("src") && x["src"].match(/pbs.twimg.com\/media/) }
if images.length > 0
src = images.first.attributes["src"]
# strip trailing :large
src.gsub! /:large$/, ''
msg = "#{msg} #{src}"
end
msg
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.