I have experienced some crazy unusual sickness and injury over the last few months. I'm baffled as to why this is so I'm going to try to work it out, and definitely boost my immunity back up so it ends and so I feel well again.
Clint and I eat 90% Paleo, get lots of nature time and I get "nakey bakey" most days (a new name for naked sun time my friend recently came up with. Love it!), so maybe some stress is the underlying cause? Well, whatever it is I know my eating could be improved a little, especially while my immune system is obviously weak.
One of the most popular natural health tonics today is raw juice. We, though, are not fans of regular juicing. Ooh, controversial…! The reason? There are two main ones: 1. Humans need to chew their food most of the time; our stomach enzymes that digest our food need to wake up to be ready for the food to arrive and that happens in the mouth when we salivate and CHEW! 2. Juicing removes a large portion of the essential fiber in the foods blended up. That's wasteful and not healthy.
But some of the foods that go into making up 'health tonic' or 'superfood' juices can be pretty darn healing, so why not utilise them in a way the body can better use?
These are really easy to make (as are most pure gelatin recipes), can easily be changed to suit tastes and allergies, and are easy to grab from the fridge during the day to get some goodness into the body.
Want to know how to make them yourself? Well alrighty, here you go!
6 tbsp pure beef gelatin powder (grab some from Gelatin Australia here).
Tips: Use half as much gelatin if you're wanting to make jelly cups instead of lollies.
Tips: Add another tbsp gelatin for really firm lollies, especially if using molds. Use half as much if you're wanting to make jelly cups instead of lollies.
Optional: Stevia powder or raw honey to your liking, to sweeten if needed.
Pour water into a small-medium saucepan, stove turned off, and gently sprinkle the gelatin powder evenly over the surface of the water.
Once all the gelatin is on and appears translucent (this is called "blooming") you can turn the stove to a medium heat to gently warm the liquid up. Use a whisk to stir as it heats up.
Once all gelatin granules have dissolved pour half the liquid into a blender jug along with the diced fruit, veg and ginger. Blend on high until you have a fine mixture with as few chunks and lumps as possible. If using a sweetener, add it to the blender to combine.
Pour the remaining gelatin liquid in and stir to combine. The more gelatin you blend with food the frothier the mixture becomes and ends up setting with a thick layer of froth. I prefer the texture of a bit of froth, not too much. For almost no froth blend the foods with just enough pure water needed then gently stir the gelatin liquid in. Possibly add a smidge more gelatin to the saucepan if you go with this method.
Once the mixture is blended to your liking you can pour straight into silicon molds or into a square/rectangle container to create a gummy 'block' to slice up once set. Tip: if you'd prefer less texture from the food 'bits' then simply strain some of the liquid through a fine sieve but keep in mind that's where a lot of the nutrients and fiber are.
Place in the fridge for a few hours to set firm. Remove from molds and store in an airtight bag or container in the fridge, or slice up the block into small squares.
Grab some to munch on during the day and enjoy the pure whole food healing goodness! Include some in the kids or your own lunchbox (as long as it stays cool), take on road trips, include them at parties.
Remember, these are versatile. Add or remove ingredients listed for others you'd prefer. Pretty much all of my recipes are versatile so you can adapt to your own tastes and needs!
If ALL of my gelatin recipes and all the techniques you'll ever need to become a gelatin pro, grab my e-book here.
Clint and I are going through periods of low and no-sugar eating at the moment because we need to for our health. He's doing 30 days straight of no sugar and I'm 5 days on / 2 days off -ish.
It's going really well for both of us; we're each noticing improvements to our health, we're feeling better, and we're getting used to some of the swap foods we've been eating.
I went live on our Facebook page last week giving my tips for no and low sugar eating, because we've been through this quite a few times and can definitely give some advice on how to be successful with it. Watch the video HERE.
Yesterday I felt like baking so I had an idea of a biscuit I wanted to try. I know pumpkin puree is a great natural sweetener and binder so I decided to try Pumpkin Spice Choc Chip Biscuits and was very pleased with the result!
They turned out nice and fluffy, quite moist and surprisingly moreish. The only negative… they're best eaten warm. Not when they've completely cooled down as they then become a bit dry and definitely not as tasty. So if you wait until they've come out of the oven and have cooled just enough to still be warm inside, or you heat them up gently if they have cooled completely, then they are delicious! And warm biccies are so much more enjoyable in the cooler months, so it's not a bad thing overall!
If you're after more sweetness and aren't on a low/no sugar eating plan, add raw honey or Grade B maple syrup to the mixture, and/or some chopped fresh Medjool dates. Yum!
If you'd like ALL of my healthy green banana flour recipes grab my e-books HERE.
I don't always consume nightshades because I have a bit of sensitivity to them, so I often enjoy creating variety with meals totally leaving out tomato, chilli, garlic, paprika.. basically all the good stuff lol and finding flavour without those common flavour options.
As most of you know, I also like to create meals that are quick, easy and super healthy. Sometimes my creative moments actually work out well and the other night was one of those occasions when I created a new meat and veg dish that got double thumbs up from Clint, woo! AND it made 4 meals worth in one go, bonus!
I decided to make meatballs, a non-tomato sauce and have some noodles… and I created Meatballs and Veggies with Noodles 2-Ways – delicious, super healthy, really easy to make, a total win!
This made 4 serves so Clint had lunch ready for work the next day, it's fine to have cold, and I had my dinner sorted for the next night. Yay!
Kids will love this because pumpkin gives sweetness, noodles and meatballs are fun and it's a bright coloured dish!
It's so healthy because it's jam-packed full of nourishing veggies, a little bit of meat, the bone broth contains gelatin and essential minerals, the turmeric is anti-inflammatory and the fat in there balances it all out nicely.
You could add some coconut amino (with or without chilli and garlic in it) to the sauce to give it a flavour boost. You could use different noodles. You can add different herbs and spices. This recipe is so versatile!
Enjoy! Please let me know how you go and how this idea helps you in the kitchen!
Last night after another awesome Primal Fitness Class we popped into Woolies to grab something for dinner (yes we still shop at big bad chain supermarkets.. we sometimes need to – don't judge!) and I had the idea to make fish n chips. Partly because we love making crispy chips out of different veggies (very rarely potato, bit too inflammatory for us unfortunately) plus there were a few choices of wild-caught seafood on special at the Deli. Yay!
So we grabbed some beautiful flathead fillets (50% off, why not?!), a parsnip and a white-fleshed sweet potato to go with the orange sweet potato we had at home.
I'd been wanting to try using green banana flour (only my favourite ingredient in the world!) with fish to fry to see how it went… so I did!
It turned out brilliantly and alongside crispy baked veggie chips and a serve of lime aioli… dinner was sorted and pretty darn enjoyable (if I do say so myself <wink>!).
Here's the recipe for you guys to make and enjoy it for yourselves!
For the chips: Pre-heat oven to 180.
Sprinkle salt over the top then place in the oven. Keep an eye on them because your oven may not cook evenly and some chips may cook or burn before others, so place your timer on to remind you to check every 2 or so minutes. Shuffle chips around as you need so they cook evenly. Keep in mind… white-flesh sweet potato hardens before it looks like it's crispy! So check doneness by tasting a piece for yourself!
Once chips are cooked to your liking place them on paper towel to absorb excess fat then place onto plates or serving dish.
Alternatively you could fry the chips in a large pan on the stove.
our event on Saturday for kids and adults, it's going to be so fun!
That's not a typo, it is actually meant to read "Our bug adventures", not "Our big adventures".. did you get a bit confused there for a second?!
If you read the blog post we did about our 2015 Paleo Camping Retreat you'll know we're open to eating bugs, because one of our awesome sponsors Primal Collective gave us tubs of roasted crickets! They actually just taste like savoury popcorn, serious! And as we've discovered recently catching and cooking up some bugs ourselves.. there's not a great deal of flavour. Generally speaking anyway. It's more the mindset and the look of them that's hard to get your head around. But once you get past that and free yourself of the ick-factor so many people naturally have at first, it's really quite a positive experience!
Humans have been eating bugs since humans first walked the earth. Insects are just another rung on the food chain ladder. But these days, with the modern conveniences we're used to such as shops selling pre-cut pieces of attractive-looking muscle meats.. we are really out of touch with what our food originally looked like, where it comes from and how it lived before it served the purpose of feeding another form of life. I.e. Us!
The fact humans do naturally eat bugs for survival and fuel seems to have been forgotten.
So because this is such a unique thing in the eyes of most, Clint and I thought we'd write about our bug hunting and eating adventures in the hopes of inspiring others to get on the insect train!
Our friend Dan the Aussie Paleo Chef has been eating bugs for a while. He often sends us photos of scorpions and other insects he finds in the bush near him in Canberra and then cooks up at home in coconut oil and other typical paleo flavourings. He's really inspired us, we'd wanted to do this ourselves for a long time but were always a bit nervous about the safety of it. There's so little information on the internet about which bugs are safe to eat, we just didn't want to eat something that ended up being poisonous. Of course!
But a few weeks ago a new friend of ours saw an article we shared on Facebook by Stirring Change on eating dehydrated ants and indicated she was keen to try this herself. So we asked if she'd like to come on a bug hunt with us and she jumped at the chance!
We picked a day and a location and off we went into the bush to catch us some bugs! Our friend Sarah and her son had a list of edible insects they'd found online and Clint and I were pretty well read on the bugs in the area that would be safe to consume. We took some gloves, plastic containers and headed down the main track of a local parkland, turning over logs, sifting through leaf litter and basically looking in all the places we figured bugs would be.
That big sucker is actually a giant centipede! Plus there's a witchitty grub-type thing, a bush cockroach and a beetle.
This little guy is a regular centipede. Not to be confused with millipedes which we read are not safe to eat. To tell the difference, centipedes only have one leg per body segment, whereas millipedes have more.
"But don't centipedes contain poison?" I hear you say? They do indeed but we'd read that cooking the bugs cooks out this poison, making them totally safe to eat!
Only 4 bugs (the beetle didn't seem worth it so we didn't include him) and 4 people to share around to.. hmmm. Sarah ended up letting us take them home to eat. I think she was still too nervous to cook them up herself! We didn't mind!
She had wanted to score a haul of ants to take home to dehydrate, but when we started trying to catch some ants at the beginning of our trek we soon realised they are pretty hard to get! They're really quick, so when you manage to get one or more in a container, you have others trying to get out at the same time. We figured we'd need to design our own ant-catcher contraption, or go home and Google for some ideas. So that'll be for another bug hunting expedition!
Clint and I took these few bugs home and fried them in just coconut oil and salt. The centipedes and roach turned out perfectly; nice and crispy. The grub, however, wasn't so nice, but we found out later from our friend The Free-ranging Chef that we needed to cook it slightly differently so we'll definitely keep that in mind for next time.
Yes, there'll be a next time! We're already planning the next Bug Hunt! Cos, well, you could say … we've caught the bug for it..! haha sorry, couldn't resist!
Next week we're planning to try catching ants with a homemade trap (cos they are fast little buggers and tricky to catch!) to dehydrate. Plus more general insects so we can keep experimenting and hopefully enjoy a bigger feed!
So as well as the actual bug hunting, we also eat farmed bugs. The roasted crickets are great, but recently we also found out about cricket FLOUR! Or "powder" to be exact, because of the texture roasted crickets become when broken down.
Our new friends from Bugsy Bros in Brisbane sell packets of cricket powder and kindly gave us some to play around with. I've been cooking with it and really like it!
I even used it in a recipe I gave at my last Sunny Coast cooking demo… Mini Banana Muffins… and the tasters when down a treat! They're a great addition for kids and adults lunchboxes because they're small but filling and nourishing. That extra protein helps you stay fuller longer, and the exclusion of nuts, and even coconut flour, means there's less chance of bloating and feeling 'heavy' after eating, unlike many paleo muffin recipes.
Would you like the recipe for the muffins so you can easily test out the cricket powder without it being a really strong and overpowering taste experience? And also to hide it from the kids? Here it is!
Tip: place slices of banana on top before baking to make them prettier!
Ideas: swap banana for pumpkin or sweet potato (to help bind and moisten but with less sugar), add dates for extra sweetness, add whole blueberries, turn into savoury muffins with grated veggies and savoury spices/herbs… there are so many ways to change this recipe to suit your health needs and tastes!
These muffins are nutrient-dense so a few are very filling and great for school and work lunchboxes. They are nut-free which is great for schools or when having kids' friends over who have allergies. They can be made coconut-free by using ghee or olive oil instead of coconut oil (the cricket powder is high in protein so it's a perfect swap).
Storage Tip: Double the quantity, make large batches and store in bags or containers in the freezer to thaw and use when needed! For use within a few days store in an air-tight container out of the fridge.
So there you have it.. you're up to date with our recent bug adventures and even scored a healthy and yummy recipe you can use insects in!
Please let us know how you go with bug hunting and/or eating, we'd love to hear from you!
DISCLAIMER: All content provided on this Under the Primal Influence blog is for informational purposes only. The owner of this blog makes no representations as to the accuracy or completeness of any information on this site or found by following any link on this site.
The owner of undertheprimalinfluence.wordpress.com will not be liable for any errors or omissions in this information nor for the availability of this information. The owner will not be liable for any losses, injuries, or damages from the display or use of this information.
Thanks to Sunshine Coast Paleo Lifestyle Meetup Group member Andrea for sending us this winning recipe!
Andrea kindly gave us a batch a few months ago and we loved it. Clint was eating it with a spoon it was that good, so we thought it about time to give you guys the recipe so you too can make and enjoy this deliciousness!
Add all the ingredients to your blender or food processor and process until completely reduced to a fine, liquid puree.
Transfer that puree to a medium saucepan and bring to a boil. Lower the heat, partly cover and simmer for 45 to 60 minutes, stirring from time to time, until the sauce is nice and thick and darker in color.
Kill the heat and let the sauce come down to room temperature.
If you want a really smooth BBQ sauce, pass it through a fine mesh sieve (you will have to help it through by swirling it around with a ladle), otherwise, just transfer it straight to an airtight container and refrigerate.
This BBQ sauce gets better after sitting in the fridge for a few days and it will keep for 2-3 weeks in the refrigerator.


