Merge pull request #1 from Kwoth/master

t
This commit is contained in:
Josh Hawking 2016-01-26 01:36:54 +10:30
commit d7f82244ed
11 changed files with 624 additions and 67 deletions

View File

@ -135,5 +135,44 @@ namespace NadekoBot.Extensions
action(element); action(element);
} }
} }
//http://www.dotnetperls.com/levenshtein
public static int LevenshteinDistance(this string s, string t) {
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
// Step 1
if (n == 0) {
return m;
}
if (m == 0) {
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i++) {
}
for (int j = 0; j <= m; d[0, j] = j++) {
}
// Step 3
for (int i = 1; i <= n; i++) {
//Step 4
for (int j = 1; j <= m; j++) {
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
} }
} }

View File

@ -204,7 +204,7 @@ namespace NadekoBot
return true; return true;
} }
int levDistance = ComputeLevenshteinDistance(guess, answer); int levDistance = guess.LevenshteinDistance(answer);
return Judge(guess.Length, answer.Length, levDistance); return Judge(guess.Length, answer.Length, levDistance);
} }
@ -238,52 +238,6 @@ namespace NadekoBot
return str; return str;
} }
//http://www.dotnetperls.com/levenshtein
private int ComputeLevenshteinDistance(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i++)
{
}
for (int j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (int i = 1; i <= n; i++)
{
//Step 4
for (int j = 1; j <= m; j++)
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
public async void GetHint(MessageEventArgs e) { public async void GetHint(MessageEventArgs e) {
if (timeout != null && !isQuit && stopwatch.ElapsedMilliseconds > 10000) if (timeout != null && !isQuit && stopwatch.ElapsedMilliseconds > 10000)
await e.Send( currentQuestion.Answer.Scramble()); await e.Send( currentQuestion.Answer.Scramble());

View File

@ -13,7 +13,9 @@ namespace NadekoBot
{ {
private Cards cards = null; private Cards cards = null;
public DrawCommand() : base() { } public DrawCommand() : base() {
cards = new Cards();
}
public override Func<CommandEventArgs, Task> DoFunc() => async (e) => public override Func<CommandEventArgs, Task> DoFunc() => async (e) =>
{ {
@ -67,6 +69,17 @@ namespace NadekoBot
.Description("Draws a card from the deck.If you supply number [x], she draws up to 5 cards from the deck.\n**Usage**: $draw [x]") .Description("Draws a card from the deck.If you supply number [x], she draws up to 5 cards from the deck.\n**Usage**: $draw [x]")
.Parameter("count", ParameterType.Optional) .Parameter("count", ParameterType.Optional)
.Do(DoFunc()); .Do(DoFunc());
cgb.CreateCommand("$shuffle")
.Alias("$reshuffle")
.Description("Reshuffles all cards back into the deck.")
.Do(async e => {
if (cards == null) {
cards = new Cards();
}
cards.Restart();
await e.Send("Deck reshuffled.");
});
} }
} }

View File

@ -14,22 +14,25 @@ namespace NadekoBot {
public static class SentencesProvider { public static class SentencesProvider {
internal static string GetRandomSentence() { internal static string GetRandomSentence() {
return "Random ultra long test sentence that i have to type every time."; var data = new ParseQuery<ParseObject>("TypingArticles").FindAsync().Result;
return data.ToList()[(new Random()).Next(0, data.Count())].Get<string>("text");
} }
} }
//todo add leniency and stuff
public class TypingGame { public class TypingGame {
public static float WORD_VALUE { get; } = 4.5f; public static float WORD_VALUE { get; } = 4.5f;
private Channel channel; private Channel channel;
public string currentSentence; public string currentSentence;
public bool IsActive; public bool IsActive;
private Stopwatch sw; private Stopwatch sw;
private List<ulong> finishedUserIds;
public TypingGame(Channel channel) { public TypingGame(Channel channel) {
this.channel = channel; this.channel = channel;
currentSentence = SentencesProvider.GetRandomSentence();
IsActive = false; IsActive = false;
sw = new Stopwatch(); sw = new Stopwatch();
finishedUserIds = new List<ulong>();
} }
public Channel Channell { get; internal set; } public Channel Channell { get; internal set; }
@ -37,6 +40,7 @@ namespace NadekoBot {
internal async Task<bool> Stop() { internal async Task<bool> Stop() {
if (!IsActive) return false; if (!IsActive) return false;
NadekoBot.client.MessageReceived -= AnswerReceived; NadekoBot.client.MessageReceived -= AnswerReceived;
finishedUserIds.Clear();
IsActive = false; IsActive = false;
sw.Stop(); sw.Stop();
sw.Reset(); sw.Reset();
@ -45,22 +49,28 @@ namespace NadekoBot {
} }
internal async Task Start() { internal async Task Start() {
if (IsActive) return; // can't start running game
IsActive = true; IsActive = true;
currentSentence = SentencesProvider.GetRandomSentence();
int i = (int)(currentSentence.Length / WORD_VALUE * 1.7f);
await channel.SendMessage($":clock2: Next contest will last for {i} seconds. Type the bolded text as fast as you can.");
var msg = await channel.SendMessage("Starting new typing contest in **3**..."); var msg = await channel.SendMessage("Starting new typing contest in **3**...");
await Task.Delay(1000); await Task.Delay(1000);
await msg.Edit("Starting new typing contest in **2**..."); await msg.Edit("Starting new typing contest in **2**...");
await Task.Delay(1000); await Task.Delay(1000);
await msg.Edit("Starting new typing contest in **1**..."); await msg.Edit("Starting new typing contest in **1**...");
await Task.Delay(1000); await Task.Delay(1000);
await msg.Edit($"**{currentSentence}**"); await msg.Edit($":book:**{currentSentence}**:book:");
sw.Start(); sw.Start();
HandleAnswers(); HandleAnswers();
int i = (int)(currentSentence.Length / WORD_VALUE * 1.7f);
while (i > 0) { while (i > 0) {
await Task.Delay(1000); await Task.Delay(1000);
i--; i--;
if (!IsActive) if (!IsActive)
break; return;
} }
await Stop(); await Stop();
@ -76,10 +86,20 @@ namespace NadekoBot {
var guess = e.Message.RawText; var guess = e.Message.RawText;
if (currentSentence == guess) { var distance = currentSentence.LevenshteinDistance(guess);
await channel.Send($"{e.User.Mention} finished in **{sw.Elapsed.Seconds}** seconds, **{ currentSentence.Length / TypingGame.WORD_VALUE / sw.Elapsed.Seconds * 60 }** WPM!"); var decision = Judge(distance, guess.Length);
if (decision && !finishedUserIds.Contains(e.User.Id)) {
finishedUserIds.Add(e.User.Id);
await channel.Send($"{e.User.Mention} finished in **{sw.Elapsed.Seconds}** seconds with { distance } errors, **{ currentSentence.Length / TypingGame.WORD_VALUE / sw.Elapsed.Seconds * 60 }** WPM!");
if (finishedUserIds.Count % 2 == 0) {
await e.Send($":exclamation: `A lot of people finished, here is the text for those still typing:`\n\n:book:**{currentSentence}**:book:");
}
} }
} }
private bool Judge(int errors, int textLength) => errors <= textLength / 25;
} }
class SpeedTyping : DiscordCommand { class SpeedTyping : DiscordCommand {
@ -124,6 +144,20 @@ namespace NadekoBot {
cgb.CreateCommand("typestop") cgb.CreateCommand("typestop")
.Description("Stops a typing contest on the current channel.") .Description("Stops a typing contest on the current channel.")
.Do(QuitFunc()); .Do(QuitFunc());
cgb.CreateCommand("typeadd")
.Description("Adds a new article to the typing contest. Owner only.")
.Parameter("text",ParameterType.Unparsed)
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID || e.GetArg("text") == null) return;
var obj = new ParseObject("TypingArticles");
obj["text"] = e.GetArg("text");
await obj.SaveAsync();
await e.Send("Added new typing article.");
});
//todo add user submissions
} }
} }
} }

View File

@ -8,6 +8,7 @@ using System.Timers;
using NadekoBot.Extensions; using NadekoBot.Extensions;
using System.Threading.Tasks; using System.Threading.Tasks;
using NadekoBot.Commands; using NadekoBot.Commands;
using System.IO;
namespace NadekoBot.Modules namespace NadekoBot.Modules
{ {
@ -335,7 +336,6 @@ namespace NadekoBot.Modules
//await e.Send("```\n" + e.User.ServerPermissions.+"\n```"); //await e.Send("```\n" + e.User.ServerPermissions.+"\n```");
}); });
//todo maybe add .opencomms and then make send always send to that user?
Server commsServer = null; Server commsServer = null;
User commsUser = null; User commsUser = null;
@ -372,8 +372,38 @@ namespace NadekoBot.Modules
await e.Send("Sending failed."); await e.Send("Sending failed.");
} }
}); });
/*
cgb.CreateCommand(".jsontype")
.Do(async e => {
Newtonsoft.Json.Linq.JArray data = Newtonsoft.Json.Linq.JArray.Parse(File.ReadAllText("data.json"));
if (data == null || data.Count == 0) return;
var wer = data.Where(jt => jt["Description"].ToString().Length > 120);
var list = wer.Select(jt => {
var obj = new Parse.ParseObject("TypingArticles");
obj["text"] = jt["Description"].ToString();
return obj;
});
await Parse.ParseObject.SaveAllAsync(list);
await e.Send("saved to parse");
}); });
cgb.CreateCommand(".repeat")
.Do(async e => {
if (e.User.Id != NadekoBot.OwnerID) return;
string[] notifs = { "Admin use .bye .greet", "Unstable - fixing", "fixing ~ani, ~mang", "join NadekoLog server", "-h is help, .stats",};
int i = notifs.Length;
while (true) {
await e.Channel.SendMessage($".setgame {notifs[--i]}");
await Task.Delay(20000);
if (i == 0) i = notifs.Length;
}
});
*/
});
} }
bool announcingGreet = false; bool announcingGreet = false;

