I would like to edit the vote, but I cannot find how to do it. Please help
this_list = [Mascot(mascot_name='Peter', species='Anteater', school_name='UC Irvine', number_of_votes=137988),
Mascot(mascot_name='Victor E.', species='Bulldog', school_name='Fresno State', number_of_votes=118302),
Mascot(mascot_name='Tuffy the Titan', species='Elephant', school_name='Cal State Fullerton', number_of_votes=94413)]
Edited
use _.replace()
from collections import namedtuple
Mascot=namedtuple('Mascot',['mascot_name','species','school_name','number_of_votes'])
list_of_mascots = [Mascot(mascot_name='Peter', species='Anteater', school_name='UC Irvine', number_of_votes=137988),
Mascot(mascot_name='Victor E.', species='Bulldog', school_name='Fresno State', number_of_votes=118302),
Mascot(mascot_name='Tuffy the Titan', species='Elephant', school_name='Cal State Fullerton', number_of_votes=94413)]
for i in range(len(list_of_mascots)):
list_of_mascots[i]=list_of_mascots[i]._replace(number_of_votes = 9)
print(list_of_mascots)
output:
[Mascot(mascot_name='Peter', species='Anteater', school_name='UC Irvine', number_of_votes=9), Mascot(mascot_name='Victor E.', species='Bulldog', school_name='Fresno State', number_of_votes=9), Mascot(mascot_name='Tuffy the Titan', species='Elephant', school_name='Cal State Fullerton', number_of_votes=9)]
Related
Using django 1.8, I'm observing something strange.
Here is my javascript:
function form_submit(){
var form = $('#form1_id');
request = $.post($(this).attr('action'), form.serialize(), function(response){
if(response.indexOf('Success') >= 0){
alert(response);
}
},'text')
.fail(function() {
alert("Failed to save!");
});
return false;
}
and here are the parameters displayed in views.py
print request.POST
<QueryDict: {u'form_4606-name': [u''], u'form_4606-parents': [u'4603', u'2231', u'2234']}>
but I cannot extract the parents:
print request.POST['form_4606-parents']
2234
Why is it just giving me the last value?
I think there is something wrong with the serialization, but I just cannot figure out how to resolve this.
From here
This is a feature, not a bug. If you want a list of values for a key, use the following:
values = request.POST.getlist('key')
And this should help retrieving list items from request.POST in django/python
The function below converts a QueryDict object to a python dictionary. It's a slight modification of Django's QueryDict.dict() method. But unlike that method, it keeps lists that have two or more items as lists.
def querydict_to_dict(query_dict):
data = {}
for key in query_dict.keys():
v = query_dict.getlist(key)
if len(v) == 1:
v = v[0]
data[key] = v
return data
Usage:
data = querydict_to_dict(request.POST)
# Or
data = querydict_to_dict(request.GET)
You can use getlist method
data = request.POST.getlist('form_4606-parentspass_id','')
The simplest way
{**request.GET}
{**request.POST}
or, if you use djangorestframework
{**request.query_params}
I have a list of difined Todo items like:
Todo{
Datetime datetime;
String task;
}
List todos = [todo1, todo2,...]
And I need to convert it to a map with type Map<Datetime, List<String>> , but in todos list, I have some todo with the same Datetime so when I use code like:
todos.forEach((todo) => map2[todo.datetime] = todo.task); the next todo will be replaced if the key is the same.
So sorry if this is a silly question, I have searched on Google but nothing there.
Thanks,
Hung PT.
Try this
todos.forEach((todo) => map2[todo.datetime] = map2[todo.datetime] == null ? [...map2[todo.datetime], todo.task] : [todo.task]);
I'm not sure why I'm having such a hard time finding an answer for this, but I have a list that I need to get the value from where the key matches certain criteria. The keys are all unique. In the example below, I want to get the color where the name equals "headache". Result should be "4294930176".
//Example list
String trendName = 'headache';
List trendsList = [{name: fatigue, color: 4284513675}, {name: headache, color: 4294930176}];
//What I'm trying
int trendIndex = trendsList.indexWhere((f) => f.name == trendName);
Color trendColor = Color(int.parse(trendsList[trendIndex].color));
print(trendColor);
Error I get: Class '_InternalLinkedHashMap' has no instance getter 'name'. Any suggestions?
EDIT:
Here's how I'm adding the data to the list, where userDocuments is taken from a Firestore collection:
for (int i = 0; i < userDocument.length; i++) {
var trendColorMap = {
'name': userDocument[i]['name'],
'color': userDocument[i]['color'].toString(),
};
trendsList.add(trendColorMap);
}
I guess, I got what the problem was. You were making a little mistake, and that was, you're trying to call the Map element as an object value.
A HashMap element cannot be called as f.name, it has to be called f['name']. So taking your code as a reference, do this, and you are good to go.
String trendName = 'headache';
List trendsList = [{'name': 'fatigue', 'color': 4284513675}, {'name': headache, 'color': 4294930176}];
//What I'm trying
// You call the name as f['name']
int trendIndex = trendsList.indexWhere((f) => f['name'] == trendName);
print(trendIndex) // Output you will get is 1
Color trendColor = Color(int.parse(trendsList[trendIndex]['color'])); //same with this ['color'] not x.color
print(trendColor);
Check that out, and let me know if that helps you, I am sure it will :)
didn't know how to name this thread but will try to explain the problem in few lines.
I have a command which need to calculate price for desired date range. To calculate it system needs to fetch the price for every day individually (DB, config, cache, it doesn't matter from where).
My suggestion was to have one PriceRangeActor which will have a pool of DailyPriceActors and will send them commands like CalculateDailyPrice.
But how to assemble all that data in PriceRanceActor?
1.
Having some big map with complex keys just smells a lot. How to determine then if the range is completely calculated? Is there any easier way of doing this?
2.
Create new PriceRangeActor for every command and use ask pattern to query the list of DailyPriceActors?
Because you aren't utilizing any message passing/queuing I suggest Futures rather than Actors as your concurrency abstraction mechanism. This blog entry makes a very compelling argument that Actors are for state and Futures are for computation.
With either Futures or Actor ? (which is a Future) you can use Future.sequence to bundle together all of the separate querying Futures into a single Future that only completes once all the sub-queries are complete.
USING FUTURES (recommended)
import scala.concurrent.Future
object Foo extends App {
type Date = Int
type Prices = Seq[Float]
type PriceMap = Map[Date, Prices]
//expensive query function
def fetchPrices(date : Date) : Prices = ???
//the Dates to query Prices for
val datesToQuery : Seq[Date] = ???
import scala.concurrent.ExecutionContext.Implicits._
def concurrentQuery(date : Date) : Future[Prices] = Future {fetchPrices(date)}
//launches a Future per date query, D Dates => D Futures
//Future.sequence converts the D Futures into 1 Future
val dates2PricesFuture : Future[PriceMap] =
Future.sequence(datesToQuery map concurrentQuery)
.map(datesToQuery zip _)
.map(_.toMap)
dates2PricesFuture onSuccess { case priceMap : PriceMap =>
//process the price data which is now completely available
}
}//end object Foo
USING ACTORS
import scala.concurrent.Future
import akka.actor.{Actor, ActorSystem, Props}
import akka.pattern.ask
import akka.util.Timeout
object Foo extends App {
type Date = Int
type Prices = Seq[Float]
type PriceMap = Map[Date, Prices]
def fetchPrices(date : Date) : Prices = ???
val datesToQuery : Seq[Date] = ???
class QueryActor() extends Actor {
def receive = { case date : Date => sender ! fetchPrices(date) }
}
implicit val as = ActorSystem()
implicit val queryTimeout = Timeout(1000)
import as.dispatcher
def concurrentQuery(date : Date) : Future[Prices] =
ask(as actorOf Props[QueryActor],date).mapTo[Prices]
val dates2PricesFuture : Future[PriceMap] =
Future.sequence(datesToQuery map concurrentQuery)
.map(datesToQuery zip _)
.map(_.toMap)
dates2PricesFuture onSuccess ... //same as first example
}//end object Foo
I have a file that I need to modify. The part I need to modify (not the entire file), is similar to the properties shown below. The problem is that I only need to replace part of the "value", the "ConfigurablePart" if you will. I receive this file so can not control it's format.
alpha.beta.gamma.1 = constantPart1ConfigurablePart1
alpha.beta.gamma.2 = constantPart2ConfigurablePart2
alpha.beta.gamma.3 = constantPart3ConfigurablePart3
I made this work this way, though I know it is really bad!
def updateFile(String pattern, String updatedValue) {
def myFile = new File(".", "inputs/fileInherited.txt")
StringBuffer updatedFileText = new StringBuffer()
def ls = System.getProperty('line.separator')
myFile.eachLine{ line ->
def regex = Pattern.compile(/$pattern/)
def m = (line =~ regex)
if (m.matches()) {
def buf = new StringBuffer(line)
buf.replace(m.start(1), m.end(1), updatedValue)
line = buf.toString()
}
println line
updatedFileText.append(line).append(ls)
}
myFile.write(updatedFileText.toString())
}
The passed in pattern is required to contain a group that is substituted in the StringBuffer. Does anyone know how this should really be done in Groovy?
EDIT -- to define the expected output
The file that contains the example lines needs to be updated such that the "ConfigurablePart" of each line is replaced with the updated text provided. For my ugly solution, I would need to call the method 3 times, once to replace ConfigurablePart1, once for ConfigurablePart2, and finally for ConfigurablePart3. There is likely a better approach to this too!!!
*UPDATED -- Answer that did what I really needed *
In case others ever hit a similar issue, the groovy code improvements I asked about are best reflected in the accepted answer. However, for my problem that did not quite solve my issues. As I needed to substitute only a portion of the matched lines, I needed to use back-references and groups. The only way I could make this work was to define a three-part regEx like:
(.*)(matchThisPart)(.*)
Once that was done, I was able to use:
it.replaceAdd(~/$pattern/, "\$1$replacement\$3")
Thanks to both replies - each helped me out a lot!
It can be made more verbose with the use of closure as args. Here is how this can be done:
//abc.txt
abc.item.1 = someDummyItem1
abc.item.2 = someDummyItem2
abc.item.3 = someDummyItem3
alpha.beta.gamma.1 = constantPart1ConfigurablePart1
alpha.beta.gamma.2 = constantPart2ConfigurablePart2
alpha.beta.gamma.3 = constantPart3ConfigurablePart3
abc.item.4 = someDummyItem4
abc.item.5 = someDummyItem5
abc.item.6 = someDummyItem6
Groovy Code:-
//Replace the pattern in file and write to file sequentially.
def replacePatternInFile(file, Closure replaceText) {
file.write(replaceText(file.text))
}
def file = new File('abc.txt')
def patternToFind = ~/ConfigurablePart/
def patternToReplace = 'NewItem'
//Call the method
replacePatternInFile(file){
it.replaceAll(patternToFind, patternToReplace)
}
println file.getText()
//Prints:
abc.item.1 = someDummyItem1
abc.item.2 = someDummyItem2
abc.item.3 = someDummyItem3
alpha.beta.gamma.1 = constantPart1NewItem1
alpha.beta.gamma.2 = constantPart2NewItem2
alpha.beta.gamma.3 = constantPart3NewItem3
abc.item.4 = someDummyItem4
abc.item.5 = someDummyItem5
abc.item.6 = someDummyItem6
Confirm file abc.txt. I have not used the method updateFile() as done by you, but you can very well parameterize as below:-
def updateFile(file, patternToFind, patternToReplace){
replacePatternInFile(file){
it.replaceAll(patternToFind, patternToReplace)
}
}
For a quick answer I'd just go this route:
patterns = [pattern1 : constantPart1ConfigurablePart1,
pattern2 : constantPart2ConfigurablePart2,
pattern3 : constantPart3ConfigurablePart3]
def myFile = new File(".", "inputs/fileInherited.txt")
StringBuffer updatedFileText = new StringBuffer()
def ls = System.getProperty('line.separator')
myFile.eachLine{ line ->
patterns.each { pattern, replacement ->
line = line.replaceAll(pattern, replacement)
}
println line
updatedFileText.append(line).append(ls)
}
myFile.write(updatedFileText.toString())