I'm opening another icon making contest for Valentine's Month. Hope people will find it interesting enough to participate.
Also, this is my first time creating a icon making contest, so please guide me if I'm going wrong and I have borrowed the rules from Tiffany's DP Themed Icon Contest since they seemed most apt.
• The next theme will be posted once the poll has been put up for previous round.
ROUND 1: FAVORITE DP COUPLE ---- OPEN NOW!
Ummmm.......mine, I love this kiss. How passionate!
Also, in case anybody's wondering this is a screencap from the end of the movie, where it changes to a storybook, not a fanart.


I remember the day I learned this technique. It felt like being a kid on Christmas morning opening a brand new toy. Only this toy makes my life much easier.
Designers are constantly challenged with trying to fit a client-approved photo into the canvas. Along with logo, typography, and a digital call-to-action (button). More often than not the subject matter in the photo blends with these elements. With less negative space to work with, I had to constantly airbrush and clone more of the photograph. It's not easy, and it's time consuming. Content-Aware scans the contents of the image to figure out what the photo would have looked like if the unwanted object or area had never been there. It lets you repair or replace larger, more challenging areas, even multiple areas at once. Simply create selections around them and let Photoshop do the rest. Amazing! This provides more negative space for logo, typography, and buttons and less conflict with the subject matter.
Back in the day, Photoshop files would have hundreds of different layers. Files were confusing and cluttered. Later, "Groups" were created and this made for more efficient organization of the layered mess. But Smart Objects one-upped layer groups.
Creating Layer Groups into Smart Objects has made website creation much easier to maintain. Designers can create primary navigations, menus, and footer navigations in Layer Groups and then convert them to Smart Objects, which generates a .PSB file. That .PSB can be linked to multiple .PSD files from one source file. That way if you make an edit to the primary navigation (.PSB file) it will update all .PSD pulling it in. This concept is similar to how InDesign works. Smart Objects can be vector files or photographs too. They can be edited in Illustrator and the changes linked back to Photoshop.
I find this photo editing tool to be the digital designer's secret weapon. It's the tool you use when type is not legible on a photo or it's too hard to read. Text is texture. Photos have texture. So when you have one texture on top of the another, it often causes legibility problems. Lowering the Dodge or Burn output and subtly brushing it behind the copy will make your copy more legible. Of course, you have may have to change a color or shadow, but at least you can maintain your design composition to make the copy more legible at the same time.
Those are my three favorite Photoshop tools. I'd love to hear what your's are.
← Take a Position and Own It.


We have a strong desire to find, address, and implement practical, insightful solutions to help families and communities navigate through the challenges of a stressful world with insight, humor and within a safe, "no-shame" environment.
Creator and Founder of an online community for pastor's wives and women in ministry, mentioned in TIME magazine in 2007, Shannon has had the unusual and rare opportunity to hear from ministers of all denominations regarding personal and professional challenges. The voices and experiences from this experience has laid the foundation for Living Stones Center after she saw the need for practical solutions to common occurrences, no matter what the denomination or workplace.
Locating resources and answers became the goal after spending over thirty years in church ministry and another twenty in the workplace environment. Shannon has identified common, specific areas of dysfunction within individuals, their families and their children that are the result of an overly stressed, and modernized society.
The lack of mentors, one-on-one teaching moments in an experiential setting and poor health, contribute to conflict and chaos that don't need to happen. her goal is to educate and train community leaders and people who have a desire to make change happen, in a way that is simple and effective.
Shannon is a Professional Life Coach, Illustrator and Graphic Recorder who brings numerous resources and relationships to Living Stones Center for the purpose of healing, encouraging and educating those who have had enough of not being in control of their lives, and who desire to make change happen, not only for themselves, but for their children and their communities.
Highly regarded, Joe's Supervisory accomplishments reflect a strong leadership ethic, trouble shooting and problem solving skills and the ability to bring a team together to accomplish tasks in a timely and efficient manner. His clear understanding of processes, resourcefulness and how these all play into the big picture are invaluable to a growing organization and community.
The father of four children, with another on the way, he understands the importance of having relationships with his children and a clear understanding of the world in which they live. He, along with his wife Suzanne, purchased five acres with a 140 year old farm house to house their growing family and to have a place where Joe's vision and dreams of helping other families connect through outdoor experiences, can occur.
A screen writer and talented visionary, Joe and Suzanne foresee a community where businesses, churches and families can explore their resources and creativity through the Arts, Entertainment and Outdoor Adventure settings.
Whether preaching, teaching or visiting nations around the world, Shirley Christmon crosses boundaries. She moves across denominational, cultural, racial and national lines to bring an expression of God's Kingdom to the individual. She longs to see people in every nation living freely in God's abundance.
Shirley is an ordained pastor whose lifework involves reaching and encouraging people right where they are at, no matter how desperate their situation may be. She faithfully prays for the larger world picture as well as for immediate needs. She often has an insightful word that by-passes the superficial and speaks directly to the heart.
Having been raised in an extended family of preachers and ministers she has a passion to also raise up the next generation to serve God whole-heartedly. She wants to impact lives with the gospel of salvation through faith in Jesus Christ, and to provide training in applying practical truth of the scriptures to everyday life. Her intent is to bring clear understanding to Hebrews 6:19, which describes our hope in God as a secure anchor for our soul.
Shirley received her B.S. in Organizational Management in Christian Leadership and she has raised 2 sons, and 3 daughters, and now has 12 grandchildren and 8 great-grandchildren. She lives in metro Denver where she has established a non-profit ministry named Anchored Life.


It's everyone's favorite wizard, Harry Potter. He may not have been the first one to pull off the 'scarface' look but he sure as hell made a lot of money doing it.
Daniel Radcliffe brought J.K. Rowling's story to life as the boy who lived but to make those massive and magical films required no shortage of hard work and ingenuity.
This behind the scenes look at some of the more intricate parts of bringing the magic to life looks at some facts about the Harry Potter franchise that are so astonishing they could in fact be the product of magic.
The set designers for Diagon Alley spent countless hours assembling every window display just so. The set was so detailed that there were over 20,000 props displayed in the various shop fronts in a massive set build.
Crew members and set builders used powerful ropes and pully systems to wrench and pull the storefront portions of the set to give the entire alley a whimsical and slightly off-kilter look.
Once inside Hogwarts, there was only one staircase set built. For the M.C. Escher-esqe staircase effect that set was multiplied and manipulated digitally.
Robbie Coltrane, the actor who played Rubeus Hagrid, had to wear a six piece hair kit to simulate Hagrid's bushy beard.
The beard in question seemed to have a life of its own; things always seemed to be getting stuck in it. In one instance a live bat (intended to be a prop) became entangled in the complicated hair kit!
In order to 'sell' the idea that Hagrid was a giant, two sets were built for Hagrid's Hut. One was sized so that Coltrane would appear large next to the contents of his home and the other was size much larger so that others would appear small by comparison.
Add that to the complicated hair and makeup and Hagrid just might be the most labor intensive character in the movies.
The case of Hagrid's duel huts is small potatoes compared to the grand total of 588 sets that were built for the eight movies.
Potions are commonplace in the movies. Every instance where an actor drinks a magical potion they are actually just taking a sip of some lukewarm soup.
Speaking of potions, in the potions classroom there are over 1,000 prop bottles that line the walls.
And to top it off, the majority of the dusty volumes that line the walls of Dumbledore's office are phonebooks that have been rebound then 'dusted'.
For the kitten-crazed Professor Umbridge, the crew held a kitten photo shoot which starred over 40 young cats. The photos were then screen printed onto plates to form her wall-mounted collection.
Don't worry, the kittens were all adopted or came from volunteer homes.
When filming the full-sized wizard's chess the crew had to contend with pieces that weighed over 500 pounds each.
In the same vein, the Knight's Bus was so top heavy that it had to have an additional balancing weight of four tons added to the lower portion to stop it from falling over.
All of the exterior shots of Hogwarts were made through the use of a highly detailed model. It took 40 people seven months to produce the scale replica of the famous wizarding school. Each and every shingle on the many roofs and spires was laid by hand.The detailed bridge with its latticework of delicate supports took three months alone.
To simulate a snowfall the crew used salt in lieu of other options for fake snow. Any accumulation had to be cleared right away however as the salt would disintegrate the delicate model.
To give an authentic effect the graphics team hand wrote and sealed thousands of letters and envelopes for the owl post to carry. Then had to double up on their efforts after learning that the first run was too heavy for the birds to carry. A second batch produced on lighter stationery was in order.
To further complicate things, it was no easy feat to train the owls to carry the letters either. It took over six months to train the owls to carry letters in their beaks and talons.


