public string LaunchBatches(int numHITSPerTask, int batchSize, string url, Dictionary <string, object> HitParams, int noTasks, out List <string> hitIDs) { hitIDs = new List <string>(); //first check if there is sufficient money double moneyInAccount = hit.getAccountBalance(); double moneyRequired = (double)HitParams["Reward"] * noTasks; if (moneyRequired > moneyInAccount) { return("INSUFFICIENT_FUNDS_TO_LAUNCH_TASK"); } int noRounds = (int)Math.Floor((double)(noTasks * numHITSPerTask) / (double)batchSize); int reminder = noTasks * numHITSPerTask - noRounds * batchSize; HitParams["MaxHITs"] = batchSize; //ActiveMTurkHitsListAccess HITList = new ActiveMTurkHitsListAccess(); for (int i = 0; i < noRounds; i++) { HIT h1 = hit.CreateExternalHIT(url, HitParams); hitIDs.Add(h1.HITId); } if (reminder > 0) { HitParams["MaxHITs"] = reminder; HIT h = hit.CreateExternalHIT(url, HitParams); hitIDs.Add(h.HITId); } return("SUCCESS"); }
public int getNumTasksRemaining(string HITId) { HIT h = client.GetHIT(HITId); int available = h.NumberOfAssignmentsAvailable; int pending = h.NumberOfAssignmentsPending; int remaining = available + pending; return(remaining); }
public void blow() { Instantiate(impacteffect, transform.position, transform.rotation); Vector3 explosionpos = equip.transform.position; Collider[] colliders = Physics.OverlapSphere(explosionpos, scriptableobject.explosionRange); foreach (Collider HIT in colliders) { Rigidbody rb = HIT.GetComponent <Rigidbody>(); if (!HIT.CompareTag("Player")) { if (rb != null && (!HIT.CompareTag("explosiveammo") && !HIT.CompareTag("bullet") && !HIT.CompareTag("explosivebarrel"))) { rb.AddExplosionForce(scriptableobject.powerOfExplosion, explosionpos, scriptableobject.explosionRange, scriptableobject.upPowerExplosion, ForceMode.Impulse); } } if (gameObject.CompareTag("explosivebarrel") && HIT.gameObject.CompareTag("explosiveammo")) { equip = this.gameObject; Instantiate(explosiondamage, transform.position, transform.rotation); } if (HIT.CompareTag("enemy")) { Instantiate(explosiondamage, transform.position, transform.rotation); } if (HIT.CompareTag("Player")) { rb.AddExplosionForce(scriptableobject.playerExplosionForce, explosionpos, scriptableobject.explosionRange, scriptableobject.playerUpForce, ForceMode.Impulse); } if (gameObject.name == "grenadelauncherammo(Clone)") { Destroy(gameObject); } if (gameObject.name == "Tankammo(Clone)") { Destroy(gameObject); } if (gameObject.name == "Explosivebarrel") { Destroy(gameObject); } if (gameObject.name == "barreldamage(Clone)") { Destroy(gameObject); } } }
public bool GetHit(int x, int y, HIT hit) { if (x < 0 || m_Width[1] <= x) { return(((HIT)0x0f & hit) != 0); } if (y < 0) { return(GetHit(x, 0, hit)); } if (y >= m_Height[1]) { return(GetHit(x, m_Height[1] - 1, hit)); } return((m_Hit[GetMapData(1, x, y)] & hit) != 0); }
private void CheckHit() { RaycastHit2D[] hits; hits = Physics2D.CircleCastAll(bullet.cachedTransform.position, bullet.data.size, Vector2.zero, 0, layerMask); for (int i = 0; i < hits.Length; i++) { //Debug.Log("!!!!!!!!!!hit " + hits[i].collider.name); HIT result = Hit(hits[i].collider); switch (result) { case HIT.ENEMY: //Debug.Log("Hit Enemy:" + name); if (pierce < 99999) { pierce--; } if (!isSplash) { CheckPierce(); } break; case HIT.WALL: //Debug.Log("Hit Wall:" + name + ", " + hits[i].collider.name + " " + hits[i].point); if (!isHitableWall) { pierce = 0; if (!isSplash) { CheckPierce(); } } break; //case HIT.FRIENDLY: // Debug.Log("Hit Friendly:"+name); // break; //case HIT.ETC: // Debug.Log("Hit ETC:" + name); // break; } } if (isSplash) { CheckPierce(); } }
void blow() { Vector3 explosionpos = equip.transform.position; Collider[] colliders = Physics.OverlapSphere(explosionpos, radius); foreach (Collider HIT in colliders) { Rigidbody rb = HIT.GetComponent <Rigidbody>(); if (!HIT.CompareTag("Player")) { if (rb != null && !HIT.CompareTag("gun") && !HIT.CompareTag("delete") && !HIT.CompareTag("bullet")) { rb.AddExplosionForce(Power, explosionpos, radius, UpPower, ForceMode.Impulse); } } } }
private void OnTriggerStay2D(Collider2D coll) { //Debug.Log(name + " OnTriggerStay " + coll.name); if (pierce <= 0 && leftDelay > 0) { return; } HIT result = Hit(coll); switch (result) { case HIT.ENEMY: //Debug.Log("Hit Enemy:" + name); if (pierce < 99999) { pierce--; } if (isSplash) { if (pierceCorou == null) { pierceCorou = PierceCorou(); StartCoroutine(pierceCorou); } } else { CheckPierce(); } break; case HIT.WALL: //Debug.Log("Hit Wall:" + name); if (!isHitableWall) { pierce = 0; StartCoroutine(PierceCorou()); } break; } }
public HIT CreateExternalHIT(string url, Dictionary <string, object> HitParams) { String HitType = Default_HitType; String title = (string)HitParams["Title"]; String description = (string)HitParams["TaskDescription"]; String keywords = Default_KeyWords; if (HitParams.ContainsKey("KeyWords")) { keywords = (string)HitParams["KeyWords"]; } /**************************External Question******************/ ExternalQuestion myExtQuestion = new ExternalQuestion(); myExtQuestion.ExternalURL = url; if (HitParams.ContainsKey("FrameHeight")) { myExtQuestion.FrameHeight = HitParams["FrameHeight"].ToString(); } else { myExtQuestion.FrameHeight = Default_FrameHeight.ToString(); } /*********************************************************/ decimal reward = Default_Reward; if (HitParams.ContainsKey("Reward")) { reward = Convert.ToDecimal((double)HitParams["Reward"]); } long assignmentDuration = Default_assignmentDurationInSeconds; if (HitParams.ContainsKey("AssignmentDuration")) { assignmentDuration = (long)Convert.ToInt64(HitParams["AssignmentDuration"]); } long autoApporvalTime = Default_autoApprovalDelayInSeconds; if (HitParams.ContainsKey("AutoApprovalTime")) { autoApporvalTime = (long)Convert.ToInt64(HitParams["AutoApprovalTime"]); } long lifeTime = Default_lifetimeInSeconds; if (HitParams.ContainsKey("AssignmentLifeTime")) { lifeTime = (long)Convert.ToInt64(HitParams["AssignmentLifeTime"]); } int maxAssignments = Default_MaxAssignments; if (HitParams.ContainsKey("MaxHITs")) { maxAssignments = (int)HitParams["MaxHITs"]; } String requesterAnnotation = Default_requesterAnnotation; if (HitParams.ContainsKey("RequesterAnnotation")) { requesterAnnotation = (string)HitParams["RequesterAnnotation"]; } /***************Qualifications***************************************/ List <QualificationRequirement> qualReqs = new List <QualificationRequirement>(); if (HitParams.ContainsKey("Country")) { //setting the qualification requirements QualificationRequirement qualReq = new QualificationRequirement(); qualReq.QualificationTypeId = MTurkSystemQualificationTypes.LocaleQualification; // locale system qual identifier Locale country = new Locale(); country.Country = "US"; qualReq.LocaleValue = country; qualReq.Comparator = Comparator.EqualTo; qualReqs.Add(qualReq); } if (HitParams.ContainsKey("Masters")) { QualificationRequirement qualReq1 = new QualificationRequirement(); if (sandBox) { qualReq1.QualificationTypeId = "2ARFPLSP75KLA8M8DH1HTEQVJT3SY6"; // masters } else { qualReq1.QualificationTypeId = "2F1QJWKUDD8XADTFD2Q0G6UTO95ALH"; // masters } qualReq1.Comparator = Comparator.Exists; qualReqs.Add(qualReq1); } /*if ((string)HitParams["PercentApproved"] == "Masters") * { * QualificationRequirement qualReq1 = new QualificationRequirement(); * qualReq1.QualificationTypeId = "2F1QJWKUDD8XADTFD2Q0G6UTO95ALH"; // masters * qualReq1.Comparator = Comparator.Exists; * qualReqs.Add(qualReq1); * }*/ /****************************************************************/ String[] responseGroup = Default_ResponseGroup; if (HitParams.ContainsKey("ResponseGroup")) { responseGroup = (string[])HitParams["ResponseGroup"]; } /************************Now create a HIT *****************************/ HIT h = client.CreateHIT(HitType, title, description, keywords, myExtQuestion, reward, assignmentDuration, // 1 hour autoApporvalTime, // 15 days lifeTime, // 3 days, maxAssignments, requesterAnnotation, qualReqs, responseGroup); Console.WriteLine("Created HIT: {0} ({1})", h.HITId, client.GetPreviewURL(h.HITTypeId)); return(h); }
/// <summary> /// Initializes a new instance of the <see cref="HITData"/> class. /// </summary> /// <param name="hit">The hit.</param> public HITData(HIT hit) { _hit = hit; }
/// <summary> /// Serializes the HIT in XML format and saves it to the specified file /// </summary> /// <param name="hit">HIT to serialize</param> /// <param name="fileName">Filename to save to</param> public void SerializeHIT(HIT hit, string fileName) { SerializeHIT(hit, fileName, MTurkSerializationFormat.Xml); }
public void SubmitHITVars(HIT.HITThread thread) { if (thread.ObjectVar == null) return; thread.ObjectVar[12] = GetPersonData(VMPersonDataVariable.Gender); }
/// <summary> /// Serializes the HIT in the specified format and saves it to the specified file /// </summary> /// <param name="hit">HIT to serialize</param> /// <param name="fileName">Name of the file.</param> /// <param name="format">The format to use for serialization</param> public void SerializeHIT(HIT hit, string fileName, MTurkSerializationFormat format) { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException("No filename specified to save object to", "fileName"); } using (StreamWriter writer = new StreamWriter(fileName)) { SerializeHIT(hit, writer, format); } }
/// <summary> /// Reads the properties file and sets the properties needed by the HITs. Reads the /// question file. Starts creating the HITs by submitting a work item for each question /// in the question file to the .Net thread pool. /// </summary> public void Start() { // Read the questions from the file questions = File.ReadAllLines(this.QuestionFile); numHits = questions.Length; // Get the properties file and instantiate HIT model object from this file. string hitFile = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, this.PropertiesFile); hitTemplate = client.DeserializeHIT(hitFile, MTurkSerializationFormat.Property); foreach (String question in questions) { // Enqueue the question string as a work item in the thread pool // and pass in a callback method that gets invoked when a thread becomes // available to do work. // // This can be replaced with other Amazon Mechanical Turk functionalities // like DisposeHIT to use the SDK in a multithreaded fashion. if (!ThreadPool.QueueUserWorkItem(new WaitCallback(CreateHitCallback), question )) { Console.WriteLine("Failed to enqueue work item for creation of HITt {0}", question); } } // Since this is a console app, we want to wait for all // work items to be completed before the process exits // In a web app or a windows service app, this would not // be necessary since it is always running. workCompleteEvent.WaitOne(); Console.WriteLine("Finished. Press any key to exit ..."); }
private void ShowWorkerURL(HIT h) { Process.Start(client.GetPreviewURL(h.HITTypeId)); }
/// <summary> /// Creates a new HIT from a populated HIT domain object /// </summary> /// <param name="newHit">The new hit to be created</param> /// <returns>A <see cref="HIT"/> instance with the populated HIT ID</returns> public HIT CreateHIT(HIT newHit) { return CreateHIT( newHit.HITTypeId, newHit.Title, newHit.Description, newHit.Keywords, newHit.Question, newHit.Reward != null ? newHit.Reward.Amount : (decimal?)null, newHit.AssignmentDurationInSecondsSpecified ? newHit.AssignmentDurationInSeconds : (long?)null, newHit.AutoApprovalDelayInSecondsSpecified ? newHit.AutoApprovalDelayInSeconds : (long?)null, newHit.ExpirationSpecified ? (long)(newHit.Expiration-DateTime.Now).TotalSeconds : 0, newHit.MaxAssignmentsSpecified ? newHit.MaxAssignments : (int?)null, newHit.RequesterAnnotation, newHit.QualificationRequirement != null ? new List<QualificationRequirement>(newHit.QualificationRequirement) : null, null); }
/// <summary> /// Serializes the HIT in the specified format and writes it to the specified writer /// </summary> /// <param name="hit">HIT to serialize</param> /// <param name="writer">The output writer.</param> /// <param name="format">The format to use for object serialization</param> public void SerializeHIT(HIT hit, TextWriter writer, MTurkSerializationFormat format) { if (writer == null) { throw new ArgumentNullException("writer", "No text writer specified to serialize object to"); } GetFormatter(format).Format(writer, new HITData(hit)); }
public void Execute(AnalysisExecutionContext context) { _context = context; if (context.Results.Count <= 0) { context.OnExecutionProgress("MechanicalTurk", new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Canceled, 0, 0, 0)); return; } MechanicalTurkSettings settings = context.CustomField as MechanicalTurkSettings; if (settings == null) { settings = new MechanicalTurkSettings(null, 3, new decimal(0.10), 300, 1800, 75); } string key = context.Key; string secret = context.Secret; MTurkConfig config = new MTurkConfig(_serviceURL, key, secret); SimpleClient client = new SimpleClient(config); List <QualificationRequirement> requirements = new List <QualificationRequirement>(); QualificationRequirement sucRequirement = new QualificationRequirement(); sucRequirement.QualificationTypeId = MTurkSystemQualificationTypes.ApprovalRateQualification; sucRequirement.IntegerValueSpecified = true; sucRequirement.IntegerValue = settings.PercentOfSuccess; sucRequirement.Comparator = Comparator.GreaterThanOrEqualTo; requirements.Add(sucRequirement); if (settings.Locale != null) { QualificationRequirement qualReq = new QualificationRequirement(); qualReq.LocaleValue = new Locale() { Country = settings.Locale }; qualReq.Comparator = Comparator.EqualTo; qualReq.QualificationTypeId = MTurkSystemQualificationTypes.LocaleQualification; requirements.Add(qualReq); } string hitType = string.Empty; try { if (context.UseDebugMode) { TimeSpan time = TimeSpan.Zero; hitType = BenchmarkHelper.Invoke(new InvokeBenchmarkHandler(delegate(object state) { return(hitType = client.RegisterHITType("Sentiment analysis", "Judge the sentiment expressed by the following text.", settings.TimeToApprove, settings.TimeToFinish, settings.Reward, "sentiment nlp", requirements)); }), null, out time) as string; Console.WriteLine("MechanicalTurk: HIT type for sentiment analysis has been created. HIT type ID is: {0} Execution time is: {1}", hitType, time.TotalMilliseconds); } else { hitType = client.RegisterHITType("Sentiment analysis", "Judge the sentiment expressed by the following text.", settings.TimeToApprove, settings.TimeToFinish, settings.Reward, "sentiment, nlp", requirements); } NotificationSpecification notification = new NotificationSpecification(); notification.Transport = NotificationTransport.Email; notification.EventType = new EventType[] { EventType.AssignmentReturned }; notification.Destination = settings.Email; notification.Version = "2006-05-05"; if (settings.Email != null) { client.SetHITTypeNotification(hitType, notification, true); } else { notification.Destination = "*****@*****.**"; client.SetHITTypeNotification(hitType, notification, false); } } catch (Exception ex) { AnalysisExecutionProgressEventArgs ea = new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Failed, context.Results.Count, 0, 0); ea.Reason = ex.Message; context.OnExecutionProgress("MechanicalTurk", ea); if (ea.Cancel) { return; } } string questionFile = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "SentimentTemplate.xml"); string template = File.ReadAllText(questionFile); QuestionForm formTemplate = QuestionUtil.DeserializeQuestionForm(template); int processed = 0; int failed = 0; foreach (KeyValuePair <string, ResultSet> document in context.Results) { formTemplate.Question[0].QuestionIdentifier = document.Key; formTemplate.Question[0].QuestionContent.Items[0] = Encoding.UTF8.GetString(Encoding.Default.GetBytes(document.Value.Source)); string question = QuestionUtil.SerializeQuestionForm(formTemplate); HIT hit = new HIT(); hit.Expiration = DateTime.Now.AddDays(1); hit.ExpirationSpecified = true; hit.HITGroupId = "SentimentAnalysis"; hit.HITTypeId = hitType; hit.MaxAssignments = settings.Assignments; hit.MaxAssignmentsSpecified = true; hit.Question = question; HIT serverHit = null; try { processed++; if (context.UseDebugMode) { TimeSpan time = TimeSpan.Zero; serverHit = BenchmarkHelper.Invoke(new InvokeBenchmarkHandler(delegate(object state) { return(client.CreateHIT(hit)); }), null, out time) as HIT; Console.WriteLine("MechanicalTurk: HIT {0} has been sent to Mechanical turk for processing. Execution time is: {1}", serverHit.HITId, time.TotalMilliseconds); } else { serverHit = client.CreateHIT(hit); } document.Value.AddOutput("MechanicalTurk", settings.Assignments, serverHit.HITId); AnalysisExecutionProgressEventArgs e = new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Processed, context.Results.Count, processed, failed); context.OnExecutionProgress("MechanicalTurk", e); if (e.Cancel) { break; } } catch (Exception ex) { failed++; document.Value.AddOutput("MechanicalTurk", 0, "failed"); AnalysisExecutionProgressEventArgs ea = new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Failed, context.Results.Count, processed, failed); ea.Reason = ex.Message; context.OnExecutionProgress("MechanicalTurk", ea); if (ea.Cancel) { break; } } } context.OnExecutionProgress("MechanicalTurk", new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Success, context.Results.Count, processed, failed)); }
public void Execute(AnalysisExecutionContext context) { _context = context; if (context.Results.Count <= 0) { context.OnExecutionProgress("MechanicalTurk", new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Canceled, 0, 0, 0)); return; } MechanicalTurkSettings settings = context.CustomField as MechanicalTurkSettings; if (settings == null) settings = new MechanicalTurkSettings(null, 3, new decimal(0.10), 300, 1800, 75); string key = context.Key; string secret = context.Secret; MTurkConfig config = new MTurkConfig(_serviceURL, key, secret); SimpleClient client = new SimpleClient(config); List<QualificationRequirement> requirements = new List<QualificationRequirement>(); QualificationRequirement sucRequirement = new QualificationRequirement(); sucRequirement.QualificationTypeId = MTurkSystemQualificationTypes.ApprovalRateQualification; sucRequirement.IntegerValueSpecified = true; sucRequirement.IntegerValue = settings.PercentOfSuccess; sucRequirement.Comparator = Comparator.GreaterThanOrEqualTo; requirements.Add(sucRequirement); if (settings.Locale != null) { QualificationRequirement qualReq = new QualificationRequirement(); qualReq.LocaleValue = new Locale() { Country = settings.Locale }; qualReq.Comparator = Comparator.EqualTo; qualReq.QualificationTypeId = MTurkSystemQualificationTypes.LocaleQualification; requirements.Add(qualReq); } string hitType = string.Empty; try { if (context.UseDebugMode) { TimeSpan time = TimeSpan.Zero; hitType = BenchmarkHelper.Invoke(new InvokeBenchmarkHandler(delegate(object state) { return hitType = client.RegisterHITType("Sentiment analysis", "Judge the sentiment expressed by the following text.", settings.TimeToApprove, settings.TimeToFinish, settings.Reward, "sentiment nlp", requirements); }), null, out time) as string; Console.WriteLine("MechanicalTurk: HIT type for sentiment analysis has been created. HIT type ID is: {0} Execution time is: {1}", hitType, time.TotalMilliseconds); } else hitType = client.RegisterHITType("Sentiment analysis", "Judge the sentiment expressed by the following text.", settings.TimeToApprove, settings.TimeToFinish, settings.Reward, "sentiment, nlp", requirements); NotificationSpecification notification = new NotificationSpecification(); notification.Transport = NotificationTransport.Email; notification.EventType = new EventType[] { EventType.AssignmentReturned }; notification.Destination = settings.Email; notification.Version = "2006-05-05"; if (settings.Email != null) client.SetHITTypeNotification(hitType, notification, true); else { notification.Destination = "*****@*****.**"; client.SetHITTypeNotification(hitType, notification, false); } } catch (Exception ex) { AnalysisExecutionProgressEventArgs ea = new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Failed, context.Results.Count, 0, 0); ea.Reason = ex.Message; context.OnExecutionProgress("MechanicalTurk", ea); if (ea.Cancel) return; } string questionFile = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "SentimentTemplate.xml"); string template = File.ReadAllText(questionFile); QuestionForm formTemplate = QuestionUtil.DeserializeQuestionForm(template); int processed = 0; int failed = 0; foreach (KeyValuePair<string, ResultSet> document in context.Results) { formTemplate.Question[0].QuestionIdentifier = document.Key; formTemplate.Question[0].QuestionContent.Items[0] = Encoding.UTF8.GetString(Encoding.Default.GetBytes(document.Value.Source)); string question = QuestionUtil.SerializeQuestionForm(formTemplate); HIT hit = new HIT(); hit.Expiration = DateTime.Now.AddDays(1); hit.ExpirationSpecified = true; hit.HITGroupId = "SentimentAnalysis"; hit.HITTypeId = hitType; hit.MaxAssignments = settings.Assignments; hit.MaxAssignmentsSpecified = true; hit.Question = question; HIT serverHit = null; try { processed++; if (context.UseDebugMode) { TimeSpan time = TimeSpan.Zero; serverHit = BenchmarkHelper.Invoke(new InvokeBenchmarkHandler(delegate(object state) { return client.CreateHIT(hit); }), null, out time) as HIT; Console.WriteLine("MechanicalTurk: HIT {0} has been sent to Mechanical turk for processing. Execution time is: {1}", serverHit.HITId, time.TotalMilliseconds); } else serverHit = client.CreateHIT(hit); document.Value.AddOutput("MechanicalTurk", settings.Assignments, serverHit.HITId); AnalysisExecutionProgressEventArgs e = new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Processed, context.Results.Count, processed, failed); context.OnExecutionProgress("MechanicalTurk", e); if (e.Cancel) break; } catch (Exception ex) { failed++; document.Value.AddOutput("MechanicalTurk", 0, "failed"); AnalysisExecutionProgressEventArgs ea = new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Failed, context.Results.Count, processed, failed); ea.Reason = ex.Message; context.OnExecutionProgress("MechanicalTurk", ea); if (ea.Cancel) break; } } context.OnExecutionProgress("MechanicalTurk", new AnalysisExecutionProgressEventArgs(AnalysisExecutionStatus.Success, context.Results.Count, processed, failed)); }