View File

@ -486,9 +486,10 @@ namespace NadekoBot.Modules
}); });
cgb.CreateCommand("dump") cgb.CreateCommand("dump")
.Description("Dumps all of the invites it can to dump.txt") .Description("Dumps all of the invites it can to dump.txt.** Owner Only.**")
.Do(async e => .Do(async e =>
{ {
if (NadekoBot.OwnerID != e.User.Id) return;
int i = 0; int i = 0;
int j = 0; int j = 0;
string invites = ""; string invites = "";

View File

@ -103,6 +103,27 @@ namespace NadekoBot.Modules
await e.Send("This feature is being reconstructed."); await e.Send("This feature is being reconstructed.");
}); });
cgb.CreateCommand("~hentai")
.Description("Shows a random image from danbooru with a given tag. Tag is optional but preffered.\n**Usage**: ~hentai yuri")
.Parameter("tag", ParameterType.Unparsed)
.Do(async e => {
try {
var rng = new Random();
var tag = e.GetArg("tag");
if (tag == "loli") //loli doesn't work for some reason atm
tag = "flat_chest";
var webpage = MakeRequestAndGetResponse($"http://danbooru.donmai.us/posts?page={ rng.Next(0, 30) }&tags={ tag }");
var matches = Regex.Matches(webpage, "data-large-file-url=\"(?<id>.*)\"");
await e.Send($"http://danbooru.donmai.us{ matches[rng.Next(0, matches.Count)].Groups["id"].Value }".ShortenUrl());
} catch (Exception) {
await e.Send("Error ;(");
}
});
cgb.CreateCommand("lmgtfy") cgb.CreateCommand("lmgtfy")
.Description("Google something for an idiot.") .Description("Google something for an idiot.")
.Parameter("ffs", ParameterType.Unparsed) .Parameter("ffs", ParameterType.Unparsed)
@ -113,12 +134,15 @@ namespace NadekoBot.Modules
}); });
} }
public static string MakeRequestAndGetResponse(string v) =>
new StreamReader(((HttpWebRequest)WebRequest.Create(v)).GetResponse().GetResponseStream()).ReadToEnd();
private string token = ""; private string token = "";
private AnimeResult GetAnimeQueryResultLink(string query) private AnimeResult GetAnimeQueryResultLink(string query)
{ {
try try
{ {
var cl = new RestSharp.RestClient("https://anilist.co/api"); var cl = new RestSharp.RestClient("http://anilist.co/api");
var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST); var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST);
RefreshToken(); RefreshToken();
@ -144,7 +168,7 @@ namespace NadekoBot.Modules
{ {
RefreshToken(); RefreshToken();
var cl = new RestSharp.RestClient("https://anilist.co/api"); var cl = new RestSharp.RestClient("http://anilist.co/api");
var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST); var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST);
rq = new RestSharp.RestRequest("/manga/search/"+Uri.EscapeUriString(query)); rq = new RestSharp.RestRequest("/manga/search/"+Uri.EscapeUriString(query));
rq.AddParameter("access_token", token); rq.AddParameter("access_token", token);
@ -164,12 +188,19 @@ namespace NadekoBot.Modules
private void RefreshToken() private void RefreshToken()
{ {
var cl = new RestSharp.RestClient("https://anilist.co/api"); var cl = new RestSharp.RestClient("http://anilist.co/api");
var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST); var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST);
rq.AddParameter("grant_type", "client_credentials"); rq.AddParameter("grant_type", "client_credentials");
rq.AddParameter("client_id", "kwoth-w0ki9"); rq.AddParameter("client_id", "kwoth-w0ki9");
rq.AddParameter("client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"); rq.AddParameter("client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z");
token = JObject.Parse(cl.Execute(rq).Content)["access_token"].ToString(); var exec = cl.Execute(rq);
/*
Console.WriteLine($"Server gave me content: { exec.Content }\n{ exec.ResponseStatus } -> {exec.ErrorMessage} ");
Console.WriteLine($"Err exception: {exec.ErrorException}");
Console.WriteLine($"Inner: {exec.ErrorException.InnerException}");
*/
token = JObject.Parse(exec.Content)["access_token"].ToString();
} }
private static async Task<bool> ValidateQuery(Discord.Channel ch,string query) { private static async Task<bool> ValidateQuery(Discord.Channel ch,string query) {

View File

@ -84,7 +84,6 @@ namespace NadekoBot
public static void DEBUG_LOG(string text) { public static void DEBUG_LOG(string text) {
#pragma warning disable CS4014 #pragma warning disable CS4014
//NadekoBot.client.GetChannel(119365591852122112).Send(text); //NadekoBot.client.GetChannel(119365591852122112).Send(text);
//TODO YOU MIGHT WANT TO CHANGE THIS TO LOOK LIKE THE LINE ABOVE
Console.WriteLine(text); Console.WriteLine(text);
#pragma warning restore CS4014 #pragma warning restore CS4014
} }

View File

@ -24,7 +24,6 @@ In your bin/debug folder (or next to your exe), you must have a file called 'cre
} }
``` ```
##### You can omit: ##### You can omit:
- Parse keys if you don't want logging
- googleAPIKey if you don't want music - googleAPIKey if you don't want music
- TrelloAppKey if you don't need trello notifications - TrelloAppKey if you don't need trello notifications
- ForwardMessages if you don't want bot PM messages to be redirected to you - ForwardMessages if you don't want bot PM messages to be redirected to you
@ -34,6 +33,8 @@ In your bin/debug folder (or next to your exe), you must have a file called 'cre
"BotMention":"<@bot_id>", "BotMention":"<@bot_id>",
"Password":"bot_password", "Password":"bot_password",
"OwnerID":123123123123, "OwnerID":123123123123,
"ParseID":"parse_app_id",
"ParseKey":"parse_api_key",
} }
``` ```
- BotMention(bot\_id) and OwnerID are **NOT** names of the owner and the bot. If you do not know the id of your bot, put 2 random numbers in those fields, run the bot and do `.uid @MyBotName` - that will give you your bot\_id, do the same for yourself `.uid @MyName` and copy the numbers in their respective fields. - BotMention(bot\_id) and OwnerID are **NOT** names of the owner and the bot. If you do not know the id of your bot, put 2 random numbers in those fields, run the bot and do `.uid @MyBotName` - that will give you your bot\_id, do the same for yourself `.uid @MyName` and copy the numbers in their respective fields.