This workshop will focus on creating paintings of animals that exhibit emotion. Working with value, color and brushwork, what to leave out and what is essential. The artist will do a demo each day before students begin painting. Beginners to more advanced students are welcome. Artists are encouraged to bring their own photographs as reference.
Within the great tradition of painting, Linda St. Clair has set herself apart as an innovator who creates animal portraits that explore the personalities of creatures great and small. Whether her subjects are of the barnyard, domestic or wild variety, they are undeniably the product of an artist inspired by wildlife's vital energy and its broad emotional range. St. Clair's body of work is infused with a strong narrative sense, a clear articulation of mood and spirit, and an intricate knowledge of animal anatomy. Each painting is completed during a single, intense session out of her home studio in Santa Fe. To get a clearer perspective of an animal's spirit, St. Clair travels frequently to find and photograph them. She's travelled extensively to observe and photograph her subjects. St. Clair's paintings are exhibited and collected throughout the nation and worldwide. She is a two-time recipient of the Grumbacher Gold Medal and member of the Society of Animal Artists in New York.


text:
Q: openpyxl readonly use_iterators I have some huge Excel files, but I'm stymied with even a "modest" one (50 Mbytes). I do need to skip over the first two rows, but I don't think that's the slowdown. Can you think of something else?
wb = load_workbook(MyFile,read_only=True)
ws = wb.active

NDepth = ws.max_row-2
NTime = ws.max_column -1

Local_Depth = np.zeros((NDepth,))
Local_Temp = np.zeros((NDepth,NTime))

iterlist = islice(ws.iter_rows(),2,None)

start = time.time()

i=0
for row in iterlist:
    Local_Depth[i] = row[0].value
    j=0
    for col in row[1:]:
        Local_Temp[i,j] = col.value
        j += 1
    i += 1

print "Done", time.time()-start

It's taking me well over 7 minutes to load the file on a M4700 Dell Precision. About 8000 rows and 800 columns. Surely there must be something wrong? Could there be some other tweaks somewhere that I should be making in my Python 2.7 set-up?
Thank, John

A: I am down to 22 seconds
import numpy as np
import time
from openpyxl import Workbook
from openpyxl import load_workbook
import zipfile

def rowList(fullfilename):
with  zipfile.ZipFile(fullfilename, mode='r') as z:
    with z.open('xl/worksheets/sheet1.xml', 'r') as f:
        irow =-1
        while irow <0:
            hstring = f.read(50000)
            if hstring == "":
                break;
            irow = hstring.find("sheetData")
            if irow < 0:
                return
        string = hstring[irow+10:]
        while True:
            irow = string.find("</row>")
            while irow<0:
                hstring = f.read(50000)
                if hstring == "":
                    break;
                string += hstring
                irow = string.find("</row>")
            if irow < 0:
                return
            irow +=6
            ist = string.find("<c")
            yield string[ist:irow-6]
            string = string[irow:]

def splitRow(func,row):

j = 0
c1 = row.find("<v")
c2 = 0
while c1 > 0:
    c1 += c2 + 3
    c2 = c1 + row[c1:].find("</v")
    yield func(row[c1:c2])
    j += 1
    c2 += 3
    c1 = row[c2:].find("<v")

start = time.time()

wb = load_workbook(MyFile,read_only=True, use_iterators=True)
ws = wb.active
NDepth = ws.max_row-2
NTime = ws.max_column -1
wb._archive.close()

Local_Store = np.empty((NDepth,NTime+1))
Local_Time = np.empty((NTime,))

print NDepth, NTime
print "Data Accessed via Iterators", time.time()-start

start = time.time()

print "About to call RowList"

i = -2
j = 1
for row in rowList(MyFile):
if i == -2:
    True
else:
    if i == -1:
        Local_Time[:] = list(splitRow(float,row))
    else:
        Local_Store[i,:] = list(splitRow(float,row))

i += 1

print i, "Rows Parsed", time.time()-start

A: I would try pandas for this task. It's very simple and gives you lots of power.
Here is a small example:
import time
import numpy as np
import pandas as pd

# let's generate some sample data (8000 rows, 800 columns)
data = np.random.randint(0, 100, (8000, 800))

# let's generate column names from 'col001' to 'col800'
cols = ['col{0:02d}'.format(i) for i in range(1,801)]

# generating Pandas data frame from numpy array
df = pd.DataFrame(data, columns=cols)

# write generated DF (Data Frame) to Excel file
df.to_excel(r'd:/temp/sample.xlsx', index=False)
# we are done with sample data

#####################################################################
#
# interesting part starts here ...
#
#####################################################################

start = time.time()

# read up the Excel file (skipping first two rows)
df = pd.read_excel(r'd:/temp/sample.xlsx', skiprows=2)

print "Done", time.time()-start

# print the shape of out DF
print(df.shape)

Output (from iPython, on my home notebook it took approx. 2 minutes):
In [24]: %paste
start = time.time()

# read up the Excel file
df = pd.read_excel(r'd:/temp/sample.xlsx', skiprows=2)

print "Done", time.time()-start
## -- End pasted text --
Done 124.375999928

In [25]:

In [25]: df.shape
Out[25]: (7998, 800)

In [26]: # print the shape of out DF

In [27]: print(df.shape)
(7998, 800)

Now you have all your data in memory as a DF and can process it very comfortable using all Panda's power
PS you would need to install the following Python modules:

*

*numpy

*pandas

*xlrd

*openpyxl or XlsxWriter  (or both)

A: If I take as a given that the Excel file is a rectangular sheet then I get a huge speed up by just going to ZIP directly. Attached is part of the code for generator that returns a series of rows that I can then parse to search for the actual values between <v> and </v> in each row. I haven't attempted to pretty this up - it looks very non-Pythony.
def rowList():
with  zipfile.ZipFile('MyFile.xlsx', mode='r') as z:
    with z.open('xl/worksheets/sheet1.xml', 'r') as f:
        irow =-1
        while irow <0:
            hstring = f.read(50000)
            if hstring == "":
                break;
            irow = hstring.find("sheetData")
        if irow < 0:
            return
        ist = hstring.find("<dimension")
        string = hstring[ist+16: ist+50]
        itl = string.find("/>")
        yield  string[:itl-1]
        string = hstring[irow+10:]
        while True:
            irow = string.find("</row>")
            while irow<0:
                hstring = f.read(50000)
                if hstring == "":
                    break;
                string += hstring
                irow = string.find("</row>")
            if irow < 0:
                return
            irow +=6
            ist = string.find("<c")
            yield string[ist:irow-6]
            string = string[irow:]

Drops computation time from minutes to seconds.
Which makes me wonder if there is something similar being considered for openpyxl - a parameter to tell it that is opening a very flat file.

redpajama_set_name: RedPajamaStackExchange


Recent studies among senior-level finance executives show that the cloud has the most transformative potential for their organizations. It's no surprise, then, that cloud-based financial management applications are increasingly replacing on-premises financials.
This report from Financial Executives Research Foundation, sponsored by Workday, provides an overview of the current state of legacy finance systems and insights behind the growing shift to the cloud.
Sign up now to learn why a consensus has grown among CFOs and IT executives about the viability of cloud-based finance systems.


text:
Tarextumab (formerly OMP-59R5) is a fully human monoclonal antibody targeting the Notch 2/3 receptors. It is being tested as a possible treatment for cancer. In January 2015, the US FDA granted orphan drug designation to tarextumab for the treatment of pancreatic cancer and lung cancer. Two early stage clinical trials have reported encouraging results.

See also
 Notch signaling pathway, e.g. in embryo tissue development

References

Experimental cancer drugs
Monoclonal antibodies

redpajama_set_name: RedPajamaWikipedia


text:
Bowlus är en ort i Morrison County i Minnesota. Vid 2010 års folkräkning hade Bowlus 290 invånare.

Källor

Orter i Minnesota
Morrison County


Earn and continually justify the trust and respect of investors, partners, and customers based on our knowledge, integrity, and dedication to their success.
Employ and retain a highly educated, experienced and well-trained staff that speaks multiple languages, demonstrates cultural sensitivity, and takes leadership roles in our fields of finance.
Apply ethical and best business practices in every company activity.
Promote and maintain transparency and accessibility for investors and strategic partners.
Originate and develop high-quality products and services through the creativity, innovation and excellence of our work.
Create principled and innovative investment solutions for institutional and high net-worth investors and provide them with superior risk-adjusted returns.
Provide in-depth structuring and placement services to companies seeking to raise capital or make their products and services Shariah-compliant.
Generate opportunities for strategic partners to originate new principled investment products and housing finance solutions.
Develop and offer values-based residential mortgage and financial products, and foster home ownership through expansion of housing finance markets in emerging and advanced economies.
Assemble, retain and draw upon an independent, authoritative and respected Shariah Supervisory Board.
Guidance Financial Group creates highly innovative and successful investment products on a global basis to meet the needs of institutional investors. We specialize in developing private equity, real estate, and fixed income investment products for these investors, as well as solutions for participants in the primary and secondary housing finance sectors.
In addition, we bring companies into being that provide housing finance and other financial services to underserved consumer populations in both developed and emerging markets. We build on an expertise developed in our two highly successful companies, a consumer finance business in the United States and a specialist housing finance provider in Saudi Arabia.
Our Guidance Investments subsidiary is charged with conceiving and realizing the novel investment products for institutional investors, collaborating with strategic partners when beneficial. We have originated a portfolio of nine private equity, real estate, and leasing funds, all of which have been approved and are monitored by our distinguished Shariah Supervisory Board. Our Capital Markets division enables companies in the Gulf Region to issue Islamic bonds that tap Asian and other demand for Middle East debt. We continue to expand our investment products on a global basis within our three targeted asset classes and develop new solutions to housing finance challenges in emerging markets.
Guidance is part of Capital Guidance, a private investment firm with nearly 50 years of global experience as a strategic investor in real estate and developing businesses and a manager of a diversified portfolio of marketable securities and private equity investments.


