text
stringlengths
29
850k
import random CARD_VALUES = { 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14, } CARD_SUITS = { 'H': u'\u2665', 'S': u'\u2660', 'C': u'\u2663', 'D': u'\u2666', } CARD_SERIALIZE = { # Tuples of (from_original_hand, suit, value) (True, 'H', 2): chr(0), (True, 'H', 3): chr(1), (True, 'H', 4): chr(2), (True, 'H', 5): chr(3), (True, 'H', 6): chr(4), (True, 'H', 7): chr(5), (True, 'H', 8): chr(6), (True, 'H', 9): chr(7), (True, 'H', 10): chr(8), (True, 'H', 'J'): chr(9), (True, 'H', 'Q'): chr(10), (True, 'H', 'K'): chr(11), (True, 'H', 'A'): chr(12), (True, 'S', 2): chr(13), (True, 'S', 3): chr(14), (True, 'S', 4): chr(15), (True, 'S', 5): chr(16), (True, 'S', 6): chr(17), (True, 'S', 7): chr(18), (True, 'S', 8): chr(19), (True, 'S', 9): chr(20), (True, 'S', 10): chr(21), (True, 'S', 'J'): chr(22), (True, 'S', 'Q'): chr(23), (True, 'S', 'K'): chr(24), (True, 'S', 'A'): chr(25), (True, 'C', 2): chr(26), (True, 'C', 3): chr(27), (True, 'C', 4): chr(28), (True, 'C', 5): chr(29), (True, 'C', 6): chr(30), (True, 'C', 7): chr(31), (True, 'C', 8): chr(32), (True, 'C', 9): chr(33), (True, 'C', 10): chr(34), (True, 'C', 'J'): chr(35), (True, 'C', 'Q'): chr(36), (True, 'C', 'K'): chr(37), (True, 'C', 'A'): chr(38), (True, 'D', 2): chr(39), (True, 'D', 3): chr(40), (True, 'D', 4): chr(41), (True, 'D', 5): chr(42), (True, 'D', 6): chr(43), (True, 'D', 7): chr(44), (True, 'D', 8): chr(45), (True, 'D', 9): chr(46), (True, 'D', 10): chr(47), (True, 'D', 'J'): chr(48), (True, 'D', 'Q'): chr(49), (True, 'D', 'K'): chr(50), (True, 'D', 'A'): chr(51), (False, 'H', 2): chr(52), (False, 'H', 3): chr(53), (False, 'H', 4): chr(54), (False, 'H', 5): chr(55), (False, 'H', 6): chr(56), (False, 'H', 7): chr(57), (False, 'H', 8): chr(58), (False, 'H', 9): chr(59), (False, 'H', 10): chr(60), (False, 'H', 'J'): chr(61), (False, 'H', 'Q'): chr(62), (False, 'H', 'K'): chr(63), (False, 'H', 'A'): chr(64), (False, 'S', 2): chr(65), (False, 'S', 3): chr(66), (False, 'S', 4): chr(67), (False, 'S', 5): chr(68), (False, 'S', 6): chr(69), (False, 'S', 7): chr(70), (False, 'S', 8): chr(71), (False, 'S', 9): chr(72), (False, 'S', 10): chr(73), (False, 'S', 'J'): chr(74), (False, 'S', 'Q'): chr(75), (False, 'S', 'K'): chr(76), (False, 'S', 'A'): chr(77), (False, 'C', 2): chr(78), (False, 'C', 3): chr(79), (False, 'C', 4): chr(80), (False, 'C', 5): chr(81), (False, 'C', 6): chr(82), (False, 'C', 7): chr(83), (False, 'C', 8): chr(84), (False, 'C', 9): chr(85), (False, 'C', 10): chr(86), (False, 'C', 'J'): chr(87), (False, 'C', 'Q'): chr(88), (False, 'C', 'K'): chr(89), (False, 'C', 'A'): chr(90), (False, 'D', 2): chr(91), (False, 'D', 3): chr(92), (False, 'D', 4): chr(93), (False, 'D', 5): chr(94), (False, 'D', 6): chr(95), (False, 'D', 7): chr(96), (False, 'D', 8): chr(97), (False, 'D', 9): chr(98), (False, 'D', 10): chr(99), (False, 'D', 'J'): chr(100), (False, 'D', 'Q'): chr(101), (False, 'D', 'K'): chr(102), (False, 'D', 'A'): chr(103), } CARD_DESERIALIZE = {val: key for key, val in CARD_SERIALIZE.items()} class Card(object): def __init__(self, suit, value, from_original_hand=True): self.suit = suit self.value = value self.from_original_hand = from_original_hand self._validate() def _validate(self): if self.value not in CARD_VALUES: raise ValueError('Bad card value', self.value) if self.suit not in CARD_SUITS: raise ValueError('Bad card suit', self.suit) @property def pretty(self): return u'%2s%s' % (self.value, CARD_SUITS[self.suit]) def is_better(self, other_card, trump, lead_suit): if self.suit == other_card.suit: return CARD_VALUES[self.value] > CARD_VALUES[other_card.value] # If the suits are different, then at most 1 is trump and at # most 1 is the lead suit. if self.suit == trump: return True elif other_card.suit == trump: return False if self.suit == lead_suit: return True elif other_card.suit == lead_suit: return False # If neither card is one of the relevant suits, their comparison # is irrelevant, but `self` is certainly not `is_better`. return False def serialize(self): return CARD_SERIALIZE[(self.from_original_hand, self.suit, self.value)] @classmethod def deserialize(cls, char): from_original_hand, suit, value = CARD_DESERIALIZE[char] return cls(suit, value, from_original_hand=from_original_hand) class Deck(object): def __init__(self): self.current_index = 0 self.cards = [] for value in CARD_VALUES.keys(): for suit in CARD_SUITS.keys(): new_card = Card(suit, value) self.cards.append(new_card) def shuffle(self): random.shuffle(self.cards) self.current_index = 0 def draw_card(self): result = self.cards[self.current_index] self.current_index += 1 return result def random_deck(): deck = Deck() deck.shuffle() return deck
This is Part 2 of an article introducing R for patent analytics that focuses on visualising patent data in R using the ggplot2 package. In Part 1 we introduced the basics of wrangling patent data in R using the dplyr package to select and add data. In this article we will go into more detail on these functions. We then focused on using qplot from the ggplot2 package to illustrate the ease with which graphics can be created and edited in R. In this article we will focus on ggplot and the Grammar of Graphics. As in Part 1 we assume that you are new to R and make no assumptions about familiarity with R. However, you must have RStudio installed on your computer (see Part 1) for instructions. We will also move a little faster on some of the initial steps than in Part 1. The majority of examples in this article are based on the list of recipes for generating graphics using ggplot2 in Winston Chang's R Graphics Cookbook and the accompanying website. This article is a work in progress and will be updated as solutions are identified to some of the issues encountered in graphing using ggplot2. Please feel welcome to add comments to this post, particularly where you identify a solution to issues. ggplot2 is an implementation of Leland Wilkinson’s Grammar of Graphics by Hadley Wickham at RStudio as described in this article and ggplot2 book. Hadley Wickham’s grammar differs from the original by focusing on layered approach to building statistical graphics. A base object. The first two of these components combine into a base object consisting of the data set and aesthetic mappings or aes for the particular data we want to see. That includes the axes and any fill or line colours. geoms or geometric objects. We then add one or more geom to specify the form in which we want to see the data we have selected in 1. This tends to also involve a statistical transformation (such as placing data into bins for a bar chart). Defaults deal with some of this. However, a statistical transformation or stat can also be specified. A coordinate system. We normally don’t need to think about this. The default is a standard Cartesian grid. However, this can be changed to a fixed grid or a polar grid. The base object defines what we want to see. The geoms define the form we want to see it in. The coordinate system defines the framework for the visualisation. As with any grammar it can take a while to get used to its terms and peculiarities. The good news is that there are plenty of free resources out there for this very popular package. Winston Chang’s R Graphics Cookbook website is a very valuable practical guide to most things you will want to do with ggplot2. The full R Graphics Cookbook goes into a lot more detail and is an invaluable reference if you will be doing a lot of work with graphics in R. Those with budgets may also want to invest in Hadley Wickham’s book ggplot2 published by Springer. RStudio have developed a very helpful cheat sheet that you can download here or view here. We suggest downloading and printing the cheat sheet when using ggplot2. We will load the pizza dataset directly from the Github datasets repository using read_csv from the readr package. If downloading from the repository note that it is the View Raw file that you want. If loading from a downloaded file include the full file path inside quotation marks. As in Part 1 we will use dplyr to create a count field using the publication number, rename some of the fields and then select fields we want to count. Inspecting our data is a first step. Type View(pizza) in the console to see the table and str(pizza) to see its structure. In practice we have a number of issues that we will want to fix. We have a blank row at the bottom of the dataset that we will want to remove because it will produce a red error message. It does not have to be removed but this will help in interpreting any error messages. Patent data commonly doesn’t contain numeric fields. Data fields are mainly characters or dates with the exception at times of cited and citing counts. We will want to add a count column. We will not be working with all 31 columns in pizza and so we will want to select just those we will be working with. To save typing we may want to rename some of the columns (and we can revert the names later if need be). Some data may be missing for particular countries. For example, for Canada some of the entries are missing a year field. That may be fine for raw totals but not for charting by year. To handle these tasks we can use the very useful functions in dplyr. For other tasks we might also want to use tidyr or plyr as sister packages to dplyr. dplyr's main functions are described here. These are the functions we think you will find most useful with patent data. dplyr functions are important because they will help you to easily extract elements of the data for graphing. They can also be very useful for basic patent analysis workflows where tools such as Excel or Open Office will struggle. For more on wrangling data using dplyr and tidyr see the RStudio Data Wrangling Cheatsheet. dplyr also includes pipes, such as %>% (meaning then) that can be used to string together chunks of code in an efficient and easy to use way. We will illustrate the use of pipes in this article but will not use pipes throughout as we are adopting a simple step by step approach. As you become more familiar and comfortable with R we suggest that you increasingly start to work with pipes to make your life easier. We caution against leaping into pipes when learning R. While they are very easy to use and efficient, they are still relatively new. That can make reading ‘normal’ R code difficult until you are more familiar with it. We will now use two dplyr functions. First we will add a column with a numeric value for each publication number in the dataset using mutate. mutate takes an argument applied to the values of one or more columns and adds a new column based on that argument. Here, as in Part 1 we simply add a new column called n that uses sum() to award each publication number the value of 1. We now have a numeric count column n from our character vectors. Next we will rename the columns to make life easier using rename(). The code has been indented to make it easier to read. To run this code, select the code and press Run in R or press command and enter. We will create a new working table called p1 that contains just the data we want to work with using dplyr's select(). select() will only include columns that we name and will drop the others from the new table. p1 will be our reference set and contains 4 columns, use View(p1) to see it. If we were to inspect this data we would see that we have some sparse results dating back to the 1940s. In the last article we controlled for this in graphs using xlim to limit the x axis to specific years. Here we will remove that data. To remove the sparse years we need to use dplyrs filter function. filter is basically the equivalent of select for rows. Rather than naming each of the years that we want to remove we will us an operator for values equal or greater than 1970 >=. We will also want to pull back from the data cliff in more recent years as discussed in Part 1. To do that we will add a second argument to filter for years that are equal to or below 2012 <=. Note here that dplyr functions can take more than one argument at a time. So we do not need to repeat the function for each filter operation. For a list of other operators see this quick table. We can now go ahead and create a publication total table pt using count() in dplyr. count is actually a wrapper for two other dplyr functions, group_by and summarise. We do not need to use those because count does that for us. Note here that wt for weight will sum the value of n for us (see ?count for details). If we inspect pt we will see that we now have totals for each year. We might want to add a rank or percentage column to that for later use. There are a variety of ways of going about this. However, staying with dplyr, behind the scenes count function has grouped the data for us (see ?count). To understand this use str(pt) in the console to view the data. This will reveal that we have a grouped data frame with attributes. To go further we will ungroup the table first. [Note that ungrouping is not normally necessary but is used here because of an unexpected problem calculating a percentage on a grouped table using sum(n) in dplyr]. ## 1 1970 2. 1 0.0223 0. This neatly demonstrates how easy it is to use mutate to add columns based on different calculations. The reason that we are focusing on adding counts to the publication total table is that when graphing later we can use these columns to split and order the graphics. This is particularly helpful because with patent data we normally have widely varying scores that produce crunched graphs. The availability of either buckets or percentages is very helpful for creating ranked bar charts or plots and faceting (trellis graphs). As we often want to see what happens with a graph before deciding how to proceed or drop data it is useful to have a ranking system. We can then filter the data using function at a later stage. We will follow the same procedure for the publication country table. However, in this case we will illustrate the use of pipes to simplify the process. We will use the most common pipe %>%, which means “then”. This basically says, “this” then “that”. Select and run the code.
#!/usr/bin/python import sys sys.path += ["../scripts/"] import pdf # a test for transparency groups: # form xobjects used for doing transparency groups can do savestate (q) # without ever needing to do a corresponding restorestate (Q) because # their content stream is self-contained. # # Test that this doesn't confuse the pdf reader. file = pdf.PDF() page = file.add_page(612,100) group1 = file.create_object("/XObject", "/Form") group1.stream = """ 0.0 1.0 0.0 rg 0.0 0.0 0.0 RG 10 10 m 70 10 l 70 70 l 10 70 l 10 10 l f 10 10 m 70 10 l 70 70 l 10 70 l 10 10 l s 0.0 0.0 1.0 rg 0.0 0.0 0.0 RG 30 30 m 90 30 l 90 90 l 30 90 l 30 30 l f 30 30 m 90 30 l 90 90 l 30 90 l 30 30 l s 1.0 0 0 1.0 1000 1000 cm q 1.0 0 0 1.0 1000 1000 cm q 1.0 0 0 1.0 1000 1000 cm q 1.0 0 0 1.0 1000 1000 cm q """ isolated = "true" knockout = "true" group1["/Group"] = pdf.PDFDict({"/S": "/Transparency", "/CS": "/DeviceRGB", "/I": isolated, "/K": knockout}) group1["/BBox"] = pdf.PDFArray([0, 0, 100, 100]) gs = file.create_object("/ExtGState") gs["/BM"] = "/Normal" gs["/CA"] = "1.0" # stroke alpha gs["/ca"] = "1.0" # fill alpha resources = file.create_object("/Resources") resources["/XObject"] = pdf.PDFDict({"/mygroup": group1}) resources["/ExtGState"] = pdf.PDFDict({"/gs0": gs}) page.header["/Resources"] = resources page.stream = """q 1.0 0.0 0.0 rg 0 40 m 612 40 l 612 60 l 0 60 l 0 40 l f q /gs0 gs 1.0 0 0 1.0 0 0 cm /mygroup Do Q Q""" file.write("transpstack.pdf")
HTML5 validated. WCAG compliant. Page generated in 0.4535 seconds.
# Copyright (c) 2016 currentsea, Joseph Bull # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # from __future__ import absolute_import import time import json import hmac import base64 import hashlib import requests import datetime import bitfinex_properties from websocket import create_connection # from decouple import config class BitfinexPrivate: def __init__(self, apiKey=bitfinex_properties.BITFINEX_API_KEY, apiSecret=bitfinex_properties.BITFINEX_API_SECRET, wsUrl=bitfinex_properties.WEBSOCKET_URL, apiUrl=bitfinex_properties.REST_API_URL): self.apiKey = apiKey self.apiSecret = apiSecret self.wsUrl = wsUrl self.apiUrl = apiUrl self.connectWebsocket() self.symbols = self.getSymbols() self.channelMappings = self.getChannelMappings() def connectWebsocket(self): try: self.ws = create_connection(self.wsUrl) except: raise return True def getSymbols(self): symbolsApiEndpoint = self.apiUrl + "/symbols" print ("SYMBOLS ENDPOINT: " + symbolsApiEndpoint) try: req = requests.get(symbolsApiEndpoint) reqJson = req.json() except: raise return reqJson def subscribeAllChannels(self): # for symbol in self.symbols: # self.ws.send(json.dumps({"event": "subscribe", "channel": "book", "pair": symbol, "prec": "P0", "len":"100"})) # self.ws.send(json.dumps({"event": "subscribe", "channel": "ticker", "pair": symbol})) # self.ws.send(json.dumps({"event": "subscribe", "channel": "trades", "pair": symbol})) # # payload = {"event": "auth", "apiKey": self.apiKey} # payload = # payloadBytes = bytes(payload, encoding='utf-8') # encodedData = base64.standard_b64encode(payloadBytes) theNonce = float(time.time() * 1000000) theNonceStr = 'AUTH' + str(theNonce) hashDigest = hmac.new(self.apiSecret.encode('utf8'), theNonceStr.encode('utf-8'), hashlib.sha384) # encodedData.encode('utf-8') signature = hashDigest.hexdigest() payload = hashDigest.update(theNonceStr.encode('utf-8')) reqBody = { "event": "auth", "apiKey": str(self.apiKey), "authSig": str(signature), "authPayload": str(payload) } # authJson = json.dumps(reqBody) self.ws.send(json.dumps(reqBody)) def getNonce(self): curTime = time.time() nonce = str(int(curTime * 1000000)) authNonce = 'AUTH' + nonce return authNonce # def signPayload(self, payload): # return { # "X-BFX-APIKEY": API_KEY, # "X-BFX-SIGNATURE": signature, # "X-BFX-PAYLOAD": data # } # var # crypto = require('crypto'), # api_key = 'API_KEY', # api_secret = 'API_SECRET', # payload = 'AUTH' + (new Date().getTime()), # signature = crypto.createHmac("sha384", api_secret).update(payload).digest('hex'); # w.send(JSON.stringify({ # event: "auth", # apiKey: api_key, # authSig: signature, # authPayload: payload # })); # // request # { # "event":"auth", # "status":"OK", # "chanId":0, # "userId":"<USER_ID>" # } def getMappingAuthentication(self): payload = 'AUTH' + datetime.datetime.utcnow() def getChannelMappings(self): allChannelsSubscribed = False channelDict = {} channelMappings = {} self.subscribeAllChannels() while (allChannelsSubscribed == False): resultData = self.ws.recv() print (resultData) try: dataJson = json.loads(resultData) pairName = str(dataJson["pair"]) pairChannelType = str(dataJson["channel"]) identifier = pairName channelId = dataJson["chanId"] channelDict[channelId] = identifier channelMappings[channelId] = dataJson print ("SUBSCRIBE TO CHANNEL " + str(channelId) + " WITH PAIR NAME: " + pairName) symbolLength = len(self.symbols) # CHANNELS ARE ALL SUBSCRIBED WHEN SYMBOL LENGTH * # # # # # # # # targetLength = symbolLength * 3 targetLength = targetLength + 1 # targetLength = 4 # fuck it # IF THIS SAVED YOU HOURS OF DEBUGGING, YOU'RE FUCKING WELCOME * # if (len(channelDict) == targetLength): allChannelsSubscribed = True except TypeError: pass except KeyError: pass except: raise return channelMappings if __name__ == "__main__": that = BitfinexPrivate() # "event":"auth", # "status":"OK", # "chanId":0, # "userId":"<USER_ID>" # }
In an exercise it is usual for a piece of work to be assessed twice. A student assesses their work before submitting it and the teacher then (re)assesses the work. The teacher's assessment uses the student's assessment as the starting point. An exercise allows the teacher to award a proportion of the grade to the student's assessment, the remainder of the grade is allocated to the teacher's assessment of the work. (The maximum grades for these are called "Grade for Student Assessments" and "Grade for Submissions" respectively.) Note that the grade from the student's assessment is not used. The student's assessment is given a grade based on how well it matches the teacher's assessment. The degree of agreement between the student's and teacher's assessment is based on the differences between the scores in individual elements (actually the squared differences are used). The mean of these differences must be converted into a meaningful grade. The "Comparison of Assessments" option allows the teacher a degree of control on how these comparisons are converted into grades. To get some idea on what effect this option has, take the (fairly simple) case of an assessment which has ten Yes/No questions. For example the assessment might use questions like "Is the chart correctly formatted?", "Is the calculated profit $100.66?", etc. Assume there are ten such questions. When the "Very Lax" setting is chosen, perfect agreement between the student's and teacher's assessment gives a grade of 100%, if there is only one question which does not match the grade is 90%, two disagreements give a grade of 80%, three disagreements 70%, etc.. That might seem very reasonable and you might be thinking why is this option called a "Very Lax" comparison. Well, consider the case of a student doing a completely random assessment where the answers of the ten questions are simply guessed. On average this would result in five of the ten questions being matched. So the "monkey's" assessment would get a grade of around 50%. The situation gets a little more sensible with the "Lax" option, then the random assessment gets around 20%. When the "Fair" option is chosen, random guessing will result in a zero grade most of the time. At this level, a grade of 50% is given when the two assessments agree on eight questions of the ten. If three questions are in disagreement then the grade given is 25%. When the option is set to "Strict" having two questions out of sync gives a grade of 40%. Moving into the "Very Strict" territory a disagreement in just two questions drops the grade to 35% and having a single question in disagreement gives a grade of 65%. This example is slightly artificial as most assessments usually have elements which have a range of values rather than just Yes or No. In those cases the comparison is likely to result in somewhat higher grades than the values indicated above. The various levels (Very Lax, Lax, Fair...) are given so that the teacher can fine tune the comparisons. If they feel that the grades being given for assessments are too low then this option should be moved towards the "Lax" or even "Very Lax" choices. And alternatively, if the grades for the student's assessments are, in general, felt to be too high this option should be moved to either the "Strict" or "Very Strict" choices. It is really a matter of trial and error with the best starting point being the "Fair" option. During the course of the exercise the teacher may feel that the grades given to the student assessments are either too high or too low. These grades are shown on the exercise's Administration Page. In this case, the teacher can change the setting of this option and re-calculate the student assessment grades (the "Grading Grades"). The re-calculation is done by clicking the "Re-grade Student Assessments" link found on the administration page of the exercise. This can be safely performed at any time in the exercise.
""" File: canvasdemo1.py uthor: Kenneth A. Lambert """ from breezypythongui import EasyFrame import random class CanvasDemo(EasyFrame): """Draws filled ovals on a canvas.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, title = "Canvas Demo 1") self.colors = ("blue", "green", "red", "yellow") # Canvas self.canvas = self.addCanvas(row = 0, column = 0, width = 300, height = 150, background = "gray") # Command button self.ovalButton = self.addButton(text = "Draw oval", row = 1, column = 0, command = self.drawOval) # Event handling method def drawOval(self): """Draws a filled oval at a random position.""" x = random.randint(0, 300) y = random.randint(0, 150) color = random.choice(self.colors) self.canvas.drawOval(x, y, x + 25, y + 25, fill = color) # Instantiate and pop up the window.""" if __name__ == "__main__": CanvasDemo().mainloop()
Happy World Oceans Day from the Plastiki team! For those of you who couldn’t make it down to Selfridges, London for the Plastiki book signing and amazing talk ‘Tales from the Deep’, with Plastiki expedition leader David de Rothschild last week, then never fear, you can catch up on the goings on through the videos below. ‘Tales from the Deep’ was the final talk in Project Oceans’ stand out series, featuring Surfers for Sewage champion Chris Hines MBE, Philip Hoare, author of Leviathan, Willie Mackenzie from Greenpeace UK and David de Rothschild. The group of diverse speakers conveyed an inspiring passion for our oceans and discussed some of the serious issues faced by the big blue and her inhabitants. Click HERE to watch the video. David de Rothschild at the Plastiki book signing Selfridges.
# This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. # TODO: add a __getitem__ method to get the tag of a file from __future__ import (absolute_import, division, print_function) from os.path import exists, abspath, realpath, expanduser, sep import string from ranger import PY3 from ranger.core.shared import FileManagerAware ALLOWED_KEYS = string.ascii_letters + string.digits + string.punctuation class Tags(FileManagerAware): default_tag = '*' def __init__(self, filename): # COMPAT: The intent is to get abspath/normpath's behavior of # collapsing `symlink/..`, abspath is retained for historical reasons # because the documentation states its behavior isn't necessarily in # line with normpath's. self._filename = realpath(abspath(expanduser(filename))) self.sync() def __contains__(self, item): return item in self.tags def add(self, *items, **others): if len(*items) == 0: return tag = others.get('tag', self.default_tag) self.sync() for item in items: self.tags[item] = tag self.dump() def remove(self, *items): if len(*items) == 0: return self.sync() for item in items: try: del self.tags[item] except KeyError: pass self.dump() def toggle(self, *items, **others): if len(*items) == 0: return tag = others.get('tag', self.default_tag) tag = str(tag) if tag not in ALLOWED_KEYS: return self.sync() for item in items: try: if item in self and tag in (self.tags[item], self.default_tag): del self.tags[item] else: self.tags[item] = tag except KeyError: pass self.dump() def marker(self, item): if item in self.tags: return self.tags[item] return self.default_tag def sync(self): try: if PY3: fobj = open(self._filename, 'r', errors='replace') else: fobj = open(self._filename, 'r') except OSError as err: if exists(self._filename): self.fm.notify(err, bad=True) else: self.tags = dict() else: self.tags = self._parse(fobj) fobj.close() def dump(self): try: fobj = open(self._filename, 'w') except OSError as err: self.fm.notify(err, bad=True) else: self._compile(fobj) fobj.close() def _compile(self, fobj): for path, tag in self.tags.items(): if tag == self.default_tag: # COMPAT: keep the old format if the default tag is used fobj.write(path + '\n') elif tag in ALLOWED_KEYS: fobj.write('{0}:{1}\n'.format(tag, path)) def _parse(self, fobj): result = dict() for line in fobj: line = line.rstrip('\n') if len(line) > 2 and line[1] == ':': tag, path = line[0], line[2:] if tag in ALLOWED_KEYS: result[path] = tag else: result[line] = self.default_tag return result def update_path(self, path_old, path_new): self.sync() changed = False for path, tag in self.tags.items(): pnew = None if path == path_old: pnew = path_new elif path.startswith(path_old + sep): pnew = path_new + path[len(path_old):] if pnew: del self.tags[path] self.tags[pnew] = tag changed = True if changed: self.dump() def __nonzero__(self): return True __bool__ = __nonzero__ class TagsDummy(Tags): """A dummy Tags class for use with `ranger --clean`. It acts like there are no tags and avoids writing any changes. """ def __init__(self, filename): # pylint: disable=super-init-not-called self.tags = dict() def __contains__(self, item): return False def add(self, *items, **others): pass def remove(self, *items): pass def toggle(self, *items, **others): pass def marker(self, item): return self.default_tag def sync(self): pass def dump(self): pass def _compile(self, fobj): pass def _parse(self, fobj): pass
Beautiful Nora Hall's rise from the London slums to the power centers of Washington, Hyannisport, and Hollywood begins with her first meeting with millionaire Hubert Hartiscor and continues with her elusive search for love. 35,000 first printing. $25,000 ad/promo. June Flaum Singer was born in Union City, New Jersey, daughter of a professional strongman. At college she won the Miss Ohio State University title before marrying Joe Singer, son of novelist I.J. singer and nephew Nobel laureate, I.B. Singer. Daughters Sharon and Brett are published writers as well. She currently lives in Bel Air, California.
# Copyright 2015-2018 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). """The base class that all handlers must extend.""" __all__ = [ "HandlerError", "HandlerPKError", "HandlerValidationError", "Handler", ] from functools import wraps from operator import attrgetter from django.contrib.postgres.fields import ArrayField from django.core.exceptions import ValidationError from django.db.models import Model from django.utils.encoding import is_protected_type from maasserver import concurrency from maasserver.permissions import NodePermission from maasserver.prometheus.middleware import wrap_query_counter_cursor from maasserver.rbac import rbac from maasserver.utils.forms import get_QueryDict from maasserver.utils.orm import transactional from maasserver.utils.threads import deferToDatabase from provisioningserver.prometheus.metrics import PROMETHEUS_METRICS from provisioningserver.utils.twisted import asynchronous, IAsynchronous DATETIME_FORMAT = "%a, %d %b. %Y %H:%M:%S" def dehydrate_datetime(datetime): """Convert the `datetime` to string with `DATETIME_FORMAT`.""" if datetime is None: return "" else: return datetime.strftime(DATETIME_FORMAT) class HandlerError(Exception): """Generic exception a handler can raise.""" class HandlerNoSuchMethodError(HandlerError): """Raised when an handler doesn't have that method.""" class HandlerPKError(HandlerError): """Raised when object is missing its primary key.""" class HandlerValidationError(HandlerError, ValidationError): """Raised when object fails to validate on create or update.""" class HandlerDoesNotExistError(HandlerError): """Raised when an object by its `pk` doesn't exist.""" class HandlerPermissionError(HandlerError): """Raised when permission is denied for the user of a given action.""" def __init__(self): super().__init__("Permission denied") class HandlerOptions: """Configuraton class for `Handler`. Provides the needed defaults to the internal `Meta` class used on the handler. """ abstract = False allowed_methods = [ "list", "get", "create", "update", "delete", "set_active", ] handler_name = None object_class = None queryset = None list_queryset = None pk = "id" pk_type = int fields = None exclude = None list_fields = None list_exclude = None non_changeable = None form = None form_requires_request = True listen_channels = [] batch_key = "id" create_permission = None view_permission = None edit_permission = None delete_permission = None def __new__(cls, meta=None): overrides = {} # Meta class will override the defaults based on the values it # already has set. if meta: for override_name in dir(meta): # Skip over internal field names. if not override_name.startswith("_"): overrides[override_name] = getattr(meta, override_name) # Construct the new object with the overrides from meta. return object.__new__(type("HandlerOptions", (cls,), overrides)) class HandlerMetaclass(type): """Sets up the _meta field on the created class.""" def __new__(cls, name, bases, attrs): # Construct the class with the _meta field. new_class = super().__new__(cls, name, bases, attrs) new_class._meta = HandlerOptions(getattr(new_class, "Meta", None)) # Setup the handlers name based on the naming of the class. if not getattr(new_class._meta, "handler_name", None): class_name = new_class.__name__ name_bits = [bit for bit in class_name.split("Handler") if bit] handler_name = "".join(name_bits).lower() new_class._meta.handler_name = handler_name # Setup the object_class if the queryset is provided. if new_class._meta.queryset is not None: new_class._meta.object_class = new_class._meta.queryset.model # Copy the fields and exclude to list_fields and list_exclude # if empty. if new_class._meta.list_fields is None: new_class._meta.list_fields = new_class._meta.fields if new_class._meta.list_exclude is None: new_class._meta.list_exclude = new_class._meta.exclude return new_class class Handler(metaclass=HandlerMetaclass): """Base handler for all handlers in the WebSocket protocol. Each handler should extend this class to get the basic implementation of exposing a collection over the WebSocket protocol. The classes that extend this class must be present in `maasserver.websockets.handlers` for it to be exposed. Example: class SampleHandler(Handler): class Meta: queryset = Sample.objects.all() """ def __init__(self, user, cache, request): self.user = user self.cache = cache self.request = request # Holds a set of all pks that the client has loaded and has on their # end of the connection. This is used to inform the client of the # correct notifications based on what items the client has. if "loaded_pks" not in self.cache: self.cache["loaded_pks"] = set() def full_dehydrate(self, obj, for_list=False): """Convert the given object into a dictionary. :param for_list: True when the object is being converted to belong in a list. """ if for_list: allowed_fields = self._meta.list_fields exclude_fields = self._meta.list_exclude else: allowed_fields = self._meta.fields exclude_fields = self._meta.exclude data = {} for field in self._meta.object_class._meta.fields: # Convert the field name to unicode as some are stored in bytes. field_name = str(field.name) # Skip fields that are not allowed. if allowed_fields is not None and field_name not in allowed_fields: continue if exclude_fields is not None and field_name in exclude_fields: continue # Get the value from the field and set it in data. The value # will pass through the dehydrate method if present. field_obj = getattr(obj, field_name) dehydrate_method = getattr(self, "dehydrate_%s" % field_name, None) if dehydrate_method is not None: data[field_name] = dehydrate_method(field_obj) else: value = field.value_from_object(obj) if is_protected_type(value) or isinstance(value, dict): data[field_name] = value elif isinstance(field, ArrayField): data[field_name] = field.to_python(value) else: data[field_name] = field.value_to_string(obj) # Add permissions that can be performed on this object. data = self._add_permissions(obj, data) # Return the data after the final dehydrate. return self.dehydrate(obj, data, for_list=for_list) def dehydrate(self, obj, data, for_list=False): """Add any extra info to the `data` before finalizing the final object. :param obj: object being dehydrated. :param data: dictionary to place extra info. :param for_list: True when the object is being converted to belong in a list. """ return data def _is_foreign_key_for(self, field_name, obj, value): """Given the specified field name for the specified object, returns True if the specified value is a foreign key; otherwise returns False. """ if isinstance(obj, Model): field_type = obj._meta.get_field(field_name).get_internal_type() if field_type == "ForeignKey" and not isinstance(value, Model): return True return False def _add_permissions(self, obj, data): """Add permissions to `data` for `obj` based on the current user.""" # Only `edit` and `delete` are used because if the user cannot view # then it will not call this method at all and create is a global # action that is not scoped to an object. has_permissions = ( self._meta.edit_permission is not None or self._meta.delete_permission is not None ) if not has_permissions: return data permissions = [] if self._meta.edit_permission is not None and self.user.has_perm( self._meta.edit_permission, obj ): permissions.append("edit") if self._meta.delete_permission is not None and self.user.has_perm( self._meta.delete_permission, obj ): permissions.append("delete") data["permissions"] = permissions return data def full_hydrate(self, obj, data): """Convert the given dictionary to a object.""" allowed_fields = self._meta.fields exclude_fields = self._meta.exclude non_changeable_fields = self._meta.non_changeable for field in self._meta.object_class._meta.fields: field_name = field.name # Skip fields that are not allowed. if field_name == self._meta.pk: continue if allowed_fields is not None and field_name not in allowed_fields: continue if exclude_fields is not None and field_name in exclude_fields: continue if ( non_changeable_fields is not None and field_name in non_changeable_fields ): continue # Update the field if its in the provided data. Passing the value # through its hydrate method if present. if field_name in data: value = data[field_name] hydrate_method = getattr(self, "hydrate_%s" % field_name, None) if hydrate_method is not None: value = hydrate_method(value) if self._is_foreign_key_for(field_name, obj, value): # We're trying to populate a foreign key relationship, but # we don't have a model object. Assume we were given the # primary key. field_name += "_id" setattr(obj, field_name, value) # Return the hydrated object once its done the final hydrate. return self.hydrate(obj, data) def hydrate(self, obj, data): """Add any extra info to the `obj` before finalizing the finale object. :param obj: obj being hydrated. :param data: dictionary to use to set object. """ return obj def get_object(self, params, permission=None): """Get object by using the `pk` in `params`.""" if self._meta.pk not in params: raise HandlerValidationError( {self._meta.pk: ["This field is required"]} ) pk = params[self._meta.pk] try: obj = self.get_queryset(for_list=False).get(**{self._meta.pk: pk}) except self._meta.object_class.DoesNotExist: raise HandlerDoesNotExistError(pk) if permission is not None or self._meta.view_permission is not None: if permission is None: permission = self._meta.view_permission if not self.user.has_perm(permission, obj): raise HandlerPermissionError() return obj def get_queryset(self, for_list=False): """Return `QuerySet` used by this handler. Override if you need to modify the queryset based on the current user. """ if for_list and self._meta.list_queryset is not None: return self._meta.list_queryset else: return self._meta.queryset def get_form_class(self, action): """Return the form class used for `action`. Override if you need to provide a form based on the current user. """ return self._meta.form def preprocess_form(self, action, params): """Process the `params` to before passing the data to the form. Default implementation just converts `params` to a `QueryDict`. """ return get_QueryDict(params) def _get_call_latency_metrics_label(self, method_name, params): call_name = "{handler_name}.{method_name}".format( handler_name=self._meta.handler_name, method_name=method_name ) return {"call": call_name} @PROMETHEUS_METRICS.record_call_latency( "maas_websocket_call_latency", get_labels=_get_call_latency_metrics_label, ) @asynchronous def execute(self, method_name, params): """Execute the given method on the handler. Checks to make sure the method is valid and allowed perform executing the method. """ if method_name in self._meta.allowed_methods: try: method = getattr(self, method_name) except AttributeError: raise HandlerNoSuchMethodError(method_name) else: # Handler methods are predominantly transactional and thus # blocking/synchronous. Genuinely non-blocking/asynchronous # methods must out themselves explicitly. if IAsynchronous.providedBy(method): # Running in the io thread so clear RBAC now. rbac.clear() # Reload the user from the database. d = concurrency.webapp.run( deferToDatabase, transactional(self.user.refresh_from_db), ) d.addCallback(lambda _: method(params)) return d else: @wraps(method) @transactional def prep_user_execute(params): # Clear RBAC and reload the user to ensure that # its up to date. `rbac.clear` must be done inside # the thread because it uses thread locals internally. rbac.clear() self.user.refresh_from_db() # Perform the work in the database. return self._call_method_track_queries( method_name, method, params ) # Force the name of the function to include the handler # name so the debug logging is useful. prep_user_execute.__name__ = "%s.%s" % ( self.__class__.__name__, method_name, ) # This is going to block and hold a database connection so # we limit its concurrency. return concurrency.webapp.run( deferToDatabase, prep_user_execute, params ) else: raise HandlerNoSuchMethodError(method_name) def _call_method_track_queries(self, method_name, method, params): """Call the specified method tracking query-related metrics.""" latencies = [] with wrap_query_counter_cursor(latencies): result = method(params) labels = self._get_call_latency_metrics_label(method_name, []) PROMETHEUS_METRICS.update( "maas_websocket_call_query_count", "observe", value=len(latencies), labels=labels, ) for latency in latencies: PROMETHEUS_METRICS.update( "maas_websocket_call_query_latency", "observe", value=latency, labels=labels, ) return result def _cache_pks(self, objs): """Cache all loaded object pks.""" getpk = attrgetter(self._meta.pk) self.cache["loaded_pks"].update(getpk(obj) for obj in objs) def list(self, params): """List objects. :param start: A value of the `batch_key` column and NOT `pk`. They are often the same but that is not a certainty. Make sure the client also understands this distinction. :param offset: Offset into the queryset to return. :param limit: Maximum number of objects to return. """ queryset = self.get_queryset(for_list=True) queryset = queryset.order_by(self._meta.batch_key) if "start" in params: queryset = queryset.filter( **{"%s__gt" % self._meta.batch_key: params["start"]} ) if "limit" in params: queryset = queryset[: params["limit"]] objs = list(queryset) self._cache_pks(objs) return [self.full_dehydrate(obj, for_list=True) for obj in objs] def get(self, params): """Get object. :param pk: Object with primary key to return. """ obj = self.get_object(params) self._cache_pks([obj]) return self.full_dehydrate(obj) def create(self, params): """Create the object from data.""" # Create by using form. `create_permission` is not used with form, # permission checks should be done in the form. form_class = self.get_form_class("create") if form_class is not None: data = self.preprocess_form("create", params) if self._meta.form_requires_request: form = form_class(request=self.request, data=data) else: form = form_class(data=data) if hasattr(form, "use_perms") and form.use_perms(): if not form.has_perm(self.user): raise HandlerPermissionError() elif self._meta.create_permission is not None: raise ValueError( "`create_permission` defined on the handler, but the form " "is not using permission checks." ) if form.is_valid(): try: obj = form.save() except ValidationError as e: try: raise HandlerValidationError(e.message_dict) except AttributeError: raise HandlerValidationError({"__all__": e.message}) return self.full_dehydrate(self.refetch(obj)) else: raise HandlerValidationError(form.errors) # Verify the user can create an object. if self._meta.create_permission is not None: if not self.user.has_perm(self._meta.create_permission): raise HandlerPermissionError() # Create by updating the fields on the object. obj = self._meta.object_class() obj = self.full_hydrate(obj, params) obj.save() return self.full_dehydrate(obj) def update(self, params): """Update the object.""" obj = self.get_object(params) # Update by using form. `edit_permission` is not used when form # is used to update. The form should define the permissions. form_class = self.get_form_class("update") if form_class is not None: data = self.preprocess_form("update", params) form = form_class(data=data, instance=obj) if hasattr(form, "use_perms") and form.use_perms(): if not form.has_perm(self.user): raise HandlerPermissionError() elif self._meta.edit_permission is not None: raise ValueError( "`edit_permission` defined on the handler, but the form " "is not using permission checks." ) if form.is_valid(): try: obj = form.save() except ValidationError as e: raise HandlerValidationError(e.error_dict) return self.full_dehydrate(obj) else: raise HandlerValidationError(form.errors) # Verify the user can edit this object. if self._meta.edit_permission is not None: if not self.user.has_perm(self._meta.edit_permission, obj): raise HandlerPermissionError() # Update by updating the fields on the object. obj = self.full_hydrate(obj, params) obj.save() return self.full_dehydrate(obj) def delete(self, params): """Delete the object.""" obj = self.get_object(params, permission=self._meta.delete_permission) obj.delete() def set_active(self, params): """Set the active node for this connection. This is the node that is being viewed in detail by the client. """ # Calling this method without a primary key will clear the currently # active object. if self._meta.pk not in params: if "active_pk" in self.cache: del self.cache["active_pk"] return # Get the object data and set it as active. obj_data = self.get(params) self.cache["active_pk"] = obj_data[self._meta.pk] return obj_data def on_listen(self, channel, action, pk): """Called by the protocol when a channel notification occurs. Do not override this method instead override `listen`. """ pk = self._meta.pk_type(pk) if action == "delete": if pk in self.cache["loaded_pks"]: self.cache["loaded_pks"].remove(pk) return (self._meta.handler_name, action, pk) else: return None self.user.refresh_from_db() try: obj = self.listen(channel, action, pk) except HandlerDoesNotExistError: obj = None if action == "create" and obj is not None: if pk in self.cache["loaded_pks"]: # The user already knows about this node, so its not a create # to the user but an update. return self.on_listen_for_active_pk("update", pk, obj) else: self.cache["loaded_pks"].add(pk) return self.on_listen_for_active_pk(action, pk, obj) elif action == "update": if pk in self.cache["loaded_pks"]: if obj is None: # The user no longer has access to this object. To the # client this is a delete action. self.cache["loaded_pks"].remove(pk) return (self._meta.handler_name, "delete", pk) else: # Just a normal update to the client. return self.on_listen_for_active_pk(action, pk, obj) elif obj is not None: # User just got access to this new object. Send the message to # the client as a create action instead of an update. self.cache["loaded_pks"].add(pk) return self.on_listen_for_active_pk("create", pk, obj) else: # User doesn't have access to this object, so do nothing. pass else: # Unknown action or the user doesn't have permission to view the # newly created object, so do nothing. pass return None def on_listen_for_active_pk(self, action, pk, obj): """Return the correct data for `obj` depending on if its the active primary key.""" if "active_pk" in self.cache and pk == self.cache["active_pk"]: # Active so send all the data for the object. return ( self._meta.handler_name, action, self.full_dehydrate(obj, for_list=False), ) else: # Not active so only send the data like it was comming from # the list call. return ( self._meta.handler_name, action, self.full_dehydrate(obj, for_list=True), ) def listen(self, channel, action, pk): """Called when the handler listens for events on channels with `Meta.listen_channels`. :param channel: Channel event occured on. :param action: Action that caused this event. :param pk: Id of the object. """ return self.get_object({self._meta.pk: pk}) def refetch(self, obj): """Refetch an object using the handler queryset. This ensures annotations defined in the queryset are added to the object. """ return self.get_object({self._meta.pk: getattr(obj, self._meta.pk)}) class AdminOnlyMixin(Handler): class Meta: abstract = True def create(self, parameters): """Only allow an administrator to create this object.""" if not self.user.has_perm( NodePermission.admin, self._meta.object_class ): raise HandlerPermissionError() return super().create(parameters) def update(self, parameters): """Only allow an administrator to update this object.""" obj = self.get_object(parameters) if not self.user.has_perm(NodePermission.admin, obj): raise HandlerPermissionError() return super().update(parameters) def delete(self, parameters): """Only allow an administrator to delete this object.""" obj = self.get_object(parameters) if not self.user.has_perm(NodePermission.admin, obj): raise HandlerPermissionError() return super().delete(parameters)
The attractive brick building on the right as we start down Packard Avenue was originally Goddard Gymnasium (take a good look and remember it when you see the present gymnasium). It was renovated to house The Fletcher School of Law and Diplomacy, which was established at Tufts in 1933 with the cooperation of Harvard University as the first graduate school of international affairs in this country. The Fletcher School has gained stature and influence throughout the world. Students come from every state in the Union and from many foreign countries to prepare for careers in all aspects of international affairs: diplomatic service; foreign affairs agencies; international finance, business, and journalism; and teaching. Since the establishment of The Fletcher School, some 80 of its graduates have risen to the rank of ambassador in the Foreign Service of the United States and the diplomatic service of other countries. Some of these were undergraduates of Tufts as well: The Honorable Malcolm Toon of Medford, A37, F38, H77, U.S. Ambassador to the USSR; The Honorable Edward W. Mulcahy of Malden, A43, F47, U.S. Ambassador to Tunisia; The Honorable Daniel P. Moynihan, BNS46, A48, F49, F61, H68, former U.S. ambassador to India and to the United Nations and now U.S. senator from New York. Women have been enrolled in The Fletcher School from the outset, and hold important assignments in many fields. For example, Dr. Jane W. Harbaugh, J52, F53, F57, is vice chancellor of the University of Tennessee at Chattanooga; Mlle. Colette M. Flesch, F61, is mayor of Luxembourg Ville, member of Parliament of the Grand Duchy of Luxembourg and member of the European Parliament; Karen Hastee Williams, F61, is chief counsel of the Committee on the Budget, U.S. Senate. name of Edwin Ginn, Arts Class of 1862, G1862, H02, who founded the publishing house of Ginn & Company and who donated $1 million to create the World Peace Foundation. As you pause at the head of the tree-lined walk leading to the entrance of The Fletcher School, notice the granite marker etched with "M" and "S" — the demarcation line between Medford and Somerville. The walkway is in Medford; the line of trees in Somerville. Down this walkway is Mugar Hall, named for Boston philanthropist Stephen P. Mugar. Mugar Hall was joined to Goddard Hall to increase the school's facilities. It contains a faculty lounge and dining room dedicated to Frank G. Wren, Arts Class of 1894, G1897, H39; a Fletcher School dining hall named for the late Roscoe Pound, renowned dean of the Harvard Law School and a founding father of The Fletcher School; and a third dining hall and lounge for students of the Graduate School of Arts and Sciences. Further down the walk is Fletcher Hall, which contains dormitory space and faculty offices. On the opposite side of Packard Avenue from The Fletcher School is the President's House. It was built for President and Mrs. Carmichael in 1939. Since then President and Mrs. Nils Y. Wessell, President and Mrs. Burton C. Hallowell, and President and Mrs. Jean Mayer have lived there.
# -*- coding: utf-8 -*- from pyramid.view import view_config from pyramid.response import Response from pyramid.renderers import render from intranet3 import config from intranet3.lib.bugs import Bugs from intranet3.log import INFO_LOG, DEBUG_LOG, EXCEPTION_LOG from intranet3.models import User, Project from intranet3.utils import mail from intranet3.utils.views import CronView from intranet3.models import DBSession LOG = INFO_LOG(__name__) DEBUG = DEBUG_LOG(__name__) EXCEPTION = EXCEPTION_LOG(__name__) @view_config(route_name='cron_bugs_oldbugsreport', permission='cron') class OldBugsReport(CronView): def _send_report(self, coordinator_id, email, bugs): # Bugs filtering & ordering # Coordinator gets bugs from his projects, manager gets bugs from # all projects if coordinator_id is None: # Manager bugs_filtered = sorted( bugs, key=lambda b: b.changeddate.replace(tzinfo=None), ) title = u'Lista najstarszych niezamkniętych bugów\nwe wszystkich projektach' else: # Coordinator bugs_filtered = [ b for b in bugs if b.project is not None and b.project.coordinator_id == coordinator_id ] bugs_filtered = sorted( bugs_filtered, key=lambda b: b.changeddate.replace(tzinfo=None), ) title = u'Lista najstarszych niezamkniętych bugów\nw projektach w których jesteś koordynatorem' if bugs_filtered: data = { 'bugs': bugs_filtered[:20], 'title': self._(title), } response = render( 'intranet3:templates/_email_reports/old_bugs_report.html', data, request=self.request ) with mail.EmailSender() as email_sender: email_sender.send( email, self._(u'[Intranet3] Old bugs report'), html_message=response, ) def action(self): coordinators = DBSession.query(Project.coordinator_id, User.email) \ .join(User) \ .filter(Project.coordinator_id!=None) \ .group_by(Project.coordinator_id, User) \ .all() manager = DBSession.query(User) \ .filter(User.email == config['MANAGER_EMAIL']) \ .first() bugs = Bugs(self.request, manager).get_all() # Coordinators for user_id, user_email in coordinators: self._send_report(user_id, user_email, bugs) # Manager self._send_report(None, config['MANAGER_EMAIL'], bugs) return Response('ok')
The Austin-based duo of Eddie Collins and Max Zimmet team up on acoustic guitar, mandolin, banjo, and vocals, playing standards and originals in bluegrass, classic country, old time rock n' roll, Texas Country, Americana and Western Swing. We play corporate events, weddings, festivals, house concerts, private events, and clubs. If you're looking for energetic roots music in a small, listenable and entertaining package, contact us today. Let us know if you’d like us to add upright bass or fiddle for a trio configuration. The seeds for the duo were planted in 1997. Max was 10 years old. He heard Bill Monroe on Austin City Limits, loved it, and his family started going to hear bluegrass at Artz Rib house in Austin, Texas. Max would tape Eddie Collins’s band, and listen to it for hours, and soon was taking lessons from Eddie. He started playing out a bit and got to do some shows with Eddie and other area pickers. Max returned to Austin after earning a degree at the Berklee College of Music in Boston (with majors in guitar and mandolin performance) and began several projects, including Hot Pickin 57s, One Eye Open, and a duo with Eddie. Max placed 3rd in the 2017 and 2018 Texas Flatpicking Guitar Championship. Eddie is a long-time staple of the Austin music scene, having performed with many of the area’s top acoustic groups. In addition to appearing on and producing recording projects for others, he has nine solo CDs, which include many original tunes. He has published over thirty instructional works and writes for national music publications.
''' Test the creation of a user on the directory ''' import unittest import pytest from wirecurly import directory class testUserCreation(unittest.TestCase): """Test user creation""" def setUp(self): ''' Create our fixtures for these tests ''' self.user = directory.User('1000', 'this is a test') def test_user_is_can_be_a_dict(self): ''' Test that our user can be properly serialized ''' assert isinstance(self.user.todict(), dict) def test_adding_parameter_to_user(self): ''' Test adding a parameter to a user ''' self.user.addParameter('vm-password', '123') assert self.user.getParameter('vm-password') == '123' def test_adding_variable_to_user(self): ''' Test adding a variable to a user ''' self.user.addVariable('toll-allow', 'intl') assert self.user.getVariable('toll-allow') == 'intl' def test_adding_existing_variable(self): ''' Test trying to replace an existing variable ''' with pytest.raises(ValueError): self.user.addVariable('test', 'intl') self.user.addVariable('test', 'intl') def test_adding_existing_parameter(self): ''' Test trying to replace an existing parameter ''' with pytest.raises(ValueError): self.user.addParameter('password', 'anything')
Prior to PVN’s involvement with the building, the Minnesota Mutual Life Insurance Company Building in Saint Paul was determined to be eligible for the National Register of Historic Places (NRHP) as part of a potential historic district of buildings in downtown Saint Paul. It was believed that the building was not individually eligible because it lacked integrity—the lobby had been altered from its original appearance and an art piece had been removed. PVN’s research team argued that the Ellerbee-designed flagship office building was individually eligible for the NRHP and significant for its association with the local Minnesota Mutual Insurance Life Company and for its representation of Midcentury office building design. Midcentury office buildings express corporate identity through their exterior design rather than through their interior configuration. The Minnesota State Review Board recommended the building for listing in the NRHP in March of 2017. The Minnesota Mutual Life Insurance Building is currently being rehabilitated as housing. The $32 million project has access to nearly $10 million in historic tax credits as a result of PVN’s understanding of Midcentury corporate architecture and our ability to achieve individual designation for a building that had been dismissed by others. PVN is proud to be part of a team that is leading the way in the preservation and rehabilitation of Midcentury buildings in Saint Paul. This month's blog series will feature the history and future of the Minnesota Mutual Life Insurance Company Building. The Minnesota Mutual Life Insurance Company Building, located at 345 Cedar Street, in Saint Paul was dedicated on August 6, 1955 – the first new office building to be constructed in downtown Saint Paul since the Great Depression. The building itself is an eight level International Style office building, designed by local architecture firm Ellerbe and Company for local insurance company Minnesota Mutual Life Insurance. During the period of significance for this building, Minnesota Mutual had branch offices located in every state of the Union and enjoyed recognition as the largest insurance agency in Saint Paul and as one of the 25 largest agencies in the country. The building exhibits a simple rectangular massing, made distinctive by its unique exterior material palate. The building is clad in stacked square panels of yellow Kasota stone at the upper levels and black granite at the water table. At the primary façade, ribbon windows at each level emphasize the building’s distinct horizontal orientation, while a large projecting cornice with an angled soffit reveals a set of square, bright yellow, porcelain-enamel panels. A projecting entry block with storefront-style windows provides visual access between the building’s public lobby and Cedar Street. The building's distinctive modern design helped usher in a new image and marketing strategy for Minnesota Mutual, and played an instrumental part in the company's prosperity over the following decades.
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Parsplice(CMakePackage): """ParSplice code implements the Parallel Trajectory Splicing algorithm""" homepage = "https://gitlab.com/exaalt/parsplice" url = "https://gitlab.com/api/v4/projects/exaalt%2Fparsplice/repository/archive.tar.gz?sha=v1.1" git = "https://gitlab.com/exaalt/parsplice.git" tags = ['ecp', 'ecp-apps'] version('develop', branch='master') version('multisplice', branch='multisplice') version('1.1', sha256='a011c4d14f66e7cdbc151cc74b5d40dfeae19ceea033ef48185d8f3b1bc2f86b') depends_on("cmake@3.1:", type='build') depends_on("berkeley-db") depends_on("nauty") depends_on("boost cxxstd=11") depends_on("mpi") depends_on("eigen@3:") depends_on("lammps+lib@20170901:") depends_on("lammps+lib+exceptions", when="@multisplice") def cmake_args(self): spec = self.spec if spec.satisfies('@multisplice'): options = [] else: options = ['-DBUILD_SHARED_LIBS=ON', '-DBoost_NO_BOOST_CMAKE=ON'] return options
Here is Harold William Churcher’s obituary. Please accept Everhere’s sincere condolences. It is always difficult saying goodbye to someone we love and cherish. Family and friends must say goodbye to their beloved Harold William Churcher (Victoria, British Columbia), who passed away at the age of 76, on February 6, 2019. You can send your sympathy in the guestbook provided and share it with the family. You may also light a candle in honor of Harold William Churcher. There are no additional memories for Harold William Churcher at this time. You can add a memory to pay tribute to Harold William Churcher at any time. Unfortunately, there are no events for Harold William Churcher at this time. If you know of an upcoming event for Harold William Churcher, please add one now. Here are the tributes to Harold William Churcher who passed away in Victoria, British Columbia. Would you like to offer Harold William Churcher’s loved ones a condolence message? Write your message of sympathy today.
from urlparse import urlparse from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import AuthenticationForm from django.core.urlresolvers import resolve, Resolver404 from django.utils.html import mark_safe from django.utils.translation import ugettext_lazy as _ from localflavor.us.forms import USZipCodeField from nocaptcha_recaptcha.fields import NoReCaptchaField from registration.forms import RegistrationForm from .models import Category, Flag, Submission VALID_SUBMISSION_DETAIL_URL_NAMES = ['vote', 'show_idea'] class VoterForm(forms.Form): email = forms.EmailField() zipcode = USZipCodeField() captcha = NoReCaptchaField( gtag_attrs={'data-size': 'compact'} ) def __init__(self, *args, **kwargs): super(VoterForm, self).__init__(*args, **kwargs) def ignore_captcha(self): del self.fields['captcha'] class QuestionForm(forms.Form): category = forms.ModelMultipleChoiceField(queryset=Category.objects.all()) headline = forms.CharField(required=True) question = forms.CharField(required=False) citation = forms.URLField(required=False, max_length=255) def __init__(self, *args, **kwargs): super(QuestionForm, self).__init__(*args, **kwargs) self.fields['category'].error_messages['invalid_pk_value'] = _("You must select a category") display_name_help_text = _("How your name will be displayed on the site. If you " "are an expert in a particular field or have a professional " "affiliation that is relevant to your ideas, feel free to " "mention it here alongside your name! If you leave this " "blank, your first name and last initial will be used " "instead.") # @@TODO display_name_label = (u"Display name <span data-toggle='tooltip' title='%s' " "class='glyphicon glyphicon-question-sign'></span>" % display_name_help_text) twitter_handle_help_text = _("Fill in your Twitter username (without the @) if you " "would like to be @mentioned on Twitter when people " "tweet your ideas.") # @@TODO twitter_handle_label = (u"Twitter handle <span data-toggle='tooltip' title='%s' " "class='glyphicon glyphicon-question-sign'></span>" % twitter_handle_help_text) class OpenDebatesRegistrationForm(RegistrationForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) display_name = forms.CharField(max_length=255, label=mark_safe(display_name_label), required=False) twitter_handle = forms.CharField(max_length=255, label=mark_safe(twitter_handle_label), required=False) zip = USZipCodeField() captcha = NoReCaptchaField(label=_("Are you human?")) def clean_twitter_handle(self): if self.cleaned_data.get("twitter_handle", "").startswith("@"): return self.cleaned_data['twitter_handle'].lstrip("@") if self.cleaned_data.get("twitter_handle", "").startswith("https://twitter.com/"): return self.cleaned_data['twitter_handle'][20:] if self.cleaned_data.get("twitter_handle", "").startswith("http://twitter.com/"): return self.cleaned_data['twitter_handle'][19:] if self.cleaned_data.get("twitter_handle", "").startswith("twitter.com/"): return self.cleaned_data['twitter_handle'][12:] return self.cleaned_data.get("twitter_handle", "").strip() or None def clean_email(self): """ Validate that the supplied email address is unique for the site. """ User = get_user_model() if User.objects.filter(email__iexact=self.cleaned_data['email']): raise forms.ValidationError("This email address is already in use. Please supply " "a different email address.") return self.cleaned_data['email'] def save(self, commit=True): user = super(OpenDebatesRegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() return user def ignore_captcha(self): del self.fields['captcha'] class OpenDebatesAuthenticationForm(AuthenticationForm): username = forms.CharField(max_length=254, label="Username or Email") class MergeFlagForm(forms.ModelForm): duplicate_of_url = forms.URLField(label=_("Enter URL here")) class Meta: model = Flag fields = ('duplicate_of_url', ) def __init__(self, *args, **kwargs): self.idea = kwargs.pop('idea') self.voter = kwargs.pop('voter') super(MergeFlagForm, self).__init__(*args, **kwargs) def clean_duplicate_of_url(self): # parse the URL and use Django's resolver to find the urlconf entry path = urlparse(self.cleaned_data['duplicate_of_url']).path try: url_match = resolve(path) except Resolver404: url_match = None if not url_match or url_match.url_name not in VALID_SUBMISSION_DETAIL_URL_NAMES: raise forms.ValidationError('That is not the URL of a question.') duplicate_of_pk = url_match.kwargs.get('id') if duplicate_of_pk == unicode(self.idea.pk): raise forms.ValidationError('Please enter the URL of the submission that this ' 'submission appears to be a duplicate of, not the ' 'URL of this submission.') self.duplicate_of = Submission.objects.filter(pk=duplicate_of_pk, approved=True) \ .first() if not self.duplicate_of: raise forms.ValidationError('Invalid Question URL.') return self.cleaned_data['duplicate_of_url'] def save(self, commit=True): flag = super(MergeFlagForm, self).save(commit=False) flag.to_remove = self.idea flag.voter = self.voter flag.duplicate_of = self.duplicate_of if commit: flag.save() return flag class ModerationForm(forms.Form): to_remove = forms.IntegerField(label="ID of submission to remove") duplicate_of = forms.IntegerField(required=False, label="(Optional) ID of submission it is a duplicate of") def clean_to_remove(self): to_remove_pk = self.cleaned_data['to_remove'] if to_remove_pk: try: self.cleaned_data['to_remove_obj'] = Submission.objects.get( pk=to_remove_pk, approved=True) except Submission.DoesNotExist: raise forms.ValidationError('That submission does not exist or is not approved.') return to_remove_pk def clean_duplicate_of(self): duplicate_of_pk = self.cleaned_data['duplicate_of'] if duplicate_of_pk: try: self.cleaned_data['duplicate_of_obj'] = Submission.objects.get( pk=duplicate_of_pk, approved=True) except Submission.DoesNotExist: raise forms.ValidationError('That submission does not exist or is not approved.') return duplicate_of_pk def clean(self): to_remove_pk = self.cleaned_data.get('to_remove') duplicate_of_pk = self.cleaned_data.get('duplicate_of') if to_remove_pk and duplicate_of_pk and to_remove_pk == duplicate_of_pk: raise forms.ValidationError('Cannot merge a submission into itself.') return self.cleaned_data
DISH in Montana offers customers the most dependable technological platform for delivering exceptional programming while creating unbeatable value. When you choose DISH satellite TV service in Melstone Montana you will simply receive professional service and benefits like none other. DISH TV will help you recognize the right package for your budget. When you order DISH you will get all of your local channels for FREE with your subscription. You will never have to pay for access to channels in your zipcode. Contact a DISH satellte TV representative in Melstone Mt to get started. When you order service, a DISH satellite service technician in Melstone, Montana can install equipment in up to 6 rooms for FREE. As an additional bonus ask a DISH representative about rush installation so you can enjoy the most impressive satellite package within one day of ordering. DISH offers some of the best programming available with more plans to select from making DISH the leader in satellite TV service. You never have to worry about missing your favorite shows ever again with the visual quality of HD FREE from DISH in Melstone Mt. DISH TV in Melstone offers you commercial-free programming with Prime Time Anytime™ on the Hopper® Whole-Home HD DVR. The Hopper and Joey has the astounding capability to record up to 8 HD channels at once including primetime hours. The Hopper® has the ability to store up to 2,000 hours of exciting programming on its 2 TD hard drive. Call now to get a Hopper® upgrade when you subscribe to America’s Top 120™ or more. *With qualifying packages. Montly fees apply. Hopper $15, Joey $7, Super Joey $10. This satellite Internet connection gives you speeds up to 10 Mbps and data plans of up to 30GB. With dishNET in Melstone Montana you have access no matter where you live and you can save $10/month on your bill when you bundle with your DISH TV package. If you would like to order DISH today and start enjoying the best satellite TV service in Melstone Montana call 1-866-887-8099.
import tensorflow as tf import io import os.path from gensim.utils import deaccent import re import string import numpy as np def regularize_charset(fname): """Reduce the set of characters in the file to the minimum to encapsulate its semantics. Replaces non-ascii chars with their ascii equivalent. Replaces non-printing chars with spaces, and tabs with 4 spaces. Arguments: fname: path to a text file to be encoded Returns: a file path with ascii chars replaced """ with open(fname, 'r') as f: s = f.read() news = to_ascii(s) return write_with_suffix(fname, '-ascii') def to_ascii(string): """ Replace all non-ascii chars with ascii-equivalent, remove all non-printing characters,replace all tabs with 4 spaces. Returns: A transformed string """ tabs = re.compile('\t') newstring, _ = tabs.subn(' ' * 4, string) car_return_etc = re.compile('\r|\x0b|\x0c') newstring, _ = tabs.subn('\n', newstring) newstring = deaccent(newstring) #FIXME removes newlines, not intended behavior nonprintable = re.compile('[^ -~\n]') newstring, _ = nonprintable.subn('', newstring) return newstring.encode('ascii') def split_text(string, elem_length): """ Splits a string into substrings of length elem_length, with space padding. Arguments: string: a string to split elem_length: length of substrings to split into Returns: A list of strings of length elem_length """ rem = len(string) % elem_length padded_string = string + b' ' * rem #jDouble braces used to create a literal brace, re matches exactly # elem_length of any char return [padded_string[i : i + elem_length] for i in range(0, len(padded_string) - elem_length, elem_length)] def to_digit_array(string, char_map): """ Convert a string into an nparray, mapping characters to ints based on char_map """ return np.array([char_map[s] for s in string], dtype = np.int8) def write_with_suffix(f, suffix): """Write a new txt file with the name of f concatted with the string suffix appended, with the same extension as the original file Arguments: f: a file object suffix: the suffix to be appended to the filename Returns: an file path to the writen file at fname + suffix.ext """ fpath = f.name basename = os.path.basename(fpath) newname = basename + suffix #rev_char_map = {i : c for i, c in char_map.items()} def translate(content): ascii_content = to_ascii(content) charset = set(ascii_content) char_map = {c : i for i, c in enumerate(sorted(list(charset)))} translated = np.array([char_map[c] for c in ascii_content], dtype = np.uint8) return translated, char_map def make_array(content, elem_length): """ Take text string, process charset, create np array of dim [-1, elem_length] """ ascii_content = to_ascii(content) charset = set(ascii_content) char_map = {c : i for i, c in enumerate(sorted(list(charset)))} substrings = split_text(ascii_content, elem_length) array = np.array([to_digit_array(s, char_map) for s in substrings], dtype = np.uint8) return array, char_map
Located in the Gulf of Chiriquí, Coiba National Park is a marine reserve off Panama’s Pacific coast. Coiba National Park (Nacional Parque Coiba) is comprised of a group of 38 islands including Coiba Island (Isla Coiba) and the waters surrounding them and covers 430,825 acres. Identified by UNESCO as a World Heritage Site in 2005, Coiba National Park offers rich and well preserved natural resources. Because Isla Coiba served Panama as a penal colony, access to the island was very restricted. Almost by accident, 80% of the islands’ natural resources have therefore survived untouched and flourished through limited human contact. Coiba National Park is managed by the National Authority for the Environment (Autoridad Nacional del Ambiente, ANAM). The park is accessible only by permit from ANAM. A number of tour operators in Panama, including EcoCircuitos Panama offer adventure tours, kayaking, snorkeling, and scuba diving trips to Coiba and can assist in obtaining appropriate permits. • Exhibition and Information Center, Park Ranger Station. • Viewing Platforms (Miradores) El Gambute. • Thermal Springs and Nature Interpretation Trial. • Nature Interpretation Trail to ancient Mangrove Forest of Santa Cruz. • Trial to the Waterfall at Juncal. • Nature Interpretation Trail to the Volcanic Rift Valley. • The Penal Colony, La Central Camp. • Nature Interpretation trails of Jicaron and Jicarita. • River Kayaking. Rio San Juan and Punta Hermosa. • Nature Interpretation Trail on Isla Rancheria. • Nature Interpretation Trail Isla Brincanco, Archipelago of Contreras.
""" This is the python module that handles all the Elixir-Python interfacing. Client python modules should never need to reference erlport at all and should instead, handle all the publisher/subscriber interactions through this module. """ import queue import string import threading import time from erlport.erlang import set_message_handler, cast from erlport.erlterms import Atom ## A horrible number of globals... Ugh. _msg_handling_pid = None _msgq = queue.Queue() _main_func = None _topic_handlers = {} _consumption_thread = None ## Client-Facing API def register_main(func): """ Registers the main function to execute - will execute this upon receipt of a signal from Elixir that everything is set up and ready to go. Will run it in a separate thread. """ global _main_func _main_func = func def register_handler(pid): """ Registers the given Elixir process as the handler for this library. This function must be called first - and the client module must define a function with the same prototype which simply calls this function. """ global _msg_handling_pid _msg_handling_pid = pid def subscribe(topics, handlers): """ Subscribes to each topic in `topics` (which may be a single str). Whenever a message is received from a topic, the associated handler is called - the handlers are associated with the topics based purely on order: topic0 -> handler0. The handlers are functions that take 'from_id', 'topic', msg. The handlers are called asynchronously, two messages received on the same topic will both fire without having to finish one. Topics MAY NOT have spaces or punctuation - they should be strings that are easily convertable to Elixir atoms. """ if type(topics) == str: topics = [topics] invalid_chars = set(string.punctuation.replace("_", "")) for topic in topics: if any(char in invalid_chars for char in topic): raise ValueError("Topic {} contains invalid characters. Topics cannot have punctuation or spaces.".format(topic)) global _topic_handlers for topic, handler in zip(topics, handlers): _topic_handlers[topic] = handler global _consumption_thread if _consumption_thread is None: _consumption_thread = threading.Thread(target=_consume) _consumption_thread.start() for topic in topics: topic_as_atom = Atom(topic.encode('utf8')) atom_subscribe = Atom("subscribe".encode('utf8')) cast(_msg_handling_pid, (atom_subscribe, topic_as_atom)) def publish(topics, msg, from_id='default'): """ Publishes `msg` to all topics in `topics`, which may be a single topic. Message must be bytes. Topics must be a string. From_id must also be a string. """ if type(msg) != bytes: raise TypeError("msg must be of type 'bytes' but is of type " + str(type(msg))) if type(topics) == str: topics = [topics] try: topics = [Atom(t.encode('utf8')) for t in topics] except TypeError: topics = [Atom(topics.encode('utf8'))] id_as_atom = Atom(from_id.encode('utf8')) for topic in topics: cast(_msg_handling_pid, (id_as_atom, topic, msg)) def _consume(): """ Sits around waiting for messages from Elixir. Expects a keepalive message to the :priv_keepalive topic at least once every a minute, otherwise exits. Spawns a new thread every time a new message is received on a topic that has a handler associated with it. """ keepalive_interval = 30 start = time.time() while True: if time.time() - start > keepalive_interval: return try: from_id, topic, msg = _msgq.get(timeout=keepalive_interval) if topic == "priv_keepalive": start = time.time() else: handler = _topic_handlers[topic] threading.Thread(target=handler, args=(from_id, topic, msg)).start() except queue.Empty: return except KeyError as e: print(e) print("Could not find key {} in {}".format(topic, _topic_handlers)) raise ## Erlport API: Don't use this in client modules def _handle_message(msg): """ `msg` should be a tuple of the form: (topic, payload). Calls the correct handler for the topic. """ if type(msg) != tuple: raise TypeError("Received a type {} for message. Always expecting tuple instead.".format(type(msg))) if msg[0] == Atom("message".encode('utf8')): msg = msg[1] signal = (Atom("ok".encode('utf8')), Atom("go".encode('utf8'))) if msg == signal: threading.Thread(target=_main_func).start() else: from_id, topic, msg_payload = msg # Will throw an error here if msg is not formatted correctly from_id = str(from_id).lstrip('b').strip("'") topic = str(topic).lstrip('b').strip("'") _msgq.put((from_id, topic, msg_payload)) # Register the handler function with Elixir set_message_handler(_handle_message)
Bali Spa and Uluwatu Tour is one of the best Bali Combination Tours Packages to enjoy one hour spa and one hour massage combine with visiting places of interest in southern part of Bali island. The tour will be start at 09.00 AM from your hotel then we will drive you to Bali Orchid Spa where you will enjoy Thalasso Foot Wash, Body Scrub, Yogurt Moisturizer and Flower Bath. Lunch will be serve at local restaurant then after lunch we will continue the tour to visit Garuda Wisnu Kencana Culture Park, A view of a breathtaking monument, classic attractions, fantasy experience and modern technology blends in and transpire as you explore this unique cultural park. Our next destination is visiting Padang Padang Beach, it's a beautiful beach and leaned on a steep of white stone cliff overlooking to the amazing view of Indian Ocean. The journey will continue to visit Uluwatu Temple, it's one of six key temples believed to be Bali's spiritual pillars and famous for its unique position. Then we will take you to watching the famous Kecak and Fire Dance where the story took from Ramayana epic. Before back to your hotel we will serve your dinner in one of the restaurant in Jimbaran Beach with special menu of Seafood Dinner. The tour will be very comfortable with our private air conditioning car transfer and to keep your convenience and enjoyable journey our professional tour driver is always outstanding offer his best service with the information you need.
import numpy as np import tectosaur.util.gpu as gpu import taskloaf as tsk arg = 1.0 def load_module(): import os D = os.path.dirname(os.path.realpath(__file__)) return gpu.load_gpu('kernels.cl', tmpl_dir = D, tmpl_args = dict(arg = arg)) async def gpu_run(): # gd = tsk.get_service('gpu_data') # if 'add' not in gd: # gd['add'] = (fnc, arg, gpu_R) # else: # fnc, arg, gpu_R = gd['add'] module = load_module() fnc = module.add R = np.random.rand(10000000) gpu_R = gpu.to_gpu(R) gpu_out = gpu.empty_gpu(gpu_R.shape) fnc(gpu_out, gpu_R, grid = (gpu_R.shape[0], 1, 1), block = (1, 1, 1)) R2 = await gpu.get(gpu_out) gpu.logger.debug('run') def setup_gpu_server(which_gpu): import os os.environ['CUDA_DEVICE'] = str(which_gpu) import taskloaf.worker as tsk_worker tsk_worker.services['gpu_data'] = dict() load_module() async def submit(): setup_prs = [ tsk.task(lambda i=i: setup_gpu_server(i), to = i) for i in range(n_workers) ] for pr in setup_prs: await pr import time start = time.time() n_tasks = 8 * 2 for j in range(10): prs = [] for i in range(n_tasks): prs.append(tsk.task(gpu_run, to = i % n_workers)) for i in range(n_tasks): await prs[i] print(time.time() - start) n_workers = 8 tsk.cluster(n_workers, submit) # # async def work_builder(): # print("YO!") # addr = tsk.get_service('comm').addr # def add_task(): # print("PEACE" + str(addr)) # return addr # rem_addr = await tsk.task(add_task, to = gpu_addr) # return (2.0, rem_addr) # # def f2(x): # return x * 2 # pr1 = tsk.task(work_builder, to = 0).then(f2) # pr2 = tsk.task(work_builder, to = 1) # print(await pr1) # print(await pr2) # return 5.0
Upcoming concerts of Zhadan and "Sobaki v kosmose" Zhadan and "Sobaki v kosmose" The pessimist seems that the political and social turmoils swept the country, so there is no place to hide from them. But the optimist thinks not to hide, he buys a ticket and goes to the concert of Sergey Zhadan and the band “Sobaki v kosmose”. These performers, completely devoid of star disease, well know what disturbs an ordinary person. They presented interpretation of current events with a daring sense of humor, and problems appear surmountable. Musicians at concerts encourage the audience and saturate with positive all the space around them. Typical for live performances mixing of styles ska, punk, rock, disco and jazz became the hallmark of the band. The leader of this creative project sings about the problems, and actively fights with them. He's not only a musician and well-known author, awarded as the Ukrainian writer # 1 in 2013-2014 according to the publications of "SHO" and "Forbes Ukraine". Sergey Zhadan is authoritative public figure, who makes every effort to improve the life in our country.
from setuptools import setup def load_requirements(*requirements_paths): """ Load all requirements from the specified requirements files. Returns a list of requirement strings. """ requirements = set() for path in requirements_paths: with open(path) as reqs: requirements.update( line.split('#')[0].strip() for line in reqs if is_requirement(line.strip()) ) return list(requirements) def is_requirement(line): """ Return True if the requirement line is a package requirement; that is, it is not blank, a comment, a URL, or an included file. """ return line and not line.startswith(('-r', '#', '-e', 'git+', '-c')) setup( name="edx_user_state_client", version="1.3.2", packages=[ "edx_user_state_client", ], install_requires=load_requirements('requirements/base.in'), tests_require=load_requirements('requirements/test.in'), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.8', ], )
What is the cost for Salt Lake City Hosted Phone System in United States? Our Salt Lake City Hosted PBX cost just 5.00 USD per month. Users get 1-385 phone number(s) and hosted phone system at no extra cost. Inbound or incoming calls to any softphone or VOIP devices are always free. You only pay per minute charges for making outbound (outgoing) calls or if forwarded to mobile / landline. All Salt Lake City hosted phone systems are non-contractual, meaning the service is prepaid each month. Our call-handling technologies are highly innovative and flexible, with Cloud PBX Phone System being able to receive simultaneous calls on your United States, Salt Lake City hosted phone system and route these calls as required. All Salt Lake City (1-385) phone numbers and packages come with a free PBX solution. It opens in your browser for quick configuration. Any VOIP phone or softphone application can register with the system. You can also forward calls to landline and mobile phones in United States or around the world. In addition, you are able to display a selected local number as your outbound Caller ID when making calls from your office, home or mobile app. What is included with Salt Lake City Hosted Phone System in United States ? Why would you need a Salt Lake City Hosted PBX in United States ? Do you need a presence in United States for your business or website? Get a Salt Lake City virtual phone number with a FREE hosted phone system for just 5.00 USD per month and talk to customers you never thought you had. Getting a United States hosted PBX phone system is one of the absolute cheapest ways you can stay in touch with customers or potential clients in United States. You can forward the 1-385 Salt Lake City virtual number to a VOIP (SIP, H.323 or IAX) solution with Unlimited Minutes and pay the 5.00 USD per month and nothing else. Get a Salt Lake City virtual phone number with a FREE hosted phone system for just 5.00 USD per month and forward the calls to wherever you’d like. One example would be if I went to United States and had family in London, I can call my 1-385 Salt Lake City virtual number which is local for me while I’m in United States and have the calls forwarded to my London family. Using the same example I can also buy a London Virtual Number and forward my cell phone or landline to the Virtual Number (Usually free when it’s local to local) which in turn forwards to a mobile phone I theoretically have set up in United States. Now I don’t miss any calls from my daily cell phone number while abroad. Now you can have a local United States phone number for friends and family to call you on directly. Friends and family in United States can call you as if it’s a local call for them (ie: on the Cheap!). You can forward all the calls made on the United States hosted PBX phone system to your cell phone / landline for an additional low per minute rate or to VOIP (SIP) for free and with unlimited minutes for only 5.00 USD per month. You can also make outbound calls (outgoing calls) with your 1-385 Salt Lake City virtual number by using our iPhone App or Android App. Our Cloud PBX Phone System come with FREE features like: voicemail, voice menu and extensions, fax, call recording, queue, time routing, conference calls, caller ID, playback and tect to speech, blacklist, notification, mobile app, auto-response, virtual receptionist and more. We have also got a free app for iPhone and Android. It lets you make and take calls through your Salt Lake City (1-385) phone number without data. Plus, you can travel with many of our great features in the palm of your hand! Receive faxes as PDF via eMail on your Salt Lake City virtual number (1-385). You just need to enter your email address to which the received faxes should be. Regular smartphone forwarding lets you accept calls sent to your Salt Lake City virtual phone number (1-385). Outbound, however, requires a VoIP app, which consumes data and relies on Wi-Fi availability. Our Salt Lake City PBX Phone System on Android and iPhone allows you to make outgoing calls (outbound calls) and take incoming calls (inbound calls) on the go. Better yet, it doesn't use data! Native to the system, the Salt Lake City PBX Phone System app extends many of the great features usable on other VoIP phones. The PBX Phone System app piggybacks on the mobile carrier. It uses the existing cellphone service to dial the Salt Lake City virtual number to initiate the call. For this reason, you must be in the same city as the number for the app to connect. Unified Voicemail acts like a traditional answering machine or mailbox. It hosts a space in which users may leave voice messages when the phone goes unanswered. Uniquely, the voicemail PBX feature from Cloud PBX Phone System forwards all recorded messages to one or more paired email addresses, attaching the audio file for download on a PC, tablet or smartphone. Salt Lake City Cloud PBX Phone System allows you to record or upload custom messages that are played to the caller when you are not available to answer the call. This message can give instructions to the caller to leave a voice message or may provide other available options, such as listing alternative contact phone numbers. Although all communication ends up in the same place, users can configure individual responses for each mode. For incoming calls, Salt Lake City Cloud PBX Phone System supports custom voicemail greetings, uploadable or recordable directly from within the workspace. This is one example of the flexibility Cloud PBX Phone System solutions give to users and callers alike. Intelligent call forwarding delivers all inbound calls to their desired locations—even if that means email. The function of the call forwarding PBX feature is to ensure no calls go unanswered. Our Salt Lake City virtual phone system achieves this by allowing users to configure a variety of call devices that can both receive and transfer calls. Salt Lake City Cloud PBX Phone System automates call forwarding to any location. Furthermore, our system directs calls either simultaneously or sequentially, depending on the user’s preferences. This means that calls may either ring all aforementioned devices at once or ring each individual phone in a sequence. The following three sections delve into common applications for hosted PBX call recording. Our Salt Lake City Cloud PBX Phone System is not just a call system; it's an advanced communications system intended to enhance productivity for users both on and off the phone lines. These examples demonstrate such. Our Salt Lake City Cloud PBX Phone System includes integrated conferencing facilities, allowing you to hold conferences without involving a third-party provider. Conferences are easily set up at your convenience, and access is restricted to participants who have the appropriate PIN code before they are allowed to join the conference; Users setup a conference room prior to inviting guests—they must distribute notifications outside of the system—as each member requires a PIN code to enter the facility. Our Salt Lake City Cloud PBX Phone System keeps track of call participants, so facilitators may block users with the PIN if necessary. Users expecting large call volumes need the queue PBX feature, yet not all hosted phone solutions offer it. To efficiently process simultaneous inbound calls, our Salt Lake City Cloud PBX Phone System sequences callers based on a first-come-first-serve basis. Understandably, many calls would go unanswered without the queue PBX feature, just as many calls would be cut short to keep the lines open. By implementing transitory spaces with brand messages and music, call agents can spend longer on each call and still process more inquires. Notifications are used to provide you with alerts when specified events occur within the Salt Lake City Cloud PBX Phone System, allowing you to manage these events appropriately and maintain full control over your voice system. For example, you may wish to be notified when voice mail is available, when a caller joins a conference or when a fax is received. As apparent in the above, the text-to-speech and audio playback pbx features serve many functions. They often work in conjunction with other Salt Lake City Cloud PBX Phone System features, too, so keep exploring what our hosted phone solutions have to offer. Since our Salt Lake City Cloud PBX Phone System interface uses drag-and-drop technology, users can add, remove or alter the time routing PBX feature with the click of a button. This means schedules can change according to the week ahead—something particularly useful for travelling businessmen and businesswomen.
import tclab import numpy as np import time import matplotlib.pyplot as plt from gekko import GEKKO # Connect to Arduino a = tclab.TCLab() # Get Version print(a.version) # Turn LED on print('LED On') a.LED(100) # Run time in minutes run_time = 15.0 # Number of cycles with 3 second intervals loops = int(20.0*run_time) tm = np.zeros(loops) # Temperature (K) T1 = np.ones(loops) * a.T1 # temperature (degC) T1mhe = np.ones(loops) * a.T1 # temperature (degC) Tsp1 = np.ones(loops) * 35.0 # set point (degC) T2 = np.ones(loops) * a.T2 # temperature (degC) T2mhe = np.ones(loops) * a.T1 # temperature (degC) Tsp2 = np.ones(loops) * 23.0 # set point (degC) # Set point changes Tsp1[5:] = 40.0 Tsp1[120:] = 35.0 Tsp1[200:] = 50.0 Tsp2[50:] = 30.0 Tsp2[100:] = 35.0 Tsp2[150:] = 30.0 Tsp2[250:] = 35.0 # heater values Q1s = np.ones(loops) * 0.0 Q2s = np.ones(loops) * 0.0 ######################################################### # Initialize Models ######################################################### # Fixed Parameters mass = 4.0/1000.0 # kg Cp = 0.5*1000.0 # J/kg-K A = 10.0/100.0**2 # Area not between heaters in m^2 As = 2.0/100.0**2 # Area between heaters in m^2 eps = 0.9 # Emissivity sigma = 5.67e-8 # Stefan-Boltzmann # initialize MHE and MPC mhe = GEKKO(name='tclab-mhe') mpc = GEKKO(name='tclab-mpc') # create 2 models (MHE and MPC) in loop for m in [mhe,mpc]: # Adjustable Parameters # heat transfer (W/m2-K) m.U = m.FV(value=2.76,lb=1.0,ub=5.0) # time constant (sec) m.tau = m.FV(value=8.89,lb=5,ub=15) # W / % heater m.alpha1 = m.FV(value=0.005,lb=0.002,ub=0.010) # W / % heater m.alpha2 = m.FV(value=0.0026,lb=0.001,ub=0.005) # degC m.Ta = m.FV(value=22.8,lb=15.0,ub=25.0) # Manipulated variables m.Q1 = m.MV(value=0) m.Q1.LOWER = 0.0 m.Q1.UPPER = 100.0 m.Q2 = m.MV(value=0) m.Q2.LOWER = 0.0 m.Q2.UPPER = 100.0 # Controlled variables m.TC1 = m.CV(value=T1[0]) m.TC2 = m.CV(value=T2[0]) # State variables m.TH1 = m.SV(value=T1[0]) m.TH2 = m.SV(value=T2[0]) # Heater temperatures m.T1i = m.Intermediate(m.TH1+273.15) m.T2i = m.Intermediate(m.TH2+273.15) m.TaK = m.Intermediate(m.Ta+273.15) # Heat transfer between two heaters m.Q_C12 = m.Intermediate(m.U*As*(m.T2i-m.T1i)) # Convective m.Q_R12 = m.Intermediate(eps*sigma*As\ *(m.T2i**4-m.T1i**4)) # Radiative # Semi-fundamental correlations (energy balances) m.Equation(mass*Cp*m.TH1.dt() == m.U*A*(m.TaK-m.T1i) \ + eps * sigma * A * (m.TaK**4 - m.T1i**4) \ + m.Q_C12 + m.Q_R12 \ + m.alpha1 * m.Q1) m.Equation(mass*Cp*m.TH2.dt() == m.U*A*(m.TaK-m.T2i) \ + eps * sigma * A * (m.TaK**4 - m.T2i**4) \ - m.Q_C12 - m.Q_R12 \ + m.alpha2 * m.Q2) # Empirical correlations (lag equations to emulate conduction) m.Equation(m.tau * m.TC1.dt() == -m.TC1 + m.TH1) m.Equation(m.tau * m.TC2.dt() == -m.TC2 + m.TH2) ################################################################## # Configure MHE # 120 second time horizon, steps of 4 sec mhe.time = np.linspace(0,120,31) #mhe.server = 'http://127.0.0.1' # solve locally # FV tuning # update FVs with estimator mhe.U.STATUS = 1 mhe.tau.STATUS = 0 mhe.alpha1.STATUS = 0 mhe.alpha2.STATUS = 0 mhe.Ta.STATUS = 0 # FVs are predicted, not measured mhe.U.FSTATUS = 0 mhe.tau.FSTATUS = 0 mhe.alpha1.FSTATUS = 0 mhe.alpha2.FSTATUS = 0 mhe.Ta.FSTATUS = 0 # MV tuning mhe.Q1.STATUS = 0 # not optimized in estimator mhe.Q1.FSTATUS = 0 # receive heater measurement mhe.Q2.STATUS = 0 # not optimized in estimator mhe.Q2.FSTATUS = 0 # receive heater measurement # CV tuning mhe.TC1.STATUS = 0 # not needed for estimator mhe.TC1.FSTATUS = 1 # receive measurement mhe.TC2.STATUS = 0 # not needed for estimator mhe.TC2.FSTATUS = 1 # receive measurement # Global Options mhe.options.IMODE = 5 # MHE mhe.options.EV_TYPE = 2 # Objective type mhe.options.NODES = 3 # Collocation nodes mhe.options.SOLVER = 3 # 1=APOPT, 3=IPOPT ################################################################## # Configure MPC # 60 second time horizon, 4 sec cycle time, non-uniform mpc.time = [0,4,8,12,15,20,25,30,35,40,50,60,70,80,90] #mpc.server = 'http://127.0.0.1' # solve locally # FV tuning # don't update FVs with controller mpc.U.STATUS = 0 mpc.tau.STATUS = 0 mpc.alpha1.STATUS = 0 mpc.alpha2.STATUS = 0 mpc.Ta.STATUS = 0 # controller uses measured values from estimator mpc.U.FSTATUS = 1 mpc.tau.FSTATUS = 1 mpc.alpha1.FSTATUS = 1 mpc.alpha2.FSTATUS = 1 mpc.Ta.FSTATUS = 1 # MV tuning mpc.Q1.STATUS = 1 # use to control temperature mpc.Q1.FSTATUS = 0 # no feedback measurement mpc.Q1.DMAX = 20.0 mpc.Q1.DCOST = 0.1 mpc.Q1.COST = 0.0 mpc.Q1.DCOST = 0.0 mpc.Q2.STATUS = 1 # use to control temperature mpc.Q2.FSTATUS = 0 # no feedback measurement mpc.Q2.DMAX = 20.0 mpc.Q2.DCOST = 0.1 mpc.Q2.COST = 0.0 mpc.Q2.DCOST = 0.0 # CV tuning mpc.TC1.STATUS = 1 # minimize error with setpoint range mpc.TC1.FSTATUS = 1 # receive measurement mpc.TC1.TR_INIT = 2 # reference trajectory mpc.TC1.TAU = 10 # time constant for response mpc.TC2.STATUS = 1 # minimize error with setpoint range mpc.TC2.FSTATUS = 1 # receive measurement mpc.TC2.TR_INIT = 2 # reference trajectory mpc.TC2.TAU = 10 # time constant for response # Global Options mpc.options.IMODE = 6 # MPC mpc.options.CV_TYPE = 1 # Objective type mpc.options.NODES = 3 # Collocation nodes mpc.options.SOLVER = 3 # 1=APOPT, 3=IPOPT ################################################################## # Create plot plt.figure() plt.ion() plt.show() # Main Loop start_time = time.time() prev_time = start_time try: for i in range(1,loops): # Sleep time sleep_max = 4.0 sleep = sleep_max - (time.time() - prev_time) if sleep>=0.01: time.sleep(sleep) else: print('Warning: cycle time too fast') print('Requested: ' + str(sleep_max)) print('Actual: ' + str(time.time() - prev_time)) time.sleep(0.01) # Record time and change in time t = time.time() dt = t - prev_time prev_time = t tm[i] = t - start_time # Read temperatures in degC T1[i] = a.T1 T2[i] = a.T2 ################################# ### Moving Horizon Estimation ### ################################# # Measured values mhe.Q1.MEAS = Q1s[i-1] mhe.Q2.MEAS = Q2s[i-1] # Temperatures from Arduino mhe.TC1.MEAS = T1[i] mhe.TC2.MEAS = T2[i] # solve MHE mhe.solve(disp=False) # Parameters from MHE to MPC (if successful) if (mhe.options.APPSTATUS==1): # FVs mpc.U.MEAS = mhe.U.NEWVAL mpc.tau.MEAS = mhe.tau.NEWVAL mpc.alpha1.MEAS = mhe.alpha1.NEWVAL mpc.alpha2.MEAS = mhe.alpha2.NEWVAL mpc.Ta.MEAS = mhe.Ta.NEWVAL # CVs T1mhe[i] = mhe.TC1.MODEL T2mhe[i] = mhe.TC2.MODEL else: print("MHE failed to solve, don't update parameters") T1mhe[i] = np.nan T2mhe[i] = np.nan ################################# ### Model Predictive Control ### ################################# # Temperatures from Arduino mpc.TC1.MEAS = T1[i] mpc.TC2.MEAS = T2[i] # input setpoint with deadband +/- DT DT = 0.2 mpc.TC1.SPHI = Tsp1[i] + DT mpc.TC1.SPLO = Tsp1[i] - DT mpc.TC2.SPHI = Tsp2[i] + DT mpc.TC2.SPLO = Tsp2[i] - DT # solve MPC mpc.solve(disp=False) # test for successful solution if (mpc.options.APPSTATUS==1): # retrieve the first Q value Q1s[i] = mpc.Q1.NEWVAL Q2s[i] = mpc.Q2.NEWVAL else: # not successful, set heater to zero print("MPC failed to solve, heaters off") Q1s[i] = 0 Q2s[i] = 0 # Write output (0-100) a.Q1(Q1s[i]) a.Q2(Q2s[i]) # Plot plt.clf() ax=plt.subplot(3,1,1) ax.grid() plt.plot(tm[0:i],T1[0:i],'ro',MarkerSize=3,label=r'$T_1$ Measured') plt.plot(tm[0:i],Tsp1[0:i],'k:',LineWidth=2,label=r'$T_1$ Set Point') plt.ylabel('Temperature (degC)') plt.legend(loc='best') ax=plt.subplot(3,1,2) ax.grid() plt.plot(tm[0:i],T2[0:i],'ro',MarkerSize=3,label=r'$T_2$ Measured') plt.plot(tm[0:i],Tsp2[0:i],'k:',LineWidth=2,label=r'$T_2$ Set Point') plt.ylabel('Temperature (degC)') plt.legend(loc='best') ax=plt.subplot(3,1,3) ax.grid() plt.plot(tm[0:i],Q1s[0:i],'r-',LineWidth=3,label=r'$Q_1$') plt.plot(tm[0:i],Q2s[0:i],'b:',LineWidth=3,label=r'$Q_2$') plt.ylabel('Heaters') plt.xlabel('Time (sec)') plt.legend(loc='best') plt.draw() plt.pause(0.05) # Turn off heaters a.Q1(0) a.Q2(0) print('Shutting down') # Allow user to end loop with Ctrl-C except KeyboardInterrupt: # Disconnect from Arduino a.Q1(0) a.Q2(0) print('Shutting down') a.close() # Make sure serial connection still closes when there's an error except: # Disconnect from Arduino a.Q1(0) a.Q2(0) print('Error: Shutting down') a.close() raise
Got mineral buildup in your kettle? Here’s how to get rid of it. If you use your kettle a lot, you can quickly get a buildup of minerals that can affect how well it works, which makes cleaning your kettle regularly a good idea. Fortunately, it’s not difficult to do and you can get the kettle to do most of the work for you. As you use your kettle and water evaporates from boiling, calcium and other minerals in the water will solidify and deposit on surfaces in both electric and stove-top kettles. While not harmful to you, the buildup can decrease the efficiency of your kettle. The simplest and most environmentally friendly way to descale your kettle is by using white vinegar. Using equal parts vinegar and water, fill your kettle halfway, bring it to a boil and then let it sit for 20 minutes or so. Unless you have excessive buildup, this should be enough to remove the deposits. You can then rinse out your kettle, fill it with fresh water and boil it again to remove any vinegar smell. If deposits remain, repeat the process, letting the boiled solution sit longer before removing. A word of caution: Some manufacturers may recommend against using vinegar to clean a kettle. If that’s the case with yours, you can use lemon or baking soda instead (juice of one lemon or a teaspoon of baking soda). Of course, you can also use commercial cleaning products. Just be sure to follow the instructions. Tip: Do you have a tendency to leave extra water in the kettle after using it? That’s not a good idea as standing water can also leave mineral deposits. Better to boil only the water you need or empty it after using. Give the exterior of your kettle a wipe-down once a week or so. Use a non-abrasive cloth with a bit of dish soap if water alone is not enough. And if you have an electric kettle, be sure to avoid immersing the element in water.
#!/usr/bin/python import os import sys import re import struct import pymongo from flight_recorder.mongo import FlightRecorderFetcher from bottle import hook, route, run, template, request, response method_list = {} def main(): #create a new flight recorder instance fr = FlightRecorderFetcher() @hook('after_request') def enable_cors(): response.headers['Access-Control-Allow-Origin'] = '*' # provides a consistent way to return data via webservices def format_results( res, err=None ): error_bool = True if(err) else False return { 'results': res, 'error': error_bool, 'error_msg': err } # takes in a validator grabs the method_name and method_description keys # to build a help message to print to the user when /help is executed def create_method_help_obj( validators ): global method_list # grab our name and description and remove them from the validator dict method_name = validators.pop('method_name', None) method_description = validators.pop('method_description', None) # make sure they are defined if(method_name is None): print "You must provide a method_name along with the validator for the /help method!" sys.exit(1) if(method_description is None): print "You must provide a method_description along with the validator for the /help method!" sys.exit(1) method_list[method_name] = {} method_list[method_name]['description'] = method_description method_list[method_name]['parameters'] = [] for param in validators: parameter = {} validator = validators[param] parameter['name'] = param parameter['required'] = validator.get('required', False) if(validator.get('pattern', False)): parameter['pattern'] = validator.get('pattern') if(validator.get('type', False)): parameter['type'] = validator.get('type') if(validator.get('checks', False)): checks = validator.get('checks'); parameter['checks'] = [] for check in checks: try: parameter['checks'].append(check.__descr__) except: print "Must provide __descr__ for checks!" sys.exit(1) method_list[method_name]['parameters'].append(parameter) method_list[method_name]['parameters'] = sorted( method_list[method_name]['parameters'], key=lambda k: k['name']) return validators # special decorator that takes in kwargs where the key is the parameter # and the value is an object representing the validation it should do to the # parameter def validate_params( **kwargs ): validators = create_method_help_obj(kwargs) def validate_params_decorator(func): def wrapper(*args, **kwargs): validated_args = {} for param in validators: validator = validators[param] checks = validator.get('checks', []) default = validator.get('default', None) value = request.params.get(param, default) # check if the param was required if(validator.get('required', False) and value == None ): return format_results( None, "Parameter, {0}, is required".format(param) ) # only do further validation if it's not required if(value != None): # if the parameter needs to match a particular pattern make sure it does if( validator.get('pattern', False) ): pattern = validator.get('pattern') regex = re.compile(pattern) if(not regex.match(value) ): return format_results( None, "Parameter, {0}, must match pattern, {1}".format(param, pattern) ) # if a type is set try to convert to the type otherwise send error if( validator.get('type', False) ): if( validator.get('type') == 'string' ): try: value = str(value) except Exception as e: return format_results( None, "Error converting {0} to string: {1}".format(value, e)) if( validator.get('type') == 'integer' ): try: value = int(value) except Exception as e: return format_results( None, "Error converting {0} to integer: {1}".format(value, e)) # if the param has any special check perform them now for check in checks: err, msg = check( value ) if(err): return format_results( None, msg ) # if we've gotten here the param is good so add it to our validated params validated_args[param] = value return func(validated_args) return wrapper return validate_params_decorator @route('/') @route('/help') @validate_params( method_name = 'help', method_description = 'Returns information about what methods are available and their parameters if a method is specified', method = {} ) def help(params): method = params.get('method') methods = None if(method is not None): try: methods = [method_list.get(method)] methods[0]['name'] = method except: return format_results( None, "Method, {0}, does not exists".format(method) ) else: methods = method_list.keys() methods.sort() return format_results( methods ) @route('/streams') @validate_params( method_name = 'streams', method_description = 'returns a list of streams matching specified params', name = {}, addr = {'required': False, 'type': 'string'}, port = {'required': False, 'type': 'integer'}, start = {'required': False, 'type': 'integer'}, stop = {'required': False, 'type': 'integer'}, ) def get_streams(params): results = fr.get_streams( params ) if(results is not None): return format_results( results ) else: return format_results( [], fr.get_error() ) @route('/messages') @validate_params( method_name='messages', method_description = 'returns a list of messages matching the specified params', name = {}, stream_id = {'required': False, 'type': 'string'}, start = {'required': False, 'type': 'integer'}, stop = {'required': False, 'type': 'integer'}, ) def get_messages(params): results = fr.get_messages( params ) if(results is not None): return format_results( results ) else: return format_results([], fr.get_error()) run(host="0.0.0.0", port=8080) main()
So far CowboyBoss has created 38 entries. Do you agree with the cowboy principle that “right is right, and wrong is wrong, and there’s nothing in between”? Or perhaps you are more inclined to think like a young university student I met in a Penn State classroom not long ago. It’s already been one of the worst winters in years, and a new line of storms is slamming much of the country with heavy snow, punishing winds, and sheets of ice. The weather has been so severe that many areas have declared states of emergency.
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source, # Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS # SPDX - License - Identifier: GPL - 3.0 + from mantid import logger, AlgorithmFactory from mantid.api import * from mantid.kernel import * import mantid.simpleapi as ms class IqtFitMultiple(PythonAlgorithm): _input_ws = None _function = None _fit_type = None _start_x = None _end_x = None _spec_min = None _spec_max = None _intensities_constrained = None _minimizer = None _max_iterations = None _result_name = None _parameter_name = None _fit_group_name = None def category(self): return "Workflow\\MIDAS" def summary(self): return r"Fits an \*\_iqt file generated by I(Q,t)." def PyInit(self): self.declareProperty(MatrixWorkspaceProperty('InputWorkspace', '', direction=Direction.Input), doc='The _iqt.nxs InputWorkspace used by the algorithm') self.declareProperty(FunctionProperty(name='Function',direction=Direction.InOut), doc='The function to use in fitting') self.declareProperty(name='FitType', defaultValue='', doc='The type of fit being carried out') self.declareProperty(name='StartX', defaultValue=0.0, validator=FloatBoundedValidator(0.0), doc="The first value for X") self.declareProperty(name='EndX', defaultValue=0.2, validator=FloatBoundedValidator(0.0), doc="The last value for X") self.declareProperty(name='SpecMin', defaultValue=0, validator=IntBoundedValidator(0), doc='Minimum spectra in the workspace to fit') self.declareProperty(name='SpecMax', defaultValue=1, validator=IntBoundedValidator(0), doc='Maximum spectra in the workspace to fit') self.declareProperty(name='Minimizer', defaultValue='Levenberg-Marquardt', doc='The minimizer to use in fitting') self.declareProperty(name="MaxIterations", defaultValue=500, validator=IntBoundedValidator(0), doc="The Maximum number of iterations for the fit") self.declareProperty(name='ConstrainIntensities', defaultValue=False, doc="If the Intensities should be constrained during the fit") self.declareProperty(name='ExtractMembers', defaultValue=False, doc="If true, then each member of the fit will be extracted, into their " "own workspace. These workspaces will have a histogram for each spectrum " "(Q-value) and will be grouped.") self.declareProperty(MatrixWorkspaceProperty('OutputResultWorkspace', '', direction=Direction.Output), doc='The output workspace containing the results of the fit data') self.declareProperty(ITableWorkspaceProperty('OutputParameterWorkspace', '', direction=Direction.Output), doc='The output workspace containing the parameters for each fit') self.declareProperty(WorkspaceGroupProperty('OutputWorkspaceGroup', '', direction=Direction.Output), doc='The OutputWorkspace group Data, Calc and Diff, values for the fit of each spectra') def validateInputs(self): self._get_properties() issues = dict() maximum_possible_spectra = self._input_ws.getNumberHistograms() maximum_possible_x = self._input_ws.readX(0)[self._input_ws.blocksize() - 1] # Validate SpecMin/Max if self._spec_max > maximum_possible_spectra: issues['SpecMax'] = ('SpecMax must be smaller or equal to the number of ' 'spectra in the input workspace, %d' % maximum_possible_spectra) if self._spec_min < 0: issues['SpecMin'] = 'SpecMin can not be less than 0' if self._spec_max < self._spec_min: issues['SpecMax'] = 'SpecMax must be more than or equal to SpecMin' # Validate Start/EndX if self._end_x > maximum_possible_x: issues['EndX'] = ('EndX must be less than the highest x value in the workspace, %d' % maximum_possible_x) if self._start_x < 0: issues['StartX'] = 'StartX can not be less than 0' if self._start_x > self._end_x: issues['EndX'] = 'EndX must be more than StartX' return issues def _get_properties(self): self._input_ws = self.getProperty('InputWorkspace').value self._function = self.getProperty('Function').value self._fit_type = self.getProperty('FitType').value self._start_x = self.getProperty('StartX').value self._end_x = self.getProperty('EndX').value self._spec_min = self.getProperty('SpecMin').value self._spec_max = self.getProperty('SpecMax').value self._intensities_constrained = self.getProperty('ConstrainIntensities').value self._do_extract_members = self.getProperty('ExtractMembers').value self._minimizer = self.getProperty('Minimizer').value self._max_iterations = self.getProperty('MaxIterations').value self._result_name = self.getPropertyValue('OutputResultWorkspace') self._parameter_name = self.getPropertyValue('OutputParameterWorkspace') self._fit_group_name = self.getPropertyValue('OutputWorkspaceGroup') def PyExec(self): from IndirectCommon import (convertToElasticQ, transposeFitParametersTable) setup_prog = Progress(self, start=0.0, end=0.1, nreports=4) setup_prog.report('generating output name') output_workspace = self._fit_group_name # check if the naming convention used is already correct chopped_name = self._fit_group_name.split('_') if 'WORKSPACE' in chopped_name[-1].upper(): output_workspace = '_'.join(chopped_name[:-1]) option = self._fit_type[:-2] logger.information('Option: ' + option) logger.information('Function: ' + str(self._function)) setup_prog.report('Cropping workspace') # prepare input workspace for fitting tmp_fit_workspace = "__Iqtfit_fit_ws" if self._spec_max is None: crop_alg = self.createChildAlgorithm("CropWorkspace", enableLogging=False) crop_alg.setProperty("InputWorkspace", self._input_ws) crop_alg.setProperty("OutputWorkspace", tmp_fit_workspace) crop_alg.setProperty("XMin", self._start_x) crop_alg.setProperty("XMax", self._end_x) crop_alg.setProperty("StartWorkspaceIndex", self._spec_min) crop_alg.execute() else: crop_alg = self.createChildAlgorithm("CropWorkspace", enableLogging=False) crop_alg.setProperty("InputWorkspace", self._input_ws) crop_alg.setProperty("OutputWorkspace", tmp_fit_workspace) crop_alg.setProperty("XMin", self._start_x) crop_alg.setProperty("XMax", self._end_x) crop_alg.setProperty("StartWorkspaceIndex", self._spec_min) crop_alg.setProperty("EndWorkspaceIndex", self._spec_max) crop_alg.execute() setup_prog.report('Converting to Histogram') convert_to_hist_alg = self.createChildAlgorithm("ConvertToHistogram", enableLogging=False) convert_to_hist_alg.setProperty("InputWorkspace", crop_alg.getProperty("OutputWorkspace").value) convert_to_hist_alg.setProperty("OutputWorkspace", tmp_fit_workspace) convert_to_hist_alg.execute() mtd.addOrReplace(tmp_fit_workspace, convert_to_hist_alg.getProperty("OutputWorkspace").value) setup_prog.report('Convert to Elastic Q') convertToElasticQ(tmp_fit_workspace) # fit multi-domain function to workspace fit_prog = Progress(self, start=0.1, end=0.8, nreports=2) multi_domain_func, kwargs = _create_multi_domain_func(self._function, tmp_fit_workspace) fit_prog.report('Fitting...') ms.Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0, Output=output_workspace, CreateOutput=True, Minimizer=self._minimizer, MaxIterations=self._max_iterations, OutputCompositeMembers=self._do_extract_members, **kwargs) fit_prog.report('Fitting complete') conclusion_prog = Progress(self, start=0.8, end=1.0, nreports=5) conclusion_prog.report('Renaming workspaces') # rename workspaces to match user input rename_alg = self.createChildAlgorithm("RenameWorkspace", enableLogging=False) if output_workspace + "_Workspaces" != self._fit_group_name: rename_alg.setProperty("InputWorkspace", output_workspace + "_Workspaces") rename_alg.setProperty("OutputWorkspace", self._fit_group_name) rename_alg.execute() if output_workspace + "_Parameters" != self._parameter_name: rename_alg.setProperty("InputWorkspace", output_workspace + "_Parameters") rename_alg.setProperty("OutputWorkspace", self._parameter_name) rename_alg.execute() conclusion_prog.report('Transposing parameter table') transposeFitParametersTable(self._parameter_name) # set first column of parameter table to be axis values x_axis = mtd[tmp_fit_workspace].getAxis(1) axis_values = x_axis.extractValues() for i, value in enumerate(axis_values): mtd[self._parameter_name].setCell('axis-1', i, value) # convert parameters to matrix workspace parameter_names = 'A0,Height,Lifetime,Stretching' conclusion_prog.report('Processing indirect fit parameters') pifp_alg = self.createChildAlgorithm("ProcessIndirectFitParameters") pifp_alg.setProperty("InputWorkspace", self._parameter_name) pifp_alg.setProperty("ColumnX", "axis-1") pifp_alg.setProperty("XAxisUnit", "MomentumTransfer") pifp_alg.setProperty("ParameterNames", parameter_names) pifp_alg.setProperty("OutputWorkspace", self._result_name) pifp_alg.execute() result_workspace = pifp_alg.getProperty("OutputWorkspace").value mtd.addOrReplace(self._result_name, result_workspace) # create and add sample logs sample_logs = {'start_x': self._start_x, 'end_x': self._end_x, 'fit_type': self._fit_type[:-2], 'intensities_constrained': self._intensities_constrained, 'beta_constrained': True} conclusion_prog.report('Copying sample logs') copy_log_alg = self.createChildAlgorithm("CopyLogs", enableLogging=False) copy_log_alg.setProperty("InputWorkspace", self._input_ws) copy_log_alg.setProperty("OutputWorkspace", result_workspace) copy_log_alg.execute() copy_log_alg.setProperty("InputWorkspace", self._input_ws) copy_log_alg.setProperty("OutputWorkspace", self._fit_group_name) copy_log_alg.execute() log_names = [item for item in sample_logs] log_values = [sample_logs[item] for item in sample_logs] conclusion_prog.report('Adding sample logs') add_sample_log_multi = self.createChildAlgorithm("AddSampleLogMultiple", enableLogging=False) add_sample_log_multi.setProperty("Workspace", result_workspace.name()) add_sample_log_multi.setProperty("LogNames", log_names) add_sample_log_multi.setProperty("LogValues", log_values) add_sample_log_multi.execute() add_sample_log_multi.setProperty("Workspace", self._fit_group_name) add_sample_log_multi.setProperty("LogNames", log_names) add_sample_log_multi.setProperty("LogValues", log_values) add_sample_log_multi.execute() delete_alg = self.createChildAlgorithm("DeleteWorkspace", enableLogging=False) delete_alg.setProperty("Workspace", tmp_fit_workspace) delete_alg.execute() if self._do_extract_members: ms.ExtractQENSMembers(InputWorkspace=self._input_ws, ResultWorkspace=self._fit_group_name, OutputWorkspace=self._fit_group_name.rsplit('_', 1)[0] + "_Members") self.setProperty('OutputResultWorkspace', result_workspace) self.setProperty('OutputParameterWorkspace', self._parameter_name) self.setProperty('OutputWorkspaceGroup', self._fit_group_name) conclusion_prog.report('Algorithm complete') def _create_multi_domain_func(function, input_ws): multi = 'composite=MultiDomainFunction,NumDeriv=true;' comp = '(composite=CompositeFunction,NumDeriv=true,$domains=i;' + str(function) + ');' stretched_indices = _find_indices_of_stretched_exponentials(function) if not stretched_indices: logger.warning("Stretched Exponential not found in function, tie-creation skipped.") return function ties = [] kwargs = {} num_spectra = mtd[input_ws].getNumberHistograms() for i in range(0, num_spectra): multi += comp kwargs['WorkspaceIndex_' + str(i)] = i if i > 0: kwargs['InputWorkspace_' + str(i)] = input_ws # tie beta for every spectrum for stretched_index in stretched_indices: ties.append('f{0}.f{1}.Stretching=f0.f{1}.Stretching'.format(i, stretched_index)) ties = ','.join(ties) multi += 'ties=(' + ties + ')' return multi, kwargs def _find_indices_of_stretched_exponentials(composite): indices = [] for index in range(0, len(composite)): if composite.getFunction(index).name() == "StretchExp": indices.append(index) return indices AlgorithmFactory.subscribe(IqtFitMultiple)
NAR has expressed thanks on behalf of America’s homebuyers to three Senators for introducing a measure to extend the present home buyer tax credit closing deadline to September 30. They are Senate Majority Leader Harry Reid, D-Nev., and Sens. Johnny Isakson, R-Ga., and Chris Dodd, D-Conn. The measure was offered as an amendment to H.R. 4213, a tax extension bill now in the Senate. NAR estimates the number of home buyers who have qualified for the tax credit and met the contract deadline of April 30, but who would not be able to close their transaction by the June 30 deadline, could go as high as 180,000. REALTORS have reported as many as one-third of qualified applicants have been notified by lenders that their mortgages will not close before June 30 due to the sheer volume of applications in the pipeline.
from django.views.generic.list import MultipleObjectMixin __all__ = ('FilterFormMixin',) class FilterFormMixin(MultipleObjectMixin): """ Mixin that adds filtering behaviour for Class Based Views. """ filter_form_cls = None use_filter_chaining = False context_filterform_name = 'filterform' def get_filter(self): """ Get FilterForm instance. """ return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining) def get_queryset(self): """ Return queryset with filtering applied (if filter form passes validation). """ qs = super(FilterFormMixin, self).get_queryset() filter_form = self.get_filter() if filter_form.is_valid(): qs = filter_form.filter(qs).distinct() return qs def get_context_data(self, **kwargs): """ Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization. """ context = super(FilterFormMixin, self).get_context_data(**kwargs) context[self.context_filterform_name] = self.get_filter() return context def get_runtime_context(self): """ Get context for filter form to allow passing runtime information, such as user, cookies, etc. Method might be overriden by implementation and context returned by this method will be accessible in to_lookup() method implementation of FilterSpec. """ return {'user': self.request.user}
In order to supply their body with various vitamins, many people opt for dietary supplements. As technology and science improve these supplements become more advanced. Nowadays, you can consume vitamins in some bottled water products, in the pill form, but also as gummy vitamins. The latter has become very popular lately, but how much you really know about them. This post focuses on the pros and cons of gummy vitamins. Scroll down to learn more. Gummy vitamins are, basically, chewable vitamins that have a similar taste and texture to gummy candies. They have become popular due to cute shapes, vibrant colors, and great taste that comes in different flavors. Many people find them convenient as they get to supply their body with much-needed vitamins easily and thereby avoid deficiencies and symptoms that come with them. Parents buy gummy vitamins to children hoping they could be a substitute for vegetables and other vitamin-dense foods their kids don’t like to eat. Children aren’t the only ones who love gummy vitamins, and adults are fans too. Gummy vitamins are usually made of gelatin, colorings, sugar, water, and corn starch. They may include various vitamins and minerals or just individual forms such as calcium and vitamin D. What people love about them is their accessibility, you can find and buy them in health stores, drug stores, supermarkets, online, you name it. But, like everything else, gummy vitamins also have both advantages and disadvantages. We’re going to start with the benefits of gummy vitamins. They are listed below. Gummy vitamins are everything but plain and boring. They come in all sorts of colors, shapes, flavors, and textures. This versatility makes gummy vitamins appealing to children and adults. Regardless of your needs and preferences, it’s entirely possible to find ideal gummy vitamins in the stores and online. Probably the most common reason why people love gummy vitamins is their convenience. They pose as a practical way to get the required amount of various vitamins, particularly if a person’s diet doesn’t deliver these much-needed nutrients. You just take these gummy candy-looking vitamins, and that’s it. This is particularly useful for parents of picky eaters. Children are able to consume vitamins in a way they like the most. With the rise of unhealthy food options, people are gradually becoming deficient in various vitamins and minerals. Our body is unable to function properly without these nutrients. However, junk food doesn’t really introduce a vast selection of vitamins and minerals, and we already know that. Therefore, eating gummy vitamins can be a practical way to prevent nutritional deficiencies. As mentioned above, some products contain a single vitamin only, e.g. vitamin C or vitamin D, but others deliver multiple vitamins and minerals. Some people find vitamins in pill form inconvenient due to the fact they can’t swallow them properly. Gummy vitamins allow you to avoid this hassle. You just chew them up, and that’s it, problem solved. There is no evidence that one form of the vitamin is superior to another. Efficacy of gummy vitamins is not necessarily weaker than that of pills or some other forms of vitamin consumption. This is important to bear in mind because we’re quick to render something ineffective just because it comes in an unusual form. Besides convenient benefits, gummy vitamins also have some disadvantages. Let’s see what they are. The primary concern regarding gummy vitamins is that most products of this kind on the market are made with added sugar. In fact, sugar is one of the reasons they’re delicious. But, eating too much can introduce way more sugar to the body than recommended for the day. Calories from sugar tend to add up quickly so if you also eat chocolate, sweets, and other sources of sugar in addition to gummy vitamins it can be too much. Some gummy vitamins may feature “sugar-free” on the label, but it doesn’t necessarily mean they contain no sugar at all. Instead, they contain sugar alcohols which are listed under total carbs on the label. Excessive intake of sugar alcohols leads to diarrhea, bloating, nausea, and other uncomfortable symptoms. FDA does not regulate the manufacturing process of dietary supplements and vitamins, including gummy vitamins. Therefore, a brand may list the entirely different amount of nutrient on the label then it’s actually present in the gummy vitamin itself. In fact, reports show that a vast majority of gummy vitamins on the market do not have the same amounts of vitamins and minerals as listed on the label. Our body needs a certain amount of various nutrients each day. But, gummy vitamins are so tasty that some people and children may end up eating more than recommended. This could lead to mineral toxicity which can harm your body. When buying gummy vitamins make sure you check the label, particularly if you’re vegetarian or vegan. Many gummy vitamins are made from gelatin which is produced from the skin, tendons, and even bones of some animals. Gummy vitamins may be a convenient way to consume enough vitamins and minerals during the day. However, you shouldn’t eat too much due to sugars and sugar alcohols. You need to bear in mind that a healthy diet should be the primary source of vitamins and children need to adopt healthy eating habits.
# -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # __revision__ = "$Id: HamacherSum.py,v 1.4 2009/08/07 07:19:19 rliebscher Exp $" from fuzzy.norm.Norm import Norm,NormException class HamacherSum(Norm): def __init__(self): Norm.__init__(self,Norm.S_NORM) def __call__(self,*args): if len(args) != 2: raise NormException("%s is supported only for 2 parameters" % self.__class__.__name__ ) x = float(args[0]) y = float(args[1]) if x*y == 1.: return 1. return (x+y-2.0*x*y)/(1.0-x*y)
McHenry County has passed an ordinance to regulate alarms and establish a violation for repeated false alarms within the County. Among the provisions contained within the ordinance is the requirement to notify the Sheriff's Office of your system. Failure to notify the Sheriff's Office of your alarm is a violation of the ordinance. Also among the provisions is a system whereby repeated false alarms will subject the owner to potential charges of violating the ordinance. I strongly urge you to carefully review the ordinance so that you will be aware of the requirements set forth. While I view alarms as a valuable tool in the prevention of crime and preservation of the health and safety of the citizens of McHenry County, false alarms constitute a danger to police and fire first responders and to the public traveling the highways of the County during those responses. False alarms are a drain on police and fire resources which are often diverted from other tasks to respond to this type of call for service. It is hoped that through compliance with this ordinance, the number of false alarms will be reduced, thereby bringing an increased level of safety to the citizens of the County not only through the reduction in responses by emergency units to these calls, but also through the allocation of these resources to other crime prevention and reduction activities.
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + """ The run tab presenter. This presenter is essentially the brain of the reduction gui. It controls other presenters and is mainly responsible for presenting and generating the reduction settings. """ from __future__ import (absolute_import, division, print_function) import copy import csv import os import sys import time import traceback from mantid.api import (FileFinder) from mantid.kernel import Logger, ConfigService from sans.command_interface.batch_csv_file_parser import BatchCsvParser from sans.common.constants import ALL_PERIODS from sans.common.enums import (BatchReductionEntry, RangeStepType, SampleShape, FitType, RowState, SANSInstrument) from sans.gui_logic.gui_common import (get_reduction_mode_strings_for_gui, get_string_for_gui_from_instrument, add_dir_to_datasearch, remove_dir_from_datasearch) from sans.gui_logic.models.batch_process_runner import BatchProcessRunner from sans.gui_logic.models.beam_centre_model import BeamCentreModel from sans.gui_logic.models.create_state import create_states from sans.gui_logic.models.diagnostics_page_model import run_integral, create_state from sans.gui_logic.models.state_gui_model import StateGuiModel from sans.gui_logic.models.table_model import TableModel, TableIndexModel from sans.gui_logic.presenter.add_runs_presenter import OutputDirectoryObserver as SaveDirectoryObserver from sans.gui_logic.presenter.beam_centre_presenter import BeamCentrePresenter from sans.gui_logic.presenter.diagnostic_presenter import DiagnosticsPagePresenter from sans.gui_logic.presenter.masking_table_presenter import (MaskingTablePresenter) from sans.gui_logic.presenter.save_other_presenter import SaveOtherPresenter from sans.gui_logic.presenter.settings_diagnostic_presenter import (SettingsDiagnosticPresenter) from sans.sans_batch import SANSCentreFinder from sans.user_file.user_file_reader import UserFileReader from ui.sans_isis import SANSSaveOtherWindow from ui.sans_isis.sans_data_processor_gui import SANSDataProcessorGui from ui.sans_isis.work_handler import WorkHandler from qtpy import PYQT4 IN_MANTIDPLOT = False if PYQT4: try: from mantidplot import graph, newGraph IN_MANTIDPLOT = True except ImportError: pass else: from mantidqt.plotting.functions import get_plot_fig row_state_to_colour_mapping = {RowState.Unprocessed: '#FFFFFF', RowState.Processed: '#d0f4d0', RowState.Error: '#accbff'} def log_times(func): """ Generic decorator to time the execution of the function and print it to the logger. """ def run(*args, **kwargs): t0 = time.time() result = func(*args, **kwargs) t1 = time.time() time_taken = t1 - t0 # args[0] is the self parameter args[0].sans_logger.information("The generation of all states took {}s".format(time_taken)) return result return run class RunTabPresenter(object): class ConcreteRunTabListener(SANSDataProcessorGui.RunTabListener): def __init__(self, presenter): super(RunTabPresenter.ConcreteRunTabListener, self).__init__() self._presenter = presenter def on_user_file_load(self): self._presenter.on_user_file_load() def on_mask_file_add(self): self._presenter.on_mask_file_add() def on_batch_file_load(self): self._presenter.on_batch_file_load() def on_process_selected_clicked(self): self._presenter.on_process_selected_clicked() def on_process_all_clicked(self): self._presenter.on_process_all_clicked() def on_load_clicked(self): self._presenter.on_load_clicked() def on_export_table_clicked(self): self._presenter.on_export_table_clicked() def on_multi_period_selection(self, show_periods): self._presenter.on_multiperiod_changed(show_periods) def on_data_changed(self, row, column, new_value, old_value): self._presenter.on_data_changed(row, column, new_value, old_value) def on_manage_directories(self): self._presenter.on_manage_directories() def on_instrument_changed(self): self._presenter.on_instrument_changed() def on_row_inserted(self, index, row): self._presenter.on_row_inserted(index, row) def on_rows_removed(self, rows): self._presenter.on_rows_removed(rows) def on_copy_rows_requested(self): self._presenter.on_copy_rows_requested() def on_paste_rows_requested(self): self._presenter.on_paste_rows_requested() def on_insert_row(self): self._presenter.on_insert_row() def on_erase_rows(self): self._presenter.on_erase_rows() def on_cut_rows(self): self._presenter.on_cut_rows_requested() def on_save_other(self): self._presenter.on_save_other() def on_sample_geometry_selection(self, show_geometry): self._presenter.on_sample_geometry_view_changed(show_geometry) def on_compatibility_unchecked(self): self._presenter.on_compatibility_unchecked() class ProcessListener(WorkHandler.WorkListener): def __init__(self, presenter): super(RunTabPresenter.ProcessListener, self).__init__() self._presenter = presenter def on_processing_finished(self, result): self._presenter.on_processing_finished(result) def on_processing_error(self, error): self._presenter.on_processing_error(error) def __init__(self, facility, view=None): super(RunTabPresenter, self).__init__() self._facility = facility # Logger self.sans_logger = Logger("SANS") # Name of graph to output to self.output_graph = 'SANS-Latest' # For matplotlib continuous plotting self.output_fig = None self.progress = 0 # Models that are being used by the presenter self._state_model = None self._table_model = TableModel() self._table_model.subscribe_to_model_changes(self) # Presenter needs to have a handle on the view since it delegates it self._view = None self.set_view(view) self._processing = False self.work_handler = WorkHandler() self.batch_process_runner = BatchProcessRunner(self.notify_progress, self.on_processing_finished, self.on_processing_error) # File information for the first input self._file_information = None self._clipboard = [] # Settings diagnostic tab presenter self._settings_diagnostic_tab_presenter = SettingsDiagnosticPresenter(self) # Masking table presenter self._masking_table_presenter = MaskingTablePresenter(self) self._table_model.subscribe_to_model_changes(self._masking_table_presenter) # Beam centre presenter self._beam_centre_presenter = BeamCentrePresenter(self, WorkHandler, BeamCentreModel, SANSCentreFinder) self._table_model.subscribe_to_model_changes(self._beam_centre_presenter) # Workspace Diagnostic page presenter self._workspace_diagnostic_presenter = DiagnosticsPagePresenter(self, WorkHandler, run_integral, create_state, self._facility) # Check save dir for display self._save_directory_observer = \ SaveDirectoryObserver(self._handle_output_directory_changed) def _default_gui_setup(self): """ Provides a default setup of the GUI. This is important for the initial start up, when the view is being set. """ # Set the possible reduction modes reduction_mode_list = get_reduction_mode_strings_for_gui() self._view.set_reduction_modes(reduction_mode_list) # Set the step type options for wavelength range_step_types = [RangeStepType.to_string(RangeStepType.Lin), RangeStepType.to_string(RangeStepType.Log), RangeStepType.to_string(RangeStepType.RangeLog), RangeStepType.to_string(RangeStepType.RangeLin)] self._view.wavelength_step_type = range_step_types # Set the geometry options. This needs to include the option to read the sample shape from file. sample_shape = ["Read from file", SampleShape.Cylinder, SampleShape.FlatPlate, SampleShape.Disc] self._view.sample_shape = sample_shape # Set the q range self._view.q_1d_step_type = [RangeStepType.to_string(RangeStepType.Lin), RangeStepType.to_string(RangeStepType.Log)] self._view.q_xy_step_type = [RangeStepType.to_string(RangeStepType.Lin), RangeStepType.to_string(RangeStepType.Log)] # Set the fit options fit_types = [FitType.to_string(FitType.Linear), FitType.to_string(FitType.Logarithmic), FitType.to_string(FitType.Polynomial)] self._view.transmission_sample_fit_type = fit_types self._view.transmission_can_fit_type = fit_types def _handle_output_directory_changed(self, new_directory): """ Update the gui to display the new save location for workspaces :param new_directory: string. Current save directory for files :return: """ self._view.set_out_file_directory(new_directory) # ------------------------------------------------------------------------------------------------------------------ # Table + Actions # ------------------------------------------------------------------------------------------------------------------ def set_view(self, view): """ Sets the view :param view: the view is the SANSDataProcessorGui. The presenter needs to access some of the API """ if view is not None: self._view = view # Add a listener to the view listener = RunTabPresenter.ConcreteRunTabListener(self) self._view.add_listener(listener) # Default gui setup self._default_gui_setup() self._view.disable_process_buttons() # Set appropriate view for the state diagnostic tab presenter self._settings_diagnostic_tab_presenter.set_view(self._view.settings_diagnostic_tab) # Set appropriate view for the masking table presenter self._masking_table_presenter.set_view(self._view.masking_table) # Set the appropriate view for the beam centre presenter self._beam_centre_presenter.set_view(self._view.beam_centre) # Set the appropriate view for the diagnostic page self._workspace_diagnostic_presenter.set_view(self._view.diagnostic_page, self._view.instrument) self._view.setup_layout() self._view.set_out_file_directory(ConfigService.Instance().getString("defaultsave.directory")) self._view.set_out_default_user_file() self._view.set_out_default_output_mode() self._view.set_out_default_save_can() self._view.set_hinting_line_edit_for_column( self._table_model.column_name_converter.index('sample_shape'), self._table_model.get_sample_shape_hint_strategy()) self._view.set_hinting_line_edit_for_column( self._table_model.column_name_converter.index('options_column_model'), self._table_model.get_options_hint_strategy()) def on_user_file_load(self): """ Loads the user file. Populates the models and the view. """ error_msg = "Loading of the user file failed" try: # 1. Get the user file path from the view user_file_path = self._view.get_user_file_path() if not user_file_path: return # 2. Get the full file path user_file_path = FileFinder.getFullPath(user_file_path) if not os.path.exists(user_file_path): raise RuntimeError( "The user path {} does not exist. Make sure a valid user file path" " has been specified.".format(user_file_path)) except RuntimeError as path_error: # This exception block runs if user file does not exist self._on_user_file_load_failure(path_error, error_msg + " when finding file.") else: try: self._table_model.user_file = user_file_path # Clear out the current view self._view.reset_all_fields_to_default() # 3. Read and parse the user file user_file_reader = UserFileReader(user_file_path) user_file_items = user_file_reader.read_user_file() except (RuntimeError, ValueError) as e: # It is in this exception block that loading fails if the file is invalid (e.g. a csv) self._on_user_file_load_failure(e, error_msg + " when reading file.", use_error_name=True) else: try: # 4. Populate the model self._state_model = StateGuiModel(user_file_items) # 5. Update the views. self._update_view_from_state_model() self._beam_centre_presenter.update_centre_positions(self._state_model) self._beam_centre_presenter.on_update_rows() self._masking_table_presenter.on_update_rows() self._workspace_diagnostic_presenter.on_user_file_load(user_file_path) # 6. Warning if user file did not contain a recognised instrument if self._view.instrument == SANSInstrument.NoInstrument: raise RuntimeError("User file did not contain a SANS Instrument.") except RuntimeError as instrument_e: # This exception block runs if the user file does not contain an parsable instrument self._on_user_file_load_failure(instrument_e, error_msg + " when reading instrument.") except Exception as other_error: # If we don't catch all exceptions, SANS can fail to open if last loaded # user file contains an error that would not otherwise be caught traceback.print_exc() self._on_user_file_load_failure(other_error, "Unknown error in loading user file.", use_error_name=True) def _on_user_file_load_failure(self, e, message, use_error_name=False): self._setup_instrument_specific_settings(SANSInstrument.NoInstrument) self._view.instrument = SANSInstrument.NoInstrument self._view.on_user_file_load_failure() self.display_errors(e, message, use_error_name) def on_batch_file_load(self): """ Loads a batch file and populates the batch table based on that. """ try: # 1. Get the batch file from the view batch_file_path = self._view.get_batch_file_path() if not batch_file_path: return datasearch_dirs = ConfigService["datasearch.directories"] batch_file_directory, datasearch_dirs = add_dir_to_datasearch(batch_file_path, datasearch_dirs) ConfigService["datasearch.directories"] = datasearch_dirs if not os.path.exists(batch_file_path): raise RuntimeError( "The batch file path {} does not exist. Make sure a valid batch file path" " has been specified.".format(batch_file_path)) self._table_model.batch_file = batch_file_path # 2. Read the batch file batch_file_parser = BatchCsvParser(batch_file_path) parsed_rows = batch_file_parser.parse_batch_file() # 3. Populate the table self._table_model.clear_table_entries() for index, row in enumerate(parsed_rows): self._add_row_to_table_model(row, index) self._table_model.remove_table_entries([len(parsed_rows)]) except RuntimeError as e: if batch_file_directory: # Remove added directory from datasearch.directories ConfigService["datasearch.directories"] = remove_dir_from_datasearch(batch_file_directory, datasearch_dirs) self.sans_logger.error("Loading of the batch file failed. {}".format(str(e))) self.display_warning_box('Warning', 'Loading of the batch file failed', str(e)) def _add_row_to_table_model(self, row, index): """ Adds a row to the table """ def get_string_entry(_tag, _row): _element = "" if _tag in _row: _element = _row[_tag] return _element def get_string_period(_tag): return "" if _tag == ALL_PERIODS else str(_tag) # 1. Pull out the entries sample_scatter = get_string_entry(BatchReductionEntry.SampleScatter, row) sample_scatter_period = get_string_period( get_string_entry(BatchReductionEntry.SampleScatterPeriod, row)) sample_transmission = get_string_entry(BatchReductionEntry.SampleTransmission, row) sample_transmission_period = \ get_string_period(get_string_entry(BatchReductionEntry.SampleTransmissionPeriod, row)) sample_direct = get_string_entry(BatchReductionEntry.SampleDirect, row) sample_direct_period = get_string_period( get_string_entry(BatchReductionEntry.SampleDirectPeriod, row)) can_scatter = get_string_entry(BatchReductionEntry.CanScatter, row) can_scatter_period = get_string_period( get_string_entry(BatchReductionEntry.CanScatterPeriod, row)) can_transmission = get_string_entry(BatchReductionEntry.CanTransmission, row) can_transmission_period = get_string_period( get_string_entry(BatchReductionEntry.CanScatterPeriod, row)) can_direct = get_string_entry(BatchReductionEntry.CanDirect, row) can_direct_period = get_string_period( get_string_entry(BatchReductionEntry.CanDirectPeriod, row)) output_name = get_string_entry(BatchReductionEntry.Output, row) user_file = get_string_entry(BatchReductionEntry.UserFile, row) row_entry = [sample_scatter, sample_scatter_period, sample_transmission, sample_transmission_period, sample_direct, sample_direct_period, can_scatter, can_scatter_period, can_transmission, can_transmission_period, can_direct, can_direct_period, output_name, user_file, '', ''] table_index_model = TableIndexModel(*row_entry) self._table_model.add_table_entry(index, table_index_model) def on_update_rows(self): self.update_view_from_table_model() def update_view_from_table_model(self): self._view.clear_table() self._view.hide_period_columns() for row_index, row in enumerate(self._table_model._table_entries): row_entry = [str(x) for x in row.to_list()] self._view.add_row(row_entry) self._view.change_row_color(row_state_to_colour_mapping[row.row_state], row_index + 1) self._view.set_row_tooltip(row.tool_tip, row_index + 1) if row.isMultiPeriod(): self._view.show_period_columns() self._view.remove_rows([0]) self._view.clear_selection() def on_data_changed(self, row, column, new_value, old_value): self._table_model.update_table_entry(row, column, new_value) self._view.change_row_color(row_state_to_colour_mapping[RowState.Unprocessed], row) self._view.set_row_tooltip('', row) self._beam_centre_presenter.on_update_rows() self._masking_table_presenter.on_update_rows() def on_instrument_changed(self): self._setup_instrument_specific_settings() # ---------------------------------------------------------------------------------------------- # Processing # ---------------------------------------------------------------------------------------------- def _handle_get_states(self, rows): """ Return the states for the supplied rows, calling on_processing_error for any errors which occur. """ states, errors = self.get_states(row_index=rows) for row, error in errors.items(): self.on_processing_error(row, error) return states def _plot_graph(self): """ Plot a graph if continuous output specified. """ if self._view.plot_results: if IN_MANTIDPLOT: if not graph(self.output_graph): newGraph(self.output_graph) elif not PYQT4: ax_properties = {'yscale': 'log', 'xscale': 'log'} fig, _ = get_plot_fig(ax_properties=ax_properties, window_title=self.output_graph) fig.show() self.output_fig = fig def _set_progress_bar_min_max(self, min, max): """ The progress of the progress bar is given by min / max :param min: Current value of the progress bar. :param max: The value at which the progress bar is full """ setattr(self._view, 'progress_bar_value', min) setattr(self._view, 'progress_bar_maximum', max) def _process_rows(self, rows): """ Processes a list of rows. Any errors cause the row to be coloured red. """ try: for row in rows: self._table_model.reset_row_state(row) self.update_view_from_table_model() self._view.disable_buttons() self._processing = True self.sans_logger.information("Starting processing of batch table.") states = self._handle_get_states(rows) if not states: raise Exception("No states found") self._plot_graph() self.progress = 0 self._set_progress_bar_min_max(self.progress, len(states)) save_can = self._view.save_can # MantidPlot and Workbench have different approaches to plotting output_graph = self.output_graph if PYQT4 else self.output_fig self.batch_process_runner.process_states(states, self._view.use_optimizations, self._view.output_mode, self._view.plot_results, output_graph, save_can) except Exception as e: self.on_processing_finished(None) self.sans_logger.error("Process halted due to: {}".format(str(e))) self.display_warning_box('Warning', 'Process halted', str(e)) def on_process_all_clicked(self): """ Process all entries in the table, regardless of selection. """ all_rows = range(self._table_model.get_number_of_rows()) all_rows = self._table_model.get_non_empty_rows(all_rows) if all_rows: self._process_rows(all_rows) def on_process_selected_clicked(self): """ Process selected table entries. """ selected_rows = self._view.get_selected_rows() selected_rows = self._table_model.get_non_empty_rows(selected_rows) if selected_rows: self._process_rows(selected_rows) def on_processing_error(self, row, error_msg): """ An error occurs while processing the row with index row, error_msg is displayed as a tooltip on the row. """ self.increment_progress() self._table_model.set_row_to_error(row, error_msg) self.update_view_from_table_model() def on_processing_finished(self, result): self._view.enable_buttons() self._processing = False def on_load_clicked(self): try: self._view.disable_buttons() self._processing = True self.sans_logger.information("Starting load of batch table.") selected_rows = self._get_selected_rows() selected_rows = self._table_model.get_non_empty_rows(selected_rows) states, errors = self.get_states(row_index=selected_rows) for row, error in errors.items(): self.on_processing_error(row, error) if not states: self.on_processing_finished(None) return self.progress = 0 setattr(self._view, 'progress_bar_value', self.progress) setattr(self._view, 'progress_bar_maximum', len(states)) self.batch_process_runner.load_workspaces(states) except Exception as e: self._view.enable_buttons() self.sans_logger.error("Process halted due to: {}".format(str(e))) self.display_warning_box("Warning", "Process halted", str(e)) def on_export_table_clicked(self): non_empty_rows = self.get_row_indices() if len(non_empty_rows) == 0: self.sans_logger.notice("Cannot export table as it is empty.") return # Python 2 and 3 take input in different modes for writing lists to csv files if sys.version_info[0] == 2: open_type = 'wb' else: open_type = 'w' try: self._view.disable_buttons() default_filename = self._table_model.batch_file filename = self.display_save_file_box("Save table as", default_filename, "*.csv") if filename: self.sans_logger.notice("Starting export of table.") if filename[-4:] != '.csv': filename += '.csv' with open(filename, open_type) as outfile: # Pass filewriting object rather than filename to make testing easier writer = csv.writer(outfile) self._export_table(writer, non_empty_rows) self.sans_logger.notice("Table exporting finished.") self._view.enable_buttons() except Exception as e: self._view.enable_buttons() self.sans_logger.error("Export halted due to : {}".format(str(e))) self.display_warning_box("Warning", "Export halted", str(e)) def on_multiperiod_changed(self, show_periods): if show_periods: self._view.show_period_columns() else: self._view.hide_period_columns() def display_errors(self, error, context_msg, use_error_name=False): """ Code for alerting the user to a caught error :param error: a caught exception :param context_msg: string. Text to explain what SANS was trying to do when the error occurred. e.g. 'Loading of the user file failed'. :param use_error_name: bool. If True, append type of error (e.g. RuntimeError) to context_msg :return: """ logger_msg = context_msg if use_error_name: logger_msg += " {}:".format(type(error).__name__) logger_msg += " {}" self.sans_logger.error(logger_msg.format(str(error))) self.display_warning_box('Warning', context_msg, str(error)) def display_warning_box(self, title, text, detailed_text): self._view.display_message_box(title, text, detailed_text) def display_save_file_box(self, title, default_path, file_filter): filename = self._view.display_save_file_box(title, default_path, file_filter) return filename def notify_progress(self, row, out_shift_factors, out_scale_factors): self.increment_progress() if out_scale_factors and out_shift_factors: self._table_model.set_option(row, 'MergeScale', round(out_scale_factors[0], 3)) self._table_model.set_option(row, 'MergeShift', round(out_shift_factors[0], 3)) self._table_model.set_row_to_processed(row, '') def increment_progress(self): self.progress = self.progress + 1 setattr(self._view, 'progress_bar_value', self.progress) # ---------------------------------------------------------------------------------------------- # Row manipulation # ---------------------------------------------------------------------------------------------- def num_rows(self): return self._table_model.get_number_of_rows() def on_row_inserted(self, index, row): """ Insert a row at a selected point """ row_table_index = TableIndexModel(*row) self._table_model.add_table_entry(index, row_table_index) def on_insert_row(self): """ Add an empty row to the table after the first selected row (or at the end of the table if nothing is selected). """ selected_rows = self._view.get_selected_rows() selected_row = selected_rows[0] + 1 if selected_rows else self.num_rows() empty_row = self._table_model.create_empty_row() self._table_model.add_table_entry(selected_row, empty_row) def on_erase_rows(self): """ Make all selected rows empty. """ selected_rows = self._view.get_selected_rows() empty_row = self._table_model.create_empty_row() for row in selected_rows: empty_row = TableModel.create_empty_row() self._table_model.replace_table_entries([row], [empty_row]) def on_rows_removed(self, rows): """ Remove rows from the table """ self._table_model.remove_table_entries(rows) def on_copy_rows_requested(self): selected_rows = self._view.get_selected_rows() self._clipboard = [] for row in selected_rows: data_from_table_model = self._table_model.get_table_entry(row).to_list() self._clipboard.append(data_from_table_model) def on_cut_rows_requested(self): self.on_copy_rows_requested() rows = self._view.get_selected_rows() self.on_rows_removed(rows) def on_paste_rows_requested(self): if self._clipboard: selected_rows = self._view.get_selected_rows() selected_rows = selected_rows if selected_rows else [self.num_rows()] replacement_table_index_models = [TableIndexModel(*x) for x in self._clipboard] self._table_model.replace_table_entries(selected_rows, replacement_table_index_models) def on_manage_directories(self): self._view.show_directory_manager() def on_sample_geometry_view_changed(self, show_geometry): if show_geometry: self._view.show_geometry() else: self._view.hide_geometry() def on_compatibility_unchecked(self): self.display_warning_box('Warning', 'Are you sure you want to uncheck compatibility mode?', 'Non-compatibility mode has known issues. DO NOT USE if applying bin masking' ' to event workspaces.') def get_row_indices(self): """ Gets the indices of row which are not empty. :return: a list of row indices. """ row_indices_which_are_not_empty = [] number_of_rows = self._table_model.get_number_of_rows() for row in range(number_of_rows): if not self.is_empty_row(row): row_indices_which_are_not_empty.append(row) return row_indices_which_are_not_empty def on_mask_file_add(self): """ We get the added mask file name and add it to the list of masks """ new_mask_file = self._view.get_mask_file() if not new_mask_file: return new_mask_file_full_path = FileFinder.getFullPath(new_mask_file) if not new_mask_file_full_path: return # Add the new mask file to state model mask_files = self._state_model.mask_files mask_files.append(new_mask_file) self._state_model.mask_files = mask_files # Make sure that the sub-presenters are up to date with this change self._masking_table_presenter.on_update_rows() self._settings_diagnostic_tab_presenter.on_update_rows() self._beam_centre_presenter.on_update_rows() def is_empty_row(self, row): """ Checks if a row has no entries. These rows will be ignored. :param row: the row index :return: True if the row is empty. """ return self._table_model.is_empty_row(row) def on_save_other(self): self.save_other_presenter = SaveOtherPresenter(parent_presenter=self) save_other_view = SANSSaveOtherWindow.SANSSaveOtherDialog(self._view) self.save_other_presenter.set_view(save_other_view) self.save_other_presenter.show() # def _validate_rows(self): # """ # Validation of the rows. A minimal setup requires that ScatterSample is set. # """ # # If SampleScatter is empty, then don't run the reduction. # # We allow empty rows for now, since we cannot remove them from Python. # number_of_rows = self._table_model.get_number_of_rows() # for row in range(number_of_rows): # if not self.is_empty_row(row): # sample_scatter = self._view.get_cell(row, 0) # if not sample_scatter: # raise RuntimeError("Row {} has not SampleScatter specified. Please correct this.".format(row)) # ------------------------------------------------------------------------------------------------------------------ # Controls # ------------------------------------------------------------------------------------------------------------------ def disable_controls(self): """ Disable all input fields and buttons during the execution of the reduction. """ # TODO: think about enabling and disable some controls during reduction pass def enable_controls(self): """ Enable all input fields and buttons after the execution has completed. """ # TODO: think about enabling and disable some controls during reduction pass # ---------------------------------------------------------------------------------------------- # Table Model and state population # ------------------------------------------------------------------------------------------------------------------ def _get_selected_rows(self): selected_rows = self._view.get_selected_rows() selected_rows = selected_rows if selected_rows else range(self._table_model.get_number_of_rows()) for row in selected_rows: self._table_model.reset_row_state(row) self.update_view_from_table_model() return selected_rows @log_times def get_states(self, row_index=None, file_lookup=True): """ Gathers the state information for all rows. :param row_index: if a single row is selected, then only this row is returned, else all the state for all rows is returned. :return: a list of states. """ # 1. Update the state model state_model_with_view_update = self._get_state_model_with_view_update() # 2. Update the table model table_model = self._table_model # 3. Go through each row and construct a state object states, errors = None, None if table_model and state_model_with_view_update: states, errors = create_states(state_model_with_view_update, table_model, self._view.instrument, self._facility, row_index=row_index, file_lookup=file_lookup) if errors: self.sans_logger.warning("Errors in getting states...") for _, v in errors.items(): self.sans_logger.warning("{}".format(v)) return states, errors def get_state_for_row(self, row_index, file_lookup=True): """ Creates the state for a particular row. :param row_index: the row index :return: a state if the index is valid and there is a state else None """ states, errors = self.get_states(row_index=[row_index], file_lookup=file_lookup) if states is None: self.sans_logger.warning( "There does not seem to be data for a row {}.".format(row_index)) return None if row_index in list(states.keys()): if states: return states[row_index] return None def _update_view_from_state_model(self): self._set_on_view("instrument") # Front tab view self._set_on_view("zero_error_free") self._set_on_view("save_types") self._set_on_view("compatibility_mode") self._set_on_view("merge_scale") self._set_on_view("merge_shift") self._set_on_view("merge_scale_fit") self._set_on_view("merge_shift_fit") self._set_on_view("merge_q_range_start") self._set_on_view("merge_q_range_stop") self._set_on_view("merge_max") self._set_on_view("merge_min") # Settings tab view self._set_on_view("reduction_dimensionality") self._set_on_view("reduction_mode") self._set_on_view("event_slices") self._set_on_view("event_binning") self._set_on_view("merge_mask") self._set_on_view("wavelength_step_type") self._set_on_view("wavelength_min") self._set_on_view("wavelength_max") self._set_on_view("wavelength_step") self._set_on_view("absolute_scale") self._set_on_view("z_offset") # Adjustment tab self._set_on_view("normalization_incident_monitor") self._set_on_view("normalization_interpolate") self._set_on_view("transmission_incident_monitor") self._set_on_view("transmission_interpolate") self._set_on_view("transmission_roi_files") self._set_on_view("transmission_mask_files") self._set_on_view("transmission_radius") self._set_on_view("transmission_monitor") self._set_on_view("transmission_mn_shift") self._set_on_view_transmission_fit() self._set_on_view("pixel_adjustment_det_1") self._set_on_view("pixel_adjustment_det_2") self._set_on_view("wavelength_adjustment_det_1") self._set_on_view("wavelength_adjustment_det_2") # Q tab self._set_on_view_q_rebin_string() self._set_on_view("q_xy_max") self._set_on_view("q_xy_step") self._set_on_view("q_xy_step_type") self._set_on_view("gravity_on_off") self._set_on_view("gravity_extra_length") self._set_on_view("use_q_resolution") self._set_on_view_q_resolution_aperture() self._set_on_view("q_resolution_delta_r") self._set_on_view("q_resolution_collimation_length") self._set_on_view("q_resolution_moderator_file") self._set_on_view("r_cut") self._set_on_view("w_cut") # Mask self._set_on_view("phi_limit_min") self._set_on_view("phi_limit_max") self._set_on_view("phi_limit_use_mirror") self._set_on_view("radius_limit_min") self._set_on_view("radius_limit_max") def _set_on_view_transmission_fit_sample_settings(self): # Set transmission_sample_use_fit fit_type = self._state_model.transmission_sample_fit_type use_fit = fit_type is not FitType.NoFit self._view.transmission_sample_use_fit = use_fit # Set the polynomial order for sample polynomial_order = self._state_model.transmission_sample_polynomial_order if fit_type is FitType.Polynomial else 2 # noqa self._view.transmission_sample_polynomial_order = polynomial_order # Set the fit type for the sample fit_type = fit_type if fit_type is not FitType.NoFit else FitType.Linear self._view.transmission_sample_fit_type = fit_type # Set the wavelength wavelength_min = self._state_model.transmission_sample_wavelength_min wavelength_max = self._state_model.transmission_sample_wavelength_max if wavelength_min and wavelength_max: self._view.transmission_sample_use_wavelength = True self._view.transmission_sample_wavelength_min = wavelength_min self._view.transmission_sample_wavelength_max = wavelength_max def _set_on_view_transmission_fit(self): # Steps for adding the transmission fit to the view # 1. Check if individual settings exist. If so then set the view to separate, else set them to both # 2. Apply the settings separate_settings = self._state_model.has_transmission_fit_got_separate_settings_for_sample_and_can() self._view.set_fit_selection(use_separate=separate_settings) if separate_settings: self._set_on_view_transmission_fit_sample_settings() # Set transmission_sample_can_fit fit_type_can = self._state_model.transmission_can_fit_type() use_can_fit = fit_type_can is FitType.NoFit self._view.transmission_can_use_fit = use_can_fit # Set the polynomial order for can polynomial_order_can = self._state_model.transmission_can_polynomial_order if fit_type_can is FitType.Polynomial else 2 # noqa self._view.transmission_can_polynomial_order = polynomial_order_can # Set the fit type for the can fit_type_can = fit_type_can if fit_type_can is not FitType.NoFit else FitType.Linear self.transmission_can_fit_type = fit_type_can # Set the wavelength wavelength_min = self._state_model.transmission_can_wavelength_min wavelength_max = self._state_model.transmission_can_wavelength_max if wavelength_min and wavelength_max: self._view.transmission_can_use_wavelength = True self._view.transmission_can_wavelength_min = wavelength_min self._view.transmission_can_wavelength_max = wavelength_max else: self._set_on_view_transmission_fit_sample_settings() def _set_on_view_q_resolution_aperture(self): self._set_on_view("q_resolution_source_a") self._set_on_view("q_resolution_sample_a") self._set_on_view("q_resolution_source_h") self._set_on_view("q_resolution_sample_h") self._set_on_view("q_resolution_source_w") self._set_on_view("q_resolution_sample_w") # If we have h1, h2, w1, and w2 selected then we want to select the rectangular aperture. is_rectangular = self._state_model.q_resolution_source_h and self._state_model.q_resolution_sample_h and \ self._state_model.q_resolution_source_w and self._state_model.q_resolution_sample_w # noqa self._view.set_q_resolution_shape_to_rectangular(is_rectangular) def _set_on_view_q_rebin_string(self): """ Maps the q_1d_rebin_string of the model to the q_1d_step and q_1d_step_type property of the view. """ rebin_string = self._state_model.q_1d_rebin_string # Extract the min, max and step and step type from the rebin string elements = rebin_string.split(",") # If we have three elements then we want to set only the if len(elements) == 3: step_element = float(elements[1]) step = abs(step_element) step_type = RangeStepType.Lin if step_element >= 0 else RangeStepType.Log # Set on the view self._view.q_1d_min_or_rebin_string = float(elements[0]) self._view.q_1d_max = float(elements[2]) self._view.q_1d_step = step self._view.q_1d_step_type = step_type else: # Set the rebin string self._view.q_1d_min_or_rebin_string = rebin_string self._view.q_1d_step_type = self._view.VARIABLE def _set_on_view(self, attribute_name): attribute = getattr(self._state_model, attribute_name) if attribute or isinstance(attribute, bool): # We need to be careful here. We don't want to set empty strings, or None, but we want to set boolean values. # noqa setattr(self._view, attribute_name, attribute) def _set_on_view_with_view(self, attribute_name, view): attribute = getattr(self._state_model, attribute_name) if attribute or isinstance(attribute, bool): # We need to be careful here. We don't want to set empty strings, or None, but we want to set boolean values. # noqa setattr(view, attribute_name, attribute) def _get_state_model_with_view_update(self): """ Goes through all sub presenters and update the state model based on the views. Note that at the moment we have set up the view and the model such that the name of a property must be the same in the view and the model. This can be easily changed, but it also provides a good cohesion. """ state_model = copy.deepcopy(self._state_model) # If we don't have a state model then return None if state_model is None: return state_model # Run tab view self._set_on_state_model("zero_error_free", state_model) self._set_on_state_model("save_types", state_model) self._set_on_state_model("compatibility_mode", state_model) self._set_on_state_model("merge_scale", state_model) self._set_on_state_model("merge_shift", state_model) self._set_on_state_model("merge_scale_fit", state_model) self._set_on_state_model("merge_shift_fit", state_model) self._set_on_state_model("merge_q_range_start", state_model) self._set_on_state_model("merge_q_range_stop", state_model) self._set_on_state_model("merge_mask", state_model) self._set_on_state_model("merge_max", state_model) self._set_on_state_model("merge_min", state_model) # Settings tab self._set_on_state_model("reduction_dimensionality", state_model) self._set_on_state_model("reduction_mode", state_model) self._set_on_state_model("event_slices", state_model) self._set_on_state_model("event_binning", state_model) self._set_on_state_model("wavelength_step_type", state_model) self._set_on_state_model("wavelength_min", state_model) self._set_on_state_model("wavelength_max", state_model) self._set_on_state_model("wavelength_step", state_model) self._set_on_state_model("wavelength_range", state_model) self._set_on_state_model("absolute_scale", state_model) self._set_on_state_model("z_offset", state_model) # Adjustment tab self._set_on_state_model("normalization_incident_monitor", state_model) self._set_on_state_model("normalization_interpolate", state_model) self._set_on_state_model("transmission_incident_monitor", state_model) self._set_on_state_model("transmission_interpolate", state_model) self._set_on_state_model("transmission_roi_files", state_model) self._set_on_state_model("transmission_mask_files", state_model) self._set_on_state_model("transmission_radius", state_model) self._set_on_state_model("transmission_monitor", state_model) self._set_on_state_model("transmission_mn_shift", state_model) self._set_on_state_model_transmission_fit(state_model) self._set_on_state_model("pixel_adjustment_det_1", state_model) self._set_on_state_model("pixel_adjustment_det_2", state_model) self._set_on_state_model("wavelength_adjustment_det_1", state_model) self._set_on_state_model("wavelength_adjustment_det_2", state_model) # Q tab self._set_on_state_model_q_1d_rebin_string(state_model) self._set_on_state_model("q_xy_max", state_model) self._set_on_state_model("q_xy_step", state_model) self._set_on_state_model("q_xy_step_type", state_model) self._set_on_state_model("gravity_on_off", state_model) self._set_on_state_model("gravity_extra_length", state_model) self._set_on_state_model("use_q_resolution", state_model) self._set_on_state_model("q_resolution_source_a", state_model) self._set_on_state_model("q_resolution_sample_a", state_model) self._set_on_state_model("q_resolution_source_h", state_model) self._set_on_state_model("q_resolution_sample_h", state_model) self._set_on_state_model("q_resolution_source_w", state_model) self._set_on_state_model("q_resolution_sample_w", state_model) self._set_on_state_model("q_resolution_delta_r", state_model) self._set_on_state_model("q_resolution_collimation_length", state_model) self._set_on_state_model("q_resolution_moderator_file", state_model) self._set_on_state_model("r_cut", state_model) self._set_on_state_model("w_cut", state_model) # Mask self._set_on_state_model("phi_limit_min", state_model) self._set_on_state_model("phi_limit_max", state_model) self._set_on_state_model("phi_limit_use_mirror", state_model) self._set_on_state_model("radius_limit_min", state_model) self._set_on_state_model("radius_limit_max", state_model) # Beam Centre self._beam_centre_presenter.set_on_state_model("lab_pos_1", state_model) self._beam_centre_presenter.set_on_state_model("lab_pos_2", state_model) return state_model def _set_on_state_model_transmission_fit(self, state_model): # Behaviour depends on the selection of the fit if self._view.use_same_transmission_fit_setting_for_sample_and_can(): use_fit = self._view.transmission_sample_use_fit fit_type = self._view.transmission_sample_fit_type polynomial_order = self._view.transmission_sample_polynomial_order state_model.transmission_sample_fit_type = fit_type if use_fit else FitType.NoFit state_model.transmission_can_fit_type = fit_type if use_fit else FitType.NoFit state_model.transmission_sample_polynomial_order = polynomial_order state_model.transmission_can_polynomial_order = polynomial_order # Wavelength settings if self._view.transmission_sample_use_wavelength: wavelength_min = self._view.transmission_sample_wavelength_min wavelength_max = self._view.transmission_sample_wavelength_max state_model.transmission_sample_wavelength_min = wavelength_min state_model.transmission_sample_wavelength_max = wavelength_max state_model.transmission_can_wavelength_min = wavelength_min state_model.transmission_can_wavelength_max = wavelength_max else: # Sample use_fit_sample = self._view.transmission_sample_use_fit fit_type_sample = self._view.transmission_sample_fit_type polynomial_order_sample = self._view.transmission_sample_polynomial_order state_model.transmission_sample_fit_type = fit_type_sample if use_fit_sample else FitType.NoFit state_model.transmission_sample_polynomial_order = polynomial_order_sample # Wavelength settings if self._view.transmission_sample_use_wavelength: wavelength_min = self._view.transmission_sample_wavelength_min wavelength_max = self._view.transmission_sample_wavelength_max state_model.transmission_sample_wavelength_min = wavelength_min state_model.transmission_sample_wavelength_max = wavelength_max # Can use_fit_can = self._view.transmission_can_use_fit fit_type_can = self._view.transmission_can_fit_type polynomial_order_can = self._view.transmission_can_polynomial_order state_model.transmission_can_fit_type = fit_type_can if use_fit_can else FitType.NoFit state_model.transmission_can_polynomial_order = polynomial_order_can # Wavelength settings if self._view.transmission_can_use_wavelength: wavelength_min = self._view.transmission_can_wavelength_min wavelength_max = self._view.transmission_can_wavelength_max state_model.transmission_can_wavelength_min = wavelength_min state_model.transmission_can_wavelength_max = wavelength_max def _set_on_state_model_q_1d_rebin_string(self, state_model): q_1d_step_type = self._view.q_1d_step_type # If we are dealing with a simple rebin string then the step type is None if self._view.q_1d_step_type is None: state_model.q_1d_rebin_string = self._view.q_1d_min_or_rebin_string else: q_1d_min = self._view.q_1d_min_or_rebin_string q_1d_max = self._view.q_1d_max q_1d_step = self._view.q_1d_step if q_1d_min and q_1d_max and q_1d_step and q_1d_step_type: q_1d_rebin_string = str(q_1d_min) + "," q_1d_step_type_factor = -1. if q_1d_step_type is RangeStepType.Log else 1. q_1d_rebin_string += str(q_1d_step_type_factor * q_1d_step) + "," q_1d_rebin_string += str(q_1d_max) state_model.q_1d_rebin_string = q_1d_rebin_string def _set_on_state_model(self, attribute_name, state_model): attribute = getattr(self._view, attribute_name) if attribute is not None and attribute != '': setattr(state_model, attribute_name, attribute) def get_cell_value(self, row, column): return self._view.get_cell(row=row, column=self.table_index[column], convert_to=str) def _export_table(self, filewriter, rows): """ Take the current table model, and create a comma delimited csv file :param filewriter: File object to be written to :param rows: list of indices for non-empty rows :return: Nothing """ for row in rows: table_row = self._table_model.get_table_entry(row).to_batch_list() batch_file_row = self._create_batch_entry_from_row(table_row) filewriter.writerow(batch_file_row) @staticmethod def _create_batch_entry_from_row(row): batch_file_keywords = ["sample_sans", "output_as", "sample_trans", "sample_direct_beam", "can_sans", "can_trans", "can_direct_beam", "user_file"] loop_range = min(len(row), len(batch_file_keywords)) new_row = [''] * (2 * loop_range) for i in range(loop_range): key = batch_file_keywords[i] value = row[i] new_row[2*i] = key new_row[2*i + 1] = value return new_row # ------------------------------------------------------------------------------------------------------------------ # Settings # ------------------------------------------------------------------------------------------------------------------ def _setup_instrument_specific_settings(self, instrument=None): if not instrument: instrument = self._view.instrument if instrument == SANSInstrument.NoInstrument: self._view.disable_process_buttons() else: instrument_string = get_string_for_gui_from_instrument(instrument) ConfigService["default.instrument"] = instrument_string self._view.enable_process_buttons() self._view.set_instrument_settings(instrument) self._beam_centre_presenter.on_update_instrument(instrument) self._workspace_diagnostic_presenter.set_instrument_settings(instrument)
2bd/2ba residence on the preferred ocean side of the new Waihonua condominium. This secured, pet-friendly building is in walking distance to Ala Moana Center, Ala Moana Beach Park, and Ward Village. The unit is elegantly appointed with matte-finish walnut wood flooring, mahogany-stained cabinetry, stone countertops, Bosch kitchen appliances, and motorized window shades. Two assigned parking stalls and a storage locker. Amenities include: Infinity pool, spa, BBQ pavilions, club room with full kitchen, fitness center, residents movie theater, two guest suites, and surfboard and bike storage.
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest from fairseq.data import iterators class TestIterators(unittest.TestCase): def test_counting_iterator_index(self, ref=None, itr=None): # Test the indexing functionality of CountingIterator if ref is None: assert itr is None ref = list(range(10)) itr = iterators.CountingIterator(ref) else: assert len(ref) == 10 assert itr is not None self.assertTrue(itr.has_next()) self.assertEqual(itr.n, 0) self.assertEqual(next(itr), ref[0]) self.assertEqual(itr.n, 1) self.assertEqual(next(itr), ref[1]) self.assertEqual(itr.n, 2) itr.skip(3) self.assertEqual(itr.n, 5) self.assertEqual(next(itr), ref[5]) itr.skip(2) self.assertEqual(itr.n, 8) self.assertEqual(list(itr), [ref[8], ref[9]]) self.assertFalse(itr.has_next()) def test_counting_iterator_length_mismatch(self): ref = list(range(10)) # When the underlying iterable is longer than the CountingIterator, # the remaining items in the iterable should be ignored itr = iterators.CountingIterator(ref, total=8) self.assertEqual(list(itr), ref[:8]) # When the underlying iterable is shorter than the CountingIterator, # raise an IndexError when the underlying iterable is exhausted itr = iterators.CountingIterator(ref, total=12) self.assertRaises(IndexError, list, itr) def test_counting_iterator_take(self): # Test the "take" method of CountingIterator ref = list(range(10)) itr = iterators.CountingIterator(ref) itr.take(5) self.assertEqual(len(itr), len(list(iter(itr)))) self.assertEqual(len(itr), 5) itr = iterators.CountingIterator(ref) itr.take(5) self.assertEqual(next(itr), ref[0]) self.assertEqual(next(itr), ref[1]) itr.skip(2) self.assertEqual(next(itr), ref[4]) self.assertFalse(itr.has_next()) def test_grouped_iterator(self): # test correctness x = list(range(10)) itr = iterators.GroupedIterator(x, 1) self.assertEqual(list(itr), [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]) itr = iterators.GroupedIterator(x, 4) self.assertEqual(list(itr), [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]) itr = iterators.GroupedIterator(x, 5) self.assertEqual(list(itr), [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) # test the GroupIterator also works correctly as a CountingIterator x = list(range(30)) ref = list(iterators.GroupedIterator(x, 3)) itr = iterators.GroupedIterator(x, 3) self.test_counting_iterator_index(ref, itr) def test_sharded_iterator(self): # test correctness x = list(range(10)) itr = iterators.ShardedIterator(x, num_shards=1, shard_id=0) self.assertEqual(list(itr), x) itr = iterators.ShardedIterator(x, num_shards=2, shard_id=0) self.assertEqual(list(itr), [0, 2, 4, 6, 8]) itr = iterators.ShardedIterator(x, num_shards=2, shard_id=1) self.assertEqual(list(itr), [1, 3, 5, 7, 9]) itr = iterators.ShardedIterator(x, num_shards=3, shard_id=0) self.assertEqual(list(itr), [0, 3, 6, 9]) itr = iterators.ShardedIterator(x, num_shards=3, shard_id=1) self.assertEqual(list(itr), [1, 4, 7, None]) itr = iterators.ShardedIterator(x, num_shards=3, shard_id=2) self.assertEqual(list(itr), [2, 5, 8, None]) # test CountingIterator functionality x = list(range(30)) ref = list(iterators.ShardedIterator(x, num_shards=3, shard_id=0)) itr = iterators.ShardedIterator(x, num_shards=3, shard_id=0) self.test_counting_iterator_index(ref, itr) def test_counting_iterator_buffered_iterator_take(self): ref = list(range(10)) buffered_itr = iterators.BufferedIterator(2, ref) itr = iterators.CountingIterator(buffered_itr) itr.take(5) self.assertEqual(len(itr), len(list(iter(itr)))) self.assertEqual(len(itr), 5) buffered_itr = iterators.BufferedIterator(2, ref) itr = iterators.CountingIterator(buffered_itr) itr.take(5) self.assertEqual(len(buffered_itr), 5) self.assertEqual(len(list(iter(buffered_itr))), 5) buffered_itr = iterators.BufferedIterator(2, ref) itr = iterators.CountingIterator(buffered_itr) itr.take(5) self.assertEqual(next(itr), ref[0]) self.assertEqual(next(itr), ref[1]) itr.skip(2) self.assertEqual(next(itr), ref[4]) self.assertFalse(itr.has_next()) self.assertRaises(StopIteration, next, buffered_itr) ref = list(range(4, 10)) buffered_itr = iterators.BufferedIterator(2, ref) itr = iterators.CountingIterator(buffered_itr, start=4) itr.take(5) self.assertEqual(len(itr), 5) self.assertEqual(len(buffered_itr), 1) self.assertEqual(next(itr), ref[0]) self.assertFalse(itr.has_next()) self.assertRaises(StopIteration, next, buffered_itr) if __name__ == "__main__": unittest.main()
It's that time of year again! The time of year where I think "wait, HOW long ago was I 15?" Well, this year it's TEN YEARS. TEN YEARS. Happy Enter From Behind Day, everyone! Can't grow up yet, I'm too busy having fun.
""" Indivo Views -- HealthActionPlan Message """ from django.http import HttpResponseBadRequest, HttpResponse from indivo.lib.view_decorators import marsloader, DEFAULT_ORDERBY from indivo.lib.query import FactQuery, DATE, STRING, NUMBER from indivo.models import HealthActionPlan HEALTHACTIONPLAN_FILTERS = { 'name' : ('name', STRING), 'name_type' : ('name_type', STRING), 'name_value' : ('name_value', STRING), 'name_abbrev' : ('name_abbrerv', STRING), 'planType' : ('planType', STRING), 'plannedBy' : ('plannedBy', STRING), 'datePlanned' : ('datePlanned', DATE), 'dateExpires' : ('dateExpires', DATE), 'indication' : ('indication', STRING), 'instructions' : ('instructions', STRING), 'system' : ('system', STRING), 'system_type' : ('system_type', STRING), 'system_value' : ('system_value', STRING), 'system_abbrev' : ('system_abbrerv', STRING), DEFAULT_ORDERBY : ('created_at', DATE) } HEALTHACTIONPLAN_TEMPLATE = 'reports/healthactionplan.xml' def healthactionplan_list(*args, **kwargs): """For 1:1 mapping of URLs to views. Calls _healthactionplan_list""" return _healthactionplan_list(*args, **kwargs) def carenet_healthactionplan_list(*args, **kwargs): """For 1:1 mapping of URLs to views. Calls _healthactionplan_list""" return _healthactionplan_list(*args, **kwargs) @marsloader(query_api_support=True) def _healthactionplan_list(request, group_by, date_group, aggregate_by, limit, offset, order_by, status, date_range, filters, record=None, carenet=None): q = FactQuery(HealthActionPlan, HEALTHACTIONPLAN_FILTERS, group_by, date_group, aggregate_by, limit, offset, order_by, status, date_range, filters, record, carenet) try: return q.render(HEALTHACTIONPLAN_TEMPLATE) except ValueError as e: return HttpResponseBadRequest(str(e))
Get a comprehensive and detailed analysis on various areas of your Mac. Monitoring these stats allows you to easily keep a check on your Mac's health and performance. Simply click on 'Free Memory' to optimize your Mac's memory after using RAM intensive programs. Control auto cleans, threshold levels and memory info on your menu bar! Customize your experience by turning on only the stats you wish to monitor. You can further choose to launch the app at startup, activate it with a hotkey, anchor it to the top of your screen, control its opacity, change update intervals and more!
#! /usr/bin/env python # # DEPRECATED in favor of just using the IPEDS data to avoid having to deal with # scraping PDFs. We can't automate this, and it's costing us too much time to # wrangle with this data source. # # The admissions data is loaded from PDF reports on the THECB website. # # Use pdftohtml to preprocess: # # find . -name "*.pdf" -exec sh -c 'pdftohtml -i -noframes -stdout "$1" > "$1.html"' -- {} \; # import glob import HTMLParser import os import re import sys from collections import defaultdict from decimal import Decimal from pprint import pprint from tx_highered.models import PublicAdmissions from tx_highered.thecb_importer.utils import (InstitutionFuzzyMatcher, create_or_update) class Node(object): html_parser = HTMLParser.HTMLParser() def __init__(self, line): self.data = line.strip().replace('<br>', '') self.is_empty = False self.is_number = False self.is_institution = False self.is_page_break = False self.is_row_header = False unescaped_data = self.html_parser.unescape(self.data) # Mark nodes we don't care about as empty if not self.data or 'BODY>' in self.data or 'HTML>' in self.data: self.is_empty = True # HR elements signify page breaks elif self.data == '<hr>': self.is_page_break = True # Sometimes multiple numbers appear in the same textbox. # We only need the last one since we only care about totals. elif re.match(r'^[\d,]+(\s[\d,]+)*$', self.data): self.is_number = True last_number = self.data.split()[-1].replace(',', '') self.data = int(last_number) # Institutions are the only non-numeric uppercase lines elif unescaped_data.upper() == unescaped_data: self.is_institution = True self.data = unescaped_data elif self.data in ('Total Texas', 'Top 10%', 'Enrolled, other Texas public university'): self.is_row_header = True def __repr__(self): return u'<Node: %r>' % self.data class Parser(object): def __init__(self, path): self.path = path self.data = defaultdict(dict) # Parse year from path name name = os.path.basename(path).replace('.pdf.html', '') self.year = int(name.split('_')[1]) # Store parser state self.cache = [] self.in_body = False self.institution = None self.expected_field = None def feed(self, line): node = Node(line) # print node # The body begins after the first page break if node.is_page_break: self.in_body = True self.institution = None return # Skip everything before the body if not self.in_body: return # Return if the node is empty if node.is_empty: return # Expect data after seeing an institution if node.is_institution: self.institution = node.data # If we reach the end of a row and expect data, the last field # of the row contains the value for the expected field. if node.is_row_header and self.expected_field and self.cache: institution_data = self.data[self.institution] institution_data[self.expected_field] = self.cache[-1].data self.expected_field = None self.cache = [] # Cache numbers until finding an expected value elif node.is_number: self.cache.append(node) # Set expected field from the row header if not self.institution: return if node.data == 'Total Applicants': self.expected_field = 'applied' elif node.data == 'Total Accepted': self.expected_field = 'accepted' elif node.data == 'Total Enrolled': self.expected_field = 'enrolled' def parse(self): for line in open(self.path): self.feed(line) def derive_rate(numerator, denominator): if denominator == 0 or numerator > denominator: return None else: return round(100.0 * numerator / denominator, 2) def main(root): for path in glob.glob(os.path.join(root, '*.pdf.html')): parser = Parser(path) parser.parse() matcher = InstitutionFuzzyMatcher() for institution, data in parser.data.iteritems(): attrs = dict(institution=institution, year=parser.year, **data) # Derive acceptance and enrollment rates acceptance_rate = derive_rate(data['accepted'], data['applied']) enrollment_rate = derive_rate(data['enrolled'], data['accepted']) # Create or update institution admissions for this year institution = matcher.match(institution) defaults = { 'year_type': 'fall', 'number_of_applicants': data['applied'], 'number_admitted': data['accepted'], 'number_admitted_who_enrolled': data['enrolled'], 'percent_of_applicants_admitted': acceptance_rate, 'percent_of_admitted_who_enrolled': enrollment_rate } obj, row_count = create_or_update(PublicAdmissions.objects, institution=institution, year=parser.year, defaults=defaults) if obj: print 'created %s %d admissions...' % ( institution.name, parser.year) else: print 'updated %s %d admissions...' % ( institution.name, parser.year) if __name__ == '__main__': main(sys.argv[1])
The Catholic bishops in Maryland have announced their full support for efforts to combat human trafficking, which, according to State Department estimates, results in 14,500 to 17,500 people being trafficked into the U.S. each year. “As people of faith, this grave injustice cries out for a response,” Baltimore Archbishop William E. Lori; Washington Archbishop Donald Wuerl; and Wilmington Bishop W. Francis Malooly said in a statement, “Proclaiming Liberty to Captives,” released April 3. The statement noted that Maryland – due to its Interstate 95 corridor connecting major cities, truck and rest stops along highways, and the Baltimore Washington International Thurgood Marshall Airport – is a prime location for trafficking, often referred to as modern-day slavery.
#!/usr/bin/env python from __future__ import print_function import sys, getopt import mol_io as io import react def main(argv): # Initial Input FileName = " " pro1Name = " " pro2Name = " " GeoType = "mol" Template = "template.txt" Code = "orca" Reaction = False xyz = [] atom = [] charge = 0 spin = 1 # python inputgen.py -i [input] --mol --orca --temp [template.txt] try: opts,args = getopt.getopt(argv,"hi:",['mol','xyz','temp=','orca','pro1=','pro2=','react']) except getopt.GetoptError: print("inputgen.py -i [input] --mol --orca --temp [template.txt]") for opt, arg in opts: if opt == "-h": print("inputgen.py -i [input] {--mol --orca --temp [template.txt]}") print(" -i : input name (w/o .mol/.xyz)") print(" --mol : read .mol file (default)") print(" --xyz : read .xyz file") print(" --orca : write orca input file") print(" --temp : read from specific template file (default is template.txt)") print(" --react : generate input for reaction") print(" --pro1 : name of first product") print(" --pro2 : name of second product") print(" -h : print this help") print("") sys.exit() elif opt == "-i": FileName = arg elif opt == "--mol": GeoType = "mol" elif opt == "--temp": Template = arg elif opt == "--xyz": GeoType = "xyz" elif opt == "--react": Reaction = True elif opt == "--pro1": pro1Name = arg elif opt == "--pro2": pro2Name = arg if not Reaction: # Standard input from single geo # open input file if GeoType == "mol": xyz,atom,charge,spin = io.ReadMol(FileName) elif GeoType == "xyz": xyz,atom,charge,spin = io.ReadXYZ(FileName) if Reaction: # Generate reaction geometry first xyz,atom,charge,spin = react.GenReaction(FileName,pro1Name,pro2Name) exit() print(charge) print(spin) print(atom) print(xyz) # read template with open(Template) as temp: keywords = temp.read().splitlines() print(keywords) # write input if Code == "orca": io.OrcaIn(FileName,keywords,atom,xyz,charge,spin) if __name__ == "__main__": main(sys.argv[1:])
Of course, it’s too late for that now and there’s a white circular ring on your beautiful wood table. These unsightly water rings (I call them the ghosts of drinks gone by) can be removed with the right method. The heavier the stain, and the longer it is allowed to remain, the harder the mineral build up will be to remove. Here are a few of my favorite cleaning tips (that really work!) to remove water stains fast. A water stain is a white ring or spot on the wood that doesn’t come off with normal cleaning. It is caused by minerals naturally present in the water that are left on a surface and allowed to air dry. The water evaporates and the mineral solids remain, causing the stain. Real wood that hasn’t been treated with a impervious wax, varnish or a polish are easily susceptible to water stains.
#!/usr/bin/python # -*- coding: utf-8 -*- ############################################################################ ## ## Copyright (C) 2015 Cabieces Julien ## Contact: https://github.com/troopa81/Qats ## ## This file is part of Qats. ## ## Qats is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## Qats is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with Qats. If not, see <http://www.gnu.org/licenses/>. ## ############################################################################ import sys import re import os import subprocess import pprint import CppHeaderParser # pprint.PrettyPrinter(depth=6).pprint( self.classInherits ) def remove( content, startRe, endRe ): # BUG PARSER while(True): index = content.find( startRe ) if ( index == -1 ): return content end = re.search(endRe, content[index:]).end() content = content[:index] + content[index+end+1:] class BindingGenerator: def __init__(self): self.globalEnums = {} self.f = None self.cppClass = None self.hasPublicConstructor = False self.isAbstract = False self.classInherits = {} self.inherited = ""; self.notGeneratedMethods = { "QObject" : [ "connect", "disconnect", "connect_functor", "find_children", "find_child" ] } self.notGeneratedClass = [ "QObjectData", "QObjectUserData", "QSignalBlocker", "QWidgetData" ] def findEnumFromValue( self, enumValueName ): for (className, enums) in self.globalEnums.iteritems(): for enum in enums: for enumValue in enum['values']: if enumValue['name'] == enumValueName: return ( className, enum ) return (None,None) def findEnum( self, enumName ): for (className, enums) in self.globalEnums.iteritems(): for enum in enums: if 'name' in enum and enum['name'] == enumName: return ( className, enum ) return (None,None) def treatType( self, typeName ): # BUG typeName = re.sub( r"__", r"::", typeName) if ( typeName == "ButtonRole" ): print( "typeName=" + typeName ) #pprint.PrettyPrinter(depth=6).pprint( self.globalEnums ) enumClassName, enum = self.findEnum( typeName ); if enumClassName != None and enum != None: return (enumClassName + "::" + typeName); elif typeName in self.cppClass[ 'typedefs' ][ 'public' ]: return self.cppClass['name'] + "::" + typeName else: return typeName # return true if current class inherits from QObject def inheritsQObject(self): parentClass = self.cppClass[ 'name' ]; while parentClass in self.classInherits: parentClass = self.classInherits[ parentClass ]; return parentClass == "QObject"; def generateScriptConstructor(self): # script constructor only if class is not abstract and have a public constructor if self.isAbstract or not self.hasPublicConstructor: return None constructorName = "script" + self.cppClass[ 'name' ] + "Constructor"; self.f.write("inline QScriptValue " + constructorName + "(QScriptContext *context, QScriptEngine *engine)\n"); self.f.write("{\n"); self.f.write("Q_UNUSED(context);\n"); # TODO manage parameters for constructor #for method in self.cppClass[ 'methods' ]['public']: # if method[ 'constructor' ]: # print( "coucou" ) # for iParameter in range( 0, len(method['parameters'])) : # print( "type=" + method['parameters'][ iParameter ]['type'] ); if self.inheritsQObject(): # TODO set the parent correctly. QWidget take QWidget as parent not QObject, so this need a cast # self.f.write("QObject *parent = context->argument(0).toQObject();\n"); self.f.write( self.cppClass['name'] + " *object = new " + self.cppClass['name'] + "(0);\n"); self.f.write("return engine->newQObject(object, QScriptEngine::ScriptOwnership);\n"); else: self.f.write( self.cppClass['name'] + " object;\n" ); self.f.write( "return engine->newVariant( QVariant( object ) );"); self.f.write("}\n\n"); return constructorName def generateEngineRegistration( self, scriptConstructorName ): self.f.write("static void registerToScriptEngine(QScriptEngine* engine)\n") self.f.write("{\n") for strType in [ self.cppClass[ 'name' ], self.cppClass[ 'name' ] + "*" ]: self.f.write("engine->setDefaultPrototype(qMetaTypeId<"); self.f.write( strType ); self.f.write( ">(), engine->newQObject(new " + self.cppClass['name'] + "Prototype(engine)));\n" ) self.f.write("\n") # script constructor only if class is not abstract if scriptConstructorName : self.f.write("QScriptValue ctor = engine->newFunction(" + scriptConstructorName + ");\n"); if self.inheritsQObject(): self.f.write("QScriptValue metaObject = engine->newQMetaObject(&" + self.cppClass[ 'name' ] + "::staticMetaObject" ); if scriptConstructorName : self.f.write( ", ctor" ); self.f.write( ");\n"); # even if class is abstract we need an instance in order to access specific enum self.f.write("engine->globalObject().setProperty(\"" + self.cppClass['name'] + "\", " + ( "metaObject" if self.inheritsQObject() else "ctor" ) + ");\n"); self.f.write("}\n") self.f.write("\n") def parseCppHeader( self, cppHeader, outputDir ): for className in cppHeader.classes.keys(): self.cppClass = cppHeader.classes[ className ]; # Do not generate all classes... if className in self.notGeneratedClass: continue; protoClassName = className + "Prototype" # compute if class is abstract or not self.isAbstract = False for methods in self.cppClass[ 'methods' ].values(): for method in methods: if method[ 'pure_virtual' ] : self.isAbstract = True break self.hasPublicConstructor = False for method in self.cppClass[ 'methods' ]['public']: if method['constructor']: self.hasPublicConstructor = True break print( "Generate " + protoClassName + "..." ); self.globalEnums[ className ] = self.cppClass[ 'enums' ][ 'public' ]; self.f = open( os.path.join( outputDir, protoClassName + ".h" ),'w') ## write licence self.f.write("/****************************************************************************\n"); self.f.write("**\n"); self.f.write("** Copyright (C) 2015 Cabieces Julien\n"); self.f.write("** Contact: https://github.com/troopa81/Qats\n"); self.f.write("**\n"); self.f.write("** This file is part of Qats.\n"); self.f.write("**\n"); self.f.write("** Qats is free software: you can redistribute it and/or modify\n"); self.f.write("** it under the terms of the GNU Lesser General Public License as published by\n"); self.f.write("** the Free Software Foundation, either version 3 of the License, or\n"); self.f.write("** (at your option) any later version.\n"); self.f.write("**\n"); self.f.write("** Qats is distributed in the hope that it will be useful,\n"); self.f.write("** but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); self.f.write("** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); self.f.write("** GNU Lesser General Public License for more details.\n"); self.f.write("**\n"); self.f.write("** You should have received a copy of the GNU Lesser General Public License\n"); self.f.write("** along with Qats. If not, see <http://www.gnu.org/licenses/>.\n"); self.f.write("**\n"); self.f.write("****************************************************************************/\n"); self.f.write("\n"); self.f.write("#ifndef _" + protoClassName.upper() + "_\n"); self.f.write("#define _" + protoClassName.upper() + "_\n"); # get possible inheritance self.inherited = ""; for inheritedClass in self.cppClass['inherits']: if inheritedClass['access'] == "public": # not suppose to happen with Qt # happen only for QWidget (keeps only first inherited which is QObject if self.inherited != "": print( "Error : multiple inheritance, take first inherited class" ); else: self.inherited = inheritedClass['class'] + "Prototype" self.classInherits[ className ] = inheritedClass['class']; self.f.write("\n") self.f.write("#include <QObject>\n") self.f.write("#include <QScriptable>\n") self.f.write("#include <QScriptValue>\n") self.f.write("#include <QScriptEngine>\n") self.f.write("#include <" + className + ">\n") self.f.write("\n") if self.inherited != "": self.f.write("#include \"" + self.inherited + ".h\"\n"); self.f.write("\n") scriptConstructorName = self.generateScriptConstructor(); self.f.write("namespace qats\n") self.f.write("{\n") self.f.write("\n") self.f.write("class " + protoClassName ); self.f.write( " : public " + ( self.inherited if self.inherited != "" else " QObject, public QScriptable") ) self.f.write( "\n" ); self.f.write("{\n") self.f.write("Q_OBJECT\n") self.f.write("\n") self.f.write("public:\n") self.f.write("\n") self.generateEngineRegistration( scriptConstructorName ); self.f.write(protoClassName + "(QObject* parent = 0):"+ (self.inherited if self.inherited != "" else "QObject") + "(parent){}\n") self.f.write("public slots:\n") self.f.write("\n") # public methods ... for method in self.cppClass[ 'methods' ][ 'public' ]: isStatic = method['static'] # do not treat constructor and destructor notGeneratedMethods = self.notGeneratedMethods[ self.cppClass[ 'name' ] ] if self.cppClass['name'] in self.notGeneratedMethods else [] if method['constructor'] or method['destructor'] or method['name'].startswith( "operator" ) or method[ 'name' ] in notGeneratedMethods or '<' in method['name']: continue returnType = method['rtnType'] # BUG : remove static from type if isStatic: returnType = returnType[ returnType.find( "static") + 7:] # compute return type returnType = self.treatType( returnType ) self.f.write(returnType + " " + method['name'] + "(" ) # remove weird case of default value as a type (see QWidget::grab) parameters = [] for iParameter in range( 0, len(method['parameters'])) : if "(" not in method['parameters'][ iParameter ]['type']: parameters.append( method['parameters'][ iParameter ] ) elif iParameter > 0 : del parameters[ iParameter-1 ][ 'defaultValue' ] for iParam in range(0, len(parameters)): parameter = parameters[iParam] paramType = self.treatType( parameter['type'] ) # bug in parser if ( parameter['name'] == "&" ): paramType += "&" parameter['name'] = "" if ( parameter['name'] == "" ): parameter['name'] = "param" + str(iParam) self.f.write(paramType + " " + parameter['name']) # default value if any if "defaultValue" in parameter : enumClassName, enum = self.findEnumFromValue( parameter['defaultValue'] ) self.f.write(" = "); if enumClassName != None and enum != None: self.f.write( enumClassName + "::" + parameter['defaultValue'] ); else: self.f.write(self.treatType( parameter['defaultValue'] ) ) if ( iParam < len(parameters)-1 ): self.f.write(",") self.f.write(")\n") self.f.write("{\n") if not isStatic: self.f.write(className + " *object = qscriptvalue_cast<" + className + "*>(thisObject());\n") if ( returnType != "void" ): self.f.write("return ") if isStatic: self.f.write( className + "::" ) else: self.f.write( "object->" ) self.f.write( method['name'] + "(" ); # method parameters in call ... for iParam in range(0, len(parameters)): self.f.write(parameters[iParam]['name']) if ( iParam < len(parameters)-1 ): self.f.write(",") self.f.write( ");\n" ); self.f.write("}\n") self.f.write("};\n") self.f.write("}\n") self.f.write("\n") if className not in [ "QWidget" ]: self.f.write("Q_DECLARE_METATYPE(" + className + "*)\n") self.f.write("\n") self.f.write("#endif\n"); f.close() ########################### main if len(sys.argv) != 3: print("[Usage] generateBindings <qt_include_dir> <output_dir>") sys.exit(0) qtDir = sys.argv[1] outputDir = sys.argv[2] # assume output dir is created if not os.path.exists( outputDir ): os.makedirs( outputDir ) try: #"qtbase/src/corelib/kernel/qmetaobject.h" qtFiles = [ "QtCore/qobject.h", "QtWidgets/qwidget.h", # "QtWidgets/qdialog.h", # "QtWidgets/qmessagebox.h" "QtWidgets/qabstractslider.h", "QtWidgets/qslider.h", # "qtbase/src/widgets/widgets/qlineedit.h", # "qtbase/src/widgets/kernel/qapplication.h", # "qtbase/src/widgets/itemviews/qtreeview.h", # "qtbase/src/widgets/itemviews/qabstractitemview.h", # "qtbase/src/corelib/itemmodels/qabstractitemmodel.h", # "qtbase/src/widgets/widgets/qtoolbar.h" # "qtbase/src/corelib/tools/qrect.h" # "qtbase/src/corelib/tools/qpoint.h" #"qtbase/src/corelib/itemmodels/qitemselectionmodel.h" #"qtbase/src/widgets/widgets/qabstractscrollarea.h" #"qtbase/src/corelib/kernel/qcoreapplication.h" #"qtbase/src/gui/kernel/qevent.h" # "qtbase/src/corelib/tools/qelapsedtimer.h" # "qtbase/src/corelib/kernel/qtimer.h", # "qtbase/src/widgets/widgets/qmenu.h", #"qtbase/src/widgets/widgets/qcombobox.h", #"qtbase/src/widgets/widgets/qscrollbar.h", #"qtbase/src/widgets/widgets/qframe.h", #"qtbase/src/widgets/widgets/qframe.h", #"qtbase/src/widgets/kernel/qaction.h", #"qtbase/src/corelib/io/qiodevice.h", #"qtbase/src/corelib/io/qfiledevice.h", #"qtbase/src/corelib/io/qfile.h" #"qtbase/src/widgets/widgets/qabstractbutton.h" ] generator = BindingGenerator() for qtFile in qtFiles: sourceFileName = os.path.join( qtDir, qtFile ) tmpPreprocessorFileName = "/tmp/tmpPreprocessorFile.h" # generate file without include scriptDir = os.path.abspath(os.path.dirname(__file__)); subprocess.call([ os.path.join( scriptDir, 'prepareFile.sh' ), sourceFileName]) sourceFile = open(tmpPreprocessorFileName,'r') sourceContent = sourceFile.read(); sourceFile.close() sourceContent = re.sub( r"(Q_PROPERTY.*)", r"\1;", sourceContent) # BUG PARSER sourceContent = sourceContent.replace( "Q_SLOTS", "" ); sourceContent = re.sub( r"(Q_PROPERTY.*)", r"\1;", sourceContent) sourceContent = re.sub( r"::", r"__", sourceContent) sourceContent = re.sub( r"static Q_DECL_DEPRECATED.*;", r"", sourceContent ) sourceContent = re.sub( r"Q_.*_EXPORT", r"", sourceContent ) sourceContent = re.sub( r"Q_DECLARE_FLAGS\((.*),(.*)\)", r"typedef QFlags<\2> \1;", sourceContent ) notdefs = [ "Q_COMPILER_DECLTYPE", "(Q_COMPILER_DECLTYPE", "QT_KEYPAD_NAVIGATION", "Q_OS_WINCE", "Q_WS_X11", "Q_WS_MAC", "Q_QDOC", "QT_NO_QOBJECT" ] for notdef in notdefs: sourceContent = remove( sourceContent, "#ifdef " + notdef, "#endif" ) sourceContent = remove( sourceContent, "#ifndef " + notdef, "#endif" ) sourceContent = remove( sourceContent, "#if defined " + notdef, "#endif" ) # BUG PARSER sourceContent = remove( sourceContent, "Q_SIGNALS", "public|protected|private|}" ) sourceContent = remove( sourceContent, "#if QT_DEPRECATED_SINCE", "#endif" ) sourceContent = remove( sourceContent, "Q_STATIC_ASSERT_X", ";" ) tmpFileName = "/tmp/tmpFile.h" f = open(tmpFileName,'w') f.write( sourceContent ) f.close() cppHeader = CppHeaderParser.CppHeader( tmpFileName ) generator.parseCppHeader( cppHeader, outputDir ) except CppHeaderParser.CppParseError as e: print(e) sys.exit(1)
The Apple Watch Only Costs How Much to Make? Angels vs. Venture Capitalists: How Do They Think? Want to Be Happy? Pick a Startup Model to Match Your Motivation. Is Your Business Idea Too Weird for a VC? What Is Your Company's Kentucky Derby? What's to Prevent Someone From Ripping Off Your Crowdfunding Campaign? Not Much. Achieved Your Goal? Reach for More. The Robots Are Coming. Is Your Job Safe? Does Your Comfort Zone Matter in Business? Microsoft is Giving People the Finger. Literally. Are Small-Business Owners Immoral If They Pay Low Wages? Does Your Business Need Buyer Personas? Is Boston Losing Another VC Firm to Silicon Valley? Shocker! Entrepreneurs Often Are Not CEO Material. Spooked by Self-Driving Cars? Get a Load of Daimler's Awesome Autonomous Big Rig. We Tested Chipotle and McDonald's New Delivery Services. Here's What Happened. Small Businesses Celebrating on a Tight Budget This Year. Have a Burning Business Question? Ask the Expert: David Ossip. Does Your Business Plan Answer These 6 Questions? What's Your GMT -- the Next Goal, Milestone and Task? Can Creative Breaks Boost Your Employees' Productivity? Does Your Company Need an App, a Website or Both? Business Travelers: Is Loyalty Dead? Should a Startup Ever Splurge on Logo Design? Want to Look Smart on Social Media? 5 Tips From Facebook, LinkedIn and Twitter. Become a Franchisee at Age 21? Just Ask Hailey Nault. She Pulled It Off. Is the Apple Watch Tax Deductible? The Key to Rapid Scale? Authentic Core Values. Which One of These Growth Curves Are You Following? Putting Your Business on Instagram? Here's What You Need to Know. Are Investment Advisors Worth the Investment? What Will AOL's Tim Armstrong Bring to Verizon? Want an Unstoppable Team? Try Using Manager and Peer Recognition. W-2 or 1099? Why It Pays to Classify Your Employees Correctly. How Frequently Should You Be Sending Out Your Email Newsletter? Does a College Diploma Make Someone Special? Forget Toothpaste. This Nifty Toothbrush Scrubs Teeth Clean With Nanotech. What is the True Entrepreneur's 'Difference'? To Find Out, Ask Yourself These 3 Questions. How Much Money Do You Really Need to Borrow? Have an Extra $117,000 to Spare? This Private Jet Company Wants to Take You on a Trip Around the World. Are Wellness Programs Right for Your Company? Would Your Teammates Rather Watch Paint Dry Than Attend Your Status Meeting? Skip the Coffee Meeting. Instead, Sweat to Success With Clients. Where Do You Find Your Marketing Talent? Tax Trouble? Avoid These 9 Common -- and Costly -- Mistakes. Someone Stole Your Design? 3 Ways to Fight Back. The Future of Social Is Messaging Apps, But How Do Brands Fit In? Tell Us: Should Schools Still Use Pencils and Paper? What Kind of Employee Will Always Have a Job? An Entrepreneur. Video Games Can Make You More Sociable. Or, You Know, They Could Ruin Your Brain. Want to Be Truly Valued? Create Opportunities by Connecting People. Who's Happier: Working Parents or Stay-at-Home Parents? Is the Tech Bubble Deflating? Maybe Just a Bit. When Will Tech Get Smart Enough to Stop Being 'Men's Work'? We Asked Whether Schools Should Stop Teaching With Paper and Pens. And the Reaction Was Fiery. Traveling in Europe? A New Search Engine Wants to Show You Every Transportation Option. Which Social Media Sites Make Sense for Your Business? Here's How to Decide. Art or Theft? Famous Artist Sells Instagram Shots for $100,000. Tell Us: Would You Swipe Right for a Networking Opportunity? What Matters More, the Quality or Size of Your Social Media Audience? Are You a Success Story? Why Not? Feeling the Sting of Recent Rotten Reviews on Yelp? As a Business Owner, Should You Make Your Personal Beliefs Public? Don't Be a Solopreneur. Do This Instead. Swamped? Someone Will Get That for You. Are You a Management Consultant or an Entrepreneur? What Determines the Winners and Losers in Entrepreneurship?
""" ****************** ClusterGraph Class ****************** This is a class for creating/manipulating Cluster Graphs, and performing inference over them - currently the only supported algorithm is Loopy Belief Propagation. Still, the class structure is in place for easy addition of any algorithms relying on the Cluster Graph framework. NOTE: A cluster graph is a generalization of the clique tree data structure - to generate a clique tree, you first generate a cluster graph, then simply calculate a maximum spanning tree. In other words, a clique tree can be considered as a special type of cluster graph. """ __author__ = """Nicholas Cullen <ncullen.th@dartmouth.edu>""" import numpy as np import pandas as pd import networkx as nx from pyBN.classes.cliquetree import Clique class ClusterGraph(object): """ ClusterGraph Class """ def __init__(self, bn): """ Initialize a ClusterGraph object """ self.BN = BN self.V = {} # key = cluster index, value = Cluster objects self.E = [] self.G = None self.initialize_graph(method) self.beliefs = {} # dict where key = cluster idx, value = belief cpt def initialize_graph(self): """ Initialize the structure of the cluster graph. """ # generate graph structure self.bethe() # initialize beliefs for clique in self.V.values(): clique.compute_psi() # initialize messages to 1 self.initialize_messages() def bethe(self): """ Generate Bethe cluster graph structure. """ self.V = {} self.E = [] factorization = Factorization(self.BN) prior_dict = {} for factor in factorization.f_list: # if factor is just a prior (i.e. already added as rv) if len(factor.scope) == 1: #self.V[len(self.V)] = Clique(scope=factor.scope) #self.V[len(self.V)-1].factors = [factor] prior_dict[factor.var] = factor if len(factor.scope) > 1: self.V[len(self.V)] = Clique(scope=factor.scope) self.V[len(self.V)-1].factors = [factor] # assign the factor sep_len = len(self.V) # First, add all individual random variables for rv in self.BN.V: # if rv is a prior, don't add it if rv in prior_dict.keys(): factor = prior_dict[rv] self.V[len(self.V)] = Clique(scope=factor.scope) self.V[len(self.V)-1].factors = [factor] else: self.V[len(self.V)] = Clique(scope={rv}) # create a new initial factor since it wont have one new_factor = Factor(BN=self.BN, var=rv, init_to_one=True) self.V[len(self.V)-1].factors = [new_factor] for i in range(sep_len): for j in range(sep_len,len(self.V)): if self.V[j].scope.issubset(self.V[i].scope): self.E.append((i,j)) new_G = nx.Graph() new_G.add_edges_from(self.E) self.G = new_G def initialize_messages(self): """ For each edge (i-j) in the ClusterGraph, set delta_(i-j) = 1 and set delta_(j-i) = 1. (i.e. send a message from each parent to every child where the message is a df = 1) """ for cluster in self.V: for neighbor in self.G.neighbors(cluster): self.V[cluster].send_initial_message(self.V[neighbor]) def collect_beliefs(self): self.beliefs = {} for cluster in self.V: self.V[cluster].collect_beliefs() #print('Belief ' , cluster , ' : \n', self.V[cluster].belief.cpt) self.beliefs[cluster] = self.V[cluster].belief def loopy_belief_propagation(self, target, evidence, max_iter=100): """ This is Message Passing (Loopy Belief Propagation) over a cluster graph. It is Sum-Product Belief Propagation in a cluster graph as shown in Koller p.397 Notes: 1. Definitely a problem due to normalization (prob vals way too small) 2. Need to check the scope w.r.t. messages.. all clusters should not be accumulating rv's in their scope over the course of the algorithm. """ # 1: Moralize the graph # 2: Triangluate # 3: Build a clique tree using max spanning # 4: Propagation of probabilities using message passing # creates clique tree and assigns factors, thus satisfying steps 1-3 cgraph = copy.copy(self) G = cgraph.G edge_visit_dict = dict([(i,0) for i in cgraph.E]) iteration = 0 while not cgraph.is_calibrated(): if iteration == max_iter: break if iteration % 50 == 0: print('Iteration: ' , iteration) for cluster in cgraph.V.values(): cluster.collect_beliefs() # select an edge e_idx = np.random.randint(0,len(cgraph.E)) edge_select = cgraph.E[e_idx] p_idx = np.random.randint(0,2) parent_edge = edge_select[p_idx] child_edge = edge_select[np.abs(p_idx-1)] print(parent_edge , child_edge) # send a message along that edge cgraph.V[parent_edge].send_message(cgraph.V[child_edge]) iteration += 1 print('Now Collecting Beliefs..') self.collect_beliefs() self.BN.ctree = self
To see the collection of prior postings to the list, visit the Capstone-news Archives. To post a message to all the list members, send email to capstone-news@simtk.org. Subscribe to Capstone-news by filling out the following form. You will be sent email requesting confirmation, to prevent others from gratuitously subscribing you. This is a private list, which means that the list of members is not available to non-members.
#!/usr/bin/env python from __future__ import print_function from builtins import input import sys import pmagpy.pmagplotlib as pmagplotlib import pmagpy.pmag as pmag def main(): """ NAME qqunf.py DESCRIPTION makes qq plot from input data against uniform distribution SYNTAX qqunf.py [command line options] OPTIONS -h help message -f FILE, specify file on command line """ fmt,plot='svg',0 if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit elif '-f' in sys.argv: # ask for filename ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') input=f.readlines() Data=[] for line in input: line.replace('\n','') if '\t' in line: # read in the data from standard input rec=line.split('\t') # split each line on space to get records else: rec=line.split() # split each line on space to get records Data.append(float(rec[0])) # if len(Data) >=10: QQ={'unf1':1} pmagplotlib.plot_init(QQ['unf1'],5,5) pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot else: print('you need N> 10') sys.exit() pmagplotlib.draw_figs(QQ) files={} for key in list(QQ.keys()): files[key]=key+'.'+fmt if pmagplotlib.isServer: black = '#000000' purple = '#800080' titles={} titles['eq']='Equal Area Plot' EQ = pmagplotlib.add_borders(EQ,titles,black,purple) pmagplotlib.save_plots(QQ,files) elif plot==1: files['qq']=file+'.'+fmt pmagplotlib.save_plots(QQ,files) else: ans=input(" S[a]ve to save plot, [q]uit without saving: ") if ans=="a": pmagplotlib.save_plots(QQ,files) if __name__ == "__main__": main()
Hotel Fabric Paris is free HD wallpaper. This wallpaper was upload at April 22, 2019 upload by admin in .You can download it in your computer by clicking resolution image in Download by size:. Don't forget to rate and comment if you interest with this wallpaper.
# MIT License # # Copyright (c) 2017 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # # from __future__ import absolute_import, division, print_function, unicode_literals from OSMModelData import OSMModelData # ============================================================================ # A register of classifier models implemented as a dictionary # ============================================================================ __modelClassRegistry__ = {} # global dictionary of classification models. # ================================================================================ # A meta class to automatically register model classes with __modelClassRegistry__ # ================================================================================ class ModelMetaClass(type): def __new__(cls, class_name, bases, attrs): class_obj = super(ModelMetaClass, cls).__new__(cls, class_name, bases, attrs) __modelClassRegistry__[class_name] = class_obj return class_obj # ============================================================================ # Utility functions to enumerate registered classifier model classes # ============================================================================ def get_model_class(class_name): class_obj = None if class_name in __modelClassRegistry__: class_obj = __modelClassRegistry__[class_name] return class_obj def get_model_instance(class_name, *args): return get_model_class(class_name)(*args) def get_model_method(class_name, method_name): method = None class_obj = get_model_class(class_name) if class_obj is not None: if method_name in class_obj.__dict__: method = class_obj.__dict__[method_name] return method # Returns a list of model instances (only models with postfix defined). def get_model_instances(args, log): model_instances = [] for class_name in __modelClassRegistry__: extfn = get_model_method(class_name, "model_postfix") if extfn is not None: instance = get_model_instance(class_name, args, log) model_instances.append(instance) return model_instances # ============================================================================ # This is a virtual base classification model that is inherited by # OSM classification models using "from OSMBaseModel import OSMBaseModel". # See example code in "OSMTemplate.py" and "OSMSequential.py" # ============================================================================ class OSMBaseModel(object): def __init__(self, args, log): # Shallow copies of the runtime environment. self.log = log self.args = args ##################################################################################### # # Local member functions that call virtual member functions defined # elsewhere in the object hierarchy. All functions prefixed "model_" are virtual. # ##################################################################################### # Perform the classification, this is the mainline function. def classify(self, data): self.initialize(data) self.model_write() def initialize(self, data): self.raw_data = data #The entire dataset for recursive models. self.data = OSMModelData(self.args, self.log, self, data) # create a "model-centric" view of the data. if self.args.shuffle >= 0: self.data.stratified_crossval(self.args.shuffle) # shuffle the test and training data if flag set. self.model = self.create_model() self.log.info("Begin Training %s Model", self.model_name()) self.model_train() self.log.info("End Training %s Model", self.model_name()) self.model_classification_results() self.model_training_summary() def create_model(self): if self.args.loadFilename != "noload": model = self.model_read() else: self.log.info("+++++++ Creating %s Model +++++++", self.model_name()) model = self.model_define() return model def model_arguments(self): return self.arguments ##################################################################################### # # Virtual member functions redefined elsewhere in the object hierarchy # ##################################################################################### def model_is_regression(self): return False # re-defined in OSMRegression def model_is_classifier(self): return False # re-defined in OSMClassification def model_is_unsupervised(self): return False # re-defined in OSMUnsupervised # Default for any model without graphics functions. def model_graphics(self): pass # Redefine these if model I/O is defined. def model_write(self): pass def model_read(self): return self.model_define() def model_epochs(self): return 0 def model_evaluate(self, data): return [] def model_training_summary(self): pass def model_analytics(self, data): return None
Why does Opera keep asking if it should save autofill addresses that are already saved? I'm running Opera 58.0.3135.107 (which was the latest version a few days ago). I have several names and addresses saved to autofill online forms. The addresses fill most forms correctly, but when I have Opera autofill a form, most of the time it then asks if I want it to save the address. This isn't a case of asking to save a change, this is exactly the address that Opera already has saved and which it just used to fill a form. So far as I can tell, it makes absolutely no difference if I click "yes" or click "no" or just click the X to close the question. Regardless of which I do, Opera does the same thing again, the next time I fill in a form. One other thing that seems odd is that the bar which Opera posts at the top of the screen asking if I want to save the address isn't very prominent, so sometimes I don't even notice it until later. Creating a topic here is kinda easy. CREATING a topic is kinda easy, once you figure out the weird way the page is laid out - with no explanation of what goes where. Then once you do figure out how to create a topic, it doesn't accomplish anything because the forum gatekeepers don't allow questions to be posted. So far as I can see, questions get posted only if a gatekeeper has a snide remark they can post as an answer to insult the person for having a problem with their beloved Opera. Sorry but it shouldn't take more than a couple of minutes to choose the category where you want to make your post and click on 'start new topic'. Regarding the 'first post needs moderation' policy, mentioned here, you should also have seen a message at the bottom right warning you about it. Believe me, I ignore that rule a lot. Regarding my previous reply, you made a comment about posting in the forums being something difficult and I replied saying that it's easy, simply that. That's nice, but it's still not an answer to the overall problem -- and, so far as I can tell, my question STILL has NEVER appeared in the forum. You will get an answer to your question if and when someone has one to give. What I can think of at the moment is that one of fields is different and this is causing Opera to ask you to save it again. It could also be a bad file or profile. Did you try to empty the autofill entry and add it again?
from uf90 import readfun from mpi4py import MPI import os,sys,time,re import numpy as np comm = MPI.COMM_WORLD rank = comm.rank # The process ID (integer 0-3 for 4-process run) #universe_size=comm.Get_attr(MPI.UNIVERSE_SIZE) try: soft=int(MPI.INFO_ENV.get("soft")) except: print('cant find MPI soft, using 2 cores') soft = 2 #maxprocs= int(MPI.INFO_ENV.get("maxprocs")) #if sys.argv[1] != 'ignore': ''' try: ncores = int(os.popen('echo $NCPUS').read()) except: sys.exit('MPI_DSMACC:Use a Queue') ''' ncpus = soft# int(comm.Get_attr(MPI.UNIVERSE_SIZE)) #int(os.popen('echo $NCPUS').read()) print(('ncpu rank', ncpus , rank , soft)) if ncpus <2 : ncpus = 2 #sys.exit('MPI_DSMACC needs more cores: Use a Queue') if ncpus > 130: sys.exit('I dont believe you are running DSMACC on %s cores, use a queue'%ncpus) #if (not os.path.exists('./model') & runsaved==0): sys.exit('No model file found. Please run "make kpp" followed by "make"') #filename = sys.argv[1] obs=False groups = None debug=None #'for boradcast' savelist = ['spec','rate','flux','vdot','jacsp'] for i in sys.argv[1:]: if i=='--obs': if rank==0: obs = int(tuple(open('include.obs'))[0].strip().replace('!obs:','')) print('observations being used, number of obs: ',int(obs)) elif i == '--spinup': obs = -1 print('Spinup period active') if '.h5' in i : filename = i.strip() if '--debug' in i: debug = True #print ('dsfds',__file__,os.popen('pwd').read()) try: if rank == 0: ###read args extend = True rewind = False print("\033]0; running dsmacc... \007") #### jacheader ### import h5py hf = h5py.File(filename, 'a') ids = ''.join( reversed(list(open('model_Parameters.f90').readlines() ) )).replace(' ','') ids = re.findall('ind_([\w\d]+)=(\d+)',ids) ids = dict(([key,value] for value,key in ids)) jacfile = ''.join( open('model_Jacobian.f90').readlines() ).replace(' ','') edges = re.findall('JVS\(\d+\)=Jac_FULL\((\d+),(\d+)\)\\n*JVS\(\d+\)',jacfile) edges = ['->'.join([ids[i[1]],ids[i[0]]]) for i in edges] print('edges:',len(edges)) ### end jacheader ### if not debug: os.system(' touch temp.txt && rm temp.txt') debug = '>>temp.txt' head= hf.attrs['ictime'] + '\n' + '!'.join(['%15s'%i.decode('utf-8') for i in hf['icspecs']])+ '\n' + '!'.join(['%15s'%i for i in hf['icconst']]) ############################################ ###hf.attrs['ictime']=1000 ##################### DEL print('duration' , hf.attrs['ictime']) #print (np.array(head)) np.savetxt('Init_cons.dat', hf['icruns'], fmt='%15e', delimiter='!', newline='\n', header= head,comments='') #print(os.popen('less Init_cons.dat').read()) groups = [[int(item.attrs['id']),item.name] for item in list(hf.values()) if isinstance(item, h5py.Group)] sys.stdout.flush() comm.Barrier() #print ('barrier') debug = comm.bcast(debug,root=0) groups = comm.bcast(groups,root=0) obs = comm.bcast(obs,root=0) lgroups = len(groups) #sys.stdout.flush() #print ('barrier:bcast') comm.Barrier() n=rank-1 if rank>0: while n < lgroups: g = groups[n] #set the model model='model' if '-' in g[1]: if runsaved: model='save/exec/%s/model'%(g[1].split('-')[-1]) else: description = g[1].split('-')[0] #run cmd version = os.popen('./%s 0 0 --version'%(model)).read() run ='./%s %d %d %s'%(model,int(g[0]),obs,debug) print('\n'+ run, ' of version ' , version) ; ##the actual run start = time.strftime("%s");os.system(run) wall = int(time.strftime("%s")) - int(start) #return data data = {'wall':wall,'group':g[1],'vers':version.strip(),'id':g[0]} comm.isend(data, 0,tag=n) #next task n+=(ncpus-1) else: for i in range(lgroups): print('Progress: %02d '%((float(i)/lgroups)*100.)) req = comm.recv(source=MPI.ANY_SOURCE,tag=MPI.ANY_TAG) #req.Wait() g = hf[req['group']] print('Finished' , req, '. Cleaning and Saving.') g.attrs['version'] = req['vers'] g.attrs['wall']= req['wall'] for dataset in savelist: data = readfun('Outputs/%s.%s'%(req['id'],dataset)) if data[1].shape[0] == 0: print(( 'no values found, skipping: ', dataset)) continue if dataset == 'jacsp': dataarr = ['TIME'] dataarr.extend(edges) elif dataset == 'vdot': dataarr = [ids[str(i+1)] for i in range(len(data[1][1]))] else: dataarr = data[0].split(',') print(data[1].shape,len(dataarr),dataset)#remove non/ #zero results through mask mask = np.array(data[1].sum(axis=0)) if dataset == 'spec': mask[:12] = 1. elif dataset == 'rate': #only save reaction which contain species match = re.compile(r'\b[\d\.]*(\w+)\b') fltr=set(fltr) keep = [len(set(match.findall(i))-fltr)==0 for i in dataarr] try: mask *= np.array(keep) except:None mask = np.where(mask) fltr = np.array(dataarr)[mask] g.attrs[dataset + 'head'] = ','.join(fltr) data[1] = np.squeeze(data[1][...,mask],axis = 1) print(data[1].shape,dataset) try: g[dataset] except:extend=False if not extend : g.create_dataset(dataset, data=data[1] , chunks=True,maxshape=(None,None)) else: print('already saved') #print g[dataset] #g[dataset] = g[dataset].extend(data[1]) ### if exists extend this #use lines below #g[dataset].resize((g[dataset].shape[0] + data[1].shape[0]),axis=0) #g[dataset][-data[1].shape[0]:] = data[1] ### move status bar to here !!! #print g[dataset] #print req,g.items() sys.stderr.flush() ## Catch Everything Up! sys.stdout.flush() comm.Barrier() if rank ==0 : print("\033]0; Simulation Finished \007") hf.close() print('written' , filename) except Exception as e: #if rank ==0 : # hf.close() print('Failed run',e) import traceback sys.stdout.flush() traceback.print_exc() comm.Abort()
I am too. Hoping more clarity would be there post 15th August. Hp offer is for Jio mifi device not for Jio link. I am a waiting for Jio link offer. How to get hp offer? This CPE can be unlocked??? Any1 got jio link in Pune? Spoke to a friend who is a distributor for Jio. He said only in Mumbai the pilot is happening for Jio link as of now. It will start in other places later. Now that Jio sim and Jio Mifi are available freely will this too be available to all soon. Any news or updates on the same? I am interested in going for the same. Still no news in Bangalore for the same. Yes, theoretically it will not increase the in building coverage. But practically in building coverage issue can be sorted out by VoWiFi and / or jio join, using the wifi from the connected router. 4000 is very expensive at this price not many people will go for the same 2500 was still a decent affordable price. But with 3 months jpo , Rs1500 difference is not a big amount. That unlimited 4g is surely much worth than Rs500 per month.
# # $Id: tex2libplot.py,v 1.5 2002/08/18 22:04:07 mrnolta Exp $ # # Copyright (C) 2000 Mike Nolta <mike@nolta.net> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with this program; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # # # This is just a quick and dirty converter from simple TeX strings # to libplot Hershey font strings. Basically just a lookup table. # import re import string class TeXLexer(object): re_control_sequence = re.compile(r"^\\[a-zA-Z]+[ ]?|^\\[^a-zA-Z][ ]?") def __init__(self, str): self.str = str self.len = len(str) self.pos = 0 self.token_stack = [] def get_token(self): if self.pos == self.len: return None if len(self.token_stack) > 0: return self.token_stack.pop() str = self.str[self.pos:] m = self.re_control_sequence.match(str) if m is not None: token = m.group() self.pos = self.pos + len(token) # consume trailing space if len(token) > 2 and token[-1] == ' ': token = token[:-1] else: token = str[0] self.pos = self.pos + 1 return token def put_token(self, token): self.token_stack.append(token) def peek(self): token = self.get_token() self.put_token(token) return token _common_token_dict = { r'\\': '\\', r'\$': r'$', r'\%': r'%', r'\#': r'#', r'\&': r'&', # r'\~' : r'~', r'\{': r'{', r'\}': r'}', r'\_': r'_', # r'\^' : r'^', r'~': r' ', r'\/': r'\r^', # special letters (p52) # r'\oe' : r'', # r'\OE' : r'', r'\ae': r'\ae', r'\AE': r'\AE', r'\aa': r'\oa', r'\AA': r'\oA', r'\o': r'\/o', r'\O': r'\/O', # r'\l' : r'', # r'\L' : r'', r'\ss': r'\ss', # ignore stray brackets r'{': r'', r'}': r'', } _text_token_dict = { ## punctuation (p52) r'\`': r'\`', r"\'": r"\'", r'\^': r'\^', r'\"': r'\:', r'\~': r'\~', r'\c': r'\,', # non-math symbols (p438) r'\S': r'\sc', r'\P': r'\ps', r'\dag': r'\dg', r'\ddag': r'\dd', } _math_token_dict = { r'*': r'\**', # spacing # r' ' : r'', r'\ ': r' ', r'\quad': r'\r1', # 1 em r'\qquad': r'\r1\r1', # 2 em r'\,': r'\r6', # 3/18 em # r'\>' : r'', # 4/18 em # r'\;' : r'', # 5/18 em r'\!': r'\l6', # -1/6 em # lowercase greek r'\alpha': r'\*a', r'\beta': r'\*b', r'\gamma': r'\*g', r'\delta': r'\*d', r'\epsilon': r'\*e', # r'\varepsilon' : r'', r'\zeta': r'\*z', r'\eta': r'\*y', r'\theta': r'\*h', r'\vartheta': r'\+h', r'\iota': r'\*i', r'\kappa': r'\*k', r'\lambda': r'\*l', r'\mu': r'\*m', r'\nu': r'\*n', r'\xi': r'\*c', r'\pi': r'\*p', # r'\varpi' : r'', r'\rho': r'\*r', # r'\varrho' : r'', r'\sigma': r'\*s', r'\varsigma': r'\ts', r'\tau': r'\*t', r'\upsilon': r'\*u', r'\phi': r'\*f', r'\varphi': r'\+f', r'\chi': r'\*x', r'\psi': r'\*q', r'\omega': r'\*w', # uppercase greek r'\Alpha': r'\*A', r'\Beta': r'\*B', r'\Gamma': r'\*G', r'\Delta': r'\*D', r'\Epsilon': r'\*E', r'\Zeta': r'\*Z', r'\Eta': r'\*Y', r'\Theta': r'\*H', r'\Iota': r'\*I', r'\Kappa': r'\*K', r'\Lambda': r'\*L', r'\Mu': r'\*M', r'\Nu': r'\*N', r'\Xi': r'\*C', r'\Pi': r'\*P', r'\Rho': r'\*R', r'\Sigma': r'\*S', r'\Tau': r'\*T', r'\Upsilon': r'\*U', r'\Phi': r'\*F', r'\Chi': r'\*X', r'\Psi': r'\*Q', r'\Omega': r'\*W', # miscellaneous r'\aleph': r'\Ah', r'\hbar': r'\hb', r'\ell': r'\#H0662', r'\wp': r'\wp', r'\Re': r'\Re', r'\Im': r'\Im', r'\partial': r'\pd', r'\infty': r'\if', r'\prime': r'\fm', r'\emptyset': r'\es', r'\nabla': r'\gr', r'\surd': r'\sr', # r'\top' : r'', # r'\bot' : r'', r'\|': r'\||', r'\angle': r'\/_', # r'\triangle' : r'', r'\backslash': r'\\', r'\forall': r'\fa', r'\exists': r'\te', r'\neg': r'\no', # r'\flat' : r'', # r'\natural' : r'', # r'\sharp' : r'', r'\clubsuit': r'\CL', r'\diamondsuit': r'\DI', r'\heartsuit': r'\HE', r'\spadesuit': r'\SP', r'\int': r'\is', # binary operations r'\pm': r'\+-', r'\mp': r'\-+', # r'\setminus' : r'', r'\cdot': r'\md', r'\times': r'\mu', r'\ast': r'\**', # r'\star' : r'', # r'\diamond' : r'', # r'\circ' : r'', r'\bullet': r'\bu', r'\div': r'\di', r'\cap': r'\ca', r'\cup': r'\cu', # r'\uplus' : r'', # r'\sqcap' : r'', # r'\sqcup' : r'', # r'\triangleleft' : r'', # r'\triangleright' : r'', # r'\wr' : r'', # r'\bigcirc' : r'', # r'\bigtriangleup' : r'', # r'\bigtriangledown' : r'', # r'\vee' : r'', # r'\wedge' : r'', r'\oplus': r'\c+', # r'\ominus' : r'', r'\otimes': r'\c*', # r'\oslash' : r'', r'\odot': r'\SO', r'\dagger': r'\dg', r'\ddagger': r'\dd', # r'\amalg' : r'', # relations r'\leq': r'\<=', # r'\prec' : r'', # r'\preceq' : r'', r'\ll': r'<<', r'\subset': r'\SB', # r'\subseteq' : r'', # r'\sqsubseteq' : r'', r'\in': r'\mo', # r'\vdash' : r'', # r'\smile' : r'', # r'\frown' : r'', r'\geq': r'\>=', # r'\succ' : r'', # r'\succeq' : r'', r'\gg': r'>>', r'\supset': r'\SS', # r'\supseteq' : r'', # r'\sqsupseteq' : r'', # r'\ni' : r'', # r'\dashv' : r'', r'\mid': r'|', r'\parallel': r'\||', r'\equiv': r'\==', r'\sim': r'\ap', r'\simeq': r'\~-', # r'\asymp' : r'', r'\approx': r'\~~', r'\cong': r'\=~', # r'\bowtie' : r'', r'\propto': r'\pt', # r'\models' : r'', # r'\doteq' : r'', r'\perp': r'\pp', # arrows r'\leftarrow': r'\<-', r'\Leftarrow': r'\lA', r'\rightarrow': r'\->', r'\Rightarrow': r'\rA', r'\leftrightarrow': r'\<>', r'\Leftrightarrow': r'\hA', # r'\mapsto' : r'', # r'\hookleftarrow' : r'', # r'\leftharpoonup' : r'', # r'\leftharpoondown' : r'', # r'\rightleftharpoons' : r'', # ... r'\uparrow': r'\ua', r'\Uparrow': r'\uA', r'\downarrow': r'\da', r'\Downarrow': r'\dA', # r'\updownarrow' : r'', # r'\Updownarrow' : r'', # r'\nearrow' : r'', # r'\searrow' : r'', # r'\swarrow' : r'', # r'\nwarrow' : r'', # openings r'\lbrack': r'[', r'\lbrace': r'{', r'\langle': r'\la', # r'\lfloor' : r'', # r'\lceil' : r'', # closings r'\rbrack': r']', r'\rbrace': r'}', r'\rangle': r'\ra', # r'\rfloor' : r'', # r'\rceil' : r'', # alternate names r'\ne': r'\!=', r'\neq': r'\!=', r'\le': r'\<=', r'\ge': r'\>=', r'\to': r'\->', r'\gets': r'\<-', # r'\owns' : r'', r'\land': r'\AN', r'\lor': r'\OR', r'\lnot': r'\no', r'\vert': r'|', r'\Vert': r'\||', # extensions r'\degree': r'\de', r'\deg': r'\de', r'\degr': r'\de', r'\arcdeg': r'\de', } def map_text_token(token): if _text_token_dict.has_key(token): return _text_token_dict[token] else: return _common_token_dict.get(token, token) def map_math_token(token): if _math_token_dict.has_key(token): return _math_token_dict[token] else: return _common_token_dict.get(token, token) def math_group(lexer): output = '' bracketmode = 0 while 1: token = lexer.get_token() if token is None: break if token == '{': bracketmode = 1 elif token == '}': break else: output = output + map_math_token(token) if not bracketmode: break return output font_code = [r'\f0', r'\f1', r'\f2', r'\f3'] def tex2libplot(str): output = '' mathmode = 0 font_stack = [] font = 1 lexer = TeXLexer(str) while 1: token = lexer.get_token() if token is None: break append = '' if token == '$': mathmode = not mathmode elif token == '{': font_stack.append(font) elif token == '}': old_font = font_stack.pop() if old_font != font: font = old_font append = font_code[font] elif token == r'\rm': font = 1 append = font_code[font] elif token == r'\it': font = 2 append = font_code[font] elif token == r'\bf': font = 3 append = font_code[font] elif not mathmode: append = map_text_token(token) elif token == '_': append = r'\sb' + math_group(lexer) + r'\eb' if lexer.peek() == '^': append = r'\mk' + append + r'\rt' elif token == '^': append = r'\sp' + math_group(lexer) + r'\ep' if lexer.peek() == '_': append = r'\mk' + append + r'\rt' else: append = map_math_token(token) output = output + append return output
What is your service area? How far will you drive to paint for me or give a FREE estimate? Who buys the paint? Do I have to buy it? What type of paint do you use? Am I going to get the cheap low-grade stuff that most contractors use? How much do you charge? How much does it cost? Is it by square foot? Like all contractors, because my work is service based every painting contract changes from job to job. That's why I provide FREE on location estimates in order to view the work and pin point an accurate price and make an offer to contract our services to you. Every job is different and when pricing out work I have to consider a number of factors which can make a price fluctuate. These factors include but are not limited to - Hours of labour needed, supply costs, paint, equipment or rentals required, clean up, major surface repairs, travel, insurance, ceiling heights, wall/surface space & condition, square footage, is there danger/risk involved, do your required extended services, is it just walls or do you need finish work, extra coats, undercoating, trim, ceilings, specialty products like eco-friendly caulking, or artistic work. All quotes are accurate within 10% of the final invoice. I strive to ensure our pricing reflects what the market can handle, and I am in the industry to make an honest living doing what I love as private local painter and decorator. My profit is what puts a roof over my families head, keeps food on the table, and allows for regular growth and expansion of skills and services. am a locally owned and operated small business therefore I do not carry a massive overhead, or have to pay out franchise fees like most larger companies, therefore our pricing reflects costs only relevant to your specific job. My service is very particular in nature and I take this craft very seriously, my pricing reflects my skill level, demand, and overall quality. I have found that my pricing tends to be on the mid-high to high range for Interior Painter & Decorators in Alberta. However, you can be rest assured that the quality and experience I provide to my clients matches this pricing. YES - 5 Million Liability Contractors Insurance. Do you have references? How can I see if you will do a good job? Most of our clients will refer a future client to us, that personal referral or word-of-mouth is the strongest reference we could ask for. BUT if you found out about us through an ad or online we encourage you to CHECK OUT our Facebook page for Customer Feedback and pictures with all of our work. We post as much as we can so that you can have access to current or past projects that we've worked on. Have fun! How do I pay? Do you take a deposit? What are your payment terms? What if I want to cancel or change my dates? We accept payment forms of Cash, Check, Money Order/Bank Note, and E-transfer. We do not accept Credit Cards. A deposit is required on your contract in order to book in and guarantee the dates for the project. I retain a 50% on the total amount as a CREDIT ON ACCOUNT deposit. Contracts of $1000 or less are subject to a retainer of 50-100% credit on account deposit. Refunds are processed within 10 business days of a written cancellation request in the form of a Check and mailed to the address on file. YES, we have a GST Registered BN therefore in the province of Alberta we are required to charge 5% GST on top of the total cost in every contract. Estimates are made to provide a breakdown of our cost plus a GST total at the bottom of your document. What kind of discounts can I get? Do you pay out for referrals? Do you have promotions? Occasionally I will offer a monthly or seasonal discount or special deal. Keep an eye on my social media to find what's new and if I have a "Special" happening. Unfortunately, I do not pay for referrals, I am very old fashioned in the way that I believe good business, and happy customers will breed new opportunities. If you believe I am worth the Referal to a potential client, I am very grateful that you share my name, to allow me to continue to practice my craft. How do I get ready for my brand new fresh coating of paint? Well, you have booked your dates! You've asked us to paint your space beautiful and we are so EXCITED to get in and start working through the project so that you can get your life back to normal! BUT, there are certain steps you need to take as a property owner/representative in order to ensure that our work goes smoothly and as quickly as possible. When I enter into your space I ask that you have all of your furniture moved to the centre of each room (or moved out if possible) leaving a minimum of 4 feet of room for me to work in and around while I paint. I request that hangings, pictures/artwork, shelves, light covers, curtains/blinds, nails/pins all be removed from your walls - This is so that I can do my work quickly and not get any paint splatter on your items. If you would like to keep a nail or pin in the wall so that you can re-hang any items please leave it in and we can paint up and into the nail, if you cannot get a nail out simply mark a little "X" beside it and I will remove it for you then patch the hole. I do not offer furniture moving services. Once your furniture and hangings etc have been moved, you will need to sweep, vacuum, or mop the floors. Take a clean, warm, and damp microfibre cloth and wipe down the surfaces being painted. To wash walls please use a dilute Dawn dish soap in your water solution. DO NOT USE bleaches, abrasives, or TSP. Clean your baseboards, and dust around any and all surfaces being painted. Please remove wall sconces, plugin and outlet covers, vent covers, bathroom towel/paper bars or any other wall mounts if possible. A $100 outlet/plugin removal fee is applicable if I remove your covers. With all of your items removed from the walls, and furniture put into the centre of a room we can drop sheet the surround of a space and take our plastic sheeting to cover your things which protects it from dust and paint splatter. I reserve the right to terminate any contract of which the client obligation to prepare the room where furniture moving and cleaning is not done. Your deposit is 100% forfeitable should you not have the space ready for me on the date of start. Once you've started painting, can I add things in? Or change things? What if I don't like the colour I chose? Of course you can add things or change things once we are in your space and have started. However if you want to add or change part of the contract we charge an extra $$ amount to cover the costs of these changes/add-ins. Please ask your contractor how much something cost will be prior to requesting the change/add-in. Changes or add-ins after a contract has started can be charged out at the end of a contract, and payment is due upon the completion of your 1st and initial contract. You will have to sign off on a secondary attachment contract before the extra work is done. If the contractor is unable to complete the changes/add-ins within your booked dates, there may be a secondary date booked to return and complete the changes/add-ins. This includes a change to colour. NOTE: I am in no way responsible for you liking a colour that you've chosen, I am coating specialist so my responsibility is to ensure that your paint goes onto a surface correctly. If you have further questions please ask us! Do I get to keep the extra paint from my project? What is your touch up policy? What if I see something that was missed? It is my goal to leave your project in a fully completed state and looking fabulous. However, sometimes there may be something small that shows up a day or two after your painting service has been finished. In this case I offer a FREE 7 day touch up policy, which means you can call me back within 7 days of the finish date to return and touch up anything that may have been missed. Please note, touch ups are scheduled in at my next available schedule opening, so sometimes there is a bit of a wait. IIf you do not contact me before the 7 day coverage period is done, after the time has expired, as touch up fee of $135+gst is applicable.
from django.db import models from django.contrib.contenttypes.models import ContentType from django.template.defaultfilters import slugify from exceptions import IllegalMove, SameLevelMove, WrongLevelMove slug_length = 50 class LocationBase(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(help_text='Unique identifier. May be used in URLs.', max_length=slug_length) description = models.CharField(max_length=255, blank=True) gn_name = models.CharField(max_length=100, help_text="GeoNames Name", blank=True) gn_id = models.CharField(max_length=20, help_text="GeoNames ID", blank=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) class Meta: ordering = ['name'] abstract = True def __unicode__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name)[:slug_length] super(LocationBase, self).save(*args, **kwargs) def get_kml_coordinates(self): return "%s,%s,0" % (self.longitude, self.latitude) @models.permalink def get_absolute_url(self): #import ipdb; ipdb.set_trace() contenttype = ContentType.objects.get_for_model(self).model return ('view_geoloc', [str(contenttype), str(self.id)]) def get_parents(self): if hasattr(self, 'parent'): parent = self.parent return parent.get_parents() + [parent] else: return [] def moveto_parent(self, new_parent): self._validate_move(new_parent) return self._perform_move(new_parent) def _validate_move(self, new_parent): if not hasattr(self, 'parent'): # Top level of tree, cannot move raise IllegalMove() if type(self) == type(new_parent): # Parent cannot be of same type raise SameLevelMove parent_field = self._meta.get_field_by_name('parent')[0] req_parent_type = parent_field.rel.to if req_parent_type != type(new_parent): # new_parent is wrong type for this class raise WrongLevelMove def _perform_move(self, new_parent): # Check for conflicting children and merge if they exist if hasattr(new_parent, 'children') and \ new_parent.children.filter(slug=self.slug): to_merge = new_parent.children.get(slug=self.slug) return self.merge(to_merge, self) else: # Simple move self.parent = new_parent self.save() # Update museumobjects field_changes = calc_field_changes(self) self.museumobject_set.update(**field_changes) return self @staticmethod def merge(target, old): if hasattr(old, 'children'): # Deal with all the children of old targets_children = [child.slug for child in target.children.all()] for child in old.children.all(): if child.slug in targets_children: # Need to merge match = target.children.get(slug=child.slug) LocationBase.merge(match, child) else: # Simply move child child.parent = target child.save() changes = calc_field_changes(target) child.museumobject_set.update(**changes) # now that old has no children # Actually merge the two changes = calc_field_changes(target) old.museumobject_set.update(**changes) if old.museumobject_set.exists(): raise Exception else: old.delete() return target def find_mo_field_name(element): return element._meta.concrete_model.museumobject_set.\ related.field.name def calc_field_changes(element): """ Walk up the tree of geo-locations, finding the new parents These will be set onto all the museumobjects. """ fieldname = find_mo_field_name(element) field_changes = {fieldname: element.id} if hasattr(element, 'parent'): field_changes.update( calc_field_changes(element.parent)) return field_changes class GlobalRegion(LocationBase): icon_path = models.CharField(max_length=255, blank=True, help_text="Relative path to icon") icon_title = models.CharField(max_length=255, blank=True, help_text="Icon title, displayed on browse page") class Meta(LocationBase.Meta): pass class Country(LocationBase): parent = models.ForeignKey(GlobalRegion, related_name='children', verbose_name='Global region', on_delete=models.PROTECT) class Meta(LocationBase.Meta): verbose_name_plural = 'countries' unique_together = ('parent', 'slug') class StateProvince(LocationBase): parent = models.ForeignKey(Country, related_name='children', verbose_name='Country', on_delete=models.PROTECT) class Meta(LocationBase.Meta): unique_together = ('parent', 'slug') class RegionDistrict(LocationBase): parent = models.ForeignKey(StateProvince, related_name='children', verbose_name='State/province', on_delete=models.PROTECT) class Meta(LocationBase.Meta): unique_together = ('parent', 'slug') class Locality(LocationBase): parent = models.ForeignKey(RegionDistrict, related_name='children', verbose_name='Region/district', on_delete=models.PROTECT) class Meta(LocationBase.Meta): verbose_name_plural = 'localities' unique_together = ('parent', 'slug') class Place(models.Model): country = models.CharField(max_length=30, blank=True) region = models.CharField(max_length=40, blank=True) australian_state = models.CharField(max_length=20, blank=True) name = models.CharField(max_length=150) is_corrected = models.BooleanField(default=False, help_text="Has someone manually" "moved the marker to it's correct location.") gn_name = models.CharField(max_length=100, help_text="GeoNames Name", blank=True) gn_id = models.CharField(max_length=20, help_text="GeoNames ID", blank=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) class Meta: ordering = ["id"] def __unicode__(self): return ' > '.join([self.country, self.region, self.name]) @models.permalink def get_absolute_url(self): return ('place_detail', [str(self.id)]) def get_geonames_url(self): if self.gn_id: return "http://www.geonames.org/%s" % self.gn_id else: return False def get_kml_coordinates(self): return "%s,%s,0" % (self.longitude, self.latitude) def geocode_net(self, force=False): """ Lookup the latitude and longitude of this place with GeoNames Place must be saved after use. Set `force` to re-lookup the location. Can take a few seconds to return, since this uses a network request. """ if self.gn_id and not force: return from utils import geocoders geonames = geocoders.GeoNamesWithId() place, geonameId, (lat, lng) = geonames.geocode('%s, %s' % (self.name, self.country,), exactly_one=False)[0] self.gn_name = place self.gn_id = geonameId self.latitude = lat self.longitude = lng @staticmethod def autocomplete_search_fields(): return ("country__icontains", "region__icontains", "australian_state__icontains", "name__icontains") class Region(models.Model): name = models.CharField(max_length=60, unique=True) description = models.CharField(max_length=200) def __unicode__(self): return self.name
We focus on bringing the high quality OLYMPUS FE-160 replacement battery to UK customers and desire our customers can buy their satisfying OLYMPUS batteries, the li-ion, 700.00mAh, 3.70V OLYMPUS FE-160 battery on sales will be the perfect replacement to your original OLYMPUS FE-160. We guarantee the high capacity OLYMPUS FE-160 battery with a full one-year warranty from the date of purchase, 30 days money back, if the OLYMPUS FE-160 battery have any quality problem! If you have any question or suggestion about this Battery, please Contact Us, We committed to providing the highest standard of excellent service for our clients. Buy OLYMPUS FE-160 battery and OLYMPUS FE-160 charger Together, Save UK £0.5! We focus on bringing the high quality OLYMPUS FE-160 replacement battery to UK customers and desire our customers can buy their satisfying OLYMPUS batteries, the li-ion, 620.00mAh, 3.70V OLYMPUS FE-160 battery on sales will be the perfect replacement to your original OLYMPUS FE-160. Shopping from us is safe and secure. We do not sell, rent or share information of our customers with other parties. Exceldigital.org.uk guarantee your OLYMPUS FE-160 batteries transaction will be 100% safe. 2) Do not incinerate or expose OLYMPUS FE-160 camera battery to excessive heat, which may result in an exposure. 3) Do not expose OLYMPUS FE-160 battery to water or other moist/wet substances. 4) Avoid piercing, hitting, crushing or any abuse use of the FE-160 battery. 6) Avoid short circuit of the terminals by keeping OLYMPUS FE-160 battery pack away from metal objects such as necklaces or hairpins. Shopping OLYMPUS FE-160 Digital Camera Battery On Exceldigital.org.uk. all OLYMPUS FE-160 Digital Camera Batteries sell with prices at rock bottom, secure and excellent customer service. just buy OLYMPUS FE-160 Digital Camera Battery right now, right here!
from __future__ import print_function from bokeh.client import push_session from bokeh.document import Document from bokeh.models import ( ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid, Circle, HoverTool, BoxSelectTool ) from bokeh.models.widgets import ( Select, DataTable, TableColumn, StringFormatter, NumberFormatter, StringEditor, IntEditor, NumberEditor, SelectEditor) from bokeh.models.layouts import Row, Column, WidgetBox from bokeh.sampledata.autompg2 import autompg2 as mpg class DataTables(object): def __init__(self): self.document = Document() self.manufacturer_filter = None self.model_filter = None self.transmission_filter = None self.drive_filter = None self.class_filter = None self.source = ColumnDataSource() self.update_data() self.document.add_root((self.create())) self.session = push_session(self.document) def create(self): manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) manufacturer_select = Select(title="Manufacturer:", value="All", options=["All"] + manufacturers) manufacturer_select.on_change('value', self.on_manufacturer_change) model_select = Select(title="Model:", value="All", options=["All"] + models) model_select.on_change('value', self.on_model_change) transmission_select = Select(title="Transmission:", value="All", options=["All"] + transmissions) transmission_select.on_change('value', self.on_transmission_change) drive_select = Select(title="Drive:", value="All", options=["All"] + drives) drive_select.on_change('value', self.on_drive_change) class_select = Select(title="Class:", value="All", options=["All"] + classes) class_select.on_change('value', self.on_class_change) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)), TableColumn(field="cty", title="City MPG", editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] data_table = DataTable(source=self.source, columns=columns, editable=True, width=1300) plot = Plot(title=None, x_range= DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300) # Set up x & y axis plot.add_layout(LinearAxis(), 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # Add Glyphs cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5) cty = plot.add_glyph(self.source, cty_glyph) hwy = plot.add_glyph(self.source, hwy_glyph) # Add the tools tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions=['width']) plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool) controls = WidgetBox(manufacturer_select, model_select, transmission_select, drive_select, class_select) top_panel = Row(controls, plot) layout = Column(top_panel, data_table) return layout def on_manufacturer_change(self, attr, _, value): self.manufacturer_filter = None if value == "All" else value self.update_data() def on_model_change(self, attr, _, value): self.model_filter = None if value == "All" else value self.update_data() def on_transmission_change(self, attr, _, value): self.transmission_filter = None if value == "All" else value self.update_data() def on_drive_change(self, attr, _, value): self.drive_filter = None if value == "All" else value self.update_data() def on_class_change(self, attr, _, value): self.class_filter = None if value == "All" else value self.update_data() def update_data(self): df = mpg if self.manufacturer_filter: df = df[df["manufacturer"] == self.manufacturer_filter] if self.model_filter: df = df[df["model"] == self.model_filter] if self.transmission_filter: df = df[df["trans"] == self.transmission_filter] if self.drive_filter: df = df[df["drv"] == self.drive_filter] if self.class_filter: df = df[df["class"] == self.class_filter] self.source.data = ColumnDataSource.from_df(df) def run(self, do_view=False, poll_interval=0.5): if do_view: self.session.show() self.session.loop_until_closed() if __name__ == "__main__": data_tables = DataTables() data_tables.run(True)
Re: I'm not sure about my Situation regarding my AAT level 2 studies? My direct experience comes from other industries; however I think some general truths still hold. 1) Do continue with your course. It demonstrates self-motivation and commitment. L2 also teaches gives you knowledge and skills which are needed whichever route to accounting you follow. 2) Yes; keep looking for an apprenticeship. Competence is the combination of training, skills, experience, the last of which can only be gained through actually doing the job. It may be that the apprenticeship recruitment cycle is tied into the academic year. This could mean that opportunities are a bit limited at the moment. As A-level studies are not competing for your time this year, perhaps you would be able to research this and prepare yourself for the "recruitment season"? It may also be worth trying to get any job in a medium to large business. Once you have your foot in the door you may find other opportunities for career progression within and organisation, continuing AAT at evening classes or by distance learning. One friend of mine started off in the kitchens of a media business and is now directing TV programmes. 3) Yes, you should mention your current studies. As well as demonstrating your self-motivation and discipline, one of AAT's fundamental principles is integrity; you must be straightforward and honest in all professional and business relationships. Hi. This caught me out also. The amount is refunded in cash so the bank account has to be credited (reduction in an asset). The double entry is that the Sales ledger control account needs to be debited. Unlike a credit note, which would be a credit entry in the SLCA (as it reduces the asset/ the amount owed), the cash refund does not reduce the money owed by the customer and is therefore a debit. I hope that helps. No as far as the calculations are correct you won't get marked down on the layout. Personally my layout differed from AAT because each of us has their own way how to break everything down. As far as the calculations are clearly stated and workings are correct then you'll be fine. They're mostly £35 and if you get one delivered, it basically has all the syllabus in - work through that before June and see if you think it's right for you. That means there'll be at least not too much commitment. They're honestly brilliant packs and well worth the money, I've used it and the exams I felt I best performed in I used one of their packs. If you wanted to test whether you thought you could get through the whole thing, buy the one for Management Accounts: Decision & Control, as I've found that to be the toughest module. If you wanted one to ease you in and see if you could carry on, go for Credit Management - I've found that to be a nicer module (though be aware that that is an optional choice, so you'd only be able to pick one other if you decided to try that one). If you had any other queries on anything just let me know, happy to help! Re: Rawhide PLC Professional Synoptic, any tips on securing a pass?! Hi, I'm resitting this exam (for the 2nd time) on Wednesday as well and honestly dont know how to feel about it. Going to send you a slide about the whole exam. I hope it helps! the standard cost for each metre is given of £8.20. hope it makes more sense. Re: I have transferred from the AQ2013to 2016 his is Greek to me.can someone help clarify ? First of all, we can look at the Balances. You had 20,000 litres at a cost of £25,000 on the 1st March. You can work out the cost per litre of these which is 25000/20000=£1.250 (the question asks for answers to THREE decimal places, so remember to add the extra 0 to cost per litres). Then you received 15,000 litres at a total cost of £24,000 which already tells you the cost per litre of £1.600 (24000/15000). So the balances on the right is now that you have 35,000 litres in total in your inventory and the total cost of these is £49,000. Your balance is updated. It states in the question that the company uses FIFO. So we need to issue 25,000 litres using First In First Out. So we will be using the oldest inventory and working downwards. Now, we only need 5,000 litres to get the 25,000 litres we want to issue. So we take 5,000 litres from the next load of inventory. 5,000 litres x £1.600 = £8000. The total cost of the issue is £25,000 + £8,000 = £33,000. We can place that answer under the Total cost in the issues. Now calculate £33,000/25,0000 litres = £1.320 cost per litre (remember its THREE decimal places in this question). Then you are left with 10,000 litres in your balance which you have correctly entered, and £49,000-£33,000 issues leaves £16,000 closing inventory in your balance at 15th March. For LIFO, work from the 10th March inventory upwards to the 1st March. For AVCO, divide your average latest balance (49,000/35,000) = £1.400 per litre, then you'd calculate 25,000 issues x £1.400 cost per litre = £35,000 cost of issue. Then the closing inventory would be £49,000 (latest balance) - AVCO issue = £14,000 closing balance for AVCO.
from django.contrib.auth.decorators import login_required from django.shortcuts import render_to_response from django.utils.decorators import decorator_from_middleware from facebook.djangofb import FacebookMiddleware import facebook.djangofb as facebook from django.http import HttpResponse from django.http import HttpResponseBadRequest from django.http import HttpResponseRedirect from django.template import RequestContext import decorators import logging import os import util import models import files import uuid import amazonDevPayClient from google.appengine.ext.db import djangoforms from google.appengine.ext import db from registration.forms import RegistrationForm from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm, PasswordChangeForm from django.conf import settings from django.http import HttpResponseRedirect import httplib devpay_client = amazonDevPayClient.AmazonDevPayClient(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY, settings.AWS_PRODUCT_TOKEN) @decorator_from_middleware(FacebookMiddleware) #@facebook.require_login() @facebook.require_login(next="http://www.littleshoot.org/publish") def freeForm(request): fbId = str(request.facebook.uid) logging.info("Facebook ID: %s", fbId) policyFile = devpay_client.policy(settings.BASE_URI) policyFileSignature = devpay_client.signedPolicy(policyFile) #if userToken is None: return render_to_response('freeUploadForm.html', {'base64_policy_file' : policyFile, 'policy_file_signature' : policyFileSignature, 'aws_access_key_id' : settings.AWS_ACCESS_KEY_ID, 'fbId' : fbId, 'baseUrl' : settings.BASE_URI}, context_instance=RequestContext(request)) #@decorator_from_middleware(FacebookMiddleware) #@facebook.require_login() def uploadSuccess(request): logging.info('Handling upload success: %s', request.REQUEST.items()) bucket = request.REQUEST.get('bucket') key = request.REQUEST.get('key') etag = request.REQUEST.get('etag') baseUri = bucket + '.s3.amazonaws.com' conn = httplib.HTTPConnection(baseUri) conn.request("HEAD", "/" + key) res = conn.getresponse() if res.status != 200: # We're responding to a callback from Amazon here, so we don't need # to write anything intelligible. logging.info("Unexpected response from S3: %s", res.status) return HttpResponse() logging.info("Status, Reason: %s, %s", res.status, res.reason) logging.info("Headers: %s", res.getheaders()) size = res.getheader("Content-Length") logging.info("Content-Length: %s", size) requestCopy = request.GET.copy() requestCopy.update({'size': size}) # See: http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1963&categoryID=117 uri = "urn:etag:" + etag requestCopy.update({'uri': uri}) requestCopy.update({'etag': etag}) # Here's the response: # Got redirect from Amazon with [(u'etag', u'"2b63da5eb9f0e5d5a76ce4c34315843d"'), (u'fbId', u'1014879'), (u'bucket', u'littleshoot_test'), (u'key', u'user/1014879/files/build.bash'), (u'title', u'build.bash')] return files.publishFileBase(requestCopy, False) #return HttpResponse('Got redirect from Amazon with %s' % (request.REQUEST.items())) #return HttpResponseRedirect('uploadMapped.html') @decorator_from_middleware(FacebookMiddleware) @facebook.require_login() def uploadForm(request): #if request.user.is_authenticated(): #logging.info('User is authenticated!') #logging.info('User is %s', request.user.username) fbId = str(request.facebook.uid) logging.info("Facebook ID: ", fbId) try: userToken = request.user.amazonDevPayUserToken except AttributeError, e: logging.error("An exception was caught: " + str(e)) policyFile = devpay_client.policy() policyFileSignature = devpay_client.signedPolicy(policyFile) #if userToken is None: return render_to_response('purchaseDevPay.html', {'base64_policy_file' : policyFile, 'policy_file_signature' : policyFileSignature, 'aws_access_key_id' : settings.AWS_ACCESS_KEY_ID, 'fbId' : fbId, 'baseUri' : settings.BASE_URI}, context_instance=RequestContext(request)) """ else: devPayPolicyFile = devpay_client.devPayPolicy(userToken) devPayPolicyFileSignature = devpay_client.signedPolicy(devPayPolicyFile) logging.info('Straight sig: %s', policyFileSignature) logging.info('DevPay sig: %s', devPayPolicyFileSignature) return render_to_response('publisherUploadForm.html', {'base64_policy_file' : policyFile, 'policy_file_signature' : policyFileSignature, 'devpay_base64_policy_file' : devPayPolicyFile, 'devpay_policy_file_signature' : devPayPolicyFileSignature, 'aws_access_key_id' : settings.AWS_ACCESS_KEY_ID}, context_instance=RequestContext(request)) else: logging.info("User is not authenticated!!") loginForm = AuthenticationForm(request) registrationForm = RegistrationForm() logging.info("Rendering loginOrRegister") return render_to_response('customRegistration/loginOrRegister.html', {'loginForm' : loginForm, 'registrationForm': registrationForm }, context_instance=RequestContext(request)) """ """ Documentation from Amazon: Once the application has the activation key and product code, it looks up the product token associated with the product code. The application then makes a signed request to the License Service action ActivateHostedProduct. The request must include the product token for the customer and the customer's activation key. The response includes the user token for the customer. """ @decorators.activationKeyRequired @decorators.productCodeRequired def activate(request): logging.info("Handling DevPay activate request: %s", request.REQUEST.items()) logging.info("Host is: %s", request.get_host()) logging.info('Cookies on DevPay callback: %s', request.COOKIES) facebookId = request.COOKIES.get('facebookId') logging.info('Facebook ID: %s', facebookId) #logging.info(request.META['SERVER_NAME']) activationKey = request.REQUEST.get('ActivationKey') # We only have a single product for now, so we don't need to look anything # up based on the product code. #productCode = request.REQUEST.get('ProductCode') response = devpay_client.activateHostedProduct(activationKey) #logging.info("Activated hosted product response: %s", dir(response)) result = response.activateHostedProductResult #logging.info("Activated hosted product result: %s", dir(result)) userToken = result.userToken persistentIdentifier = result.persistentIdentifier logging.info('User token: %s', userToken) logging.info('Persistent Identifier: %s', persistentIdentifier) urlBase = "http://" + request.get_host() + "/amazonDevPay" if request.user.is_authenticated(): logging.info('User is authenticated!') logging.info('User is %s', request.user.username) request.user.amazonDevPayUserToken = userToken request.user.amazonDevPayPersistentIdentifier = persistentIdentifier # We also need to create a bucket for the user. request.user.put() # We redirect to a page that will get rid of the separate Amazon frame. #return HttpResponse('Activation Successful!') # We just use the server name in case we're running from a staging # server, for example. finalUrl = urlBase + "Purchase"; return render_to_response('frameBuster.html', {'frameUrl' : finalUrl}) else: finalUrl = urlBase + "Error"; return render_to_response('frameBuster.html', {'frameUrl' : finalUrl}) @decorator_from_middleware(FacebookMiddleware) @facebook.require_login() #@facebook.require_login(next="http://www.littleshoot.org/publish") def listS3Files(request): logging.info("Handling listS3Files request: %s", request.REQUEST.items()) logging.info('Cookies on list files: %s', request.COOKIES) fbId = str(request.facebook.uid) json = devpay_client.listS3FilesForId(fbId) return HttpResponse(json, mimetype='application/json; charset=utf-8') @decorator_from_middleware(FacebookMiddleware) @facebook.require_login() #@facebook.require_login(next="http://www.littleshoot.org/publish") def listS3FilesForId(request): userId = request.REQUEST.get('userId') json = devpay_client.listS3FilesForId(userId) return HttpResponse(json, mimetype='application/json; charset=utf-8')
When I walked out of the house this morning, I was armed with more than just the fuzzy goodness of my favorite sweater (but seriously: this thing has reindeer on it) -- I was clothed in peace. As a worrier, I tend to worry about oh, I don't know, everything. Big things, of course, like what if I can't find a job once I graduate from college, or what if my house burns down? But small things, too, like worries about my eating habits, homework assignments, job. Ridiculous, petty things. For a long time my mother and others told me that worrying was a sin. That didn't sit too well with me. How was worrying a sin? What was I doing wrong to myself, to others? As far as I was concerned, I was just anxious. As it turns out, worry actually harms my relationship with Christ. Someone who is webbed in worry is not walking deeply with the Lord. That's kind of a punch in the face, a wake up call to someone like me - how can I say I really know Jesus if I'm always eaten up with doubt? I'm not always keen on speaking up in class. Whether this is common for most writers, I don't know, but it is for me. So I was a little reluctant to take an Ethics class this semester. How was I going to articulate my beliefs about the death penalty, when I wasn't even sure what my beliefs were to begin with? It was a little unnerving. But God has been singing peace over me this week, and it has been wonderful. None of my worries about my Ethics class came true, and what was more, I felt so relieved to not have spent my entire weekend ruminating about it. Worry wastes a lot of time and energy! Instead, I spent that time talking to God throughout my day, fellowshipping with Him. It felt natural, and I definitely didn't miss the anxiety. God is not just the God of refuge in our most intense storms. He is here through it all, beside us in whatever we are experiencing, whatever life has for us. Remember His presence in your daily life, because He wants to fight for you. All you have to do is be still.
#!/usr/bin/env python # # ELBE - Debian Based Embedded Rootfilesystem Builder # Copyright (C) 2013 Linutronix GmbH # # This file is part of ELBE. # # ELBE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ELBE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ELBE. If not, see <http://www.gnu.org/licenses/>. import sys from elbepack.treeutils import etree from optparse import OptionParser def run_command( argv ): oparser = OptionParser( usage="usage: %prog setcdrom <xmlfile> <cdrom>") (opt,args) = oparser.parse_args(argv) if len(args) != 2: print "Wrong number of arguments" oparser.print_help() sys.exit(20) try: xml = etree( args[0] ) except: print "Error reading xml file!" sys.exit(20) mirror = xml.node("project/mirror") mirror.clear() cdrom = mirror.ensure_child("cdrom") cdrom.set_text( args[1] ) try: xml.write( args[0] ) except: print "Unable to write new xml file" sys.exit(20)
You’ve read the book. You’ve started the program. Now you need some feedback. We can help. Our strength coaching services are for those lifters who are looking for help with their form and technique. We offer 60 minute sessions. During this time, we can work on 2-3 lifts, depending on your needs. Most often, we focus on the squat, press and deadlift. If you would like help with the bench or power clean, we can always schedule a second visit. These sessions can be scheduled during the week or weekend. Price for one person for a 60 minute session is $120. Price for two people for a 60 minute session is $200. Contact us for group rates. Our One Day Clinic is a comprehensive tutorial on 4 lifts of your choice. We will review and cover proper technique and performance of each lift, but this is a workout. We will go heavy enough to find errors in your form. Scheduling is by appointment only. Please allow for up to two hours to get through all 4 exercises. Our One Day Clinics are ONLY scheduled on the weekends, Saturday afternoons from 11:30-1:30 or 12-2pm or Sunday from 12-2pm. We do not schedule clinics during the week. Price for one person is $225. Price for two people for a clinic is $376. Contact us for group rates. Fill this out and we’ll contact you right away! Do you have questions about getting started?
import os import re import sys import ssl import time import signal import socket import commands import optparse import datetime import cPickle as pickle import stomp from dq2.common import log as logging from config import panda_config from brokerage.SiteMapper import SiteMapper from dataservice import DataServiceUtils from dataservice.DDMHandler import DDMHandler import yaml import logging logging.basicConfig(level = logging.DEBUG) # logger from pandalogger.PandaLogger import PandaLogger _logger = PandaLogger().getLogger('datasetCallbackListener') # keep PID pidFile = '%s/dataset_callback_listener.pid' % panda_config.logdir # overall timeout value overallTimeout = 60 * 59 # expiration time expirationTime = datetime.datetime.utcnow() + datetime.timedelta(minutes=overallTimeout) # kill whole process def catch_sig(sig, frame): try: os.remove(pidFile) except: pass # kill _logger.debug('terminating ...') commands.getoutput('kill -9 -- -%s' % os.getpgrp()) # exit sys.exit(0) # callback listener class DatasetCallbackListener(stomp.ConnectionListener): def __init__(self,conn,tb,sm,subscription_id): # connection self.conn = conn # task buffer self.taskBuffer = tb # site mapper self.siteMapper = sm # subscription ID self.subscription_id = subscription_id def on_error(self,headers,body): _logger.error("on_error : %s" % headers['message']) def on_disconnected(self,headers,body): _logger.error("on_disconnected : %s" % headers['message']) def on_message(self, headers, message): try: dsn = 'UNKNOWN' # send ack id = headers['message-id'] #self.conn.ack(id,self.subscription_id) # convert message form str to dict messageDict = yaml.load(message) # check event type if not messageDict['event_type'] in ['datasetlock_ok']: _logger.debug('%s skip' % messageDict['event_type']) return _logger.debug('%s start' % messageDict['event_type']) messageObj = messageDict['payload'] # only for _dis or _sub dsn = messageObj['name'] if (re.search('_dis\d+$',dsn) == None) and (re.search('_sub\d+$',dsn) == None): _logger.debug('%s is not _dis or _sub dataset, skip' % dsn) return # take action scope = messageObj['scope'] site = messageObj['rse'] _logger.debug('%s site=%s type=%s' % (dsn, site, messageDict['event_type'])) thr = DDMHandler(self.taskBuffer,None,site,dsn,scope) thr.start() thr.join() _logger.debug('done %s' % dsn) except: errtype,errvalue = sys.exc_info()[:2] _logger.error("on_message : %s %s" % (errtype,errvalue)) # main def main(backGround=False): _logger.debug('starting ...') # register signal handler signal.signal(signal.SIGINT, catch_sig) signal.signal(signal.SIGHUP, catch_sig) signal.signal(signal.SIGTERM,catch_sig) signal.signal(signal.SIGALRM,catch_sig) signal.alarm(overallTimeout) # forking pid = os.fork() if pid != 0: # watch child process os.wait() time.sleep(1) else: # main loop from taskbuffer.TaskBuffer import taskBuffer # check certificate certName = '%s/pandasv1_usercert.pem' %panda_config.certdir keyName = '%s/pandasv1_userkey.pem' %panda_config.certdir #certName = '/etc/grid-security/hostcert.pem' _logger.debug('checking certificate {0}'.format(certName)) certOK,certMsg = DataServiceUtils.checkCertificate(certName) if not certOK: _logger.error('bad certificate : {0}'.format(certMsg)) # initialize cx_Oracle using dummy connection from taskbuffer.Initializer import initializer initializer.init() # instantiate TB taskBuffer.init(panda_config.dbhost,panda_config.dbpasswd,nDBConnection=1) # instantiate sitemapper siteMapper = SiteMapper(taskBuffer) # ActiveMQ params queue = '/queue/Consumer.panda.rucio.events' ssl_opts = {'use_ssl' : True, 'ssl_version' : ssl.PROTOCOL_TLSv1, 'ssl_cert_file' : certName, 'ssl_key_file' : keyName} # resolve multiple brokers brokerList = socket.gethostbyname_ex('atlas-mb.cern.ch')[-1] # set listener connList = [] for tmpBroker in brokerList: try: clientid = 'PANDA-' + socket.getfqdn() + '-' + tmpBroker subscription_id = 'panda-server-consumer' _logger.debug('setting listener %s to broker %s' % (clientid, tmpBroker)) conn = stomp.Connection(host_and_ports = [(tmpBroker, 61023)], **ssl_opts) connList.append(conn) except: errtype,errvalue = sys.exc_info()[:2] _logger.error("failed to connect to %s : %s %s" % (tmpBroker,errtype,errvalue)) catch_sig(None,None) while True: for conn in connList: try: if not conn.is_connected(): conn.set_listener('DatasetCallbackListener', DatasetCallbackListener(conn,taskBuffer,siteMapper, subscription_id)) conn.start() conn.connect(headers = {'client-id': clientid}) conn.subscribe(destination=queue, id=subscription_id, ack='auto') _logger.debug('listener %s is up and running' % clientid) except: errtype,errvalue = sys.exc_info()[:2] _logger.error("failed to set listener on %s : %s %s" % (tmpBroker,errtype,errvalue)) catch_sig(None,None) time.sleep(5) # entry if __name__ == "__main__": optP = optparse.OptionParser(conflict_handler="resolve") options,args = optP.parse_args() try: # time limit timeLimit = datetime.datetime.utcnow() - datetime.timedelta(seconds=overallTimeout-180) # get process list scriptName = sys.argv[0] out = commands.getoutput('env TZ=UTC ps axo user,pid,lstart,args | grep %s' % scriptName) for line in out.split('\n'): items = line.split() # owned process if not items[0] in ['sm','atlpan','pansrv','root']: # ['os.getlogin()']: doesn't work in cron continue # look for python if re.search('python',line) == None: continue # PID pid = items[1] # start time timeM = re.search('(\S+\s+\d+ \d+:\d+:\d+ \d+)',line) startTime = datetime.datetime(*time.strptime(timeM.group(1),'%b %d %H:%M:%S %Y')[:6]) # kill old process if startTime < timeLimit: _logger.debug("old process : %s %s" % (pid,startTime)) _logger.debug(line) commands.getoutput('kill -9 %s' % pid) except: errtype,errvalue = sys.exc_info()[:2] _logger.error("kill process : %s %s" % (errtype,errvalue)) # main loop main()
The blog post of Nursery Single Wardrobe was uploaded on September 21, 2018 at 12:16 pm. It is published on the Wardrobe category. Nursery Single Wardrobe is tagged with Nursery Single Wardrobe, Nursery, Single, Wardrobe.. Tips on picking a backyard counter readymade. Furthermore, for anyone of you who wish to obtain a park counter, seek out costs to accommodate the budget-you have and desires. In deciding the price is a consideration how often the minimalist garden bench you use, along with the budget, it must be relied. Alter the table and chair models' size together with design and the measurement of one's backyard. Selecting furniture for outdoor tricky, not just any Nursery Single Wardrobe could be positioned on yard or the rooftop. In just a small amount of time the temperature will rapidly damages the seat if any. Grass bedrooms are utilized generally made of lumber, bamboo, material, a plastic, and rattan. This type of content is extremely difficult to determine whether or not in terms of preservation. As an example made from iron and wood, shouldn't be exposed to rainfall or sunshine specifically. As the material is simply damaged. Seats are constructed of metal wherever possible, offered the nature of easily corroded then a painting have to be performed every certain time frame, eliminated. As it is today choosing a Nursery Single Wardrobe is becoming an important the main design of the playground. In addition to performance as a couch, this can be the point of view of the playground when not inuse. Numerous models of yard beds in many cases are located on the marketplace. But the selection of mix and straightforward layout with all the playground is the selection that is greatest.
import requests from requests.auth import HTTPBasicAuth import json from requests_futures.sessions import FuturesSession from .promise import Promise class Client: def __init__(self, base_url, api_key_id=None, api_key_secret=None, disable_async=False): self.base_url = base_url if api_key_id is not None: self.auth = HTTPBasicAuth(api_key_id, api_key_secret) else: self.auth = None if disable_async: self.session = requests.Session() else: self.session = FuturesSession() self.session.headers.update({ 'content-type': 'application/json' }) def request(self, method, path, data=None): if data is not None: data = json.dumps(data) res = self.session.request(method, self.base_url + path, data=data, auth=self.auth) def raise_on_error_response(res): res.raise_for_status() return res return Promise.resolve(res).then(raise_on_error_response) def add_notebook(self, title): data = { 'data': { 'type': 'notebooks', 'attributes': {'title': title}, }, } promise = self.request('post', '/api/v2/notebooks', data) return promise.then(lambda res: Notebook(self, res.json()['data']['id'])) class Notebook: def __init__(self, client, notebook_id): self.client = client self.id = notebook_id def update(self, title=None, pinned=None, progress=None): """Updates the attributes of this notebook. Args: title (str): Notebook title pinned (bool): Set to True to protect notebook against deletion progress (float): Notebook progress (from 0.0 to 1.0) """ attrs = {} if title is not None: attrs['title'] = title if pinned is not None: attrs['pinned'] = pinned if progress is not None: attrs['progress'] = progress data = { 'data': { 'id': self.id, 'type': 'notebooks', 'attributes': attrs, }, } self.client.request('patch', '/api/v2/notebooks/' + self.id, data) def set_title(self, title): self.update(title=title) def set_pinned(self, pinned): self.update(pinned=pinned) def set_progress(self, progress): self.update(progress=progress) def add_tag(self, name): data = { 'data': { 'type': 'tags', 'attributes': {'name': name}, 'relationships': { 'notebook': { 'data': {'type': 'notebooks', 'id': self.id}, }, }, }, } promise = self.client.request('post', '/api/v2/tags', data) return promise.then(lambda res: Tag(self, res.json()['data']['id'])) def add_frame(self, title, bounds=None): data = { 'data': { 'type': 'frames', 'attributes': {'title': title}, 'relationships': { 'notebook': { 'data': {'type': 'notebooks', 'id': self.id}, }, }, }, } if bounds is not None: data['data']['attributes'].update(bounds) promise = self.client.request('post', '/api/v2/frames', data) return promise.then(lambda res: Frame(self.client, res.json()['data']['id'])) class Tag: def __init__(self, client, tag_id): self.client = client self.id = tag_id class Frame: def __init__(self, client, frame_id): self.client = client self.id = frame_id def update(self, title=None, type=None, content=None): attrs = {} if title is not None: attrs['title'] = title if type is not None: attrs['type'] = type if content is not None: attrs['content'] = content data = { 'data': { 'id': self.id, 'type': 'frames', 'attributes': attrs, }, } self.client.request('patch', '/api/v2/frames/' + self.id, data) def set_title(self, title): self.update(title=title) def set_content(self, type, content): self.update(type=type, content=content) def vega(self, spec): self.set_content('vega', {'body': spec}) def vegalite(self, spec): self.set_content('vegalite', {'body': spec}) def plotly(self, fig): self.set_content('plotly', fig) def text(self, message): self.set_content('text', {'body': message}) def html(self, html): self.set_content('html', {'body': html}) def progress(self, current_value, max_value): percentage = min(100 * current_value / max_value, 100) html = """<div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="{percentage:0.2f}" aria-valuemin="0" aria-valuemax="100" style="width: {percentage:0.2f}%; min-width: 40px;" > {percentage:0.2f}% </div> </div>""".format(percentage=percentage) self.html(html) def line_graph(self, xss, yss, series_names=None, x_title=None, y_title=None, y_axis_min=None, y_axis_max=None): if not isinstance(xss[0], list): xss = [xss] * len(yss) show_legend = True if series_names is None: show_legend = False series_names = ['series_{:03d}'.format(i) for i in range(len(xss))] min_x = float('inf') max_x = -float('inf') min_y = float('inf') max_y = -float('inf') tables = [] marks = [] for i, xs in enumerate(xss): marks.append({ 'type': 'line', 'from': {'data': 'table_{:03d}'.format(i)}, 'properties': { 'enter': { 'x': {'scale': 'x', 'field': 'x'}, 'y': {'scale': 'y', 'field': 'y'}, 'stroke': {'scale': 'c', 'value': series_names[i]}, } }, }) points = [] for j, x in enumerate(xs): y = yss[i][j] min_x = min(x, min_x) max_x = max(x, max_x) min_y = min(y, min_y) max_y = max(y, max_y) points.append({'x': x, 'y': y}) tables.append(points) data = [] for i, table in enumerate(tables): data.append({ 'name': 'table_{:03d}'.format(i), 'values': table }) spec = { 'width': 370, 'height': 250, 'data': data, 'scales': [ { 'name': 'x', 'type': 'linear', 'range': 'width', 'domainMin': min_x, 'domainMax': max_x, 'nice': True, 'zero': False, }, { 'name': 'y', 'type': 'linear', 'range': 'height', 'domainMin': y_axis_min or min_y, 'domainMax': y_axis_max or max_y, 'nice': True, 'zero': False, }, { 'name': 'c', 'type': 'ordinal', 'range': 'category10', 'domain': series_names, } ], 'axes': [ {'type': 'x', 'scale': 'x', 'title': x_title}, {'type': 'y', 'scale': 'y', 'title': y_title, 'grid': True}, ], 'marks': marks, } if show_legend: spec['legends'] = [{'fill': 'c'}] self.vega(spec)
A wireless weather station with a thermometer is used to monitor time, as well as indoor and outdoor temperatures, within a 100-foot range. A wireless weather station thermometer has an inbuilt transmitter with dual or multi-channel capabilities that display temperatures in both Celsius and Fahrenheit can be placed inside or outside the home. All what is required is to mount the sensor outside, and the display unit will show the current temperature every ten seconds. It is an extremely convenient and up-to-the-second method of figuring out what the weather patterns are in your area or wherever you may roam. That way, you will not have to be at the mercy of weathpersons on the radio and television; instead, you can be your own meteorologist. Various brands of wireless weather station thermometers like GE and Lacrosse Technology are available commonly in the market. Even from the same company various wireless weather station thermometers with variety of different features are available to suit your needs. This compact and handy device, with no hassles of managing wires is best suitable for use in homes, offices etc. It saves you from monotonous practice of switching on the TV or radio sets to get the weather news. Wireless weather station thermometer gives you the advantage of knowing the every minute weather update at the comfort of your house or office. A small device carries wit itself a bundle of advantages, and in today’s unpredictable weather scenario, a wireless weather station thermometer is a requirement of every house.
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import os import random import tempfile import pytest from django.conf import settings from django.core.management import call_command from django.test.utils import override_settings from mock import patch import kolibri from kolibri.core.auth.constants.collection_kinds import FACILITY from kolibri.core.deviceadmin.management.commands.dbrestore import CommandError from kolibri.core.deviceadmin.utils import dbbackup from kolibri.core.deviceadmin.utils import dbrestore from kolibri.core.deviceadmin.utils import default_backup_folder from kolibri.core.deviceadmin.utils import get_dtm_from_backup_name from kolibri.core.deviceadmin.utils import IncompatibleDatabase from kolibri.core.deviceadmin.utils import search_latest from kolibri.utils.server import NotRunning from kolibri.utils.server import STATUS_UNKNOWN MOCK_DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ":memory:", 'OPTIONS': { 'timeout': 100, } } } MOCK_DATABASES_FILE = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(tempfile.mkdtemp(), "test{}.db".format(random.randint(0, 100000))), 'OPTIONS': { 'timeout': 100, } } } def is_sqlite_settings(): """ This does not work during pytest collection, needs to be called while executing tests! """ return 'sqlite3' in settings.DATABASES['default']['ENGINE'] def mock_status_not_running(): raise NotRunning(STATUS_UNKNOWN) def test_latest(): with pytest.raises(RuntimeError): call_command("dbrestore", latest=True) def test_illegal_command(): with pytest.raises(CommandError): call_command("dbrestore", latest=True, dump_file="wup wup") def test_no_restore_from_no_file(): with pytest.raises(CommandError): call_command("dbrestore", dump_file="does not exist") def test_active_kolibri(): """ Tests that we cannot restore while kolibri is active """ with patch( "kolibri.utils.server.get_status", return_value=(12345, "http://127.0.0.1", 1234) ) as gs: with pytest.raises(SystemExit): call_command("dbrestore", latest=True) gs.assert_called_once() def test_inactive_kolibri(): """ Tests that we cannot restore while kolibri is active """ with patch( "kolibri.utils.server.get_status", side_effect=mock_status_not_running ) as gs: # Since there's no backups available during a test, this should fail! with pytest.raises(RuntimeError): call_command("dbrestore", latest=True) gs.assert_called_once() def test_not_sqlite(): if is_sqlite_settings(): return with pytest.raises(IncompatibleDatabase): dbrestore("/doesnt/matter.file") def test_fail_on_unknown_file(): with pytest.raises(ValueError): get_dtm_from_backup_name("this-file-has-no-time") @pytest.mark.django_db @pytest.mark.filterwarnings('ignore:Overriding setting DATABASES') def test_restore_from_latest(): """ Tests that we cannot restore while kolibri is active """ if not is_sqlite_settings(): return with patch( "kolibri.utils.server.get_status", side_effect=mock_status_not_running ): # Create something special in the database! from kolibri.core.auth.models import Facility Facility.objects.create(name="test latest", kind=FACILITY) # Create a backup file from the current test database call_command("dbbackup") # Also add in a file with an old time stamp to ensure its ignored sql = "syntax error;" fbroken = "db-v{}_2015-08-02_00-00-00.dump".format(kolibri.__version__) open(os.path.join(default_backup_folder(), fbroken), "w").write(sql) # Add an unparsable file name fbroken = "db-v{}_.dump".format(kolibri.__version__) open(os.path.join(default_backup_folder(), fbroken), "w").write(sql) # Restore it into a new test database setting with override_settings(DATABASES=MOCK_DATABASES): from django import db # Destroy current connections and create new ones: db.connections.close_all() db.connections = db.ConnectionHandler() call_command("dbrestore", latest=True) # Test that the user has been restored! assert Facility.objects.filter(name="test latest", kind=FACILITY).count() == 1 @pytest.mark.django_db @pytest.mark.filterwarnings('ignore:Overriding setting DATABASES') def test_restore_from_file_to_memory(): """ Restores from a file dump to a database stored in memory and reads contents from the new database. """ if not is_sqlite_settings(): return with patch( "kolibri.utils.server.get_status", side_effect=mock_status_not_running ): # Create something special in the database! from kolibri.core.auth.models import Facility Facility.objects.create(name="test file", kind=FACILITY) # Create a backup file from the current test database dest_folder = tempfile.mkdtemp() backup = dbbackup(kolibri.__version__, dest_folder=dest_folder) # Restore it into a new test database setting with override_settings(DATABASES=MOCK_DATABASES): from django import db # Destroy current connections and create new ones: db.connections.close_all() db.connections = db.ConnectionHandler() call_command("dbrestore", dump_file=backup) # Test that the user has been restored! assert Facility.objects.filter(name="test file", kind=FACILITY).count() == 1 @pytest.mark.django_db @pytest.mark.filterwarnings('ignore:Overriding setting DATABASES') def test_restore_from_file_to_file(): """ Restores from a file dump to a database stored in a file and reads contents from the new database. """ if not is_sqlite_settings(): return with patch( "kolibri.utils.server.get_status", side_effect=mock_status_not_running ): # Create something special in the database! from kolibri.core.auth.models import Facility Facility.objects.create(name="test file", kind=FACILITY) # Create a backup file from the current test database dest_folder = tempfile.mkdtemp() # Purposefully destroy the connection pointer, which is the default # state of an unopened connection from django import db db.connections['default'].connection = None backup = dbbackup(kolibri.__version__, dest_folder=dest_folder) # Restore it into a new test database setting with override_settings(DATABASES=MOCK_DATABASES_FILE): # Destroy current connections and create new ones: db.connections.close_all() db.connections = db.ConnectionHandler() # Purposefully destroy the connection pointer, which is the default # state of an unopened connection db.connections['default'].connection = None call_command("dbrestore", dump_file=backup) # Test that the user has been restored! assert Facility.objects.filter(name="test file", kind=FACILITY).count() == 1 def test_search_latest(): search_root = tempfile.mkdtemp() major_version = ".".join(map(str, kolibri.VERSION[:2])) files = [ "db-v{}_2015-08-02_00-00-00.dump".format(kolibri.__version__), "db-v{}_2016-08-02_00-00-00.dump".format(kolibri.__version__), "db-v{}_2017-07-02_00-00-00.dump".format(major_version), "db-v{}_2017-08-02_00-00-00.dump".format(kolibri.__version__), ] latest = files[-1] for f in files: open(os.path.join(search_root, f), "w").write("") __, search_fname = os.path.split(search_latest(search_root, major_version)) assert search_fname == latest
Welcome to our charming oasis in Oslo! Located in the most vibrant area of the city yet still calm and relaxing environment. Here you can relax on the balcony on warm summer evening or light the fireplace in the fully equipped kitchen when you want it extra cozy. You will also have access to a beautiful backyard.
# -*- coding: utf-8 -*- import sys from .problem import Problem def main(): problems = list(Problem.discover()) if not problems: print('Did not find any problems!') sys.exit(1) num_problems = len(problems) if num_problems == 1: print('1 problem attempted') else: print(num_problems, 'problems attempted') for i, problem in enumerate(problems, start=1): print() print('{}/{}: Solving problem {}...' .format(i, num_problems, problem.number)) problem.solve() print('Answer:', problem.answer) print(problem) print() total_seconds = sum(problem.time.total_seconds() for problem in problems) print(total_seconds, 'seconds total') num_correct = sum(problem.correct for problem in problems) print('{}/{} correct'.format(num_correct, num_problems)) if num_correct == num_problems: print('You win!') else: print('FAILURE') sys.exit(1) if __name__ == '__main__': main()
The Elders have spent years learning to pray and communicate with the Great Spirit. Their job is to pass this knowledge onto the young people. The Elders have told us we are now in a great time of healing. The Creator is guiding them to help the young people figure this out. We must get involved and participate. We should pray and see what it is the Great Spirit wants us to do. We need to sacrifice our time to help the people and to be of maximum use to the Creator. Every person is needed to accomplish this great healing.
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe import erpnext from frappe.utils import flt, nowdate, add_days, cint from frappe import _ def reorder_item(): """ Reorder item if stock reaches reorder level""" # if initial setup not completed, return if not (frappe.db.a_row_exists("Company") and frappe.db.a_row_exists("Fiscal Year")): return if cint(frappe.db.get_value('Stock Settings', None, 'auto_indent')): return _reorder_item() def _reorder_item(): material_requests = {"Purchase": {}, "Transfer": {}, "Material Issue": {}, "Manufacture": {}} warehouse_company = frappe._dict(frappe.db.sql("""select name, company from `tabWarehouse` where disabled=0""")) default_company = (erpnext.get_default_company() or frappe.db.sql("""select name from tabCompany limit 1""")[0][0]) items_to_consider = frappe.db.sql_list("""select name from `tabItem` item where is_stock_item=1 and has_variants=0 and disabled=0 and (end_of_life is null or end_of_life='0000-00-00' or end_of_life > %(today)s) and (exists (select name from `tabItem Reorder` ir where ir.parent=item.name) or (variant_of is not null and variant_of != '' and exists (select name from `tabItem Reorder` ir where ir.parent=item.variant_of)) )""", {"today": nowdate()}) if not items_to_consider: return item_warehouse_projected_qty = get_item_warehouse_projected_qty(items_to_consider) def add_to_material_request(item_code, warehouse, reorder_level, reorder_qty, material_request_type, warehouse_group=None): if warehouse not in warehouse_company: # a disabled warehouse return reorder_level = flt(reorder_level) reorder_qty = flt(reorder_qty) # projected_qty will be 0 if Bin does not exist if warehouse_group: projected_qty = flt(item_warehouse_projected_qty.get(item_code, {}).get(warehouse_group)) else: projected_qty = flt(item_warehouse_projected_qty.get(item_code, {}).get(warehouse)) if (reorder_level or reorder_qty) and projected_qty < reorder_level: deficiency = reorder_level - projected_qty if deficiency > reorder_qty: reorder_qty = deficiency company = warehouse_company.get(warehouse) or default_company material_requests[material_request_type].setdefault(company, []).append({ "item_code": item_code, "warehouse": warehouse, "reorder_qty": reorder_qty }) for item_code in items_to_consider: item = frappe.get_doc("Item", item_code) if item.variant_of and not item.get("reorder_levels"): item.update_template_tables() if item.get("reorder_levels"): for d in item.get("reorder_levels"): add_to_material_request(item_code, d.warehouse, d.warehouse_reorder_level, d.warehouse_reorder_qty, d.material_request_type, warehouse_group=d.warehouse_group) if material_requests: return create_material_request(material_requests) def get_item_warehouse_projected_qty(items_to_consider): item_warehouse_projected_qty = {} for item_code, warehouse, projected_qty in frappe.db.sql("""select item_code, warehouse, projected_qty from tabBin where item_code in ({0}) and (warehouse != "" and warehouse is not null)"""\ .format(", ".join(["%s"] * len(items_to_consider))), items_to_consider): if item_code not in item_warehouse_projected_qty: item_warehouse_projected_qty.setdefault(item_code, {}) if warehouse not in item_warehouse_projected_qty.get(item_code): item_warehouse_projected_qty[item_code][warehouse] = flt(projected_qty) warehouse_doc = frappe.get_doc("Warehouse", warehouse) while warehouse_doc.parent_warehouse: if not item_warehouse_projected_qty.get(item_code, {}).get(warehouse_doc.parent_warehouse): item_warehouse_projected_qty.setdefault(item_code, {})[warehouse_doc.parent_warehouse] = flt(projected_qty) else: item_warehouse_projected_qty[item_code][warehouse_doc.parent_warehouse] += flt(projected_qty) warehouse_doc = frappe.get_doc("Warehouse", warehouse_doc.parent_warehouse) return item_warehouse_projected_qty def create_material_request(material_requests): """ Create indent on reaching reorder level """ mr_list = [] exceptions_list = [] def _log_exception(): if frappe.local.message_log: exceptions_list.extend(frappe.local.message_log) frappe.local.message_log = [] else: exceptions_list.append(frappe.get_traceback()) for request_type in material_requests: for company in material_requests[request_type]: try: items = material_requests[request_type][company] if not items: continue mr = frappe.new_doc("Material Request") mr.update({ "company": company, "transaction_date": nowdate(), "material_request_type": "Material Transfer" if request_type=="Transfer" else request_type }) for d in items: d = frappe._dict(d) item = frappe.get_doc("Item", d.item_code) uom = item.stock_uom conversion_factor = 1.0 if request_type == 'Purchase': uom = item.purchase_uom or item.stock_uom if uom != item.stock_uom: conversion_factor = frappe.db.get_value("UOM Conversion Detail", {'parent': item.name, 'uom': uom}, 'conversion_factor') or 1.0 mr.append("items", { "doctype": "Material Request Item", "item_code": d.item_code, "schedule_date": add_days(nowdate(),cint(item.lead_time_days)), "qty": d.reorder_qty / conversion_factor, "uom": uom, "stock_uom": item.stock_uom, "warehouse": d.warehouse, "item_name": item.item_name, "description": item.description, "item_group": item.item_group, "brand": item.brand, }) schedule_dates = [d.schedule_date for d in mr.items] mr.schedule_date = max(schedule_dates or [nowdate()]) mr.insert() mr.submit() mr_list.append(mr) except: _log_exception() if mr_list: if getattr(frappe.local, "reorder_email_notify", None) is None: frappe.local.reorder_email_notify = cint(frappe.db.get_value('Stock Settings', None, 'reorder_email_notify')) if(frappe.local.reorder_email_notify): send_email_notification(mr_list) if exceptions_list: notify_errors(exceptions_list) return mr_list def send_email_notification(mr_list): """ Notify user about auto creation of indent""" email_list = frappe.db.sql_list("""select distinct r.parent from `tabHas Role` r, tabUser p where p.name = r.parent and p.enabled = 1 and p.docstatus < 2 and r.role in ('Purchase Manager','Stock Manager') and p.name not in ('Administrator', 'All', 'Guest')""") msg = frappe.render_template("templates/emails/reorder_item.html", { "mr_list": mr_list }) frappe.sendmail(recipients=email_list, subject=_('Auto Material Requests Generated'), message = msg) def notify_errors(exceptions_list): subject = "[Important] [ERPNext] Auto Reorder Errors" content = """Dear System Manager, An error occured for certain Items while creating Material Requests based on Re-order level. Please rectify these issues: --- <pre> %s </pre> --- Regards, Administrator""" % ("\n\n".join(exceptions_list),) from frappe.email import sendmail_to_system_managers sendmail_to_system_managers(subject, content)
Open Me --- Hi guys! Today I am sharing another home here in Newcrest that is perfect for a professor and his dog. I hope you enjoy, thanks for watching!
""" Print override delta delay placement model in human readable format. """ import argparse import capnp import os.path # Remove magic import hook. capnp.remove_import_hook() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( '--schema_path', help='Path to override delta delay placement model schema', required=True ) parser.add_argument('--place_delay_matrix', required=True) args = parser.parse_args() place_delay_model = capnp.load( os.path.join(args.schema_path, 'place_delay_model.capnp') ) with open(args.place_delay_matrix, 'rb') as f: delay_model = place_delay_model.VprOverrideDelayModel.read(f) x_dim = delay_model.delays.dims[0] y_dim = delay_model.delays.dims[1] itr = iter(delay_model.delays.data) for x in range(x_dim): row = [] for y in range(y_dim): value = next(itr) row.append(str(value.value.value)) print(','.join(row)) if __name__ == "__main__": main()
Free apps always outnumber the paid ones since the majority of the users today expect their apps to be free. As such, many may wonder how do app creators recoup their expenses and make profits? Yes, apps that are free to download also make money. Did you pay anything to download or use Facebook? Whatsapp? Candy Crush? Perhaps tinder? No, not a dime, right? As a matter of fact, the most popular and widely used apps in the market are free and are generating excellent money as well. So, what’s the trick you ask? The monetization strategy of free apps is designed to optimize revenue opportunities. We also recommend identifying your strategy before you start developing your app idea, this can be done by consulting with an app developer with some experience. Now, if you are up in the air struggling to figure out whether or not to market your app for free, then read on. In this post, we will uncover the clever monetization strategies that popular free apps have utilized and made generous profits. The most common form of monetization is the advertisements of third parties. Apps display the advertisements of third parties and charge them whenever a user clicks on their ads. Usually, they display banner ads which occupy a lot of screen space. This method works well for apps which have a large user base. The key to making money is to generate massive traffic using aggressive marketing techniques. The in-app advertising is used by the apps that generate a considerable traffic every on a daily basis. It is based on the traditional form of online advertising which involves ads and makes money through networks such as Google’s Admob and iAds. The free app is paid differently for clicks on ads, impressions and video ads based on the format of ads and location of the users. These advertising networks are available in various models and are specially made for the mobile apps. Apps offer their users to use various features that are paid and charge a certain amount that is billed monthly or yearly. For example, a gaming app may allow the user to play advanced levels through a monthly subscription. Some apps allow their users to download music, videos, news, and articles. It’s a common practice to offer some essential features free of cost and charge the users for using particular features. Some apps offer their users some additional features for which they charge them. This strategy of monetization is usually used by the gaming apps. They provide their users to buy power, a weapon or play advanced levels. Games typically offer one or two stages free, and then they charge them to play advanced degrees. Not only the gaming apps but the audio, video and image editors also use this monetization strategy. Free apps promote some third party apps and products and get a commission whenever a user clicks the third party app or product. The third-party products are related to the app in some way. For example, if you are using a free meditation app, it may show you an advertisement of some meditation music or video. If you buy the music, then the app gets a commission which is its affiliate income. For example, the social media apps and news apps use the affiliate marketing strategy for monetization. Sponsors are another way to generate income. The apps approach a sponsor and show that they have thousands of downloads and users. The free app offers the sponsors to market their brand and charges them a fee. Sponsor also market the free app as more the number of downloads; more is the number of clicks on the sponsor ads. The technique is beneficial for both the free app and sponsor. Many free apps also come with their premium versions. Such apps offer their users to upgrade to premium versions for a onetime fee to use a complete set of features. They provide limited elements in their free app version and charge their users for access to full features. The link to the premium version of the app is given in the free app itself. Users can buy or subscribe to the premium version by accessing the link and making the payment by any of the available options. Free apps partners with companies having a similar customer base and offer them to integrate their offers in the app. When a user views or buys a product, they charge the partner company for a commission. This is similar to affiliate marketing but differs in the point that here the free app partners with the company having a similar customer base. However, in affiliate marketing, the customer base of the app and company may not be similar. Cost Per install is a new marketing strategy by which the free apps make money. Free app partners with a new app which needs to be downloaded by users and display its advertisement in it. When a user downloads the new app, the free app gets a commission. The marketing strategy is beneficial for both apps as the free app makes money and the new app gets new users. Some of the free apps make many by collecting and selling the data of their users to third parties. When you download some free apps and install them, they ask your permission to access some information on your device. If you click on “yes” or “accept,” they access the websites you visit, your browsing history, your social media activities, contacts and sell this information to third parties to make money. The third parties now use this information to market their products or services based on your interests and preferences. Any free app that uses a monetization strategy to make money needs to grow aggressively to have a significant active user base. As only a small fraction of the total users helps generate income for them, it needs to grow continuously to make substantial revenue. The amount of money a free app makes depends on many factors such as free to paid conversion rates, customer engagement, churn rate and competition from similar apps. All the popular apps such as Whatsapp, Instagram, Candy Crush, etc. have used a sound marketing strategy to make millions of users, which is the reason for their worldwide popularity. Contact us at App Boxer if you have any questions regarding app development or the monetization methods that suit your idea. We are located in Sydney Australia and love to meet people with exciting ideas!
# # Copyright 2009 Eigenlabs Ltd. http://www.eigenlabs.com # # This file is part of EigenD. # # EigenD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # EigenD is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with EigenD. If not, see <http://www.gnu.org/licenses/>. # from pi import atom,database,utils,logic,container,node,action,const,async,rpc,paths from pibelcanto import lexicon from plg_language import noun,verb,macro,imperative class Database(database.Database): def __init__(self): self.__primitives = {} database.Database.__init__(self) self.add_module(noun) self.add_module(verb) self.add_module(imperative) self.add_lexicon(lexicon.lexicon) # widget manager for updating widget names if they change self.__widget_manager = None def lookup_primitive(self,klass): return self.__primitives.get(klass) def add_module(self,module): logic.Engine.add_module(self,module) self.add_primitives(module) def add_primitives(self, module): a = dict([ (k[10:],getattr(module,k)) for k in dir(module) if k.startswith('primitive_') ]) self.__primitives.update(a) def find_all_descendants(self, ids): s = frozenset() for id in ids: d = self.find_descendants(id) if len(d)==0: s = s.union(frozenset([id])) else: s = s.union(self.find_all_descendants(d)) return s def object_changed(self,proxy,parts): # on agent or atom name change, updates the osc widgets and Stage tabs id=proxy.id() if 'name' in parts or 'ordinal' in parts: # build osc name name_str = '_'.join(proxy.names()) ordinal = proxy.ordinal() if ordinal!=0: name_str += '_'+str(ordinal) # id change set is this object, plus any children # add subsystems that are not agents to prevent changes to rigs # from including the agents they contain agents = self.__propcache.get_idset('agent') changed_nodes = set(self.find_joined_slaves(id)).difference(agents) changed_nodes.add(id) changed_nodes_frozenset = self.find_all_descendants(frozenset(changed_nodes)) #for changed_node in changed_nodes_frozenset: # print changed_node, self.find_full_desc(changed_node) if self.__widget_manager is not None: self.__widget_manager.check_widget_name_updates(changed_nodes_frozenset) def set_widget_manager(self, widget_manager): self.__widget_manager = widget_manager
Asher, G; Reinke, H; Altmeyer, M; Gutierrez-Arcelus, M; Hottiger, M O; Schibler, U (2010). Poly(ADP-ribose) polymerase 1 participates in the phase entrainment of circadian clocks to feeding. Cell, 142(6):943-953. Toller, I M; Altmeyer, M; Kohler, E; Hottiger, M O; Müller, A (2010). Inhibition of ADP ribosylation prevents and cures helicobacter-induced gastric preneoplasia. Cancer Research, 70(14):5912-5922. Altmeyer, M; Hottiger, M O (2009). Poly(ADP-ribose) polymerase 1 at the crossroad of metabolic stress and inflammation in aging. Aging, 1(5):458-469. Messner, S; Schuermann, D; Altmeyer, M; Kassner, I; Schmidt, D; Schär, P; Müller, S; Hottiger, M O (2009). Sumoylation of poly(ADP-ribose) polymerase 1 inhibits its acetylation and restrains transcriptional coactivator function. FASEB Journal, 23(11):3978-3989. This list was generated on Fri Apr 19 06:50:31 2019 CEST.
import secret from models import User,Currency,Expense,Bill import urllib2,json import urllib2 import urllib from docx import Document import time from docx.shared import Inches import os from datetime import timedelta from django.core.files import File #FlockOS from pyflock import FlockClient, verify_event_token from pyflock import Message, SendAs, Attachment, Views, WidgetView, HtmlView, ImageView, Image, Download, Button, OpenWidgetAction, OpenBrowserAction, SendToAppAction def appInstall(pjson): try: userId = pjson['userId'] token = pjson['token'] u = User(userId = userId, token=token) u.save() except: raise def appUninstall(pjson): try: userId = pjson['userId'] User.objects.get(userId=userId).delete() except: raise def sendMessage(chat_id,userId,message): try: user = User.objects.get(userId=userId) flock_client = FlockClient(token=user.token, app_id=secret.getAppID) send_as_xpense = SendAs(name='Xpense', profile_image='https://pbs.twimg.com/profile_images/1788506913/HAL-MC2_400x400.png') send_as_message = Message(to=chat_id,text=message,send_as=send_as_xpense) flock_client.send_chat(send_as_message) except: raise def total(expense_list,trackObj): try: currency_list = Currency.objects.all() total = {} for curr in currency_list: total[curr.abbr] = 0 for expense in expense_list: total[expense.currency.abbr]+=expense.amount total = {key: value for key, value in total.items() if value is not 0} target_curr = str(trackObj.budget_currency.abbr) target_value = 0 perc_spent = 0 if target_curr in total.keys(): target_value = total[target_curr] #check if there is a budget if trackObj.budget != 0: #converting all currencies to budget currency target_value = 0 symbols = total.keys() rates = getconversionrates(target_curr,symbols) target_value = 0 for key, value in total.items(): if key==target_curr: target_value+=value else: target_value+= round(value/rates[key],2) perc_spent = round((target_value/trackObj.budget)*100,2) return total,target_value,perc_spent except: raise def getconversionrates(to_curr,from_curr_list): if to_curr in from_curr_list: from_curr_list.remove(to_curr) from_curr_list_str = ','.join(from_curr_list) API_string = 'http://api.fixer.io/latest?base='+to_curr+'&symbols='+from_curr_list_str response = urllib2.urlopen(API_string).read() pjson = json.loads(response) return pjson['rates'] def fetchMessagePictures(group_id,token,uids): data = [('chat',str(group_id)),('token',str(token)),('uids',uids)] url = 'https://api.flock.co/v1/chat.fetchMessages' req = urllib2.Request(url, headers={'Content-Type' : 'application/x-www-form-urlencoded'}) result = urllib2.urlopen(req, urllib.urlencode(data)) content = result.read() content = json.loads(content) src_list = [] for data in content: for attachment in data['attachments']: for fil in attachment['downloads']: if str(fil['mime']) in ['image/jpeg','image/png']: src_list.append(fil['src']) return src_list def report(track,userId): document = Document() document.add_heading('Expense Report - '+ str(track.name)) status = '\nPurpose : '+str(track.purpose)+'\n' now = time.strftime("%c") status = status + 'Report date: '+str(now)+'\n' expense_list = Expense.objects.filter(track = track) user = User.objects.get(userId=userId) flock_client = FlockClient(token=user.token, app_id=secret.getAppID) pjson = flock_client.get_user_info() utc = str(pjson['timezone']) hours = int(utc[1:3]) minutes = int(utc[4:6]) if(utc[0]=='+'): for expense in expense_list: expense.timestamp += timedelta(hours=hours,minutes=minutes) else: for expense in expense_list: expense.timestamp -= timedelta(hours=hours,minutes=minutes) total_expense_by_curr,converted_total,perc_spent = total(expense_list,track) if track.budget != 0: status = status + 'Budget: '+str(track.budget_currency.abbr)+' '+str(track.budget)+'\n' status = status + 'Total spent: '+str(track.budget_currency.abbr)+' '+ str(converted_total)+'\n' status = status + 'Spending: '+str(perc_spent)+'%'+'\n' status = status + 'Spending per currency:\n' for key,value in total_expense_by_curr.items(): status = status+' - '+str(key)+' '+str(value)+'\n' paragraph = document.add_paragraph(status) #table table = document.add_table(rows=1, cols=4) heading_cells = table.rows[0].cells heading_cells[0].text = 'Purpose' heading_cells[1].text = 'Paid By' heading_cells[2].text = 'Time' heading_cells[3].text = 'Amount' for expense in expense_list: cells = table.add_row().cells cells[0].text = expense.purpose cells[1].text = expense.paidby cells[2].text = str(expense.timestamp) cells[3].text = expense.currency.abbr +' '+str(expense.amount) filename = 'media/'+str(track.chat.chat_id[2:])+'_'+str(track.id)+'.docx' download_bills(expense_list,document) document.save(filename) django_file = File(open(filename,'r')) print (django_file.name) return django_file def download_bills(expense_list,document): url_list = [] for expense in expense_list: ul = Bill.objects.filter(expense = expense) for u in ul: url_list.append(str(u.url)) print url_list if(len(url_list)): document.add_page_break() file_list = [] for url in url_list: f = open(url[33:],'wb') f.write(urllib.urlopen(url).read()) f.close() file_list.append(url[33:]) for fil in file_list: document.add_picture(fil,width=Inches(6.0)) os.remove(fil)
It’s a brave man who launches a privately-owned, independent coffee shop in an area surrounded by the likes of Costa, Caffè Nero and Starbucks. But that’s what John Wheeler did and, six years on, business is good. John puts the secret of his success down to a mixture of quality service from polite and courteous staff, his own blend of fair trade coffee – and the versatility of a revenue generating loyalty card system that’s part of his Aloha point of sale software. Before opening Coffee Bamber in Darlington’s Cornmill Shopping Centre, John ran a hotel, where he used roomMaster property management software from NFS Technology Group. So, when he needed a sophisticated point of sale system for his newly-opened coffee shop, he turned again to NFS, who demonstrated and then installed Aloha. “Day to day, Aloha Quickservice covers every aspect of our point of sale needs and simplifies operations for staff, putting everything at their fingertips on a touch screen,” says John. But, for John it’s the way Aloha handles his loyalty card system that has proved to be a winner for generating new customers and keeping them coming back for more. The importance of loyalty cards to Coffee Bamber was ably demonstrated when their EPOS system went down on a Saturday morning. Staff recorded points manually for addition to accounts, but it was clear that customers didn’t entirely trust that, and were likely to start drifting away. A call to NFS solved the problem fast.
#!/usr/bin/env python3 # Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Command-line tool for printing package-level dependencies.""" import argparse import graph import print_dependencies_helper import serialization def print_package_dependencies_for_edge(begin, end): """Prints dependencies for an edge in the package graph. Since these are package edges, we also print the class dependency edges comprising the printed package edge. """ if begin == end: return print(f'\t{begin.name} -> {end.name}') class_deps = begin.get_class_dependencies_in_outbound_edge(end) print(f'\t{len(class_deps)} class edge(s) comprising the dependency:') for begin_class, end_class in graph.sorted_edges_by_name(class_deps): print(f'\t\t{begin_class.class_name} -> {end_class.class_name}') def print_package_dependencies_for_key(package_graph, key, ignore_subpackages): """Prints dependencies for a valid key into the package graph. Since we store self-edges for the package graph but they aren't relevant in this case, we skip them. """ node = package_graph.get_node_by_key(key) inbound_without_self = [other for other in node.inbound if other != node] print(f'{len(inbound_without_self)} inbound dependency(ies) ' f'for {node.name}:') for inbound_dep in graph.sorted_nodes_by_name(inbound_without_self): if ignore_subpackages and inbound_dep.name.startswith(node.name): continue print_package_dependencies_for_edge(inbound_dep, node) outbound_without_self = [other for other in node.outbound if other != node] print(f'{len(outbound_without_self)} outbound dependency(ies) ' f'for {node.name}:') for outbound_dep in graph.sorted_nodes_by_name(outbound_without_self): if ignore_subpackages and outbound_dep.name.startswith(node.name): continue print_package_dependencies_for_edge(node, outbound_dep) def main(): """Prints package-level dependencies for an input package.""" arg_parser = argparse.ArgumentParser( description='Given a JSON dependency graph, output the package-level ' 'dependencies for a given package and the ' 'class dependencies comprising those dependencies') required_arg_group = arg_parser.add_argument_group('required arguments') required_arg_group.add_argument( '-f', '--file', required=True, help='Path to the JSON file containing the dependency graph. ' 'See the README on how to generate this file.') required_arg_group.add_argument( '-p', '--package', required=True, help='Case-insensitive name of the package to print dependencies for. ' 'Matches names of the form ...input, for example ' '`browser` matches `org.chromium.browser`.') optional_arg_group = arg_parser.add_argument_group('optional arguments') optional_arg_group.add_argument( '-s', '--ignore-subpackages', action='store_true', help='If present, this tool will ignore dependencies between the ' 'given package and subpackages. For example, if given ' 'browser.customtabs, it won\'t print a dependency between ' 'browser.customtabs and browser.customtabs.content.') arguments = arg_parser.parse_args() _, package_graph, _ = serialization.load_class_and_package_graphs_from_file( arguments.file) package_graph_keys = [node.name for node in package_graph.nodes] valid_keys = print_dependencies_helper.get_valid_package_keys_matching( package_graph_keys, arguments.package) if len(valid_keys) == 0: print(f'No package found by the name {arguments.package}.') elif len(valid_keys) > 1: print(f'Multiple valid keys found for the name {arguments.package}, ' 'please disambiguate between one of the following options:') for valid_key in valid_keys: print(f'\t{valid_key}') else: print(f'Printing package dependencies for {valid_keys[0]}:') print_package_dependencies_for_key(package_graph, valid_keys[0], arguments.ignore_subpackages) if __name__ == '__main__': main()
New Times reporting played a key role in the potential suspension of an Arizona physician’s medical license. The physician, Dr. Elliott Schmerler, was named in the April 10, 2008 feature “Dr. Loophole.” Though banned from performing cosmetic surgery in Nevada, Schmerler slipped through a licensing loophole to perform the same surgeries in Arizona, according to staff and a former patient of his. At its August 5 meeting the Arizona Homeopathic Board requested that Dr. Schmerler voluntarily suspend his license while the board continues its investigation. That investigation was launched as a result of New Times findings, according to board meeting minutes. New Times named Schmerler as one of at least six doctors who’ve come to practice in Arizona – after having their medical licenses pulled in other states. Because Schmerler was once booted by another state medical board, he cannot secure a conventional MD license in Arizona. But Arizona’s alternative or “homeopathic” medical board routinely licenses doctors who’ve been booted from other states. Those homeopathic doctors then bear the initials MD(h) instead of MD – a subtle distinction that’s lost on most patients. The homeopathic license arms disgraced doctors with conventional prescribing privileges. Homeopathic doctors aren’t allowed to perform conventional surgeries (unless of course they have a conventional MD license in Arizona), but New Times found some Arizona homeopathic doctors use their “alternative” license to practice the very conventional surgeries that got them booted from their previous state. Schmerler is a case in point. He was expressly banned from practicing cosmetic surgery in Nevada. Because of a trail of patients who claim he maimed them and a past prison sentence for tax fraud, Schmerler can’t even apply to be an MD in Arizona. But he applied for and quickly received his MD(h), thanks to the homeopathic board. Despite Schmerler’s long and controversial career as a cosmetic surgeon in Nevada, Arizona’s homeopathic board didn’t ask Schmerler if he would try to practice cosmetic surgery on Arizonans with his MD(h) license. At one point Schmerler even presented the board with a business card reading “A Surgical Art” – a cosmetic surgery practice. The board still didn't take action. New Times called “A Surgical Art” in March, and a staff member there confirmed that Schmerler performs all sorts of surgeries that are illegal with only an MD(h) license – from liposuctions to tummy tucks. It seemed clear enough that Schmerler – who could never practice as an MD in Arizona – slipped right through the MD(h) loophole so he could continue with the same profitable surgeries he’s banned from performing in Nevada. At its May 13 meeting the homeopathic board’s executive director, Chris Springer, announced an investigation into Schmerler. “In her review of the pending matter, Mrs. Springer informed the Board that she had initiated this investigation based on statements made in a recent New Times article. In that article, the reporter had stated that office personnel working at Dr. Schmerler’s clinic, A Surgical Art, LLC, indicated to the reporter that Dr. Schmerler provided cosmetic surgery. Mrs. Springer indicated that her own call to the clinic had not confirmed this allegation,” board meeting minutes read. Schmerler then provided the board with a written statement, claiming he only worked as a surgeon’s assistant during surgical procedures. But within weeks a former patient of Schmerler’s contacted the board, confirming that it was Schmerler himself who performed her liposuction procedure in May of 2007. He didn't work as an assistant in her procedure, she says. Upon hearing the patient corroboration at its August 5 meeting, the board voted 6-0 to continue its investigation and to ask Schmerler for a voluntary six-month suspension. While the board has not yet addressed it, Schmerler's advertising himself as an MD in Arizona is also in question. He is not a licensed MD in Arizona, but his place of business uses the initials MD and MD(h). A Surgical Art's phone number, which once connected to a receptionist, now connects directly to Schmerler's cell phone. In a phone conversation today Schmerler said the first New Times story damaged him. When asked about inaccuracies, Schmerler did not identify any facts that were wrong with the story. He also said the board hasn’t actually done anything to his license yet. “This is just an investigation, and it’s really preliminary for you to print anything at this point. There’s been no facts at all, and I think for you to go print something at this stage in the game is very unprofessional,” Schmerler said. Arizona’s Homeopathic Medical Board is one of only three such alternative medical boards in the country. It licenses more homeopathic physicians than the other two homeopathic boards combined (Nevada and Connecticut). This state's homeopathic board is allowed to overlook previous discipline against physicians in other states. Its homeopathic license also gives more prescribing power than alternative licenses in some other states.
""" Background task scheduling. """ import asyncio from contextlib import suppress from typing import Any, Coroutine, Set from aiohttp import web from brewblox_service import features CLEANUP_INTERVAL_S = 300 def setup(app: web.Application): features.add(app, TaskScheduler(app)) def get_scheduler(app: web.Application) -> 'TaskScheduler': return features.get(app, TaskScheduler) async def create_task(app: web.Application, coro: Coroutine, *args, **kwargs ) -> asyncio.Task: """ Convenience function for calling `TaskScheduler.create(coro)` This will use the default `TaskScheduler` to create a new background task. Example: import asyncio from datetime import datetime from brewblox_service import scheduler, service async def current_time(interval): while True: await asyncio.sleep(interval) print(datetime.now()) async def start(app): await scheduler.create_task(app, current_time(interval=2)) app = service.create_app(default_name='example') scheduler.setup(app) app.on_startup.append(start) service.furnish(app) service.run(app) """ return await get_scheduler(app).create(coro, *args, **kwargs) async def cancel_task(app: web.Application, task: asyncio.Task, *args, **kwargs ) -> Any: """ Convenience function for calling `TaskScheduler.cancel(task)` This will use the default `TaskScheduler` to cancel the given task. Example: import asyncio from datetime import datetime from brewblox_service import scheduler, service async def current_time(interval): while True: await asyncio.sleep(interval) print(datetime.now()) async def stop_after(app, task, duration): await asyncio.sleep(duration) await scheduler.cancel_task(app, task) print('stopped!') async def start(app): # Start first task task = await scheduler.create_task(app, current_time(interval=2)) # Start second task to stop the first await scheduler.create_task(app, stop_after(app, task, duration=10)) app = service.create_app(default_name='example') scheduler.setup(app) app.on_startup.append(start) service.furnish(app) service.run(app) """ return await get_scheduler(app).cancel(task, *args, **kwargs) class TaskScheduler(features.ServiceFeature): def __init__(self, app: web.Application): super().__init__(app) self._tasks: Set[asyncio.Task] = set() async def startup(self, *_): await self.create(self._cleanup()) async def shutdown(self, *_): [task.cancel() for task in self._tasks] await asyncio.wait(self._tasks) self._tasks.clear() async def _cleanup(self): """ Periodically removes completed tasks from the collection, allowing fire-and-forget tasks to be garbage collected. This does not delete the task object, it merely removes the reference in the scheduler. """ while True: await asyncio.sleep(CLEANUP_INTERVAL_S) self._tasks = {t for t in self._tasks if not t.done()} async def create(self, coro: Coroutine) -> asyncio.Task: """ Starts execution of a coroutine. The created asyncio.Task is returned, and added to managed tasks. The scheduler guarantees that it is cancelled during application shutdown, regardless of whether it was already cancelled manually. Args: coro (Coroutine): The coroutine to be wrapped in a task, and executed. Returns: asyncio.Task: An awaitable Task object. During Aiohttp shutdown, the scheduler will attempt to cancel and await this task. The task can be safely cancelled manually, or using `TaskScheduler.cancel(task)`. """ task = asyncio.get_event_loop().create_task(coro) self._tasks.add(task) return task async def cancel(self, task: asyncio.Task, wait_for: bool = True) -> Any: """ Cancels and waits for an `asyncio.Task` to finish. Removes it from the collection of managed tasks. Args: task (asyncio.Task): The to be cancelled task. It is not required that the task was was created with `TaskScheduler.create_task()`. wait_for (bool, optional): Whether to wait for the task to finish execution. If falsey, this function returns immediately after cancelling the task. Returns: Any: The return value of `task`. None if `wait_for` is falsey. """ if task is None: return task.cancel() with suppress(KeyError): self._tasks.remove(task) with suppress(Exception): return (await task) if wait_for else None
Southport Wellness is a relaxing space to receive friendly and welcoming chiropractic care, acupuncture, massage therapy, and nutritional support. In addition to our convenient hours, our online intake form saves you time, and our treatment plans give you a clear and quick timeline to get you back to enjoying life. Whether you've had an injury, unexplained nagging symptoms, or are just looking to stay at peak health, we have the expertise to help. We serve a diverse community and treat patients of all stages and walks of life. Our mission is to provide better health for the individual while nurturing our community and planet. We have been a part of the Lakeview community since 2003 and give back throughout the year with donations to local charities, an annual fall food drive benefiting the Chicago Food Depository, and an annual Spring Coat Drive with donations going to Lakeview area charities. We'd love to see you soon! Call us at 773.525.2225 to make an appointment and feel better soon!
# Copyright 2016 Darjus Loktevic # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..data_converter import JSONDataConverter, AbstractDataConverter from ..constants import USE_WORKER_TASK_LIST, CHILD_TERMINATE from ..utils import str_or_NONE, snake_keys_to_camel_case from ..context import get_context, DecisionContext, StartWorkflowContext from ..workflow_execution import WorkflowExecution from .base_flow_type import BaseFlowType class WorkflowType(BaseFlowType): _continue_as_new_keys = (('taskStartToCloseTimeout', 'task_start_to_close_timeout'), ('childPolicy', 'child_policy'), ('taskList', 'task_list'), ('taskPriority', 'task_priority'), ('executionStartToCloseTimeout', 'execution_start_to_close_timeout'), ('version', 'version'), ('input', 'input')) DEFAULT_DATA_CONVERTER = JSONDataConverter() def __init__(self, version, execution_start_to_close_timeout, task_list=USE_WORKER_TASK_LIST, task_priority=None, task_start_to_close_timeout=30, # as in java flow child_policy=CHILD_TERMINATE, description="", name=None, data_converter=None, skip_registration=False): self.version = version self.name = name self.task_list = task_list self.task_priority = task_priority self.child_policy = child_policy self.execution_start_to_close_timeout = execution_start_to_close_timeout self.task_start_to_close_timeout = task_start_to_close_timeout self.description = description self.skip_registration = skip_registration self.workflow_id = None self.data_converter = data_converter @property def data_converter(self): return self._data_converter @data_converter.setter def data_converter(self, converter): if converter is None: # set the default self._data_converter = self.DEFAULT_DATA_CONVERTER return if isinstance(converter, AbstractDataConverter): self._data_converter = converter return raise TypeError("Converter {0!r} must be a subclass of {1}" .format(converter, AbstractDataConverter.__name__)) # noinspection PyShadowingBuiltins def to_decision_dict(self, input, workflow_id=None, worker_task_list=None, domain=None): task_list = self.task_list if task_list == USE_WORKER_TASK_LIST: task_list = worker_task_list serialized_input = self.data_converter.dumps(input) decision_dict = { 'workflowType': {'version': self.version, 'name': self.name}, 'taskList': {'name': str_or_NONE(task_list)}, 'childPolicy': str_or_NONE(self.child_policy), 'executionStartToCloseTimeout': str_or_NONE( self.execution_start_to_close_timeout), 'taskStartToCloseTimeout': str_or_NONE( self.task_start_to_close_timeout), 'input': serialized_input} if self.task_priority is not None: decision_dict['taskPriority'] = str_or_NONE(self.task_priority) # for child workflows if workflow_id is not None and self.workflow_id is None: decision_dict['workflowId'] = workflow_id if domain is not None: decision_dict['domain'] = domain # apply any overrides context = get_context() _decision_dict = {} _decision_dict.update(decision_dict) _decision_dict.update(snake_keys_to_camel_case(context._workflow_options_overrides)) return _decision_dict # noinspection PyShadowingBuiltins def to_continue_as_new_dict(self, input, worker_task_list): decision_dict = self.to_decision_dict( input, worker_task_list=worker_task_list) continue_as_new_dict = {} for key, continue_as_new_key in self._continue_as_new_keys: try: continue_as_new_dict[continue_as_new_key] = decision_dict[key] except KeyError: pass return continue_as_new_dict def to_registration_options_dict(self, domain, worker_task_list): if self.skip_registration: return None task_list = self.task_list if task_list == USE_WORKER_TASK_LIST: task_list = worker_task_list registration_options = { 'domain': domain, 'version': self.version, 'name': self.name, 'defaultTaskList': {'name': str_or_NONE(task_list)}, 'defaultChildPolicy': str_or_NONE(self.child_policy), 'defaultExecutionStartToCloseTimeout': str_or_NONE( self.execution_start_to_close_timeout), 'defaultTaskStartToCloseTimeout': str_or_NONE( self.task_start_to_close_timeout), 'description': str_or_NONE(self.description) } if self.task_priority is not None: registration_options['defaultTaskPriority'] = str_or_NONE(self.task_priority) return registration_options def _reset_name(self, name, force=False): # generate workflow name if self.name is None or force: self.name = name def __call__(self, __class_and_instance, *args, **kwargs): _class, _instance = __class_and_instance context = get_context() if isinstance(context, StartWorkflowContext): workflow_id, run_id = context.worker._start_workflow_execution( self, *args, **kwargs) # create an instance with our new workflow execution info workflow_instance = _class(WorkflowExecution(workflow_id, run_id)) workflow_instance._data_converter = self.data_converter return workflow_instance elif isinstance(context, DecisionContext): if context.decider.execution_started: if context._workflow_instance == _instance: continue_as_new_dict = self.to_continue_as_new_dict( [args, kwargs], context.decider.task_list) return context.decider._continue_as_new_workflow_execution( **continue_as_new_dict) else: # create an instance with our new workflow execution info # but don't set the workflow_id and run_id as we don't yet # know them workflow_instance = _class(WorkflowExecution(None, None)) workflow_instance._data_converter = self.data_converter future = context.decider._handle_start_child_workflow_execution( self, workflow_instance, [args, kwargs]) return future else: raise NotImplementedError("Unsupported context") def __hash__(self): return hash("{0}{1}".format(self.name, self.version)) def __repr__(self): return "<{} (name={}, version={})>".format(self.__class__.__name__, self.name, self.version)
Q. Hey Gale! I am loving the Fat-Burning Machine plan. Thank you so much for helping me see a way of eating that can last a lifetime. (I know you call it a “diet” but it is a new lifestyle for me!) I’ve only been following the plan for three weeks and I’ve lost 6 pounds, I’m not hungry and I’m sleeping better. In the book you recommend breakfast, lunch and two snacks. As I’ve become a Fat-Burning Machine (yay!) I sometimes don’t feel like a snack. Because I’m having success, I’m afraid to cut it out. Is snacking required in order to lose weight? A. Hello A.K. ~ First, congratulations on your success! What you’ve discovered is that as you change your body into a Fat-Burning Machine, you experience less hunger – especially that desperately hungry feeling. I’m happy to read that you are in tune with your body, noticing that you are not hungry. When you are not hungry, don’t snack. Don’t “force” a snack, they are optional. Keep me posted on your success and let me know if you have more questions.
#!/usr/bin/python ''' @file fractal_qt4_mpl.py @author Philip Wiese @date 12 Okt 2016 @brief Displays Mandelbrot Set with PyQt4 and Matplotlip ''' from PyQt4.QtCore import * from PyQt4.QtGui import * from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.pyplot import * from matplotlib.widgets import RectangleSelector from numpy import log10 from fractal_qt4_mpl_lib import mandelbrot from gtk._gtk import Alignment ###### Config ####### re_min = 0.385 re_max = 0.395 im_min = 0.135 im_max = 0.145 max_betr = 2 max_iter = 100 res = 400 # X Resolution cont = True # Show continual color norm = True # Normalize Values ###################### class AppForm(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setWindowTitle('Mandelbrot Set') self.create_menu() self.create_main_frame() self.create_status_bar() # # Initialize textbox values # self.textbox_re_min.setText(str(re_min)) self.textbox_re_max.setText(str(re_max)) self.textbox_im_min.setText(str(im_min)) self.textbox_im_max.setText(str(im_max)) self.textbox_max_iter.setText(str(max_iter)) # # Render mandelbrot set # self.setMinimumWidth(620) self.resize(620, 460) self.draw() def save_plot(self): file_choices = "PNG (*.png)|*.png" path = unicode(QFileDialog.getSaveFileName(self, 'Save file', '', file_choices)) if path: self.canvas.print_figure(path) self.statusBar().showMessage('Saved to %s' % path, 2000) # # Display infos about application # def on_about(self): msg = """Mandelbrot Set Generator: ### Features ### * Click left mouse button and drag to zoom * Enter custom values for ReMin, ReMin, ImMin and ImMax * Show or hide the grid * Save the plot to a file using the File menu * De-/activate continuous color spectrum * De-/activate normalized values ### Used Libraries ### * PyQt4 * Matplotlib ### Author ### Made by Philip Wiese info@maketec.ch 16. Oktober 2016 """ QMessageBox.about(self, "About the demo", msg.strip()) # # Show mouse position in statusbar # def statusbar_coord(self, event): # Show coordinates time in statusbar if event.inaxes is not None: text = "Re(c): % .5f, Im(c) % .5f" % (event.xdata, event.ydata) self.coord_text.setText(text) # # Calculates mandelbrot set and updates mpl plot # def draw(self): """ Redraws the figure """ # Grap values from textboxes re_min = float(unicode(self.textbox_re_min.text())) re_max = float(unicode(self.textbox_re_max.text())) im_min = float(unicode(self.textbox_im_min.text())) im_max = float(unicode(self.textbox_im_max.text())) max_iter = int(unicode(self.textbox_max_iter.text())) # Grap values from checkboxes self.axes.grid(self.grid_cb.isChecked()) cont = self.cont_cb.isChecked() norm = self.norm_cb.isChecked() # Calculate mandelbrot set self.fractal = mandelbrot(re_min, re_max, im_min, im_max, max_betr, max_iter, res, cont) # Normalize Values if norm: self.fractal.data[self.fractal.data > 0] -= self.fractal.min # Show calculation time in statusbar self.status_text.setText("Calculation Time: %0.3fs" % self.fractal.calc_time) # Load data to mpl plot self.axes.imshow(self.fractal.data.T, origin="lower left", cmap='jet', extent=[re_min, re_max, im_min, im_max]) self.axes.set_xlabel("Re(c)", labelpad=20) self.axes.set_ylabel("Im(c)") # Show/hide grid if self.grid_cb.isChecked(): self.axes.grid(linewidth=1, linestyle='-') # Align layout and redraw plot self.canvas.draw_idle() #self.fig.tight_layout() def line_select_callback(self, eclick, erelease): # eclick and erelease are the press and release events x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata # Zoom with left mouse click if eclick.button == 1: # Check for valid coordinates if (x1 != None and y2 != None and x1 != None and y1 != None): self.xmin = min(x1, x2) self.xmax = max(x1, x2) self.ymin = min(y1, y2) self.ymax = max(y1, y2) # Save array with relative values self.xy = [self.xmax - self.xmin, self.ymax - self.ymin] # Calculate precision in decimal digits for v in self.xy: if v <= 1: self.decimals = round(log10(1 / v)) + 2 # Round values with calculated precision re_min = round(self.xmin, int(self.decimals)) re_max = round(self.xmax, int(self.decimals)) im_min = round(self.ymin, int(self.decimals)) im_max = round(self.ymax, int(self.decimals)) # Update textbos values self.textbox_re_min.setText(str(re_min)) self.textbox_re_max.setText(str(re_max)) self.textbox_im_min.setText(str(im_min)) self.textbox_im_max.setText(str(im_max)) # Calculate and draw new mandelbrot set self.draw() # Zoom with right mouse click if eclick.button == 3: # Grap values from textboxes re_min = float(unicode(self.textbox_re_min.text())) re_max = float(unicode(self.textbox_re_max.text())) im_min = float(unicode(self.textbox_im_min.text())) im_max = float(unicode(self.textbox_im_max.text())) self.xy = [ re_max - re_min, im_max - im_min] # Calculate new values re_min = re_min - self.xy[0] / 2 re_max = re_max + self.xy[0] / 2 im_min = im_min - self.xy[1] / 2 im_max = im_max + self.xy[1] / 2 # Calculate precision in decimal digits for v in self.xy: if v <= 1: self.decimals = round(log10(1 / v)) + 2 # Round values with calculated precision re_min = round(re_min, int(self.decimals)) re_max = round(re_max, int(self.decimals)) im_min = round(im_min, int(self.decimals)) im_max = round(im_max, int(self.decimals)) # Update textbos values self.textbox_re_min.setText(str(re_min)) self.textbox_re_max.setText(str(re_max)) self.textbox_im_min.setText(str(im_min)) self.textbox_im_max.setText(str(im_max)) # Calculate and draw new mandelbrot set self.draw() def create_main_frame(self): self.main_frame = QWidget() self.main_frame.setMinimumHeight(280) # Create the Figure and FigCanvas objects self.fig = Figure((5,10), tight_layout=True) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) # Add sublot to figure do formatting self.axes = self.fig.add_subplot(111) self.axes.ticklabel_format(style='sci', scilimits=(0,0), axis='both') # Create zoom event handler self.RS = RectangleSelector(self.axes, self.line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button spancoords='data') # Other GUI controls self.textbox_re_min = QLineEdit() self.textbox_re_min_text = QLabel("ReMin: ") self.textbox_re_min.setMinimumWidth(55) self.textbox_re_max = QLineEdit() self.textbox_re_max_text = QLabel("ReMax: ") self.textbox_re_max.setMinimumWidth(55) self.textbox_im_min = QLineEdit() self.textbox_im_min_text = QLabel("ImMin: ") self.textbox_im_min.setMinimumWidth(55) self.textbox_im_max = QLineEdit() self.textbox_im_max_text = QLabel("ImMax: ") self.textbox_im_max.setMinimumWidth(55) self.textbox_max_iter = QLineEdit() self.textbox_max_iter_text = QLabel("Max Iterration: ") self.textbox_max_iter.setMinimumWidth(55) self.grid_cb = QCheckBox("Show Grid") self.grid_cb.setChecked(False) self.cont_cb = QCheckBox("Continuous Coloring") self.cont_cb.setChecked(True) self.norm_cb = QCheckBox("Normalize Values") self.norm_cb.setChecked(True) self.draw_button = QPushButton("Calculate && Draw") self.connect(self.draw_button, SIGNAL('clicked()'), self.draw) # # Layout with box sizers # hbox = QHBoxLayout() grid = QGridLayout() hbox.addWidget(self.canvas, 3) self.canvas.setCursor(Qt.CrossCursor) hbox.addLayout(grid,1) grid.setRowStretch(1,1) grid.addWidget(self.textbox_re_min , 0,1) grid.addWidget(self.textbox_re_min_text , 0,0) grid.addWidget(self.textbox_re_max , 1,1) grid.addWidget(self.textbox_re_max_text , 1,0) grid.addWidget(self.textbox_im_min , 2,1) grid.addWidget(self.textbox_im_min_text , 2,0) grid.addWidget(self.textbox_im_max , 3,1) grid.addWidget(self.textbox_im_max_text , 3,0) grid.addWidget(self.textbox_max_iter , 5,1) grid.addWidget(self.textbox_max_iter_text , 5,0) grid.addWidget(self.grid_cb , 6,0,1,2) grid.addWidget(self.cont_cb , 7,0,1,2) grid.addWidget(self.norm_cb , 8,0,1,2) grid.addWidget(self.draw_button , 9,0,1,2) grid.addWidget(QLabel(""), 10,0,2,2) self.main_frame.setLayout(hbox) self.setCentralWidget(self.main_frame) def create_status_bar(self): self.status_text = QLabel("Ready") self.coord_text = QLabel("Re(c): % 7f, Im(c) % 7f" % (0, 0)) self.canvas.mpl_connect("motion_notify_event", self.statusbar_coord) self.statusBar().addWidget(self.status_text, 1) self.statusBar().addWidget(self.coord_text, -1) def create_menu(self): # -- Menu Structure -- # File # Save plot (Ctrl+S) # Quit (Ctrl+Q) # Help # About (F1) # self.file_menu = self.menuBar().addMenu("&File") load_file_action = self.create_action("&Save plot", shortcut="Ctrl+S", slot=self.save_plot, tip="Save the plot") quit_action = self.create_action("&Quit", slot=self.close, shortcut="Ctrl+Q", tip="Close the application") self.add_actions(self.file_menu, (load_file_action, None, quit_action)) self.help_menu = self.menuBar().addMenu("&Help") about_action = self.create_action("&About", shortcut='F1', slot=self.on_about, tip='About the application') self.add_actions(self.help_menu, (about_action,)) def add_actions(self, target, actions): for action in actions: if action is None: target.addSeparator() else: target.addAction(action) def create_action(self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, signal="triggered()"): action = QAction(text, self) if icon is not None: action.setIcon(QIcon(":/%s.png" % icon)) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if slot is not None: self.connect(action, SIGNAL(signal), slot) if checkable: action.setCheckable(True) return action if __name__ == '__main__': app = QApplication(sys.argv) form = AppForm() form.show() app.exec_()
SO - ARE YOU LOOKING FOR A RELIABLE, EXPERIENCED, FULLY INSURED GARDEN AND GROUNDS MAINTENANCE CONTRACTOR TO TAKE COMPLETE CARE OF YOUR DOMESTIC GARDEN OR COMMERCIAL GROUNDS? OR PERHAPS YOU JUST NEED SOME SPECIALIST LAWN OR TURF MAINTENANCE OR A CONTRACTOR TO MAINTAIN AND IMPROVE YOUR PADDOCKS? We pride ourselves on our reliable, competent and friendly service. With nearly ten years of experience across the domestic and commercial garden maintenance sector we feel we have the skills, knowledge and tools to do all tasks safely, efficiently and at a competitive price. With a wide range of tools and equipment available to us, we can undertake a wide range of tasks, from cutting small lawns with a pedestrian mower to mowing larger acreage with a compact tractor and flail, rotary or cylinder mower - all equipment is ours, in-house and ready to work. We carry a wide range of specialist turf care equipment from scarifiers (both pedestrian and tractor mounted) to sprayers (knapsack and self propelled), aerators (again both pedestrian and tractor mounted), rotovators and seeding machines for setting new lawns to over ten different types and sizes of mowers for all different scenarios. Hedge cutting for both domestic and commercial properties and on contract is another service we commonly provide - we have all tools, equipment, working platforms and means to dispose of the waste created. We are fully insured for both public and employers liability, with staff NPTC trained and qualified in the safe use of pest and herbicides (more commonly known as weedkillers), we are also licensed waste carriers under registration number CBDU162103. All our relevant certificates are available to view on request. Contact us today by phone or email to discuss your exact requirements. ANP Services Spalding Ltd is a member of the Federation of Small Businesses & Landscape Juice Network - for more information, click links below.
from django.contrib.auth.models import User from django_countries import countries def get_user(user_id): user = User.objects.get(id=user_id) return user def get_user_profile(user_id): user = User.objects.get(id=user_id) return user.profile def get_ambassadors(country_code=None): ambassadors = [] all_ambassadors = User.objects.filter( groups__name='ambassadors').order_by('date_joined') for ambassador in all_ambassadors: if country_code: if ambassador.profile.country == country_code: ambassadors.append(ambassador.profile) else: ambassadors.append(ambassador.profile) return ambassadors def get_ambassadors_for_countries(): ambassadors = get_ambassadors() countries_ambassadors = [] # list countries minus two CUSTOM_COUNTRY_ENTRIES for code, name in list(countries)[2:]: readable_name = unicode(name) country_ambassadors = [ambassador for ambassador in ambassadors if ambassador.country == code] # load main ambassadors main_ambassadors = [ambassador for ambassador in country_ambassadors if ambassador.is_main_contact] # exclude main ambassadors supporting_ambassadors = [ambassador for ambassador in country_ambassadors if not ambassador.is_main_contact] countries_ambassadors.append( (code, readable_name, supporting_ambassadors, main_ambassadors)) countries_ambassadors.sort() return countries_ambassadors def get_ambassadors_for_country(country): ambassadors = User.objects.filter( groups__name='ambassadors', userprofile__country=country) return ambassadors def update_user_email(user_id, new_email): user = User.objects.get(id=user_id) user.email = new_email user.save(update_fields=["email"]) return user
TL; DR: The largest independent email provider, FastMail brings inbox management software to more than 150,000 customers around the world. The company’s top priority, in an age of inbox overload, is to make email feel less like work — by making it work for the customer. FastMail and its related products give users the flexibility and power to control the flow of information in and out of their email. Helen Horstmann-Allen, COO at FastMail and long-time email services veteran, chatted with us about the unorthodox notion of making work emails a shared resource and how the company plans to take up less of its users’ time. Helen Horstmann-Allen doesn’t have the typical response when you ask how she came to work for FastMail. After running email services Pobox and Listbox for nearly 20 years, she approached the independent email hosting platform about buying her company, thinking the company would be able to take her vision even further. FastMail’s values of privacy and owning one’s own data aligned with hers, and the two groups decided to merge platforms. Since then, the FastMail team has enhanced the products that Helen’s company brought in and has devised new ones that are changing the way people think about email. From the beginning, FastMail has been centered on making a quick and easy web email interface. Over time, the company’s vision has evolved beyond email to how email fits into the bigger picture of a customer’s workflow. Email is like an electronic cultural memory. It reminds teams of past interactions, drives future innovation and decisions, and keeps current projects on track. FastMail’s newest product, Topicbox, takes this cultural memory and preserves it by placing it in a shared environment from the start. With this in mind, Topicbox allows for the sharing of messages sent and received by anyone in the company and provides customizations to keep inboxes manageable. Message threads are assigned to different groups, and users can choose how many and what types of emails they receive from each group. In addition to its predicted success among established commercial and nonprofit organizations, Topicbox also resonates with smaller teams across a variety of markets, Helen told us. The notion of deprivatizing email can take a while to get used to, according to Helen, but clients overall see improvement in communication and workflows. In the never-ending quest to figure out how FastMail can make life easier for customers, Helen said the answers often come from everyday interactions with clients. Helen Horstmann-Allen joined FastMail in 2015, bringing Pobox and Listbox email services with her. One feature that came out of such conversations is the ability for people to customize their notifications on the mobile versions of FastMail’s products. The customer support team is intentionally overstaffed so team members can spend more time individually with clients. They’re constantly engaged in casual daily research on what makes customers tick and how they interact with the products. Not only a leader in the email industry by way of its high-performing products, FastMail also collaborates with other companies and organizations to make email better for everyone — regardless of the platform they’re using. “Our technical teams work in industry groups on email and calendar standards, in anti-spam and anti-abuse groups, and in the open-source community building email tools used by thousands of organizations to power their own products,” Helen said. As a foundational technology used by everyone with increasing volume, email demands new and improved ways to make it more efficient. Being part of building standards and open-source tools enables FastMail to take solutions beyond its customer base to understand and address concerns of all emailers. FastMail emphasizes reliability, security, and efficiency in its ad-free email, calendar, and contacts platform. The collaborative culture at FastMail lends itself to open-source work. From customer service representatives to software engineers, all voices are heard to get a holistic view of problems and potential solutions. In an effort to get past the mundane email communication to focus on innovation and mission-critical work, businesses are retreating from “always-on” communication tools and optimizing efficient workflows, according to Helen. Customer privacy is also a primary consideration when developing new product features and enhancements, Helen said. With security issues involving various free email and social media services making headlines, privacy is at the forefront of business and technical conversations in the email industry. Because the company has prioritized privacy since its founding more than 15 years ago, it’s in a position to stay ahead of those vulnerabilities. Like many other online providers, FastMail recently completed preparations for the GDPR (General Data Protection Regulation) — a European Union regulation intended to give citizens increased protection and control of their personal data — but it mostly involved creating documentation instead of changing business practices to come into compliance.
"""Module containing the class Quick, a text-based format to read a rxncon system.""" import re from typing import List, Optional from rxncon.input.shared.contingency_list import contingencies_from_contingency_list_entries, \ contingency_list_entry_from_strs, ContingencyListEntry from rxncon.core.reaction import reaction_from_str from rxncon.core.rxncon_system import RxnConSystem from rxncon.core.reaction import Reaction from rxncon.core.contingency import Contingency from rxncon.input.shared.reaction_preprocess import split_bidirectional_reaction_str class Quick: def __init__(self, rxncon_str: str) -> None: self.quick_input = rxncon_str.split('\n') self._rxncon_system = None # type: Optional[RxnConSystem] self._reactions = [] # type: List[Reaction] self._contingencies = [] # type: List[Contingency] self._contingency_list_entries = [] # type: List[ContingencyListEntry] self._parse_str() self._construct_contingencies() self._construct_rxncon_system() assert self._rxncon_system is not None @property def rxncon_system(self) -> RxnConSystem: assert self._rxncon_system is not None return self._rxncon_system def _parse_str(self) -> None: BOOL_REGEX = '^\<.+?\>$' for line in self.quick_input: reaction_string = line.split(';')[0].strip() contingency_strings = line.split(';')[1:] if reaction_string: if not re.match(BOOL_REGEX, reaction_string): self._add_reaction_from_string(reaction_string) self._add_contingency_list_entries(contingency_strings, reaction_string) def _add_reaction_from_string(self, reaction_str: str) -> None: reaction_strs = split_bidirectional_reaction_str(reaction_str) for rxn in reaction_strs: reaction = reaction_from_str(rxn) self._reactions.append(reaction) def _add_contingency_list_entries(self, contingency_strs: List[str], reaction_str: str) -> None: for cont in contingency_strs: cont = cont.strip() cont_type = cont.split()[0] modifier = cont.split()[-1] # If the verb is bidirectional, only apply the contingency to the forward direction. reaction_strs = split_bidirectional_reaction_str(reaction_str) entry = contingency_list_entry_from_strs(reaction_strs[0], cont_type, modifier) self._contingency_list_entries.append(entry) def _construct_contingencies(self) -> None: self._contingencies = contingencies_from_contingency_list_entries(self._contingency_list_entries) def _construct_rxncon_system(self) -> None: self._rxncon_system = RxnConSystem(self._reactions, self._contingencies)
Used the repair guide for replacing the upper case and purchased tools and an upper case to do the repairs. Went swimmingly until step 34--removing the display hinges. The screws were so tight that I twisted loose the handle of my new T6 screwdriver, then broke the tip of another T6 driver. So, frustrated, I gave up on replacing the whole upper case when I noticed how the trackpad could be replaced without removing the display, etc. So I returned the upper case to Ifixit (thanks guys), bought the trackpad and a pro driver set and dove back in. Voila! the trackpad went in pretty easily and now my MBP is up and running fine. A few caveats though: #1) when replacing the back, one of the long screws pierced the wiring to the DC-in board and I had to replace that too. Word to the wise--be sure that DC-in wiring harness is tucked out of the way when reassembling the logic board or that screw could pinch the wires! #2) when reattaching the ribbon-style cables to the keyboard (and trackpad) one needs to be careful to make sure the connection is secure--that is, all the way in. It is easy to leave it partially out and then you won't be able to start up once it's all back together. I found out the hard way and had to reopen and recheck my connections. Upside to this is that I can open up this baby blindfolded now (LOL). Thanks Ifixit for all the support.
# -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User class Account(models.Model): account_number = models.CharField(max_length=30) agency_number = models.CharField(max_length=30) created_at = models.DateTimeField(auto_now=True) status = models.BooleanField(default="") accountant = models.ForeignKey( User, on_delete=models.CASCADE ) class Meta: unique_together = ('accountant','account_number','agency_number') class Cards(models.Model): name = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=100) flag = models.CharField(max_length=100) status = models.BooleanField(default=True) def save(self, *args, **kwargs): cards = Cards.objects.filter(name=self.name) if len(cards) == 0: super(Cards, self).save(*args, **kwargs) def __str__(self): return self.name def __unicode__(self): return self.name class Meta: verbose_name = 'Card' verbose_name_plural = 'Cards'
You’ve made it. You’ve been accepted to the coding bootcamp of your dreams (hopefully, Claim Academy). You’ve committed your time, money and energy to launch your career in programming, IT, software development, or any of the myriad career paths you may choose after learning to code. Like anything in life, the best way to get the most out of a large investment is to prepare as best you can. In this article, we’re outlining 5 ways to prep for this life-changing learning opportunity. Though some of these suggestions may seem obvious, it’s important to consider the basics and take them seriously. Otherwise, you may be wasting your time. First and foremost… you must eliminate distractions. Weddings, parties and trips all sound like great ways to celebrate… but only after you walk away from the classroom with your certificate of completion. Prior to bootcamp, we advise you to clear your calendar as much as possible for the duration of your 12-week course. It’s hard to fit fun events into your weekends when you need that time to relax your mind, attend to chores at home, and, of course, complete any outstanding assignments. While looking at your calendar, consider your finances. Get everything in order so you don’t have to stress about paying bills or spending within budget while your focus is set primarily on learning dense coding concepts. It’s also helpful to communicate to your friends and family that you’ll be mainly “off grid” as you focus on learning as much as possible for 12 weeks. This will help prevent those tempting texts from your favorite people asking you to socialize when you should be sleeping (more on this later). Remember strolling into Office Depot or the Dollar Store as a 2nd-grader and picking out your favorite pens and pencils, notebooks, and crayons? I, for one, always looked forward to this inevitable summer errand (shoutout to pencil grips and Lisa Frank). Before you start bootcamp, reclaim that childlike enthusiasm and go get yourself some fresh supplies for the classroom. You’ll walk in to your first day feeling prepared and ready to take lots of notes. Speaking of note-taking… our instructors highly advise writing down notes in class to improve comprehension. Experts agree that writing things down is better than typing them out… that is, if you want to learn quickly. In our context, for example, drawing out a wireframe is WAY faster and easier to do on a piece of paper. If you’re looking for advice on how to choose a laptop for bootcamp, check out an older blog post here on the subject. Final suggestions for essential supplies include noise canceling headphones and a reusable water bottle. Of course, hydration is an everyday need, but it is especially important to hydrate while coding. It’s quite easy to forget to drink water when you’re bent over a laptop for hours on end. As obvious as it is, if you don’t already have them, start developing habits to stay in ship-shape so you can max out your attentiveness at bootcamp. To start, give your body the proper fuel it needs to perform. If you haven’t heard of superfoods, do a quick Google search. Blueberries, avocados, and Greek yogurt are just a few examples of healthy food that is easy to eat on the go. Speaking of food, our team works to make it easy for our students to hole up comfortably in the Claim Academy building to study or work. Our kitchenette area has a refrigerator, microwave, and coffee maker, so feel free to bring snacks, your favorite coffee creamer, or any other refreshments that make your time here grinding it out as pleasant as possible. Prepare to eat on-site as much as possible to save money and time. Meal planner apps like Eat This Much are helpful for managing cost; you can create a custom meal plans and adjust your weekly or daily budget to ensure you avoid spending too much on food, or worse, “stress-eating” junk food out of desperation and poor planning. If you’re somewhat of a night owl, remember this: you still need to get as close to 8 hours of sleep per night as humanly possible. Consistent deep sleep is crucial to prepare your body for full, productive days. Additionally, though you may normally get away with counting trips to the grocery store as “exercise”, once you’re enrolled in bootcamp, you’ll need to make a more intentional effort to carve time for physical activity. In order for you to be successful when you’re plugged in and coding for hours, you need to get up and move around periodically. Go outside and walk around the block, ride a bike, run a mile, lift weights or take an exercise class. Don’t run yourself down. You’ll lack focus, or worse, catch a seasonal cold. Speaking of focus… ever hear of the mind-body connection? We can’t emphasize this enough: it’s really important that you manage stress well in a bootcamp environment. This means that you must work to relieve your own stress while also protecting yourself from taking on your fellow students’ stress. On the subject of mental fitness, as you prepare to start your course, work to train your brain to learn in a circular fashion. This means revisiting topics over again that didn’t quite stick the first time you heard them. The Circular Learning Model is a helpful tool for making the most of your classroom and post-class study hours. Practice using this method with the pre-course work we provide. For any concepts that feel muddier than others, revisit that section and practice exercises over again. Never lose sight of the ultimate goal: job placement. You’re paying to become an all-star coder so you can score a well-paying job, right? Many graduates suggest joining Meetup groups in your local area. In her post on Medium, bootcamp grad Jessica Dembe explains, “I went to meetups and let it be known that I was a coding bootcamp student who is looking for a job. I mean, that is how I got the job that I have now! So definitely attend meetups and let people know about your story.” Think about how to describe yourself, or tell your story, in a compelling way. Then: practice, practice, practice. There are plenty of tools on the internet to lay the groundwork for exploring jobs both locally and in remote cities. For example, the review site SwitchUp offers a rolling list of jobs in tech that they keep updated. (SwitchUp also is a great resource for more helpful tips from bootcamp grads across the country; we highly recommend visiting their blog to explore these insights by topic). Other ways to prepare for selling yourself to future employers include setting up a LinkedIn profile — read through this stellar advice on getting the most out of LinkedIn — exploring various career paths in technology, and connecting with past graduates for coffee or lunch to chat about their experience getting hired after bootcamp. We’d be happy to facilitate these meetings if you wanted to connect with any of our graduates. In short, there are a ton of ways to prepare for bootcamp. Don’t neglect these 5 important “to-do’s”. Got any other ideas? Comment below!
__license__ = "Python" __copyright__ = "Copyright (C) 2007, Stephen Zabel" __author__ = "Stephen Zabel - sjzabel@gmail.com" __contributors__ = "Jay Parlar - parlar@gmail.com" """ From django snippets: http://www.djangosnippets.org/snippets/85/ """ from django.conf import settings from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect, get_host SSL = 'SSL' class SSLRedirect: def process_view(self, request, view_func, view_args, view_kwargs): if SSL in view_kwargs: secure = view_kwargs[SSL] del view_kwargs[SSL] else: secure = False if not secure == self._is_secure(request): return self._redirect(request, secure) def _is_secure(self, request): if request.is_secure(): return True #Handle the Webfaction case until this gets resolved in the request.is_secure() if 'HTTP_X_FORWARDED_SSL' in request.META: return request.META['HTTP_X_FORWARDED_SSL'] == 'on' return False def _redirect(self, request, secure): protocol = secure and "https" or "http" newurl = "%s://%s%s" % (protocol,get_host(request),request.get_full_path()) if settings.DEBUG and request.method == 'POST': raise RuntimeError, \ """Django can't perform a SSL redirect while maintaining POST data. Please structure your views so that redirects only occur during GETs.""" return HttpResponsePermanentRedirect(newurl)
What makes a great trail? On Thursday, June 9 at 7pm, the public is invited to meet with consultants to share their thoughts on the design of the proposed Manayunk Bridge trail. The design team, led by Whitman, Requardt and Associates, will host the meeting which will be held at the North Light Community Center, 175 Green Lane. As the design process moves forward, the team seeks to actively engage the public in shaping the look and feel of the trail. “We will meet with community groups and the public this spring and summer to get their ideas, share alternatives, and collaboratively develop the design,” said Jeff Riegner, leader of the WR&A Design Team. The meeting on June 9 is the first public meeting held by the group for this purpose. The walking and bicyclingtrail across the iconic Manayunk Bridge will connect Lower Merion Township’s Cynwyd Heritage Trail, currently under construction, with the site of a former SEPTA station at Dupont and High Streets in Manayunk. Future phases will extend the trail to the Ivy Ridge Station and beyond, eventually connecting to the Schuylkill River Trail at Shawmont Avenue. The design must be complete by fall 2012 to meet the terms of the $1.3 million grant PennDOT announced in January for construction. Partial funding for the final design of the bridge has been provided by the William Penn Foundation. The trail is heralded by community members and municipalities alike as a landmark project with the potential to be a pivotal link in the Philadelphia trail network. It is also recognized as a true collaborative effort, with project partners including Philadelphia Parks and Recreation, Philadelphia Streets Department, Delaware Valley Regional Planning Commission, Manayunk Development Corporation, Lower Merion Township, the Bicycle Coalition of Greater Philadelphia, and SEPTA.