364
scripts/psychology-10.json Normal file
View File

@ -0,0 +1,364 @@
[
{
"Title":"The Gender of Psychology",
"Description":"This book addresses the diversity of psychological knowledge and practice through the lens of gender."
},
{
"Title":"Unto Others: The Evolution and Psychology of Unselfish",
"Description":"In Unto Others philosopher Elliott Sober and biologist David Sloan Wilson demonstrate once and for all that unselfish behavior is in fact an important feature of both biological and human nature."
},
{
"Title":"Forensic and Legal Psychology",
"Description":"Using research in clinical, cognitive, developmental, and social psychology, Forensic and Legal Psychology shows how psychological science can enhance the gathering and presentation of evidence, improve legal decision-making, prevent crime,"
},
{
"Title":"International Handbook of Psychology in Education",
"Description":"Suitable for researchers, practitioners and advisers working in the fields of psychology and education, this title presents an overview of the research within the domain of psychology of education."
},
{
"Title":"Handbook of Personality Psychology",
"Description":"This comprehensive reference work on personality psychology discusses the development and measurement of personality, biological and social determinants, dynamic personality processes, the personality's relation to the self, and personality"
},
{
"Title":"Dictionary of Theories, Laws, and Concepts in Psychology",
"Description":"A fully cross-referenced and source-referenced dictionary which gives definitions of psychological terms as well as the history, critique, and relevant references for the terms."
},
{
"Title":"Essays on Plato's Psychology",
"Description":"With a comprehensive introduction to the major issues of Plato's psychology and an up-to-date bibliography of work on the relevant issues, this much-needed text makes the study of Plato's psychology accessible to scholars in ancient Greek"
},
{
"Title":"Psychology Statistics For Dummies",
"Description":"As an alternative to typical, lead-heavy statistics texts or supplements to assigned course reading, this is one book psychology students won't want to be without."
},
{
"Title":"Doing Psychology Experiments",
"Description":"David W. Martin’s unique blend of informality, humor, clear instruction, and solid scholarship make this concise text a popular choice for research methods courses in psychology."
},
{
"Title":"A Handbook of Research Methods for Clinical and Health",
"Description":"For both undergraduate and postgraduate students, the book will be essential in making them aware of the full range of techniques available to them, helping them to design scientifically rigorous experiments."
},
{
"Title":"A History of Psychology",
"Description":"First published in 2002. Routledge is an imprint of Taylor & Francis, an informa company."
},
{
"Title":"An Introduction to the Psychology of Religion",
"Description":"The third edition of this successful book, which applies the science of psychology to problems of religion. Dr Thouless explores such questions as: why do people believe? Why are their beliefs often held with irrational strength?"
},
{
"Title":"Psychology of Champions: How to Win at Sports and Life",
"Description":"In this unprecedented book, two psychologist researchers interview sports legends and super-athletes across sports to explain the thinking that powers stellar performers, pushing them to amazing and historic successes."
},
{
"Title":"The Psychology of Humor: An Integrative Approach",
"Description":"This is a singly authored monograph that provides in one source, a summary of information researchers might wish to know about research into the psychology of humor."
},
{
"Title":"Psychology and Deterrence",
"Description":"Now available in paperback, Psychology and Deterrence reveals deterrence strategy's hidden and generally simplistic assumptions about the nature of power and aggression, threat and response, and calculation and behavior in the international"
},
{
"Title":"Psychology: An International Perspective",
"Description":"Unlike typical American texts, this book provides an international approach to introductory psychology, providing comprehensive and lively coverage of current research from a global perspective, including the UK, Germany, Scandinavia,"
},
{
"Title":"Psychology, Briefer Course",
"Description":"Despite its title, 'Psychology: Briefer Course' is more than a simple condensation of the great 'Principles of Psychology."
},
{
"Title":"Psychology, Seventh Edition (High School)",
"Description":"This new edition continues the story of psychology with added research and enhanced content from the most dynamic areas of the field—cognition, gender and diversity studies, neuroscience and more, while at the same time using the most"
},
{
"Title":"Psychology of Russia: Past, Present, Future",
"Description":"This book is for all psychologists and for readers whose interest in Russia exceeds their interest in psychology. Readers of this book will quickly discover a new world of thought."
},
{
"Title":"Barron's AP Psychology",
"Description":"Provides information on scoring and structure of the test, offers tips on test-taking strategies, and includes practice examinations and subject review."
},
{
"Title":"Psychology for Inclusive Education: New Directions in",
"Description":"International in focus and at the very cutting edge of the field, this is essential reading for all those interested in the development of inclusive education."
},
{
"Title":"Applied Psychology: Putting Theory Into Practice",
"Description":"Applied Psychology: Putting theory into practice demonstrates how psychology theory is applied in the real world."
},
{
"Title":"The Psychology of Science: A Reconnaissance",
"Description":"' This eBook edition contains the complete 168 page text of the original 1966 hardcover edition. Contents: Preface by Abraham H. Maslow Acknowledgments 1. Mechanistic and Humanistic Science 2."
},
{
"Title":"Filipino American Psychology: A Handbook of Theory,",
"Description":"This book is the first of its kind and aims to promote visibility of this invisible group, so that 2.4 million Filipino Americans will have their voices heard."
},
{
"Title":"The Psychology of Visual Illusion",
"Description":"Well-rounded perspective on the ambiguities of visual display emphasizes geometrical optical illusions: framing and contrast effects, distortion of angles and direction, and apparent 'movement' of images. 240 drawings. 1972 edition."
},
{
"Title":"The Psychology of Women",
"Description":"This highly respected text offers students an enjoyable, extraordinarily well-written introduction to the psychology of women with an up-to-date examination of the field and comprehensive coverage of topics."
},
,
{
"Title":"Psychology and Race",
"Description":"' Psychology and Race is divided into two major parts. The first half of the book looks at the interracial situation itself."
},
{
"Title":"Psychology for A-Level",
"Description":"'Precisely targeted at AQA A Level Psychology, specification A. It will also be of interest to those who are new to psychology, and who want to get a flavour of the kinds of topics in which psychologists are interested'--Preface, p. vii."
},
{
"Title":"Biological Psychology",
"Description":"Updated with new topics, examples, and recent research findings--and supported by new online bio-labs, part of the strongest media package yet--this text speaks to today’s students and instructors."
},
{
"Title":"Psychology: Concepts & Connections",
"Description":"The theme of this book is applying theories and research to learning and to contemporary life."
},
{
"Title":"The Psychology of Adoption",
"Description":"In this volume David Brodzinsky, who has conducted one of the nation's largest studies of adopted children, and Marshall Schechter, a noted child psychiatrist who has been involved with adoption related issues for over forty years, have"
},
{
"Title":"Psychology and Adult Learning",
"Description":"This new edition is thoroughly revised and updated in light of the impact of globalising processes and the application of new information technologies, and the influence of postmodernism on psychology."
},
{
"Title":"Gestalt Psychology: An Introduction to New Concepts in",
"Description":"The general reader, if he looks to psychology for something more than entertainment or practical advice, will discover in this book a storehouse of searching criticism and brilliant suggestions from the pen of a rare thinker, and one who"
},
{
"Title":"The Psychology of Goals",
"Description":"Bringing together leading authorities, this tightly edited volume reviews the breadth of current knowledge about goals and their key role in human behavior."
},
{
"Title":"Metaphors in the History of Psychology",
"Description":"Through the identification of these metaphors, the contributors to this volume have provided a remarkably useful guide to the history, current orientations, and future prospects of modern psychology."
},
{
"Title":"Abnormal Psychology: An Integrative Approach",
"Description":"ABNORMAL PSYCHOLOGY: AN INTEGRATIVE APPROACH, Seventh Edition, is the perfect book to help you succeed in your abnormal psychology course!"
},
{
"Title":"Art and Visual Perception: A Psychology of the Creative Eye",
"Description":"Gestalt theory and the psychology of visual perception form the basis for an analysis of art and its basic elements"
},
{
"Title":"Psychology & Christianity: Five Views",
"Description":"This revised edition of a widely appreciated text now presents five models for understanding the relationship between psychology and Christianity."
},
{
"Title":"The Psychology of Hope: You Can Get There from Here",
"Description":"Why do some people lead positive, hope-filled lives, while others wallow in pessimism? In The Psychology of Hope, a professor of psychology reveals the specific character traits that produce highly hopeful individuals."
},
{
"Title":"Perspectives on Psychology",
"Description":"This is a title in the modular 'Principles in Psychology Series', designed for A-level and other introductory courses, aiming to provide students embarking on psychology courses with the necessary background and context."
},
{
"Title":"Psychology the Easy Way",
"Description":"Material is presented in a way that makes these books ideal as self-teaching guides, but Easy Way titles are also preferred by many teachers as supplements to classroom textbooks."
},
{
"Title":"Ethics in Psychology: Professional Standards and Cases",
"Description":"In this book, their main intent is to present the full range of contemporary ethical issues in psychology as not only relevant and intriguing, but also as integral and unavoidable aspects of the profession."
},
{
"Title":"Psychology Gets in the Game: Sport, Mind, and Behavior,",
"Description":"The essays collected in this volume tell the stories not only of these psychologists and their subjects but of the social and academic context that surrounded them, shaping and being shaped by their ideas'--Provided by publisher."
},
{
"Title":"Psychology for Physical Educators: Student in Focus",
"Description":"This updated edition focuses on attitude and motivation as important aspects of the physical education curriculum, illustrating practical ideas and pedagogical solutions for any PE setting."
},
{
"Title":"The Psychology of Leadership: New Perspectives and Research",
"Description":"In this book, some of the world's leading scholars come together to describe their thinking and research on the topic of the psychology of leadership."
},
{
"Title":"The Psychology of Interpersonal Relations",
"Description":"As the title suggests, this book examines the psychology of interpersonal relations. In the context of this book, the term 'interpersonal relations' denotes relations between a few, usually between two, people."
},
{
"Title":"Applied Psychology",
"Description":"The chapters on Counselling Psychology and Teaching Psychology are available online via the Student Companion Site at: http://tinyurl.com/c3ztvtj The text is written to be accessible to Level 1 Introductory Psychology students, and also to"
},
{
"Title":"Psychology",
"Description":"An exciting read for anyone interested in psychology and research; because of its comprehensive appendix, glossary, and reference section, this book is a must-have desk reference for psychologists and others in the field."
},
{
"Title":"The Psychology of Music",
"Description":"On interpreting musical phenomena in terms of mental function"
},
{
"Title":"Abnormal Psychology",
"Description":"Ron Comer's Abnormal Psychology continues to captivate students with its integrated coverage of theory, diagnosis, and treatment, its inclusive wide-ranging cross-cultural perspective, and its compassionate emphasis on the real impact of"
},
{
"Title":"The Psychology of Food Choice",
"Description":"This book brings together theory, research and applications from psychology and behavioural sciences applied to dietary behaviour."
},
{
"Title":"Psychology: brain, behavior, & culture",
"Description":"Rather than present psychological science as a series of facts for memorization, this book takes readers on a psychological journey that uncovers things they didn't know or new ways of thinking about things they did know."
},
{
"Title":"A Brief History of Psychology",
"Description":"Due to its brevity and engaging style, the book is often used in introductory courses to introduce students to the field. The enormous index and substantial glossary make this volume a useful desk reference for the entire field."
},
{
"Title":"Psychology AS: The Complete Companion",
"Description":"Presented in double-page spreads this book written to the average AS ability level, provides information on psychology in bite-sized chunks with learning and revision features."
},
{
"Title":"The Psychology Book: From Shamanism to Cutting-Edge",
"Description":"Lavishly illustrated, this new addition in the Sterling's Milestones series chronicles the history of psychology through 250 groundbreaking events, theories, publications, experiments and discoveries."
},
{
"Title":"The Psychology Book",
"Description":"All the big ideas, simply explained - an innovative and accessible guide to the study of human nature The Psychology Book clearly explains more than 100 groundbreaking ideas in this fascinating field of science."
},
{
"Title":"Handbook of Positive Psychology",
"Description":"' The Handbook of Positive Psychology provides a forum for a more positive view of the human condition. In its pages, readers are treated to an analysis of what the foremost experts believe to be the fundamental strengths of humankind."
},
{
"Title":"Psychology of Sustainable Development",
"Description":"With contributions from an international team of policy shapers and makers, the book will be an important reference for environmental, developmental, social, and organizational psychologists, in addition to other social scientists concerned"
},
{
"Title":"An Introduction to the History of Psychology",
"Description":"In this Fifth Edition, B.R. Hergenhahn demonstrates that most of the concerns of contemporary psychologists are manifestations of themes that have been part of psychology for hundreds-or even thousands-of years."
},
{
"Title":"Careers in Psychology: Opportunities in a Changing World",
"Description":"This text addresses the growing need among students and faculty for information about the careers available in psychology at the bachelor’s and graduate level."
},
{
"Title":"Philosophy of Psychology",
"Description":"This is the story of the clattering of elevated subways and the cacophony of crowded neighborhoods, the heady optimism of industrial progress and the despair of economic recession, and the vibrancy of ethnic cultures and the resilience of"
},
{
"Title":"The Psychology of Risk Taking Behavior",
"Description":"This book aims to help the reader to understand what motivates people to engage in risk taking behavior, such as participating in traffic, sports, financial investments, or courtship."
},
{
"Title":"The Nazi Doctors: Medical Killing and the Psychology of",
"Description":"This book explores the psychological conditions that promote the human potential for evil, relating medical killing to broader principles of doubling and genocide"
},
{
"Title":"The Body and Psychology",
"Description":"The material in this volume was previously published as a Special Issue of th"
},
,
{
"Title":"Introduction to Psychology: Gateways to Mind and Behavior",
"Description":"Important Notice: Media content referenced within the product description or the product text may not be available in the ebook version."
},
{
"Title":"Psychology of Time",
"Description":"Basic Structure The book would contain 14 or 15 chapters of roughly 12 000 words. The exact final number of chapters would depend on further discussions with you about the book's basic structure."
},
{
"Title":"Handbook of Psychology, Experimental Psychology",
"Description":"Includes established theories and cutting-edge developments. Presents the work of an international group of experts. Presents the nature, origin, implications, and future course of major unresolved issues in the area."
},
{
"Title":"Study Guide for Psychology, Seventh Edition",
"Description":"This new edition continues the story of psychology with added research and enhanced content from the most dynamic areas of the field--cognition, gender and diversity studies, neuroscience and more, while at the same time using the most"
},
{
"Title":"Culture and Psychology",
"Description":"In addition, the text encourages students to question traditionally held beliefs and theories as and their relevance to different cultural groups today."
},
{
"Title":"Exploring the Psychology of Interest",
"Description":"The most comprehensive work of its kind, Exploring the Psychology of Interest will be a valuable resource for student and professional researchers in cognitive, social, and developmental psychology."
},
{
"Title":"Handbook of Adolescent Psychology",
"Description":"The study of adolescence in the field of psychology has grown tremendously over the last two decades, necessitating a comprehensive and up-to-date revision of this seminal work."
},
,
{
"Title":"The Psychology of Diplomacy",
"Description":"World class clinicians, researchers, and activists present the psychological dimensions to diplomacy drawn from examples set in the United Nations, Camp David, the Middle East, Japan, South Africa, and elsewhere."
},
{
"Title":"The Psychology of Social Class",
"Description":"By addressing differences in social class, the book broadens the perspective of social psychological research to examine such topics as the effect of achievement motivation and other personality variables on social mobility and the effect"
},
{
"Title":"Applied Psychology: Current Issues and New Directions",
"Description":"Key features of this book: - Consistently pedagogical throughout - chapter summaries, questions for reflection and discussion and annotated further reading in every chapter - Comprehensive coverage - all areas of applied psychology included"
},
{
"Title":"Popular Psychology: An Encyclopedia",
"Description":"Entries cover a variety of topics in the field of popular psychology, including acupuncture, emotional intelligence, brainwashing, chemical inbalance, and seasonal affective disorder."
},
{
"Title":"Advanced Psychology: Applications, Issues and Perspectives",
"Description":"The second of two books, Advanced Psychology covers units 4 to 6 for the second year at Advanced Level."
},
{
"Title":"Mindset: The New Psychology of Success",
"Description":"This is a book that can change your life, as its ideas have changed mine.”—Robert J. Sternberg, IBM Professor of Education and Psychology at Yale University, director of the PACE Center of Yale University, and author of Successful"
},
{
"Title":"E-Z Psychology",
"Description":"This book covers material as it is taught on a college-101 level."
},
{
"Title":"Myers' Psychology for AP*",
"Description":"Already The Bestselling AP* Psychology Author, Myers Writes His First Exclusive AP* Psych Text Watch Dave G. Myers introduce this new text here."
},
{
"Title":"Psychology and Health",
"Description":"Part of a series of textbooks which have been written to support A levels in psychology. The books use real life applications to make theories come alive for students and teach them what they need to know."
},
{
"Title":"Applying Psychology in Business: The Handbook for Managers",
"Description":"To learn more about Rowman & Littlefield titles please visit us at www.rowmanlittlefield.com."
},
{
"Title":"Influence",
"Description":"Influence, the classic book on persuasion, explains the psychology of why people say 'yes'—and how to apply these understandings. Dr. Robert Cialdini is the seminal expert in the rapidly expanding field of influence and persuasion."
},
{
"Title":"Psychology and Policing",
"Description":"The book should draw attention to the often unrecognized and valuable contribution that mainstream psychology can make to the knowledge base underpinning a wide variety of policing practices."
},
{
"Title":"Applied Psychology: New Frontiers and Rewarding Careers",
"Description":"This book examines how psychological science is, and can be, used to prevent and ameliorate pressing human problems to promote positive social change."
},
{
"Title":"Psychology: Concepts and Applications",
"Description":"Nevid developed the effective teaching devices in this text based on a comprehensive system derived from research on learning and memory as well as his own research on textbook pedagogy."
},
{
"Title":"Foundations of Sport and Exercise Psychology, 6E: ",
"Description":"This text offers both students and new practitioners a comprehensive view of sport and exercise psychology, drawing connections between research and practice and capturing the excitement of the world of sport and exercise."
},
{
"Title":"Biographical Dictionary of Psychology",
"Description":"This Dictionary provides biographical and bibliographical information on over 500 psychologists from all over the world from 1850 to the present day. All branches of psychology and its related disciplines are featured."
},
{
"Title":"Psychology: A Self-Teaching Guide",
"Description":"Frank Bruno explains all the major psychological theories and terms in this book, covering perception, motivation, thinking, personality, sensation, intelligence, research methods, and much more."
},
{
"Title":"A Dictionary of Psychology",
"Description":"Entries are extensively cross-referenced for ease of use, and cover word origins and derivations as well as definitions. Over 80 illustrations complement the text."
},
{
"Title":"An Intellectual History of Psychology",
"Description":"Invaluable as a text for students and as a stimulating and insightful overview for scholars and practicing psychologists, this volume can be read either as a history of psychology in both its philosophical and aspiring scientific periods or"
}]