text:
Volcanic Lightning Could Aid Hazard Response During Eruptions
Lightning and ash plume dynamics reflected eruption behavior and signaled the onset of fast-moving rock and gas flows during the 2015 eruption of Chile's Calbuco volcano.
by Sarah Stanley 15 April 2016 15 April 2016
A volcanic ash plume dwarfs the city of Puerto Montt in southern Chile just after the start of the eruption of Calbuco volcano on 22 April 2015. The radially expanding umbrella cloud is clearly visible, with ash moving in different directions due to wind shear. Credit: Carolina Barría Kemp, CC BY-SA 2.0
Source: Geophysical Research Letters
In the evening of 22 April 2015, Calbuco volcano began to erupt, forcing more than 6500 nearby residents to evacuate. For several days, ash ejected by the eruption disrupted air travel and damaged buildings in Chile, Argentina, and Uruguay. Calbuco is a 2015-meter stratovolcano located in southern Chile, and before 2015, it hadn't erupted since 1972. Its last major eruption in 1961 also produced an ash plume. Now, researchers have used satellite and lightning data to reconstruct the 2015 eruption and its behavior.
Van Eaton et al. used data from the Geostationary Operational Environmental Satellite 13 (GOES 13) to track the growth of the ash-rich "umbrella cloud" that reached several kilometers above the volcano. The plume dispersed to the north and northeast, depositing a total of about 0.5 cubic kilometer of ash.
The eruption also caused more than 1000 cloud-to-ground lightning flashes. The researchers investigated the timing and location of the strokes using data from the World Wide Lightning Location Network, which employs ground sensors to detect lightning's electromagnetic signals.
The scientists found a sharp increase in lightning flashes close to Calbuco just after the formation of pyroclastic density currents (PDCs)—destructive flows of ash, gas, and other volcanic debris that swept down the flanks of the mountain. On the basis of thermodynamic modeling, the authors propose that the intensified lightning was triggered by an electrical charge layer created by the PDCs.
The intensified lightning and formation of PDCs also coincided with the end of upwind growth of the ash umbrella—that is, the radial expansion of the umbrella cloud in the upwind direction (pictured in this animation; upwind direction is lower left). During eruptions of similar volcanoes, the researchers speculate, these combined observations could be used as a signal that PDCs have formed.
The team also found that certain changes in volcanic lightning and plume dynamics corresponded to the eruption's start time, duration, and material ejection rate. For similar eruptions, such changes could be used to predict ash dispersal and minimize hazards to nearby communities and infrastructure. (Geophysical Research Letters, doi:10.1002/2016GL068076, 2016)
—Sarah Stanley, Freelance Writer
Citation: Stanley, S. (2016), Volcanic lightning could aid hazard response during eruptions, Eos, 97, doi:10.1029/2016EO050231. Published on 15 April 2016.
Text © 2016. The authors. CC BY-NC-ND 3.0
Except where otherwise noted, images are subject to copyright. Any reuse without express permission from the copyright owner is prohibited.
Taal Eruption and Ashfall Continue; Thousands Still at Risk
Anticipating Climate Impacts of Major Volcanic Eruptions
The Art of Volcanic Ash Modeling 10 Years After Eyjafjallajökull
Tagged: Explosive volcanism, Geophysical Research Letters, Hazards & Disasters, Remote sensing of volcanoes, Volcanic hazards and risks, Volcano monitoring, Volcanoclastic deposits

redpajama_set_name: RedPajamaCommonCrawl


text:
WATCH: Cyclists saddle up for island games challenge
0 comments, 20/06/2017 , by Keegan Murray, in Headlines, News, Sport, Videos
Shetland's cyclists will have their endurance tested when they hit the roads in Gotland, with each member of the squad participating in three events.
Strength and tactical riding will also be a must with each event requiring a different approach from the competitors. In the town centre, criterium riders will race around a short track in central Visby for 50 minutes.
Any cyclist lapped during that period will be removed from the race, at which point a frantic five lap dash will decide the victors.
Crashes are not uncommon in the criterium with so many cyclists on the road at one time.
First-time competitor Iain McDiarmid described the event as "a bunch of mad bastards riding around in circles trying not to crash."
There was no doubt that a criterium was a more "hostile" event than the time trials which Shetland cyclists were more familiar with from local competitions, added John William Simpson.
But it was in these events where you discovered your true ability, said Robin Atkinson.
"When you get to do a group ride on the mainland that's when you notice how much power you have. When you're riding in a big group you have to chase wheels."
June Porter, who was part of the table tennis team two years ago, reiterated this, saying that in time trials it was "easier to not push yourself" to your limits.
But in past years it has been in the time trial events in which Shetland have enjoyed most medal success.
Comparing the two, Atkinson said that time trials were like "a candle". There was a steady burning from beginning to end. Road races were more like a box of matches, he said. In these races there are areas of attack where quick bursts of strength were required, but "when you run out of matches it's game over".
Atkinson joked that veteran competitor Carlos Riise was the team's star endurance competitor, and burned energy like a "church candle."
The road races were more dependent on tactics, Simpson said, and riders would have to assess where they should push forward and attack. This was in part due to the flat nature of the Gotland track.
Atkinson said it was key for the riders to get a look at the track before they competed.
"When we get out there we'll get the bikes built then go for a wee recce of the courses to get an idea of what we're up against."
The time trial would help to "settle the nerves" but this meant nothing in the road race if riders had not developed an "idea of where the areas of attack are going to be".
For the first time competitors, there will be a steep learning curve in all of the group events, with time trials making up the bulk of their experience.
McDiarmid joked that he had bought a bike in Shetland 12 years ago as something "that was supposed to be a cheap hobby". Now, "thousands of pounds later", he was faced with the challenge of competing in a town centre criterium.
"That's a warning," he quipped, "it's like drugs."
"Before you know it you're mainlining £7,000 bikes clad in lycra from head to toe."
Island Games
« WATCH: Blues prepare to face-off against gold medal winning Guernsey
Carmichael warns centralising air traffic control would be 'fraught with danger' »
More articles about Cycling, Gotland, Island Games and Shetland
Swimmers bag two more medals on final night
Dinwoodie wins gold as Shetland take two more track medals
High jump silver as Team Shetland wins more medals
Shetland wins three more medals in the pool
First gold for Shetland as MacKay defends title
Swimmers add to Island Games medal tally


text:
/ Drama Books /
Onto the Stage - Slighted Souls and Other Stage and Radio Plays /
Onto the Stage - Slighted Souls and Other Stage and Radio Plays - PDF Preview
Onto the Stage - Slighted Souls and Other Stage and Radio Plays
by BS Murthy
A compendium of the author's Indian stage and radio plays: 'Slighted Souls' revolves around the rebellion of the downtrodden and 'Men at work on Women at work' is all about sexual harassment at workplace. While 'Castle of Despair' is built in the arena of man's despair for success, the radio play 'A Love on Hold' depicts the drama of love and possession.


text:
import hashlib
import logging
import os
import re
import secrets
import sys
import time
import traceback
from functools import _lru_cache_wrapper, lru_cache, wraps
from typing import (
    TYPE_CHECKING,
    Any,
    Callable,
    Dict,
    Generic,
    Iterable,
    List,
    Optional,
    Sequence,
    Tuple,
    TypeVar,
)

from django.conf import settings
from django.core.cache import caches
from django.core.cache.backends.base import BaseCache
from django.db.models import Q
from django.db.models.query import QuerySet
from django.http import HttpRequest
from typing_extensions import ParamSpec

from zerver.lib.utils import make_safe_digest, statsd, statsd_key

if TYPE_CHECKING:
    # These modules have to be imported for type annotations but
    # they cannot be imported at runtime due to cyclic dependency.
    from zerver.models import Attachment, Message, MutedUser, Realm, Stream, SubMessage, UserProfile

MEMCACHED_MAX_KEY_LENGTH = 250

ParamT = ParamSpec("ParamT")
ReturnT = TypeVar("ReturnT")

logger = logging.getLogger()

remote_cache_time_start = 0.0
remote_cache_total_time = 0.0
remote_cache_total_requests = 0

def get_remote_cache_time() -> float:
    return remote_cache_total_time

def get_remote_cache_requests() -> int:
    return remote_cache_total_requests

def remote_cache_stats_start() -> None:
    global remote_cache_time_start
    remote_cache_time_start = time.time()

def remote_cache_stats_finish() -> None:
    global remote_cache_total_time
    global remote_cache_total_requests
    global remote_cache_time_start
    remote_cache_total_requests += 1
    remote_cache_total_time += time.time() - remote_cache_time_start

def get_or_create_key_prefix() -> str:
    if settings.PUPPETEER_TESTS:
        # This sets the prefix for the benefit of the Puppeteer tests.
        #
        # Having a fixed key is OK since we don't support running
        # multiple copies of the Puppeteer tests at the same time anyway.
        return "puppeteer_tests:"
    elif settings.TEST_SUITE:
        # The Python tests overwrite KEY_PREFIX on each test, but use
        # this codepath as well, just to save running the more complex
        # code below for reading the normal key prefix.
        return "django_tests_unused:"

    # directory `var` should exist in production
    os.makedirs(os.path.join(settings.DEPLOY_ROOT, "var"), exist_ok=True)

    filename = os.path.join(settings.DEPLOY_ROOT, "var", "remote_cache_prefix")
    try:
        with open(filename, "x") as f:
            prefix = secrets.token_hex(16) + ":"
            f.write(prefix + "\n")
    except FileExistsError:
        tries = 1
        while tries < 10:
            with open(filename) as f:
                prefix = f.readline()[:-1]
            if len(prefix) == 33:
                break
            tries += 1
            prefix = ""
            time.sleep(0.5)

    if not prefix:
        print("Could not read remote cache key prefix file")
        sys.exit(1)

    return prefix

KEY_PREFIX: str = get_or_create_key_prefix()

def bounce_key_prefix_for_testing(test_name: str) -> None:
    global KEY_PREFIX
    KEY_PREFIX = test_name + ":" + str(os.getpid()) + ":"
    # We are taking the hash of the KEY_PREFIX to decrease the size of the key.
    # Memcached keys should have a length of less than 250.
    KEY_PREFIX = hashlib.sha1(KEY_PREFIX.encode()).hexdigest() + ":"

def get_cache_backend(cache_name: Optional[str]) -> BaseCache:
    if cache_name is None:
        cache_name = "default"
    return caches[cache_name]

def cache_with_key(
    keyfunc: Callable[ParamT, str],
    cache_name: Optional[str] = None,
    timeout: Optional[int] = None,
    with_statsd_key: Optional[str] = None,
) -> Callable[[Callable[ParamT, ReturnT]], Callable[ParamT, ReturnT]]:
    """Decorator which applies Django caching to a function.

    Decorator argument is a function which computes a cache key
    from the original function's arguments.  You are responsible
    for avoiding collisions with other uses of this decorator or
    other uses of caching."""

    def decorator(func: Callable[ParamT, ReturnT]) -> Callable[ParamT, ReturnT]:
        @wraps(func)
        def func_with_caching(*args: ParamT.args, **kwargs: ParamT.kwargs) -> ReturnT:
            key = keyfunc(*args, **kwargs)

            try:
                val = cache_get(key, cache_name=cache_name)
            except InvalidCacheKeyError:
                stack_trace = traceback.format_exc()
                log_invalid_cache_keys(stack_trace, [key])
                return func(*args, **kwargs)

            extra = ""
            if cache_name == "database":
                extra = ".dbcache"

            if with_statsd_key is not None:
                metric_key = with_statsd_key
            else:
                metric_key = statsd_key(key)

            status = "hit" if val is not None else "miss"
            statsd.incr(f"cache{extra}.{metric_key}.{status}")

            # Values are singleton tuples so that we can distinguish
            # a result of None from a missing key.
            if val is not None:
                return val[0]

            val = func(*args, **kwargs)
            if isinstance(val, QuerySet):  # type: ignore[misc] # https://github.com/typeddjango/django-stubs/issues/704
                logging.warning(
                    "cache_with_key attempted to store a full QuerySet object -- flattening using list()",
                    stack_info=True,
                )
                val = list(val)

            cache_set(key, val, cache_name=cache_name, timeout=timeout)

            return val

        return func_with_caching

    return decorator

class InvalidCacheKeyError(Exception):
    pass

def log_invalid_cache_keys(stack_trace: str, key: List[str]) -> None:
    logger.warning(
        "Invalid cache key used: %s\nStack trace: %s\n",
        key,
        stack_trace,
    )

def validate_cache_key(key: str) -> None:
    if not key.startswith(KEY_PREFIX):
        key = KEY_PREFIX + key

    # Theoretically memcached can handle non-ascii characters
    # and only "control" characters are strictly disallowed, see:
    # https://github.com/memcached/memcached/blob/master/doc/protocol.txt
    # However, limiting the characters we allow in keys simiplifies things,
    # and anyway we use make_safe_digest when forming some keys to ensure
    # the resulting keys fit the regex below.
    # The regex checks "all characters between ! and ~ in the ascii table",
    # which happens to be the set of all "nice" ascii characters.
    if not bool(re.fullmatch(r"([!-~])+", key)):
        raise InvalidCacheKeyError("Invalid characters in the cache key: " + key)
    if len(key) > MEMCACHED_MAX_KEY_LENGTH:
        raise InvalidCacheKeyError(f"Cache key too long: {key} Length: {len(key)}")

def cache_set(
    key: str, val: Any, cache_name: Optional[str] = None, timeout: Optional[int] = None
) -> None:
    final_key = KEY_PREFIX + key
    validate_cache_key(final_key)

    remote_cache_stats_start()
    cache_backend = get_cache_backend(cache_name)
    cache_backend.set(final_key, (val,), timeout=timeout)
    remote_cache_stats_finish()

def cache_get(key: str, cache_name: Optional[str] = None) -> Any:
    final_key = KEY_PREFIX + key
    validate_cache_key(final_key)

    remote_cache_stats_start()
    cache_backend = get_cache_backend(cache_name)
    ret = cache_backend.get(final_key)
    remote_cache_stats_finish()
    return ret

def cache_get_many(keys: List[str], cache_name: Optional[str] = None) -> Dict[str, Any]:
    keys = [KEY_PREFIX + key for key in keys]
    for key in keys:
        validate_cache_key(key)
    remote_cache_stats_start()
    ret = get_cache_backend(cache_name).get_many(keys)
    remote_cache_stats_finish()
    return {key[len(KEY_PREFIX) :]: value for key, value in ret.items()}

def safe_cache_get_many(keys: List[str], cache_name: Optional[str] = None) -> Dict[str, Any]:
    """Variant of cache_get_many that drops any keys that fail
    validation, rather than throwing an exception visible to the
    caller."""
    try:
        # Almost always the keys will all be correct, so we just try
        # to do normal cache_get_many to avoid the overhead of
        # validating all the keys here.
        return cache_get_many(keys, cache_name)
    except InvalidCacheKeyError:
        stack_trace = traceback.format_exc()
        good_keys, bad_keys = filter_good_and_bad_keys(keys)

        log_invalid_cache_keys(stack_trace, bad_keys)
        return cache_get_many(good_keys, cache_name)

def cache_set_many(
    items: Dict[str, Any], cache_name: Optional[str] = None, timeout: Optional[int] = None
) -> None:
    new_items = {}
    for key in items:
        new_key = KEY_PREFIX + key
        validate_cache_key(new_key)
        new_items[new_key] = items[key]
    items = new_items
    remote_cache_stats_start()
    get_cache_backend(cache_name).set_many(items, timeout=timeout)
    remote_cache_stats_finish()

def safe_cache_set_many(
    items: Dict[str, Any], cache_name: Optional[str] = None, timeout: Optional[int] = None
) -> None:
    """Variant of cache_set_many that drops saving any keys that fail
    validation, rather than throwing an exception visible to the
    caller."""
    try:
        # Almost always the keys will all be correct, so we just try
        # to do normal cache_set_many to avoid the overhead of
        # validating all the keys here.
        return cache_set_many(items, cache_name, timeout)
    except InvalidCacheKeyError:
        stack_trace = traceback.format_exc()

        good_keys, bad_keys = filter_good_and_bad_keys(list(items.keys()))
        log_invalid_cache_keys(stack_trace, bad_keys)

        good_items = {key: items[key] for key in good_keys}
        return cache_set_many(good_items, cache_name, timeout)

def cache_delete(key: str, cache_name: Optional[str] = None) -> None:
    final_key = KEY_PREFIX + key
    validate_cache_key(final_key)

    remote_cache_stats_start()
    get_cache_backend(cache_name).delete(final_key)
    remote_cache_stats_finish()

def cache_delete_many(items: Iterable[str], cache_name: Optional[str] = None) -> None:
    keys = [KEY_PREFIX + item for item in items]
    for key in keys:
        validate_cache_key(key)
    remote_cache_stats_start()
    get_cache_backend(cache_name).delete_many(keys)
    remote_cache_stats_finish()

def filter_good_and_bad_keys(keys: List[str]) -> Tuple[List[str], List[str]]:
    good_keys = []
    bad_keys = []
    for key in keys:
        try:
            validate_cache_key(key)
            good_keys.append(key)
        except InvalidCacheKeyError:
            bad_keys.append(key)

    return good_keys, bad_keys

# Generic_bulk_cached fetch and its helpers.  We start with declaring
# a few type variables that help define its interface.

# Type for the cache's keys; will typically be int or str.
ObjKT = TypeVar("ObjKT")

# Type for items to be fetched from the database (e.g. a Django model object)
ItemT = TypeVar("ItemT")

# Type for items to be stored in the cache (e.g. a dictionary serialization).
# Will equal ItemT unless a cache_transformer is specified.
CacheItemT = TypeVar("CacheItemT")

# Type for compressed items for storage in the cache.  For
# serializable objects, will be the object; if encoded, bytes.
CompressedItemT = TypeVar("CompressedItemT")

# Required arguments are as follows:
# * object_ids: The list of object ids to look up
# * cache_key_function: object_id => cache key
# * query_function: [object_ids] => [objects from database]
# * setter: Function to call before storing items to cache (e.g. compression)
# * extractor: Function to call on items returned from cache
#   (e.g. decompression).  Should be the inverse of the setter
#   function.
# * id_fetcher: Function mapping an object from database => object_id
#   (in case we're using a key more complex than obj.id)
# * cache_transformer: Function mapping an object from database =>
#   value for cache (in case the values that we're caching are some
#   function of the objects, not the objects themselves)
def generic_bulk_cached_fetch(
    cache_key_function: Callable[[ObjKT], str],
    query_function: Callable[[List[ObjKT]], Iterable[ItemT]],
    object_ids: Sequence[ObjKT],
    *,
    extractor: Callable[[CompressedItemT], CacheItemT],
    setter: Callable[[CacheItemT], CompressedItemT],
    id_fetcher: Callable[[ItemT], ObjKT],
    cache_transformer: Callable[[ItemT], CacheItemT],
) -> Dict[ObjKT, CacheItemT]:
    if len(object_ids) == 0:
        # Nothing to fetch.
        return {}

    cache_keys: Dict[ObjKT, str] = {}
    for object_id in object_ids:
        cache_keys[object_id] = cache_key_function(object_id)

    cached_objects_compressed: Dict[str, Tuple[CompressedItemT]] = safe_cache_get_many(
        [cache_keys[object_id] for object_id in object_ids],
    )

    cached_objects: Dict[str, CacheItemT] = {}
    for (key, val) in cached_objects_compressed.items():
        cached_objects[key] = extractor(cached_objects_compressed[key][0])
    needed_ids = [
        object_id for object_id in object_ids if cache_keys[object_id] not in cached_objects
    ]

    # Only call query_function if there are some ids to fetch from the database:
    if len(needed_ids) > 0:
        db_objects = query_function(needed_ids)
    else:
        db_objects = []

    items_for_remote_cache: Dict[str, Tuple[CompressedItemT]] = {}
    for obj in db_objects:
        key = cache_keys[id_fetcher(obj)]
        item = cache_transformer(obj)
        items_for_remote_cache[key] = (setter(item),)
        cached_objects[key] = item
    if len(items_for_remote_cache) > 0:
        safe_cache_set_many(items_for_remote_cache)
    return {
        object_id: cached_objects[cache_keys[object_id]]
        for object_id in object_ids
        if cache_keys[object_id] in cached_objects
    }

def transformed_bulk_cached_fetch(
    cache_key_function: Callable[[ObjKT], str],
    query_function: Callable[[List[ObjKT]], Iterable[ItemT]],
    object_ids: Sequence[ObjKT],
    *,
    id_fetcher: Callable[[ItemT], ObjKT],
    cache_transformer: Callable[[ItemT], CacheItemT],
) -> Dict[ObjKT, CacheItemT]:
    return generic_bulk_cached_fetch(
        cache_key_function,
        query_function,
        object_ids,
        extractor=lambda obj: obj,
        setter=lambda obj: obj,
        id_fetcher=id_fetcher,
        cache_transformer=cache_transformer,
    )

def bulk_cached_fetch(
    cache_key_function: Callable[[ObjKT], str],
    query_function: Callable[[List[ObjKT]], Iterable[ItemT]],
    object_ids: Sequence[ObjKT],
    *,
    id_fetcher: Callable[[ItemT], ObjKT],
) -> Dict[ObjKT, ItemT]:
    return transformed_bulk_cached_fetch(
        cache_key_function,
        query_function,
        object_ids,
        id_fetcher=id_fetcher,
        cache_transformer=lambda obj: obj,
    )

def preview_url_cache_key(url: str) -> str:
    return f"preview_url:{make_safe_digest(url)}"

def display_recipient_cache_key(recipient_id: int) -> str:
    return f"display_recipient_dict:{recipient_id}"

def display_recipient_bulk_get_users_by_id_cache_key(user_id: int) -> str:
    # Cache key function for a function for bulk fetching users, used internally
    # by display_recipient code.
    return "bulk_fetch_display_recipients:" + user_profile_by_id_cache_key(user_id)