View File

@ -0,0 +1,91 @@
use strict;
use warnings;
use HTML::Entities;
my $url = 'https://www.google.com/search?tbm=bks&';
my $userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36';
print "\n\nPlease enter the query you would like to scrape.\n";
my $query = <STDIN>;
$query =~ s/^\s+|\s+$//g;
print "\nHow many pages?\n";
my $maxPages = <STDIN>;
$maxPages =~ s/^\s+|\s+$//g;
print "\nOutput folder?\n";
my $folder = <STDIN>;
$folder =~ s/^\s+|(\\|\/)?\s+$//g;
my $file = "$folder/$query-$maxPages.json";
my %hash;
print "\nFetching...\n";
for(my $i = 0; $i < $maxPages; $i++)
{
my $fullUrl = $url . "q=$query";
if($i != 0)
{
$fullUrl .= "&start=$i" .0;
}
print "Getting this: $fullUrl\n";
my $html = `curl -A "$userAgent" -k -L "$fullUrl"`;
#print "HTML: $html";
#<STDIN>;
#Disclaimer: kids, don't parse HTML like this at home
#it's bad for your health/sanity ;)
my @sections = split /div class="rc"/, $html;
shift @sections;
for my $section (@sections)
{
my $title;
my $desc;
if($section =~ /<h3\s+class="r">\s*<a\s+href="[^"]+">([^<]+)/)
{
$title = clean($1);
}
if($section =~ /<span\s+class="st">([^<]+)/)
{
$desc = clean($1);
}
print "\nTITLE:$title:\n\nDESC:$desc:\n";
$hash{$title} = $desc;
}
#Google is really quick to shut down botting.
sleep 3;
}
open FILE, ">:utf8", $file or die "Could not open file to write $!";
print FILE "[\n";
my $first = 1;
for my $title (keys %hash)
{
if($first)
{
$first = 0;
}
else
{
print FILE ",\n";
}
next unless (defined $title and defined $hash{$title});
next unless ($title ne '' and $hash{$title} ne '');
print FILE "\t{\n";
print FILE "\t\t\"Title\":\"$title\",\n";
print FILE "\t\t\"Description\":\"$hash{$title}\"\n";
print FILE "\t}";
}
print FILE "\n]";
close FILE;
sub clean
{
my $str = $_[0];
$str = decode_entities($str);
$str =~ s/\s+\.\.\.$//;
$str =~ s/"/'/g;
return $str;
}