def user_profile_cache_key_id(email: str, realm_id: int) -> str:
    return f"user_profile:{make_safe_digest(email.strip())}:{realm_id}"

def user_profile_cache_key(email: str, realm: "Realm") -> str:
    return user_profile_cache_key_id(email, realm.id)

def user_profile_delivery_email_cache_key(delivery_email: str, realm: "Realm") -> str:
    return f"user_profile_by_delivery_email:{make_safe_digest(delivery_email.strip())}:{realm.id}"

def bot_profile_cache_key(email: str, realm_id: int) -> str:
    return f"bot_profile:{make_safe_digest(email.strip())}"

def user_profile_by_id_cache_key(user_profile_id: int) -> str:
    return f"user_profile_by_id:{user_profile_id}"

def user_profile_by_api_key_cache_key(api_key: str) -> str:
    return f"user_profile_by_api_key:{api_key}"

realm_user_dict_fields: List[str] = [
    "id",
    "full_name",
    "email",
    "avatar_source",
    "avatar_version",
    "is_active",
    "role",
    "is_billing_admin",
    "is_bot",
    "timezone",
    "date_joined",
    "bot_owner_id",
    "delivery_email",
    "bot_type",
    "long_term_idle",
]

def realm_user_dicts_cache_key(realm_id: int) -> str:
    return f"realm_user_dicts:{realm_id}"

def get_muting_users_cache_key(muted_user_id: int) -> str:
    return f"muting_users_list:{muted_user_id}"

def get_realm_used_upload_space_cache_key(realm: "Realm") -> str:
    return f"realm_used_upload_space:{realm.id}"

def active_user_ids_cache_key(realm_id: int) -> str:
    return f"active_user_ids:{realm_id}"

def active_non_guest_user_ids_cache_key(realm_id: int) -> str:
    return f"active_non_guest_user_ids:{realm_id}"

bot_dict_fields: List[str] = [
    "api_key",
    "avatar_source",
    "avatar_version",
    "bot_owner_id",
    "bot_type",
    "default_all_public_streams",
    "default_events_register_stream__name",
    "default_sending_stream__name",
    "email",
    "full_name",
    "id",
    "is_active",
    "realm_id",
]

def bot_dicts_in_realm_cache_key(realm: "Realm") -> str:
    return f"bot_dicts_in_realm:{realm.id}"

def get_stream_cache_key(stream_name: str, realm_id: int) -> str:
    return f"stream_by_realm_and_name:{realm_id}:{make_safe_digest(stream_name.strip().lower())}"

def delete_user_profile_caches(user_profiles: Iterable["UserProfile"]) -> None:
    # Imported here to avoid cyclic dependency.
    from zerver.lib.users import get_all_api_keys
    from zerver.models import is_cross_realm_bot_email

    keys = []
    for user_profile in user_profiles:
        keys.append(user_profile_by_id_cache_key(user_profile.id))
        for api_key in get_all_api_keys(user_profile):
            keys.append(user_profile_by_api_key_cache_key(api_key))
        keys.append(user_profile_cache_key(user_profile.email, user_profile.realm))
        keys.append(
            user_profile_delivery_email_cache_key(user_profile.delivery_email, user_profile.realm)
        )
        if user_profile.is_bot and is_cross_realm_bot_email(user_profile.email):
            # Handle clearing system bots from their special cache.
            keys.append(bot_profile_cache_key(user_profile.email, user_profile.realm_id))

    cache_delete_many(keys)

def delete_display_recipient_cache(user_profile: "UserProfile") -> None:
    from zerver.models import Subscription  # We need to import here to avoid cyclic dependency.

    recipient_ids = Subscription.objects.filter(user_profile=user_profile).values_list(
        "recipient_id", flat=True
    )
    keys = [display_recipient_cache_key(rid) for rid in recipient_ids]
    keys.append(display_recipient_bulk_get_users_by_id_cache_key(user_profile.id))
    cache_delete_many(keys)

def changed(update_fields: Optional[Sequence[str]], fields: List[str]) -> bool:
    if update_fields is None:
        # adds/deletes should invalidate the cache
        return True

    update_fields_set = set(update_fields)
    return any(f in update_fields_set for f in fields)

# Called by models.py to flush the user_profile cache whenever we save
# a user_profile object
def flush_user_profile(
    *,
    instance: "UserProfile",
    update_fields: Optional[Sequence[str]] = None,
    **kwargs: object,
) -> None:
    user_profile = instance
    delete_user_profile_caches([user_profile])

    # Invalidate our active_users_in_realm info dict if any user has changed
    # the fields in the dict or become (in)active
    if changed(update_fields, realm_user_dict_fields):
        cache_delete(realm_user_dicts_cache_key(user_profile.realm_id))

    if changed(update_fields, ["is_active"]):
        cache_delete(active_user_ids_cache_key(user_profile.realm_id))
        cache_delete(active_non_guest_user_ids_cache_key(user_profile.realm_id))

    if changed(update_fields, ["role"]):
        cache_delete(active_non_guest_user_ids_cache_key(user_profile.realm_id))

    if changed(update_fields, ["email", "full_name", "id", "is_mirror_dummy"]):
        delete_display_recipient_cache(user_profile)

    # Invalidate our bots_in_realm info dict if any bot has
    # changed the fields in the dict or become (in)active
    if user_profile.is_bot and changed(update_fields, bot_dict_fields):
        cache_delete(bot_dicts_in_realm_cache_key(user_profile.realm))

def flush_muting_users_cache(*, instance: "MutedUser", **kwargs: object) -> None:
    mute_object = instance
    cache_delete(get_muting_users_cache_key(mute_object.muted_user_id))

# Called by models.py to flush various caches whenever we save
# a Realm object.  The main tricky thing here is that Realm info is
# generally cached indirectly through user_profile objects.
def flush_realm(
    *,
    instance: "Realm",
    update_fields: Optional[Sequence[str]] = None,
    from_deletion: bool = False,
    **kwargs: object,
) -> None:
    realm = instance
    users = realm.get_active_users()
    delete_user_profile_caches(users)

    if (
        from_deletion
        or realm.deactivated
        or (update_fields is not None and "string_id" in update_fields)
    ):
        cache_delete(realm_user_dicts_cache_key(realm.id))
        cache_delete(active_user_ids_cache_key(realm.id))
        cache_delete(bot_dicts_in_realm_cache_key(realm))
        cache_delete(realm_alert_words_cache_key(realm))
        cache_delete(realm_alert_words_automaton_cache_key(realm))
        cache_delete(active_non_guest_user_ids_cache_key(realm.id))
        cache_delete(realm_rendered_description_cache_key(realm))
        cache_delete(realm_text_description_cache_key(realm))
    elif changed(update_fields, ["description"]):
        cache_delete(realm_rendered_description_cache_key(realm))
        cache_delete(realm_text_description_cache_key(realm))

def realm_alert_words_cache_key(realm: "Realm") -> str:
    return f"realm_alert_words:{realm.string_id}"

def realm_alert_words_automaton_cache_key(realm: "Realm") -> str:
    return f"realm_alert_words_automaton:{realm.string_id}"

def realm_rendered_description_cache_key(realm: "Realm") -> str:
    return f"realm_rendered_description:{realm.string_id}"

def realm_text_description_cache_key(realm: "Realm") -> str:
    return f"realm_text_description:{realm.string_id}"

# Called by models.py to flush the stream cache whenever we save a stream
# object.
def flush_stream(
    *,
    instance: "Stream",
    update_fields: Optional[Sequence[str]] = None,
    **kwargs: object,
) -> None:
    from zerver.models import UserProfile

    stream = instance
    items_for_remote_cache = {}

    if update_fields is None:
        cache_delete(get_stream_cache_key(stream.name, stream.realm_id))
    else:
        items_for_remote_cache[get_stream_cache_key(stream.name, stream.realm_id)] = (stream,)
        cache_set_many(items_for_remote_cache)

    if (
        update_fields is None
        or "name" in update_fields
        and UserProfile.objects.filter(
            Q(default_sending_stream=stream) | Q(default_events_register_stream=stream)
        ).exists()
    ):
        cache_delete(bot_dicts_in_realm_cache_key(stream.realm))

def flush_used_upload_space_cache(
    *,
    instance: "Attachment",
    created: bool = True,
    **kwargs: object,
) -> None:
    attachment = instance

    if created:
        cache_delete(get_realm_used_upload_space_cache_key(attachment.owner.realm))

def to_dict_cache_key_id(message_id: int) -> str:
    return f"message_dict:{message_id}"

def to_dict_cache_key(message: "Message", realm_id: Optional[int] = None) -> str:
    return to_dict_cache_key_id(message.id)

def open_graph_description_cache_key(content: bytes, request: HttpRequest) -> str:
    return "open_graph_description_path:{}".format(make_safe_digest(request.META["PATH_INFO"]))

def flush_message(*, instance: "Message", **kwargs: object) -> None:
    message = instance
    cache_delete(to_dict_cache_key_id(message.id))

def flush_submessage(*, instance: "SubMessage", **kwargs: object) -> None:
    submessage = instance
    # submessages are not cached directly, they are part of their
    # parent messages
    message_id = submessage.message_id
    cache_delete(to_dict_cache_key_id(message_id))

class IgnoreUnhashableLruCacheWrapper(Generic[ParamT, ReturnT]):
    def __init__(
        self, function: Callable[ParamT, ReturnT], cached_function: "_lru_cache_wrapper[ReturnT]"
    ) -> None:
        self.key_prefix = KEY_PREFIX
        self.function = function
        self.cached_function = cached_function
        self.cache_info = cached_function.cache_info
        self.cache_clear = cached_function.cache_clear

    def __call__(self, *args: ParamT.args, **kwargs: ParamT.kwargs) -> ReturnT:
        if settings.DEVELOPMENT and not settings.TEST_SUITE:  # nocoverage
            # In the development environment, we want every file
            # change to refresh the source files from disk.
            return self.function(*args, **kwargs)

        if self.key_prefix != KEY_PREFIX:
            # Clear cache when cache.KEY_PREFIX changes. This is used in
            # tests.
            self.cache_clear()
            self.key_prefix = KEY_PREFIX

        try:
            return self.cached_function(
                *args, **kwargs  # type: ignore[arg-type] # might be unhashable
            )
        except TypeError:
            # args or kwargs contains an element which is unhashable. In
            # this case we don't cache the result.
            pass

        # Deliberately calling this function from outside of exception
        # handler to get a more descriptive traceback. Otherwise traceback
        # can include the exception from cached_function as well.
        return self.function(*args, **kwargs)

def ignore_unhashable_lru_cache(
    maxsize: int = 128, typed: bool = False
) -> Callable[[Callable[ParamT, ReturnT]], IgnoreUnhashableLruCacheWrapper[ParamT, ReturnT]]:
    """
    This is a wrapper over lru_cache function. It adds following features on
    top of lru_cache:

        * It will not cache result of functions with unhashable arguments.
        * It will clear cache whenever zerver.lib.cache.KEY_PREFIX changes.
    """
    internal_decorator = lru_cache(maxsize=maxsize, typed=typed)

    def decorator(
        user_function: Callable[ParamT, ReturnT]
    ) -> IgnoreUnhashableLruCacheWrapper[ParamT, ReturnT]:
        return IgnoreUnhashableLruCacheWrapper(user_function, internal_decorator(user_function))

    return decorator

def dict_to_items_tuple(user_function: Callable[..., Any]) -> Callable[..., Any]:
    """Wrapper that converts any dict args to dict item tuples."""

    def dict_to_tuple(arg: Any) -> Any:
        if isinstance(arg, dict):
            return tuple(sorted(arg.items()))
        return arg

    def wrapper(*args: Any, **kwargs: Any) -> Any:
        new_args = (dict_to_tuple(arg) for arg in args)
        return user_function(*new_args, **kwargs)

    return wrapper

def items_tuple_to_dict(user_function: Callable[..., Any]) -> Callable[..., Any]:
    """Wrapper that converts any dict items tuple args to dicts."""

    def dict_items_to_dict(arg: Any) -> Any:
        if isinstance(arg, tuple):
            try:
                return dict(arg)
            except TypeError:
                pass
        return arg

    def wrapper(*args: Any, **kwargs: Any) -> Any:
        new_args = (dict_items_to_dict(arg) for arg in args)
        new_kwargs = {key: dict_items_to_dict(val) for key, val in kwargs.items()}
        return user_function(*new_args, **new_kwargs)

    return wrapper

redpajama_set_name: RedPajamaGithub


text:
Luke Bryan Invites Hurricane Harvey Responders to Houston Concert
Billy Dukes Published: September 12, 2017
Gustavo Cabellero, Getty Images
Luke Bryan was a surprise last-minute addition to the all-network Hand in Hand hurricane relief concert on Tuesday night, but he's not resting when he's done. The singer has invited first responders to his Sept. 22 concert in Houston and turned it into a benefit for the Houston Community Fund.
Proceeds from next Friday's show at the Cynthia Woods Mitchell Pavilion will go to the non-profit. The Huntin', Fishin' and Lovin' Every Day Tour rushes through Texas next weekend, with stops in Austin, Houston and Dallas. After that he'll begin the Farm Tour, which benefits a different charitable cause.
Early on during the Hand in Hand: A Benefit for Hurricane Relief concert Bryan was seen answering phones and taking donations. He's joined by dozens of celebrities including many from country music. Blake Shelton was the second performer, singing "Stand By Me" with Usher. Tim McGraw and Faith Hill are also slated to be there while George Strait, Miranda Lambert, Chris Stapleton and more will appear from San Antonio.
Viewers are encouraged to call 1-800-258-6000 to donate or text "Give" to 80077 to make a $25 donation. Several country stars like Chris Young and Granger Smith have gotten personally involved with the relief effort, setting up or supporting fundraising initiatives. Miranda Lambert brought her animal rescue charity to south Texas to help.
Miranda Lambert Steps Up for Hurricane Victims
Next: Donate to the Hurricane Relief Fund
Filed Under: Luke Bryan
Luke Bryan's Wife Went Hunting With Her Boys, and She Regrets It
Luke Bryan Sets the Record Straight on His 'Absurd' Dustin Lynch Comments at Crash My Playa
Luke Bryan and Lionel Richie Pal Around Onstage at Crash My Playa [Watch]
Look Out, Mexico! Luke Bryan's Mama Has Arrived for Crash My Playa
The 2023 iHeartCountry Festival Lineup Is a Country Fan's Dream Come True
Caroline Bryan Just Had an Epic Mom Fail


Are you Looking for Ann Cusack Age, Birthday, Height, Net Worth, Family, Salary, Weight etc..? Find the latest complete information. Ann Cusack was born on 22 May 1961, in Manhattan, New York, United States. She is an Actress , Singer known for her famous movies like- Malice (1993), Renaissance Man (1994), Tank Girl (1995), The Point of Betrayal (1995), The Point of Betrayal (1995), The Birdcage (1996), My Fellow Americans (1996), Multiplicity (1996).
Ann is one of the 5 children of her parents.
She made her debut in movies in 1992 through A League of Their Own. She has appeared in movies like- Malice (1993), Renaissance Man (1994), Tank Girl (1995), The Point of Betrayal (1995), The Point of Betrayal (1995), The Birdcage (1996), My Fellow Americans (1996), Multiplicity (1996), Midnight in the Garden of Good and Evil (1997), Grosse Pointe Blank (1997), Cannes Man (1997), Peoria Babylon (1997), Stigmata (1999), What Planet Are You From? (2000), America's Sweethearts (2001), Accepted (2006), The Sensation of Sight (2006), Arc (2006), The Neighbor (2007), Cake: A Wedding Story (2007), The Informant! (2009), Love at First Hiccup (2009), Crooked Lane (2010), Nightcrawler (2014), Sully (2016), Heart, Baby (2017), The Three Lucias.
She has appeared in main or recurring roles in TV shows such as- The Jeff Foxworthy Show, Maggie, The Brotherhood of Poland- New Hampshire, The Unit, Private Practice, Better Call Saul.


Camelina microcarpa Andrz. ex DC.
Annuals. Stems unbranched or branched distally, (0.8-)2-8 (-10) dm, densely to moderately hirsute basally, trichomes simple, to 2.5 mm, often mixed branched ones, (glabrescent distally). Basal leaves withered by anthesis. Cauline leaves: blade lanceolate, narrowly oblong, or linear-lanceolate, (0.8-)1.5-5.5(-7) cm × 1-10(-20) mm, base sagittate or minutely auriculate, margins entire or, rarely, remotely denticulate, (often subciliate), apex acute, surfaces pubescent, trichomes primarily simple. Fruiting pedicels ascending, 4-14(-17) mm. Flowers: sepals 2-3.5 × 0.5-1 mm; petals pale yellow, (2.5-) 3-4(-6) × 1-2 mm; filaments 1.5-3 mm; anthers ca. 0.5 mm. Fruits pyriform to narrowly so, 3.5-5(-7) × 2-4(-5) mm, apex acute; valves each often with obscure midvein, margin narrowly winged; style 1-3.5 mm. Seeds reddish brown or brown, 0.8-1.4(-1.5) × 0.5-0.6 mm. 2n = 40. Flowering May-Jul. Farms, fields, meadows, prairies, roadsides, forest margins, open woods; 0-2500 m; introduced; Alta., B.C., Man., N.B., Nfld. and Labr., N.W.T., N.S., Nunavut, Ont., P.E.I., Que., Sask., Yukon; Ala., Ariz., Calif., Colo., Conn., Del., D.C., Idaho, Ill., Ind., Iowa, Kans., Ky., La., Maine, Md., Mass., Mich., Minn., Mo., Mont., Nebr., Nev., N.H., N.J., N.Mex., N.Y., N.C., N.Dak., Ohio, Okla., Oreg., Pa., R.I., S.Dak., Tenn., Tex., Utah, Vt., Va., Wash., W.Va., Wis., Wyo.; Europe; Asia; n Africa; introduced also in South America.
Annual herb 30 cm - 0.7 m tall Stem: upright, densely covered with simple and star-shaped grayish hairs (mainly on lower part). Flowers: in loosely branched clusters, pale yellow, 4 - 5 mm long, 1.2 mm wide at apex. Petals four. Stamens six. Fruit: a pod, on 4 - 9 mm long stalks, upright, 2.5 - 5 mm long, to 4 mm wide, nearly round but slightly flattened, keeled, with a beak up to 2 mm long. Seeds reddish brown, about 1 mm long, oblong, triangular in cross-section, smooth, slightly glossy. Lower leaves: alternate, 5 - 6 cm long, 1.5 - 2 cm wide, oblong, densely covered with simple and star-shaped grayish hairs. Upper leaves: alternate, stalkless, clasping, smaller than lower leaves (progressively reducing in size), lance-shaped, base lobed (typically pointed), sometimes with a few small teeth along the margins near the tip, hairy.
Similar species: The similar Camelina sativa bears larger fruit.
Habitat and ecology: Introduced from Europe. An infrequent weed of cultivated fields, waste ground, and roadsides. It is also found in nursery plots, sandy fields, and along railroads.
Notes: This plant is best viewed when the sky is overcast, because the flowers close and shrivel on sunny, warm days.
Etymology: Camelina comes from the Greek words camai, meaning dwarf, and linon, meaning flax (the term "dwarf" being used to mean "false"). Microcarpa means small-fruited.
This species is essentially a sandy ballast plant and is more or less frequent throughout the state. I have found it also along sandy roadsides and in sandy, fallow fields where I once found it as an abundant weed.
Erect, 3-7 dm, rough-hairy; lvs entire or remotely denticulate; frs erect, 2.5-5 mm, obscurely rugulose, on pedicels 4-9 mm; seeds ca 1 mm; 2n=40. Fields and waste places, usually in sandy soil; native of the Old World, established as a casual weed throughout most of the U.S. and s. Can. Apr.-June.


text:
Q: Display the closest future time to now from database In my Ruby on Rails application I want to be able to display the next future time in the database that is the closest to the current time, e.g., in the database if there are records with the times 13:00, 13:30, 18:00, 19:00 etc.  And, if the time currently is 13:48 the time 18:00 will be displayed. I have a similar thing working with the date:
<% film.showings.take(1).each do |showing| %>
    <%= film.showings.select{|s| s.show_date >= Date.today}.sort_by(&:show_date).first.show_date.strftime("%A %e %B %Y") %>
<% end %>

But attempting to adapt this with the time:
<% film.showings.take(1).each do |showing| %>
    <%= film.showings.select{|s| s.show_time >= Time.now}.sort_by(&:show_time).first.show_time %>
<% end %>

This does not work and I get the following error:
undefined method `show_time' for nil:NilClas

which occurs because of s.show_time >= Time.now. If I change this to s.show_time = Time.now the error goes but then it just displays the current time and not the time from the database.
It is worth noting that the show_date and show_time are in the same record, for example the first record could have a date of 26/01/2015 and a time of 22:00. What I want is to display the time of records where the date is in the future and show that date's first time, as could have two records in the database with a date of 26/01/2015 and one with a time of 22:00 and another with a time of 22:30.
Can anyone help?

A: In your example, you loading the entire database into memory, then filtering it to find the row with the time you want. I'd let the database do all the work instead.
film.showings.where("show_time >= ?", Time.now).order(show_time: :asc).first

That doesn't answer your actual original problem where it appeared there were no suitable times even though you think there should be. You may or may not still have this problem with this approach -- if you do, debugging it will be different than debugging your "all in memory with ruby" original approach, so I'd start out with this, then debug by looking at the SQL generated, etc.
On the other hand, if you only expect a dozen or so results to filter, maybe your approach is fine too.
Additionally, if every row in your database has one date and one time -- I'd change your database schema to use a combined date+time value in one column. Ordinarily this is the best way to go. For a movie database, I could see separating date and time might make sense -- but if every row has ONE date and ONE time already, then there's no disadvantage to combining them as a datetime, and that's what I'd do. I suspect your bug may go away if you do that -- you should be able to do it with separate date and time, sure, but combined makes more sense, and will be less confusing to deal with in ruby too.

A: It's very strange code.
But I think it doesn't find suitable records.
Try this:
<% film.showings.take(1).each do |showing| %>
  <%= film.showings.select{|s| s.show_time >= Time.now}.sort_by(&:show_time).first.try(:show_time) %>
<% end %>

If it doesn't crash, I'm right.


Test automation in Salesforce is the need of the hour as it is best customer relationship software and removing bugs at regular intervals with the speed of thought is important to survive in this business. The software is a merciless business where even minuscule error can get magnified into losses of millions of dollars when the code gets implemented. It also leads to erosion of brand equity in the market.
How companies cope with the challenge?
Salesforce is a robust dynamic prospect management and customer retention tool that sees three new releases every year. The reason is that it is a global player catering to numerous industries and their ever evolving requirement. Companies these days have to do more with less. And Salesforce understands this too well and therefore users in fast improvement and fast delivery cycles.
The more customers that are added to Salesforce ecosystem, the more functionality will be demanded. For this mode, the code needs to be written and more bugs will be created and the best way to remove bugs is to fix them at the development stage itself.
The earlier method of testing the whole code after it is written is out and a new paradigm shift based on automation is being witnessed. Vendors responsible for salesforce implementation get around this problem of removing bugs in software through the method of pair programming where two developers work on one system wherein one develops the code, the other tests the code for its accuracy at the same time.
Most companies that have high-quality assurance parameters and have CMM Level 5 rating and ISO certification often go for this system but it proves to be costly for another start -ups.
So they go in for manual testing that includes both black box testing and white box testing. One kind of testing, just tests whether the code can deliver the desired results or output. While the other kind of testing actually tests the code for its syntax, consistency, and accuracy. The good quality code is always fast, optimized and is light-weight meaning it occupies the minimum lines of code and still delivers flawless results.
Being the global leader in CRMproducts,salesforce benefits immensely from automated testing that can prove to be critical in deciding the success or failure of customer campaigns.
There are several new modules that are being added to the salesforce suite of products and each new functionality needs to be tested thoroughly for its robustness before it can be actually released in the market.
There are already functionalities that are there in salesforce for lead tracking; daily sales report generation, prospect management, invoicing, and many such tools, so automated testing is best in order to add functionalities fast.
Manual testing can be boring and is prone to errors and it is time-consuming. Developers usually have twelve minutes to write a particular piece of code in the software business and it can get very stressful at times leading to errors which emerge as bugs as the program does not run properly. The code developed should be such that it can execute itself flawlessly at the browser of the end user and delight teams working on it.
Moreover, speed is of the essence in the software business and if you cannot test thousands of lines of code within minutes, you are bound to be outclassed by your competitors.Salesforce and its implementation partners cannot afford that and believe implicitly in agile software development that can only be possible by bringing manual testing role down to 5 to 20% from the existing 60-70% it occupies in the development process.
If you are seeking to drive exponential growth with revenue visibility and desire a flawless salesforce solution that is immersed in the cloud and is mobile based, then you need to employ automated testing to increase the velocity of the development process.


text:
Q: Is it possible to get code editors in virtualenv? I recently downloaded virtualenv on my MacOSX Sierra (10.12.2). I'm not very experienced with virtualenv and I've been coding using the interactive interpreter in terminal and I was wondering if there was an alternate way that I could use an editor(IDLE, Sublime, etc.) and still use it in virtualenv. Would I just install an editor into virtualenv or am I limited to only the interactive shell?

A: You are not limited to only interactive shell. For your coding part you can download and install sublime text and open your project (any project irrespective of the language you use) and get started. Here is a quick guide for getting started in sublime text : sublime text getting started
You might also want to take a look at this post: SublimeREPL plugin

A: You can use atom editor, inside that you can use virtualenv plugin


Thumbs up, you've finally set your mind on going to Barcelona under the Erasmus + programme! Two options are available: studying or completing an internship. Worrying about how you will pay for your stay abroad? You might be able to get an Erasmus grant through your home institution. The monthly grant varies according to the country you live in and the country you are heading to. The Erasmus grant simply gives a significant boost to student mobility: don't expect it to cover all your expenses abroad.
Aiming to spend your third academic year in Berlin under the Erasmus programme? Accommodation, student insurance, travel expenses: paying for a 12-month stay abroad can be tricky. You'd better start dealing with all the financial aspects well in advance. Students who go abroad under the study mobility programme are often entitled to receive an Erasmus grant. The amount of money you get every month depends primarily on the country you visit. Usually, a student will receive between 150€ and 300€ per month. Want to know how you can apply for an Erasmus grant? Get in touch with the International Office of your institution.
Did you just secure an internship in an Italian import-export company? Congratulations! You've landed your dream internship but you are still desperately hunting for funding solutions. If your institution signed the extended Erasmus University Charter, you may go abroad under the placement mobility programme and might be able to receive an Erasmus grant. Here again, internship grant rates depend on the country of destination but they are usually somewhat higher than those of study grants: students receive between 300 and 450 € per month.
Here's the picture: you will receive a 370 € monthly grant during your year in Berlin. You also just discovered that accommodation is going to cost you no less than 500 € per month… Bear in mind that the Erasmus grant is a supplement: this means that you can continue to receive all the grants you may be entitled to in your home country while also benefiting from an Erasmus grant. By adding up grants, you could end up covering most of your expenses.
To learn all about the Erasmus programme, browse the European Commission website.
Communities (towns, cities, regions and departments) often provide grants to students going abroad.


What used to be a problem that affects only certain industries like petrochemicals, pharmaceuticals, energy, and so on, have begun to be relevant challenges to diverse industries today. Think in recent terms, many organizations spanning financial institutions, e-commerce, and consumer goods companies, that are affected by cybersecurity lapses, data and privacy leaks, and you see new crises evolving to affect just about any organization. So there is a need for any organization to know how best to deal with a crisis, and communicate to all stakeholders.
When a crisis strikes, some organizations then begin to hunt around for a public relations (PR) agency with the belief that PR practitioners can smooth over any crisis and get the organization out of the damage to its reputation and brand.
So, should an organization hire a PR agency? Should an organization only hire a PR agency when a crisis strikes? What are the best practices for crisis management and crisis communication? What should an organization do after a crisis is mediated and resolved?
Generally, many large enterprises are fully staffed with PR and communications professionals who assist the leadership team in tweaking or developing crisis communication and management programs. They also simultaneously retain external PR agencies so that in the event of any crisis large and small, more people are on board to think and work through the crisis.
By engaging an external PR counsel, the organizations avoid the "echo chamber" effect where internal employees may inadvertently hold inward-looking views and may not have considered macro perspectives from the outside.
In a crisis, the best strategy is to tell the truth, even if it hurts.
After the crisis has been managed properly and hopefully resolved, the enterprise should do a post-mortem and continue to refine its crisis management and communication program. A crisis is only a crisis if one is ill-prepared, but only an obstacle if one is prepared. There are still some organizations without a crisis management and communication program. I would advise such organizations to expediently work on one.
A crisis is a crisis if one is ill-prepared, but merely an obstacle if one is prepared.
Companies should work on a corporate-wide crisis communication and management program, and permeate it throughout the organizations.
Training is a necessary first step, and organizations must also ensure coherence in how everyone from the CEO to the front desk receptionist are aware of an in-house crisis communication and management program.
Often, organizations look for "media training", which primarily educate corporate leaders on how best to work with the media during media interviews. However, organizations should also ensure key leaders are educated in both media interviews and crisis communication. Just as you will always be presented with safety procedures when you board a plane or a cruise ship, organizations must not simply set up a crisis communication and management program and then forget it. Regular and sometimes unscheduled drills should be implemented so that everyone in the organization can be prepared for crises. Think "Kaizen 改善" (the Japanese management philosophy of "continuous improvement").
Get external counsel to be your 'red team" to help identify flaws and vulnerabilities during such crisis drills, so that the crisis communication and management program can be as comprehensive as possible.
The crisis communication and management program should always be a "live" document, kept up to date with the times. In the modern context, we often advocate the crisis communication and management program not just printed on paper, but in an intranet wiki or knowledgebase, so that it can be updated quickly and easily accessed by internal leaders and employees.
When a crisis is imminent, quickly bring together the action teams.
For example, if it is a cybersecurity lapse and data leakage, the top management, legal, information technology (IT), and external counsel, should converge to discuss the course of action based on an existing crisis communicaiton and management program (this is the premise).
The program would contain designated spokespersons, communication policies, contact workflow, communication preferences (whether issuing statements or a media event), collaterals such as statements, news releases, frequently asked questions (FAQs), etc.
Remember, it is wise to be prepared for crises BEFORE they occur, rather than drag people together only during a crisis.
Different organizations have different procedures and programs. It all depends on how they work out their crisis management and communication programs. Also, each crisis communication and management program may be proprietary material. Some basic parameters persist.
For example, the ultimate stakeholder in the organization may be the designated spokesperson, assisted by functional leaders who have a part to play in the crisis involved.
For example, in a common case of data leaks or cybersecurity incident, the CISO (chief information security officer) or some related leader may be present. If there are legal implications, the top legal officer will be involved. If it involves employee mistreatment or some human capital related, the human capital leader will be involved.
The summit is always lonely, and only people of character can scale to to top, and it demands the whole being to stay on top.
So, in a crisis, a leader needs to tell the whole truth, nothing but the truth, and tell it quickly without delay.
In such a dark and weak hour for the organization, the leader also needs to converge the employees together to stand as one. Behind telling the truth, however painful it seems, remember that once the problem is resolved, all things will pass over the passage of time.
Can we balance integrity with stakeholder relations?
A brand is only valuable if it has universal meaning.
A brand that has made missteps, but make corrective measures, shows humility in the process, can be forgiven, and can bounce back.
However, if a brand and the organization behind the brand, upon making missteps, fails to make reparations and corrective measures, shows a cold, aloof and arrogant attitude, the brand will only diminish.
Customer loyalty is fickle these days, and the wise leaders will always understand that customers can easily march elsewhere, and that there are options. Ultimately, the customer is king. Without customers, any investor, employee, stakeholder, will count as nothing.
The crux of a successful crisis management and communication program has to be one that is already in place, permeated throughout the entire organization, with truth, ethics and integrity at the center of the program. Such a program will, in our perspective, converge the best industry practices of how mission-critical environments manage and thrive in any crisis. In all things, tell the truth, the whole truth, and expediently without fail.
PS – For more information on our methodology of crisis management and communication converging decades of media relations and aviation best practices for any organization, visit our program page.
PPS – This full length piece was inspired by some thoughts I shared with a Financial Times journalist (who subsequently published a quote from me).