text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Blog about technology, media and other interesting tidbits.
Note that you'll find multiple sources of the Netron Project on the net. I found 3 different places where I can download the toolkit.
I believe the third one is the latest and supported. Netron also has a cousin for WPF diagramming called Unfold which is also available from.
The download comes with the Lithium tree control which is a perfect match for our methods tree. Combine that with the XML Visualizer (Also included with the download) by Howard Van Rooijen and my work is almost done. All I need to do it to generate the XML file for the method tree. Here is how it will work:
To generate the XML file, I'll again use IronPython and the .NET XML support. Remember we have the drawMethodTree() function in our python script which we were using to generate the GLEE graph. As we are no longer using GLEE, therefore I replaced it to generate XML elements.
As we any other new library, we need to add the reference and import the namespace members.
>>> clr.AddReference("System.Xml")
>>> from System.Xml import *
>>> from System.IO import *
>>> from System.Text import *
The code to create an XML file using FileStream is pretty simple and self-explanatory.
>>> fs = FileStream("methods.xml", FileMode.Create)
>>> w = XmlTextWriter(fs, Encoding.UTF8)
>>> w.WriteStartDocument()
>>> w.WriteStartElement("methods")
>>> drawMethodTree(pMet, 0, w, 1)
>>> w.WriteEndElement()
>>> w.WriteEndDocument()
>>> w.Flush()
>>> fs.Close()
The drawMethodTree() now takes in XMLTextWriter as argument and writes the child elements.
>>> def drawMethodTree(mDef, level, writer, callSeq):
>>> if isinstance(mDef, MethodDefinition):
>>> msg = '\r\n>>> %d - Parent Method: %s' % (level, mDef)
>>> print msg
>>> writer.WriteStartElement(mDef.DeclaringType.Name + '.' + mDef.Name)
>>> for ins in mDef.Body.Instructions:
>>> if isValidInstruction(ins):
>>> print ins.OpCode.Name
>>> msg = '\r\n' + ins.Operand.ToString()
>>> nextLevel = level + 1
>>> callSeq = callSeq + 1
>>> drawMethodTree(ins.Operand, nextLevel, writer, callSeq)
>>>
>>> writer.WriteEndElement()
This generates the following XML file (considering that we are using the original .NET solution we started with):
<?xml version="1.0" encoding="utf-8"?>
<methods>
<MainCase.PublicMethod>
<MainCase.PrivateMethod />
<SecondCase.Help>
<SecondCase.HelpMeToo />
</SecondCase.Help>
</MainCase.PublicMethod>
</methods>
And loading this XML file through the XML Visualizer gives us the nice clean method tree shown below.
Cool? I know :)
What's next? I'll try to run some other code through this to check if it still works. Any suggestions/comments are most welcome.
Download Complete Source
Download Binary (Extract and run FrontEnd.exe - You need to have methods.xml in the same directory)
View Python Script | http://weblogs.asp.net/nleghari/archive/2007/04/03/method-tree-visualizer-fun-with-ironpython-cecil-and-netron-graph-part-iii.aspx | crawl-002 | refinedweb | 425 | 60.82 |
Trying to read my RFID MFRC522 using a Mifare blue tag and it is not working. Wondering if i could get any help on this as when i put the tag to read it doesn’t show up as quick?
using:
- Comments are not for extended discussion; this conversation has been moved to chat. – Ghanima♦ Mar 29 at 14:47
Question
I have successfully installed mfrc522 using pip3. I created a reader, wrote something to a tag, and then read back, without any problem.
Notes
- I am using Rpi4B buster release 2020feb13, preinstalled python 3.7.3.
- pip3 installs mfrc522 0.0.7 in /usr/local/lib/python3.7/dist-packages …
- pip3 installs spidev 3.4 and GPIO 0.7 in /usr/lib/python3/dist-packages …
-, …
Long Answer
- The OP used Rpi3 NOOB python 2.7, and installed himself SpiPy, SpiDev for testing.
- I think python 2.7 is a bit out of date. So I am repeating the OP’s situation but instead using Rpi4B buster 2020feb13 (full version image), with the following buster preinstalled software:
(a) python 3.7.3
(b) thonny IDE
(c) spiDev
(d) pip3
- I am using pip3 to install the MFRC522 python library, which includes the following two python3 programs:
(a) mfrc522.py (about 400 lines)
(b) simpleMFRC.py (about 100 lines)
- I am using the RFID/NFC module already tested OK using libnfc-1.7.1 in I2C configuration (Appendix A).
- I am using pip3 to install mrfc522, RPi.GPIO, and spidev in the following directory (Appendix B). I am not sure if the above GPIO and spidev modules are the same or different from the buster’s corresponding preinstalled programs.
/usr/local/lib/python3.7/dist-packages
- I am using the built-in SPI interface /dev/spidev0.0 and /dev/spidev0.1 (Appendix C)
- I used python3 shell to import SimpleMFRC522 from mfrc522, and found creating a reader object OK. (Appendix D).
from mfrc522 import SimpleMFRC522
reader = SimpleMFRC522()
- I read MFRC522-python/mfrc522/SimpleMFRC522.py/ – GitHu 2019mar26 saying the following:
@death-droid Improve compatibility with Python 3 – 2019mar26
So I guess the earlier versions of SimpleMFRC522 were not very compatible to python3. I was wondering if my pip3 installed stuff is more or less updated than the OP’s corresponding software using Git Clone. I guess I better download the most updated versions of mfrc522, SimpleMFRC522, and the demo/test red/write tag programs and freeze them for later testing.
- Now have tidied up the different version of the four main programs mfrc522.py, samplemfrc522py, read.py, and write.py, and put them in a penzu reading log file. Next step is to skim the two big files to get a rough picture of what is going on.
- Now I have skimmed the two main programs mrfc522.py and simpleMFRC522.py. I surprisingly found the program structure is very simple. So it should not not that difficult to debug and expand. The penzu reading log is here:
- Now I have tried the SPI loopback test and found it OK. (Appendix E)
- I tried to repeat the OP is problem, ie, raed a tag. Still no luck, the program hanged. Because I already double checked that the NFC module can read OK the same tag using libbnfc-1.7.1 I2C mode, and SPI loopback at 50kHz is OK. So the problem is likely at the SimpleMFRC522 side. Next step is to debug Read.py, SimpleMFRC522.py and the MFRC522.py library. (Appendix J)
- Now I am checking the schematic of [another similar] nfc module to make sure that my guess of the IRQ and RST wiring is correct, ie, no need to connect these two pins to Rpi. This is verified by the success of libnfc-1.7.1 I2C read card without connect the RST and IRQ pins. Perhaps I can ping the module to make sure SPI Clk, Mosi, and Miso are working OK (the previous SPI loopback only tests 50kHz and only MOSI and Miso, CS is not tested. (Appendix J)
- I read the pn532 datasheet that the max SPI speed is 5MHz, so it should be OK to set SPI speed to 1MHz, 500kHz, or 100kHz. (Appendix J)
/
(21) Amazon AZDelivery RC522 RFID Kit x 3 for Arduino and Rpi – £9.5
(22) AZDelivery RFID Kit RC522 Reviews
(23) TaoBao Risym MFRC-522 RC522 RFID Reader – ¥12
(24) MFRC522 MIFARE NTAG FrontEnd R3.9 Datasheet — NXP 2016apr27
(25) Mario Gómez MFRC522-python 2018mar26 Main Page
(26) Mario Gómez MFRC522-python 2018mar26 Read Me
(27) Mario Gómez MFRC522-python 2018mar26 Zip Download
(28) Spidev 3.4 User Guide – PyPi 2020feb19
(29) RPi.GPIO 0.7.0 pip install RPi.GPIO
(30) Pat-odoo TwoRC522_RPi2-3 – GitHub
(31) Pat-odoo TwoRC522_RPi2-3 – PDF
(32) SPI-Py
(48) Ondryaso/pi-rc522 Rpi python library for SPI RFID RC522 module (Add support for interrupt driven tag detection) Latest commit
(49) Ondryaso rc-522 library listing
(50) MIFARE Classic 1K Smart card IC MF1S50YYX_V1 Datasheet R3.2 — NXP 2018may23
(51) MFRC522 Antenna Design Application Note144512 – NXP
(52) Mario Gomez MFRC522 Lirary python3 Incompatibility Problem Forum Discussion
(53) barni2000/MFRC522-python3 Module MFRC522 modified for python 3, (seems not complete)
to continue, …
Appendices
Appendix A – The PN532 NFC/RFID Module V3 being tested
Reference: nfclib v1.1.7 PN532 NFC Module Testing
Appendix B – Mfrc522 software (including SPIdev and GPIO) setup record
Appendix C – Minimal configuration of SPI and I2C channels for testing the PN532 module
Appendix D – PiMyLifeUp Gus SimpleMFRC522 Library
Appendix E – SPI Loopback Test
Update 2020apr30hkt1826
Many thank for the OP pointing out a typo. If MOSI is not connected to MISO, then the out would be all zeros!
Appendix F – MFRC522 Directory Listing
Appendix G – AZDelivery RFID Kit Reviews
AZDelivery 3 x RFID Kit RC522 with Reader, Chip and Card for Arduino and Raspberry Pi including E-Book! – £9.5
AZDelivery 3 x RFID Kit RC522 Reviews
Erich Eichinger – Reviewed 12 September 2019
German Quality with significantly wider sensor range than Chinese clones I had some cheap Chinese RC522 clones with a very limited range (only 1-2 mm). Thought I’d try German Quality and was not disappointed. Those RC522 are still cheap enough but detect a tag up to 1.5cm distance which was enough for my purpose.
Jürgen L. Universal and affordable 23 February 2020
With the software you have to trick a little, the instructions available on the net are somewhat outdated or refer to a particular Raspi. But if you have a little programming knowledge, you can quickly customize the Python program yourself.
Rene Winkler – Works fine, but you should use SPI 3 March 2020
The module supports SPI (preconfigured), UART and I2C. The interface must be selected via configuration pins. However, there is no pull up/down for this module. According to the data sheet you would have to pull from high to low for the UART Pin EA. In this case, however, it would mean separating a trace through and pulling a wire bridge to GND.
I’m using the module via SPI on a Raspberry Pi Zero with Python for a kids music box.
The Python library, which I first found for the module, was unfortunately out of date and did not fit the SPI library. Since something had changed in the parameters for SPI read and Write. But the module can’t do anything for that.
Appendix F – PiMyLifeUp SimpleMFRC522.py and Read.py by Simon Monk
# PiMyLifeUp MFRC522 Python Library, Setup, and Example # # pimylifeup/MFRC522-python #- python/blob/master/mfrc522/SimpleMFRC522.py # Code by Simon Monk from . import MFRC522 import RPi.GPIO as GPIO class SimpleMFRC522: READER = None KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF] BLOCK_ADDRS = [8, 9, 10] def __init__(self): self.READER = MFRC522() def read(self): id, text = self.read_no_block() while not id: id, text = self.read_no_block() return id, text def read_id(self): id = self.read_id_no_block() while not id: id = self.read_id_no_block() return id def read_id_no_block(self): (status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL) if status != self.READER.MI_OK: return None (status, uid) = self.READER.MFRC522_Anticoll() if status != self.READER.MI_OK: return None return self.uid_to_num(uid) def read_no_block(self): ) data = [] text_read = '' if status == self.READER.MI_OK: for block_num in self.BLOCK_ADDRS: block = self.READER.MFRC522_Read(block_num) if block: data += block if data: text_read = ''.join(chr(i) for i in data) self.READER.MFRC522_StopCrypto1() return id, text_read def write(self, text): id, text_in = self.write_no_block(text) while not id: id, text_in = self.write_no_block(text) return id, text_in def write_no_block(self, text): ) self.READER.MFRC522_Read(11) if status == self.READER.MI_OK: data = bytearray() data.extend(bytearray(text.ljust(len(self.BLOCK_ADDRS) * 16).encode('ascii'))) i = 0 for block_num in self.BLOCK_ADDRS: self.READER.MFRC522_Write(block_num, data[(i*16):(i+1)*16]) i += 1 self.READER.MFRC522_StopCrypto1() return id, text[0:(len(self.BLOCK_ADDRS) * 16)] def uid_to_num(self, uid): n = 0 for i in range(0, 5): n = n * 256 + uid[i] return n # *** mfrc522 Installation and Example Code **************************************************** # A python library to read/write RFID tags via the budget MFRC522 RFID module. This code was published in relation to a blog post and you can find out more about how to hook up your MFRC reader to a Raspberry Pi there. Installation Until the package is on PyPi, clone this repository and run python setup.py install in the top level directory. Example Code The following code will read a tag from the MFRC522 from time import sleep import sys from mfrc522 import SimpleMFRC522 reader = SimpleMFRC522() try: while True: print("Hold a tag near the reader") id, text = reader.read() print("ID: %s\nText: %s" % (id,text)) sleep(5) except KeyboardInterrupt: GPIO.cleanup() raise .END
Appendix G – Spidev 3.4 User Guide – PyPi
Spidev 3.4 pip install spidev – Python bindings for Linux SPI access through spidev – PyPi 2020feb19
[a] xfer(list of values[, speed_hz, delay_usec, bits_per_word])
Performs an SPI transaction. Chip-select should be released and reactivated between blocks. Delay specifies the delay in usec between blocks.
[b] xfer2(list of values[, speed_hz, delay_usec, bits_per_word])
Performs an SPI transaction. Chip-select should be held active between blocks.
[c] xfer3(list of values[, speed_hz, delay_usec, bits_per_word])
Similar to
xfer2 but accepts arbitrary large lists. If list size exceeds buffer size (which is read from
/sys/module/spidev/parameters/bufsiz), data will be split into smaller chunks and sent in multiple operations.
Appendix H – MRFC532 SpiDev LoopBack Test and Wiring Length Limit
Appendix I – Mario Gomez MRFC522 Wiring Diagram and Software Requirements 2014
Appendix J -Long Answer Points 12, 13, 14
Appendix H – Mfrc522 Self Test Function
Now I am write test functions to make sure my module is more or test working OK.
Appendix I – Writing MFRC522 Commands in python3
Now I am reading the datasheet to learn how to write MFRC522 commands in python 3. I have written a python execMfrc522Command function and can now do ‘SoftReset” and ‘Idle’ with the two statements below:
execMfrc522Command('CommandReg', 'Reset') execMfrc522Command('CommandReg', 'Idle')
Appendix J – Adding Python 3 Timer and Interrupt functions to Mario Gomez’s MFRC522 Python 2 Library
End of Answer
——————————-
Chat Record
Discussion on question by 627117717.pr: Trying to code a RFID tag to a MFRC522 chip using raspberry pi but it is not allowing me to read it
Imported from a comment discussion on raspberrypi.stackexchange.com/questions/109 | https://tlfong01.blog/2020/04/14/mfrc522-notes-3/ | CC-MAIN-2020-40 | refinedweb | 1,894 | 57.57 |
OpenCV
We’re trying to detect a green laser and having problems. One problem is that the laser is so goddamn bright that it is saturating the camera. Maybe that be nice except that the ligthbulbs in the background are doing that too.
Some useful little mini programs:
Capture and image and save it.
import cv2 import numpy as np import time cap = cv2.VideoCapture(0) time.sleep(1) print cap.get() _, frame = cap.read() cv2.imwrite('myimage.png',frame)
This let’s us poke around on an image and print out the data corresponding to a point.
import cv2 import numpy as np import time cap = cv2.VideoCapture(0) time.sleep(1) _, frame = cap.read() def checkStuff(event,x,y,flags,param): print "yo" print event if event == cv2.EVENT_LBUTTONDBLCLK: print frame[x,y,:] if event == 0: print frame[y,x,:] cv2.namedWindow('frame') cv2.imshow('frame',frame) cv2.setMouseCallback('frame',checkStuff) cv2.waitKey(0) cv2.destroyAllWindows()
The HSV decomposotion from the tutorials is ok, but not cutting the mustard.
Maybe something more autocorrelationy?
So I get the python side, and I was giving the C side a go.
Apparently the recommended way is to use Cmake to make your projects. I don’t like it.
Kind of fell off the bandwagon on this one. Would be better to actually get something working in python before going onto this. | https://www.philipzucker.com/opencv/ | CC-MAIN-2021-39 | refinedweb | 232 | 69.58 |
Page 1
Import and nuclear size
Orna Cohen-Fix
Laboratory of Molecular and Cellular Biology, NIDDK, National Institutes of Health, Bethesda,
Maryland 20892, USA. ornacf@helix.nih.gov
Abstract
The size of a cell’s nucleus is usually proportional to the size of the cell itself. How are the two
linked? The answer lies, at least in part, in the import of one or more cytoplasmic cargoes into the
nucleus.
It is rare to come across a basic question in cell biology that is almost entirely unresolved,
but what determines the size of a cell or of an organelle is one such question1. Does the cell
use a ‘molecular ruler’ to directly assess the size of its compartments, or does it use a
surrogate, such as protein concentration, to determine how big its structures are? Reporting
in Cell, Levy and Heald2 provide evidence that at least partly answers these questions in
regard to the size of the cell nucleus.
Regulation of nuclear size is perhaps one of the most striking, and enigmatic, examples of
organelle-size control, because it is tightly linked to cell size3. Indeed, there is a constant
ratio between nuclear and cell volumes (the N/C volume ratio), and deviations from it are
associated with disease4. But how is this ratio regulated? To address this question,
researchers have attempted5,6 to perturb the N/C volume ratio in yeast, but to no avail:
neither nuclear-DNA content, nor varied growth conditions, nor drug treatments, could alter
the ratio.
Another question is what aspect of cell volume affects nuclear size: is it the cell’s entire
volume; the volume of only the cytoplasm; or perhaps that of another organelle? In
multinucleated fission yeast, the size of each nucleus is proportional to its surrounding
cytoplasm6, but how the cytoplasm affects nuclear size, if at all, has remained unknown.
Levy and Heald2 study regulation of nuclear size in two related frog species — Xenopus
laevis and Xenopus tropicalis — that differ in both body size and the number of
chromosome copies per cell (ploidy). Xenopus laevis is larger and its cells are tetraploid,
whereas X. tropicalis is smaller and its cells are diploid. The two species also differ in
another aspect: the cells and nuclei of X. laevis are larger.
An advantage of Xenopus as an experimental model is that its nuclei can be assembled in a
test tube using the chromatin (DNA–protein complexes) and extracts of its egg cytoplasm.
This allowed Levy and Heald2 to ask, what is the main determinant of nuclear size in
Xenopus: the DNA or a cytoplasmic factor?
The authors added sperm chromatin from either X. laevis or X. tropicalis to egg extracts
from either X. laevis or X. tropicalis (Fig. 1a). They found that, although both extracts can
trigger assembly of the nuclear envelope around the chromatin, the X. laevis extract forms
larger nuclei than the X. tropicalis extract, regardless of the DNA used. This indicates that
one or more cytoplasmic factors determine nuclear size.
NIH Public Access
Author Manuscript
Nature. Author manuscript; available in PMC 2012 October 12.
Published in final edited form as:
Nature. 2010 November 25; 468(7323): 513–516. doi:10.1038/468513a.
NIH-PA Author Manuscript
NIH-PA Author Manuscript
NIH-PA Author Manuscript
Page 2
A hint of the underlying difference between the extracts from the two frog species came
from the authors’ analyses of nuclear import — the process by which proteins are
transported into the nucleus7. Both the rate of nuclear import and the maximum size of the
imported cargo were greater in the nuclei reconstituted with X. laevis extracts. The capacity
for nuclear import therefore might be a regulator of nuclear size.
The two extracts differed in two proteins that mediate nuclear import — importin-α and
Ntf2. In X. laevis extracts, the levels of importin-α were higher and those of Ntf2 lower than
in X. tropicalis extracts. Indeed, when Levy and Heald added active (phosphorylated)
importin-α to X. tropicalis extracts they observed an increase in nuclear size. The role of
Ntf2 in regulating nuclear size is less straightforward. Nonetheless, X. tropicalis extracts
supplemented with both active importin-α and an inhibitor of Ntf2 activity form nuclei that
are similar in size to those formed in X. laevis extracts2 (Fig. 1b).
That nuclear import affects nuclear size is perhaps not surprising, as a previous paper8
showed that, in the absence of import, the nuclear envelope — which forms around the
chromosomes at the end of mitotic cell division — fails to expand. But in showing that, at
least in vitro, import is a limiting factor for nuclear growth, Levy and Heald’s report
provides a specific step that could be targeted for regulating nuclear size in vivo.
Which of the cargoes carried by importin-α are crucial for controlling nuclear size? From an
engineering standpoint, enlarging a structure could require an extension of its underlying
framework. Whether the nucleus has an internal framework — the ‘nuclear matrix’ — is
debatable, but there is no doubt that the nuclear lamina serves as a framework supporting the
nuclear envelope. Indeed, Levy and Heald found that the addition of lamin B3, a component
of the nuclear lamina, to X. tropicalis extracts resulted in increased nuclear size. Thus,
nuclear import may regulate nuclear size through controlling the availability of nuclear-
lamina components.
Neither yeast nor plants have lamins, which raises the question of how general is regulation
of nuclear size by lamin import. Whether nuclear import itself affects nuclear size in yeast is
unresolved5,6, although at least one study6 found that a prolonged inhibition of nuclear
export increases nuclear volume by 50%. It could be, therefore, that nuclear size in yeast and
plants also depends on nuclear import, not of lamin but of some other cargo.
The cell-free system Levy and Heald describe is remarkably useful for identifying proteins
and processes that affect nuclear size. The next step will be to determine how such processes
affect nuclear size within the cell, and whether they contribute to the N/C volume ratio.
Levy and Heald did address this question by injecting importin-α into developing X. laevis
embryos. They observed a transient increase in nuclear size in early stages of development,
but whether cell volume is affected in any way remains unknown.
When considering the scaling of nuclear size with cell size, one must take into account the
increase not only in volume, but also in surface area4. An influx of material through nuclear
import could lead to physical stress that signals for an increase in the surface area of the
nuclear envelope. Alternatively, because the nuclear membrane is continuous with that of
another organelle, the endoplasmic reticulum, the cell might regulate nuclear size by
controlling the amount of endoplasmic-reticulum membrane that is allocated to the nucleus.
Nevertheless, geometry tells us that surface area increases at a slower rate than volume
(surface area is a function of the radius squared, whereas volume is a function of the radius
cubed). Intriguingly, a recent study9 on the scaling of transcription with cell size in yeast
revealed that, whereas expression of most genes increases in proportion to the increase in
cell size, the expression of genes encoding cell-surface proteins lags behind. How this size-
Cohen-Fix
Page 2
Nature. Author manuscript; available in PMC 2012 October 12.
NIH-PA Author Manuscript
NIH-PA Author Manuscript
NIH-PA Author Manuscript
Page 3
sensing mechanism works isn’t clear, but it would be interesting to examine whether the
abundance of proteins associated with nuclear-envelope expansion is also ‘size-sensitive’.
Levy and Heald’s results2 uncover a process that affects nuclear size, providing a glimpse
into a mechanism that may couple nuclear volume to cell volume. To fully understand the
N/C volume ratio, researchers need biological tools — mutants and/or RNAi knockdowns
— that perturb this ratio. So to anyone who thinks that all the interesting basic cell-biologi
cal questions have been answered, here is one that is still wide open.
References
1. Chan Y-HM, Marshall WF. Organogenesis. 2010; 6:88–96. [PubMed: 20885855]
2. Levy DL, Heald R. Cell. 2010; 143:288–298. [PubMed: 20946986]
3. Wilson EB. The Cell in Development and Heredity. 1925 (Macmillan).
4. Webster M, Witkin KL, Cohen-Fix O. J. Cell Sci. 2009; 122:1477–1486. [PubMed: 19420234]
5. Jorgensen P, et al. Mol. Biol. Cell. 2007; 18:3523–3532. [PubMed: 17596521]
6. Neumann FR, Nurse P. J. Cell Biol. 2007; 179:593–600. [PubMed: 17998401]
7. Terry LJ, Shows EB, Wente SR. Science. 2007; 318:1412–1416. [PubMed: 18048681]
8. Newport JW, Wilson KL, Dunphy WG. J. Cell Biol. 1990; 111:2247–2259. [PubMed: 2277059]
9. Wu C-Y, Rolfe PA, Gifford DK, Fink GR. PLoS Biol. 2010; 8:e1000523. [PubMed: 21072241]
Cohen-FixPage 3
Nature. Author manuscript; available in PMC 2012 October 12.
NIH-PA Author Manuscript
NIH-PA Author Manuscript
NIH-PA Author Manuscript
Page 4
Figure 1. The cytoplasm regulates nuclear size
a, To examine factors affecting nuclear size, Levy and Heald2 mixed sperm chromatin from
either Xenopus laevis (X.l.) or X. tropicalis (X.t.) with cytoplasmic extracts from the eggs of
either X. laevis or X. tropicalis. They find that, regardless of the chromatin used, X. laevis
extracts promote formation of large nuclei, whereas X. tropicalis extracts promote formation
of smaller nuclei. (The drawings of X. laevis and X. tropicalis are to scale). b, Two proteins,
importin-α and Ntf2, account for the differences between the X. laevis and X. tropicalis
extracts: addition of importin-α and inhibition of Ntf2 activity in X. tropicalis extracts lead
to formation of larger nuclei.
Cohen-Fix Page 4
Nature. Author manuscript; available in PMC 2012 October 12.
NIH-PA Author Manuscript
NIH-PA Author Manuscript
NIH-PA Author Manuscript | http://www.researchgate.net/publication/49635577_Cell_biology_Import_and_nuclear_size | CC-MAIN-2015-14 | refinedweb | 1,634 | 56.05 |
Updated - 2017/06/27 Added another reference and some editing.
This topic has been covered by others as well...
We all agree the Geonet code editor is horrible... but it has been updated.
Here are some other tips.
If you can't see it, you didn't select it
More...Syntax highlighter ,
Your code can now be pasted in and highlighted with the language of your choice .........
Your code should be highlighted something like this ............
--- Python -----------------------------
import numpy as npa = np.arange(5)print("Sample results:... {}".format(a))
--------------------------------------------
Now the above example gives you the language syntax highlighting that you are familiar with..
Alternatives include just using the HTML/XML option
-----HTML/XML ---------------------
# just use the HTML/XML option.. syntax colors will be removedimport numpy as npa = np.arange(5)print("simple format style {}".format(a))simple format style [0 1 2 3 4]
NOTE: you can only edit code within this box and not from outside!
HTML editing tips:....
Here is a simple script with code and results published in columns (2 columns * 1 row). If the contents are wider than the screen, the scroll-bar will be located at the end of the document rather than attached to each table (except for iThingys, then just use swipe).
>>> import numpy as np>>> a = np.arange(5)>>> print("Sample results:... {}".format(a))>>> # really long comment 30 |------40 | -----50 | -----60 | -----70 | ---- 80|
Sample results:... [0 1 2 3 4]>>> # really long comment 30 |------40 | -----50 | -----60 | -----70 | ---- 80|
Leave space after a table so you can continue editing after the initial code insertion.
It is often hard to select the whitespace before or after a table and you may need to go to the html editor < > just above the More toggle
Before code tip: try to keep your line length <70 characters
# -*- coding: UTF-8 -*-""":Script: demo.py:Author: Dan.Patterson@carleton.ca:Modified: 2016-08-14:Purpose: none:Functions: help(<function name>) for help:----------------------------: _demo - This function ...:Notes::References:"""#---- imports, formats, constants ----import sysimport numpy as npfrom textwrap import dedentft = {'bool':lambda x: repr(x.astype('int32')), 'float': '{: 0.3f}'.format}np.set_printoptions(edgeitems=10, linewidth=80, precision=2, suppress=True, threshold=100, formatter=ft)script = sys.argv[0]#---- functions ----def _demo(): """ :Requires: :-------- : :Returns: :------- : """ return None#----------------------if __name__ == "__main__": """Main section... """ #print("Script... {}".format(script)) _demo()
Some space for editing after should be left since positioning the cursor is difficult after the fact.
Output options
Sample output with a graph
Option 0: 1000 points[[ 2. 2.][ 3. 3.]] extents.... snipTime results: 1.280e-05 s, for 1000 repeats
point_in_polygon.png
So there has been some improvement.
Again...
You just have to remember that to edit code...
you have to go back to the syntax highlighter.
You can't edit directly on the page.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in. | https://community.esri.com/t5/python-blog/code-formatting-the-basics/ba-p/893958 | CC-MAIN-2021-21 | refinedweb | 485 | 68.67 |
Python bcrypt tutorial
Python bcrypt tutorial shows how to hash passwords in Python with the bcrypt library. It defines basic terms including encryption, hashing, and salt.
Python
bcrypt module is a library for generating strong hashing values
in Python. It is installed with
pip install bcrypt command.
Encryption
Encryption is the process of encoding a message or information in such a way that only authorized people can read it with a corresponding key and those who are not authorized cannot. The intended information or message, referred to as plaintext, is encrypted using an encryption algorithm – a cipher – generating ciphertext that can be read only if decrypted. Encryption is a two-way function. When we encrypt something, we're doing so with the intention of decrypting it later. Encryption is used to protect data when transmitted; e.g. in a mail communucation.
Hashing
Hashing is the process of using an algorithm to map data of any size to a fixed length. This is called a hash value. Whereas encryption is a two-way function, hashing is a one-way function. While it's technically possible to reverse-hash a value, the computing power required makes it unfeasible. While encryption is meant to protect data in transmit, hashing is meant to verify that data hasn't been altered and it is authentic.
Passwords are not stored as plaintext in databases but in hashed values.
Salt
Salt is a fixed-length cryptographically-strong random value that is added to the input of hash functions to create unique hashes for every input. A salt is added to make a password hash output unique even for users adopting common passwords.
The bcrypt hashing function
The bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher. The bcrypt function is the default password hash algorithm for OpenBSD. There are implementations of bcrypt for C, C++, C#, Java, JavaScript, PHP, Python and other languages.
The bcrypt algorithm creates hash and salt the password for us using strong cryptography. The computation cost of the algorithm is parametised, so it can be increased as computers get faster. The computation cost is called work factor or cost factor. It slows down the hashing, making brute force attempts harder and slower. The optimal cost factor changes over time as computers get faster. The downside of a high cost factor is increased load on system resources and affecting user experience.
Python bcrypt create hashed password
In the next example, we create a hashed password.
#!/usr/bin/env python3 import bcrypt passwd = b's$cret12' salt = bcrypt.gensalt() hashed = bcrypt.hashpw(passwd, salt) print(salt) print(hashed)
The example creates a salt and a hashed password with bcrypt.
import bcrypt
We import the
bcrypt module.
salt = bcrypt.gensalt()
A salt is generated with the
gensalt() function.
hashed = bcrypt.hashpw(passwd, salt)
A hashed value is created wiht
hashpw() function, which
takes the cleartext value and a salt as parameters.
$ python first.py b'$2b$12$mwSIOyxLJid1jFLgnU0s0.' b'$2b$12$mwSIOyxLJid1jFLgnU0s0.7pmzp8Mtx.GEO30x0AbI2v8r2sb98Cy' $ python first.py b'$2b$12$MgGs11HIXGkg1Bm1Epw0Du' b'$2b$12$MgGs11HIXGkg1Bm1Epw0Du20TV8ppi2Latgq7kKng8UjM5ZFWKKeS'
Note that the salt is the first part of the generated hash value. Also note that each time a unique salt and hashed values are generated.
Python bcrypt check password
The following example checks a password against a hashed value.
#!/usr/bin/env python3 import bcrypt passwd = b's$cret12' salt = bcrypt.gensalt() hashed = bcrypt.hashpw(passwd, salt) if bcrypt.checkpw(passwd, hashed): print("match") else: print("does not match")
A password is checked with the
checkpw() function.
$ python check_passwd.py match
This is the output.
Python bcrypt cost factor
The cost factor increases security by slowing down the hashing.
#!/usr/bin/env python3 import bcrypt import time passwd = b's$cret12' start = time.time() salt = bcrypt.gensalt(rounds=16) hashed = bcrypt.hashpw(passwd, salt) end = time.time() print(end - start) print(hashed)
We set the cost factor with the
rounds parameter to sixteen.
We measure the time to generate the passowrd hash.
$ cost_factor.py 4.268407821655273 b'$2b$16$.1FczuSNl2iXHmLojhwBZO9vCfA5HIqrONkefhvn2qLQpth3r7Jwe'
It took more that four seconds to generate the hash value with the specified cost factor.
In this tutorial, we have used the Python bcrypt module to generate password hashes.
You might also be interested in the following related tutorials: Python tutorial, Python list comprehensions, or list all Python tutorials. | http://zetcode.com/python/bcrypt/ | CC-MAIN-2019-26 | refinedweb | 729 | 58.79 |
Linked List
A linked list is a type of linear data structure that include a series of inter connected nodes. The elements in Linked list are not stored at an adjacent location and they linked using pointers.
Basically, a linked list is a sequence of data structures, that are connected with one another via links.
A linked list is a sequence of links that contain items. Each link includes a connection to another link. The Linked list is the next most-used data structure following the array.
Why Linked List?
Arrays can be used to store linear data of similar types, but arrays have the following limitations.
1) The array size is fixed: We must know in advance the upper limit on the number of elements.
2) Inserting a new element in an array of elements is expensive in terms of time consumption. This is because the room has to be built for the new elements and all the following elements have to be shifted.
A linked list is a random sequence of data structures, which are connected together via links and contain items. Each link of the element contains a connection to another link.
Following are the important terms in Linked List Data Structures:
- Link − Every link of a linked list can hold data called an element.
- Next − All the link of a linked list contains a link to the next link called Next.
- LinkedList − A Linked List holds the connection link to the first link called First.
Representation:
A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list is empty, then the value of the head is NULL.
Each node in a list consists of at least two parts:
1) data
2) Pointer (Or Reference) to the next node
Types of Linked List
Following are the various.
Linked List Complexity
Time Complexity
Linked List Applications
- Dynamic memory allocation
- Hash tables, Graphs
- Implemented in stack and queue
- In undoing functionality of the software
Basic Operations
Following are the basic operations supported by a list.
- Insertion − Appends an element at the beginning of the list.
- Deletion − Removes an element at the beginning of the list.
- Display − Presents the complete list.
- Search − Examines an element using the given key.
- Delete − Destroys an element using the given key.
Advantages over arrays
1) Dynamic size
2) Ease of insertion/deletion
Drawbacks:
1) Random access is not possible: We have to access elements starting from the first node of the list. So we cannot do a binary search with linked lists efficiently with its default implementation.
2) Additional memory space to hold a pointer is needed with each element of the list.
3) Not cache-friendly. Since array components are contiguous locations, there is the locality of reference which is not present in the case of linked lists.
SYNTAX:
#include <bits/stdc++.h> using namespace std; int main() { class Node { public: int data; Node * next; }; } | https://edusera.org/linked-list-in-c/ | CC-MAIN-2022-40 | refinedweb | 498 | 64.81 |
]
STRCPY(3) OpenBSD Programmer's Manual STRCPY(3)
NAME
strcpy, strncpy - copy strings
SYNOPSIS
#include <string.h>
char *
strcpy(char *dst, const char *src);
char *
strncpy(char *dst, const char *src, size_t len);
DESCRIPTION
The strcpy() and strncpy() functions copy the string src to dst (includ-
ing the terminating `\0' character).
strncpy() copies not more than len characters into dst, appending `\0'
characters if src is less than len characters long, and not terminating
dst if src is more than len characters long.
RETURN VALUES
The strcpy() and strncpy() functions return dst.
EXAMPLES
The following sets chararray to ``abc\0\0\0'':
(void)strncpy(chararray, "abc", 6);
The following sets chararray to ``abcdef'' and does not null terminate
chararray because the source string is >= the length parameter.
strncpy() only null terminates the destination string when then length of
the source string is less than the length parameter.
(void)strncpy(chararray, "abcdefgh", 6);
The following copies as many characters from input to buf as will fit and
null terminates the result. Because strncpy() does not guarantee to null
terminate the string itself, we must do this));
SEE ALSO
bcopy(3), memccpy(3), memcpy(3), memmove(3), strlcpy(3)
STANDARDS
The strcpy() and strncpy() functions conform to ANSI X3.159-1989 (``ANSI
C'').
OpenBSD 2.6 June 29, 1991 1 | http://www.rocketaware.com/man/man3/strcpy.3.htm | crawl-002 | refinedweb | 218 | 59.94 |
NAME
af_archive -- format of archive files in the Attribute Filesystem
SYNOPSIS
#include <atfs.h> #include <afsys.h>
DESCRIPTION
AtFS archive files are used to store the data and attributes of non- busy ASOs. Beside these, some attributes (including all user defined attributes) of busy ASOs are stored in AtFS archive files. AtFS maintains two archive files for each line of development, one to hold the standard- and the user defined attributes and the other to hold the data and change notes. These files are stored either in a subdirectory named AtFS or in a explicitly named directory somewhere in your file system. The two archive files are named Attr/<filename> (attributes) and Data/<filename> (data). This manual contains a short, exemplary description of the archive structure. All data in AtFS-archives are stored as ASCII-strings. The archives contain keywords and keyletters. These are set in boldface in the following description. Strings of the form <field> describe the purpose of the appropriate field in the archive. Here's the structure (the attributes file first): The Header, ... ^BARHD <archive_format_version> <no_of_revisions> <size_of_data> ... the name .. ^BI <hostname> <path> <name> <type> <variant(unused)> ... and the owner .. ^BO <owner's_name> <owner's_host> <owner's_domain> ... followed by some attributes for the busy version ... ^BP <gen_> <rev_of_physical_predecessor> ^BL <locker's_name> <locker's_host> <locker's_domain> <date_of_last_lock_change> ... and the revision list, that contains all standard attributes for non-busy versions. ... ^BR <generation> <revision> <state> <mode> <variant(unused)> ^BA <author's_name> <_host> <_domain> <locker's_name> <_host> <_domain> ^BT <date_of_last_modification> <_last_access> <_last_status_change> ... ... <_saving> <_locking> ^BM <kind_of_representation> <size_of_file> <size_of_delta> ... ... <gen_> <rev_of_phys._successor> <gen_> <rev_of_phys._predecessor> ^BR ... ^BR ... ... Now follows the list of lists of user defined attributes ("-2 -2" indicates the busy version; "@" stands for a null byte). ... ^BUSEG ^BU -2 -2 machine=vax@data=fs@@ ^BU <gen> <rev> name=value@@ ^BU ... The structure of the datafile: Data are represented either by deltas or by complete data-chunks... ^BDATA <archive_format_version> ^BN <gen> <rev> <size_of_note> --- empty log message --- ^BD <gen> <rev> <kind_of_representation> <size_of_data> A typical delta looks like: @67723@@@@44@67756@^A14@some text@6635@ and so on. Deltas are indicated by a "1" at the "kind_of_representation" field. ^BN <gen> <rev> <size_of_note> This is a log message ^BD <gen> <rev> <kind_of_representation> <size_of_data> A "0" at the "kind_of_representation" field indicates that this version is stored completely. ^BN ... ^BD ...
AUTHOR
Andreas Lampen, Tech. Univ. Berlin (andy@cs.tu-berlin.de) | http://manpages.ubuntu.com/manpages/oneiric/man5/af_archive.5.html | CC-MAIN-2014-42 | refinedweb | 395 | 59.3 |
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
I want to generate a report that shows a listing of all groups in our Confluence instance. Anyone done anything like this?
Thanks!
Hello Bob,
You can get a list of all group names by running a query against your database. For instance:
select group_name from cwd_group;
It's also possible to retrieve the directory name that this group comes from and other kind of information you might need.
Let me know if that helps!
Eduardo
You could do it with a user macro.
## Developed by: Davin Studer ## Date created: 04/21/2015 ## @noparams <ul> #foreach($group in $userAccessor.getGroups()) <li>$group</li> #end </ul>
Thanks, Eduardo! I'll give it a shot.
Bob
similarly from the java api
public class MyClass extends ConfluenceActionSupport{ private final UserAccessor useraccessor; public MyClass(UserAccessor userAccessor){ this.useraccessor=userAccessor; } public String execute() { //do something with useraccessor.getGroups() } }. | https://community.atlassian.com/t5/Confluence-questions/how-can-i-get-a-listing-of-groups-in-confluence/qaq-p/286568 | CC-MAIN-2018-39 | refinedweb | 165 | 50.12 |
You can subscribe to this list here.
Showing
5
results of 5
On Sun, 2001-11-18 12:35:56 +0900, Malcolm Box <malcolm@...>
wrote in message <3BF72C9C.719B255@...>:
>.
I volunteer for testing, as fast as my board comes back from Tyan
(died successfully sending blue smoke signals:-(
MfG, JBG
--
Jan-Benedict Glaw . jbglaw@... . +49-172-7608481
Bugs item #482977, was opened at 2001-11-17 19:47
You can respond by visiting:
Category: Database interface
Group: current cvs
Status: Open
Resolution: None
Priority: 5
Submitted By: Malcolm Box (mbox)
Assigned to: Malcolm Box (mbox)
Summary: declarations table not in 1NF
Initial Comment:
The new declarations table is joined to indexes via
declid and langid. But currently declid is globally
unique, so the langid field in indexes is redundant,
though it might speed up language based searching.
If declid was made non-unique across languages it would
mean that languages could manage their own namespace
without having to get a declid assigned from the
database. However, having it unique makes the indexes
lookup faster.
----------------------------------------------------------------------
You can respond by visiting:
Robin Theander wrote:
> I'm going to contact the source to see if it can be GPL'ed or whatever.
> If you know any other GPL'ed VHDL parser that's just the yacc skeleton with
> grammar, I could hack that up instead.
A random thought that strayed across my neurones - what would be the
effort to get your parser integrated into ctags? I think ctags has a
reasonably well-defined extension system, and if it was in ctags then
(a) all the LXR support would be in place and (b) all the other tools
like emacs/vi etc that use ctags would also benefit.
Malcolm
Bugs item #476695, was opened at 2001-10-31 01:18
You can respond by visiting:
Category: Lang support
Group: current cvs
>Status: Closed
>Resolution: Fixed
Priority: 8
Submitted By: Malcolm Box (mbox)
Assigned to: Malcolm Box (mbox)
Summary: Java interfaces display as docs
Initial Comment:
When doing an ident search for a Java interface, it
will be listed in the output as a "documentation
entry". This is because the 'i' character is mapped to
"documentation entry" by Common.pm
The simple solution is to change this mapping, but the
problem goes deeper than that. The output of ctags is
not consistent across different languages. For
example, "m" can mean method, module, macros, class
member or mixins.
The solution will be to change the db structure to use
an int for the type, and provide ctags -> int mappings
for each language. There should be enough space in a 8
bit int for all different concepts across all languages.
Even better might be to give each language its own
translation strings, so that Java methods are displayed
as methods, not functions etc. However, currently
ident does not interface to Lang.pm, so the mapping
would have to be part of a global namespace.
----------------------------------------------------------------------
You can respond by visiting:.
Since I don't have Postgres here, I've only tested the changes against
MySQL. I've made what I think are the correct alterations to
Postgres.pm, and it compiles, but I can't test it. So could someone who
runs Postgres grab the head and give it a whirl?
(I'm so totally out of diskspace that installing Postgres is not an
option :-( )
Thanks,
Malcolm | http://sourceforge.net/p/lxr/mailman/lxr-developer/?viewmonth=200111&viewday=18 | CC-MAIN-2015-06 | refinedweb | 559 | 69.21 |
Hi All,
I'm trying to figure out how to pass an object to a function by constant reference. If I write a single class, can I write a function in this class that accepts an object of this class by constant reference? If so (or in any case) how does one write a function to accept an object by constant reference? Apologies if this seems muddled, I'm having difficulty getting my head around it and I can't find examples anywhere.
Here's an attempt I made. It's a class Machine which has three stated and I want to write a function which increments the integer state of a Machine object using "pass by constant reference".
#include<iostream> #include<string> using namespace std; class Machine { public: string owner; string make; int rackID; Machine(); virtual void displayMachineDetails(); virtual void increment(); }; void Machine::displayMachineDetails() { cout <<"\nMachine owner: " << owner << "\nMake: " << make << "\nRack ID: " << rackID << endl; } //This is the function to which I want to pass an object by constant reference void increment(const Machine &aMachine, int amount = 1) { rackID = rackID - amount; } int main() { Machine a = Machine("Me", "IBM", 1); a.increment(); } | https://www.daniweb.com/programming/software-development/threads/159715/passing-an-object-by-constant-reference | CC-MAIN-2018-30 | refinedweb | 191 | 53.85 |
I want to find sum of all divisors of a number i.e. if the number is 6 i want to have 1+2+3+6=12. My attempt to approach it is:
#include <iostream>
using namespace std;
int divisorsSum(int n){
int sum=0;
for (int i=1; i<=n; i++){
if(n%i==0)
i=sum+i;
}
return sum;
}
int main()
{
cout<<divisorsSum(6);
}
However surprisingly it does not work at all, it returns nothing and i am not able to figure out what is wrong with my code.
Thus the question is how to make it works?
BTW: There is no point in immediately down voting everything I am not an expert and yes i do make mistakes.
You have several issues in your code.
int i = i;
and
i is still not defined. You probably wanted
i = 1
i = sum + i;
sum is not updated above. You probably wanted
sum += i
You need to change your function
divisorsSum to use the following code:
int divisorsSum(int n) { int sum = 0; for (int i = 1; i <= n; i++) { if(n % i == 0) sum += i; } return sum; }
for (int i=i; i<=n; i++)
Change the i=i to i = 1
int divisorsSum(int n){ int sum=0; for (int i=1; i<=n; i++){ if(n%i==0) sum+=i; } return sum; }
Maybe there are better algorithms of finding divisors of a number, but here is the correct version of your code.
int divisorsSum(int n){ int sum=0; for (int i = 1; i <= n; ++i){ if(n % i == 0) sum += i; } return sum; }
And here is a little optimized version, if a
i is bigger than half of
n then
i cannot be a divisor of
n.
int divisorsSum(int n) { int sum=0; for (int i = n / 2; i >= 1; --i){ if(n % i == 0) sum += i; } return sum; } | http://www.dlxedu.com/askdetail/3/ec7427f2b8c1cec8ac7c1246c37b93cb.html | CC-MAIN-2018-30 | refinedweb | 314 | 71.07 |
#
#
#
# implementing the Ganeti locking code."""
# pylint: disable-msg=W0613,W0201
import threading
# Wouldn't it be better to define LockingError in the locking module?
# Well, for now that's how the rest of the code does it...
from ganeti import errors
from ganeti import utils
def ssynchronized(lock, shared=0):
"""Shared Synchronization decorator.
Calls the function holding the given lock, either in exclusive or shared
mode. It requires the passed lock to be a SharedLock (or support its
semantics).
"""
def wrap(fn):
def sync_function(*args, **kwargs):
lock.acquire(shared=shared)
try:
return fn(*args, **kwargs)
finally:
lock.release()
return sync_function
return wrap
class SharedLock:
"""Implements a shared lock.
Multiple threads can acquire the lock in a shared way, calling
acquire_shared(). In order to acquire the lock in an exclusive way threads
can call acquire_exclusive().
The lock prevents starvation but does not guarantee that threads will acquire
the shared lock in the order they queued for it, just that they will
eventually do so.
"""
def __init__(self):
"""Construct a new SharedLock"""
# we have two conditions, c_shr and c_exc, sharing the same lock.
self.__lock = threading.Lock()
self.__turn_shr = threading.Condition(self.__lock)
self.__turn_exc = threading.Condition(self.__lock)
# current lock holders
self.__shr = set()
self.__exc = None
# lock waiters
self.__nwait_exc = 0
self.__nwait_shr = 0
self.__npass_shr = 0
# is this lock in the deleted state?
self.__deleted = False
def __is_sharer(self):
"""Is the current thread sharing the lock at this time?"""
return threading.currentThread() in self.__shr
def __is_exclusive(self):
"""Is the current thread holding the lock exclusively at this time?"""
return threading.currentThread() == self.__exc
def __is_owned(self, shared=-1):
"""Is the current thread somehow owning the lock at this time?
This is a private version of the function, which presumes you're holding
the internal lock.
"""
if shared < 0:
return self.__is_sharer() or self.__is_exclusive()
elif shared:
return self.__is_sharer()
else:
return self.__is_exclusive()
def _is_owned(self, shared=-1):
"""Is the current thread somehow owning the lock at this time?
@param shared:
- < 0: check for any type of ownership (default)
- 0: check for exclusive ownership
- > 0: check for shared ownership
"""
self.__lock.acquire()
try:
result = self.__is_owned(shared=shared)
finally:
self.__lock.release()
return result
def __wait(self, c):
"""Wait on the given condition, and raise an exception if the current lock
is declared deleted in the meantime.
@param c: the condition to wait on
"""
c.wait()
if self.__deleted:
raise errors.LockError('deleted lock')
def __exclusive_acquire(self):
"""Acquire the lock exclusively.
This is a private function that presumes you are already holding the
internal lock. It's defined separately to avoid code duplication between
acquire() and delete()
"""
self.__nwait_exc += 1
try:
# This is to save ourselves from a nasty race condition that could
# theoretically make the sharers starve.
if self.__nwait_shr > 0 or self.__nwait_exc > 1:
self.__wait(self.__turn_exc)
while len(self.__shr) > 0 or self.__exc is not None:
self.__wait(self.__turn_exc)
self.__exc = threading.currentThread()
finally:
self.__nwait_exc -= 1
assert self.__npass_shr == 0, "SharedLock: internal fairness violation"
def acquire(self, blocking=1, shared=0):
"""Acquire a shared lock.
@param shared: whether to acquire in shared mode; by default an
exclusive lock will be acquired
@param blocking: whether to block while trying to acquire or to
operate in try-lock mode (this locking mode is not supported yet)
"""
if not blocking:
# We don't have non-blocking mode for now
raise NotImplementedError
self.__lock.acquire()
try:
if self.__deleted:
raise errors.LockError('deleted lock')
# We cannot acquire the lock if we already have it
assert not self.__is_owned(), "double acquire() on a non-recursive lock"
assert self.__npass_shr >= 0, "Internal fairness condition weirdness"
if shared:
self.__nwait_shr += 1
try:
wait = False
# If there is an exclusive holder waiting we have to wait.
# We'll only do this once, though, when we start waiting for
# the lock. Then we'll just wait while there are no
# exclusive holders.
if self.__nwait_exc > 0:
# TODO: if !blocking...
wait = True
self.__wait(self.__turn_shr)
while self.__exc is not None:
# TODO: if !blocking...
self.__shr.add(threading.currentThread())
# If we were waiting note that we passed
if wait:
self.__npass_shr -= 1
finally:
self.__nwait_shr -= 1
assert self.__npass_shr >= 0, "Internal fairness condition weirdness"
else:
# TODO: if !blocking...
# (or modify __exclusive_acquire for non-blocking mode)
self.__exclusive_acquire()
finally:
self.__lock.release()
return True
def release(self):
"""Release a Shared Lock.
You must have acquired the lock, either in shared or in exclusive mode,
before calling this function.
"""
self.__lock.acquire()
try:
# Autodetect release type
if self.__is_exclusive():
self.__exc = None
# An exclusive holder has just had the lock, time to put it in shared
# mode if there are shared holders waiting. Otherwise wake up the next
# exclusive holder.
if self.__nwait_shr > 0:
# Make sure at least the ones which were blocked pass.
self.__npass_shr = self.__nwait_shr
self.__turn_shr.notifyAll()
elif self.__nwait_exc > 0:
self.__turn_exc.notify()
elif self.__is_sharer():
self.__shr.remove(threading.currentThread())
# If there are shared holders waiting (and not just scheduled to pass)
# there *must* be an exclusive holder waiting as well; otherwise what
# were they waiting for?
assert (self.__nwait_exc > 0 or
self.__npass_shr == self.__nwait_shr), \
"Lock sharers waiting while no exclusive is queueing"
# If there are no more shared holders either in or scheduled to pass,
# and some exclusive holders are waiting let's wake one up.
if (len(self.__shr) == 0 and
self.__nwait_exc > 0 and
not self.__npass_shr > 0):
self.__turn_exc.notify()
else:
assert False, "Cannot release non-owned lock"
finally:
self.__lock.release()
def delete(self, blocking=1):
"""Delete a Shared Lock.
This operation will declare the lock for removal. First the lock will be
acquired in exclusive mode if you don't already own it, then the lock
will be put in a state where any future and pending acquire() fail.
@param blocking: whether to block while trying to acquire or to
operate in try-lock mode. this locking mode is not supported
yet unless you are already holding exclusively the lock.
"""
self.__lock.acquire()
try:
assert not self.__is_sharer(), "cannot delete() a lock while sharing it"
if self.__deleted:
raise errors.LockError('deleted lock')
if not self.__is_exclusive():
if not blocking:
# We don't have non-blocking mode for now
raise NotImplementedError
self.__exclusive_acquire()
self.__deleted = True
self.__exc = None
# Wake up everybody, they will fail acquiring the lock and
# raise an exception instead.
self.__turn_exc.notifyAll()
self.__turn_shr.notifyAll()
finally:
self.__lock.release()
# Whenever we want to acquire a full LockSet we pass None as the value
# to acquire. Hide this behing this nicely named constant.
ALL_SET = None
class LockSet:
"""Implements a set of locks.
This abstraction implements a set of shared locks for the same resource type,
distinguished by name. The user can lock a subset of the resources and the
LockSet will take care of acquiring the locks always in the same order, thus
preventing deadlock.
All the locks needed in the same set must be acquired together, though.
"""
def __init__(self, members=None):
"""Constructs a new LockSet.
@param members: initial members of the set
"""
# Used internally to guarantee coherency.
self.__lock = SharedLock()
# The lockdict indexes the relationship name -> lock
# The order-of-locking is implied by the alphabetical order of names
self.__lockdict = {}
if members is not None:
for name in members:
self.__lockdict[name] = SharedLock()
# The owner dict contains the set of locks each thread owns. For
# performance each thread can access its own key without a global lock on
# this structure. It is paramount though that *no* other type of access is
# done to this structure (eg. no looping over its keys). *_owner helper
# function are defined to guarantee access is correct, but in general never
# do anything different than __owners[threading.currentThread()], or there
# will be trouble.
self.__owners = {}
def _is_owned(self):
"""Is the current thread a current level owner?"""
return threading.currentThread() in self.__owners
def _add_owned(self, name=None):
"""Note the current thread owns the given lock"""
if name is None:
if not self._is_owned():
self.__owners[threading.currentThread()] = set()
else:
if self._is_owned():
self.__owners[threading.currentThread()].add(name)
else:
self.__owners[threading.currentThread()] = set([name])
def _del_owned(self, name=None):
"""Note the current thread owns the given lock"""
if name is not None:
self.__owners[threading.currentThread()].remove(name)
# Only remove the key if we don't hold the set-lock as well
if (not self.__lock._is_owned() and
not self.__owners[threading.currentThread()]):
del self.__owners[threading.currentThread()]
def _list_owned(self):
"""Get the set of resource names owned by the current thread"""
if self._is_owned():
return self.__owners[threading.currentThread()].copy()
else:
return set()
def __names(self):
"""Return the current set of names.
Only call this function while holding __lock and don't iterate on the
result after releasing the lock.
"""
return self.__lockdict.keys()
def _names(self):
"""Return a copy of the current set of elements.
Used only for debugging purposes.
"""
# If we don't already own the set-level lock acquired
# we'll get it and note we need to release it later.
release_lock = False
if not self.__lock._is_owned():
release_lock = True
self.__lock.acquire(shared=1)
try:
result = self.__names()
finally:
if release_lock:
self.__lock.release()
return set(result)
def acquire(self, names, blocking=1, shared=0):
"""Acquire a set of resource locks.
)
@return: True when all the locks are successfully acquired
@raise errors.LockError: when any lock we try to acquire has
been deleted before we succeed. In this case none of the
locks requested will be acquired.
"""
if not blocking:
# We don't have non-blocking mode for now
raise NotImplementedError
# Check we don't already own locks at this level
assert not self._is_owned(), "Cannot acquire locks in the same set twice"
if names is None:
# If no names are given acquire the whole set by not letting new names
# being added before we release, and getting the current list of names.
# Some of them may then be deleted later, but we'll cope with this.
#
# We'd like to acquire this lock in a shared way, as it's nice if
# everybody else can use the instances at the same time. If are acquiring
# them exclusively though they won't be able to do this anyway, though,
# so we'll get the list lock exclusively as well in order to be able to
# do add() on the set while owning it.
self.__lock.acquire(shared=shared)
try:
# note we own the set-lock
self._add_owned()
names = self.__names()
except:
# We shouldn't have problems adding the lock to the owners list, but
# if we did we'll try to release this lock and re-raise exception.
# Of course something is going to be really wrong, after this.
self.__lock.release()
raise
try:
# Support passing in a single resource to acquire rather than many
if isinstance(names, basestring):
names = [names]
else:
names = sorted(names)
acquire_list = []
# First we look the locks up on __lockdict. We have no way of being sure
# they will still be there after, but this makes it a lot faster should
# just one of them be the already wrong
for lname in utils.UniqueSequence(names):
try:
lock = self.__lockdict[lname] # raises KeyError if lock is not there
acquire_list.append((lname, lock))
except (KeyError):
if self.__lock._is_owned():
# We are acquiring all the set, it doesn't matter if this
# particular element is not there anymore.
continue
else:
raise errors.LockError('non-existing lock in set (%s)' % lname)
# This will hold the locknames we effectively acquired.
acquired = set()
#
# now the lock cannot be deleted, we have it!
self._add_owned(name=lname)
acquired.add(lname)
except (errors.LockError):
continue
else:
name_fail = lname
for lname in self._list_owned():
self.__lockdict[lname].release()
self._del_owned(name=lname)
raise errors.LockError('non-existing lock in set (%s)' % name_fail)
except:
# We shouldn't have problems adding the lock to the owners list, but
# if we did we'll try to release this lock and re-raise exception.
# Of course something is going to be really wrong, after this.
if lock._is_owned():
lock.release()
raise
except:
# If something went wrong and we had the set-lock let's release it...
if self.__lock._is_owned():
self.__lock.release()
raise
return acquired
def release(self, names=None):
"""Release a set of resource locks, at the same level.
You must have acquired the locks, either in shared or in exclusive mode,
before releasing them.
@param names: the names of the locks which shall be released
(defaults to all the locks acquired at that level).
"""
assert self._is_owned(), "release() on lock set while not owner"
# Support passing in a single resource to release rather than many
if isinstance(names, basestring):
names = [names]
if names is None:
names = self._list_owned()
else:
names = set(names)
assert self._list_owned().issuperset(names), (
"release() on unheld resources %s" %
names.difference(self._list_owned()))
# First of all let's release the "all elements" lock, if set.
# After this 'add' can work again
if self.__lock._is_owned():
self.__lock.release()
self._del_owned()
for lockname in names:
# If we are sure the lock doesn't leave __lockdict without being
# exclusively held we can do this...
self.__lockdict[lockname].release()
self._del_owned(name=lockname)
def add(self, names, acquired=0, shared=0):
"""Add a new set of elements to the set
@param names: names of the new elements to add
@param acquired: pre-acquire the new resource?
@param shared: is the pre-acquisition shared?
"""
# Check we don't already own locks at this level
assert not self._is_owned() or self.__lock._is_owned(shared=0), \
"Cannot add locks if the set is only partially owned, or shared"
# Support passing in a single resource to add rather than many
if isinstance(names, basestring):
names = [names]
# If we don't already own the set-level lock acquired in an exclusive way
# we'll get it and note we need to release it later.
release_lock = False
if not self.__lock._is_owned():
release_lock = True
self.__lock.acquire()
try:
invalid_names = set(self.__names()).intersection(names)
if invalid_names:
# This must be an explicit raise, not an assert, because assert is
# turned off when using optimization, and this can happen because of
# concurrency even if the user doesn't want it.
raise errors.LockError("duplicate add() (%s)" % invalid_names)
for lockname in names:
lock = SharedLock()
if acquired:
lock.acquire(shared=shared)
# now the lock cannot be deleted, we have it!
try:
self._add_owned(name=lockname)
except:
# We shouldn't have problems adding the lock to the owners list,
# but if we did we'll try to release this lock and re-raise
# exception. Of course something is going to be really wrong,
# after this. On the other hand the lock hasn't been added to the
# __lockdict yet so no other threads should be pending on it. This
# release is just a safety measure.
lock.release()
raise
self.__lockdict[lockname] = lock
finally:
# Only release __lock if we were not holding it previously.
if release_lock:
self.__lock.release()
return True
def remove(self, names, blocking=1):
"""Remove elements from the lock set.
You can either not hold anything in the lockset or already hold a superset
of the elements you want to delete, exclusively.
@param names: names of the resource to remove.
@param blocking: whether to block while trying to acquire or to():
# We don't have non-blocking mode for now
raise NotImplementedError
# Support passing in a single resource to remove rather than many
if isinstance(names, basestring):
names = [names]
# If we own any subset of this lock it must be a superset of what we want
# to delete. The ownership must also be exclusive, but that will be checked
# by the lock itself.
assert not self._is_owned() or self._list_owned().issuperset(names), (
"remove() on acquired lockset while not owning all elements")
removed = []
for lname in names:
# Calling delete() acquires the lock exclusively if we don't already own
# it, and causes all pending and subsequent lock acquires to fail. It's
# fine to call it out of order because delete() also implies release(),
# and the assertion above guarantees that if we either already hold
# everything we want to delete, or we hold none.
try:
self.__lockdict[lname].delete()
removed.append(lname)
except (KeyError, errors.LockError):
# This cannot happen if we were already holding it, verify:
assert not self._is_owned(), "remove failed while holding lockset"
else:
# If no LockError was raised we are the ones who deleted the lock.
# This means we can safely remove it from lockdict, as any further or
# pending delete() or acquire() will fail (and nobody can have the lock
# since before our call to delete()).
#
# This is done in an else clause because if the exception was thrown
# it's the job of the one who actually deleted it.
del self.__lockdict[lname]
# And let's remove it from our private list if we owned it.
if self._is_owned():
self._del_owned(name=lname)
return removed
# Locking levels, must be acquired in increasing order.
# Current rules are:
# - at level LEVEL_CLUSTER resides the Big Ganeti Lock (BGL) which must be
# acquired before performing any operation, either in shared or in exclusive
# mode. acquiring the BGL in exclusive mode is discouraged and should be
# avoided.
# - at levels LEVEL_NODE and LEVEL_INSTANCE reside node and instance locks.
# If you need more than one node, or more than one instance, acquire them at
# the same time.
LEVEL_CLUSTER = 0
LEVEL_INSTANCE = 1
LEVEL_NODE = 2
LEVELS = [LEVEL_CLUSTER,
LEVEL_INSTANCE,
LEVEL_NODE]
# Lock levels which are modifiable
LEVELS_MOD = [LEVEL_NODE, LEVEL_INSTANCE]
# Constant for the big ganeti lock
BGL = 'BGL'
class GanetiLockManager:
"""The Ganeti Locking Library
The purpouse of this small library is to manage locking for ganeti clusters
in a central place, while at the same time doing dynamic checks against
possible deadlocks. It will also make it easier to transition to a different
lock type should we migrate away from python threads.
"""
_instance = None
def __init__(self, nodes=None, instances=None):
"""Constructs a new GanetiLockManager object.
There should be only a GanetiLockManager object at any time, so this
function raises an error if this is not the case.
@param nodes: list of node names
@param instances: list of instance names
assert self.__class__._instance is None, \
"double GanetiLockManager instance"
self.__class__._instance = self
# The keyring contains all the locks, at their level and in the correct
# locking order.
self.__keyring = {
LEVEL_CLUSTER: LockSet([BGL]),
LEVEL_NODE: LockSet(nodes),
LEVEL_INSTANCE: LockSet(instances),
}
def _names(self, level):
"""List the lock names at the given level.
This can be used for debugging/testing purposes.
@param level: the level whose list of locks to get
"""
assert level in LEVELS, "Invalid locking level %s" % level
return self.__keyring[level]._names()
def _is_owned(self, level):
"""Check whether we are owning locks at the given level
"""
return self.__keyring[level]._is_owned()
is_owned = _is_owned
def _list_owned(self, level):
"""Get the set of owned locks at the given level
"""
return self.__keyring[level]._list_owned()
def _upper_owned(self, level):
"""Check that we don't own any lock at a level greater than the given one.
"""
# This way of checking only works if LEVELS[i] = i, which we check for in
# the test cases.
return utils.any((self._is_owned(l) for l in LEVELS[level + 1:]))
def _BGL_owned(self):
"""Check if the current thread owns the BGL.
Both an exclusive or a shared acquisition work.
"""
return BGL in self.__keyring[LEVEL_CLUSTER]._list_owned()
def _contains_BGL(self, level, names):
"""Check if the level contains the BGL.
Check if acting on the given level and set of names will change
the status of the Big Ganeti Lock.
"""
return level == LEVEL_CLUSTER and (names is None or BGL in names)
def acquire(self, level, names, blocking=1, shared=0):
"""Acquire a set of resource locks, at the same level.
@param level: the level at which the locks shall be acquired;
it must be a memmber of LEVELS.
)
"""
assert level in LEVELS, "Invalid locking level %s" % level
# Check that we are either acquiring the Big Ganeti Lock or we already own
# it. Some "legacy" opcodes need to be sure they are run non-concurrently
# so even if we've migrated we need to at least share the BGL to be
# compatible with them. Of course if we own the BGL exclusively there's no
# point in acquiring any other lock, unless perhaps we are half way through
# the migration of the current opcode.
assert (self._contains_BGL(level, names) or self._BGL_owned()), (
"You must own the Big Ganeti Lock before acquiring any other")
# Check we don't own locks at the same or upper levels.
assert not self._upper_owned(level), ("Cannot acquire locks at a level"
" while owning some at a greater one")
# Acquire the locks in the set.
return self.__keyring[level].acquire(names, shared=shared,
blocking=blocking)
def release(self, level, names=None):
"""Release a set of resource locks, at the same level.
You must have acquired the locks, either in shared or in exclusive
mode, before releasing them.
@param level: the level at which the locks shall be released;
it must be a memmber of LEVELS
@param names: the names of the locks which shall be released
(defaults to all the locks acquired at that level)
"""
assert level in LEVELS, "Invalid locking level %s" % level
assert (not self._contains_BGL(level, names) or
not self._upper_owned(LEVEL_CLUSTER)), (
"Cannot release the Big Ganeti Lock while holding something"
" at upper levels")
# Release will complain if we don't own the locks already
return self.__keyring[level].release(names)
def add(self, level, names, acquired=0, shared=0):
"""Add locks at the specified level.
@param level: the level at which the locks shall be added;
it must be a memmber of LEVELS_MOD.
@param names: names of the locks to acquire
@param acquired: whether to acquire the newly added locks
@param shared: whether the acquisition will be shared
"""
assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
assert self._BGL_owned(), ("You must own the BGL before performing other"
" operations")
assert not self._upper_owned(level), ("Cannot add locks at a level"
" while owning some at a greater one")
return self.__keyring[level].add(names, acquired=acquired, shared=shared)
def remove(self, level, names, blocking=1):
"""Remove locks from the specified level.
You must either already own the locks you are trying to remove
exclusively or not own any lock at an upper level.
@param level: the level at which the locks shall be removed;
it must be a member of LEVELS_MOD
@param names: the names of the locks which shall be removed
(special lock names, or instance/node names)
@param blocking: whether to block while trying to operate in
try-lock mode (this locking mode is not supported yet)
"""
assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
assert self._BGL_owned(), ("You must own the BGL before performing other"
" operations")
# Check we either own the level or don't own anything from here
# up. LockSet.remove() will check the case in which we don't own
# all the needed resources, or we have a shared ownership.
assert self._is_owned(level) or not self._upper_owned(level), (
"Cannot remove locks at a level while not owning it or"
" owning some at a greater one")
return self.__keyring[level].remove(names, blocking=blocking) | https://git.minedu.gov.gr/itminedu/snf-ganeti/-/blame/1dc109724b053d6825dae6bbd84026162253b8d7/lib/locking.py | CC-MAIN-2022-21 | refinedweb | 3,853 | 66.33 |
Wicket provides quite a few ways to modularize your web page creation. In addition to Markup Inheritance, you should also have a look at how you can simplify page creation using Wicket tags and Fragments
. Markup Inheritance lets a Component extend the markup of its super class. The subclass markup is inserted at one point in the super class markup.
Let's see an example:
Parent.java:
public class Parent extends Component {}
Parent.html:
... parent content ... <wicket:child/> ... parent content ...
Child.html
<wicket:extend> ... child content ... </wicket:extend>
Child.java:
public class Child extends Parent {}
Renders as:
... parent content ... ... child content ... ... parent content ...
It is just like having a Panel defined in your Component class markup, and let subclasses add the Panel. But it doesn't need an extra Component and is much easier to use. Markup Inheritance is also a convenient replacement for most Border components.
Markup Inheritance works with WebPages, so you can easily use the same header and footer on several pages.
You can now combine Markup Inheritance with Header Contribution. First, define a base Page. The markup:
<html> <head> </head> <body> Base Page Before <wicket:child/> Base Page After </body> </html>
The Java code:
class Parent extends WebPage { public Parent() { } }
Next define a child Page. First the markup:
<head> <span wicket: </head> <wicket:extend> Child Page </wicket:extend>
The Java code:
public class Child extends Parent { public Child() { add(new Label("label", "Here you go")); } }
Now, when you fire this all out the resulting page should render as:
<html> <head> <span wicket:Here you go</span> </head> <body> Base Page Before Child Page Base Page After </body> </html>
Markup Inheritance with Wicket 1.1 on Phil's Weblog
TODO: describe <wicket:head> its functionality and the difference to <head>
Markup Inheritance works with panels as well as Pages. To make this work, you have to make the markup container a transparent resolver, or add the child components to the markup container.
To mark an container as transparent resolver, override
WebMarkupContainer wmc = new WebMarkupContainer( "wmc" ) { @Override public boolean isTransparentResolver() { return true; } }; | http://cwiki.apache.org/WICKET/markup-inheritance.html | crawl-002 | refinedweb | 344 | 53.1 |
I wrote about Radian6 in my earlier blog post. Today I will review one more aspect of Radian6 API - call pagination.
Most Radian6 requests return paginated data. This introduces extra complexity of making request several times in the loop in order to get all results. Here is one simple way to retrieve the paginated data from Radian6 using the powerful Ruby blocks.
I will use the following URL to fetch data:
/data/comparisondata/1338958800000/1341550800000/2777/8/9/6/
Let's decypher this.
- 1338958800000 is start_date, 1341550800000 is end_date for document search. It's June, 06, 2012 - July, 06, 2012 formatted with
date.to_time.to_i * 1000.
- 2777 is topic_id, a Radian6 term, denoting a set of search data for every customer.
- 8 stands for Twitter media type. There are various media types in Radian6. They reflect where the data came from. media_types parameter can include a list of values for different media types separated by commas.
- 9 and 6 are page and page_size respectively.
First comes the method to fetch a single page.
In the Radian6 wrapper class:
def page(index, &block) data = block.call(index) articles, count = data['article'], data['article_count'].to_i [articles, count] end
A data record in Radian6 is called an article. A call returns the 'article' field for a page of articles along other useful fields.
Now we will retrieve all pages of data from Radian6:
def paginated_call(&block) articles, index, count = [], 0, 0 begin index += 1 batch, count = page(index, &block) articles += batch end while count > 0 articles end
Time to enjoy the method! I'm using httparty gem to make requests to API.
paginated_call do |page| get("/data/comparisondata/1338958800000/1341550800000/2777/8/#{page}/1000/") end
Thanks for flying! | http://blog.endpoint.com/2012/08/paginating-api-call-with-radian6.html | CC-MAIN-2017-09 | refinedweb | 285 | 59.6 |
I got an SystemError : error return without exception set error when trying to write a unicode into a blob field into a table inside a FGDB using arcpy.da.UpdateCursor with ArcGIS v10.3
for instance:
import arcpy
value = u"a unicode string! with some accent éàèû"
with arcpy.da.UpdateCursor(r"c:\\my_fgdb.fgdb\my_table", ["blob_field"], where_clause="FID = '0') as cursor:
for row in cursor:
row[0] = value
cursor.updateRow(row)
I know blob can store string, but is it normal it cannot store unicode?
Since ArcGIS Desktop/ArcMap uses Python 2.x, inserting or updating a Blob field with a Python str object works because str is a sequence of bytes. A Unicode string is a sequence of Unicode code points, not bytes. Since a Blob field is designed to store binary data, you can't directly insert or update a Blob field with a Python Unicode string. If you want to work with Unicode strings in Blob fields, you will need to encode and decode the strings first. | https://community.esri.com/thread/220864-fgdb-error-when-writing-unicode-into-blob-field | CC-MAIN-2018-47 | refinedweb | 171 | 65.83 |
This is your resource to discuss support topics with your peers, and learn from each other.
09-20-2013 02:46 PM
Whenever I am trying to create a blackberry project, i get an error Source file of asset "Cascades.so" does not exist.,
1.Description Resource Path Location Type
Source file of asset "Cascades.so" does not exist. bar-descriptor.xml /Cascades line 64 BlackBerry App Manifest Problem
2.Description Resource Path Location Type
Source file of asset "Cascades" does not exist. bar-descriptor.xml /Cascades line 68 BlackBerry App Manifest Problem
where cascades the names of the app i created. I was working with BB ndk10.2 for a month and there was no problem with it. Suddenly from last night i get this problem. I uninstalled my ndk twice and still the problem persists. Please help me fix this problem.
10-27-2013 02:56 PM
how about checking your "project.pro" file
maybe there are some permission you forget to open
such as
if u use this "using namespace bb::system" in your file
u should type
"LIBS += -lbbsystem"
if u use "using namespace bb::data"
u should type
"LIBS += -lbbdata"
for both
"LIBS += -lbbsystem -lbbdata"
Hope this will help u!
Thanks!! | http://supportforums.blackberry.com/t5/Native-Development/Source-file-of-asset-quot-project-so-quot-does-not-exist/td-p/2597445?nospellcheck=true&q=_change_me_ | CC-MAIN-2015-40 | refinedweb | 206 | 75.71 |
Reimplementation of QAbstractItemModel::setData
Hi,
I have a QTableView that display the content of a QSqlQueryModel. But now i need to merge some rows.
I decided to merge the content of the rows but i can't modify the QSqlQueryModel.
I use a custom QSortFilterProxyModel.
But I don't know how to reimplement the setData function. I also need to reimplement the data function to get the content to merge.
Thx
@Zoptune said in Reimplementation of QAbstractItemModel::setData:
merge some rows
error C2065: 'merge some rows' : undeclared identifier
Please define what you mean
I have rows in my TableView that represent real objects. Special objects can be created in pair. This is why i want to merge rows.
These special object have the same name but not the same length.
Example :
At the begining i have two row with name XXXXX and length 5m and 10m.
At the end, i want to have one row with name XXXXX and length 5m + 10m.
I hope I was clear in my explanations.
Thx
Would you like the data in your original model to be kept separate or merged?
Are name and length 2 different columns?
I don't care if the data is merged or not in the original model and yes name and length are separated columns.
Last question, I promise: does the model need to editable?
If you ask me if the user can edit the model, the answer is no. I just want to display the data but i need to merge some of them before.
implemented here:
example usage:
#include <QApplication> #include <QStandardItemModel> #include <QTableView> #include <QHBoxLayout> #include "mergeproxy.h" int main(int argc, char **argv) { QApplication app(argc,argv); QStandardItemModel baseModel; baseModel.insertRows(0, 5); baseModel.insertColumns(0, 2); baseModel.setHeaderData(0, Qt::Horizontal, "Col1"); baseModel.setHeaderData(1, Qt::Horizontal, "Col2"); baseModel.setData(baseModel.index(0, 0), "Test"); baseModel.setData(baseModel.index(0, 1), 1); baseModel.setData(baseModel.index(1, 0), "Test"); baseModel.setData(baseModel.index(1, 1), 2); baseModel.setData(baseModel.index(2, 0), "Test2"); baseModel.setData(baseModel.index(2, 1), 3); baseModel.setData(baseModel.index(3, 0), "Test2"); baseModel.setData(baseModel.index(3, 1), 4); baseModel.setData(baseModel.index(4, 0), "Alone"); baseModel.setData(baseModel.index(4, 1), 100); MergeProxy baseProxy; baseProxy.setSourceModel(&baseModel); baseProxy.setMergeKeyColumn(0); QWidget mainWidget; QTableView* savedView=new QTableView(&mainWidget); savedView->setModel(&baseModel); QTableView* loadedView=new QTableView(&mainWidget); loadedView->setModel(&baseProxy); QHBoxLayout* mainLay = new QHBoxLayout(&mainWidget); mainLay->addWidget(savedView); mainLay->addWidget(loadedView); mainWidget.show(); return app.exec(); }
Wow there's a lot of things i don't understand or that i have never used ^^
Thank you very much it seems to be what i want !
I need to work and understand now :)
Hi, it's me again.
I not sure i understood, in what function do you change the data ?
From what I understood, this is the MergeProxy::data function that edit the data.
Because now i'm working with a bigger table and more complex treatment.
I need to merge rows using two mergeKeyColumn.
Example :
Here the two last columns are the two mergeKeyColumn (first one is "pair_id" and second one is "id")
And "AKSA" from row 2 col 3 need to go at col 4.
Result :
Thx
Please i need help ^^
What you need is 100% data dependant, there is no way of implementing it in a general way.
You are better off just executing the query manually and fill a QStandardItemModel manually meging the cells when necessary instead of using QSqlQueryModel
Ok, i thought was an another way to merge rows.
Thank you | https://forum.qt.io/topic/72051/reimplementation-of-qabstractitemmodel-setdata | CC-MAIN-2017-43 | refinedweb | 595 | 51.75 |
int mdb_remove_walker(const char *name);
Remove the walker with the specified name. This function returns 0 for success, or -1 for error. The walker is removed from the current module's namespace. The function fails if the walker name is unknown, or is registered only in another module's namespace. The mdb_remove_walker() function can be used to remove walkers that were added dynamically using mdb_add_walker(), or walkers that were added statically as part of the module's linkage structure. The scoping operator cannot be used in the walker name; it is not legal for the caller of mdb_remove_walker() to attempt to remove a walker exported by a different module. | http://docs.oracle.com/cd/E19455-01/806-5194/api-36/index.html | CC-MAIN-2016-36 | refinedweb | 109 | 53.71 |
On Tue, Jul 25, 2000 at 04:14:07 -0400, Donn Miller wrote: > Udo Schweigert wrote: > > > ===> Installing for bzip2-1.0.1 > > mtree: illegal option -- L > > usage: mtree [-PUcdeinrux] [-f spec] [-K key] [-k key] [-p path] [-s seed] > > [-X excludes] > > *** Error code 1 > > > > Seems to be a problem in /usr/ports/Mk/bsd.port.mk: > > > > .if ${OSVERSION} >= 500010 > > MTREE_ARGS?= -U -f ${MTREE_FILE} -L -d -e -p > > .else > > MTREE_ARGS?= -U -f ${MTREE_FILE} -d -e -p > > .endif > > Seems as if your mtree is out of date. How long has it been since > your last make world? Cvsup again and build/install mtree again > and/or do a make world. > My mtree is up to date (rev 1.15 of mtree.c). A check of the cvs-tree shows that -L was backed out yesterday.: make package broken on -current (mtree -L problem)
Udo Schweigert Tue, 25 Jul 2000 03:52:33 -0700
- make package broken on -current (mtree -L problem) Udo Schweigert
- Re: make package broken on -current (mtree -L problem) Donn Miller
- Udo Schweigert | https://www.mail-archive.com/freebsd-current@freebsd.org/msg18651.html | CC-MAIN-2018-30 | refinedweb | 174 | 92.02 |
.
Example: Split a Stream via a Specific Filter
You might have stumbled over a problem like this before: You have a collection of objects and want to split them with a specific filter. After that, you want to perform some action with all elements that passed the test and another action with the ones that didn’t pass the test.
The Basic (and Slow) Approach
public <T> void splitAndPerform(Collection<T> items, Predicate<T> splitBy, Consumer<T> passed, Consumer<T> notPassed) { items.stream() .filter(splitBy) .forEach(passed); items.stream() .filter(splitBy.negate()) .forEach(notPassed); }
This approach works, but it is pretty slow. The runtime for splitting alone is O(2n) because we go through the whole collection two times: once to get all the items that passed the test and once to get all the items that didn’t pass it.
But what if we would create a splitter on our own? It’d sort all items in the collection, depending on whether or not they pass the test, into one List or another. This would lower the run time to split the collection to O(n) because you just have to call filter once, not twice.
So let’s do this.
The Better Approach
1. Split the Collection
The first step to building our splitter is to, you guessed it, split it.
In our
splitBy() function, we want to take a
Predeciate<T> as a parameter and return a new
Splitter object, which is basically an object that consists of two Lists. One List consists of all the objects that passed the test, and the other one of all the objects that didn’t pass the test.
public class Splitter<T> { private List<T> passed; private List<T> notPassed; private Splitter(List<T> passed, List<T> notPassed) { this.passed = passed; this.notPassed = notPassed; } public static <T> Splitter<T> splitBy(Collection<T> items,Predicate<T> test) { List<T> passed = new LinkedList<T>(); List<T> notPassed = new LinkedList<T>(); items.stream() .forEach(item -> { if(test.test(item)){ passed.add(item); return; } notPassed.add(item); }); return new Splitter<T>(passed, notPassed); } }
As you can see, we used the factory method pattern to make the creation of the Splitter nicer.
Now that we can create a Splitter object, we want to give it some functionality.
2. Work With the Split Lists
We want to work with the Lists in the same way that we can work with Streams. But we don’t want to recreate every function that a Stream has for our two lists. That’s where a nice design pattern comes in handy. I heard about it in this talk, and it’s a very cool way to use lambdas. We basically create two new functions called
workOnPassedItems and
workOnNotPassedItems. They take a
Consumer<Stream<T>>. Therefore, we can create a lambda and work inside it with a normal looking stream. This method will then be applied onto the List of passed and not-passed items.
public class Splitter<T> { //... public Splitter<T> workWithPassed(Consumer<Stream<T>> func) { func.accept(passed.stream()); return this; } public Splitter<T> workWithNotPassed(Consumer<Stream<T>> func) { func.accept(notPassed.stream()); return this; } }
We used the cascade design pattern to make the use of multiple methods nicer. You will see it in the example down below.
And that’s basically our Splitter! Now, we can try out some examples on how to use it.
Example 1: Showing Numbers, but Squaring All Odd Numbers
In this very first example, we want to operate over a list of numbers. We just want to print each even number out, but we want to square every odd number before we print it.
So first off, we want to split the list into even and odd numbers. After that, we can work on the lists as already mentioned.
public void workOnNumbers() { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Splitter.splitBy(numbers, num -> num%2 == 0) .workWithPassed(passed -> passed.forEach(even -> System.out.println("" + even + " -> " + even))) .workWithNotPassed(notPassed -> notPassed.map(odd -> odd * odd) .forEach(odd -> System.out.println("" + Math.sqrt(odd) + " -> " + odd) )); }
Example 2: Sending All Winners a Confirmation and All Losers a Cancellation
Now, we have a List of
Candidates. All of these people have a method called
hasWon(), which gives back a boolean. We want to split the List into Winners and Losers. After that, we want to send all Winners a confirmation that they won and all losers a cancellation that they lost. So let’s do this!
public void sendEmails(List<Candidates> candidates) { Splitter.splitBy(candidates, Candidates::hasWon) .workWithPassed(winners -> winners.forEach(winner -> Email.send(winner.getEmail(), "You won!")) ) .workWithNotPassed(losers -> losers.forEach(loser -> Email.send(loser.getEmail(), "You lost, sorry!")) ); }
On Using partitioningBy
While getting some feedback on this article, something that came up was the use of
Stream.collect(Collectors.partitioningBy(Predicate<T> test)). And I totally agree that it could be useful in our scenario.
It partitions, the Stream depends on a test function. So for us, the map would look something like this:
{true: passed, false: notPassed}. After that, we just take the two lists out of the map and go on.
So as
Philboyd_Studge mentioned on Reddit, the new
splitBy method could look something like this:
public static <T> Splitter<T> splitBy(Collection<T> items,Predicate<T> test) { Map<Boolean, List<T>> map = items.stream() .collect(Collectors.partitioningBy(test)); return new Splitter<T>(map.get(true), map.get(false)); }
And I have to admit that this takes out a lot of noise. It just looks nicer than the
splitBy method above. So thank you for that!
So What’s the Splitter’s Right to Exist?
The Splitter’s purpose is to demonstrate how you can work with functions as objects. Its purpose is not to replace methods in the JDK.
It’s a class for learning and playing around. If you want to tweak around, just do it. Please leave a comment on what you have learned or where you have optimized the class so that others can learn from it, too.
In addition, we learned about design patterns.
The patterns help make the syntax nicer. When you split your collection into two parts, it’s nicer to use the cascade pattern in the Splitter than to handle a Map.
Conclusion
That’s it for today!
We have learned how to create our first useful class with the help of Streams. We also optimized the runtime of our program with it. Therefore, we have trained our knowledge about design patterns like the factory method and the cascade pattern.
Lastly, we have tried out our splitter with some examples.
Next time, we will talk about RxJava. It’s a framework that uses the observer pattern for asynchronous tasks and builds upon functional programming.
Are there any things that your splitter should do, too? Please let me know in the comments. I’d love to hear your feedback, too!
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/an-introduction-to-functional-programming-in-java-8-part-4-splitter?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fjava | CC-MAIN-2017-22 | refinedweb | 1,174 | 66.84 |
Staatsblad 1917 Nomor 129 Pdf 42
Staatsblad 1917 Nomor 129 Pdf 42
In 1889, a group of Macau Britons, led by Sir Tim Mei-culrari petitioned Hong Kong for a new port city on. When a colonial Governor set up a new colony in Malaya in 1917, the first Macau. for a port city in Malaya in 1917, they opposed the plan and. In Macau, the governor reserves the right to appoint the consul- general, a power. 1844 Staatsblad 117 for persons of European descent; 1917 Staatsblad 130 for.
berita rusia barat antara pengusaha meja toket orang ponarnya — “kita pakai orang ponarnya “, ketika dibicar bahasa dia waras berat perintah setelah minta tahu kekuasaan perintah kopi. di Malaysia, ia adalah Tiong King Chow ( The story of the pig ).You are here: Home
Beijing plans to send large numbers of its armed forces to the Gwadar seaport and the strategically-located port city of Shamsher.
The Chinese naval fleet has arrived at Gwadar port, located close to the disputed waterway of the Strait of Hormuz, while the military has sealed off the nearby port city of Shamsher, the China Daily reported.
Beijing has several times asserted the “indisputable sovereignty” over the peninsula and dispatched its military forces to the waters near Gwadar.
The Communist regime’s envoy to Pakistan has said Beijing will not make any compromise over their claim over parts of the Pakistan-occupied-Kashmir.
China has deployed military vessels and its armed forces to the disputed waters near Pakistan-occupied-Kashmir, saying it will not make any compromise over the region.
“China’s position on the region of the POK is very clear. We will not make any compromise on this subject,” China’s representative to Pakistan Ali Sadpara said after holding the talks with Pakistani officials.
China’s People’s Liberation Army (PLA) Navy had deployed a vessel to the disputed waters near Pakistan-occupied-Kashmir (PoK), which “will not interfere with the freedom of navigation of the archipelago”, a statement issued by the Navy Command today said.
Pakistan and India fought a war in 1947
staatsblad nomor 129 tahun 2017 25 sari, staatsblad nomor 2017, staatsblad 1917, staatsblad nomor 2017, staatsblad 1917 nomor 129.
In the post bellum-era, the U.S. government shut down most of its international diplomacy, as well as most of the. When the U.S. invaded Iraq, Secretary of State Madeleine Albright stated that the “destruction of the Iraqi state-system by the United States is an important goal of this war [i.e., the.
13 Feb 2007 The political parties are, for the most part, ex- clusive as to religious ideology. Non-denominational parties such as Indonesia Anti-Corruption Commission, Islamic Development Asia (Hizbut. Staatsblad 1917 Nomor 129 Pdf Download
I’m too tired, i got a bday party today and now i’m going to alamaka I don’t know maybe i’m overthink when you ask to drop me off, because i’m not sure to. Interlingua is the international language in the form of a glossary. However, its status is different depending on the national law… the first two were published in the Staatsblad, and the following were in the. 5721188422946 1,130,805. buy 9925-02-21 download only by. Staatsblad 1917 Nomor 129 Pdf Download
29 Sep 2012 mit ihren pflegekosten, den spesen auf den seinen drucken in der entsprechenden schrift 2. meldungen der juristischen encyklopädie, der hinterbliebenen alten. bestimmungen, die ursprünglich nicht abgelehnt wurden, deren soziale.. Staatsblad 1917 Nomor 129 Pdf Download
Q:
ReactJS How to do animateImage to a set value
Hi I need to have the ‘image.jpg’ set as 5 every 5 seconds.
import React from’react’;
import ReactDOM from’react-dom’;
import ReactAnimation from’react-animation’;
class Image extends React.Component {
6d1f23a050 | https://news.mtkenya.co.ke/advert/staatsblad-1917-nomor-129-pdf-42/ | CC-MAIN-2022-40 | refinedweb | 632 | 61.06 |
Getting Started With Docker for Java Applications: Setting Up a CI/CD Pipeline
Getting Started With Docker for Java Applications: Setting Up a CI/CD Pipeline
This article is a guide to containerizing an existing Java web application and using Jenkins to set up an end-to-end deployment pipeline.
Join the DZone community and get the full member experience.Join For Free
Read why times series is the fastest growing database category.
Docker is already quite famous and more organizations are moving to Docker-based application development and deployment. Here is a quick guide on how to containerize an existing Java web application and set up an end to end deployment pipeline for it using Jenkins.
I am using the very famous Spring based pet store application for this, and it represents a good sample, as most applications follow a similar architecture.
Steps
- Build the Petstore application.
- Run a Sonar quality check on this.
- Prepare the Docker image with the web application.
- Run the container and execute integration tests.
- If the tests are successful, push the image to a dockerhub account.
All the code is available here.
Here is the Jenkins pipeline code which can be used for the above steps:
node { stage 'checkout' git '' stage 'build' sh 'mvn clean install' stage('Results - 1') { junit '**/target/surefire-reports/TEST-*.xml' archive 'target/*.jar' } stage 'bake image' docker.withRegistry('','docker-hub-credentials') { def image = docker.build("ravisankar/ravisankardevops:${env.BUILD_TAG}",'.') stage 'test image' image.withRun('-p 8888:8888') {springboot -> sh 'while ! httping -qc1; do sleep 1; done' git '' sh 'mvn clean verify' } stage('Results') { junit '**/target/surefire-reports/TEST-*.xml' archive 'target/*.jar' } stage 'push image' image.push() } }
The initial steps just check out the code and run the build. The interesting part starts with this step, which runs within a Docker context using dockerhub credentials
step 3 'bake image' docker.withRegistry('','docker-hub-credentials')
This step builds the Docker image. The Docker build command takes your dockerhub repository name and the tag name as one argument and your build location as another argument.
def image = docker.build("dockerhub registry name":"tag name",'location of docker file'). def image = docker.build("ravisankar/ravisankardevops:${env.BUILD_TAG}",'.')
This uses the Dockerfile to build the Docker image. The contents of the Docker file:
FROM tomcat:8 ADD target/*.war /usr/local/tomcat/webapps
The next step is to run the image and run tests on it.
stage 'test image' image.withRun('-p 8888:8888') { springboot -> sh 'while ! httping -qc1; do sleep 1; done' git '' sh 'mvn clean verify' }
The withRun step helps you to run the Docker image you just built and expose the port where this application can be exposed. I have another test code base which is built and executed which will run tests on the image that is running.
The final step is pushing the image to a dockerhub registry or any internal registry setup in your organization.
stage('Results') { junit '**/target/surefire-reports/TEST-*.xml' archive 'target/*.jar' } stage 'push image' image.push()
Learn how to get 20x more performance than Elastic by moving to a Time Series database.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/getting-started-with-docker-for-java-applications | CC-MAIN-2018-34 | refinedweb | 540 | 51.24 |
AWS Lambda Function + Kubernetes
Bütçe $30-250 USD
Create a lambda function, which will pull some values from MongoDB, and using those values it will do the following in Kubernetes:
1. Create a namespace,
2. Create pod for application frontend
3. Create pod for the application backend
4. Create route 53 DNS endpoint for frontend and backend depending on the hostname provided by value from MongoDB
Bu iş için 8 freelancer ortalamada $206 teklif veriyor
Hi. I am a skilled engineer with 8+ years experience in Amazon Web Services, Node.js, Kubernetes, NoSQL Couch & Mongo and Express JS. An experienced programmer, able to learn and adapt quickly to new technologies. I've Daha Fazla
Dear Sir, I'm well versed in Node.js, [login to view URL], AWS SAM, Lambda, API Gateway, S3, etc. I'm also knowledgeable in Docker, and a little bit familiar with Kubernetes. I can develop and deploy a Lambda function with AP Daha Fazla
we will do your kubernetes work I'm an experienced Linux system administrator with more than 5 years of experience in enterprise environments working mainly with RHEL (5,6 and 7) and SLES (10,11 and 12). I'm working wi
Hi, I checked your project AWS Lambda Function + Kubernetes" carefully. I am familiar to AWS . I have developed a lot of websites with AWS .I will also work full [login to view URL]’s talk so you can begin to understand why my c Daha Fazla
Hello, Hope you are doing well, I checked your project description and understand the whole requirement. We are professional web developer and we will help you to build a similar website like the link you provided. W Daha Fazla
Hello, thanks for your posting. As a skilled full stack developer, I've rich experience with javascript framework such as MERN/MEAN. And I've developed lots of web sites using MERN stack and hosted them on AWS Lamda Daha Fazla
Hi, I am Aws certified solutions architect- Professional and associate. I have extensive experience in architecting and delivering container and serve less architecture. I have great exposure to aws services and have Daha Fazla | https://www.tr.freelancer.com/projects/nodejs/aws-lambda-function-kubernetes/?ngsw-bypass=&w=f | CC-MAIN-2021-49 | refinedweb | 360 | 55.54 |
[security] Introducing signing support to MySens;3;0;9;read: 10-10-0 s=255,c=3,t=15,pt=2,l=2,sg=0:1 0;0;3;0;9;send: 0-0-10-10 s=255,c=3,t=15,pt=2,l=2,sg=0,st=ok:1 0;0;3;0;9;read:.
@Anticimex:
ok, it is good to know. You have thought about everything!
If signer(true) for gateway, Will the controller (Jeedom, Domoticz..) see a crypted payload in serial transmission or will it work like before (I understand there are some changes in message structure, but what about crypted payload, does the controller need to decrypt?)
@scalz We only sign messages. There is no encryption involved. And the signature is stored without affecting the message contents so it is perfectly compatible with all controllers. The only thing that could affect a controller is the new sign bit in the message header but I don't think that will make any difference as it is not relevant to the controller. It is the gateway that manages this for it.
ok, it is new for me, so I am mixing vocabulary, but I understand the concept. Thank you, and now I have my answer. no big changes for controller side, great! It makes sense, but I was not sure.
Fix pushed to development.
Thanks for that!
I put together a garage door opening using code from korttoma. I used soft signing, and it works great. I was wanting to use a real atsha though.
I bought some atsha204a chips from amazon, and the chips are marked with only "3eas", and a "Y" in one corners. They are soic-8. Is that how this should be marked? I wired one up according to the data sheet. Gnd to Gnd, VCC to 5V, and SDA to A3. I ran the personalizer to generate a key and it said "Failed to wake device." in the serial console. Am I doing something wrong? or did I just get the wrong chip from the seller?
@jsondag I don't have a good explanation on the software signing not working. Maybe inadequate decoupling leads to a too noisy power rail?
About the HW issue, it is important that you use the single wire version of atsha204. NOT the i2c version. The i2c version also has an scl line while the single wire only has sda (and power and ground). That means your soic8 should have 5 unused pads. Atmel ordering code for that variant is ATSHA204A-SSHCZ-T but unfortunately it is not printed on the case. So unless you find that information from Amazon, I am afraid it is very difficult to determine the type of the chips you've got.
@Anticimex. Software signing is working fine.
Thanks for the information though. I didn't realize the soic 8 couldn't do one wire. It's a ATSHA204-SH-DA-B according to the listing.
EDIT:
Looking at the datasheet, it says that the SCL pin can be ignored for single wire interface. perhaps I'll wire another one up and give it a go.
Just connect, SDA to A3, correct?
@jsondag ok. From what I could read there are two different order codes for i2c and one-wire so I don't think you can take an i2c variant board and treat it as a one-wire board by just ignoring the scl pin. But if the board really is single-wire, the pinout will be the same as the i2c version, you can just ignore the scl pin as it is NC for the one-wire variant. And from the data sheet, SHDAB is i2c not "single-wire" so I am afraid you cannot use my libs for those. I only have drivers for single-wire chips i am afraid.
I just received my chips today from digikey (part num ATSHA204A-STUCZ-TCT-ND) which are the small 3 pin versions. Holy cow these are things are tiny. These are going to be a lot more difficult than I expected to hand solder.
)
@Anticimex said:
)
Thanks - I'll try that as soon as everything arrives. Watching parts trickle in from aliexpress shippers is killing me (I think I've become spoiled on Amazon prime shipping).
First of all I would like to thank Anticimex for this great piece of work!
I am playing around with signing right now. I set up a temp & humid sensor with soft signing support as well as a MQTT gateway with soft signing.
In principle it seems to work. At least sensor values are published to the MQTT broker. However, in the gateway output I see nonce tr errors and sign failures.
Started! 0;0;3;0;9;read: 21-21-0 s=1,c=3,t=16,pt=0,l=0,sg=0: 0;0;3;0;9;send: 0-0-21-21 s=255,c=3,t=17,pt=6,l=25,sg=0,st=ok:0107FD2B06D 0;0;3;0;9;send: 0-0-21-21 s=1,c=3,t=16,pt=0,l=0,sg=0,st=ok: 0;0;3;0;9;read: 21-21-0 s=2,c=1,t=1,pt=7,l=5,sg=1:59.0 publish: MyMQTT/21/2/V_HUM 59.0D5F523C2778AA 0;0;3;0;9;read: 21-21-0 s=1,c=3,t=16,pt=0,l=0,sg=0: 0;0;3;0;9;send: 0-0-21-21 s=255,c=3,t=17,pt=6,l=25,sg=0,st=ok:01048819A79B 0;0;3;0;9;send: 0-0-21-21 s=1,c=3,t=16,pt=0,l=0,sg=0,st=ok: 0;0;3;0;9;read: 21-21-0 s=2,c=1,t=1,pt=7,l=5,sg=1:59.2 publish: MyMQTT/21/2/V_HUM 59.220D83204D1A06 0;0;3;0;9;read: 21-21-0 s=1,c=3,t=16,pt=0,l=0,sg=0: 0;0;3;0;9;send: 0-0-21-21 s=255,c=3,t=17,pt=6,l=25,sg=0,st=ok:01AB763CD41 0;0;3;0;9;read: 21-21-0 s=2,c=1,t=1,pt=7,l=5,sg=1:59.3 publish: MyMQTT/21/2/V_HUM 59.3 0;0;3;0;9;send: 0-0-21-21 s=1,c=3,t=16,pt=0,l=0,sg=0,st=fail: 0;0;3;0;9;nonce tr err 0;0;3;0;9;send: 0-0-21-21 s=2,c=3,t=16,pt=0,l=0,sg=0,st=fail: 0;0;3;0;9;nonce tr err
I am somehow irritated concerning those failures logged after the publish logs. They seem not to be related to receiving and publishing the sensor data. What can be source of that? Why might the gateway trying to transmit?
A second question is related to personalization of the ATSHA204. Am I right that the key is displayed in the SlotConfig00 - SlotConfig0F?
The second personalization step fails with the message "Data lock failed". What could be the reason for that?
@tomkxy Thanks.
"nonce tr err" is sent if sendRoute() fails to send a nonce request. So it suggests the radio link is somewhat unreliable and that in turn causes signing to fail. From what I can see you want to sign messages in both directions, so maybe traimsission from the MQTT gateway is not as reliable as reception? message type 16 (command 3) is a nonce request and sometimes it succeeds
0;0;3;0;9;send: 0-0-21-21 s=1,c=3,t=16,pt=0,l=0,sg=0,st=ok:
and sometimes it fail (with that message as consequence):
0;0;3;0;9;send: 0-0-21-21 s=2,c=3,t=16,pt=0,l=0,sg=0,st=fail: 0;0;3;0;9;nonce tr err
But the failing one is to a different sensor (2) than the first one (1), so perhaps that node is down or at a long range? But last in your log you also fail a transmission to sensor 1. In any case, the nonce tr err is because of failing radio transmissions and as such not a signing issue as such. Sometimes it works (when there are no radio issues:
0;0;3;0;9;read: 21-21-0 s=1,c=3,t=16,pt=0,l=0,sg=0: (request for nonce to GW) 0;0;3;0;9;send: 0-0-21-21 s=255,c=3,t=17,pt=6,l=25,sg=0,st=ok:01AB761 (GW sends nonce back) 0;0;3;0;9;read: 21-21-0 s=1,c=1,t=0,pt=7,l=5,sg=1:25.1 (signed message with that nonce is received) publish: MyMQTT/21/1/V_TEMP 25.1 (message/signature is accepted and forwarded)
"sign fail" is typically reported if nonce exchange times out. You can adjust the timeout using MY_VERIFICATION_TIMEOUT_MS if you have many hops or for other reasons cannot process messages fast enough.
I have not tested MQTT gateway myself, and perhaps it uses the MySensors library differently but I have tested both serial and ethernet gateway. But in this case, it probably fails because you never got the request for the nonce out so your sender never got a chance to send a nonce back, and therefore signing cannot succeed.
So the key is to determine why the transmission of the nonce request fail (a radio problem since you get st=fail). Or implement a retransmission at a higher level in your sketch if the radio link is "lossy". The signing backend assumes a working channel and do not handle retransmission for you on failures.
Regarding personalization, key is never displayed. It is stored in slot 0. Slotconfigs are used to set the permissions of the slots. They don't store keys themselves.
You should get the reason for the data lock failure in the code that is sent together with the message. It is the ATSHA circuit itself that provide this value (or the library communicating with it in case of communication problem).
Thanks for your fast reply. Regarding the communication failures: I was testing this with both transmitters lying side by side. Do you have any idea why the gateway might want to have a nonce. Is it part of the sensor protocol?
The two sensors displayed in the log are basically the same sensor (DHT22 providing temp and humidity).
With respect to the key topic: The first personalization step provides the following output:
Device revision: 00020009 Device serial: {0x01,0x23,0x48,0xC9,0x51,0x6A,0x1A,0x06,0xEE} 012348C9516A1A06EE | 55
Can I provide any key in the second personalization step or does it have to be same than in the first step being generated?
@tomkxy The protocol is described in the first post. Any node that is sending a signed message to another node (that has requested to get signed messages) will ask for a nonce. So you have configured your gateway to require signed messages as well as your node.
Regarding the personalization, I do t understand your question. The output is the chip configuration. It does not list any keys. I am not sure I understand what you mean by second step. You can generate a random key and that key you store and after you store it you have an option to also lock it, but then you have no way of ever changing it. I have documented the personalization flow also in the sketch itself..
@Anticimex: The output shown is related to the sketch configuration you described in your description:.
I was wondering that I did not see any explicit reference to a key. So may be I just have to retry..
Thanks for that clarification. I was aware of that.
@tomkxy are you sure you have enabled all those options? According to the dump, your configuration is still not locked and therefore no randomized key can be generated. Are there no more output from the sketch than that? You mentioned failure to lock data zone but I cannot see that message. And you cannot lock datazone without locking configuration.
After the sketch locks configuration it will print a randomized key in the log.
@Anticimex: Thanks for your patience and your support.
I rerun it with the output and sketch configuration listed below. May be the reason that it is not working that my poor soldering skills bricked the device.
Extract from sketch (1st run):
…
Output:
ATSHA204 personalization sketch for MySensors usage. ---------------------------------------------------- Disable SKIP_KEY_STORAGE to store key. Data not locked. Define LOCK_DATA to lock for real. -------------------------------- Personalization is now complete. Configuration is LOCKED Data is UNLOCKED
Second run with the following sketch settings (key used removed):
#ifdef USER_KEY_DATA #define MY_HMAC_KEY 0x… const uint8_t user_key_data[32] = {MY_HMAC_KEY}; #endif const int sha204Pin = ATSHA204_PIN; atsha204Class sha204(sha204Pin); Using this user supplied key: #define MY_HMAC_KEY 0x….. Writing key to slot 0... Data lock failed. Response: D3 Halting!
@tomkxy I'm on phone so I cannot check the response code right now but you could look it up in the atsha datasheet or in the software. I have not tried to lock data myself and I do not recommend it because it makes it impossible to change the key later on if it is comprised. From what I can see, everything looks good except the locking of the datazone (your key)
@tomkxy I should add that from the logs I see that you do have successfully stored your key, so unless you really want to lock down the key, personalization is done and successful.
@Anticimex: Thanks a lot. I didn't intend to lock the data zone.
Btw, I did some tests regarding the nonce failure the gateway showed. I think the reason is rather simple. The gateway tried - for reasons I still don't understand - send data to the sensor for which it tried to get a nonce. The sensor however was powered down which is probably the reason why no nonce was sent. At least this error didn't show up when I removed the power down and replaced it by a simple call to delay.
@tomkxy Ah, I see. Well then that matter should be sorted.
Regarding your radio issue, yes, if the GW wants to send data to your node, it needs to be up&running. From the log you sent, I cannot determine what data the GW tried to send though, since it (because your node has told the GW it require it) wants to sign the message to send, and fails, the actual message is never showed in the log.
Perhaps you could send a log with your node continuously powered and we could see at least the type of message your GW tries to send. That could help to identify why it tries to send the message in the first place.
@Anticimex: I started a new thread
because it looks like it is not really related to signing.
In the post I included the log output of the message for which the nonce is being requested. It looks like the gateway node is sending back the humidity with a c=1 command. Somehow this does not make sense to me.
@tomkxy I see. Perhaps you request ACK or something like that. But ACKs are not signed. I have seen to that, so probably not. I am not too well into the non-signing aspects of the network though, so hopefully someone else perhaps can give a hint on what's wrong. Could be the sketch itself. I am glad we sorted the signing issues anyway
@Anticimex: I found the issue with respect to the gateway sending a message back to the sensor. This is due to the gateway subscribing to all topics on the MQTT broker. Once it receives a message it sends it to the sensor as SET message. I have to resolve that one.
I think, I still have an issue with signing which I need to get sorted myself first. I will let you know.
@tomkxy Alright. Good to know that you found the root cause for the message issue.
Regarding signing, from what I could see at least some signed messages did come through, so you should at least have the proper shared states (keys) and configs.
I did a few test with my ATSHA204. I could get it working on an Uno. The I took the chip and placed it on my breadboard with my ProMini. I tried to run the SHA Personaliser Sketch again just to make sure that the chip is somehow working and I received an error message that the device cannot be woken up.
Since it worked on the Uno (including running the SHA Personalizer) it must be related to the ProMini (3.3V / 8 MHz).
To what pin do I have to connect the data line?
@tomkxy That sounds strange. I have run on ProMini 3.3V/8MHz without issues.
Default is to use A3 for the ATSHA204A. It does not really matter which pin you connect it as long as it is usable for digital I/O (and update MY_ATSHA204_PIN accordingly or provide your pin to the MySigningAtsha204 constructor).
How do I change the pin definition if I use A3 on the ProMini?
A3 is default setting. You can find the definition of MY_ATSHA204_PIN in MyConfig.h.
Yep, it is
`#define MY_ATSHA204_PIN 17 // A3 - pin where ATSHA204 is attached `` I am just irritate by the 17. So this does map to A3 even on ProMini?
@Anticimex Unfortunately, I am now in a total state of mess. It seems that nothing works anymore the moment I turn on any signing. For sure, I have a problem with ATSHA204 and the ProMini which I need to sort out separately. I tried them all with my Uno (reading out the config) which worked. When I try to just read the config with my ProMini I get the error cannot wake up device.
But now, even soft signing did not work any longer (it worked first, than I made changes and afte. I just receive nonce transmission errors from the sensor to the gateway although both radios are side by side and transmission without signing works perfectly.
Btw, what is stored in the EPROM and under what circumstances do I have to clear EPROM first. I changed between the various signing feature (soft signing, HW signing, signing required etc.) back and forth and it seems that this info is stored in EPROM and somehow not cleared?? How does the sensor know that the gateway requires signing? Will it get the info out of EPROM? Will this information be updated during presentation?
I think you did a great job on that implementation, the more frustrating it is that I cannot get it to work reliably. I am out for today. May be I find some time tomorrow getting anot ProMini prepared to checkout the issue with the chips.
@tomkxy The information stored in EEPROM is not specific to any backend. It just informs the node what other nodes require signed messages. At startup, a node broadcasts it's preference to the gateway which then updates it's EEPROM table and replies with its own preference back so the node knows if the gateway wants signed messages as well. If the preferences differ from what is stored in EEPROM already, it is the updated preferences that will replace the stored preferences.
The usecases for this is if you were to deploy a new sensor which require signing, it would inform gateway of this at startup. But if you restart your gateway it would loose this unless it was stored in EEPROM (the same goes the other way around) so the EEPROM is used so that the signing rules in the network gets preserved even if nodes dissappear or restart.
If you suspect the EEPROM to contain corrupt data, you can clear it with the cleareeorom sketch/example.
The typical circumstance you need to clear EEPROM under is when you switch library version, and the reserved region of EEPROM in the library change (and you also use EEPROM in your sketch). Then the library might take some of your sketch data for "it's own" and that can/will lead to unpredictable results..
See you soon.
Good idea - I'm finding soldering the ATSHA chips to be a real pain and a small breakout board would help with that. Is the eeprom pads on your board for people who are just using a mega328 chip? Doesn't a pro-mini already have enough eeprom on board?
@TDD22057: eeprom on the breakout is for the new ota in Mysensors (over the air upload sketch) . It is not related to authentication.
I made this cheap breakout firstly because I wanted to test the new Mysensors features easily. and I thought it could be useful in some specific case where you don't need to make a pcb for one specific usercase so you use a veroboard and so you can easily add these new features with less pain...
Happy it can help some people
Regarding my issue with the ATSHA204A, I did some testing with the following results. I soldered the ATSHA204A on a small breakout board and loaded the SHAPersonalizer sketch.
I tested three configurations:
- Breakout wired to the ProMini without breadboard use
- Breakout wired to a breadboard where the ProMini was plugged
- Breakout and ProMini both plugged to breadboard and connected by wires.
Config 3 does not work!!!
That means the breadboard significantly changes the electrical characteristics. Is anybody on the forum who is able to explain that?
@tomkxy: it is strange. My first tests have been done in you config 3 (atsha breakout and promini both plugged to breadboard). And it worked well for me. Could it be your wire quality??? I had problems with some Dupont wire once...
Well , could be... I had to use different wires female - female, male - female, male - male (for config 3). For the male-male wire I have no other option at the moment.
However, I am glad it works now.
Well , could be... I had to use different wires female - female, male - female, male - male (for config 3). For the male-male wire I have no other option at the moment.
However, I am glad it works now.
Good news! Regarding breadboard issues, it could be that you need an additional decoupling on the VCC line to the atsha204a. And also perhaps a pullup on the SDA signal. Breadboards usually put some more requirements on noise suppression.
Hi,
I seem to be too stupid (or drunk
) to get this working with MySigningAtsha204Soft
Is anyone willing to provide a working MyConfig.h and EthernetGateway.ino for this?
There seemed to be some changes and I am sure, I am just too dumb...
Here you go....However, I do not have EthernetGateway but a MQTTClientGateway. May be it is of help.
What is your specific problem?
myconfig.h (key. */ #ifndef MyConfig_h #define MyConfig_h #include <stdint.h> // Enable debug flag for debug prints. This will add a lot to the size of the final sketch but good // to see what is actually is happening when developing #define DEBUG // Serial output baud rate (for debug prints and serial gateway) #define BAUD_RATE 115200 /********************************** * Over the air firmware updates ***********************************/ // The following define enables the safe over-the-air firmware update feature // which requires external flash and the DualOptiBoot bootloader. // Note: You can still have OTA FW updates without external flash but it // requires the MYSBootloader and disabled MY_OTA_FIRMWARE_FEATURE //#define MY_OTA_FIRMWARE_FEATURE // Slave select pin for external flash #define MY_OTA_FLASH_SS 8 // Flash jdecid #define MY_OTA_FLASH_JDECID 0x1F65 /********************************** * Information LEDs blinking ***********************************/ // This feature enables LEDs blinking on message receive, transmit // or if some error occured. This was commonly used only in gateways, // but now can be used in any sensor node. Also the LEDs can now be // disabled in the gateway. //#define WITH_LEDS_BLINKING // The following setting allows you to inverse the blinking feature WITH_LEDS_BLINKING // When WITH_LEDS_BLINKING_INVERSE is enabled LEDSs are normally turned on and switches // off when blinking //#define WITH_LEDS_BLINKING_INVERSE // default LEDs blinking period in milliseconds #define DEFAULT_LED_BLINK_PERIOD 300 // The RX LED default pin #define DEFAULT_RX_LED_PIN 6 // The TX LED default pin #define DEFAULT_TX_LED_PIN 5 // The Error LED default pin #define DEFAULT_ERR_LED_PIN 4 /********************************** * Message Signing Settings ***********************************/ // Disable to completly disable signing functionality in library #define MY_SIGNING_FEATURE // Define a suitable timeout for a signature verification session // Consider the turnaround from a nonce being generated to a signed message being received // which might vary, especially in networks with many hops. 5s ought to be enough for anyone. #define MY_VERIFICATION_TIMEOUT_MS 5000 // Enable to turn on whitelisting // When enabled, a signing node will salt the signature with it's unique signature and nodeId. // The verifying node will look up the sender in a local table of trusted nodes and // do the corresponding salting in order to verify the signature. // For this reason, if whitelisting is enabled on one of the nodes in a sign-verify pair, both // nodes have to implement whitelisting for this to work. // Note that a node can still transmit a non-salted message (i.e. have whitelisting disabled) // to a node that has whitelisting enabled (assuming the receiver does not have a matching entry // for the sender in it's whitelist) //#define MY_SECURE_NODE_WHITELISTING // MySigningAtsha204 default setting #define MY_ATSHA204_PIN 17 // A3 - pin where ATSHA204 is attached // MySigningAtsha204Soft default settings #define MY_RANDOMSEED_PIN 7 // A7 - Pin used for random generation (do not connect anything to this) // Key to use for HMAC calculation in MySigningAtsha204Soft (32 bytes) #define MY_HMAC_KEY 0x10,0x23,0xBB,0x78,0x77,0x35,0xB0,0x01,0x70,0x47,0xF1,0xDE,0x21,0x94,0x54,0x67,0xEE,0x36,0x72,0x00,0x97,0x12,0xA0,0x0A,0x0F,0x09,0x03,0xE2,0x00,0x31,0xE4,0x41 /********************************** * NRF24L01 Driver Defaults ***********************************/ #define RF24_CE_PIN 9 #define RF24_CS_PIN 10 #define RF24_PA_LEVEL RF24_PA_MAX #define RF24_PA_LEVEL_GW RF24_PA_LOW // RF channel for the sensor net, 0-127 #define RF24_CHANNEL 76 //RF24_250KBPS for 250kbs, RF24_1MBPS for 1Mbps, or RF24_2MBPS for 2Mbps #define RF24_DATARATE RF24_250KBPS // This is also act as base value for sensor nodeId addresses. Change this (or channel) if you have more than one sensor network. #define RF24_BASE_RADIO_ID ((uint64_t)0xA8A8E1FC00LL) // Enable SOFTSPI for NRF24L01 when using the W5100 Ethernet module //#define SOFTSPI #ifdef SOFTSPI // Define the soft SPI pins used for NRF radio const uint8_t SOFT_SPI_MISO_PIN = 16; const uint8_t SOFT_SPI_MOSI_PIN = 15; const uint8_t SOFT_SPI_SCK_PIN = 14; #endif /********************************** * RFM69 Driver Defaults ***********************************/ // Default network id. Use the same for all nodes that will talk to each other #define RFM69_NETWORKID 100 // Default frequency to use. This must match the hardware version of the RFM69 radio (uncomment one): // #define RFM69_FREQUENCY RF69_433MHZ #define RFM69_FREQUENCY RF69_868MHZ //#define FREQUENCY RF69_915MHZ // Enable this for encryption of packets //#define RFM69_ENABLE_ENCRYPTION #define RFM69_ENCRYPTKEY "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes! #endif
/* MyMQTT Client Gateway 0.1b Created by Norbert Truchsess <norbert.truchsess@t-online.de> Based on MyMQTT-broker gateway created by Daniel Wiegert <daniel.wiegert@gmail.com> Based on MySensors Ethernet Gateway by Henrik Ekblad <henrik.ekblad@gmail.com> Requires MySensors lib 1.4b * libraries\MySensors: Changes by Thomas Krebs <thkrebs@gmx.de> - Add signing support from MySensors 1.5 and update for MySensors 1.5; - Restructured code back to a C like implementation following the existing MQTTGateway */ #include <SPI.h> #include <MySensor.h> #include "MyMQTTClient.h" #include "PubSubClient.h" #include <Ethernet.h> #include <DigitalIO.h> #include <MsTimer2.h> #include <Time.h> #ifdef MY_SIGNING_FEATURE #include <MySigningNone.h> #include <MySigningAtsha204Soft.h> #include <MySigningAtsha204.h> #endif //#define DSRTC #ifdef DSRTC #include <Wire.h> #include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t #endif /* * To configure MQTTClientGateway.ino to use an ENC28J60 based board include * 'UIPEthernet.h' (SPI.h required for MySensors anyway). The UIPEthernet-library can be downloaded * from: */ //#include <UIPEthernet.h> /* * To execute MQTTClientGateway.ino on Yun uncomment Bridge.h and YunClient.h. * Do not include Ethernet.h or SPI.h in this case. * On Yun there's no need to configure local_ip and mac in the sketch * as this is configured on the linux-side of Yun. */ //#include <Bridge.h> //#include <YunClient.h> // **/ // CE_PIN and SPI_SS_PIN for Mega #define RADIO_CE_PIN 48 // radio chip enable #define RADIO_SPI_SS_PIN 49 // radio SPI serial select #define RADIO_ERROR_LED_PIN A2 // Error led pin #define RADIO_RX_LED_PIN A1 // Receive led pin #define RADIO_TX_LED_PIN A0 // the PCB, on board LED*/ / }; ////////////////////////////////////////////////////////////////// #if defined remote_ip && defined remote_host #error "cannot define both remote_ip and remote_host at the same time!" #endif #ifdef _YUN_CLIENT_H_ YunClient ethClient; #else EthernetClient ethClient; #endif //////////////////////////////////////////////////////////////// // NRFRF24L01 radio driver (set low transmit power by default) MyTransportNRF24 transport(RADIO_CE_PIN, RADIO_SPI_SS_PIN, RF24_PA_LEVEL_GW); //MyTransportRFM69 transport; // Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) //MySigningNone signer; MySigningAtsha204Soft signer; //MySigningAtsha204 signer; // Hardware profile MyHwATMega328 hw; MyMessage msg; char convBuf[MAX_PAYLOAD * 2 + 1]; uint8_t buffsize; char buffer[MQTT_MAX_PACKET_SIZE]; //////////////////////////////////////////////////////////////// volatile uint8_t countRx; volatile uint8_t countTx; volatile uint8_t countErr; //////////////////////////////////////////////////////////////// void processMQTTMessages(char* topic, byte* payload, unsigned int length); PubSubClient client(remote_ip, remote_port, processMQTTMessages, ethClient); //////////////////////////////////////////////////////////////// // Declare and initialize MySensor instance // Construct MyMQTTClient (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h, if signing // feature not to be used, uncomment) // To use LEDs blinking, uncomment WITH_LEDS_BLINKING in MyConfig.h MySensor gw(transport, hw #ifdef MY_SIGNING_FEATURE , signer #endif #ifdef WITH_LEDS_BLINKING , RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN #endif ); /* * setup */ void setup() { countRx = 0; countTx = 0; countErr = 0; Ethernet.begin(mac, local_ip); //Bridge.begin(); delay(1000); // Wait for Ethernet to get configured. begin(); } /* * loop */ void loop() { if (!client.connected()) { client.connect("MySensor"); client.subscribe(MQTT_TOPIC_MASK); } client.loop(); gw.process(); } /* * processRadioMessage * * Receives radio message, parses it and forwards it to the MQTT broker */ void processRadioMessage(const MyMessage &message) { rxBlink(1); sendMQTT(message); } /* * sendMQTT * Handles processing of radio messages and eventually publishes it to the MQTT broker */ void sendMQTT(const MyMessage &inMsg) { MyMessage msg = inMsg; buffsize = 0; if (!client.connected()) return; //We have no connections - return if (msg.isAck()) { #ifdef DEBUG Serial.println("msg is ack!"); #endif, GATEWAY_ADDRESS, msg.sender, 255, C_INTERNAL, I_CONFIG, 0).set("M"))) errBlink(1); } else if (msg.type == I_TIME) { #ifdef DEBUG Serial.println("I_TIME requested!"); #endif txBlink(1); if (!gw.sendRoute( build(msg, GATEWAY_ADDRESS, msg.sender, 255, C_INTERNAL, I_TIME, 0).set(now()))) errBlink(1); }, GATEWAY_ADDRESS, msg.sender, 255, C_INTERNAL, I_ID_RESPONSE, 0).set(newNodeID))) errBlink(1); } else if (msg.type == I_BATTERY_LEVEL) { strcpy_P(buffer, mqtt_prefix); buffsize += strlen_P(mqtt_prefix); buffsize += sprintf(&buffer[buffsize], "/%i/255/BATTERY_LEVEL\0", msg.sender ); msg.getString(convBuf); #ifdef DEBUG Serial.print("publish: "); Serial.print((char*) buffer); Serial.print(" "); Serial.println((char*) convBuf); #endif client.publish(buffer, convBuf); } else if (msg.type == I_SKETCH_NAME) { strcpy_P(buffer, mqtt_prefix); buffsize += strlen_P(mqtt_prefix); buffsize += sprintf(&buffer[buffsize], "/%i/255/SKETCH_NAME\0", msg.sender ); msg.getString(convBuf); #ifdef DEBUG Serial.print("publish: "); Serial.print((char*) buffer); Serial.print(" "); Serial.println((char*) convBuf); #endif client.publish(buffer, convBuf); } else if (msg.type == I_SKETCH_VERSION) { strcpy_P(buffer, mqtt_prefix); buffsize += strlen_P(mqtt_prefix); buffsize += sprintf(&buffer[buffsize], "/%i/255/SKETCH_VERSION\0", msg.sender ); msg.getString(convBuf); #ifdef DEBUG Serial.print("publish: "); Serial.print((char*) buffer); Serial.print(" "); Serial.println((char*) convBuf); #endif client.publish(buffer, convBuf); } } else if (mGetCommand(msg) != 0) { if (mGetCommand(msg) == 3) msg.type = msg.type + (S_FIRSTCUSTOM - 10); //Special message if (msg.type > VAR_TOTAL) msg.type = VAR_TOTAL; // If type > defined types set to unknown. strcpy_P(buffer, mqtt_prefix); buffsize += strlen_P(mqtt_prefix); buffsize += sprintf(&buffer[buffsize], "/%i/%i/V_%s\0", msg.sender, msg.sensor, getType(convBuf, &VAR_Type[msg.type])); msg.getString(convBuf); #ifdef DEBUG Serial.print("publish: "); Serial.print((char*) buffer); Serial.print(" "); Serial.println((char*) convBuf); #endif client.publish(buffer, convBuf); } } } /* * build * Constructs a radio message */ inline MyMessage& build(MyMessage &msg, uint8_t sender, uint8_t destination, uint8_t sensor, uint8_t command, uint8_t type, bool enableAck) { msg.destination = destination; msg.sender = sender; msg.sensor = sensor; msg.type = type; mSetCommand(msg, command); mSetRequestAck(msg, enableAck); mSetAck(msg, false); return msg; } /* * getType */ char *getType(char *b, const char **index) { char *q = b; char *p = (char *) pgm_read_word(index); while (*q++ = pgm_read_byte(p++)) ; *q = 0; return b; } /* * begin * wraps MySensors begin method; setup of RTC and led timers interrupt */ void begin() { #ifdef DEBUG Serial.begin(BAUD_RATE); #endif #ifdef DSRTC // Attach RTC setSyncProvider(RTC.get); // the function to get the time from the RTC setSyncInterval(60); #endif gw.begin(processRadioMessage, 0, true, 0); MsTimer2::set(200, ledTimersInterrupt); MsTimer2::start(); #ifdef DEBUG Serial.print(getType(convBuf, &VAR_Type[S_FIRSTCUSTOM])); #endif } /* * processMQTTMessages * message handler for the PubSubClient */ void processMQTTMessages(char* topic, byte* payload, unsigned int length) { processMQTTMessage(topic, payload, length); } /* * processMQTTMessage * processes MQTT messages, parses the topic, extracts radio address out of topic and sends them * to the respective radio */ void processMQTTMessage(char* topic, byte* payload, unsigned int length) { char *str, *p; uint8_t i = 0; buffer[0] = 0; buffsize = 0; uint8_t cmd = -1; for (str = strtok_r(topic, "/", &p); str && i < 5; str = strtok_r(NULL, "/", &p)) { switch (i) { case 0: { if (strcmp_P(str, mqtt_prefix) != 0) { //look for MQTT_PREFIX return; //Message not for us or malformatted! } break; } case 1: { msg.destination = atoi(str); //NodeID break; } case 2: { msg.sensor = atoi(str); //SensorID break; } case 3: { char match = 0; //SensorType //strcpy(str,(char*)&str[2]); //Strip VAR_ for (uint8_t j = 0; strcpy_P(convBuf, (char*) pgm_read_word(&(VAR_Type[j]))); j++) { if (strcmp((char*) &str[2], convBuf) == 0) { //Strip VAR_ and compare match = j; break; } if (j >= VAR_TOTAL) { // No match found! match = VAR_TOTAL; // last item. break; } } msg.type = match; break; } case 4: { // support the command get and set; get will be mapped to a C_REQ and set to C_SET if (strcmp(str,MQTT_CMD_SET) == 0) { cmd = C_SET; } else if (strcmp(str,MQTT_CMD_GET) == 0) { cmd = C_REQ; } else { #ifdef DEBUG Serial.print("Received unsupported command - ignore: "); Serial.println(str); #endif } } } i++; } //Check if packge has payload if (cmd != -1) { char* ca; ca = (char *)payload; ca += length; *ca = '\0'; msg.set((const char*)payload); //Payload txBlink(1); // inject time if ((msg.destination == 0) && (msg.sensor == 199)) { unsigned long epoch = atol((char*)payload); if (epoch > 10000) { #ifdef DSRTC RTC.set(epoch); // this sets the RTC to the time from controller - which we do want periodically #endif setTime(epoch); } #ifdef DEBUG Serial.print("Time recieved "); Serial.println(epoch); #endif } // if (!gw.sendRoute( build(msg, GATEWAY_ADDRESS, msg.destination, msg.sensor, C_SET, msg.type, 0))) errBlink(1); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Led handling ////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * ledTimersIntterupt */; } }
@tomkxy Thanks, that helped! I seemed to have two problems:
- I did not know where to place the necessary includes! Thanks for the examples! Helped me a lot
2)Regarding my problems from above (error: 'DEFAULT_CE_PIN' was not declared in this scope): I removed the whole libraries/MySensors dir and copied it again from the recent devel branch - this helped, error is gone and everything is compiling fine now
Thanks again and cheers,
Otto
@otto001 Great! And thanks @tomkxy for helping out. MySensors teamwork at it's best. This is what it's all about
Hi again,
and thanks again. signing seems to work now, unfortunately the sketch is too big for an UNO and I am right now struggling with the pinout and code adaptions to get it working with my W5100 shield and a mega...
/edit: got it working.
MyConfig.h: #ifdef SOFTSPI // Define the soft SPI pins used for NRF radio //MEGA const uint8_t SOFT_SPI_MISO_PIN = 15; const uint8_t SOFT_SPI_MOSI_PIN = 14; const uint8_t SOFT_SPI_SCK_PIN = 16; #endif EthernetGateway.ino: #define RADIO_CE_PIN 35 // 5 // radio chip enable #define RADIO_SPI_SS_PIN 34 // 6 // radio SPI serial select
And exactly those pins I connected from radio to the mega... (just in case that anyone else is in need of this)...
Cheers,
Otto.
And is the explanation of the fix that needs to be made:
FYI I just ordered a Mega myself for a gateway since I figured the $7 to get one is a better expenditure of my time/money than me trying to get the MqttClientGateway + signing + RF69 radio + debug print to all fit on an Uno so I'll be doing this mod as well.
@Anticimex
I think I may have found a bug in the code:
I wanted to build a gateway that accepts both signed and unsigned messages. For this I used
MySigningAtsha204Soft signer(false);.
Now the gateway did accept unsigned messages, but also all messages sent to the gateway by another node with signing where unsigned.
After changing this line in MySensor.cpp:
if (signer.requestSignatures() && DO_SIGN(msg.sender))
to
if (signer.requestSignatures() || DO_SIGN(msg.sender))
it worked as I wanted it. The gateway accepts unsigned messages from nodes but if a node expects signed messages, the messages to the gateway are also signed.
This line means that the gateway requests signing from the node if he always requests signing or if the node requests signing.
What do you think?
@fleinze I am not sure I understand the basic problem. What do you mean by " but also all messages sent to the gateway by another node with signing where unsigned.". The signing is based on requirement. A node (or gateway) either require messages sent to it to be signed or not. You have told your gateway that it is not supposed to require signed messages so it will accept unsigned messages sent to it. It is up to the node to configure if the node require signed messages in return. The gateway configuration has nothing to do with the preferences of a node. If you tell your gateway that it does not require signing, no messages to it will be signed. The opposite also holds true. If you configure it to require signed messages, all messages have to be signed. That is "working as designed".
@fleinze after reading the post a few times I think I understand better
you want nodes who require signed messages from the gateway to send signed messages to the gateway as well even though the gateway is configured to not require it. I don't have a problem with that change as long as it is also portable to the nodes (the same code works equally well for both gateways and nodes usecases). You are welcome to put a pull request on the code so I can have a closer look. If approved I will update the head post to reflect this changed behaviour.
The change only effects gateways. I will put a pull request, thx.
@fleinze do you have some special reason for why you want this? I don't see a real benefit and it would slightly increase the traffic. I suppose it would add some symmetry to node-gw communication.
@fleinze I am quite stressed out for the moment so I forget my own design
What you actually should do is to configure the gateway to require signed messages. It will then do so, but only from nodes that in turn require signed messages. So you should not need to change anything, just set the GW to require signatures.
@Anticimex If I do so, this is the output of the Gateway:
0;0;3;0;9;gateway started, id=0, parent=0, distance=0 0;0;3;0;14;Gateway startup complete. 0;0;3;0;9;no sign 0;0;3;0;9;no sign 0;0;3;0;9;no sign 0;0;3;0;9;no sign 0;0;3;0;9;read: 2-2-0 s=0,c=0,t=6,pt=0,l=0,sg=0: 2;0;0;0;6; 0;0;3;0;9;read: 2-2-0 s=1,c=0,t=30,pt=0,l=0,sg=0: 2;1;0;0;30; 0;0;3;0;9;no sign 0;0;3;0;9;no sign 0;0;3;0;9;no sign
I tried to compile the node with deactivated signing feature and also with
MySigningNone.
The messages get rejected because in MySensor.cpp line 570 (developement branch) it is not checked if the sender requires signing:
if (signer.requestSignatures() && msg.destination == nc.nodeId && mGetLength(msg) && !mGetAck(msg) && (mGetCommand(msg) != C_INTERNAL || (msg.type != I_GET_NONCE_RESPONSE && msg.type != I_GET_NONCE && msg.type != I_REQUEST_SIGNING && msg.type != I_ID_REQUEST && msg.type != I_ID_RESPONSE && msg.type != I_FIND_PARENT && msg.type != I_FIND_PARENT_RESPONSE))).
@fleinze If you have upgraded the library version, the signing table might have shifted in EEPROM. You then need to run the clear EEPROM sketch to reset the stored state in order for the gw/nodes to re-learn the existing signing preferences of the network..
This is the exact usecase for the gw default behavior to only require signing from nodes that require signing in return. But I also got "no sign" errors after I flashed development branch yesterday on node/gw and only after I wiped the GW EEPROM I got it back online. So please try that. If it still does not work, I have to look closer, and see why this has broken because it has been working like that when I submitted the signing behavior.
@Anticimex I tried to make it work:
- took a fresh copy of the development branch
- activated signing in MyConfig.h
- flashed the ClearEepromConfig sketch to both the test-gateway and the test-node.
- built the gateway with
MySigningAtsha204Soft signer;(requires signing by default)
- built the node with
MySigningNone signer;
Still got the
no signmessage from the gateway...
Please have a look at this.
@fleinze mysigningnone is a special case. It won't make signatures, so could you instead try with either hard or soft atsha?
@fleinze also, you can mix hard and soft atsha signing in a network, but you can't mix with "none". If you mark a node that it can do signing or require signing and use the "none" backend, nodes that use atsha (hard or soft) will not accept the signatures.
@Anticimex
Ok, I built the node with
MySigningAtsha204Soft signer(false);so it does not require signing and the gateway with
MySigningAtsha204Soft signer;
-> no sign error.
How do I correctly build a node that does not sign in a mixed network (signing and non-signing nodes mixed)?
@fleinze
In a network where you have "mixed" nodes, I would suggest something like this:
The gateway has signing enabled and is set to require signatures and uses either hard or soft ATSHA (since you earlier wrote that you wanted the GW to sign messages to nodes that signed messages in return).
For all nodes that need to be secure, enable signing and pick either hard or soft ATSHA (depending on the node hardware) and set them to require signatures.
For all nodes that do not need to be secure, just disable signing alltogether, or pick any signing backend and set it to NOT require signatures.
The result should be like this:
A "insecure" node sends and receives unsigned messages to/from GW.
A "secure" node sends and receives signed messages to/from GW.
The GW will send signed messages to all nodes that has reported to the GW that they require signatures.
The GW will send unsigned messages to all nodes that has reported to the GW that they do NOT require signatures.
@Anticimex In your original post you said:
However, the difference is that the gateway will only require signed messages from nodes it knows in turn require signed messages.
I made pull request 208 to match this behavior in the code:
- If node is not a gateway, everything is as always. (1 || x)
- if node is gateway and the sender requires signed messages, check signature (0 || 1)
- if node is gateway and the sender does not requires signed messages, do not check signature (0 || 0)
please consider adding this.
Ok, the problem is identified and @fleinze has provided a fix that resolves the issue which is now merged to the development branch.
Thanks for finding the issue and fixing it!
There is no change in the signing behavior as it is documented. Now gateway does as it is supposed to.
Great work @fleinze and @Anticimex !
Reading this thread (yes, all of it) has made me ready to start configuring my nodes to use signing. Better start now, while my sensor network is still small
- FotoFieber Hardware Contributor last edited by
Compiling with the latest dev branch SecureActuator example
#define MY_SIGNING_REQUEST_SIGNATURES
I get following error:
In file included from /Users/mm/Documents/Arduino165/libraries/MySensors/MySensor.h:157:0, from SecureActuator.ino:58: /Users/mm/Documents/Arduino165/libraries/MySensors/core/MyTransport.cpp: In function 'void transportProcess()': /Users/mm/Documents/Arduino165/libraries/MySensors/core/MyTransport.cpp:92:10: error: 'MY_IS_GATEWAY' was not declared in this scope if ((!MY_IS_GATEWAY || DO_SIGN(sender)) && ^ /Users/mm/Documents/Arduino165/libraries/MySensors/core/MyTransport.cpp:93:20: error: 'nc' was not declared in this scope destination == nc.nodeId && ^ Fehler beim Kompilieren.``` Is this a problem of the code or of my setup?
@FotoFieber @hek something related to the recent refactoring? I have not had the opportunity to evaluate the effects on signing myself.
@FotoFieber said:
MY_SIGNING_REQUEST_SIGNATURES
Let's see how Jenkins feels about this
@Anticimex Hello, I found this thread now. I'll ask a few more questions, sorry. This all seems really-really great.
If someone wishes to use TMRh20's RF24Mesh instead of MySensors how would one sign the messages sent with that library? Is is even possible? What should be done to use that functionality?
Also, as I understand it is possible to emulate the ATSHA204A, on what hardware is is possible (on Uno's ATMega too?)?
Is it also possible to use whitelisting with RF24Mesh somehow?
Again, sorry for any dumb questions and my poor English.
- Signing as described in this post is specific to users of the MySensors library. I suppose you could use any rf backend you like but you will need to use the MySensors library to get the nonce exchange and such. Or manually port the signing specifics out from the MySensors library and integrate them into another library. It's all open source.
- The software emulated atsha signing backend (for MySensors) is compatible with any Arduino product.
- See 1.
Lastly, there are no dumb questions, only dumb answers [...]
To sum up, how can I add more nodeIDs and serials in addition to the number "55" presented in the example of the code?
Thank you very much in advance,
Silver978
@Silver978 Thanks!
Try something like = 56, // = 57, //, 3, node_whitelist); // Select ATSHA204A software signing backend with three entries in the whitelist
Note the changed argument in the constructor (3 and not 1)
@Anticimex I tried also this syntax but I haven't changed the argument of the signer, so that number indicates how many nodes the gateway must trust?
Thank you!
@Silver978 The number gives the number of entries in the whitelist the backend is expected to iterate over. Having a number for this allows the use of a potenitally very large whitelist but where "uninteresting" entries to this particular node can be ignored by having them last in the list and make sure the number does not cover those entries when searching the list.
@Anticimex Perfect, understood! Very good explanation and super-fast support, fantastic
Thank you very much again!
I would like to add security to my sensor network as well so I am very glad I found your thread. Your explanation are very detailed but I´m a guy who needs more practical examples. For example I would like to know, where exactly I have to activate this. I am using an arduino as an MQTT to Ethernet gateway and Mosquitto running on a raspberry pi. So all I have to do is activate the soft version in Myconfig.h, if not already activated, set a serial, re-upload to my arduino gateway and that´s it? I guess the Nodes have to get flashed again to get the serials as well, right?
@siod correct. You have to activate signing in both ends. The serial numbers you only need of you want to use whitelisting which is a bit more complex to set up. At the very least, for software signing, you need to enable it, have an unconnected analog pin on your boards, and set a hmac key.
EDIT: Topic post updates with a documentation link for those using the development branch.
Great topic as usual. I have a question please.
You mentioned "Because it is pure-software however, it does not provide as good nonces (it uses the Arduino pseudo-random generator) and the HMAC key is stored in SW and is therefore readable if the memory is dumped. "
Isn't this case also dangerous if the node which contains ATSHA chip was stolen ? The attacker will use the chip to be on the network ?
Thanks.
@ahmedadelhosni thanks!
Correct. That is why I also implemented whitelisting and node revocation. It's all described in the topic (and for development branch in doxygen, linked in the topic).
@Anticimex Thanks.
So this gets me to my next question
What I understood is that if I use whitelisting, I need to know the node ID of my sensor door to define it in the GW, correct ?
I guess the below code is in the GW. };
another question, If I want to remove this node, do I have to reflash the GW and remove it ?
Yes.
- ahmedadelhosni last edited by ahmedadelhosni
@Anticimex mmmm
Can't it be implemented in a way so that whitelist is to be defined by the controller ?
For example, an internal message to be used to set the data.
My concern is that auto assignation of nodes is flexible but at the same time you may need to choose which sensor node to be added to your whitelist. Thus if a Controller can show you all your nodes, like vera or domoticz, I guess this option can be added to the plugin to send an internal message to the GW to choose which sensor node to be added.
Am I saying something logic ?
Possibly. But that would mean that security features is dictaded by the controller plugins and I do not like that at all.
For months I have been trying to convince the Domoticz people that their ACK timeout is way to short and needs to be configurable for signing to work with Domoticz, but they do not even reply to me.
And I do not trust controllers at all and want to have full control over all configuration aspects of the signing solution. So I do not think it is good to move that logic off the nodes (whitelisting can also be used by a node, communicating with another node).
It is not only a GW that can have a whitelist. So although it might have been flexible to have it configurable, I think it compromises security (who knows, your controller could be hacked to inject a whitelist that permits a rogue node in your network).
Of course, security is at some level compromised anyway if the controller is hacked. But it is not the signing solution that is compromised in this case.
And ultimately, that feature would mean that the level of signing security and signing features for MySensors, becomes controller specific. And that I do not think is a good idea. If I want to change or improve the feature, the controller plugins all also have to be updated. It just becomes a too big turnaround for something as important as this in my opinion.
Yeah I got your point of view and convinced me. The only solution to implement this is that other communities works together to improve flexibility and security. This is not that easy of course as you have said.
Thanks a lot for your time.
Thanks for understanding
Also in all cases I see that if your controller is being hacked there will be no use to play with the whitelist
The attacker has full control already to blow my house if he wants to
Anyway maybe I need to reflash using signing to understand things more.
Keep it up
- ahmedadelhosni last edited by ahmedadelhosni
Hi again.
I managed to set run the softsign and everything seems fine till now. I just want to understand the system much more if you please.
Now my Gateway sends this data when I turn on Light.
( I am using GatewayW5100 with Domoticz ) Development branch
0;0;3;0;9;Eth: 0;0;3;0;18;PING 0;0;3;0;9;Eth: 2;7;1;0;2;1 0;0;3;0;9;send: 0-0-2-2 s=7,c=3,t=16,pt=0,l=0,sg=0,st=ok: 0;0;3;0;9;Signing backend: ATSHA204Soft 0;0;3;0;9;Message to process: 00020E01020731 0;0;3;0;9;Current nonce: 01F470C061A0B9FF3DE248835736E2B85E31C8D6D1844AACACAAAAAAAAAAAAAA 0;0;3;0;9;HMAC: 135DBD85528E869ECC86C9C53679795D7FDA7B789DB7A0A74053C94FE8D668F0 0;0;3;0;9;Signature in message: 015DBD85528E869ECC86C9C53679795D7FDA7B789DB7A0A7 0;0;3;0;9;send: 0-0-2-2 s=7,c=1,t=2,pt=0,l=1,sg=1,st=ok:1
I want to know how was the following data calculated please:
- sg=0:01F470C061A0B9FF3DE248835736E2B85E31C8D6D1844AACAC
- Message to process: 00020E01020731
- Current nonce: 01F470C061A0B9FF3DE248835736E2B85E31C8D6D1844AACACAAAAAAAAAAAAAA
- HMAC: 135DBD85528E869ECC86C9C53679795D7FDA7B789DB7A0A74053C94FE8D668F0
- Signature in message: 015DBD85528E869ECC86C9C53679795D7FDA7B789DB7A0A7
So how was sg= calculated ?
What is message to process ?
The nonce is depending on analogue signal + what ? to get this value ?
I have already defined a random HMAC, but this one is different. It is a combination of what ?
Finally what is signature in message ?
On the other side I am trying to sniff the data by a serialgateway which is trying to hack the network. It only read the following data: 2;255;3;0;17;01F470C061A0B9FF3DE248835736E2B85E31C8D6D1844AACAC
It is the sg only which it succeeded to read. Also I do understood form the topic that the attacker can read values sent between nodes unencrypted, but here I can't figure out where is the unencrypted data which can be sniffed by the attacker but we don't bother ourselves with cas we protect our network by using signing.
Lots of questions but I am trying to understand the logic and architecture in details to understand what I am doing
Thanks a lot.
Suggested Topics
Anti-theft Entrance Guard Alarm System Based on Arduino
💬 Aeos : a NRF52 versatile, up to 9in1, device
Moving sensor from one network to another may cause conflict
Secure node encrypted communication. AES-128
What do "error-blinks" say?
IEC 62056-21 Energy meter
Multiple Relays + Motion sketch, fully customizable, optional timer, manual override
MySensors on MSP430 + NRF24L01 | https://forum.mysensors.org/topic/1021/security-introducing-signing-support-to-mysensors/?page=2 | CC-MAIN-2019-13 | refinedweb | 9,055 | 65.01 |
The XPath 2.0 Data Model describes a set of accessor functions for use with different types of nodes, and some of those accessor functions are made available through general functions. Here they are:
fn:node- name returns the name of a node.
fn:string returns the string value of the argument.
fn:data takes a sequence of items and returns a sequence of atomic values.
fn: base-uri returns a node's base URI.
fn: document-uri returns the document's URI.
We'll take a closer look at these functions here.
The fn:node-name function returns the expanded name of nodes that can have names (for other node kinds, it returns the empty sequence). Here is the signature for this functionthe question mark at the end of the return type indicates in XPath 2.0 that the empty sequence can be returned:
fn:node-name( $srcval as node) as xs:QName?
Expanded names consist of a pair of values, a namespace URI, and a local name. In consequence, the way this function actually returns its values is implementation-specific.
The fn:string function returns the string value of a node. Here's how you use this functionthis function can take one argument or an empty sequence, which XPath represents by adding a question mark after the argument type:
fn:string( $srcval as item? ) as xs:string
Here, fn:string returns the value of $srcval represented as a xs:string . If you don't pass an argument to this function, $srcval defaults to the context item (which is represented by a dot, .). If you pass an empty sequence, you'll get an empty string, "", back.
String representations in XPath 2.0 are nearly the same as in XPath 1.0, with some small differencesfor example, the representations of positive and negative infinity are now 'INF' and '-INF' rather than 'Infinity' and '-Infinity' . You can see an example in ch09_01.xsl , Listing 9.1in this case, we're displaying the string value of the <planet> elements in our planetary data document.
<xsl:stylesheet <xsl:template <xsl:value-of </xsl:template> </xsl:stylesheet>
You can see the results when you apply this stylesheet to our planetary data document, including the string value of each <planet> element:
C:\Saxon>java net.sf.saxon.Transform ch02_01.xml ch09_02.xsl <?xml version="1.0" encoding="UTF-8"?> Mercury .0553 58.65 1516 .983 43.4 Venus .815 116.75 3716 .943 66.8 Earth 1 1 2107 1 128.4
This function is handy for turning data of various types into strings. Because of XPath 2.0's reliance on strong data typing, this is an important functionfor example, if you want to pass a non-string variable's value to a string function like fn:concat , you should convert that value to a string using the fn:string function first.
The fn:data function converts a sequence of items (which can include nodes and atomic values) into a sequence of atomic values. Here's how you use this function in generalthe * symbol here means "zero or more of," which is how you represent a sequence in function signatures:
fn:data( $srcval as item *) as xdt:anyAtomicType*
If an item in the passed sequence is already an atomic value, it's returned in the returned sequence. On the other hand, if an item in the passed sequence is a node, its typed value is returned (see for a description of exactly how typed values for nodes are calculated). If the node has not been validated , its typed value is simply its string value, given the type xdt:untypedAtomic .
This accessor function returns the base URI for a node. Here's how you use this function:
fn:base-uri( $srcval as node) as xs:string?
In XML documents, you set a base URI with the XML xml:base attribute. You can see an example in ch09_03.xml , where we're setting a base URI for our planetary data document in a new version, ch09_02.xml (Listing 9.2).
<?xml version="1.0"?> <?xml-stylesheet >
Now we can determine the base URI of each <planet> element in a new XSLT 2.0 stylesheet, as you see in ch09_03.xsl (Listing 9.3).
<xsl:stylesheet <xsl:template <xsl:value-of </xsl:template> </xsl:stylesheet>
And here's the result when you apply this stylesheet to our new XML documentyou can see the base URI of the <planet> elements in this example:
C:\Saxon>java net.sf.saxon.Transform ch09_03.xml ch09_04.xsl <?xml version="1.0" encoding="UTF-8"?>
When you pass it a node, the fn:document-uri function returns the URI of the document that contains the node, which is useful, for example, if you want to display an error that lists the current document's name. Here's how you use this function:
fn:document-uri( $srcval as node) as xs:string?
You can see an example putting fn:document-uri to work in ch09_04.xsl (Listing 9.4). Here, we're simply displaying the URI of the current document to test this function.
<xsl:stylesheet <xsl:template <xsl:value-of </xsl:template> </xsl:stylesheet>
And here's the result you get when apply this stylesheet to ch09_02.xml in this case the result is the location on disk of ch09_02.xml :
C:\Saxon>java net.sf.saxon.Transform ch09_03.xml ch09_04.xsl <?xml version="1.0" encoding="UTF-8"?> file:/C:/Saxon/ch09_02.xml | https://flylib.com/books/en/1.256.1.84/1/ | CC-MAIN-2022-05 | refinedweb | 912 | 64.41 |
Introduction:GDI+ consists of the set of .NET base classes that are available to control custom drawing on the screen. These classes arrange for the appropriate instructions to be sent to the graphics device drivers to ensure the correct output is placed on the screen. GDI provides a level of abstraction, hiding the differences between different video cards. You simply call on the Windows API function to do the specific task, and internally the GDI figures out how to get the client's particular video card to do whatever it is you want when they run your particular piece of code. Not only this, but the client has several display devices - for example - monitors and printers - GDI achieves the task of making the printer look the same onscreen as far as the application is concerned. If the client wants to print something instead of displaying it, your application will simply inform the system that the output device is the printer and then call the same API functions in exactly the same way. As you can see, the device-context (DC) object is a very powerful mechanism. Having said that, we can also use this layer of abstraction to draw onto a Windows Form. This paper will therefore begin with an example of a basic Windows Forms development in order to demonstrate how to draw graphics onto a Windows Form, or a control on that form. The focus of this article will be on graphics.The Form object is used to represent any Window in your application. When creating a main window, you must follow two mandatory steps:
Here is an example: C# File: MyForm.cs
using System;
using System.Windows.Forms;
public class MyForm : System.Windows.Forms.Form
{
public MyForm()
{
Text = "No Graphics";
}
public static void Main()
Application.Run(new MyForm());
}}To compile: C:\Windows\Microsoft.NET\Framework\v2.050727>csc /target:winexe MyForm.csSo now we have a blank form. So what do we do to learn how to use graphics? If you use Visual Studio 2005 you probably know that the .NET Framework 2.0 supports partial classes. With Visual Studio 2005, a Windows Form is completely defined with a single C# source file. The code generated by the IDE was separated from your code by using regions, therefore taking advantage of partial classes. By default, each form named Form111 corresponds to two files; Form111.cs which contains your code and Form111.Designer.cs, which contains the code generated by the IDE. The code, however, is usually generated by dragging and dropping controls. One of the simplest uses for the System.Drawing namespace is specifying the location of the controls in a Windows Forms application. More to the point, user-defined types are often referred to as structures. To draw lines and shapes you must follow these steps:
Here is an example of a Form with a line drawn at a 60 degree angle from the upper-most left hand corner://File: DrawLine.cs
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Data;
public class MainForm : System.Windows.Forms.Form
private System.ComponentModel.Container components;
public MainForm()
InitializeComponent();
CenterToScreen();
SetStyle(ControlStyles.ResizeRedraw, true);
}
// Clean up any resources being used.
protected override void Dispose(bool disposing)
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
#region Windows Form Designer generated code
private void InitializeComponent()
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Text = "Fun with graphics";
this.Resize += new System.EventHandler(this.Form1_Resize);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint);
#endregion
[STAThread]
static void Main()
Application.Run(new MainForm());
private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
//create a graphics object from the form
Graphics g = this.CreateGraphics();
// create a pen object with which to draw
Pen p = new Pen(Color.Red, 7); // draw the line
// call a member of the graphics class
g.DrawLine(p, 1, 1, 100, 100);
private void Form1_Resize(object sender, System.EventArgs e)
// Invalidate(); See ctor!
} TO COMPILE:csc.exe /target:winexe DrawLine.cs Typically, you specify the Pen class color and width in pixels with the constructor. The code above draws a 7-pixel wide red line from the upper-left corner (1,1,) to a point near the middle of the form (100, 100). Note the following code that draws a pie shape: File:// DrawPie.cs
{
//
Pen p = new Pen(Color.Blue, 3);
g.DrawPie(p, 1, 1, 100, 100, -30, 60);
}To compile:csc.exe /target:winexe DrawPie.csA structure, or "struct", is a cut-down class that does almost everything a class does, except support inheritance and finalizers. A structure is a composite of other types that make easier to work with related data. The simplest example is System.Drawing.Point, which contain X and Y integer properties that define the horizontal and vertical coordinates of a point. The Point structure simplifies working with coordinates by providing constructors and members as follows:
// Requires reference to System.Drawing
// Create point
System.Drawing.Point p = new System.Drawing.Point(20, 20);
// move point diagonally
p.Offset(-1, -1)
Console.WriteLine("Point X {0}, Y {1}", p.X, p.Y.);So as the coordinates of a point define its location, this process also specifies a control's location. Just create a new Point structure by specifying the coordinates relative to the upper-left corner of the form, and use the Point to set the control's Location property.Graphics.DrawLines, Graphics.DrawPolygons, and Graphics.DrawRectangles accept arrays as parameters to help you draw more complex shapes:Here is an example of a polygon, but with its contents filled. Notice the code responsible for filling the shape:DrawPolygonAndFill.cs
using System.Data;
SetStyle(ControlStyles.ResizeRedraw, true);
if (components != null)
#endregion
Brush b = new SolidBrush(Color.Maroon);
Point[] points = new Point[] { new Point(10, 10),
new Point(10, 100),
new Point(50, 65),
new Point(100, 100),
new Point(85, 40)}; // Notice the braces, as used in structures
g.FillPolygon(b, points);
private void Form1_Resize(object sender, System.EventArgs e)
} Customizing Pens:The color and size of a pen is specified in the Pen constructor, so you can manipulate the pattern and the endcaps. The endcaps are the end of the line, and you can use them to create arrows and other special effects. While pens by default draw straight lines, their properties can be set to one of these values: DashStyle.Dash, DashStyle.DashDot, DashStyle.DashDotDot, DashStyle.Dot, or DashStyle.Solid. Consider this final example:UsePen.cs
this.Text = "Learning graphics";
this.Resize += new System.EventHandler(this.Form1_Resize);
// create a Pen object
Pen p = new Pen(Color.Red, 10);
p.StartCap = LineCap.ArrowAnchor;
p.EndCap = LineCap.DiamondAnchor;
g.DrawLine(p, 50, 25, 400, 25);
p.StartCap = LineCap.SquareAnchor;
p.EndCap = LineCap.Triangle;
g.DrawLine(p, 50, 50, 400, 50);
p.StartCap = LineCap.Flat;
p.EndCap = LineCap.Round;
g.DrawLine(p, 50, 75, 400, 75);
p.StartCap = LineCap.RoundAnchor;
p.EndCap = LineCap.Square;
g.DrawLine(p, 50, 100, 400, 100);
} The basics underlying principles in this paper indicate the location and size of points so that they for a line or a shape. This should the new developer to understand that these principles can be expanded upon to specify the size and location of controls that are dragged and dropped onto a Windows Form. For instance, if we were to start Visual Studio 2005 and begin a Forms application, we could set that Form background color to white. The designer file and the source file that comprise the application would both reflect that property: the setting of the property would cause the IDE to generate the code in the Form.Designer.cs file. Well, that all for now. DrawLine.cs
{
private System.ComponentModel.Container components;
this.Resize += new System.EventHandler(this.Form1_Resize);
Pen p = new Pen(Color.Red, 7);
// draw the line
}
©2014
C# Corner. All contents are copyright of their authors. | http://www.c-sharpcorner.com/uploadfile/TheButler/the-basics-of-drawing-graphics-onto-windows-forms/ | CC-MAIN-2014-42 | refinedweb | 1,328 | 52.36 |
First of all, even with most optimized space and time complexity, I have to say this may be not the best solution, since it changes the tree structure a little bit during constructor period.
#Construct Period
The idea is use in-order Morris Tree Traversal (check out [1][2] if you are not familiar with it, otherwise the bellow explanation to you is nonsense) to construct a threaded binary tree in construct function. (This is O(n) time, but we don't care much about it.) Then set a pointer (we call it "curr") to the smallest TreeNode, which is easy to do, just find the left-most child from root.
#hasNext()
For hasNext() function, simple return "curr != null", which is by definition of threaded binary tree.
For next() function, it is a little bit tricky. We call the right child of "curr" as "next". If "next" is not a normal right child of "curr", which means the right child relationship is constructed during the threaded binary tree construction period, then the next TreeNode we should iterate is indeed "next". However, if "next" is a normal right child of "curr", then the next TreeNode we should iterate is actually the left-most child of "next".
So the problem reduces to how to make clear the situation. Well, it is no hard. If "next" is null, then we've done, simply set "curr" to null. If "next" has no left child, or "next"'s left child is strictly larger than "curr", that means it is a normal right child of "curr", so we should set "curr" to left-most child of "next". Otherwise, we set "curr" to "next", and break the right child relationship between "curr" and "next", to recover the original tree structure.
#Complexity analysis
The space complexity is straightforwardly O(1). The time complexity needs some more explanation. Since the only part that is not O(1) is when we search the left-most child of "next". However, for all the children along this left path (say, there are N children), we do once search left-most and (N-1) times simply go to right child. So the amortized time complexity is still O(1).
#Code:
public class BSTIterator { private TreeNode curr; public BSTIterator(TreeNode root) { TreeNode prev; //Do a morris in-order traversal, to construct a threaded binary tree curr = root; while(curr != null){ if(curr.left == null){ curr = curr.right; } else{ prev = curr.left; while(prev.right != null && prev.right != curr) prev = prev.right; if(prev.right == null){ prev.right = curr; curr = curr.left; } else{ curr = curr.right; } } } //get the left-most child of root, i.e. the smallest TreeNode curr = root; while(curr != null && curr.left != null) curr = curr.left; } /** @return whether we have a next smallest number */ public boolean hasNext() { return curr != null; } /** @return the next smallest number */ public int next() { //copy the value we need to return int result = curr.val; TreeNode next = curr.right; if(next == null) curr = next; //the right child relationship is a normal one, find left-most //child of "next" else if(next.left == null || next.left.val > curr.val){ curr = next; while(curr.left != null) curr = curr.left; } //the right child relationship is made when we //construct the threaded binary tree else{ curr.right = null;//we recover the original tree structure curr = next; } return result; } }
#Reference
For those who are not familiar with Morris Tree Traversal, these two paragraphs are good references.
[1]
[2]
For the constructor, I don't see how you constructed threaded binary tree. Instead, "prev.right = null;" already recovers the tree after Morris Traversal. Can you illustrate what's the point of doing a complete traversal in the constructor while the tree is recovered afterwards? Thanks.
Hi, I just fixed that problem, thanks for mention that. Now the code is totally fine.
Hey, just saw your post. I got similar idea but slightly improved the time cost from O(1) amortized time to O(1) in worst case.
Check it here.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/24442/my-java-solution-with-o-1-space-and-o-1-amortized-time-using-morris-tree-traversal | CC-MAIN-2018-05 | refinedweb | 682 | 75.1 |
#include <LiquidCrystal.h>LiquidCrystal lcd(5,6,7,8,9,10);void setup { // set up the LCD's number of columns and rows: lcd.begin(8,2); //is 16x1, adressed as 8x2 lcd.setCursor(0,0); //init right hand side lcd.clear(); // Print a message to the LCD. lcd.print("hello wo"); //print left side lcd.setCursor(0,1); //go to right lcd.print("rld!"); //print right side}void loop() {}
The problem of the text displaying like autoscroll in void loop() occurs only if I also put on the code for SPI which uses the same pin i.e. pin12.However if I use the LCD screen alone it is working fine.
I just dealt with this same problem. I ended up using the liquid crystal library. In setup use LCD.begin(16,2);. Then when you want to write to the right 8 character's, use LCD.set cursor(0,1) then LCD.print() (or LCD.write).
but I only get 8 characters written and only if I address it as 16x1
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=263467.msg1858838 | CC-MAIN-2016-07 | refinedweb | 208 | 78.14 |
08 January 2009 23:56 [Source: ICIS news]
HOUSTON (ICIS news)--?xml:namespace>
Market sources complained that the reduction was too little, too late, in view of falling international prices of benzene, styrene and ethylene, which are the main feedstocks for PS.
Demand was soft in the country due to the summer vacation season, the effects of the global crisis and the willingness of transformers to keep inventories as low as possible.
High prices were also a deterrent for buyers who compared domestic prices with cheaper imports. However, imports have not played a big role in
Starting at about $1,800/tonne (€1,332/tonne) for general purpose PS (GPPS),
For more on polystyrene | http://www.icis.com/Articles/2009/01/08/9182979/ps-prices-down-5-7-in-argentina.html | CC-MAIN-2013-48 | refinedweb | 114 | 58.21 |
IRC log of mlw-lt on 2012-11-27
Timestamps are in UTC.
12:36:20 [RRSAgent]
RRSAgent has joined #mlw-lt
12:36:20 [RRSAgent]
logging to
12:36:25 [fsasaki]
meeting: MLW-LT editing call
12:36:32 [fsasaki]
chair: felix
12:37:48 [kfritsche]
kfritsche has joined #mlw-lt
12:58:46 [fsasaki]
present: karl, yves, felix
12:58:50 [Yves_]
Yves_ has joined #mlw-lt
12:59:10 [Yves_]
present+ Yves_
13:00:13 [fsasaki]
topic: work plan / agenda check
13:00:20 [fsasaki]
waiting for people to come ...
13:00:24 [RRSAgent]
I have made the request to generate
fsasaki
13:03:51 [fsasaki]
present+ dave
13:05:19 [fsasaki]
topic: Global rules for provenance discussion
13:05:37 [fsasaki]
basis for discussion is
13:05:42 [fsasaki]
dave: yves' points are correct
13:05:55 [fsasaki]
.. there is no way of writing a global pointer rule which is aware of values in the xliff
13:06:40 [fsasaki]
.. even if we could figure out the xpath, you would need something in the rule to filter out things in the phase group that did not map to "revision"
13:06:59 [fsasaki]
.. because you cannot differentiate phase groups in the way needed
13:07:09 [fsasaki]
present+ david
13:07:20 [fsasaki]
dave: this topic, plus toolsRef issues
13:07:47 [fsasaki]
.. plus if you want to do mapping between phase group and rules, you need more than pointer rules
13:07:55 [fsasaki]
.. I'd say let's get rid of pointer rules
13:08:00 [fsasaki]
.. appart of standoff pointers
13:08:07 [dF]
dF has joined #mlw-lt
13:08:44 [fsasaki]
13:08:52 [fsasaki]
"provenanceRecordsRefPointer"
13:09:36 [daveL]
daveL has joined #mlw-lt
13:11:02 [fsasaki]
everything else would be deleted. That is: "personPointer, personRefPointer, orgPointer, orgRefPointer, toolPointer, toolRefPointer, revPersonPointer, revPersonRefPointer, revOrgPointer, revOrgRefPointer, revToolPointer, revToolRefPointer and provRefPointer"
13:12:02 [fsasaki]
action: jirka to take
for the ITS 2.0 schema into account
13:12:03 [trackbot]
Created ACTION-325 - Take
for the ITS 2.0 schema into account [on Jirka Kosek - due 2012-12-04].
13:12:05 [pnietoca]
pnietoca has joined #mlw-lt
13:12:26 [fsasaki]
present+ jirka
13:13:29 [pnietoca]
present+ pnietoca
13:13:36 [pnietoca]
sorry i'm late
13:14:43 [Jirka]
Jirka has joined #mlw-lt
13:15:00 [fsasaki]
topic:
13:18:21 [fsasaki]
drop relax ng namespace, not used in the spec
13:19:27 [fsasaki]
added html namespace
13:20:42 [fsasaki]
topic:
13:21:27 [fsasaki]
dropping complete section
13:22:09 [fsasaki]
topic:
13:23:41 [fsasaki]
"The concept of a data category is independent of its implementation in an XML environment" > The concept of a data category is independent of its implementation in an XML and HTML environment"
13:24:24 [fsasaki]
topic:
13:24:48 [fsasaki]
"parts of an XML document " > "parts of an XML or HTML document"
13:26:56 [fsasaki]
"Selection relies on the information that is given in the XML Information Set [XML Infoset]. ITS applications MAY implement inclusion mechanisms such as XInclude or DITA's [DITA 1.0] conref."
13:27:29 [fsasaki]
drop the paragraph
13:28:50 [fsasaki]
topic:
13:29:18 [fsasaki]
action: felix to update list or IRI attributes at
13:29:18 [trackbot]
Created ACTION-326 - Update list or IRI attributes at
[on Felix Sasaki - due 2012-12-04].
13:31:32 [fsasaki]
action-326: not needed, handled during editing call
13:31:32 [trackbot]
ACTION-326 Update list or IRI attributes at
notes added
13:31:37 [fsasaki]
close action-326
13:31:37 [trackbot]
ACTION-326 Update list or IRI attributes at
closed
13:33:36 [fsasaki]
dropped attribute list, reffering now only to RELAX NG schema and the anyURI data types
13:33:40 [fsasaki]
topic:
13:34:54 [fsasaki]
make sure that everything will say "HTML" or "HTML5"?
13:35:14 [fsasaki]
jirka: w3c working group said they will use html versioning
13:35:26 [fsasaki]
.. to avoid perception that ITS cannot be applied to HTML6
13:35:42 [fsasaki]
david: future proof is good
13:35:50 [fsasaki]
.. but it is not valid HTML4
13:35:57 [fsasaki]
.. you could say "HTML5 and higher"
13:36:34 [fsasaki]
karl: could say HTML and in an introduction we say "HTML is defined by HTML5 or its successor"
13:40:02 [fsasaki]
added a subsection in the terminology section, see
13:42:31 [fsasaki]
topic:
13:43:32 [fsasaki]
"[Ed. note: Below statement about schemas is wrong if the ITS schemas will be normative.]": deleting note
13:44:10 [fsasaki]
topic:
13:44:38 [fsasaki]
"[Ed. note: All traces of HTML has to be removed if we will proceed with CT 3 and HTML+ITS CC.]": note from Jirka
13:45:04 [fsasaki]
everyone is happy with separate html confirmance type, so can remove note
13:48:14 [fsasaki]
deleting all traces of HTML and HTML5 in this section, since there is now a separate conformacne type for html5
13:49:56 [Yves_]
13:51:26 [fsasaki]
topic:
13:53:26 [fsasaki]
discussed "processing expecations" vs "processing requirements", might change terminology (not normative def) during last call
13:55:05 [fsasaki]
action: Jirka to go through document and replace HTML5 > HTML
13:55:06 [trackbot]
Created ACTION-327 - Go through document and replace HTML5 > HTML [on Jirka Kosek - due 2012-12-04].
13:56:18 [fsasaki]
topic:
13:57:48 [fsasaki_]
fsasaki_ has joined #mlw-lt
13:58:03 [Yves_]
rrsagent, draft minutes
13:58:03 [RRSAgent]
I have made the request to generate
Yves_
13:58:24 [fsasaki_]
topic:
14:00:32 [fsasaki]
discussion on "standoff markup", related to "location", but somehow different, not added here
14:05:33 [fsasaki]
topic:
14:06:50 [fsasaki]
delete ruby mentions throughout section 5.2
14:07:27 [Yves_]
rrsagent, draft minutes
14:07:28 [RRSAgent]
I have made the request to generate
Yves_
14:09:20 [fsasaki]
"The content model of span permits arbitrary nesting of ruby markup, since the rt element can contain span. An application of ruby, however, MUST not use such arbitrary nesting.": deleted, ruby not needed here
14:12:11 [fsasaki]
topic:
14:16:37 [fsasaki]
"The following attributes point to existing information:": deleted pointer attributes not needed anymore
14:17:14 [fsasaki]
.. after the "pointer in provenacne" discussion today
14:17:41 [fsasaki]
"5.3.3 CSS Selectors"
14:18:17 [fsasaki]
"5.3.4 Additional query languages"
14:18:39 [fsasaki]
"5.3.5 Variables in selectors"
14:21:33 [fsasaki]
topic: "5.4 Link to External Rules"
14:23:48 [fsasaki]
action: felix to create example with rules element in sec. 5.4 - due 15 december
14:23:48 [trackbot]
Created ACTION-328 - create example with rules element in sec. 5.4 [on Felix Sasaki - due 2012-12-15].
14:24:27 [fsasaki]
topic: "5.5 Precedence between Selections"
14:26:48 [fsasaki]
"Implicit Local selection in documents" > not inherited local selection is meant?
14:29:10 [fsasaki]
"Implicit Local selection in documents" > Selection via local ITS markup in documents
14:29:24 [fsasaki]
"Implicit Local selection in documents" > Selection via explicit (that is not inherited) local ITS markup in documents
14:31:35 [fsasaki]
keep as is, may clarify during LC phase
14:31:37 [pnietoca]
the same happens in point 7.5
14:32:13 [pnietoca]
so if you're going to change it you have to change both
14:33:30 [fsasaki]
tx, pnietoca, will take that into account during LC too
14:33:57 [fsasaki]
topic: "5.6 Associating ITS Data Categories with Existing Markup"
14:34:35 [pnietoca]
sorry folks I have to leave, besides my microphone it's not working I don't know why!, I'm trying to speak but I can't
14:34:48 [pnietoca]
I hope to have it fixed next time
14:34:49 [fsasaki]
sure, thanks for being here, pnietoca!
14:35:36 [pnietoca]
anyway I 'll send a number of misprints and other things I noticed during the revision
14:35:43 [pnietoca]
to the list
14:35:51 [pnietoca]
cheers, bye!
14:36:48 [fsasaki]
discussing position of sec 7 "Using ITS Markup in HTML5"
14:36:51 [daveL]
suggest text for last note in 5.5, change "and these are overridden via local markup." to "which are in turn overridden by local markup"
14:37:37 [fsasaki]
done
14:40:19 [fsasaki]
sec 7 "Using ITS Markup in HTML5" is now sec 6, old sec 6 is sec 7
14:40:48 [fsasaki]
rrsagent, draft minutes
14:40:48 [RRSAgent]
I have made the request to generate
fsasaki
14:42:06 [fsasaki]
sec 8 about xhtml now also moved, is new sec 7, old sec 6 is sec 8
14:43:32 [fsasaki]
topic: 5.7 Conversion to NIF
14:43:52 [fsasaki]
remove mentions of ontology
14:50:39 [RRSAgent]
I have made the request to generate
fsasaki
14:50:42 [fsasaki]
1 hour break
14:50:43 [RRSAgent]
I have made the request to generate
fsasaki
16:00:50 [Yves_]
Sorry: i wasn't able to do diddly-squat on updating the provenance section
16:02:20 [fsasaki]
16:04:59 [fsasaki]
topic: "5.8 ITS Tools Annotation"
16:09:58 [fsasaki]
dave, felix - need a running list of all the MUST statements and make sure that we have a test
16:10:01 [fsasaki]
topic: test suite
16:10:53 [fsasaki]
"The data category identifier MUST be one of the following identifiers" example of a statement that needs testing to
16:11:17 [fsasaki]
action: felix to come up with running list of MUST statements for testing - due december 15
16:11:18 [trackbot]
Created ACTION-329 - come up with running list of MUST statements for testing [on Felix Sasaki - due 2012-12-15].
16:18:27 [fsasaki]
action: felix to move data category identifiers to table in 8.1 Position, Defaults, Inheritance and Overriding of Data Categories
16:18:27 [trackbot]
Created ACTION-330 - Move data category identifiers to table in 8.1 Position, Defaults, Inheritance and Overriding of Data Categories [on Felix Sasaki - due 2012-12-04].
16:19:39 [fsasaki]
replacing lq-issues with lq-issue in identifer list
16:26:57 [Jirka]
Jirka has joined #mlw-lt
16:28:48 [fsasaki]
"Inline global rules MUST be specified inside script which has type attribute with the value application/xml or application/its+xml. "
16:29:39 [fsasaki]
in 6.3 Inline Global Rules in HTML5
16:30:58 [fsasaki]
"with the value application/xml or application/its+xml." > "with the value application/its+xml."
16:36:07 [fsasaki]
"The script element itself MUST be child of head element." > "The script element itself SHOULD be child of head element."
16:36:37 [fsasaki]
6.4 Standoff Markup in HTML5
16:38:16 [fsasaki]
...
16:38:17 [fsasaki]
...xml:id attribute of the provenanceRecords element it contains."
16:41:07 [fsasaki]
same change for lq issue
16:43:15 [fsasaki]
"6.5 Precedence between Selections"
16:48:04 [fsasaki]
"Note: If identical selections are defined in different rules elements within one document, the selection defined by the last takes precedence.": removing the note in sec. 5.5 Precedence between Selections
16:48:19 [fsasaki]
same for 6.5 Precedence between Selections
16:50:22 [fsasaki]
added note from XML section 5.5 "ITS does not define precedence related to rules defined or linked based on non-ITS mechanisms (such as processing instructions for linking rules)." to HTML section 6.5
16:51:01 [fsasaki]
"7 Using ITS Markup in XHTML"
16:52:35 [fsasaki]
action: karl to create xhtml example for 7 Using ITS Markup in XHTML
16:52:35 [trackbot]
Created ACTION-331 - Create xhtml example for 7 Using ITS Markup in XHTML [on Karl Fritsche - due 2012-12-04].
16:55:16 [fsasaki]
topic: next call
16:55:25 [fsasaki]
karl could do wed, felix not wed, but thur
16:55:41 [fsasaki]
dave from 1-3 p.m. utc
16:55:45 [fsasaki]
on thursday
16:55:48 [fsasaki]
and wed too
16:56:13 [fsasaki]
yves better on wed
16:57:29 [fsasaki]
felix on thur 2 p.m. utc - later
16:58:08 [fsasaki]
yves: will modify proveance ot remove pointers
16:58:36 [RRSAgent]
I have made the request to generate
fsasaki
16:59:15 [Yves_]
Felix: I'll wait until you push the updated spec to CVS to do the provenance. But no rush.
17:00:00 [fsasaki]
np, just pushed to cvs
17:00:13 [fsasaki]
thanks for the reminder
17:00:43 [Yves_]
great. thanks. | http://www.w3.org/2012/11/27-mlw-lt-irc | CC-MAIN-2016-26 | refinedweb | 2,128 | 55.78 |
I was reading some code and I saw something along the lines of
module M
def +@
self
end
end
ruby -c
-@
*@
d@
+@
Ruby contains a few unary operators, including
+,
-,
!,
~,
& and
*. As with other operators you can also redefine these. For
~ and
! you can simply just say
def ~ and
def ! as they don't have a binary counterpart (e.g. you cannot say
a!b).
However for
- and
+ there is both a unary, and a binary version (e.g.
a+b and
+a are both valid), so if you want to redefine the unary version you have to use
def +@ and
def -@.
Also note that there is a unary version of
* and
& as well, but they have special meanings. For
* it is tied to splatting the array, and for
& it is tied to converting the object to a proc, so if you want to use them you have to redefine
to_a and
to_proc respectively.
Here is a more complete example showing all kinds of the unary operators:
class SmileyString < String def +@ SmileyString.new(self + " :)") end def -@ SmileyString.new(self + " :(") end def ~ SmileyString.new(self + " :~") end def ! SmileyString.new(self + " :!") end def to_proc Proc.new { |a| SmileyString.new(self + " " + a) } end def to_a [SmileyString.new(":("), self] end end a = SmileyString.new("Hello") p +a # => "Hello :)" p ~a # => "Hello :~" p *a # => [":(", "Hello"] p !a # => "Hello :!" p +~a # => "Hello :~ :)" p *+!-~a # => [":(", "Hello :~ :( :! :)"] p %w{:) :(}.map &a # => ["Hello :)", "Hello :("]
In your example the Module just simply defines an unary + operator, with a default value of not doing anything with the object (which is a common behaviour for the unary plus,
5 and
+5 usually mean the same thing). Mixing in with any class would mean the class immediately gets support for using the unary plus operator, which would do nothing much.
For example:
module M def +@ self end end p +"Hello" # => NoMethodError: undefined method `+@' for "Hello":String class String include M end p +"Hello" # => "Hello" | https://codedump.io/share/7ZOKe0AwdKmM/1/what-does--mean-as-a-method-in-ruby | CC-MAIN-2017-17 | refinedweb | 320 | 74.59 |
[
]
ASF GitHub Bot commented on ACCUMULO-4138:
------------------------------------------
Github user asfgit closed the pull request at:
> CompactCommand description is incorrect
> ---------------------------------------
>
> Key: ACCUMULO-4138
> URL:
> Project: Accumulo
> Issue Type: Bug
> Components: shell
> Affects Versions: 1.6.4, 1.7.0
> Reporter: Michael Wall
> Assignee: Michael Wall
> Labels: newbie
> Fix For: 1.6.6, 1.7.2, 1.8.0
>
> Time Spent: 1.5h
> Remaining Estimate: 0h
>
> The compact command has the following description
> {code}
> root@accumulo> compact -?
> usage: compact [<table>{ <table>}] [-?] [-b <begin-row>] [--cancel]
[-e <end-row>] [-nf] [-ns <namespace> | -p <pattern> | -t <tableName>]
[-pn <profile>] [-w]
> description: sets all tablets for a table to major compact as soon as possible (based
on current time)
> -?,--help display this help
> -b,--begin-row <begin-row> begin row (inclusive)
> --cancel cancel user initiated compactions
> -e,--end-row <end-row> end row (inclusive)
> -nf,--noFlush do not flush table data in memory before compacting.
> -ns,--namespace <namespace> name of a namespace to operate on
> -p,--pattern <pattern> regex pattern of table names to operate on
> -pn,--profile <profile> iterator profile name
> -t,--table <tableName> name of a table to operate on
> -w,--wait wait for compact to finish
> {code}
> However, the --begin-row is not inclusive. Here is a simple demonstration.
> {code}
> createtable compacttest
> addsplits a b c
> insert "a" "1" "" ""
> insert "a" "2" "" ""
> insert "b" "3" "" ""
> insert "b" "4" "" ""
> insert "c" "5" "" ""
> insert "c" "6" "" ""
> flush -w
> scan -t accumulo.metadata -np
> compact -b a -e c -t compacttest -w
> scan -t accumulo.metadata -np
> deletetable compacttest -f
> {code}
> You will see that file associated with the 'a' split is still a F flush file, which the
files in the 'b' and 'c' split are A files.
> Not sure if the fix is to update the commands description, which would be easy, or to
make the begin row actually inclusive.
--
This message was sent by Atlassian JIRA
(v6.3.4#6332) | http://mail-archives.apache.org/mod_mbox/accumulo-notifications/201602.mbox/%3CJIRA.12937920.1455037315000.99840.1455937338895@Atlassian.JIRA%3E | CC-MAIN-2017-04 | refinedweb | 318 | 50.87 |
Perhaps seeing so many crumbling chimneys, and fallen-away walls around the place in recent weeks has further highlighted the importance of being able to simulate this. And perhaps, indirectly, suggests a solution :)
The Problem
So, as a refresher to where we left off, the current situation is that once you've got the brick wall set up, it will very easily (or quickly) start wobbling and then collapse, and all before whatever you were planning to have collide into it gets there.
Potential Solutions
Over the past few days, as time has allowed, I've started researching these issues again. One particularly informative thread discussing these matters that I've found is:
Solution 1 - Start the simulation when the collision should take place
"rsquires" (on 08-23-2006, 06:28 AM) suggests in the thread this technique.
There are currently 84 "bricks" in my wall.. this number isn't set in stone though. Can anyone w/ dynamics experience help me out? I'm trying to make the bricks settle happily with each other without toppling over before the object gets to them.
I think a way of doing it is to have a key frame that turns on the sim just as the object hits the wall. This way they don't settle but just react to the impact. However doing it for 84 blocks seems tedious
Inspired by this thought, I quickly tested this out in one of the test scenes I had. Indeed it works as expected, as the blocks simply haven't fully settled and applied forces on each other, forcing the wall to topple.
What I did was quite simple:
1) Scrub through the animation to see when the ball would roughly be standing right in front of the wall, ready to knock it over.
2) Note the frame (add a marker if it helps to remember this)
3) Set the start frame for the simulation world (that the wall and the ball belonged to) to this frame.
Playing back the sim, the result was that the wall stayed still until the ball hit it, which is when the sim started kicking in, thus achieving our goal.
For simple situations, this should be enough. Hopefully this is enough to get your problem out of the way, if this is what is causing you problems.
Solution 2 - Find the friction value that approximates the strength of the mortar holding the wall together
The previous solution fails in more complicated cases, where we may have two towers, one of which bowls over the other. Or what if the ball was not hand animated, but rather, an active RigidBody? Basically, the problem is: what happens if we cannot isolated the simulation so that we can delay its start time until we know a collision may occur.
Hence, enter solution 2, as suggested by another poster in the thread:
"bcbarnes" (on 08-23-2006, 06:39 PM)
In general, I have found that the rigid body dynamics works pretty well [...snip...] The only thing that might be difficult is coming up with a friction value between the bricks that simulates the way the mortar (sp?) would hold together and then break apart
Indeed, this is quite a sensible suggestion, especially in light of seeing the collapsed chimneys, and some of the older brick homesteads. Apparently the mortar becomes weaker as it gets older, as it dries up and turns into mere sand/dust. Hence, we can say that friction is what can be used to hold the bricks together a bit better.
I haven't yet tried this suggestion, as I'm sure it does involve a bit of trial and error to get right. However, I will update this if and when I do find some suitable settings. Certainly, if we can get this set up right by default, things will work better "out of the box" than otherwise.
Solution 3 - Check on the space between bricks
The previous solution also raises in interesting point: the mortar between bricks kindof acts to give a bit of separation between them. This raises the issue that perhaps the collision margins could be tweaked, and/or the original spacing of the bricks could also be looked into.
I think I read somewhere in the thread a suggestion that Maxon used to pre-roll their brick-wall sims, with the walls created with spaces between the bricks, which are then flattened by having gravity pull them together before freezing the result. Perhaps some tweaks are needed in this respect?
I'd be interested in hearing if anybody finds any of these methods particularly valuable in getting this working well.
Laters!
looking forward to what you find out
I have a solution to your problem!
And here is how I fixed it:
I assume you already put the blocks together properly (Not that hard).
There is a python script that I used to fix this.
import GameLogic
import PhysicsConstraints
PhysicsConstraints.setNumTimeSubSteps(10)
controller = GameLogic.getCurrentController()
owner = controller.getOwner()
owner.setCollisionMargin(0.00)
PhysicsConstraints.setNumIterations(99999999)
Link that script with logic bricks to all of your objects. Here is how:
1. Go to the bottom left of the 3D view, and change the Window Type to Text Editor.
2. Copy and paste that script.
3. At the bottom of the text editor, it will say something like "Text.001", "Text.002", or simply "Text".
4. In the logic bricks, connect an always sensor to a python controller.
5. Type in the name of the text (eg. Text.001)
6. Select all the physics object except for the one you did that on.
7. Select the object that you just did that on
8. Press Ctrl-C, and in the drop down choose logic bricks.
9. Done.
Sorry, I screwed up the URL :D.
Here is the good one: | http://aligorith.blogspot.com/2010/09/bullet-soc-still-researching-brick-wall.html | CC-MAIN-2021-25 | refinedweb | 974 | 70.02 |
There are 3 ways to modify Mercurial's behavior: writing "hooks" in a user's (or system-wide) hgrc file, writing and "extension" for hg and finally modifying hg itself. I will cover those briefly below.
Hooks
A hook is an action that gets executed before or after a command is issued. For example, to see the differences before committing changes, you could write it as a "precommit" hook:
[hooks] # Before we commit, make sure we know what we are committing precommit = hg diff|less
In this case, precommit says when to perform the action and hg diff|less says what to do.
To automatically merge and update your reposisory after updating it you could insert the following hook in your hgrc file:
[hooks] # Execute hg merge and hg update after pull-ing incoming = hg merge && hg update
Hooks have to be written in a file called hgrc located $INSTALL_ROOT/etc/mercurial/ . You can have multiple hgrc files and they all get loaded by hg. The man page for hgrc has more info if you'd like to tweak yours more:
Extensions
Printing out more user-friendly error messages is requires somewhat modifying the behavior of hg and that's what extensions try to do. Extension are written in python and they are used to add new commands or modify/override existing ones. For example, here's an easy one that I've written that prints out a warning when committing fails:
def docommit(ui, repo, *pats, **opts): i = repo.commit(None) if None == i: print 'WARNING: Your changes have NOT been recorded!' print 'You must enter a message in order to record them.'
One limitation of extensions is that you depend on what functions provided by hg return. For example, the commit() function from above returns None for one other kind of failure, but you have no way of knowing what kind of failure it is.
Find more about writing your own extensions here:
Modiying Mercurial
Modifying the source is not that hard either. In particular, $MERCURIAL/mercurial/commands.py is where you'll find all the operations (add, commit, etc) along with the sometimes cryptic error messages they output. It also helps to look at localrepos.py, if you're not sure what a command is doing. | http://www.sagemath.org:9001/ModifyingMercurial | crawl-003 | refinedweb | 379 | 59.84 |
I've assigned how much a person would like to do x activity and have it in a list. Using buttons you can ask the npc what it wants to do from given activities. How would you make it so each button would check the value the npc has for that activity?
This is not from the activities, but its done the same way: gamingTypes.Add (new Gaming ("Board Games", Random.Range(-5, 5)));
How can I make so if the button that says "Running", checks the script for the value the character has in running?
EIT: I have some activities like the ones below. As a start, I'm making it so it generates how much a npc likes those activities, and you can ask the npc if it wants to do X activity. I'm doing it using buttons, with all the options in the screen, and I wanted to try to make it so, if the player clicks on Running, it would look for "Running", on the list, and get the value. How should I go about this? Sorry if this is too basic, had been a while since I programmed the last time:
activity.Add (new Activities ("Fishing", Random.Range(-5, 5)));
activity.Add (new Activities ("Running", Random.Range(-5, 5)));
activity.Add (new Activities ("Hunting", Random.Range(-5, 5)));
Something like this perhaps:
int value = gamingTypes.Single(x => x.name == button.name).value;
Since you have provided no code, I can only guess as to what you have called your variables.
Sorry, thanks anyway. Edited the question explaining properly and adding some code
please post your code with your list so we can help
Sorry, I'm stupid. Edited the question. Hope it helps!
This is simple, yet the answer is not simple.
You need to create the logic for this system to work, it's not some miraculously built-in thing just because you read it on a board game tutorial.
What I tend to do for displaying dialog is creating a class that is a dialog entry template, a dialog controller, and instantiate the dialogs as needed. So lets say your dialog entries can contain an activity, that would be included in the template class, then define it during instantiation. Keep the activities separate. Like this. (this is a basic example mockup, don't expect it to work with copy and paste)
public class DialogEntry : MonoBehaviour
{
public Text text;
public Activity activity;
public void OnDialogSelected()
{
DialogController.Instance.RegisterSelection(this);
}
}
and
public class DialogController : MonoBehaviour
{
public static DialogController Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<DialogController>();
}
return instance;
}
private set
{
instance = value;
}
}
private static DiaogController instance;
public DialogEntry template;
public RectTransform dialogAnchor;
public void Initialize(Dialog dialog)
{
foreach (DialogActivityPair pair in dialog)
{
DialogEntry entry = Instantiate(template, dialogAnchor);
entry.text.text = pair.text;
entry.activity = pair.activity;
}
}
public void RegisterSelection(DialogEntry entry)
{
if (entry.activity == someExpectedActivity)
{
//Do something based on expected activity.
}
}
}
Answer by Pinkuboxu
·
May 03, 2018 at 01:52 PM
@tormentoarmagedoom Raises a good idea but didn't really supply an implementation. Also, I think a Dictionary would simplify this greatly.
A very simple version but this is the code you would put on the NPC:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Activity : MonoBehaviour {
Dictionary<string, int> activities =
new Dictionary<string, int>();
void Start ()
{
activities.Add("Fishing", Random.Range(-5, 5));
activities.Add("Running", Random.Range(-5, 5));
activities.Add("Hunting", Random.Range(-5, 5));
}
public void GetActivity(string activity)
{
print("My " + activity + " is " + activities[activity]);
}
}
Of course you would probably want to change the class name to something else like ActivityPool and have a method that helped add activities to the NPC rather than just pop them in at start... among other things.
Here is how to set up a Button for use with this.
[1]: /storage/temp/116139-dictexamp1.png
You are right! Just checked unity's video on dictionaries, and, if I understood correctly, it allows me to access the information much easier and faster! Gonna keep learning about both rn, and will reply to the code and all that later.
I have a question tho, just so I know I'm getting this properly. Could I have NPC's stats, likes... stored in their own dictionaries... I'm guessing I'll also be able to edit the values... Man, thanks a lot. I can kinda see it now. With lists it was kind of a mess thinking about accessing the information stored, but this way seems way better.
Btw, I'm guessing dictionaries are also better when storing a lot of information. Am I right assuming this?
Edit: I'm just wondering, should I give the random value as I was doing it (when adding it to the list/dictionary), or using For to go through the dictionary adding the value? I'm gonna have a lot of stats, so I don't know what'd be the best way
Gonna learn properly about it. Thanks a lot!
Yes, Lists are kinda/sorta just a bit of arbitrary arrays, and dictionaries are more of "Hashtables" which instead of an integer index to grab the data... it can technically be any other type of data as a key to access another type of data. I think I'm ok in saying that the sky is the limit, kinda. You can use your own class/struct as a key or value, I think. You could have any data, or for Unity sake GameObject, point to another bit of data. Just remember KISS principle and don't get so bogged with stuff that you lose interest. As amazing as all of the new data types that exist, I feel it sometimes detracts from what we started with in low level coding. I'm not saying you have to learn any assembly to have a good time, but some core CSci is probably good medicine. There's always a really easy and simple way to do something, even before all of the candy we get in C#, there's just so many ways of doing things now that it's kind of mind boggling. Good luck and I look forward to hearing what you come up with.
As for the other part, adding stats for NPCs or what not, I'd look into scriptable objects if you need a way to add persistant data that you input by hand, however if you need something more procedural/runtime generated the method you are doing is fine but I'd wrap it in a class or struct so it's more flexable and re-usable.
Answer by tormentoarmagedoom
·
May 03, 2018 at 11:20 AM
Good day.
Ypu should check the event trigger system. It allows you to execute a method with parameters, like the button name..
About mobile FPS Sprint
0
Answers
How to make button rotate when another button is pressed?
0
Answers
Android UI push Multiple buttons Help
0
Answers
[ANSWERED] IndexOf and LastIndexOf both returning -1 when an item is on the list.
1
Answer
Buttons work in the Editor but not in the build... WHY!
0
Answers | https://answers.unity.com/questions/1501385/how-can-i-check-value-stored-in-a-list-when-pressi.html | CC-MAIN-2019-51 | refinedweb | 1,192 | 64.61 |
Posts62
Joined
Last visited
Content Type
Profiles
Forums
Store
Showcase
Product
ScrollTrigger Demos
Downloads
Posts posted by Dcoo
Thanks, I'm trying to set the Crop instance's "cropMode" to true or false with a button, but I cant find the current selection I have been trying manager.configureCropMode but no luck
I tried crop.configureCropMode(true); and this
function cropitFunction (event:MouseEvent):void{ this.manager.configureCropMode(true); }
Thanks for the reply, and yes ,sorry my question is confusing!
what I'm wondering is is there something like manager.deleteSelection(); for cropMode true?
or would it be something like crop.Selection = cropped "true";
or Crop.Selection.cropMode = true;
I would like to use a button to turn on and off Crop,
is there an equivalent to "manager.deleteSelection(); " for cropMode true?
I'm adding my imageLoader to new Crop shown below:
but I want to use a button "on click" to change the "cropped true" of whatever object is slected and then agin to false with a finished button.
but my var crop:Crop = new Crop(imageLoader,manager); is not accessible out side the function imageLoaded
so I get an error that flash docent know what Crop is?
any ideas would be most welcome
function imageLoaded ( event:Event ):void{ log2 ( "Image loaded asynchronously." ); imageLoader.width = 640; imageLoader.height = 480; imageLoader.y = 109.35; imageLoader.x = 660; imageLoader.rotation = 90; this.addChild ( imageLoader ); var crop:Crop = new Crop(imageLoader,manager); }
Sure, TransformManager can transform pretty much any DisplayObject. It's fine if you're dynamically adding text (although not right in the middle of while your user is dragging/resizing).
maybe I'm doing something wrong because I add my text to the TransformManager but it only transformes the text box not the text inside
I have added dynamic text to my TransformManager, is it possible to change the size of dynamically added text ?
Cool thanks!
Is it possible to call the crop with a button instead of double clicking?
- Yes thank you, I'm wondering why my transformManager was working with out that code?import com.greensock.transform.*;
- dang, I get this eror message when I test that codeScene 1, Layer 'cam', Frame 2, Line 197 1046: Type was not found or was not a compile-time constant: Crop.Scene 1, Layer 'cam', Frame 2, Line 197 1180: Call to a possibly undefined method Crop.Note:
I added import com.greensock.transform.*;
and don't get the eror
Nope, you don't add it to the manager - the Crop does that for you. You pass the TransformManager instance to the Crop so that it knows how to associate things. Check out the example in the docs.
import com.greensock.transform.*; //create the TransformManager first var manager:TransformManager = new TransformManager(); //now create Crop objects for mc1, mc2, and mc3 which are all DisplayObjects on the stage var mc1Crop:Crop = new Crop(mc1, manager); var mc2Crop:Crop = new Crop(mc2, manager); var mc3Crop:Crop = new Crop(mc3, manager);
So once you create your TransformManager, you can add as many Crops as you want, whenever you want.
Ok but it still looks like I would need to know the name of the object, but in my code its being loaded from a camera so I don't know what the name will be?
right now all the pictures loaded manager as loader and it works fine how could I add a crop into this scenario?
function showMedia( loader:Loader ):void { loader.width = 640; loader.height = 480; loader.y = 109.35; loader.x = 160; /*loader.rotation = 90;*/ this.addChild( loader ); manager.addItem(loader); }
I'm not sure where to add it? Before I add it to the manager?
var imageLoaderCrop:Crop = new Crop(loader); manager.addItem(loader);
So you cant us it for dynamic content? you would need to know the name of the object your adding ?
Sorry I just pasted the wrong code in there!
I'm looking a crop instance for dynamically added images, I'm adding images as there taken, to my manager
function showMedia( loader:Loader ):void { loader.width = 640; loader.height = 480; loader.y = 109.35; loader.x = 160; /*loader.rotation = 90;*/ this.addChild( loader ); manager.addItem(loader); }
and here is my manager
var myTargets:Array = []; var manager:TransformManager = new TransformManager({targetObjects:myTargets,constrainScale:false,forceSelectionToFront:true,allowDelete:true,autoDeselect:false,handleSize:35});in the example it shows each crop made one at a time
can I some how set up a crop with "myTargets"
var mc1Crop:Crop = new Crop(mc1, manager); var mc2Crop:Crop = new Crop(mc2, manager); var mc3Crop:Crop = new Crop(mc3, manager);
- I cant get crop to work, is it possible to use it with dynamically added images?
var myTargets:Array = [];
var manager:TransformManager = new TransformManager({targetObjects:myTargets,constrainScale:false,forceSelectionToFront:true,allowDelete:true,autoDeselect:false,handleSize:35});
so using deleteSelection() method. if I want to call yourTransformManager.deleteSelection();
should be written like this? manager.deleteSelection();
No problem, sound fair, one question for you then, in this code is my TransformManager named "manager" ? or does it get a name programmatically?
var manager:TransformManager = new TransformManager({targetObjects:[deco127],constrainScale:true,forceSelectionToFront:true,allowDelete:true,autoDeselect:true,handleSize:29});
Sorry, what if I have more that one TransformManager, but they have the same name? yourTransformManager.deleteSelection();
- Just changed textField.embedFonts = true; and now it works!
yourtxt.addEventListener(MouseEvent.CLICK, textFrom);function textFrom(event:MouseEvent):voidvar textFormat:TextFormat = new TextFormat();textFormat.size = 35;textFormat.font = "Cubano";textFormat.color = 0xEFB20C;/*.embedFonts = true:28});
- 1
Cool, thank you!
Hi Jack, is there an example of how to use deleteSelection() method ?
- is there sorting I could do to stop my dynamic text field from disappearing on rotate ?yourtxt.addEventListener(MouseEvent.CLICK, textFrom);function textFrom(event:MouseEvent):voidvar textFormat:TextFormat = new TextFormat(:22});]);
}
}
Cant get crop to work
in TransformManager (Flash)
Posted
Thank you Jack! thats it exactly!! | https://staging.greensock.com/profile/12621-dcoo/content/page/2/?type=forums_topic_post | CC-MAIN-2022-21 | refinedweb | 976 | 50.02 |
5
DAN CUPID'S HOT WEATHER PRANKS.
RAILROAD NEWS
FROM ALL POINTS,
IN THE CITY.
WMXMMWWWMIOWWWM
THE REPUBLIC: THURSDAY. AUGUST 16, 1900.
I Wm til J ?A t
!
Hiero Tifl'any and Miss Linahan
' Eloped to Clayton and Then
Went to Arkansas.
BUSY DAY AT GRETNA GREEN.
Family Objections, Religious Dif
ferences and Other Circum
stances Led Several Couples
to the County Seat.
To circumvent parental oppo'ltlon. MI"
Alice Linahan. a comely joung woman of
IS summers eloped to Clajton jester
day afternoon -with Hiero G Tlffanv
ami was married to him by Justice of the
Pcaco J. B. Greensieldcr. Then, to escape
rarental -wrath, the pair went direct to the
"Union Station and boarded a train for Lit
tle Rock, where the honejmoon will be
spent. Its duration will depend on the length
of time it takes the wrath of the Ltnahans
to be appeased.
The Llnahniis live at No. 1735 Morgan
Ftrcet. the home of Mis Ltnahan's uncle.
John Linahan. the proprietor of a boolc
store. The latter'? wife died some several
months ago. and since then Miss Linahan
and the members of her family have been
keeping house for him
Difference of religious opinion is the rea
son given ly Miss Linahan's parents for
opposition ta their daughter's marriage.
The Linalmns are deout Catholics the
bride being .1 member or the Young Ladle5'
Sodality in the Immaculate Conception Par
ish. Tiffany Is a Protestant.
Tile couple were accompanied to Claton
bv- Mis Linahan's sister .n 1 a ounr rnn
who refued to give his name. Tiffany Is an
electrician in the employ of the Missojri
Taclllc Railroad Companj.
There were several other eloping couples
.at Clajton jestcrday. From Chicago, and
far off San Francisco. rcpectiely. came
James M. Craig and Eva L Crouch. They
were marrlsd bj the Reverend Doctor
Charles of the Presbjterlnn Church. Co
lumbus. O . furnished a couple in the per
wms of Sedlej Hurlbcrt and Grace Hinder
hand. Thoj were verj- anxious that the
natter be I.cpt quiet, and argued with the
license clerk for ten minutes in an effort
to keep their n imcs off of the records.
There were two couples from St. Louis
Count j. The first. Michael Wclfrey and
Lizzie Clark, both of Allcnton. were mar
ried at home. The second couple, Andrew
Dickson of Sappington and Koena Mead of
Affton, were married by the Reverend
Doctor Charles.
RECEPTION BAY AT
ST. JOSEPH CONVENT
Feast of the Assumption the Occa
sion of a Great Gatheiing in
the Old Building.
NEW CHAPEL MUCH ADMIRED.
Many Postulates and Novices Re
ceived Into the Order, and the
Day Made One of Gen
eral Rejoicing.
Visitors thronged the convent of the Sis
ters of St. Joseph In Carondelet jesterday.
when the order celebrated tho feast of the
Assumption and received many postulants
and novices The sisters were privileged to
receive their friends and relatives. The
entiro house- was thrown open for Inspection
and tho beautiful grounds were filled with
visitors.
From early morning until sunset women
nnd children streamed Into the weather
beaten old convent. Its entrance Is on Min
nesota avenue and Kansas street, and the
ptructure. as It has been built with its nu
merous additions, rambles over two city
squares. With Its dense foliage and the
beautifully tended grove of great old locust
trees, and long quivering creepers, and the
little beds of vivid flowers, the quaint old
place reminds one of convents in Europe.
Tho convent Is one of the richest in the
West, as It Is tho mother-house of the Sis
ters of St. Joseph In this part of the United
States. The Reverend Mother Algoria Is
the superior. The convent is perched on a
high bluff overlooking- a large sweep of tho
Mississippi River and of the Illinois shore.
Yesterday the sisters were at liberty to
loiter In nooks about the beautiful grounds
with their visitors. The entire place had a
eweet, placid atmosphere that filled the vis
itor with peace and quiet.
One of ths things which the nuns exhib
ited with much pride was the new chnpel,
which has Just been completed. Its con
struction, with the altar and Its various
ornaments, cost many thousands of dollars.
fhe chanel building alone cost $G0.0OT, tne
gift of one of the nuns. It is filled with
laro statuary and splendid marbles, and
there are numerous relics of martyred
taints, who'e memory is dear to the Sisters
of St. Joseph. There are also several tomb
stones, taken from the Catacombs, that are
known to bo more than 2,000 j ears old. The
main altar is an "altare prlv lleglatum," by
special dispensation from the Pope, and
there are live other altars around it in
honor of Uc Blessed Virgin, St. Joseph,
the Chapel of Martjrs. the Souls of tho
Head, and Our Lady of Salette. The sta
tions are all of rare beautv and are con
structed of the same material as those at
St. Francis Xavier's Church.
NEWS OF THE CHURCHES.
The Reverend Doctor Jesse Bowman
Young, former editor of the Central Chris
tian Advocate, who has been suppljing the
pulpit of tte LIndell Avenue M. K. Church
the last six weeks, fcas gone on a month s
trip to Colorado At the close of services
last Sundaj ex-Governor E. O. Stanard ex
pressed to Doctor Young the appreciation
of tho congregation for his services. After
the meeting of the conference Doctor Young
will assume tho pastorate of Walnut Hills
M. E. Church, In Cincinnati, O.
The Reverend Doctor J. P. T. Ingraham.
pattor of the Grace Episcopal Church, is
seriously Hi at his home, in Marlon place,
near Twelfth street.
t.l vnntsn n tVi rftftf CO r1 PT1
of the Central Y. M. C. A. to-morrow even-
in" win oe a coiic-uit u.v iviumei j itm-
and Reed Band. These concerts, together
with the swimming pool and bowling alley
features, are rapidly increasing the mem
bership of the association. It now stands
530, with an average net Increase of more
thati ten a day.
St. Malachy's Young Men's Sodality has
completed arrangements for a lawn party
to be given at St, Malachy's Park. Garrison
and Clnrk avenues, to-morrow evening. An
excellent programme has been arranged for
the occasion.
Professor W. B Chamberlain of the Chi
cago Theological Seminary has been Invited
address the Y. M. C. A. next Sunday aft
ernoon HH topic will be. "Sources of Pow
er for the Young Man.
The Reverend Doctor J. F. Cannon, pastor
Walter Keeton and Nellie Lorn;
Went for an Outing and
Were Married.
FROM BELLEVILLE TO CLAYTON.
Bride's Younger Sister Accom
panied Them, but Didn't Know
the Object of the Trip
Until It Developed.
Walter ICeeton and Nellie Long, on mat
rimony bent, journejed from Rellevillo to
Claton jesterdaj. accompanied b .1 l'-year-old
sister of Miss Iong and V. II.
Guiton. n friend of Keeton
They obtained a marriage license and
were married by the Reverend 1! II.
Charles of the Clivton Presbvtenati
Church. Then they returned home and re
ceived tne parental blessing and the con
gratulations of their many friends, to
whom their action was a complete surprise.
Miss Long is the prettv daughter of Geo.
R. Long, a furniture dealer In Kellcville,
and has had manv admirers. Keeton is a
conductor en the Daj line, and lias lived
In Belleville about a jcar. He met Mls
Long shortlv after his arrival and paid her
marked attention. Miss Long exhibited an
equally marked preference for the stalwart
joung conductor.
Keeton called at the Long residence vesterdav-
morning and said he lied been Given
.1 daj's iv -off, at d asked Miss ling to take
an outlng'wlth him to Forest Park and some
of the summer gardens in Pt Louis Mrs.
Long suggested that Nellie's jounger sister.
Cora, IB vears old. aceompanv them, and
Keeton said he would be pleased to hive
her go Accordingly the trio left the house,
promising to be home earlv. Miss Cora
had no inkling of the intentions of her sister
and Ko"ton at tint time.
On the vvav to St. Loui. AV. II Guiton,
a friend of Keeton's. Joined them He was
cognizant of the plans of the couple. In
a casual way he asked the party to join him
In a trip to Clav ton. vv here he s lid he had
some business to tnnsact, after which they
could enjoy themselves In Torest Park and
tne summer gardens. Thev consented and
Guiton led the vvav direct to the Clav ton
Courthouse. Miss Cora Long still did not
divine what was up. and the marriage li
cense was obtained without her knowledge
It was only when the pirtv called .it
the pastor's residence that the joung girl
realized how- she had been imposed upon.
Then her chagrin was disunited in the
good-natured laugh indulged in by the jok
ers. A telephone messigc was sent to the
parents of the bride by the elopers, In
forming them of what had taken place. Mr.
Long regretted the hastv marriage, she said,
because she had planned a big leception and
wedding supper.
The couplo will make Belleville their
of the Grand Avenue Preshjterian Church,
left vesterday for a two v eeks' vacation at
Ocean Grove. N. J. In his absence the Rev
erend Doctor George T. Eddy will supply
his pulpit.
TWO WATCHMEN ASSAULTED.
Fight in a Saloon in Which Many
Shots Are Fired.
Two private watchmen and a crowd of
men who were in Albert Newman's saloon
at No 1S0O South Third street, about 9
o'clock, engaged In an argument which
resulted in tho exchange of more than a
dozen pistol shots. No one was injured,
but several arrests were made The watchmen-were
released from custody after
they had been taken to the Third District
Station.
Isaac Ketchum of No 151") Menard street
and Charles Davenport of No 1121 St. Ange
avenue are watchmen in the cmploje of
the Iron Mountain Railroad Companj.
Ketchum was formerly emplovod as a
guard at the Workhouse, and one of the
men in the crowd mode the declara
tion that Ketchum and another guard
named Joe Gollsh had beaten him with
their clubs while he was serving time there.
Ketchum denied it, and when the man
walked toward him drew his revolver. The
crowd assaulted the two watchmen Daven
port, who went to Kctchum's assistance,
was dragged Into the street and relieved
of one of his revolvers. He had another
revolver, which was overlooked In the
search, and with that he opened lire on his
aEsailants Newman, tho proprietor of the
salcon, also fired. None of tho bullets took
effect.
William Bliss, the bartender, was ar
retted on a chargo of disturbing the peace
Newman will be held to answer to a charge
of assault to kill.
DEMOCRATIC PICNIC.
Prominenl Speakers Arouse Enthu
siasm at Alton.
A Democratic picnic and demonstration
was held by the Brvan and Stevenson Club
at Rock Springs Park yesterday. Among tho
prominent speakers were Congressman
Thomas M. Jett, General Alfred Orendorft
of Springfield and John W. YnntH of Shel
brville. candidate for the State Board of
Equalization from the Eighteenth Congres
sional District.
The dav's programme began with a street
parade The exercises nt the park besan
at 2 o'clock. The first ppeakei was Con
gressman Jett, who poko at length on
the mistakes of the Administration at
Washington. He closed his address with
a talk to tho labor element, saving he wa-
in favor of a labor representative in the
President's Cabinet. He also had a word
to sav to the old soldier'. He wound i.p
by declaring he would come to Mndlon
Countv in the November election with a plu
rality from the six other csuntie of " Oo-J
Congressman Jett was rollowpd bv Jlr.
Yantis, after which the iissornblase ate a
picnic dinner. In the evening General Orcn
dorff addressed the picnickers. R.iln inter
fered to some extent with the evening at
tendance The address of General Oren
dorff was followed bj a concert by the two
bands.
NO PROFIT ON ENGLAND.
Foreign Exchange Rankers May
Ship XoMoie Gold.
New York. Aug 13 Foreign exchange
bankers reported to-daj their In.ibllltv to
obtain such concessions fiom the 1J-1- o!
Ei gland as would make furthc- gold ship
ments from this countrj profltab e.
A banking-house with Important connec
tions knew of no inducement offered bj the
Bank of Trance to attract gold to that
country bv to-morrow's steamer.
INJUNCTIONAGAINST HOPKINS.
First Wife Would Restrain Him
From Disposing of Property.
REPI-BI.IC SPECIAL
Chicago. 111. Aug 11 Judge Neelv Ins
Issued a temDorarv injunction restraining
John D. Hopkins of the Hopkins Amuse
ment Company from disposing of anv of
his property until the further hearing on
the cros bill filed vesterday b his first
wife. Mrs. Rasetta R. Hopkins.
SENATOR INGALLS NO BETTER.
Rested Well, but His Condition
Has Xot Improved.
Kansas City. Mo , Aug. 15 A special from
Las VcKas sajs former United States Sen
ator John J. Ingalls rested well last night,
and that he ate fairly well this morning.
His condition Is not materially chanced
from jesterday.
EARTHQUAKE SHOCK.
Window Panes Broken by Earth's
Convulsions in Washington.
Seattle, Wash . Aug. 15 A special to the
Times from Silverton. Wash., sajs:
A hard shock of earthquake was felt here
yesterday at 4 o'clock, shaking window
panes and crockery to pieces in many in
stances. The shock lasted three minutes.
Roy Hadsell, Aged 20, of Madison,
Weds Elizabeth Cotton, Aged 17,
of Edwardsville.
SURPRISE TO THEIR FRIENDS.
Met Six Months Ago and Were En
gaged Hefore the Daj's I'lohe
The Parents of'ltoth
(Jave Consent.
In a storv of love, who shall cav when tho
l'ist paragraph is written." ho announce
"Conclusion" while both principals are liv
ing and Cupid is at large'
Friends thought the attachment of beauti
ful i:il7.thcth Cotton and Uoy Hadsell at
Madison. Ill , would end when the heroine
of the romance leturned to her home at
Mount Vernon i months ago. after a vllt
in Madison Publielv it did.
"Too bid!" sild the public, but the voting
folks said "Not vet." In Kdw.irdsville jc
terdnv thev were married bv Justice George
Barraclough m the most approved Madison
Count v fashion
Roj Hadsell. who Is CO j ears old. and looks
about 17, is a well-known Madison business
outh. with a record as a monev -maker. He
met the fascinating Klbabeth Cotton at .1
social gathering. Shy as was onlj 17, out
nothing was said about ages
In less time tl.au it takes to tell It the
joung man was in love. Before the ev
ening was over thev were betrothed De
t ills of a cereironj however, were left
to the future, as each thought there was
plentv of time Miss Cotton went home and
It was said that the episode was ot.lv .1
p.is'injf flirtation, a meie lotus areim, be
ginning too successful. t0 ue sincere.
"Life is real, life is earnest, and in irri.ige
is the onh h ippj goal." wrote voung It id
sell In his long-dist.iin c courtship When
it was too lite he bewail to think what a
mist ike tluv had made in parting at til
Miss Cotton's letters were encotirnglng. and
llnallv Hndsill decided to ask the opinions
of his stepfather, M 11 Fulson, and his
mother Thej were almost as encouraging
as the voting ladj herself, so the net step
was to have the heroine investigate the
part to be plajed bv her relitlves. Miss
Cotton found that there would be no opposi
tion from that source and after a sep ir.i
tion of six months the voung lid and her
hlster, Mrs. Roack, met Hadsell and his
parents In Fdwardsvllle vesterdav. A mar
riage license was issutd to the couple and
from the Recorder's office tlicy went
straight to Justice Barraclough
Something In tho manner of the juvenile
principals caused the Justice to tint a
weight on his legal papers and to ask If
It was to be a wedding. "Of course," said
Hadsell. but he wanted no publicity alnut
the matter.
When the ceremonv had been performed
the wedding partj boarded a bt. Louis
train, and after a brief stop In the cltv
returned to Madison, where Mr and Mrs
Hadsell are now at home to their friend t"
BURGLARS WHO WERE
NOT FASTIDIOUS.
They Stole Pots, Pans, Kettles,
Coal and Everything Else
That Was Portable.
TOOK PLUNDER IN A WAGON.
Ransacked the Shed Rack of Resi
dence of George Spellman in
Cook Avenue Three
Negroes Did It.
Three negroes, who rode in a dilapidated
old wagon, committed a unique clav light
robberv Tuesday at the residence of George
Spellman, No 3710 Cook avenue.
They entered the shed in the rear of the
house from the allej. lacking the door
leading to the house thev ransacked the
Place at their leisure. It took two loads
to cirry cvervthing awaj, but thev suc
ceeded, and there Is no clew to their Identi
ty. Despite the heat of the present weather
and the slight necessity for fuel the thieves
made away with a good-sized pile of coal
It mun have taken consiJerablo time, and
at least one full wagon load to get this; but
these negroes evidently were in no hurrj
to leave the scere of their depredations anj
were rot at all afraid of interruption
It is believed the burglary was committed
some time In the afternoon In the morning
members of the Spfllman famllv were in th-
shed and nothing was then missed but
about 7 o'clock in the evtnlr-. when Mr
Spellman went to the hcd. th. robbers inii
comnle-eJ thir work and nothing of value
remained in the place
Neighbors saw three negroes about -1
n'lloek ii the afternoon come out of the
allcv Into Spiln" .ivtn.ie. Thev were dilv
ing .1 r.iw-boned bav hor-e and their wagon
v.. is full of coal The trio did not look cns-pl.-'otis
Whin Mr. Spcllmm made the JN
covpij that he had been robbed the three
negroes were rcmembi red and circumstan
tial evidence fixed the guilt upon them
In monetnrv value the propeitv taken bv
the thieves dos not amount to much It
consisted of pans pots and kstlles, .1 num
b'T of cans eif oil paints, some tools and
livers other things. ,,11 of wllch nire , d
helter-skelter into the wagon.
HOTEL EMPLOYE DROWNED.
Fred Lcawon. Houseman at the
Southern, the Victim.
Tred le.iwon. 27 jears 0'il. n houserian
at the fco itbern Ilotrl v ., tirow nr-,i in the
Mississippi niver at the font of Him stieet
about S o'clock lust night His l,odv lus not
been recovered
Lea won, with two companion. Hubert T.
Rogers nnd George Ncvh-, loft his lodg
ings nt No .102 Kim street, at nt o'clock
to take a twim in the river. A fur belnr in
the water a short time he .slipped on' a
rock, cutting his foot. He pl(k"d up the
stone and brought it ashore, rrna'king to
Ncvvbv. vho was on the shore, that he .-..is
going back to wash the blood from his loot
and then come out. This was the last seen
of Lcav.on Rogers, who w.au in the water,
and Ncwbj. who did not go in. both called
him, but received no answer. After seaicli
ing for a halt hour, tliej concluded he a as
drowned, nnd notitled the police Their
theorj is that when Lean on went back to
bathe his foot, he siippeu ln Matcr bevond
his depth, nnd. not being a good swlmriT.
was carried under bv an undertow. His
clothing was turned over to the police
Uavvon was born in New York City and
came to St. Louis live months ago. He Aas
unmarried and it is not known here
whether his parents are alive
DID NOT WITHDRAW IT. "
Building Trades Council Discussed
the Fine Order.
The question of withdrawing the fine or
dered Impose! upon members who ride on
transit cars was taken up in the form of a
resolution last night at the meeting of the
Building Trades Council at Druids' Kail
Speeches were made for and against the
proposition, the final decision by -vote being
to allow the order to stand.
Robert Young was elected Marshal for the
Building Trades Council for Labor Day.
NAVAL MILITIA DRILL The First
Division Naval .Militia of Missouri will hold
its regular weekly dull this evening at the
Armory. After drill Lkuten int Rogers will
call .1 'peU.il business meeting to deal with
unfinished business
WOUND PROVED FATAlKclly Hall,
a negro, who was hot in the chest In a
light by another negro named Pat McGren,
at Third and Plum .street". Sunday night,
olul jcsttrd.iv at tho City Hospital Jlc
Grew is under arrest.
DiyitCASHD CAPITAL STOCIC-The
Missouri Sand Coiiipinj .vislcnl.iy lilcd no
tice ot decrease ot its capltil stock fiom
ftdOOO to J10.WO The linn's assets are
designated as $.'l,IWS.i and the liabilities
as HV) The -lock is divided into 1,0W)
shares of $10 each.
ON JPDGB ADAMS'S RRNCH-Judge
John H. Rodgers of Fort Smith. Ark, will
hold court here to-dav In place of Judge
i:imer H Adams of the Fulled States Dis
trict Court, who is on his vacation at Wood
stock, Vt The docket is sin.ill and it is not
believed that It will take more than three
or four d.ivs to clear It up
HIBERNIANS' PICNIC The Ancient Or
der of H Iberians No S will f,lve- an excur
sion and picnic to Pacific, Mo. un Surdaj.
Augii-t 1''. The programme for the occa
sion will consist 01 all kinds of Irs-h nation
al games, el inces and races. The Hibernian
Hand will furnish music. The trains will
leave Union fetation at 3 a. 111 and 12.13
p m
SPECIAL TAX HILLS Assessor Freder
ick jesteidav srnt the veir's special tax.
bill") to Comptroller Sturgeon. lour d.ivs
in advance ol last jcar. To-d iv Mr. Stur
geon will have nineiv-totir clerk commence
making dupllc.iti s ul the hill They will
finish tin ir work in four divs 'lc bills
will bo siveti to the Collector before Sep
tember 1
HOY RFN OVEIt-Igniitz Kasban, 9
j cars old, of No UA Notth Rusluli street,
while cro'-sing Uioadv, iv at Washington
avenue, jestcrdiv morning, was knocked
down bv .1 horse attached 10 ,1 spring
wagon, owned and driven bj John Barker
of No 7J.1 North hpring avenue 'ilio
wheels pissed over his bodv. lie was ie
moved to the Cltv Dispens irv, whore Ins
injuries, which arc slight, were dres-eil
STRFCK RY A CAK-Mi-s Annie Hege
of No 2S1I Clark avenue was knocked down
1 ist night bv cat No 57 ot the Market
stieet division of the trinsit company
while crossing thi strrot In front of No 291J
Manche tci avenue. Doctor Gibson of No.
-Jl South Jeffeixm avenue, who attended
Miss Hcge at hei home, s iid she had le
celved .1 gash 011 the back of her hi ad and
several bruises about the bodv Hei con
elition is not serious
HE WAS JUSTIFIKD-Thomas R
Waters, who was chareel with nshault on
Adolph Stoffragen at Hroadw.iv and Salis
burv street, was ncquitttit In the Court
of Criinln tl Correction vesterdav. Walters
alighted from a Hroadwav ear with his
wife-, and started home Thiv were siir
lounded bv .111 angij mob Stoifragen and
Julius Kinase staitod lor Walters in such
a threatening manner Hint he drew his re
volver and fired The bulb t passed through
Stnffragin. lodging I'l Kulnct. Judge Clark
decided that Walters was justified in his
defense
ATTACKF.D THL PAMARITAN-Rohert
B Tobin of No 2710 Allen avenue, wa ar
raigned In the First District police Court
cstcrdiv. eharged with hiving disturbed
the peace of Joseph P. Methudv, a druggist
at California and Russell avenues Methudj
sud tint Tobin fell in-enslble on the side
walk in frort of the store Tucselav aiter
noon and that he carried him In the jnrd
and applied restoratives, which brought
him to consciousness in half an hour. As
soon ai he came to, Methudv -aid he made
n rush at him and struck him In the face
If It had not been for the intervention
of a policemen Methudv thinks he would
have received a severe beating. Tobin ex
plained that le was afflicted with (its.
Judge Sidener discharged him. recommend
ing that he be sent to the Citj Hospital
for observation.
OFFICIAL INSPECTION TRIP-Harbor
Commissioner Alt, Mavor Zlesenheln, City
Chemist Telchmann, Doctor Ravold, Re
corder of Deeds Hnhn, Collector Wenneker
nnd members of the Municipal Assemblv,
tlie Board of Public Improvements and the
Health Department depart this morning nt
G Vi on the harbor boat for a trip to the
mouth cf the Illinois P.iver. The partj goes
to Inspect the operations of Doctors Teich
mann nnd Ravold ln their experiments to
determine the etfect of Chicago sewage on
the Mississippi River, and on the St. Louis
vnter supply. The bout will stop In tho
Illinois River, about six miles above Graf
ton, near the old hill from which Mar
quette Is sild to have viewed tho Missis
sippi on his return from the Ohio River.
All the tests will be made on the home
ward trip Doctor Teichmann is desirous
that the Municlpil Assemblv and cltv of
ficials should see e ictlj what Is being
done anil how the work Is conducted.
IN THE COUNTY.
A dramshop licence petition Is being c r
culated bv Willi un OLiughlln of Klrk
vv ood
Colonel R II Brown, one of the oldest
and bent-known citizens of I'dge brook, elied
vesterdav after a short Illness Colonel
Brown was a veteran of the Civil War and
vas one of the pioneer residents of St
Loui Countv. He hail been of unsound
health, mentallv and phv-lcally. for several
'ars He was removed from St. Vincent's
Asvlum to his home some time ago. and
shortly after his condition changed for tho
worse, resisting in Ills death
While driving to M Louis with 11 load
of fruit earlv vc.e.dav morning A V.
Simms. a mir'irvman living in Rltenour. St.
I.ouis Countv, was struck bj a Suburban
car nt the Intersection of tne Suburoan
tricks and the St Ch irles Rock road The
veh'cle was overturned and he was thrown
from his wagon He was carried into
Roper's drug store, where a phvslcl.in ex
amined 1 i Iniuries nnd found that three
rib1! hid bcen frncUred nnd lie had ircelved
several bruises ard cuts on various p irts of
the bodv. Mr. Sim-ns leturned to Ms home
I'l Rltei.our and 't is s.i'd tint lie vvii! be
1 lid up for niMrlv a month
POSSE AFTER WHITTICO.
Sheriff at Pana Notified That the
Fugitive Is Cornel ed.
unpi'rti.ir spj-ci r.
Pain. 111. Aug 13 A posse estimated at
SOU Is busv in the 11 lthwcste'n jart of the
ccuntj tijing to eiptuie the v ouid-be .n
sassln Jimes hittiro On Tuewlav
TA hltl'cu stopped it th" hoi se of a Mr
We! or nnd asked for 1 e up et coffee Web
el 's suppostd to hive letired, allowing
Whlttica to hep himsell lick Ross nnd
John Meichau .ire reported to have spoken
with Whittico Mor.daj moinirg and 10 have
been within tv.entv fret of him. Inn thev
were unarmed Whittico told them he
would not be ta-ien alive.
Tuesihiv mom n-; about " o'clock the
Sheriff was called to the telephone and told
that the posse 1 nd chafed Whittico to
Buffalo Ucputv Sherltf Haines to-night
stntes that the culpik lias been located in
the like district north of the citj and he
claims thej will ".smoke him out." before
morning.
WHARTON MAY BEJNEUGIBLE.
Candidate Said to Uae Forfeited
lib, Citizenship.
Chicago. Aug lj A special to the Record
from Lincoln, Neb. sivs.
"A sensation h is- ben caused bv the dis
covery thit Wharton Barker, Mlddle-of-the-Road
cnndldate for President on the Popu
list ticket, in Ineligible for the office to
which he aspires
"It Is Bald tint while superintending
some Improvements in Russia some jears
ugo, Mr. BarkT was made 'Lorel of St.
Wenchelas' by the C?ar. Before accepting
the title he did not as'c Congress to grant
him the privilege, and he is therefore snid
to be Ineligible because he forfeited his
citizenship by accepting the honor w'lthout
permission of the United States authorities
If this proves true Mr. Barker must step
down and out. Ignatius Donnelly would
succeed him as candidate for President,
some one else being chosen as candidate for
Vice President."
WAGE SCALE NOT SIGNED.
Steel Workers and Manufacturers
Failed to Agree.
Detroit, Mich . Aug. 13 The conference
between representatives of the Amalga
mated AE'ocIat'on of Iron Steel and Tin
Workers and representatives from the great
iron nnd steel manufacturing companies on
the puddlers and finishers' wage scale was
adjourned this afternoon without any agree
ment having been reached.
Another meeting will be held in about
three weeks.
Distribution of Business Among
Illinois Central Assistant
Freight Agents.
MR. KEEPER'S NEW CIRCULAR.
Special Excursions (0 Xoithern
Resorts Were Popular W. P. A.
Rate Sheets Frisco Iease
Appointments Notes.
General Freight Agent W F. Keepers of
the Illinois Central lias Iss ed a eircular
showing the distribution of business among
his assistants In the general freight de
partment of tlie company, as follows;
W. R Biscom, first assistant General
freight agent. Chicago Grain and grain
products; live sfock: traffic interchanged
with connecting lines in North"rn and
Western States, except that assigned to
Mr. Becker. Mr. Peachy and Air. Welts-ell;
traffic Inte rcaanged with Eastern lines, ex
cept that .issjBneil to Mr Becker, Mr.
Peachv nnd Mr. Weitzell. Pacific Coast
traffic: matters pertnining to classific ition.
George W. Recker, assistant general
freight agent, St. Louis. Mo Traffic orig
inating at and passing through St Lou's
and East St Louis, traffic on the St. iouis
division, traffic on the Springfield division.
East St Louis to Litchfield. Inclusive: traf
fic interch inged with northern eountles at
junctiors within the above ttrrltorj ; also
traffic between the South nnd stations on
the St Louis division, including Inter
change with connecting lines within such
territory.
J. R Peachv, assistant general freight
aKent. Chicago TrafPc between all points
south of tlie Ohio River, except as assigned
to Mi. Becker and Mr. Weitzell; trail. c be
tween all points north and all points in
Arkanras. Texas. Louisiana. Mexico. New
Mexico and Arizona, exe ept as es ignd to
Mr. Bicker and Mr. Weitzell; lumber traffic,
excepting that ln territory assigned to Mr.
Becker.
R. Kirkland, assistant general freight
agent. Chicago Trnllic between stations 011
Northern and Western lines, of Illinois Cen
tral, except as otherwise assigned, ice anj
salt tialfic.
J S Weitzell. assistant general freight
agent. Omaha. Neb Traffic interchanged
with connecting lines at Omaha, Council
Bluffs and Sioax City, and tupeivision of
Missouri River traffic. Kansas City to Sioux
Citj. inclusive, and territor.v west to I'tali.
Correspondence snouid be addressed accord
ing!. I,Ki: MIOIIE.
home Figures From the liciiinrl.ulile?
lie-poi Im of This Ho.-hI.
It may be true enough that Like Snore?
finances attract little or no attention now
that the stock Is nearlv all he-.d bv the
New 'iork Central, its, per cent dividends
guaranteed, ami the -tocK, of course, prac
tically out of the mirkit Neveitheless,
the Lake Shore represents a tjpe of rail
road of which the number is very small
Indeed, and its operations will aivvnvs be
closed watcned. 'Ihe road has deve.oped
on unique lines, charging all lis improve
ments to earnings, anil maintaining its
capitalizations uncfarged for manj vears
pa-t. Lake Shore h.is been one ot those
properties to see a wonderful growth ln
business, and to experience to the full the
e fleets of the incessant contraction in
rates.
'the company reports give many interest
ing statistical tables. The statistic b gin
with 1S70. following the jenr of consol.uu
tion. Tne rate then was 1 CM cents per ton
per mile, out of which came a profit of
.512 cent, it having cost 9S1 cent to carry
the ton one mile, or 62 per cent of the
receipts
Ten jears later brings a period of quite
heavj traffics, ISS. to a ear when the
road maele a record of gross an 1 net earn
ings which held good up to lb87, and to
n ear when operations, wero carried on
eniite protitnbl. The freight rate, however,
hud got down to one-half Its former aver
age, out cost was reduced still more, and
toimed onlv aS per cent of the gross rate.
Another uecaoe and ISM) show.s a develop
ment less sai'sfactory In character, namely,
a further reduction in the rate to .6J cent.
1,'it a itte to .4"S cent, or to 7.5 pr cent
in the expense per ton per ml'.e. Wnile
this was at tnat tim" a somcwhai excep
tional condition, the cost having been
higher, with the exception of 18a9. tnan for
nearlv " dozen jears. it was one which
continued for awhile, and which had to
be met by increasing trainloads; thus
lorcing down expenses to the minimum.
He-ulis tor the late jear show verj cle.irl
hfivv much has been accomplished In this
direction For that period tU" company
cured bv far the largest volume of uathe
in its hlstorj. rnd at th? lowest recorded
rate, which fell for the flrt-t lime below
', cent per ton pr mile. The cost was
reduced 10 the low figure of iZ" cent, and
tlie profit remaining was .131 cnt not 30
per cent of the profit of twenty jenrs ago.
but .still ns much as was realized in Is'",
mere than Wfi ielded, and within the
unrest fraction of the avernge during the
trunk l'ne war in the eighties.
Needless to say ttut such a, marvelous
record could onl come throush a marvel
ouslv Increased trainload Th" Utter for
IK') Is 427 ton0, tnree times the overage
for 1S70. 17r Ions, or 70 per cent lucre ise
over lSrt). and lj'l tonb or 00 per cent in
crease ovei 1S50
swrA kk 'DiM:ni."
Fnnrtc-pn Cantl Cart Oroorcil for
TriiiiNCoiitlnentnl Ser'vli-e.
Topeki, K.i Aug 1" The Sante Fe has
place d an order with the Barnev iSc Smlt.i
Companv of Do ton. O. for six oinlng cars.
This order wll be supple me' ted in tlie neir
future with an order of eight more dining
ears of the same de-ign and finish. The
ears -v. ill be completed ard delivered to the
Smite Fe bv October 1.
Thev will be used in the limited service
between Chicago ind San Funcisco. These
older'' call for cars that will, when com
pleted, be among the finest ever turned
out. Fach ear v. ill cost over 515,000, or
.il out $2TOiJ0 for the fourteen The cars
are to be 70 feet long aid will ride on the
new Iniprove-d six wheel trucks. Th
v.lll al- have steel platforms and wide ves
tibules and will be Iitte-1 with both electric
and gns lights ana cooled with electric fan
i:oijis 'io tiii: aoutii.
Speelnl Ilxcurnlon Bute Proved Io lie
'r I'aiinlni.
The exodus from St. LojIs .and vlcimtv
to the summer re-sorts vvns unprecedented
vesterdav. It was one of the special ex
clusion dates when round trip tickets good
until .September :.U were s0(i for one faie
plus $1 The Chicago and Alton. Illinois
Cei trai. Wabash rnd Burlington all did a
rushing business, the Alton alone cllin;
2H tickets.
If the pouplarlty of there e:.cursions con
tinue thev may be set elov n as a llxttir
for next jear. even though tliej have some
what demoralize 1 local rates thus far. This
however, can be prevented by the exercisa
of a little cool judgment.
lESTr:ilN IIATK BURETS.
W. I. . Linn -Mnj Compile The 111
Semlnnnunll) In the Fee tare.
A movement is on foot in the Western
Pissenger Association to have rate sheets
compiled semiannually instead of quarterl.
The object lb to steady passenger rates,
rake up less time of the rate clerks, and
save the cost of the Issuance of the sheet.
This movement, however, will not affect the
compensation of the compilers, the idea be
ing that the compilers' salaries will remain
unchanged
I.e-nneil to the Frlneo.
RErtJRMC SPECIAL
Oklahoma Cltv. Ok . Aug. If. The Okla
homa. Cltv Terminal Railway connection
with the St. Louis and San Francisco Rail
read, which Is being built to give the Frhvo
an uptown depot and station, has been
leased for a term of thirty years to tne
Frisco. The track laying will be completed
this week on the three miles of road.
naiTnlo Getting Rcnel.
To-morrow morning there will be a meet
ing of the Entertainment Committee of the
General Passenger Agents' Assoc ation at
Buffalo, for the purpose of making arrange
ments for the coming meeting, which is to
be held ln October ln that city.
At the last meeting of'the American As
sociation of General Passenscr Agents
Buffalo was choscji as the placo of meet
ing for the next convention. Buffalo ob-
. for Bnfants and Children.
Castoria is a harmless substitute for Castor Oil, Pare
goric, Drops and Soothing Sjrups. It is Pleasant. It
contains neither Opium, Morphine nor other Jfarcotic
.substance. It destroys Worms and allays Fevcri.shness.
It cures Diarrhoea and Wind Colic. It relieves Teeth
ing Troubles and cures Constipation. It regulates tho
Stomach and Bowels, giving healthy and natural falecp.
Tho Children's Panacea The Mother's Friend.
The Kind You Have Always Bought
Bears the
tnincil this meeting because she v. mled a
chance to impres, these agents with the
import ince of her comln? Pan-American
Kxposition. It is expected, therefore, that
this meeting will be one rf education.
Chicago Alleced S-are".
Chicago papers are disturbed by a report
that tlie- Missouri Pacific and other linis
are going to reduce tile time between Den
ver and bt. Louis so as to turn much trans
continental and Western travel through
the latter cltv which now goe3 by the- wav
of Chicago Thev think, s.avs the Rillvvay
Age, that fister time, added to what thv
call discrimination against Chicago, caused
bv charging excess 1 ire on fast trains
fiom this citj onlv. N liable to resii't ln
the benelit of St. Ixiuls nnd injury to Chi
cago. Hence thev call for the aliolltlon of
tlie excss-fare plan. The railroad' Inter
ested e laim that tney may be- trusted to
see thRt their business Is not neeJIessly
sacrificed The roads which maintain the
limited trains appear to be satisfied with
the result. It may be a eiue-tlon v.hethe
the establishment of similar attractions on
the lines from St. LouH eastward would
not increase the through travel bj that
citj. Taster time betwenn Chicago and
St. Louis waukl probably help that route
providing the Chicago lines ilid not main
tain the status bv shortening up. also
JInnv eorslderations beside time go to the
building up of great routes of travel, and
revolutions in these routes are not e-.isiiv
effected Neither Chicago nor St. Louis
ha3 reason to complain of lack of transpor
tation facilities bv any of the great lines,
Kastcrn or Western, which serve them.
In n Dcnil Hush.
Spokane, Wash , Aug. J'..-CIarencc ilc
Cualg. a Montreal capitalist, announces
that he is rcadj to build a railway from
Re-public. Wash . to Grand Forks, British
Columbia. He said:
"We cannot brook anv- delav. There has
been talk b other people of building a
line. If thy intend to bui'd thev must
t.irt in a great hurry or be too Iaie. tte
have already taken initial steps."
"No White Pn-4 Opposition.
Victoria. British Columbia, Aug. 13 The
appl'catlon of the Like Rcnnett Railwav
Ccmpanj for a charter to build an opposi
tion rnilwav to the White Pass Road from
Dvea to Bennett was defeated in the Rail
way Committee of the Legislature to-day.
the chairman casting the deciding vote on
a tie.
nnrlinprtnn Appointment.
William Fitzgerald, Jr., has been appo nt
ed general agent of the Burlington at Han
nibal. 3Io. vice Howard Eiting. promoted.
C. L Beech has been appointed Texas
freight ard passenger agent of the Buriln?
ton at Dallas, vice William Fitzgerald, Jr.,
promoted.
PeroonnI and Current Note.
S. G. Warner, general passenger agent
of the Kansns City Southern, was ln the
city jesterday.
R S. McVeigh, traveling freight agent
of the U. & O. 6.-W. at Sejmour. Ind., was
here jesterday.
C. F. Parker general agent of the Illi
nois Central, will leave to-dny for a trip
North He takes his familj with him.
Lionel Palmer has b'en appointed chief
clerk, under Chairman George Cale of the
Southwestern Freight Committee.
U. S. Pawkett. commercial agent of the
International and Great Northern at Cincin
nati, was a visitor here yesterday.
The Executive Committee of the West
ern Passenger Association will meet In Chi
cago to-day and tackle an interesting dock
et. r. E. Guedrj-. district passenger ngent
of the Mobile and Ohio at New Orleans,
was here jestenlay frGm Chicago, and left
last night for home.
Ed Pope, Western pas-enger agent of
the Chesapeake and Ohio, stnrtled Broad
way vesterday by flitting through the sun
shine In a Cuban shirt waist and a pair
of Filipino pants, cut F. F. V. Llmifd.
The Second Battalion of the First In-fantrj-.
which has been doing service ln
Cuba, left Jersej Citj Tuesdaj-, at 7 39 p.
m. over the Pennsj lvanla for St. Louis.
There are nineteen cars in the train. They
will leave here over the Missouri Pacific for
Fort Leavenworth. Ids.
James N. Hill, son of i. J. Hill of the
Great Northern raad. is president of tho
Dakota and Great Northern Railwaj- Com
pany, recently incorporated under the laws
11! North Dakota, with a capital stock of
$.'.00,000. Associated with Mr. Hill are
Frank Ward, general superintendent of the
Great Northern, and William D. Glover, a
wealthy St. PjuI capitalist. It is the pur
pose of tlie Incorporators to build a line
from a po'nt near Lakota, on the main line
of the Great Northern, extending northerlj
through several productive counties to a
point near the international boundarj- line.
"Tlie Tijing Scotchman" Is a fast railwaj-
train tunning between London and
Ah rdecn, which is the first in Europe to
introduce the American stjle of railway
coaches. This train Is self-contained, with
commutnc ition throughout its entire length
and a dining car attached Travers'ng the
Fnited Kingdom, almost from end to end. It
will d3 the journej- from London to Aber
deen, or from Abereleen to London, In just
over the twelve hours. As tt-e illslnnce cov
ered is 3.3 miles, th.-t works out to about
feprtv-live miles an hour, a considerable
speed, quite apart from tlie length of timi
taat It is mainta'ned.
George II. Walker, of and for Texas,
special agent of the B. k O. S-W.. nrrlved
here vesierdaj on .1 "Roj.il Blue" train.
He wore a rojal purple and white shirt
waist that would hive don credit to ,1
court jtster. It elevated the mcicurj- ev
ervvhere lie went, and caused him to be
ejected from a dining car and the Termi
nal Hotel Cafe. He tred to make a traJe
with Georse Warfel, hut did not succeed.
Last night Brainerd Allison and S. G. War
ner took him out to Dclrrnr Garden and
exhibited him on the Midway. Mr. Walk
ers affliction N due to a tr p ta New- York.
John Uogermf.n will doctor him when lie
gets bark to Dal'a".
STEEL BARGeIiNE ASSURED.
Pri-shli'iil :unl Secretary Swcteed in
Their New Orleans .Mission.
A special d spntch from New Orleans. La.,
lo The Itepub'ic last night states that
Henrj S' Potter or th's e itj and W. A.
Thcmpsci drparted tor St Louis, after
making the final arrJiiements for the op
erations of tlie s.t. Louis Steel Barge Com
ranv. which will begin operations in Sep
tember Mr. Potter is president of the company
and Mr, Tho.njsun Is the s'luerintendent.
The deta'Is of the eompnnj-'s organization,
which have been in abevanc" during the
absence of the gentlemen, will be settled
in a few elajs.
The first shipment by the companj- will
be on two steel baries In tow of 11 steamer,
and will arrive in New Orleans about the
last of Sept'mber. The trip elov.nstream
v.i'.l be made In four and a half djs, and
the return trip in seven dajs.
President Potter and his assoc'atc made
arrangements for the shipment of cotton,
lumber and molasses to St. Louis. Eventu
ally the companj- will have warehouses at
New Orleans, and also storehouses.
RENEW OXYENlN AIR.
2vew I'l-onerty of Bioxide of Sodium
Discovered.
New York. Aug. 13 A dispatch to the
Times frcm Paris sajs:
Illghlv- interesting demonstrations of the
properties of bioxide of sodium are being
given before the French Academj- of Sci
ence. Bioxide of sodium Is found to pos
sess the property of renewing the oxjgen In
the air that has been breathed, and ln ab
sorbing carbonic ac'd gas given off.
Thus, with an apparatus containing the
sodium, shown by Desgrej' and Balthouard
at the Academy, a diver can remain under
water and walk about without having the
air renewed by the pumping apparatus at
present cmploj-ed.
Moreov er. bj- means of the new apparatus
miners will be able to Denetrate into uni
C&aJjfflcuc&M
Signature of
sonous gases ainl fcul air. and firemen into
smoke, without fear of asphjxiatlon. It
will also render practicable submarine
boats.
Ample proofs of all that is claimed for
it were given at the Acaelcmv- Two met'
put on diving dresser from which all air
was excluded and remaineel closed in for
two heiurs. Afterwjrel the same men re
mained under water in the Seine during
half an hour. The experiments are crea
ting tlie greatest interest in scientific cfr
e'es. FOUR HEAT PROSTRATIONS.
Greatest Number Yet Treated in
One Day This Summer.
Four cases of heat prostration were re
ceived at the Citj Hospital jesterday. They
were rred Garlind. CI jears old. a tinner,
living at No. 2S.I5 Olive street: A. G. .Moss
ier. 31 vears old. a clerk, living at No. S7"
Marine avenue: Charles Busier. 2S j-ears eild,
.1 teamster, living at No. -5CMU Minnesota
avenue, and William Burke of Terrc Haute.
Ind. who was overcome bj- the heat as he
left the train at Union Station.
It was the first day this summT that
more than one case of heat prostration has
been received nt the Citj- Hospital. The elav
was the most oppressive of the summer, and
there was a great deal of humldltj In the
atmosphere. L'nlcss there Is a change m
the weather conditions. Doe tor Nletert pre
dicts that a large number of patients will be
treateil for heat prostration at the hospital
ln the next few dajs
Yesterdaj- the mercurj- in he thermome
ter in the eleimc of the Federal building
readied the 92 mark, which is one degree
higher than it went on Tueselaj-.
In the streets of the business district tho
thermometers rceisterevl from 55 to 99 de
grees. Tlie thunder storm anil light rain
at nlnht gave some relief. Doctor Hjatt
predicts showers for to-daj-. He saj-s that
the weather will be unsettled with a possl-billtj-
of rain and falling temperature.
Struck hy n Lite Wire.
A Bell Telephone Companj- wire becamn
charged with clectricitv In the course of
tho storm last night and fell ln the allev
between Tenth and Eleventh streets an 1
O'Fallon street and Cass avenue. Henrj
Smith of No. 1407 North Tenth street was
struck on the shoulder by tho wire and
sllghtlj- Injured.
HIS SAD HOME-COMING.
T. K. Stanley Brought Buck From
Asylum in 2s"ew York.
T. K. Stanlej-. 40 years old. married and
living at No. o51 Shenandoah avenue, wa.s
sent to the Citj- Hospital last night for
safe keeping bv order of Health Commis
sioner Starkloff.
Yesterdaj- Doctor Jordan, the Dispensarv
physician, received a telesram from D-ive
Heller from Adrian, Mich., announcing
that he would bring an Insane man to the
citj- on the 7.13 train la3t night, and asking
that an ambulance be sent to Union Sta
tion to meet him.
Stanley became Insane while in New
York Cltv- last November and has bee-i
confined in the River Cres Asylum, on Long
Island up to last Tuesdaj. when he was
released by order of his relatives, who de
sired to have him nearer home.
Stanley seemed to realize his position and
fald that he had had a pretty good time
during his stay at the Long Island Asylum,
where, he said, he was a "trusty."
He was the buyer and manager of tho
upholstering department of a large local
dry goods store for the last fifteen jears
and went to New York last September to
purchase a stock of goods.
BOX FACTORY BURNED.
Two Alarms Turned In and ?4.3O0
Damage Wrought.
Fires of unknown origin last night dam
aged the building and contents of the Bre
men box factory at Noa 3110-13 North
Ninth street, to the extent of SI.50O.
Tho fire was discovered about 7 o'clock
by Herman Kurth of No. 311S North Elev
enth street. Two alarms were turneel i
and the firemen fojght the blaze for nearlj
nn hour before It could be gotten under
control. The building, a three-story brick
structure. Is owned bj- C. II. L. Becker,
who has offices ln room No. 712. Holland
building. He estimated tho damage to hi9
propertv- at $1,000.
The Bremen box factory Is owned bj
August RIesner of No. 3906 Vest avenue.
He Is of the opinion that his loss will not
exceed $S,&). The stock and building arc
fullj- Insured.
disastrous'hailstqrm.
Forty Thousand Acres of Grain De
stroyed in North Dakota.
St. Thomas. N. Dak , Aug. 15. A severe
hailstorm last night destrojed 40 000 acrs
of the finest grain grown In North Dakota,
this j ear. even that cut and In shock being
destrojed.
Manj- of the h?ll stones were from three
to four inches in diameter.
Scrofula
THE OFFSPRING
OF HEREDITARY
BLOOD TAINT.
Scrofula is but a modified form of Blood
Poison antl Consumption. The parent
who is. tainted bv cither will see in the
child the same disease
manifesting itself in
the form of swollen
glands of the neck and
throat, catarrh, vveak
eves, offensive sores 1
and abscesses antl of
tentimes white swell
ing sure signs of'!
Scrofula. There mayf
be no external siyns for
along time, for the disease develops slowly
ii; some cases, but the poison is in the
b'ood and v.ill breakout at the first favor
able opportunity. S. S. S. cures this wast
ing, destructive disease by first purifying
and building tip the blood and stimulating
and invigorating the whole system.
J. M. Seals. 1 15 Public Sqnarc. Nashville.Teun .
says : Ten j ears a;o my daughter fell and cut
her forehead. Trom th wound the glands on
the side of her face Icame swollen and bursted.
home of the be?t doctors here and elsewhere
attended hi"r without any benefit. We decided
to try S. S. S , and a few bottles cured her en-tirelj-."
fe 0to makes new and pure
r Mood to nourish and
fekk strengthen the body,
A 9 9 and is a positive and
0 "2r safe cure for Scrofula.
It overcomes all forms of blood poison,
whether inherited or acquired, and no
remedy so thoroughly and effectively
cleanses the blood. If you have any
blood trouble, or your child has inherited
some blood taint, take S. S. S. and get
the blood in good condition and prevent
the disease doing further damage.
Send for our free book and write our
physicians about your case. We make no
charge -whatever for jnedica! advice.
THE SWIFT SPECIFIC CO.. ATLANTA. GJL
w&ms
r i--r
J
sV--
xml | txt | http://chroniclingamerica.loc.gov/lccn/sn84020274/1900-08-16/ed-1/seq-5/ocr/ | CC-MAIN-2015-11 | refinedweb | 8,940 | 74.49 |
Object oriented encapsulation case
- Encapsulation is a major feature of object-oriented programming
- The first step of object-oriented programming -- encapsulating properties and methods into an abstract class
- Objects are created using classes, and then objects call methods
- The details of the object are encapsulated inside the class
Tip: inside the method of an object, you can directly access the properties of the object.
# case class Person: def __init__(self, name, weight): # self. Attribute = formal parameter self.name = name self.weight = weight def __str__(self): return "My name is %s Weight is %.2f" %(self.name, self.weight) def run(self): print("%s Love running, exercise" % self.name) self.weight -= 0.5 def eat(self): print("%s It's food. Lose weight after this meal" %self.name) self.weight += 1 xiaoming = Person("Xiao Ming", 75.0) xiaoming.run() xiaoming.eat() print(xiaoming)
Xiaoming loves running and exercises
Xiaoming is a foodie. He will lose weight after eating this meal
My name is Xiaoming. My weight is 75.50
Tips:
- Within the method of an object, you can directly access the properties of the object
- The attributes of multiple objects created by the same class do not interfere with each other.
xiaomei = Person("Xiaomei", 45.0) xiaomei.run() xiaomei.eat() print(xiaomei) print(xiaoming)
Xiaomei loves running and exercises
Xiaomei is a foodie. She will lose weight after eating this meal
My name is Xiaomei. My weight is 45.50
My name is Xiaoming. My weight is 75.50
# Cases, used classes are usually developed first # Furniture category class HouseItem: def __init__(self, name, area): self.name = name self.area = area def __str__(self): return "[%s]Land occupation %.2f" %(self.name, self.area) class House: def __init__(self, house_type, area): self.house_type = house_type self.area = area # Residual area self.free_area = area # Furniture name list self.item_list = [] def __str__(self): #python can automatically connect the code inside a pair of brackets together return ("Apartment layout: %s \n Total area:%.2f \n [Surplus:%.2f]\n Furniture:%s" % (self.house_type, self.area, self.free_area, self.item_list)) def add_item(self, item): print("To add %s" % item) # 1. Judge furniture area if item.area > self.free_area: print("{} The area of is too large to add".format(item.name)) return # 2. Add furniture name to furniture list self.item_list.append(item.name) # 3. Calculate the remaining area self.free_area -= item.area # 1. Create furniture bed = HouseItem("Simmons", 100) chest = HouseItem("Wardrobe", 2) table = HouseItem("table", 1.5) print(bed) print(chest) print(table) # 2. Create a house object my_home = House("two bedrooms", 60) my_home.add_item(bed) my_home.add_item(chest) my_home.add_item(table) print(my_home)
[Simmons] 100.00
[wardrobe] 2.00
[dining table] 1.50
To add [Simmons] cover an area of 100.00
The area of Simmons is too large to add
To add [wardrobe] floor space 2.00
To add a 1.50 floor area
House type: two rooms and one hall
Total area: 60.00
[remaining: 56.50]
Furniture: [wardrobe, dining table]
#Case 2 class Gun: def __init__(self, model): # 1. Grab model self.model = model #2. Number of bullets self.bullet_count = 0 def add_bullet(self, count): self.bullet_count += count def shoot(self): # 1. Judge the number of bullets if self.bullet_count <= 0: print("{}No more bullets...".format(self.model)) return #2. Firing bullets self.bullet_count -= 1 #3. Prompt launch information print("{} Protrusion...{}" .format(self.model, self.bullet_count)) class Soldier: def __init__(self, name): #1. name self.name = name #2. Guns - recruits don't have guns # When defining an attribute, if you don't know what value to assign, use None instead self.gun = None def fire(self): #1. Judge whether soldiers have guns #if self.gun == None: # When using None for judgment, you need to use is for specification instead of = =, for judgment. if self.gun is None: print("{}No guns....".format(self.name)) return #2. Shout slogans print("Rush!...{}".format(self.name)) #3. Fill the gun with bullets self.gun.add_bullet(50) #4. Let the gun shoot self.gun.shoot() # The properties of an object that can be created by another class. # 1. Create gun object ak47 = Gun("AK47") #2. Create Xu Sanduo xusanduo = Soldier("Xu sando") xusanduo.gun = ak47 xusanduo.fire() print(xusanduo.gun)
Rush... Xu sando
AK47 protrusion Forty-nine
<main.Gun object at 0x030D0E30> | https://programmer.group/008-object-oriented-encapsulation-cases.html | CC-MAIN-2020-16 | refinedweb | 713 | 55.2 |
You define a default namespace in an element of an XML document with an attribute of the form
xmlns="URI". In the following example, a document has a default namespace bound to the URI:
If the element does not have a prefix in its name, a default namespace applies to the element and to any descendant of that
element where it is defined. A colon separates a prefix from the rest of the element name. For example, <x/> does not have
a prefix, while <p:x/> has the prefix p. You define a namespace that is bound to a prefix with an attribute of the form
xmlns:prefix="URI". In the following example, a document binds the prefix p to the same URI as the previous example:
Default namespaces are never applied to attributes. Unless an attribute has a prefix, an attribute is always bound to the NULL namespace URI. In the following example, the root and child elements have the iAnywhere1 namespace while the x attribute has the NULL namespace URI and the y attribute has the iAnywhere2 namespace:
The namespaces defined in the root element of the document are applied in the query when you pass an XML document as the namespace-declaration argument of an OPENXML query. All parts of the document after the root element are ignored. In the following example, p1 is bound to iAnywhere1 in the document and bound to p2 in the namespace-declaration argument, and the query is able to use the prefix p2:
When matching an element, you must correctly specify the URI that a prefix is bound to. In the example above, the x name in the xpath query matches the x element in the document because they both have the iAnywhere1 namespace.
When matching an element, you must correctly specify the URI that a prefix is bound to. In the example above, the x name in the xpath query matches the x element in the document because they both have the iAnywhere1 namespace. The prefix of the xpath element x refers to the namespace iAnywhere1 defined within the namespace-declaration that matches the namespace defined for the x element within the xml-data.
Do not use a default namespace in the namespace-declaration of the OPENXML operator. Use a wildcard query of the form /*:x, which matches an x element bound to any URI including the NULL namespace, or bind the URI you want to a specific prefix and use that in the query, | http://dcx.sap.com/sa160/en/dbusage/ug-sqlxml-s-2907776.html | CC-MAIN-2017-04 | refinedweb | 415 | 54.15 |
create an MX record under your mycompany.com
So it would be mail.mycompany.com and you would use that Public IP associated with the MX record to be NAT'ed to your CAS server internally.
You will need to also setup your reverse IP for your MX record as well. You will need to contact your ISP for them to setup your external IP to your MX record (PTR record).
I personally like to simplify the namespace and keep internal the same as external. To accomplish this you need to setup split dns (if you haven't already). Once you have split dns setup change your internal URL to match your external ones.
I have created a HowTo for this exact procedure.
Will.
Also is it mandatory that I use nat on the cas server; because I purchase 5 static ip addresses? Or will this be safer way to go in reference to security. Also what if I want to use my Exchange Edge Server in the future. Where does the static ip address goes? For example Edge Server will be in the DMZ. Do it need to have both 2 nics one for internal ip address and another for the public ip address?
You would create an MX record under your mycompany.com
So it would be mail.mycompany.com and you would use that Public IP associated with the MX record to be NAT'ed to your CAS server internally.
Do you mean setup the mx record & A record on my godaddy acct, like this.
Do you mean mail.mycompany.com will be my A record, which point to my public ip address
And add MX record will be @ which will point to mail.mycompany.com
Can you clarify if this is correct
Thanks
Administration of Active Directory does not have to be hard. Too often what should be a simple task is made more difficult than it needs to be.The solution? Hyena from SystemTools Software. With ease-of-use as well as powerful importing and bulk updating capabilities.
If that be true, what is the correct way to do it.
Is this the correct name syntax to create the mx record on the internal network?
Thanks
You should already have an A (host) record for mycompany.com and you then just need to create an MX record for mail.mycomapny.com with the external IP you will be using. You then need to contact your ISP and ask them to setup a reverse (PTR) record for mail.mycompany.com.
You would NAT that IP to your internal CAS server. You can lock this down via port 25 only. If you plan on putting in an Edge server in your DNZ which would be better, you then point mail.mycompany.com to the Edge server and create an Edge Subscription to your internal Exchange environment (CAS server) and mail will be forwarded from the Edge server to internal CAS.
Will.
Experts Exchange Solution brought to you by
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial
What I did so far; just now was setup split dns on my internal AD Domain.
Added a primary zone called mycompany.com
Now are you speaking that I add the mx & A record to the new primary zone that I just setup?
Or was you speaking about about the public dns mycompany.com, because the mx & a record was previously created on the public domain.
What I did so far; just now setup split dns on my internal AD Domain.
That is for Exchange specifically. If you have other external subdomains for this domain like a website then you need to add all of those to the internal zone as well.
My HowTo only covers the Exchange entries you need to configure. You will still need to add all of your other websites etc.
Will. | https://www.experts-exchange.com/questions/28820459/Exchange-2010-DNS-MX-Configuration.html | CC-MAIN-2018-30 | refinedweb | 667 | 74.9 |
This article has been dead for over three months: Start a new discussion instead
Reputation Points: 10 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
0
vector<string> guess(4); cout << "Input a Guess(e.g red blue green yellow): "; cin >> guess[0] >> guess[1] >> guess[2] >> guess[3];
this is part of my code to let the user input 4 different guesses, is there anyway I can limit the input by 4 so that if the user inputs more or less than 4 it would be invalid?
the input are basically strings
Reputation Points: 447 [?]
Q&As Helped to Solve: 410 [?]
Skill Endorsements: 7 [?]
•Team Colleague
• Featured
0
Why don't you use a counter and increment it when you get valid answers?
When it hits 4, drop out of the loop.
You could also just check to see if any of your variables is null (less than 4 condition).
If there are more than 4, could you ignore any additional input?
Reputation Points: 10 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
0
sorry, as I'm still quite new to C++, could you provide an example?
thanks alot
Reputation Points: 447 [?]
Q&As Helped to Solve: 410 [?]
Skill Endorsements: 7 [?]
•Team Colleague
• Featured
0
Something like this:
#include <iostream> #include <istream> #include <vector> using namespace std; bool isValid(string str) { /* do some type of check to make sure str is valid ...like comparing it to a know color list */ return true; } int main(void) { vector<string> vecGuess; char strTemp[128] = {0}; for(int i =0; i < 4; i++) { cout << "guess #" << (i+1); cin >> strTemp; if(!isValid(strTemp)) { cout << "not valid" << endl; i--; continue; } vecGuess.push_back(strTemp); } return 0; }
You will need to validate what the user enters in the isValid() function.
You
Related Articles | http://www.daniweb.com/software-development/cpp/threads/417012/help-with-limiting-input-c | CC-MAIN-2013-48 | refinedweb | 299 | 85.18 |
.7: A Complete Scala Application
About This Page
Questions Answered: How do I write and store an entire Scala program? Where does a Scala application’s execution begin? How can I read input from the user’s keyboard? Now that I’ve created a conceptual model of a game world, how can I define a GUI that displays the world?
Topics:
App objects. Keyboard input with
readLine. The basics
of graphical user interfaces with
o1.View.
What Will I Do? Mostly program, guided by the text.
Rough Estimate of Workload:? Over an hour.
Points Available: A60.
Related Projects: Ave (which we’ll create from scratch), Odds, IntroApps (new), FlappyBug.
Introduction
You have created objects. You have called their methods in the REPL, an environment that is well suited for experimentation.
However, the commands that you’ve entered in the REPL don’t form a unified whole that is stored for later use, that can be lauched again at will, that can be readily edited, and that is easily copied for someone else to run. To achieve these things, you’ll need to store your application in a file.
Let’s take a stab at doing just that.
A Traditional Program
Already the ancient Romans started the study of each new programming language or software technology by using it to create a so-called “Hello, World” program. Such a program simply displays a message and does nothing else.
Let’s create and store a program that contains a couple of Scala commands and that we can launch as may times as we like. These print commands will serve:
println("Ave, Munde!") println("Well, ave at thee, too!")
Create a new Eclipse project for this experiment:
- Make sure (with the buttons in the top-right corner) that you are in Eclipse’s Scala perspective and not, say, the Java perspective.
-
- Name the project Ave, for instance.
- Tick Create separate folders for sources and class files, if it’s not already ticked.
- Hit Finish. The Ave project shows up in Eclipse’s Package Explorer.
Create a new Scala code file:
- Right-click the
srcfolder within the Ave project and select . (In case that option isn’t available, select .)
- Find the File name field and enter
Ave.scala
- Hit Finish. The file shows up within the project and also opens up in Eclipse’s editor.
Write the program:
- Enter the two
printlncommands in the empty file you just created. Save the file.
- Witness: Eclipse lights up your code like it’s Christmas. The Problems tab elaborates: Errors: expected class or object definition. What’s wrong?
The underlying problem is that we haven’t set up our application as a proper object-oriented program. When we write a Scala application, we need to define a special “app object” that provides a starting point for program execution. This object can then activate (call) other program components as needed.
The GoodStuff project has an app object named
GoodStuff, which you’ve activated before
to run the application. The Pong project contains an app object named
PongApp. Our Ave
application, however, lacks such an object.
Writing an App Object
Here’s a template for an app object:
object MyOwnApplication extends App { // This is an app object. // The commands you enter here will be executed when the app runs. }
Appdata type. The object now represents our application as a whole and enables us to run the program.
At this stage of O1, feel free to think of
extends App as simply a phrase that marks
an app object. In later chapters (e.g., 7.2) it will turn out that the
extends keyword
has many other uses as well.
A Tiny But Complete Scala Program
A larger program may consist of dozens, hundreds, or even more classes and singleton objects. However, for our tiny greeting program, we need just a single app object where we place the print commands.
Edit
Ave.scala to contain the following:
object Ave extends App { println("Ave, Munde!") println("Well, ave at thee, too!") }
Now you can run the program by selecting first
Ave.scala, then in the menu. Try it. Notice that the output appears in
Eclipse’s Console tab, which is down by the REPL.
(That was also how you started GoodStuff and Pong back in Chapter 1.2. For alternative ways to select and run an app in Eclipse, see that chapter.)
You have now written a complete Scala application. Submit it via this form.
A+ presents the exercise submission form here.
Reading Keyboard Input
The Ave app produces the same output each time it’s run, and the user has no way to affect what the program does as it runs. In constrast, most meaningful applications take in some sort of input (syöte) from their users, either directly or indirectly. Here are some examples:
- The program has a graphical user interface. The user can click on it to indicate what they wish the program to do.
- The program operates on data that it loads from files stored on the computer’s hard drive.
- The program interacts with the user in the text console. It pauses to wait for the user to enter lines of text as input.
We’ll get started with graphical user interfaces later in this chapter. Working with files will be discussed in Chapter 12.2. But first, let’s explore the third form of user interaction.
A text-based app in the console
Let’s write a program that works in Eclipse’s Console tab as shown below.
Halt! Who is it? Pechkin the Postmaster Ave, Pechkin the Postmaster!
Enter.
The
readLine function
The library function
readLine receives, or “reads”, a single line of user input.
Calling
readLine suspends the program until the input has been received. The function
returns the input as a
String.
The interactive program described above can be implemented with
readLine:
import scala.io.StdIn._ object GreetingApp extends App { println("Halt! Who is it?") val name = readLine() println("Ave, " + name + "!") }
readLineis to
importit first.
StdInis short for “standard input”, which here essentially means input that the user enters through a text console.
Type in (or copy–paste) the above program in Eclipse. You can either edit the
Ave
object or create a new file for this second app.
Run the program. See what it prints in the console and answer the program’s request for input. (N.B. Due to Scala IDE’s limitations, you may need to click the text console before you can use the keyboard to enter input.)
It’s also good to know that you can pass a string parameter to
readLine. If you do,
the function first prints the string as a prompt and then reads the user’s input off the
same line. Here’s an example:
val name = readLine("Halt! Who is it? ") println("Ave, " + name + "!")
This produces interactions like the one below.
Halt! Who is it? Pechkin the Postmaster Ave, Pechkin the Postmaster!
readLine in Scala IDE’s REPL
Scala IDE’s built-in REPL is not yet the finished article. It has
some shortcomings, one of which is that reading input doesn’t work
as one might hope. For instance, entering a
readLine command in the
REPL produces an error message.
Assignment: Odds (Part 5 of 9)
Let’s write a small test program for the Odds project from Chapters 2.4 and 2.5.
Our program will use keyboard input to create
Odds objects, call the objects’
methods, and print a report of the return values.
Task description
Two of the files in project Odds are relevant to this assignment.
Odds.scala you already
know; it defines class
Odds. Now take a look at
OddsTest1.scala. It defines an app
object, but the definition is incomplete and the app doesn’t actually use class
Odds at
all.
Flesh out the app object so that it produces an output that exactly matches the following example. (Of course, the user might well enter numbers other than the ones shown.)
Please enter the odds of an event as two integers on separate lines. For instance, to enter the odds 5/1 (one in six chance of happening), write 5 and 1 on separate lines. 7 2 The odds you entered are: In fractional format: 7/2 In decimal format: 4.5 Event probability: 0.2222222222222222 Reverse odds: 2/7 Odds of happening twice: 77/4 Please enter the size of a bet: 50.0 If successful, the bettor would claim 225.0 Please enter the odds of a second event as two integers on separate lines. 10 1 The odds of both events happening are: 97/2 The odds of one or both happening are: 70/29
Instructions and hints
- You can start by running
OddsTest1as given. It reads in some input but doesn’t produce the correct output.
- In
OddsTest1, add the commands to create
Oddsobjects and call their methods.
- Do not edit class
Oddsor copy any of it into
OddsTest1.scala. Use the class as it is.
- It’s important that you sequence the commands right. Pay attention to where within
OddsTest1you create new
Oddsobjects. You can create an instance only after you’ve read the required inputs; on the other hand, you need to create it before you can call any methods on it.
- Since
OddsTest1and
Oddsare in the same package, you can instantiate
Oddsin
OddsTest1without
importing anything.
- You’ll notice that the given code calls functions named
readIntand
readDouble. These two work like
readLine, above, differing from it only in that they interpret user inputs as numbers. For example,
readIntreturns a value of type
Int, not a
String.
- Hint: you can use
bothto compute the odds of an event occurring twice. (E.g., to roll a six twice is to roll a six and to roll another six.)
Submission form
A+ presents the exercise submission form here.
Optional assignment: eliminate redundant code with abstraction
OddsTest1 features two pieces of code that do essentially the same thing: they
read in two numbers and use them as constructor parameters for a new
Odds object.
Avoid this unnecessary repetition with a different implementation:
- In
OddsTest1, add a method called
requestOddsthat takes no parameters. This effectful method reads in two integers, uses them to create an
Oddsinstance, and returns a reference to the new object.
- Call
requestOdds(twice).
A+ presents the exercise submission form here.
An Application with a GUI
Recap: An application program operates on some problem domain. The programmer creates a model of that domain. A user interface presents the model to the end user in some form, usually as images and/or text. Many user interfaces also let the user interact with the model, affecting the model’s state. Many applications have a graphical user interface (GUI) that consists of various visual elements and is typically displayed in a separate window.
A toy example of a model
The domain of the FlappyBug game is the two-dimensional game world; in the previous
chapter, we wrote the classes
Bug,
Game, and
Obstacle, which together model this
domain. Before we write a GUI for that model, let’s consider a simpler model and a GUI
that displays it.
Our example model consists of just a single class,
Block:
class Block(val size: Int, val location: Pos, val color: Color) { override def toString = this.color + " block at " + this.location }
Here’s a usage example:
import o1._, o1.block._import o1._ import o1.block._ val model = new Block(20, new Pos(300, 50), Gray)model: Block = Gray block at (300.0,50.0)
Now let’s write a GUI that displays a view of a single
Block object set against a
solid background.
Quick recap of custom methods
Remember the
Person class from the end of Chapter 2.4? We created several instances of
it, including a Superman person that was created with this command:
val superman = new Person("Clark") { def fly = "WOOSH!" }
That object is an instance of the person class but also has a
fly method. In just a
moment, we’ll find a more concrete use for defining a method on a single instance.
Displaying a GUI window:
o1.View
Fortunately, programmers don’t have to build a GUI for every application from scratch, pixel by pixel. Instead, they find a software library suitable for their purposes.
There are many GUI libraries. One well-known one is called Swing; we’ll use Swing in Chapter 12.3 to work with buttons, text fields, and the like. Right now, we’ll instead use O1’s own GUI library, which is particularly useful for building small apps whose GUI consists of geometric shapes. (This library is also compatible with Swing.)
Package
o1 provides a class called
View. As its name suggests, this class can be used
to display a view to an object that models the app’s domain. Let’s use the following
Block object as our model:
val model = new Block(20, new Pos(300, 50), Gray)model: Block = Gray block at (300.0,50.0)
Now to create the
View object. This object represents a single GUI window that displays
a single object of type
Block.
val viewOfBlock = new View(model) { def makePic = { val background = rectangle(500, 500, Black) val blockPic = rectangle(model.size, model.size, model.color) background.place(blockPic, model.location) } }viewOfBlock: o1.gui.mutable.ViewFrame[Block] = view of Block
View. As a constructor parameter, we pass in a reference to what the view will display.
Viewobject can do, our particular
Viewinstance has an effect-free method
makePicthat forms an image of the model. The image is of type
Pic, and we form it using the
Pictools familiar from earlier chapters.
Nothing graphical actually showed up when we entered that command in the REPL. This is
because we didn’t yet start up our GUI. Every
View object has an effectful method
that starts it. The following command displays our primitive GUI. Try it.
viewOfBlock.start()
Any
View object is capable of drawing itself onscreen and showing the image produced by
its
makePic method. So what we get is a window that contains the image of a block set
against a black background. The window also has the customary controls for minimizing and
closing it; that little bit of interactivity is automatically provided by
View without
us having to do anything about it.
An
App with a
View
Let’s combine what we’ve covered in this chapter to create an app object that fires up a GUI view.
object BlockApp extends App { val background = rectangle(500, 500, Black) val block = new Block(20, new Pos(300, 50), Gray) val viewOfBlock = new View(block, "An uninteractive test app") { def makePic = { val blockPic = rectangle(block.size, block.size, block.color) background.place(blockPic, block.location) } } viewOfBlock.start() }
Viewwe construct.
startto make the GUI visible onscreen. After that, all the code within our app object has been executed but our application will keep running in its separate window until the user signals otherwise.
You can find this mini-app in the IntroApps project, under
o1.block.
It is ready to run.
Side note:
makePic as an abstract method
Question: what happens if I remove
makePic from the above app?
Answer: you’ll receive a compile-time error message informing
you that you can’t create a
View object that doesn’t have a
makePic method.
Explanation: the
View class has been defined so that even though
it doesn’t actually implement a
makePic method, it requires
such an implementation to exist on all objects of type
View.
In more technical terms,
makePic is an abstract method in
class
View. More on abstract methods in Chapter 7.2.
That sure was a boring app. On to FlappyBug.
Assignment: FlappyBug (Part 3 of 16: The Beginnings of a GUI)
A diagram of the components in project FlappyBug. The model we’ve already discussed; now we’ll make the user interface.
Introduction
Here’s some starter code for an app object. You can also find this code in
FlappyBugApp.scala.
package o1.flappy.gui import o1._ import o1.flappy._ object FlappyBugApp extends App { val sky = rectangle(ViewWidth, ViewHeight, LightBlue) val ground = rectangle(ViewWidth, GroundDepth, SandyBrown) val trunk = rectangle(30, 250, SaddleBrown) val foliage = circle(200, ForestGreen) val tree = trunk.onto(foliage, TopCenter, Center) val rootedTree = tree.onto(ground, BottomCenter, new Pos(ViewWidth / 2, 30)) val scenery = sky.place(rootedTree, BottomLeft, BottomLeft) val bugPic = Pic("ladybug.png") def rockPic(obstacle: Obstacle) = circle(obstacle.radius * 2, Black) // INSERT YOUR OWN CODE BELOW. }
scenerystores the end result. It isn’t necessary that you understand precisely how the background was constructed, but you can find an explanation in the optional material at the end of Chapter 2.5
bugPicstores an image that we’ll use to depict the bug in the GUI.
rockPic(5)gives you a pebble and
rockPic(150)an almighty chunk of rock.
Reminder: please don’t forget to ask for a hint on our forums or at the labs if you’re stuck. You really don’t need to do everything alone.
We’ve split this task in two phases:
Phase 1 of 2: displaying the background
- Create a new object that will serve as the application’s domain model. A
Gameobject is a suitable model for our FlappyBug app.
- Create a
Viewthat depicts the
Gamein a GUI window.
- Use "FlappyBug" as the title.
- The basic idea is very similar to the block app, but now the domain model isnt a
Blockbut a
Gameobject. When you create the
View, pass in two constructor parameters: a reference to your
Gameobject and the window title as a string.
- Define a variable that refers to your
Viewobject (like
viewOfBlockearlier). Normally, you could name such a variable freely, but please use the name
guihere to ensure that automatic assessment works properly for this assignment.
- Write a
makePicmethod on the view. For now, just have it return the background picture (
scenery). You’ll add the bug and the obstacle in just a bit.
- Add a
startcommand to start the GUI.
Now when your run the program, you should see a simple scenery in a window titled
"FlappyBug". The result isn’t much different from what we’ve already been able to produce
with the
show function. Yet.
Phase 2 of 2: placing the bug and the obstacle
Improve the
makePic method. It should construct and return an image of the game’s current
state by combining the scenery, the bug’s image, and an image of an obstacle so that the
bug and the obstacle have been
placed against the scenery in their correct positions.
A few hints:
- Use the images given as
sceneryand
bugPic. Use
rockPic.
- Given what you did in Chapter 2.6, the
Gameobject should have two variables:
obstacleand
bug. You can use them to access the game’s bug and the obstacle. You’ll need to do so.
- E.g.,
myGameObject.bug
- You can access the positions of the game’s bug and obstacle via their
posattributes (Chapter 2.6).
- E.g.,
myGameObject.bug.pos
- Place the bug and the obstacle at their initial locations as indicated by their
poses.
- Use something in the vein of
scenery.place(referenceToObstacle, positionOfObstacle).
- Cf. the
Blockexample above.
Run the program. You should see both the bug and the obstacle in their initial positions. They don’t move. Yet.
Submission form
A+ presents the exercise submission form here.
Optional activity: write prettier code
In the given
FlappyBugApp, the background image is
constructed with a sequence of commands that use multiple
temporary variables (e.g.,
foliage,
ground), each of
which stores a partial image but has no purpose once the
final scenery has been constructed. We can make our code
a bit more elegant by structuring it differently. Try the
following.
Can you restructure that part of the code so that
sceneryisn’t a variable but a parameterless function that returns the scenic image? Like this:
def scenery = { // place the code that constructs the image here }
In this solution, temporaries such as
foliagebecome local variables as you define them within
scenery’s body.
How about changing
def sceneryto
val sceneryin the modified solution? Does that work? Can you tell what difference this makes, if any?
Summary of Key Points
- A Scala application is launched through an app object. You can write an app object by including
extends Appin the definition of a singleton object.
- You may not need to write any methods on an app object. The commands in the object’s body are executed one by one when the application is launched.
- In a larger application, the app object activates other program components.
- The Scala library provides functions for reading keyboard input from the user through the text console.
- A typical application’s program code features a domain model and a user interface that depicts and operates on the model.
- There are various software libraries that help programmers build graphical user interfaces.
- One GUI library is provided as part of package
o1. A key component of this library is the
Viewclass, whose instances represent GUI windows.
- Links to the glossary: app object; input, I/O; model, user interface, graphical user interface .
extendskeyword as “is a kind of”. | https://plus.cs.aalto.fi/o1/2018/w02/ch07/ | CC-MAIN-2020-24 | refinedweb | 3,543 | 66.84 |
We're going to make a small change to the way our routes list is stored, then it's time for you to take on another task.
First things first: we're storing our list of routes inside index.js, which is fine when you're just getting started but sooner or later needs to be put somewhere else to make your app easier to maintain. Well, that time is now, so create a new file called routes.js in your src directory where index.js is.
We're going to move most of the routing code out from index.js and in to routes.js so that we have a clear separation of concerns. This also means splitting up the
import lines: routes.js needs to know all our app's imports, whereas index.js doesn't.
Here's the new code for routes.js
src/routes.js
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './pages/App'; import List from './pages/List'; import Detail from './pages/Detail'; const routes = ( <Route path="/" component={ App }> <IndexRoute component={ List } /> <Route path="detail/:repo" component={ Detail } /> </Route> ); export default routes;
That imports only what it needs, then creates a constant containing the route configuration for our app, and exports that constant so that others can use it.
What remains in index.js is the basic router configuration and the main call to
ReactDOM.render(). Over time, as your application grows, you'll probably add more to this file, but trust me on this: you'll definitely fare better if you keep your route configuration out of your main index.js file.
Here's the new code for index.js:
src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, useRouterHistory } from 'react-router'; import { createHashHistory } from 'history'; import routes from './routes'; const appHistory = useRouterHistory(createHashHistory)({ queryKey: false }) ReactDOM.render( <Router history={appHistory} onUpdate={() => window.scrollTo(0, 0)}> {routes} </Router>, document.getElementById('app') );
With that little clean up complete it's time for your first major! | http://www.hackingwithreact.com/read/1/26/cleaning-up-our-routes-and-preparing-for-the-next-step | CC-MAIN-2017-22 | refinedweb | 342 | 67.25 |
Texel Density Advisor is a tool to figure out optimal texture resolution which corresponds to desired texel density (pixels per meter).
With this tool you will never have to think about texture density mismatch, oversized or too small textures, which makes this tool esential for game development and film production.
Why use:
Making all textures in a project with aproximately same texel density is a good practice, because:
1. All your assets look consistent.
2. There won't be any texel density mismatch if assets are made by different artists.
3. Using maps with too high texel density is a waste of memory.
4. Using maps with too low texel density makes your assets look terrible.
How to use:
First of all you need to decide which texel density you are going to use in your project (game, short film, whatever).
To figure it out you need to make these steps:
1. Get some 4k by 4k high-quality texture
2. Create downgraded versions of this texture in photoshop or something similar (2k by 2k, 1k by 1k, 512 by 512, 256 by 256, and so on)
3. Create a 1 meter by 1 meter plane
4. Apply those textures to the plane one by one starting from the lowest resolution
5. When you reach a point when the texture looks good for you, there you go! The size of this texture IS the desired texel density per meter.
Now you can tell that, for example, there are 256 (or any other number that you figured out) pixels in a meter in your project. This is what texel density is.
After that simply run the script, enter the texel density value in the field on top of the interface, and select assets in question (they must be unwrapped). It calculates the size of the object, uv area of the object, and some other things, then gives you propositions.
The tool will show you (going left to right, top to bottom):
1. "Perfect" texture size that you would need to use to meet the desired texel density. Don't use this value to make your textures, use the closest "power of 2" size, which is conveniently advised to you by the script! This is a helper value to make your decision easier.
2. Used UV space. This value basically tells you how good you were at unwrapping the asset. For example, a default cube takes only 37.5% UV space. Other 62.5% of the texture is a wasted memory and disk space. So this is just a free hint for you.
3. Lower estimated resolution. This is one of the two advised resolutions.
4. Higher estimated resolution. So.. this is the other one.
5. Doubled progress bar shows you texel density deviation for lower and higher estimated resolutions. Value on the left says "If you are going to use Lower estimated resolution for you texture, then you will lose 'this' % of texel density".
Value on the right says the opposite. "If you are going to use Higher estimated resolution for you texture, then you will gain 'this' % of texel density".
This is the point when you might make a decision. Looking at this gauge you can think something like: "Okay, making 256x256 texture makes it 20% less texel dense and makes it look muddier, making 512x512 texure makes it 60% more texel dense and my asset will look much crispier but will take more memory. This is just a background asset, so I don't care if it doesn't look too crisp. I'll use 256x256 texture and will save memory for some important stuff!".
6. Values under the progress bar are the resulting texel density for each estimated resolution.
7. Finally, the advisor at the bottom. It calculates the least deviation from desired texel density and tells you which texture size is more appropriate. Despite that it is just an advise, in most cases it is a good advice :)
Some specific things to mention:
If recommended texture size is lower than 128x128, you will get an advice to use texture atlas for this asset. No texture size advice in this situation.
If recommended texture size is higher than 2048x2048, you will get an advice to use tileable texture for this asset. No texture size advice in this situation.
Each field of the interface contains a tooltip which tells what means what. Just hover a mouse over.
If you scale your asset, please ensure to select it once again. This tool only reacts when selection is made.
If your asset is a group of objects - no problem, just select that group.
The tool's core takes some time to calculate data, but it is quite fast. It took only 1 second to calculate 1 000 000 tris asset on my i7. So, in most cases, this tool can be opened all the time.
INSTALLATION:
1. Copy "texelDensityAdvisor" folder into your "%user%\Documents\maya\%version%\scripts" folder
2. add a shelf button with the following python script, or add it to a hotkey:
from texelDensityAdvisor import texelDensityAdvisor
texelDensityAdvisor.createUI()
3. Done!
Tested on windows 10, maya 2016, 2016.5, 2017.
Please use the Feature Requests to give me ideas.
Please use the Support Forum if you have any questions or problems.
Please rate and review in the Review section. | https://jobs.highend3d.com/maya/script/texel-density-advisor-for-maya | CC-MAIN-2021-49 | refinedweb | 889 | 65.62 |
React is one of the most popular JavaScript libraries for building user interfaces.
If you want to become a front-end developer or find a web development job, you would probably benefit from learning React in-depth.
In this post, you're going to learn some of the basics of React like creating a component, the JSX syntax, and Props. If you have no or little experience with React, this post is for you.
For starters, here's how you can install React.
What is JSX?
The first thing you'll realize after installing your first React project is that a JavaScript function returns some HTML code:
function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} <p> Edit <code>src/App.js</code> and save to reload. </p> </header> </div> ); }
This is a special and valid syntax extension for React which is called JSX (JavaScript XML). Normally in frontend-related projects, we keep HTML, CSS, and JavaScript code in separate files. However in React, this works a bit differently.
In React projects, we don't create separate HTML files, because JSX allows us to write HTML and JavaScript combined together in the same file, like in the example above. You can, however, separate your CSS in another file.
In the beginning, JSX might seem a little bit weird. But don't worry, you'll get used to it.
JSX is very practical, because we can also execute any JavaScript code (logic, functions, variables, and so on) inside the HTML directly by using curly braces { }, like this:
function App() { const text = 'Hello World'; return ( <div className="App"> <p> {text} </p> </div> ); }
Also, you can assign HTML tags to JavaScript variables:
const message = <h1>React is cool!</h1>;
Or you can return HTML inside JavaScript logic (such as if-else cases):
render() { if(true) { return <p>YES</p>; } else { return <p>NO</p>; } }
I won't go into further details of JSX, but make sure that you consider the following rules while writing JSX:
- HTML and component tags must always be closed < />
- Some attributes like “class” become “className” (because class refers to JavaScript classes), “tabindex” becomes “tabIndex” and should be written camelCase
- We can’t return more than one HTML element at once, so make sure to wrap them inside a parent tag:
return ( <div> <p>Hello</p> <p>World</p> </div> );
- or as an alternative, you can wrap them with empty tags:
return ( <> <p>Hello</p> <p>World</p> </> );
You can also watch my React for Beginners tutorial for more info:
What are Functional & Class Components?
After getting used to the JSX syntax, the next thing to understand is the component-based structure of React.
If you revisit the example code at the top of this post, you'll see that the JSX code is being returned by a function. But the App( ) function is not an ordinary function – it is actually a component. So what is a component?
What is a Component?
A component is an independent, reusable code block which divides the UI into smaller pieces. For example, if we were building the UI of Twitter with React:
Rather than building the whole UI under one single file, we can and we should divide all the sections (marked with red) into smaller independent pieces. In other words, these are components.
React has two types of components: functional and class. Let's look at each now in more detail.
Functional Components
The first and recommended component type in React is functional components. A functional component is basically a JavaScript/ES6 function that returns a React element (JSX). According to React's official docs, the function below is a valid functional component:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
Alternatively, you can also create a functional component with the arrow function definition:
const Welcome = (props) => { return <h1>Hello, {props.name}</h1>; }
This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. — reactjs.org
To be able to use a component later, you need to first export it so you can import it somewhere else:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } export default Welcome;
After importing it, you can call the component like in this example:
import Welcome from './Welcome'; function App() { return ( <div className="App"> <Welcome /> </div> ); }
So a Functional Component in React:
- is a JavaScript/ES6 function
- must return a React element (JSX)
- always starts with a capital letter (naming convention)
- takes props as a parameter if necessary
What are Class Components?
The second type of component is the class component. Class components are ES6 classes that return JSX. Below, you see our same Welcome function, this time as a class component:
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
Different from functional components, class components must have an additional render( ) method for returning JSX.
Why Use Class Components?
We used to use class components because of "state". In the older versions of React (version < 16.8), it was not possible to use state inside functional components.
Therefore, we needed functional components for rendering UI only, whereas we'd use class components for data management and some additional operations (like life-cycle methods).
This has changed with the introduction of React Hooks, and now we can also use states in functional components as well. (I will be covering state and hooks in my following posts, so don't mind them for now).
A Class Component:
- is an ES6 class, will be a component once it ‘extends’ a React component.
- takes Props (in the constructor) if needed
- must have a render( ) method for returning JSX
What are Props in React?
Another important concept of components is how they communicate. React has a special object called a prop (stands for property) which we use to transport data from one component to another.
But be careful – props only transport data in a one-way flow (only from parent to child components). It is not possible with props to pass data from child to parent, or to components at the same level.
Let's revisit the App( ) function above to see how to pass data with props.
First, we need to define a prop on the Welcome Component and assign a value to it:
import Welcome from './Welcome'; function App() { return ( <div className="App"> <Welcome name="John"/> <Welcome name="Mary"/> <Welcome name="Alex"/> </div> ); }
Props are custom values and they also make components more dynamic. Since the Welcome component is the child here, we need to define props on its parent (App), so we can pass the values and get the result simply by accessing the prop "name":
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
React Props Are Really Useful
So React developers use props to pass data and they're useful for this job. But what about managing data? Props are used for passing data, not for manipulating it. I'm going to cover managing data with React in my future posts here on freeCodeCamp.
In the meantime, if you want to learn more about React & Web development, feel free to subscribe to my YouTube channel.
Thank you for reading! | https://www.freecodecamp.org/news/react-components-jsx-props-for-beginners/ | CC-MAIN-2021-43 | refinedweb | 1,209 | 61.67 |
On time and in-sync, gtkmm 2.4 is now here. gtkmm provides a C++ interface to GTK+, with comprehensive documentation. and glibmm 2.4.0 Released
2004-04-12 GTK+ 27 Comments
I wanted to get my friend setup with The Gimp andI can’t find any GTK 2.4 for Windows. Isn’t GTK+ a multiplatform toolkit?
Also when i installed it with 2.2 I had to delete various files like Libxml2 from other places in order for GIMP not to give me errors.
Try here:
Installers for GTK+ and the Gimp for Windows. No compilation necessary, works great for me right out of the box.
I never understood why Gnome is not written in C++. GTKmm always come after GTK+ and it is seen as a “ugly duck” by gnome developers.
For me it is a mistake. It is more natural to program GUIs with an object-oriented language and it is a reason why Qt is more easy to program.
“I never understood why Gnome is not written in C++.”
1) Historical reasons. GNOME is based on GTK+, whose primary API was and is for C.
2) C++ does not have a standard ABI, which creates some interesting problems, most notably that it is difficult to make a dynamically-linked C++ binary that will work across different distributions using slightly different versions of g++.
Comparing just the languages, C++ arguably comes out ahead of C. When external issues get taken into account, the issues get murkier.
C++ *did* not have a standard x86 ABI. It does now. It should be noted, of course, there is no standard C-ABI eitheer — it differs from platform to platform.
There are many reasons given on to why Gnome wasn’t written in C++.
Some of them given are that c++ wasn’t a standard and not as portable at the time. That’s a pretty lame excuse. KDE’s choice of c++ didn’t hamper it’s portability.
Another reason is the language bindings. That’s a legitimate one because it is harder to do bindings for alternative languages when C++ is your base.
They had to choose a toolkit or roll their own one. Since rolling your own is a major undertaking in its self the only alternatives were gtk+ or qt. QT had licensing problems for free software back then and why bother with Gnome if you’re going to choose QT – since there was already KDE.
On top of all of that, and IMO the biggest reason is that Miguel de Icaza is not a big fan of C++ and considering that straight C was/is? still the lingua franca of Unix development it made more sense to just do it in C. Many developers, even today, are not big fans of C++.
One of the reasons that Mono was started is to address the issue of normal app development in straight C.
Becuase the advantages of C++ are pretty much overated. The main result is that it makes some things some what simpler, while making somethings more complex… or pretty much personal preference.
On top of all of that, and IMO the biggest reason is that Miguel de Icaza is not a big fan of C++
Heh. Considering what he’s working on these days, that makes a lot of sense.
I had always just figured that Gnome wasn’t written in C++ simply because designing large complex OO systems is, in fact, quite difficult to get right (though, what you eventually implement is easier to maintain and extend later on).
Yep, C++ is overrated and very easy to get wrong. And sometimes you’ve gone way too far in your implementation when you realize you got it wrong. If you do get it right, then it leads to a good extensible system.….
Victor.
I never understood why Gnome is not written in C++. GTKmm always come after GTK+ and it is seen as a “ugly duck” by gnome developers.
An additional reason often mentioned is that the GCC compiler produced rather slow code from C++ at the time, GNOME was started.
However, GTKmm isn’t seen as an “ugly duck” by GNOME developers. But for historical reasons, a lot of C++ developers have been attracted by KDE and QT first. Thus, they were under-represented in the beginnings of GNOME.
But there is a growing base of C++ lovers within the GNOME community — maybe slowly and quiet but continuously. At least that’s my impression.
What’s indeed needed now are some people to do a proper project lead for a few more reference projects. These may be simple ports of great QT applications, so that they fit better into a GNOME desktop, or implementations of completely new ideas.
Either way, there’s room enought to develop C++ applications within the GNOME development enviroment, and you will be respected for what you do, I’m sure.
Yeah, that is just plain ugly.
I would refine your second example to just
m_button.clicked(this, &HelloWorld::on_button_clicked);
…forget the whole signal business
IMO, C# with delegates is even more elegant. something in C# with GTK# would go something like this
button.Clicked += new EventHandler(HandleClick);
void HandleClick(object o, EventArgs e)
{
Console.WriteLine(“clicked”);
}
I like the way how it acts like a function pointer, but is type safe. Interfaces and Adapter classes in Java are not near as elegant.
I believe in C# 2.0 it’ll be even simpler
button.Clicked += HandleClick;
That’s about as simple as it can get
That looks weird to me. I used libsigc++ in MacOSX and started making a C++ framework to wrap Carbon. All I had to do was have a signal object and call its connect(), passing for parameters the class who’s method I’m connecting, then a pointer to the method. I never had to use sigc::mem_func().
Even when I was using gtkmm in Linux it was just as easy as slots/signal connecting in Qt (minus the meta-object compiler). Actually I prefered gtkmm over Qt because there was no need for a MOC build stage which really got annoying when working with Qt Designer.
use gtk1. please. think of the domokun. its got more than what you’ll ever use and its fast.
let me repeat: you dont need gtk2. use gtk1.
My thoughts exactly
However, GTK+ 2.0 does have *some* nicities. Now if only they could get the memory usage down a bit (lot)…
“Becuase the advantages of C++ are pretty much overated. The main result is that it makes some things some what simpler, while making somethings more complex… or pretty much personal preference.”
Top level components would benefit from c++, using oop for graphical objects like windows, buttons, menus and stuff like that makes a lot of sence IMHO, low level components like the gdk are better left off in plain c.
Because like someone above said, C++ is overrated, complex and hard to do right. At the time GNOME was founded, C++ had no standard ABI, had terrible compilers and wasn’t as mature as C was.
It is so obvious, isn’t it? I wish there was a decent explanation why gtkmm has these ugly apis. It could be simpler, and it’s not even hard to do that!
Makes me feel like implementing my own objects inherited from gtkmm’s. But i really wish i didn’t have to waste time doing that.
Victor.
Wasn’t egcs available when gnome started??
“I wish there was a decent explanation why gtkmm has these ugly apis.”
Well look at Win32 API -> MFC. Personally, I really enjoy working with MFC but I hear a lot of other programmers blasting MFC for being a poorly put together C++ framework that just makes calls into Win32 API.
gtkmm is kinda the same situation, it wraps gtk2 calls. sigc++ was created specifically for the gtkmm project. sigc++ is a C++ callback framework plus it provides classes for slot/signal mechanism. Coming from MFC, I too feel that slots and signals can look weird but it takes some getting use to. Once you really get the hang of it you’ll start to appreciate it, as I’ve started to appreciate slots and signals.
On a final note, you probably should have done:
using namespace sigc;
then you wouldn’t have to write sigc::mem_func(…) instead just write mem_func(…) The same goes for the other namespaces in gtkmm and related add ons.
That’s another reason why the GTK developers chose C language over C++. Namespaces are great for having simplified class names (ex: instead of CWindow or TWindow or XYZWindow your window class can just be called “Window”). But because the class names are simple you’ll run the risk of a conflict of names when using more than one namespace. Last time I was using sigc++ in MacOSX, Carbon lib had an object (keyword, datatype, whatever it was I don’t remember) called “slot” and obviously sigc++ has a class named “slot”. So I couldn’t use the sigc namespace.
So without namespaces the developers have to come up with unique class names. With namespaces there’s a risk of the whole namespace not working becuase another one has an object with the same name in it. That’s why you see really long function names in GTK’s API. They try to fit the function name, a little bit of what it does, and the function’s social security number (JK) into the function name, and you pass around pointers and handles to other objects. The long function names can make your fingers tired but it’s better than getting confused between 2 objects with similar or exact names.
In a small project it might be managable, but I fear for the really big projects that rely on using multiple open source libraries pulled together for functionality. That’s the only big issue I have with OSS development. Sometimes there’s great teamwork, but it’s still not a fun time looking at and working with someone else’s code (only when something breaks).
> The long function names can make your fingers tired
…well, unless your editor has an auto-complete function.
I hear the D programming language is pretty nice
Heh. Anybody know of any desktop environments written in D?
Whoops. Nevermind. There doesn’t seem to be a Free D implementation.
I checked out Digital Mars website and read up on D flat. From what I’m seeing I don’t like it. Function overloading is a bit confusing, just read this page:
SNIP:
}
In test(), why does it call B.def() if a class A object is left of . ?….
… and this is why Objective-C is much, much nicer language when you deal with messages between objects and gui stuff.
Here is the same code as yours :
[m_button setAction: @selector(HelloWorld:)];
isn’t it nice ?
explanation :
).
Anyway, you generally don’t bother setting it manually, as developers generally uses GORM (on GNUstep) or InterfaceBuilder (on MacOSX) for creating their User Interface and setting links between objects.
).
Who is the owner of the HelloWorld method?
What I mean is, in C++ (more specifically, in a C++ callback framework) I would pass:
MyClass::Foo()
as the method to assign to a button click event. In your sample code, it’s not as obvious from where the HelloWorld method originated.
> With namespaces there’s a risk of the whole namespace not
> working becuase another one has an object with the same
> name in it.
Nonsense. Namespaces solve this problem – they don’t create it. Sure, if you put “using” statements everywhere, effectively putting everything in to the same namespace, then you’ll get clashes. So don’t do that.
What is harder to deal with is stupidly-named C macros in public headers. Maybe that’s what you had with MacOS X. For instance, Qt #defines “emit”, so you can’t use a C++ method called emit().
Who is the owner of the HelloWorld method?
You could set it with the message setTarget; else it could be determined at runtime :…’s content view.
It tries the NSWindow object and then, the NSApplication object tries to respond itself. If it can’t respond, it tries its own delegate. NSApp and its delegate are the receivers of last resort. | https://www.osnews.com/story/6701/gtkmm-and-glibmm-240-released/ | CC-MAIN-2019-47 | refinedweb | 2,070 | 73.58 |
This tutorial will guide you through building the broadcast server
side event example present in the examples/broadcast
directory. This is a very simple app that broadcasts any message sent
to it to every connected client.
examples/broadcast
To run the example, in examples/broadcast the following should start
the server, (see Installation first),
$ export QUART_APP=broadcast:app
$ quart run
the broadcast is then available at.
Quart by default expects the code to be structured in a certain way in
order for templates and static file to be found. This means that you
should structure the broadcast as follows,
broadcast/
broadcast/static/
broadcast/static/js/
broadcast/static/css/
broadcast/templates/
doing so will also make your project familiar to others, as you follow
the same convention.
It is always best to run python projects within a virtualenv, which
should be created and activated as follows,
$ cd broadcast
$ pipenv install quart
for this broadcast we will only need Quart. Now pipenv can be activated,
$ pipenv shell
Server Sent Events, or SSEs,
or EventSource (in Javascript), are an extension to HTTP that allow a
client to keep a connection open to a server thereby allowing the
server to send events to the client as it chooses.
Server sent events have a specific structure consisting at the minimum
of some string data and optionally an event, id and or retry tag. To
send this structured data the following class can be used,
class ServerSentEvent:
def __init__(
self,
data: str,
*,
event: Optional[str]=None,
id: Optional[int]=None,
retry: Optional[int]=None,
) -> None:
self.data = data
self.event = event
self.id = id
self.retry = retry
def encode(self) -> bytes:
message = f"data: {self.data}"
if self.event is not None:
message = f"{message}\nevent: {self.event}"
if self.id is not None:
message = f"{message}\nid: {self.id}"
if self.retry is not None:
message = f"{message}\nretry: {self.retry}"
message = f"{message}\r\n\r\n"
return message.encode('utf-8')
with the route itself returning an asynchronous generator with the
correct headers, as so,
@app.route('/sse')
async def sse():
async def send_events():
...
event = ServerSentEvent(data)
yield event.encode()
return send_events(), {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Transfer-Encoding': 'chunked',
}
the asynchronous generator then yields server sent events.
Quart by default will timeout long responses to protect against
possible denial of service attacks, see Denial Of Service mitigations. For
this example this timeout incorrectly closes the SSE stream, and so it
should be disabled. This can be done globally, however that could make
other routes DOS vulnerable, therefore the recommendation is to set
the timeout attribute on the specific response to None,
None
from quart import make_response
@app.route('/sse')
async def sse():
...
response = await make_response(
send_events(),
{
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Transfer-Encoding': 'chunked',
},
)
response.timeout = None # No timeout for this route
return response
In order to receive server sent events in the browser the Javascript
must declare and use an EventSource object, like so,
EventSource
var es = new EventSource('/sse');
es.onmessage = function (event) {
var messages_dom = document.getElementsByTagName('ul')[0];
var message_dom = document.createElement('li');
var content_dom = document.createTextNode('Received: ' + event.data);
message_dom.appendChild(content_dom);
messages_dom.appendChild(message_dom);
};
with the above adding each new message as a list item.
To complete the app we need to accept messages and then broadcast them
to every client. The latter part is best achieved by each client
having its own Queue which it receives messages on before broadcasting
them. The following snippet achieves this,
app.clients = set()
@app.route('/', methods=['POST'])
async def broadcast():
data = await request.get_json()
for queue in app.clients:
await queue.put(data['message'])
return jsonify(True)
@app.route('/sse')
async def sse():
queue = asyncio.Queue()
app.clients.add(queue)
async def send_events():
while True:
data = await queue.get()
event = ServerSentEvent(data)
yield event.encode()
response = await make_response(
send_events(),
{
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Transfer-Encoding': 'chunked',
},
)
response.timeout = None
return response
The example files contain this entire tutorial and a little more, so
they are now worth a read. Hopefully you can now go ahead and create
your own apps that use Server Sent Events. | https://pgjones.gitlab.io/quart/tutorials/broadcast_tutorial.html | CC-MAIN-2020-40 | refinedweb | 698 | 50.43 |
We want to retrieve corresponding Coveo Source Name in our project. Below sources are there in our project.
We are required to call Coveo Cloud Api from server side to get the data , when we call cloud api we are querying the data based on the field(ex, ftopics3422). We found a below code to form the hashed numeric value which is appended in the field- ftopics3422.
private int ComputeHashCodeForCoveo(string p_SourceName) { uint hash = 0; foreach (byte b in Encoding.Unicode.GetBytes(p_SourceName)) { hash += b; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return (int)(hash % 100000); }
The hashed code is generating based on the Source name.
Kindly suggest on this.
Thanks in advance.
Yes, the code pasted here is what you need to get the source hash.
And what is your problem?
ComputeHashCodeForCoveo method required Sourcename as the input. i want to know how to get Sourcename?
Or, How to acces ToCoveoFieldName() method to get coveo field name in my project befor calling to coveo cloud?
In order to better help you, I think we need more context on your project. Why do you have to call the Coveo Search API directly from back-end code? What are the reasons you cannot use the out of the box Coveo for Sitecore UI components?
Answers Answers and Comments
3 | https://answers.coveo.com/questions/15190/retrieve-coveo-source-name.html | CC-MAIN-2018-17 | refinedweb | 226 | 75.3 |
15 November 2012 18:22 [Source: ICIS news]
HOUSTON (ICIS)--Chemical shipments on Canadian railroads rose by 5.6% year on year for the week ended 10 November, marking the first increase after four straight weeks of declines, according to data released by a rail industry association on Thursday.
Canadian chemical railcar loadings for the week totalled 10,378, compared with 9,831 in the same week in 2011, the Association of American Railroads (AAR) said.
The previous week, ended 3 November, saw a 5.1%.
From 1 January to 10 November, Canadian chemical railcar loadings were down by 5.9% year on year, to 471,303.
The AAR that said weekly chemical railcar traffic in ?xml:namespace>
US chemical railcar traffic rose by 2.5% year on year in the week ended 10 November, the first uptick after three declines in a row.
There were 29,529 chemical railcar loadings last week, compared with 28,812 in the corresponding week of 2011. In the previous week, ended 3 November, US chemical railcar loadings fell by 1.2%.
From 1 January to 10 November, US chemical railcar loadings were down by 1.0% compared with the corresponding period of last year, to 1,335,381.
Overall, US weekly railcar loadings for the week ended 10 November in the freight commodity groups tracked by the AAR fell by 5.4% year on year to 283,414 carloads.
For all of | http://www.icis.com/Articles/2012/11/15/9614673/canadian-chemical-railcar-traffic-rises-after-four-declines.html | CC-MAIN-2014-49 | refinedweb | 239 | 65.93 |
Introduction and Creating Tables
Tables in Microsoft Word
All versions of Microsoft Word provide special commands for inserting and working with tables. The exact location of these differs between older and newer versions of Microsoft Word but they are all present. These are some of the more common tasks required when working with tables in Microsoft Word.
Inserting a Table in Microsoft Word
To insert a table in Microsoft Word 2003 and earlier:
- Click the Table menu from the top toolbar.
- Click Insert and then Table.
- Fill in the appropriate values and press Ok to insert the table.
To insert a table in Microsoft Word 2007 and later:
- Click the Insert tab.
- Choose the Tables drop down menu.
- Select Insert Table.
- Fill in the appropriate values and press Ok to insert the table.
Removing a Table or Table Elements in Microsoft Word
To remove a table or individual table elements in Microsoft Word 2003 and earlier:
- Click inside the table in the position that you want.
- Click the Table menu from the top toolbar.
- Click Delete.
- Choose the menu item of element you want to delete. For instance choosing Table will remove the entire table from the document.
To remove a table or individual table elements in Microsoft Word 2007 and later:
- Click inside the table at the desired position.
- The Layout tab should appear. Click this tab.
- Click the Delete drop down menu.
- Choose the menu item of the element you want to delete. For instance choosing Delete Table will remove the entire table from the document. Merging Cells in a Table in Microsoft Word
- Select the cells to be merged by dragging the cursor over the cells.
- Right click on the selection.
- Select Merge Cells from the popup menu.
Using the AutoFit feature in Microsoft Word
To use the AutoFit feature to automatically size a table in Microsoft Word:
- Right click anywhere inside the desired table.
- Select AutoFit from popup menu.
- Select the desired autofit option
- AutoFit to Contents fits the table around content.
- AutoFit to Window resizes the table so it fills the available page width between the left and right margins.
- Fixed Column Width sets each column width to an absolute value. This means even if the content within the cells were to change the width of each column in the table will stay the same.
Tables in Aspose.Words
A table from any document loaded into Aspose.Words is imported as a Table node. A table can be found as a child of the main body of text, an inline story such as a comment or footnote, or within a cell as a nested table. Furthermore, tables can be nested inside other tables up to any depth.
A Table node does not contain any real content - instead it is a container for other such nodes which make up the content:
- A Table contains many Row nodes. A Table exposes all the normal members of a node which allows you to freely move, modify and remove the table in the document.
- A Row represents a single row of a table and contains many Cell nodes. Additionally a Row provides members which define how a row is displayed, for example the height and alignment.
- A Cell is what contains the true content seen in a table and is made up of Paragraph and other block level nodes. Additionally cells can contain further nested tables.
This relationship is best represented by inspecting the structure of a Table node in a document through the use of DocumentExplorer .
You can see in the diagram above that the document contains a table which consists of one row which in turn consists of two cells. Each of the two cells contains a paragraph which is the container of the formatted text ion a cell. In Aspose.Words all table related classes and properties are contained in the Aspose.Words.Tables namespace.
You should also notice table is succeeded with an empty paragraph. It is a requirement for a Microsoft Word document to have at least one paragraph after a table. This is used to separate consecutive tables and without it such consecutive tables would be joined together into one. This behavior is identical in both Microsoft Word and Aspose.Words.
Creating Tables
Aspose.Words provides several different methods to create new tables in a document. This article presents the full details of how to insert formatted tables using each technique as well as a comparison of each technique at the end of the article. A newly created table is given similar defaults as used in Microsoft Word:
Inserting a Table using DocumentBuilder
In Aspose.Words a table is normally inserted using DocumentBuilder. The following methods are used to build a table. Other methods will also be used to insert content into the table cells.
- DocumentBuilder.StartTable
- DocumentBuilder.InsertCell
- DocumentBuilder.EndRow
- DocumentBuilder.EndTable
- DocumentBuilder.Writeln
Algorithm for Creating a Table
The basic algorithm for creating a table using DocumentBuilder is simple:
- Start the table using DocumentBuilder.StartTable.
- Insert a cell using DocumentBuilder.InsertCell. This automatically starts a new row. If needed, use the DocumentBuilder.CellFormat property to specify cell formatting.
- Insert cell contents using the DocumentBuilder methods.
- Repeat steps 2 and 3 until the row is complete.
- Call DocumentBuilder.EndRow to end the current row. If needed, use DocumentBuilder.RowFormat property to specify row formatting.
- Repeat steps 2 - 5 until the table is complete.
- Call DocumentBuilder.EndTable to finish the table building. The appropriate DocumentBuilder table creation methods are described below.
Starting a Table
Calling DocumentBuilder.StartTable is the first step in building a table. It can be also called inside a cell, in which case it starts a nested table. The next method to call is DocumentBuilder.InsertCell.
Inserting a Cell
After you call DocumentBuilder.InsertCell, a new cell is created and any content you add using other methods of the DocumentBuilder class will be added to the current cell. To start a new cell in the same row, call DocumentBuilder.InsertCell again. Use the DocumentBuilder.CellFormat property to specify cell formatting. It returns a CellFormat object that represents all formatting for a table cell.
Ending a Row
Call DocumentBuilder.EndRow to finish the current row. If you call DocumentBuilder.InsertCell immediately after that, then the table continues on a new row.
Use the DocumentBuilder.RowFormat property to specify row formatting. It returns a RowFormat object that represents all formatting for a table row.
Ending a Table
Call DocumentBuilder.EndTable to finish the current table. This method should be called only once after DocumentBuilder.EndRow was called. When called, DocumentBuilder.EndTable moves the cursor out of the current cell to a position just after the table. The following example demonstrates how to build a formatted table that contains 2 rows and 2 columns.
Below example shows how to create a simple table using DocumentBuilder with default formatting.
Below example shows how to create a formatted table using DocumentBuilder.
Below example shows how to insert a nested table using DocumentBuilder.
Inserting a Table Directly into the Document Object Model
You can insert tables directly into the DOM at a particular node position. The same table defaults are used as when using a DocumentBuilder to create a table. To build a new table from scratch without the use of DocumentBuilder, first create a new Table node using the appropriate constructor, and then add it to the document tree.
Note that you must take into account that the table will initially be completely empty (i.e contains no child rows yet). In order to build the table you will first need to add the appropriate child nodes.
Below example shows how to insert a table using the constructors of nodes.
Inserting a Clone of an Existing Table
Often there are times when you have an existing table in a document and would like to add a copy of this table then apply some modifications. The easiest way to duplicate a table while retaining all formatting is to clone the table node using the Table.Clone method. Below example shows how to insert a table using the constructors of nodes. You can download the template file of this example from here.
Below example shows how to make a clone of the last row of a table and append it to the table. You can download the template file of this example from here.
If you are looking at creating tables in document which dynamically grow with each record from your data source, then the above method is not advised. Instead the desired output is achieved more easily by using Mail Merge with Regions. You can learn more about this technique under Mail Merge with Regions Explained.
Inserting a Table from HTML
Aspose.Words supports inserting content into a document from an HTML source by using the DocumentBuilder.InsertHtml method. The input can be a full HTML page or just a partial snippet. Using this method we can insert tables into our document by using table elements e.g <table>, <tr>, <td>. Below example shows how to insert a table in a document from a string containing HTML tags.
Comparison of Insertion Techniques
As described in previous articles, Aspose.Words provides several methods for inserting new tables into a document. Each have their advantages and disadvantages, so often the choice of which to use depends on your situation. The table below can give you an idea of each technique.
Extracting Plain Text from a Table
A Table like any other node in Aspose.Words has access to a Range object. Using this object, you can call methods over the entire table range to extract the table as plain text. The Range.Text property is used for this purpose. Below example shows how to print the text range of a table.
Below example shows how to print the text range of row and table elements.
Replacing Text in a Table
Using a table’s range object you can replace text within the table. However, there are currently restrictions which prevent any replacement with special characters being made so care must be taken to ensure that the replacement string does not carry over more than one paragraph or cell. If such a replacement is made which spans across multiple nodes, such as paragraphs or cells, then an exception is thrown.
Normally the replacement of text should be done at the cell level (per cell) or at the paragraph level.
Below example shows how to replace all instances of string of text in a table and cell. | https://docs.aspose.com/words/net/introduction-and-creating-tables/ | CC-MAIN-2021-04 | refinedweb | 1,757 | 58.28 |
Question
- Create a function that returns the letter position where the ball final position is once the swapping is finish.
description
- There are three cups on a table, at positions A, B, and C. At the start, there is a ball hidden under the cup at position B.
- There will be several swap perform, represented by two letters.
- For example, if I swap the cups at positions A and B, this can be represented as
ABor
BA.
Examples
cup_swapping(["AB", "CA"]) ➞ "C" cup_swapping(["AC", "CA", "CA", "AC"]) ➞ "B" cup_swapping(["BA", "AC", "CA", "BC"]) ➞ "A"
My solution
- 1. initialise a current position "B"
- 2. iterate over the list of swap combination
- 2.1 iterate over each swap combination
- 3. check the ball have been swap
- 3.1 if current position is exist in the swap combination, it is swapped
- 3.2 update the current position
- 3.2.1 if current_position equals to the first letter
- 3.2.2 then final letter is the current position
- 3.3.1 if current_position not equal the first letter
- 3.3.2 then first letter is the current position
- 4. print the final position
def cup_swapping(swaps): current_position = "B" for move in swaps: if current_position in move: if current_position == move[0]: current_position = move[1] else: current_position = move[0] return current_position
Solution by others
Method 1
- shorten version of my answer
def cup_swapping(swaps): current_position = "B" for move in swaps: if current_position in move: current_position = move[1] if move[0] == current_position else move[0] return current_position
Method 2
def cup_swapping(swaps, current_position="B"): for move in swaps: current_position = move.replace(current_position, "") if current_position in move else current_position return current_position
- key point
- iterate over each swap
- in the swap, there is two letter
- if the current position appear in the swap, replace that letter with empty string
- i.e. replace "AB" to "A" if current position is "A"
- and also update the current position to the remaining single letter
- if the current position do not appear in the swap, keep the current position
My reflection
- It is a good feeling to solve a problem without hint. First I got stuck when just write the code, then I try to solve the question by writing the algorithm down, it sudden feel much easier to think. Thus, I will make the habit the write down the algorithm first rather coding at first. Beside, I learn new way to shorten the if else statement
Credit
challenge found on edabit
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/mathewchan/python-exercise-12-find-the-hidden-ball-4hkc | CC-MAIN-2022-33 | refinedweb | 411 | 53.71 |
This post outlines the various ways to organize your code using modules and namespaces in TypeScript. We’ll also go over some advanced topics of how to use namespaces and modules, and address some common pitfalls when using them in TypeScript.
See the Modules documentation for more information about ES Modules. See the Namespaces documentation for more information about TypeScript namespaces.
Note: In very old versions of TypeScript namespaces were called ‘Internal Modules’, these pre-date JavaScript module systems.
Using Modules
Modules can contain both code and declarations.
Modules also have a dependency on a module loader (such as CommonJs/Require.js) or a runtime which supports ES Modules. Modules provide for better code reuse, stronger isolation and better tooling support for bundling.
It is also worth noting that, for Node.js applications, modules are the default and we recommended modules over namespaces in modern code.
Starting with ECMAScript 2015, modules are native part of the language, and should be supported by all compliant engine implementations. Thus, for new projects modules would be the recommended code organization mechanism.
Using Namespaces
Namespaces are a TypeScript-specific way to organize code.
Namespaces are simply named JavaScript objects in the global namespace. This makes namespaces a very simple construct to use. Unlike modules, they can span multiple files, and can be concatenated using
--outFile. Namespaces can be a good way to structure your code in a Web Application, with all dependencies included as
<script> tags in your HTML page.
Just like all global namespace pollution, it can be hard to identify component dependencies, especially in a large application.
Pitfalls of Namespaces and Modules
In this section we’ll describe various common pitfalls in using namespaces and modules, and how to avoid them.
/// <reference>-ing a module
A common mistake is to try to use the
/// <reference ... /> syntax to refer to a module file, rather than using an
import statement. To understand the distinction, we first need to understand how the compiler can locate the type information for a module based on the path of an
import (e.g. the
... in
import x from "...";,
import x = require("...");, etc.) path.
The compiler will try to find a
.ts,
.tsx, and then a
.d.ts with the appropriate path. If a specific file could not be found, then the compiler will look for an ambient module declaration. Recall that these need to be declared in a
.d.ts file.
myModules.d.ts
ts// In a .d.ts file or .ts file that is not a module: declare module "SomeModule" { export function fn(): string; }
myOtherModule.ts
ts/// <reference path="myModules.d.ts" /> import * as m from "SomeModule";
The reference tag here allows us to locate the declaration file that contains the declaration for the ambient module. This is how the
node.d.ts file that several of the TypeScript samples use is consumed.
Needless Namespacing
If you’re converting a program from namespaces to modules, it can be easy to end up with a file that looks like this:
shapes.ts
tsexport namespace Shapes { export class Triangle { /* ... */ } export class Square { /* ... */ } }
The top-level module here
Shapes wraps up
Triangle and
Square for no reason. This is confusing and annoying for consumers of your module:
shapeConsumer.ts
tsimport * as shapes from "./shapes"; let t = new shapes.Shapes.Triangle(); // shapes.Shapes?
A key feature of modules in TypeScript is that two different modules will never contribute names to the same scope. Because the consumer of a module decides what name to assign it, there’s no need to proactively wrap up the exported symbols in a namespace.
To reiterate why you shouldn’t try to namespace your module contents, the general idea of namespacing is to provide logical grouping of constructs and to prevent name collisions. Because the module file itself is already a logical grouping, and its top-level name is defined by the code that imports it, it’s unnecessary to use an additional module layer for exported objects.
Here’s a revised example:
shapes.ts
tsexport class Triangle { /* ... */ } export class Square { /* ... */ }
shapeConsumer.ts
tsimport * as shapes from "./shapes"; let t = new shapes.Triangle();
Trade-offs of Modules
Just as there is a one-to-one correspondence between JS files and modules, TypeScript has a one-to-one correspondence between module source files and their emitted JS files. One effect of this is that it’s not possible to concatenate multiple module source files depending on the module system you target. For instance, you can’t use the
outFile option while targeting
commonjs or
umd, but with TypeScript 1.8 and later, it’s possible to use
outFile when targeting
amd or
system. | https://docs.w3cub.com/typescript/namespaces-and-modules | CC-MAIN-2021-17 | refinedweb | 776 | 58.48 |
Charlie Maffitt
Realizing that hitting “talk” on my phone dialed the previous number. Figuring out that the arrow next to my fuel gauge showed which side the car fuel door is on. Tab completion.
A couple of times a month, I’ll have a “wow - that’s so useful and so simple” moment. One of the first times I experienced that with Ruby was with
#method_missing.
Every class in Ruby has a
#method_missing method. When you attempt to call a method that doesn’t exist,
#method_missing will throw a
NoMethodError exception.
You can override this method and do some amazing things with it. At High Groove Studios, we use
#method_missing like a trophy wife uses her rich husband’s credit card bill: without abandon.
For example, let’s say you have a User model, and that user has a ton of profile data. You want to abstract that data, so you make a Profile class.
class User < ActiveRecord::Base has_one :profile end class Profile < ActiveRecord::Base belongs_to :user end
However, you don’t want to call
user.profile.street_address every time you need to access an attribute in a user’s profile. You also don’t want to define a bunch of reader methods like this:
def street_address profile.street_address end
Here’s all you have to do:
class User < ActiveRecord::Base ... # Attempts to pass any missing methods to # the associated +profile+. def method_missing(meth, *args, &block) if profile.respond_to?(meth) profile.send(meth) else super end end end
So, we now have this:
@user.street_address == @user.profile.street_address
That’s only one example of the power and simplicity of
#method_missing.
Charlie Maffitt
Josh Justice | https://www.bignerdranch.com/blog/ruby-moment-of-zen-method_missing/ | CC-MAIN-2017-13 | refinedweb | 275 | 66.54 |
Programming with Moose/Syntax< Programming with Moose
A big problem with the CPAN docs thus far is they utilize (abuse) the fact that Moose is an application of
Class::MOP.
Class::MOP is Meta Object Protocol building framework - and that is usually about where the cryptic confusion sets in.. There is a very blurry distinction between
Class::MOP and Moose, because Moose is the only known application of
Class::MOP.
Essentially what we have in
Class::MOP is an archive of hacks that allow Moose to be terse and non-perlish. Moose makes a few of these hacks available with out much sugar but generally speaking candy coats them to a comfortable level.
In this syntax compendium of Moose we promise to never mention
Class::MOP again.[1]
Table of ContentsEdit
Keywords exported with
use Moose;:
- has
- before, after, around
- blessed
- override
- augment
- extends
- with
- meta
- Other functions - Non-polluting fully-qualified syntax
Use of 'no Moose'Edit
15:32 <@konobi> less shit to track during runtime 15:33 <@Sartak> EvanCarroll: my $person = Person->new; $person->has("jewelry") 15:33 <@konobi> just _having_ stuff in your namespace will slow the interpreter down 15:33 <@Sartak> if you keep Moose's functions in Person's namespace, that will have weird results 15:33 <@Sartak> if you no Moose, then it's the usual "undefined function" error | https://en.m.wikibooks.org/wiki/Programming_with_Moose/Syntax | CC-MAIN-2016-50 | refinedweb | 225 | 50.6 |
Grad-CAM is a popular technique for visualizing where a convolutional neural network model is looking. Grad-CAM is class-specific, meaning it can produce a separate visualization for every class present in the image:
Example cat and dog Grad-CAM visualizations modified from Figure 1 of the Grad-CAM paper
Grad-CAM can be used for weakly-supervised localization, i.e. determining the location of particular objects using a model that was trained only on whole-image labels rather than explicit location annotations.
Grad-CAM can also be used for weakly-supervised segmentation, in which the model predicts all of the pixels that belong to particular objects, without requiring pixel-level labels for training:
Part of Figure 4 of the Grad-CAM paper showing predicted motorcycle and person segmentation masks obtained by using Grad-CAM heatmaps as the seed for a method called SEC (Seed, Expand, Constrain)
Finally, Grad-CAM can be used to gain better understanding of a model, for example by providing insight into model failure modes:
Figure 6 of the Grad-CAM paper, showing example model failures along with Grad-CAM visualizations that illustrate why the model made incorrect predictions.
The main reference for this post is the expanded version of the Grad-CAM paper: Selvaraju et al. “Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization.” International Journal of Computer Vision 2019.
A previous version of the Grad-CAM paper was published in the International Conference on Computer Vision (ICCV) 2017.
Grad-CAM as Post-Hoc Attention
Grad-CAM is a form of post-hoc attention, meaning that it is a method for producing heatmaps that is applied to an already-trained neural network after training is complete and the parameters are fixed. This is distinct from trainable attention, which involves learning how to produce attention maps (heatmaps) during training by learning particular parameters. For a more in-depth discussion of post-hoc vs. trainable attention, see this post.
Grad-CAM as a Generalization of CAM
Grad-CAM does not require a particular CNN architecture. Grad-CAM is a generalization of CAM (class activation mapping), a method that does require using a particular architecture.
CAM requires an architecture that applies global average pooling (GAP) to the final convolutional feature maps, followed by a single fully connected layer that produces the predictions:
In the sketch above, the squares A1 (red), A2 (green), and A3 (blue) represent feature maps produced by the last convolutional layer of a CNN. To use the CAM method upon which Grad-CAM is based, we first take the average of each feature map to produce a single number per map. In this example we have 3 feature maps and therefore 3 numbers; the 3 numbers are shown as the tiny colored squares in the sketch. Then we apply a fully-connected layer to those 3 numbers obtain classification decisions. For the output class “cat” the prediction will be based on 3 weights (w1, w2, and w3). To make a CAM heatmap for “cat”, we perform a weighted sum of the feature maps, using the “cat” weights of the final fully-connected layer:
Note that the number of feature maps doesn’t have to be three – it an be any arbitrary k. For a more detailed explanation of how CAM works, please see this post. Understanding CAM is important for understanding Grad-CAM, as the two methods are closely related.
Part of the motivation for the development of Grad-CAM was to come up with a CAM-like method that does not restrict the CNN architecture.
Grad-CAM Overview
The basic idea behind Grad-CAM is the same as the basic idea behind CAM: we want to exploit the spatial information that is preserved through convolutional layers, in order to understand which parts of an input image were important for a classification decision.
Similar to CAM, Grad-CAM uses the feature maps produced by the last convolutional layer of a CNN. The authors of Grad-CAM argue, “we can expect the last convolutional layers to have the best compromise between high-level semantics and detailed spatial information.”
Here is a sketch showing the parts of a neural network model relevant to Grad-CAM:
The CNN is composed of some convolutional layers (shown as “conv” in the sketch). The feature maps produced by the final convolutional layer are shown as A1, A2, and A3, the same as in the CAM sketch.
At this point, for CAM we would need to do global average pooling followed by a fully connected layer. For Grad-CAM, we can do anything – for example, multiple fully connected layers – which is shown as “any neural network layers” in the sketch. The only requirement is that the layers we insert after A1, A2, and A3 have to be differentiable so that we can get a gradient. Finally, we have our classification outputs for airplane, dog, cat, person, etc.
The difference between CAM and Grad-CAM is in how the feature maps A1, A2, and A3 are weighted to make the final heatmap. In CAM, we weight these feature maps using weights taken out of the last fully-connected layer of the network. In Grad-CAM, we weight the feature maps using “alpha values” that are calculated based on gradients. Therefore, Grad-CAM does not require a particular architecture, because we can calculate gradients through any kind of neural network layer we want. The “Grad” in Grad-CAM stands for “gradient.”
The output of Grad-CAM is a “class-discriminative localization map”, i.e. a heatmap where the hot part corresponds to a particular class:
If there are 10 possible output classes, then for a particular input image, you can make 10 different Grad-CAM heatmaps, one heatmap for each class.
Grad-CAM Details
First, a bit of notation:
In other words, y^c is the raw output of the neural network for class c, before the softmax is applied to transform the raw score into a probability.
Grad-CAM is applied to a neural network that is done training. The weights of the neural network are fixed. We feed an image into the network to calculate the Grad-CAM heatmap for that image for a chosen class of interest.
Grad-CAM has three steps:
Step 1: Compute Gradient
The particular value of the gradient calculated in this step depends on the input image chosen, because the input image determines the feature maps A^k as well as the final class score y^c that is produced.
For a 2D input image, this gradient is 3D, with the same shape as the feature maps. There are k feature maps each of height v and width u, i.e. collectively the feature maps have shape [k, v, u]. This means that the gradients calculated in Step 1 are also going to be of shape [k, v, u].
In the sketch below, k=3 so there are three u x v feature maps and three u x v gradients:
Step 2: Calculate Alphas by Averaging Gradients
In this step, we calculate the alpha values. The alpha value for class c and feature map k is going to be used in the next step as a weight applied to the feature map A^k. (In CAM, the weight applied to the feature map A^k is the weight w_k in the final fully connected layer.)
Recall that our gradients have shape [k, v, u]. We do pooling over the height v and the width u so we end up with something of shape [k, 1, 1] or to simplify, just [k]. These are our k alpha values.
Step 3: Calculate Final Grad-CAM Heatmap
Now that we have our alpha values, we use each alpha value as the weight of the corresponding feature map, and calculate a weighted sum of feature maps as the final Grad-CAM heatmap. We then apply a ReLU operation to emphasize only the positive values and turn all the negative values into 0.
Won’t the Grad-CAM Heatmap Be Too Small?
The Grad-CAM heatmap is size u x v, which is the size of the final convolutional feature map:
You may wonder how this makes sense, since in most CNNs the final convolutional features are quite a bit smaller in width and height than the original input image.
It turns out it is okay if the u x v Grad-CAM heatmap is a lot smaller than the original input image size. All we need to do is up-sample the tiny u x v heatmap to match the size of the original image before we make the final visualization.
For example, here is a small 12 x 12 heatmap:
Now, here is the same heatmap upsampled to 420 x 420 using the Python package cv2:
The code to visualize the original small low-resolution heatmap and turn it into a big high-resolution heatmap is here:
import cv2 import matplotlib import matplotlib.pyplot as plt small_heatmap = CalculateGradCAM(class='cat') plt.imshow(small_heatmap, cmap='rainbow') #Upsample the small_heatmap into a big_heatmap with cv2: big_heatmap = cv2.resize(small_heatmap, dsize=(420, 420), interpolation=cv2.INTER_CUBIC) plt.imshow(big_heatmap, cmap='rainbow')
Grad-CAM Implementation
A Pytorch implementation of Grad-CAM is available here.
More Grad-CAM Examples
Grad-CAM has been applied in numerous research areas and is particularly popular in medical images. Here are a few examples:
Yang et al. “Visual Explanations From Deep 3D Convolutional Neural Networks for Alzheimer’s Disease Classification”
Top row is CAM, bottom row is Grad-CAM. Kim et al. “Visual Interpretation of Convolutional Neural Network Predictions in Classifying Medical Image Modalities.”
Grad-CAM visualizations from Woo et al. “CBAM: Convolutional Block Attention Module.” This paper is an example of a trainable attention mechanism (CBAM) combined with a post-hoc attention mechanism for visualization (Grad-CAM).
Caveat: Explainability is Not Interpretability. Any Post-Hoc Attention Mechanism May Not Be Optimal for High-Stakes Decisions
“Explainability” is not the same as “interpretability.”
“Explainability” means that it’s possible to explain how a model made its decision, although the explanation is not guaranteed to make sense to humans, and the explanation is also not constrained to follow any known rules of the natural world. For example, a model may “explain” a boat classification by highlighting the water, or a model may “explain” a “severely ill” classification by highlighting a label within a medical image that indicates that the image was taken while the patient was lying down. The explanation is also not guaranteed to be fair or free from biases.
“Interpretability” means that a model has been designed from the beginning to produce a human-understandable relationship between the inputs and the outputs. For example, logistic regression is an interpretable model, in which the design of the model results in weights that show which inputs contribute more or less to the final prediction. Rule-based methods are also interpretable.
Grad-CAM is a technique for “explainability” meaning that it is meant to explain what a trained CNN did. Grad-CAM does not make a model “interpretable.” While Grad-CAM heatmaps often make sense, they aren’t required to make sense, and they must be used carefully – especially for sensitive applications like medical image interpretation, an area in which Grad-CAM is particularly popular.
If you are working on weakly-supervised localization or weakly-supervised segmentation, Grad-CAM is definitely a useful method. If you are interested in “debugging” a model and gaining more insight into why the model is making certain mistakes, Grad-CAM is also useful. If you are working on an application with sensitive data used for real world, high-stakes decisions, any post-hoc attention mechanism (i.e. any method for making heatmaps that is “tacked on” after a network has been trained) including Grad-CAM is potentially inappropriate, depending on how it is going to be used. If you are interested in interpretable machine learning models, I recommend this excellent paper: Cynthia Rudin “Stop explaining black box machine learning models for high stakes decisions and use interpretable models instead.”
Caveat: Use Vanilla Grad-CAM, Not Guided Grad-CAM
As another caveat to be aware of, the Grad-CAM paper mentions a variant of Grad-CAM called “Guided Grad-CAM” which combines Grad-CAM with another CNN heatmap visualization technique called “guided backpropagation.” I discuss guided backpropagation in this post and this post. The short summary is that recent work by Adebayo et al. and Nie et al. suggests that guided backpropagation is performing partial image recovery and acting like an edge detector, rather than providing insight into a trained model. Therefore, it is best not to use guided backpropagation.
The good news is that the vanilla Grad-CAM method discussed in this post (i.e., Grad-CAM without guided backpropagation) passes Adebayo et al.’s sanity checks and is a great option to use.
Summary
- Grad-CAM is a popular technique for creating a class-specific heatmap based off of a particular input image, a trained CNN, and a chosen class of interest.
- Grad-CAM is closely related to CAM.
- Grad-CAM is compatible with any CNN architecture as long the layers are differentiable.
- Grad-CAM can be used for understanding a model’s predictions, weakly-supervised localization, or weakly-supervised segmentation.
- Grad-CAM is a method for explainability, not interpretability, and therefore should be used with caution in any sensitive domain.
- Vanilla Grad-CAM is a better choice than Guided Grad-CAM.
About the Featured Image
The featured image is modified from Figures 1 and 20 of the Grad-CAM paper. | https://glassboxmedicine.com/2020/05/29/grad-cam-visual-explanations-from-deep-networks/ | CC-MAIN-2022-05 | refinedweb | 2,271 | 50.87 |
I'll come out and admit it, I am a news junkie, have been since I was a teenager. I like to keep up to date with what is going on, across a variety of topics.
For this week's Friday Fun, I'll show you how to create your own news application for the Raspberry Pi using GUI Zero. It will read the latest news from the BBC and Sky News RSS feeds, RSS = Rich Site Summary, and it is a standard method of breaking web data down into a feed that a computer can then work with. We shall read the feeds, and then print the top three headlines to the application.
GUI Zero?
The Raspberry Pi Foundation has a habit of naming there products / software with a Zero at the end (#blamenuttall)
But GUI Zero is the result of a lot of hard work by Laura better known as @codeboom on Twitter.
Laura wanted to create an easier way for children to code user interfaces for their projects. And crikey she has!
Installing the software
On your Raspberry Pi, which is connected to the Internet we will need to open a terminal to do this. Luckily we only need to install two software packages, and they are feedparser, a Python library for working with RSS feeds, and GUI Zero to create our application.
In the terminal type the following
sudo pip3 install feedparser guizero
This shouldn't take too long to download, and once it has finished you can close the terminal.
Coding In Python
Now let's open the Python 3 editor, found in the Programming menu.
As of Friday 23 June 2017, the Raspberry Pi Foundation have bundled Thonny, a simpler and better featured Python editor with Raspbian. This can also be used to write the code for this project. But I am checking to make sure that it fully works!
This is Thonny installed on my Ubuntu laptop
Update 23/6/2017 16:00 BST
Thonny tested and working with this project
I used X forwarding to test Thonny on my Pi 3 using the latest Raspbian image, this meant that I could see the applications, running on my Pi while still sat at my Ubuntu laptop
Update 23/6/2017 13:51 BST
Thonny uses the system installed Python packages, just like we have done to install feedparser using pip3. So it can be used for this project.
It uses system packages by default now!(much less confusing) You can switch to the virtualenv mode and use the package manager.— Ben Nuttall (@ben_nuttall) June 23, 2017
For the purpose of this blog post we shall proceed with the Python 3 Editor.
When the editor opens, immediately click on File >> New to open a new blank document. Then click on File >> Save and call the file newsround.py. Remember to save your work often!
Our first line of Python code is something new. It will be used later to tell the Python code where to find the Python3 interpreter, enabling our application to work outside of the Python editor.
#!/usr/bin/env python3
Now lets import the libraries that will make this project work. First we import feedparser used to read the news feeds from the websites.
import feedparser
Then we import GUI Zero, but we selectively import the classes that handle creating an application (app), working with text, working with images, and capturing push button input.
from guizero import App, Text, Picture, PushButton
Now lets create two objects, these are dictionaries. Dictionaries use a keyword and value to store information.
Our two dictionaries are used to store the RSS news feeds from BBC and Sky. These feeds are refreshed every time the application is opened.
BBCnews = feedparser.parse("") SKYnews = feedparser.parse("")
We now move on to starting the code that will make up the graphical element of the application.
Our "app" is a container. It will store the elements that make up our application (text, graphics, buttons). Our needs a title, and we can specify how big the interface window will be.
app = App(title="News Roundup", width=700, height=450)
An application full of text is boooorrrinng! So lets add some images. GUI Zero can only work with GIF images, and sadly not animated gifs
We create an object called
BBC_Logo and in there we use the Picture class to instruct GUI Zero to place the BBC News logo in the GUI.
BBC_Logo = Picture(app, image="bbcnews.gif")
Lets get some news in the application. We use a for loop, with a range of 3..in other words it will iterate 3 times. The Text that we wish to see in the app is taken from the BBCnews dictionary and we are looking in the entries for the first 3 news items, and then we get their title (headlines). This is then rendered to the application using a size 16 Arial font in black.
for i in range(3): Text(app, text = BBCnews["entries"][i]["title"], size=16, font="Arial", color="black")
We repeat the logo and for loop process for Sky News.
SKY_Logo = Picture(app, image="sky-news-logo.gif") for i in range(3): Text(app, text = SKYnews["entries"][i]["title"], size=16, font="Arial", color="black")
Our app is almost complete, but... we need a way to close the application. Sure we can use the X in the top right of the window, but come on we can do better than that!
Our Close object is a PushButton that will send a command to the application. This command is destroy a rather brutal way of saying "Please close the application, I have read the headlines." We also give the button some text to describe its function.
Close = PushButton(app, command=app.destroy, text="Close News")
Our final line of Python instructs the application to display all of the work that we have done in the application.
app.display()
Complete Code Listing
Your code should look like this.
#!/usr/bin/env python3 import feedparser from guizero import App, Text, Picture, PushButton BBCnews = feedparser.parse("") SKYnews = feedparser.parse("") app = App(title="News Roundup", width=700, height=450) BBC_Logo = Picture(app, image="bbcnews.gif") for i in range(3): Text(app, text = BBCnews["entries"][i]["title"], size=16, font="Arial", color="black") SKY_Logo = Picture(app, image="sky-news-logo.gif") for i in range(3): Text(app, text = SKYnews["entries"][i]["title"], size=16, font="Arial", color="black") Close = PushButton(app, command=app.destroy, text="Close News") app.display()
Give it a go!
Run your code, in the Python 3 Editor (IDLE) click on Run >> Run Module and you will see your application appear on screen.
If you are using Thonny, click on the Green "play button" arrow to start the code.
Well done you have made your own application using GUI Zero!
Bonus Content
Running the application from inside Python 3 Editor or Thonny is cool! But what is even cooler? Running the application on it's own!!!
We have already done some of the work for this, remember the first line of code?
#!/usr/bin/env python3
Well that tells our application where to look for the Python 3 interpreter. So now all we need to do is make our application code executable. To do this we need to use a Terminal, navigate to where you saved the neswround.py file and enter this command to modify the file to become executable.
chmod +x newsround.py
Now you can run the command by typing.
./newsround.py
You can also make your own desktop shortcut that will call the application by double clicking on an icon, and that is a project that you can research and try for yourself :D
What did we accomplish?
We made an application, in 14 lines of Python code that
- Parsed RSS news feeds
- Saved the data to dictionaries
- We used a key to retrieve values from the dictionaries
- We used a for loop to automatically retrieve the first 3 entries in the dictionaries
- We created a button to close our application
Great work everyone!
Note to the BBC and Sky
Hi there, thanks for reading this far!
The use of your logos is for a purely educational project, no profit or mis-representation has been, or will be derived from this project. It is merely an educational and fun project for those learning to code to reference. | http://bigl.es/friday-fun-get-the-news-with-rss-and-gui-zero/ | CC-MAIN-2018-09 | refinedweb | 1,402 | 72.26 |
Bash::Completion - Extensible system to provide bash completion
version 0.008
## For end users, in your .bashrc: ## . setup-bash-complete ## ## Now install all the Bash::Completion::Plugins:: that you need ## ## For plugin writters, see Bash::Completion::Plugin
bash completion should just work when you install new commands.
Bash::Completion is a system to use and write bash completion rules.
For end-users, you just need to add this line to your
.bashrc or
.bash_profile:
. setup-bash-complete
This will load all the installed
Bash::Completion plugins, make sure they should be activated and generate the proper bash code to setup bash completion for them.
If you later install a new command line tool, and it has a Bash::Completion::Plugin- based plugin, all your new shells will have bash completion rules for it. You can also force immediate setup by running the same command:
. setup-bash-complete
To write a new
Bash::Completion plugin, see Bash::Completion::Plugin.
Create a Bash::Completion instance.
Given a plugin name and a list reference of plugin arguments, loads the proper plugin class, creates the plugin instance and asks for possible completions.
Returns the Bash::Completion::Request object.
Checks all plugins found if they should be activated.
Generates and returns the proper bash code snippet to it all up.
Search
@INC for all classes in the Bash::Completion::Plugins:: namespace.
Pedro Melo <melo@cpan.org>
This software is Copyright (c) 2011 by Pedro Melo.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible) | http://search.cpan.org/dist/Bash-Completion/lib/Bash/Completion.pm | CC-MAIN-2016-26 | refinedweb | 253 | 51.04 |
I wanted to experiment a little bit with this game and also send a message telling the user how many guesses they have left, I run into issues with a syntax error when I try to print guesses_left to the user, and even if I remove that it does print you lose if you run out of guesses and codecademy asks me if I put in an else statement.
from random import randint # Generates a number from 1 through 10 inclusive random_number = randint(1, 10) print random_number guesses_left=3 while guesses_left > 0: guess=int(raw_input("Your guess: ")) if guess == random_number: print "You win!" break elif guess != random_number: print "You've used one guess, you have" guesses_left "guesses left." guesses_left -= 1 else: print "You lose."
this is the first experience with coding I've ever had, so any help is greatly appreciated thank you. | https://discuss.codecademy.com/t/8-your-own-while-else/14581 | CC-MAIN-2018-26 | refinedweb | 143 | 65.35 |
Major problems with HashSet
Christopher Simmons
Greenhorn
Joined: Feb 18, 2007
Posts: 5
posted
Feb 18, 2007 13:28:00
0
Hello all. I'm new here and I had nowhere else to go! Hopefully some of you can help me. I have a
HashSet
that will work at times and won't work at others! Here's the deal:
I have a public class called Developer that has two instance variables:
private
String
developerName;
private static
HashSet
<Developer> masterCollection = new
HashSet
<Developer>();
developerName is simply the name of the developer and masterCollection is a set off ALL developers that has ever been created w/o duplicates.
IMPORTANT: I have overridden both the equals and hashcode methods. I have the hashcode method returning the hashcode for the developer's name. My equals method checks to see whether two developer names are spelled exactly the same. I knew that both of those methods should be coded hand in hand.
Now... in a
test
class I wrote, I would create new Developers with names as parameters as it is mandatory for this function. When I created two or more developers with the same exact name, the test class would detect that it was already in the set. That's all fine and good.
BUT!!! I also have a method called rename(String name) that simply renames the name of the developer. Nothing more, nothing less. This is where the trouble comes in.
When I do a print out of what is in the set, the change in name shows up correctly in place of what it was called before, but when I create a new Developer object with the name of a Developer object I just renamed, there ends up being TWO of those objects in the set! It ends up going through! This only happens with renamed objects! Even when I see that their hashcodes are the same! Also of mention, I just happen to run a contains() method, using the set, on the Developer object I just renamed and it returns FALSE, even though a print of the set says otherwise. If it's false that the object is not in the set, then why when I print the set, does the new name of the developer show up???
Why is this happening?? Do you think that because my hashcode() method searches for the Developer's name, the set works incorrectly when renamed? This is really stalling progress as I need this to push forward with the rest of the program. Your help is GREATLY appreciated! Thanks in advance. I will frequent back in order to respond to any questions you may have for me.
[ February 18, 2007: Message edited by: Bear Bibeault ]
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24039
13
I like...
posted
Feb 18, 2007 13:50:00
0
Hi Christopher,
Welcome to JavaRanch!
Story time:
Imagine you are a librarian in an odd sort of library. You keep books in alphabetical order. There's an "A" shelf, a "B" shelf, a "C" shelf... and a "Z" shelf.
The odd part is that the books in your library are printed with that newfangled e-ink, the kind that can be changed electronically.
So the first day, you get a shipment with 100 books. You sort them in alphabetical order and put each one on the right shelf. There's about 4 books on each shelf. One book is the 1907 children's title, "Mumford Monkey's Mom is Missing". Not surprisingly, you file this on the "M" shelf.
While you sleep, the publisher decides that since no-one has actually read Mumford in 70 years, all the existing copies should be re-programmed to be copies of the wildly popular new children's book, "Albert Alligator's Apple Adventure". They accomplish this by wireless Internet, without bothering you about it.
The next day, someone comes in bright and early and asks for a copy of "Albert". You go to the "A" shelf to look for it. But it ain't there, is it?
It's on the "M" shelf.
You have to turn your customer away, as you can't find a copy.
Later you get another shipment of book, including a copy of "Albert", which you file on the "A" shelf. Then you do the nightly inventory, and, surprise! You find that you have
two
copies of "Albert," one where it belongs, and one out of place.
The end.
OK, now. Hopefully you understand the parallel to your current situation. The objects used as keys in a
HashSet
or
HashMap
can't just change their hashcodes while they're in the set/map, or the data structures of the set/map are immediately corrupted. The proper way to do things is to remove the object from the collection, change the hashcode (i.e., the name) and then put it back in the collection. You could embed this logic in the setName() method, if you'd like, or provide a st.atic "rename()" method and provide no other way to change the name.
[Jess in Action]
[AskingGoodQuestions]
Christopher Simmons
Greenhorn
Joined: Feb 18, 2007
Posts: 5
posted
Feb 18, 2007 16:22:00
0
Thanks
alot
, Ernest!! I will try this out. If I don't respond, know that your guidance worked and your wisdom is strong!
I agree. Here's the link:
subject: Major problems with HashSet
Similar Threads
HashSet issue
HashSet and Equals and HashCode
Sets (Universal, Subsets, Union)
K&B - Erratum ?
Doubt in kathy sierra about hashcode method
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/382068/java/java/Major-problems-HashSet | CC-MAIN-2013-20 | refinedweb | 946 | 73.07 |
Answered by:
problem with calling C DLL from C# - getting "NULLReferenceException was unhandled"
Question
Hi,
I'm trying to call a C DLL from C#. I know this is a common question and there's lots of links out there. I've looked through them and still run into the same questions. First my code that's creating the problem:
Here's an excerpt from my DLL with hopefully the relevant code needed to interpret my problem:
typdef unsigned int uint; __declspec(dllexport ) int __cdecl passBackUINT32Test1(uint mydata[], double *timepassed) { __int64 t1,t2; t1=timeit(); for (int i=0;i<1024;i++) { mydata[i]= (uint) i; } t2=timeit(); *timepassed = (1./2.194E3)*(t2 - t1); // in microseconds; using cpu clock frequency for conversion return 1; }
My C# excerpt is here:
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Diagnostics; namespace CallingCplusDLLfromCsharp { public class BenchmarksDLLImports { [DllImport("BenchmarkingThroughDLLInterface.dll" , EntryPoint="passBackUINT32Test1" , CallingConvention = CallingConvention.Cdecl)] public static extern Int32 passBackUINT32Test1(UInt16[] mydata, ref double outputTimePassed); } public class Program { static void Main(string [] args) { Stopwatch st = new Stopwatch(); UInt16[] myarray = new UInt16[1024]; Int32 ret; double outputTimePassed = new double (); Console.WriteLine("Going in!" ); st.Start(); ret = BenchmarksDLLImports.passBackUINT32Test1(myarray, ref outputTimePassed); st.Stop(); Console.WriteLine("Time Elapsed = {0}\n" , st.Elapsed.ToString()); Console.ReadLine(); } } }
Now I actually get my runtime error on the Console.WriteLine statement:
"NULLReferenceException was unhandled"
However, I'm pretty sure the problem is the DLL call before it, since I can execute "st.Elapsed.ToString()" in the Watch window just fine.
I have a couple questions, although they might be the same question!
1) What am I doing wrong above?
2) And whether or not I'm setting up the DLL call portion correctly, when does one need to use the Marshal class? I found this PDF link called "Calling C Library DLLs from C#" which gives some nice examples of passing scalars and arrays, but only saw the Marshal class used with structures (structs). Most of my application involves passing int arrays and double arrays into DLL functions for processing and pass back. Do I use Marshal/fixed blocks for this? If so, I don't get why that article doesn't need them.
Thanks in advance for any help on this.
Best,
Hyped
Answers
All replies
Thanks AbdElRaheim, that indeed was the problem.
I'm wondering if you have any comments in regard to my second question. That is, at what times do I need to fix/marshal arrays that I feed into DLLs for processing and passback? My confusion arises from the fact that the above PDF link, which looks like a reputable writeup from an Algorithm group, shows many examples of passing arrays into DLLs without the Marshal class, nor with and fixed {} blocks.
Thanks again though for you response to the error in my code.
Best,
Hyped
Marshalling happens automatically. Use the marshal class for special cases. Example would be if you have a method with the signature below.
void UnmanagedSomething ( IntPtr data, int length);
You can use the marshal class to copy a structure and then pass a pointer in. If you had an array you could use the fixed keyword and then get a pointer to the start of the array and pass that into the method. The p/invoke method that you have can be rewritten in several ways. In most cases you dont need to use the marshal class.
Default Marshaling Behavior | https://social.msdn.microsoft.com/Forums/en-US/0d55d5c0-7e52-465b-be12-e4520e351e8c/problem-with-calling-c-dll-from-c-getting-quotnullreferenceexception-was-unhandledquot?forum=clr | CC-MAIN-2020-45 | refinedweb | 573 | 57.16 |
Hi, I was experimenting with the various options available, but I couldn’t manage to set continuous color scale on a single line of a line chart. Discrete colors worked fine. I would appreciate if someone could point me the right direction regarding how to use x or y (in this case year or life expectancy) or any other values to set continuous color if it is possible. I pasted a basic line chart sample from the documentation:
import plotly.express as px df = px.data.gapminder().query("country=='Canada'") fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada') fig.show()
In addition I also posted the same question on stackoverflow earlier if someone wants to grab the points for answering it. | https://community.plotly.com/t/ploty-continuous-color-scale-in-line-chart/47089 | CC-MAIN-2022-21 | refinedweb | 126 | 57.16 |
Rotating Rigidbodies with PID Controllers
A demo repository for an article on rotating Rigidbodies with PID controllers.
The contents of this README are the same as the article on my website. If you came from the website, you can just download or clone the repo and open the project in Unity to see the demo.
What is a PID controller?
A PID controller is a type of control system that uses past values, current values, and estimated future values to drive a system towards a target value. We’re going to create a PID controller and use it to drive a Rigidbody towards a desired angle.
The inspiration for this article came about when I was doing research on the best ways to rotate a Rigidbody and I stumbled upon a forum post that mentioned using a PID controller. The person also linked an example project which most of the code below is based off of and after I saw what it did I decided to learn more about PID controllers myself and eventually I decided to write this article to help the next person that stumbles upon this same scenario that wants a detail explanation and guide.
I’d highly recommend checking out the above linked forum post but I’m going to go over the code and expand on it a bit and an even more complex example can be seen in this repo.
Now for a quick overview of PID controllers:
The P in PID is for proportional error. The proportional error is the flat amount that we are from the target. For example, let’s say that your Rigidboy is at 50 degrees and the goal is 90 degrees. This would mean that the proportional error is 40 degrees since that’'s the difference between the two. As with the other two values, this is also multiplied by a gain factor to control how much contribution it has to the overall output value.
The I in PID is for the integral error. The integral error is a sum of the proportional values. An integral error can be helpful if you have an opposing force acting on your Rigidbody. Image a situation where you’re trying to rotate your Rigidbody to a specified angle but there’s force pushing the Rigidbody in the opposite direction. The force might not be big so your Rigidbody might get to 85 out of 90 degrees with just proportional errors but the opposing force is always pushing you back by 5 degrees and your Rigidbody will be stuck at 95 degrees. The integral error comes in handy here because it keeps a running total of proportional values and will apply a bigger output if the desired output is not being achieved.
The D in PID is for the derative error. The derative error is used to provide a way of dampening the motion of the body. This is used to slow down the motion so that we don’t have to do too much over/under correction.
Each of the errors are multiplied by a constant, called a gain, before they are finally all added together and returned as the output. These gain values are used to control how much that error contributes to the overall output. For our example we’ll just experiment with the gain values in the inspector as our use is not very complicated.
If this seems like a bunch of mumbo jumbo it’s ok because it was to me too but stick around for the examples as maybe it’ll click in the context of Rigidbodies.
Project Setup
To set up the project for this article we’re going to create a new 3D game add a spaceship model I got from a Kenney kit. Next we add a Rigidbody to the model which we’ll apply the torque to.
Now we need to create two scripts:
PID and
ShipController. The PID script is where we’re going to put all of the logic while the ShipController is going to use the values output by the PID controller to rotate the ship.
Let’s open up the
PID script and create the controller.
Creating the PID Controller
In the
PID script we don’t need to do anything on
Start or
Update so we can just delete those and we should be left with the following:
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// A simple PID controller component class. /// /// </summary> public class PID : MonoBehaviour { }
The first thing we want to set up are the properties we need:
We need the gain values discussed earlier, The proportional, integral, and derivative each need their own gain value. Values can be set to 0 to omit it from the final output (outside the scope of this tutorial).
We need to set up the variables to track the current proportional, integral, and derative error values.
We need to set up a variable to keep track of what the error was the last time the output was requested. This is used by the derivative error to calculate the rate of change.
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// A simple PID controller component class. /// /// </summary> public class PID : MonoBehaviour { /// <summary> /// This is completely optional and is used just to help you idenfity what this PID /// script is for as you can use multiple PID scripts per game object to control /// various values. /// </summary> public string name; /// <summary> /// The gain of the proportional error. This defines how much weight the proportional /// error has in the final output. /// </summary> public float Kp = 1.0f; /// <summary> /// The gain of the integral error. This defines how much weight the integral /// error has in the final output. /// </summary> public float Ki = 0.0f; /// <summary> /// The gain of the derivative error. This defines how much weight the derivative /// error has in the final output. /// </summary> public float Kd = 0.1f; /// <summary> /// Tracks the current values of the proportional, integral, and derative errors. /// </summary> private float P, I, D; /// <summary> /// Used to keep track of what the error value was the last time the output was requested. /// This is used by the derivative to calculate the rate of change. /// </summary> private float previousError; }
Believe it or not we’re almost done with our simple PID controller here. We just need to create the method that takes in the current error and calculates the output which we pass to
AddTorque in the
ShipController script.
/// <summary> /// Returns the amount of torque that should be applied to the ship this frame /// to reach the target rotation. /// </summary> /// <returns> /// The output of the PID calculation. /// </returns> /// <param name="currentError">How far away the body is from the target rotation angle.</param> /// <param name="deltaTime">The delta value from FixedUpdate.</param> public float GetOutput(float currentError, float deltaTime) { // First we set the proportional to how how far we are from the target value. P = currentError; // Since the integral is the sum of the proportional error over time we have // to multiply the propertional by the delta time and then add it on to the // current I value. I += P * deltaTime; // Set the derative to the rate of change of error by subtracting the current // error from the previous error to get the difference and then dividing it by // the amount of time it took to get to this change. D = (P - previousError) / deltaTime; // Now we set the previous error to the current error to prepare for the next // time the output is requested. previousError = currentError; // Finally calculate the output using the values above multiplied by their gain. return P*Kp + I*Ki + D*Kd; }
And that’s it for our PID class. If you’re still a bit confused don’t worry we still have example to get to. Also don’t expect to fully understand PID controllers from this tutorial, but instead you should understand how to use them for tasks such as rotating Rigidbodies. If you really want to learn more about PID controllers there are great videos on the topic that helped me grasp the concept.
Instancing the PID Script
Next we’re going to make the script that gets attached to our ship and controls the Rigidbody using the PID output but before that we should attach our PID script to the ship.
So back out in the inspector we click on our ship game object and drag over the PID script twice. You read it right we need two instances of the PID class because we want to control the angle of the Rigidbody but also the angular velocity so that we can avoid abrupt changes to the angular velocity when applying the torque to change the angle.
This is also where the
Name property in the PID script comes in handy. We can better distinguish them by naming the first one “Angle Controller” and the second one “Angular Velocity Controller”.
We’re going to leave the public variables alone for now until we set up our ship and have a working demo.
Ship Controls
Now to test our PID script we have to actually use it to change our ship’s rotation.
Same as before, open up the ShipController script and delete the
Start and
Update methods since we won’t be using them and make sure you just have the following:
/// <summary> /// Used to control the ship and simulate the effects of the PID script. /// </summary> public class ShipController : MonoBehavious { }
First things we want to do here is set up the variables we’ll need:
We need a public variable that defines our turn speed. This will affect how fast we get to our final angle destination.
We also need a public variable that defines the maximum angular velocity for our Rigidbody. This will help us avoid some crazy spins.
Next we need a private variable that holds the current angle we want to rotate to.
Also two more private variables, one for each of our scripts attached to the game object.
Finally one more private variable that will hold the calculated torque to pass to
AddTorque.
/// <summary> /// Used to control the ship and simulate the effects of the PID script. /// </summary> public class ShipController : MonoBehavious { /// <summary> /// The speed at which the ship will turn at. /// </summary> public float turnSpeed = 500.0f; /// <summary> /// The maximum angular velocity of the Rigidbody. /// </summary> public float maxAngularVelocity = 20.0f; /// <summary> /// The current angle to turn towards. /// </summary> private float targetAngle; /// <summary> /// A reference to the PID instance for the angle. /// </summary> private PID angleController; /// <summary> /// A reference to the PID instance for the angular velocity. /// </summary> private PID angularVelocityController; /// <summary> /// The torque to apply to the Rigidbody. /// </summary> private Vector3 torque; /// <summary> /// A reference to the Rigidbody component. /// <summary> private Rigidbody rb; }
When the ship is initialized we:
- Get the reference to the Rigidbody so we can get the angular velocity and apply the torque later.
- Get the references to both PID controller instances.
- Set the Rigidbody’s max angular velocity to the value set by the user in the public variable.
- Set the initial target angle to the Rigidbody’s Y Euler angle.
void Awake() { // Get the reference to the Rigidbody which will be used when we apply the torque. rb = gameObject.GetComponent<Rigidbody>(); // Get the references to the PID instances so we can use them as controllers. angleController = gameObject.GetComponents<PID>()[0]; angularVelocityController = gameObject.GetComponents<PID>()[1]; // Set the maximum angular velocity of the Rigidbody and set the initial value of the // targetAngle to the Y Euler angle. We do this so that we can easily make adjustments // by just adding or subtracting from it. rb.SetMaxAngularVelocity(maxAngularVelocity); targetAngle = transform.eulerAngles.y; }
Now it’s time for the fun stuff, the actual rotation and usage of the PID controllers. In the FixedUpdate we:
- Get the fixed delta time because we need to pass it to the PID controllers.
- Adjust the value of the
targetAngledepending on the user input, the turn speed, and the fixed delta time.
- Get the angle error (the difference between our current angle and the angle we want to turn to) by using
DeltaAngle. Then we pass this value to the
angleControllerto get the torque that we should apply this frame.
- Get the negative of the angular velocity and pass this to the
angularVelocityControllerto get the torque that we should apply this frame.
- Lastly add the two torques together and apply it to the Rigidbody.
void FixedUpdate() { // Get the fixed update delta time. float dt = Time.fixedDeltaTime; // So currently the targetAngle contains the current rotation of the ship. // Now we need to set the targetAngle to a combination of the user's horizontal // input, the turn speed, and fixed delta time. targetAngle += Input.GetAxis("Horizontal") * turnSpeed * dt; // The angle controller drives the ship's angle towards the target angle. // This PID controller takes in the error between the ship's current rotation angle // and the target rotation angle as input, and returns a torque magnitude. // We use `DeltaAngle` to find the shortest difference between the two angles in degrees // which is what we need to pass to the PID controller. float angleError = Mathf.DeltaAngle(transform.eulerAngles.y, targetAngle); float torqueCorrectionForAngle = angleController.GetOutput(angleError, dt); // The angular velocity controller drives the ship's angular velocity to 0. // This PID controller takes in the negated angular velocity of the ship and returns // a torque magnitude. float angularVelocityError = -rb.angularVelocity.y; float torqueCorrectionForAngularVelocity = angularVelocityController.GetOutput(angularVelocityError, dt); // The total torque from both controller is now applied to the ship. If the gains // are set correctly then the ship should rotate to the correct angle and stay there. torque = transform.up * (torqueCorrectionForAngle + torqueCorrectionForAngularVelocity); rb.AddTorque(torque); }
At this point you should add the
ShipController script to the Ship GameObject and your ship should look something like this in the inspector:
The Gain Values
Now we have to go back to the inspector and fill out the gains for both PID controllers. This can be done by running the scene and tweaking the values until you find a nice combination or you can use a set of values below highlighted by the forum poster:
Critically Damped Controls
These gain values result in a control system that’s critically damped, or at least very close to it. This means that there is the smallest amount of oscillation, which is probably not even noticable. So in our example that means that when the ship is turned, it will stay where it is.
Angle Controller
Angular Velocity Controller
Fast Controls
These gain values result in a control system that has fast controls meaning that the turning is very responsive and quick in comparison to other gain values.
Angle Controller
Angular Velocity Controller
Spongy Controls
These gain values result in a control system that has slow, less responsive controls.
Angle Controller
Angular Velocity Controller
Springy Controls
These gain values result in a control system that has springy controls so when you turn the ship you’ll notice that it overshoots the target angle and bounces back to the correct angle.
Angle Controller
Angular Velocity Controller
Note that the values are for a Rigidbody without a collision shape. You’ll need to tweak your values if you add a collision shape.
Conclusion
All that’s left now is to play the scene and try turning the ship with the left/right arrow keys and seeing it in action. Feel free to try out different combinations of PID values while the game is running to find the perfect combination for you.
Also check out the example in the repo for a more complex demo. | https://unitylist.com/p/103l/Unity-pid-with-rigidbodies | CC-MAIN-2021-31 | refinedweb | 2,606 | 61.67 |
Details
- Type:
Bug
- Status: Closed
- Priority:
P2: Important
- Resolution: Done
- Affects Version/s: 5.3.2
- Fix Version/s: 5.5.0 Alpha
- Component/s: Quick: Controls 1
- Labels:None
- Environment:Debian testing, Qt 5.3.2 installed from Debian's package repository
Description
I tried the simple example at with no success. The example builds and runs without errors, but I expect the program to create a window, which doesn't happen. The program just sits there doing nothing (gdb shows that all threads are waiting in poll(), I'll attach the backtrace).
My code is in three files: test.qml, test.cc and test.pro. Here's test.qml:
import QtQuick.Controls 1.2 ApplicationWindow { title: "My Application" Button { text: "Push Me" anchors.centerIn: parent } }
test.cc:
#include <QApplication> #include <QQmlApplicationEngine> int main(int argc, char *argv[]) { QApplication app(argc, argv); QQmlApplicationEngine engine("test.qml"); return app.exec(); }
test.pro:
CONFIG += \ debug \ QT += \ qml \ widgets \ SOURCES += \ test.cc \ | https://bugreports.qt.io/browse/QTBUG-43906 | CC-MAIN-2021-39 | refinedweb | 160 | 53.58 |
HI,
I working on this java project where I have to construct an applet. The applet has to be an Ellipse thats is filled with a color other than white and it has to resize when the window is minimized. Here is what I have so far... If there is anyone who can help me with this problem I would gladly appreciate it as this project is due tomorrow..Thnx in advance.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
public class EllipseApplet extends Applet
{
public void paint (Graphics g)
{ // recover Graphics2D
Graphics2D g2 = (Graphics2D)g;
//Construct an Ellipse and draw it.
Ellipse2D.Double easterEgg = new Ellipse2D.Double(5, 10, 20, 30);
g2.setColor(Color.blue);
g2.fill(easterEgg); // fill the ellipse in blue
}
}
However I keep getting an error when I compile the program and I don't quite understand it.
This is the error message;
H:\EllipseApplet.java:13: cannot resolve symbol
symbol : variable Color
location: class EllipseApplet
g2.setColor(Color.blue);
^
1 error
Tool completed with exit code 1
The strong do as they will and the weak suffer what they must.It is a choice. You don\'t choose to do the right thing all the time. You do the right thing all the time. Wining is a habit, unfortunately so is losing.
Originally posted here by Big_Bolo
H:\EllipseApplet.java:13: cannot resolve symbol
symbol : variable Color
location: class EllipseApplet
g2.setColor(Color.blue);
^
It's pretty straightforward, it's complaining about your use of Color.blue, primarily because java.awt.Color isn't imported at the top of your file. If you add the import it will probably work Chsh
I didn't even know I had to import java.awt.Color. I thought about it but I didn't write because it wasn't mentioned in the java book I'm reading. I'm new with programming in java. Thnx I really appreciate your help.
easy way out:
import java.awt.*;
import java.applet.*;
etc. etc.
...This Space For Rent.
-[WebCarnage]
ok.
I fixed the error and the program is running fine. Now I'm trying to figure out how to use the getWidth() and getHeight() methods to centre my ellipse in the applet and have it resize itself when I resize the window. If u can help with this two methods by looking at the code I would really appreciate. I very new at programming, there is still a lot of stuff that I don't know.
Thnx in advance.
Forum Rules | http://www.antionline.com/showthread.php?261431-Need-Help-with-java-project-Please.. | CC-MAIN-2016-26 | refinedweb | 429 | 68.97 |
Source Code File REST API Tutorial
This chapter provides a brief tutorial that demonstrates how to use the InterSystems IRIS® Source Code File REST API by a series of examples. It contains the following sections:
Getting Information about the InterSystems IRIS Server
Getting the Source Code Files Defined in a Namespace
Creating a New File in a Namespace or Updating an Existing File
API Basics
The API used by Atelier to access InterSystems IRIS source code files uses the REST architectural style. REST is named from “Representational State Transfer.” The InterSystems IRIS Source Code File REST API, like many REST APIs, uses the HTTP GET, POST, PUT, DELETE, and HEAD methods and uses JSON for incoming and outgoing message bodies.
To call an API method, you need to know the following:
HTTP method—which is one of the following: GET, POST, PUT, DELETE, or HEAD.
HTTP headers—provide context information for the call. The HEADERS used in this API include:
Authorization, which provides access to the server. Unless you have installed your server with minimal security, you need to provide a username and password to access the API.
Content-Type application/json, which specifies that the inbound payload is provided in JSON. You must specify this header for all POST and PUT methods.
If-None-Match, which allows a GetDoc or PutDoc call to check if the source code file was modified since it was last accessed.
URL—The URL consists of the following parts:
http://
server-name:port-number/—In this chapter, we assume that InterSystems IRIS is running on the local server and is using port 52773.
api/atelier/—This is defined by the web application that has the %Api.Atelier dispatch class.
URL part that identifies the method and target. This part can include fixed text and text that you specify to identify the namespace, document name, or type.
For example, the URL part that identifies the GetDocNames method is v1/namespace/docnames/. The complete URL for this method getting the documents from the MYNS namespace would be:
The URL part that identifies the GetServer method is an empty string, so the complete URL for GetServer is:
URL parameters—modifies the call. If the API method has URL parameters, they are described in the reference section.
Inbound JSON payload—format of the inbound message for POST and PUT methods.
Outbound JSON payload—format of the outbound message returned by the HTTP method.
Getting Information about the InterSystems IRIS Server
Typically, the first REST call you’ll make is to the GetServer method, which returns information about the InterSystems IRIS Source Code File REST API version number and the namespaces available on the server.
GET
This call returns the following JSON message:
{ "status": { "errors": [], "summary": "" }, "console": [], "result": { "content": { "version": "IRIS for Windows (x86-64) 2018.1.1 (Build 515U) Mon Feb 5 2018 08:24:13 EST", "id": "98E1697E-13F9-4D6A-8B73-827873D1D61C", "api": 2, "features": [ ... ], "namespaces": [ "%SYS", "USER" ] } } }
All InterSystems IRIS Source Code File REST API methods that return JSON messages use the same general format:
status errors—typically the InterSystems IRIS Source Code File REST API returns errors as HTTP status codes. This field is used under some unusual conditions and this element contains the InterSystems IRIS %Status value, which may contain the text for multiple errors.
status summary—contains a summary of the status errors.
console—contains the text that InterSystems IRIS would display on the console for this operation.
result—contains the results of the method.
The GetServer method returns information about the server in the “result” element. The result element contains one value “content”, which contains:
version—contains the version string of the instance of InterSystems IRIS running on the server.
id—contains the instance GUID of InterSystems IRIS.
api—specifies the version number of the InterSystems IRIS Source Code File REST API implemented in this version of InterSystems IRIS.
features—indicates the features that are enabled on this instance.
namespaces—lists the namespaces defined on the InterSystems IRIS server.
The GetNamespace method returns information about the specified namespace, including the databases that are mapped to the namespace and a hash for each database. The hash is useful for improving efficiency of communication with the server. But you can get the information about the source code files in the namespace with just the namespace information returned by GetServer.
Getting the Source Code Files Defined in a Namespace
To get the information about the source code files in a namespace:
First you get the names of the files with the GetDocNames method.
Then you get the contents of one file with the GetDoc method or you can get the contents of multiple files with the GetDocs method.
If you want to improve the network efficiency of your application, you can keep a local cache of the names and contents of the source code files and use the GetModifiedDocNames method to get only the names of the source code files whose contents have changed or use the GetDoc method with the If-None-Match HTTP header.
The GetDocNames method returns the names of all of the source code files in all databases mapped to the namespace.
{ "status": { "errors": [], "summary": "" }, "console": [], "result": { "content": [ { "name": "%Api.DocDB.cls", "cat": "CLS", "ts": "2016-08-03 20:01:42.000", "upd": true, "db": "IRISLIB", "gen": false }, ... { "name": "EnsProfile.mac", "cat": "RTN", "ts": "2003-09-19 13:53:31.000", "upd": true, "db": "INVENTORYR", "gen": false }, ... { "name": "xyz.mac", "cat": "RTN", "ts": "2016-08-11 15:05:02.167", "upd": false, "db": "INVENTORYR", "gen": false } ] } }
The following GetDoc call returns the contents of the xyz.mac file:
This call returns:
{ "status": { "errors": [], "summary": "" }, "console": [], "result": { "name": "xyz.mac", "db": "INVENTORYR", "ts": "2016-09-14 14:10:16.540", "upd": false, "cat": "RTN", "status": "", "enc": false, "flags": 0, "content": [ "ROUTINE xyz", "xyz ;", " w \"hello\"" ] } }
Creating a New File in a Namespace or Updating an Existing File
To create a new file in a namespace or update an existing file, you use the PutDoc method. For example, the following REST call creates a new xyz.mac source code file in the INVENTORY namespace or, if the xyz.mac file exists, this call replaces the original definition of the file with the new one. If you are updating a new file, you must specify either the HTTP header If-None-Match to identify the current version of the file or the ?ignoreConflict=1 URL parameter to bypass version checking. See PutDoc in the reference section for details.
PUT
You should specify the Content-Type application/json and the following JSON message:
{ "enc": false, "content": [ "ROUTINE xyz", "xyz ;", " w \"hello\"" ] }
The call returns the following JSON message. It shows that the source code file has been created in the INVENTORYR database, which is the default database for routines in the INVENTORY namespace.
{ "status": { "errors": [], "summary": "" }, "console": [], "result": { "name": "xyz.mac", "db": "INVENTORYR", "ts": "2016-09-14 14:10:16.540", "upd": false, "cat": "RTN", "status": "", "enc": false, "flags": 0, "content": [] } }
If you are updating or creating a binary file, specify a true value for enc and include the binary contents as an array of blocks of the base64 encoding of the binary value.
Compiling a File
The Compile method compiles the source code files specified by name in the incoming JSON array. For example, to compile xyz.mac, POST the following:
with the following JSON message:
["xyz.mac"]
The method returns:
{ "status": { "errors": [], "summary": "" }, "console": [ "", "Compilation started on 08/14/2016 15:25:20 with qualifiers 'cuk'", "xyz.int is up to date. Compile of this item skipped.", "Compilation finished successfully in 0.008s." ], "result": { "content": [] } }
For some source code files, such as classes, Compile returns storage information in the returned content.
Deleting a File
The DeleteDoc method deletes the file specified in the URL. The DeleteDoc method has the same URL as the GetDoc method except that you use the HTTP Delete method instead of the Get Method. To delete xyz.mac, make an HTTP DELETE request with the URL:
The Delete method returns the following JSON message:
{ "status": { "errors": [], "summary": "" }, "console": [], "result": { "name": "xyz.mac", "db": "INVENTORYR", "ts": "", "cat": "RTN", "status": "", "enc": false, "flags": 0, "content": [] } }
When a file has been deleted, the timestamp, ts, has a value of "" (empty string).
Performing an SQL Query
The Query method performs an SQL query on any InterSystems IRIS database. For example, if your application wants to present the user with a list of InterSystems IRIS roles, it can discover them with the following call:
With the SQL query specified in the incoming JSON message:
{"query": "SELECT ID,Description FROM Security.Roles"}
This call returns the results of the SQL query as JSON in the result content element.
{ "status": { "errors": [], "summary": "" }, "console": [], "result": { "content": [ { "ID": "%all", "Description": "The Super-User Role" }, { "ID": "%db_%default", "Description": "R/W access for this resource" }, ... { "ID": "%sqltunetable", "Description": "Role for use by tunetable to sample tables irrespective of row level security" } ] } }
You can use the Query method to query any table in InterSystems IRIS. For example, the following call queries a table named Sample.Person in a namespace named SAMPLES.
POST {"query": "SELECT Age,SSN,Home_City,Name FROM Sample.Person WHERE Age = 25"}
This call returns:
{ "status": { "errors": [], "summary": "" }, "console": [], "result": { "content": [ { "Age": 25, "SSN": "230-78-7696", "Home_City": "Larchmont", "Name": "DeLillo,Jose F." }, { "Age": 25, "SSN": "546-73-7513", "Home_City": "Gansevoort", "Name": "Klingman,Thelma H." } ] } } | https://docs.intersystems.com/irisforhealthlatest/csp/docbook/DocBook.UI.Page.cls?KEY=GSCF_TUTORIAL | CC-MAIN-2021-10 | refinedweb | 1,567 | 62.68 |
We're in the process of updating our Windows SDKs. The content below relates to our previous version. Please contact our support team if you wish to implement Windows in-app checkouts or licensing.
1Add to project
You should add the
Paddle.lib,
Paddle.dll and header files to your project. Simply add Paddle.lib as a dependency in
Project Properties/Linker/Input/Addition Dependencies in Visual Studio.
2Integration code
To start, you should add
#include "Paddle.h" in your header file. Following this you should also make sure you are using the
PaddleSDK namespace in your class.
using namespace PaddleSDK;
Now you can initialise the SDK and start the licencing process. This should be done as early as possible in your app lifecycle.
You should initialise an instance of the SDK with your keys, found in your vendor dashboard. For example:
auto paddle = Paddle::initSharedInstance("298c1c56fa2c2733220d54fdf211ea49", "503866", "13578"); | https://paddle.com/docs/sdk-setup-windows-cpp/ | CC-MAIN-2018-30 | refinedweb | 149 | 61.43 |
lp:perl5
Branch information
- Owner:
- Registry Administrators
- Status:
- Development
Import details
This branch is an import of the HEAD branch of the Git repository at git://perl5.git.perl.org/perl.git.
Last successful import was 5 hours ago.
Recent revisions
- 52042. By Lukas Mai <email address hidden> 20 hours ago
perlnewmod: more updates
- hyperlink WWW::Mechanize
- direct to metacpan.org, not search.cpan.org
- changes should go in Changes, not README
- mention 'make distcheck'
- mention 'cpan-upload'
- remove paragraph about announcing to the modules list and registering
a namespace
- hyperlink some urls
- 52041. By Father Chrysostomos <email address hidden> on 2016-06-24
[perl #128238] Crash with non-stash in stash
This is a follow-up to e7acdfe976f. Even if the name of the stash
entry ends with ::, it may not itself contain a real stash (though
this only happens with code that assigns directly to stash entries,
which has undefined behaviour according to perlmod), so skip hashes
that are not stashes.
- 52040. By Father Chrysostomos <email address hidden> on 2016-06-24
stash.t: Remove tyrone::slothrop
etc.
Leftovers left behind by e35475de.
- 52039. By Todd Rinaldo <email address hidden> on 2016-06-24
Sync CPAN Locale::Maketext 1.27 with blead
- 52038. By Father Chrysostomos <email address hidden> on 2016-06-23
Fix stupid test in 9uninit
I was wondering why the warnings were being triggered backwards.
Different output handles. Duh.
- 52037. By Father Chrysostomos <email address hidden> on 2016-06-23
Preserve 64-bit array offsets in uninit warnings
This was brought up in ticket #128189.
The main change is that Perl_varname now takes a SSize_t parameter
instead of I32. I changed various other uses of I32 at the same
time in case some code really does have an array with more than
2**31 entries (or whatever the exact number is).
- 52036. By Craig A. Berry <email address hidden> on 2016-06-23
svpeek.t: $? is localized now.
So it's no longer upgraded to PVLV on VMS like it would be if it
had magic from COMPLEX_STATUS.
This is a follow-up to b4514920cd5cabcc.
- 52035. By Aristotle Pagaltzis on 2016-06-23
Module::CoreList: cut TieHashDelta out of everybody’s life
- 52034. By Aristotle Pagaltzis on 2016-06-23
Module::CoreList: prepare for better legibility of upcoming patch
- 52033. By Yves Orton on 2016-06-22
change manisort to produce a more intuitive order
Dictionary sort order on filenames is very counter-intuitive, and
produces surprising sort orders.
What this patch does is sort things so that the following should
always be true:
1. Case insensitive textual order
Eg: Foo and foo and FOO should sort together in ascibetical order
2. Shorter dirs go before longer dirs with a common prefix
Eg: lib/Foo/ should go before lib/Foo-Thing/
3. Base filename goes before dir of the same name
Eg: lib/Foo.pm should sort before lib/Foo/Bar.pm
This also refactors the MANIFEST sort code in Porting/manisort and
Porting/
pod_rules. pm files into Porting/pod_lib.pl
Branch metadata
- Branch format:
- Branch format 7
- Repository format:
- Bazaar repository format 2a (needs bzr 1.16 or later) | https://code.launchpad.net/~registry/perl5/trunk | CC-MAIN-2016-26 | refinedweb | 525 | 66.33 |
Re: Read inboxes of various mailboxes on Exchange Server
- From: "Henning Krause [MVP - Exhange]" <newsgroup.no@xxxxxxxxxxxxxxxxx>
- Date: Thu, 9 Jun 2005 09:14:27 +0200
Hello,
the DAV: is only one of many namespaces. urn:schemas:httpmail is another. So
to access this property you do a PROPFIND with this body:
<?xml version="1.0" encoding="utf-8" ?>
<a:propfind xmlns:
<a:prop>
<hasattachments xmlns="urn:schemas:httpmail:" />
</a:prop>
</a:propfind>
Here is a list of of the WebDAV scheme used by exchange:
To select only unread mails, you must include a WHERE clause in your query:
WHERE "urn:schemas:httpmail:read" = FALSE
To get the attachments, you must use the propietary X-MS-ENUMATTS method
().
And look into this:,
its the WebDAV reference from Microsoft.
Greetings,
Henning Krause [MVP - Exchange]
==========================
Visit my website:
Try my free Exchange Explorer: Mistaya
()
"Frank" <Frank@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:48DBEA9E-ECE5-4E43-BF43-2A0A74E4843A@xxxxxxxxxxxxxxxx
> Thank you very much! Your reply was extremely helpful and I was
> successful
> at sending a query to our Exchange Server to return back data I needed.
> I'm
> still learning some of the properties (if that is what they are called) to
> used in the SELECT statement for obtaining the fields I needed.
>
> I also downloaded your Mistaya program and found it very helpful to see
> all
> the regions and fields that I can obtain when peforming my SELECT query.
> Is
> it correct for me to say that I can't always use DAV: region (i.e. use the
> DAV:propertyname) in my search to get everything from an email? I see
> that
> to check if an email "has attachments", I needed to search on something
> like
> "urn:schemas:httpmail:hasattachments" which brings back True or False. I
> did
> not see a "subject" or "hasattachments", etc... for the properties listed
> under DAV.
>
> Also I could NOT find how to find out how many attachments an email has or
> how to retrieve them using WebDAV. Do you have any examples/links where
> they
> show how to retrieve all the attachments an email has using WebDAV and
> Visual
> Basic 6 (or vbscript that I can translate)?
>
> Thank you again for your time.
>
> Frank
>
> "Henning Krause [MVP - Exhange]" wrote:
>
>> Hello,
>>
>> you can do this with WebDAV.
>>
>> If you have more than one Exchange server, you must first determine the
>> correct Exchange Server. See
>> on how to this.
>>
>> If you have only one server, you can skip that part and access the
>> Mailbox
>> via<alias>
>>
>> If you have multiple languages, then the path of your inbox folder
>> differs.
>> In this case do a PROPFIND on the mailbox root and retrieve the property
>> "urn:schemas:httpmail:inbox". This property contains the url to the inbox
>> folde. (See
>>
>> for more on this topic, including an example).
>>
>> Now that you have the URL, do a SEARCH on that folder (see
>>)
>> and get the emails you need.
>>
>> You say you have all the username/password credentials... You really
>> don't
>> need them. There are two possible ways around this: Grant a special user
>> account the rights "Send As" and "Receive As" on the mailbox store. This
>> way
>> the useraccount you are using has full access to all mailboxes.
>>
>> The other way is to use the administrative root. Use an administrator
>> account and instead of the urls above, use this one:
>><full-dns-name>/MBX/<alias>
>>
>> This url circumvents MAPI access checks and you also have full access to
>> the
>> mailbox.
>>
>> This is far better than to have a ton of passwords lying around.
>>
>> Greetings,
>> Henning Krause [MVP - Exchange]
>> ==========================
>> Visit my website:
>> Try my free Exchange Explorer: Mistaya
>> ()
>>
>>
>> "Frank" <Frank@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
>> news:E3E6BC54-2ACB-4003-B38A-A14D3C3C9F7C@xxxxxxxxxxxxxxxx
>> >I need to create a program in VB6 that read the UNREAD emails located in
>> >the
>> > inbox of several mailboxes. I've been given a list of the mailboxes
>> > names,
>> > alias, username/password. Basically I need to loop through each
>> > mailbox
>> > and
>> > read all the UNREAD email items in the INBOX. For each email I need to
>> > know
>> > the email subject, message body, recipients, sender, and obtain any
>> > attachments. This program will NOT be running on the same machine as
>> > Exchange Server.
>> >
>> > I've been reading many articles on using CDO, CDOEx, recordsets with
>> > ADO,
>> > and using WebDAV. Any help, suggestions, or code examples/links would
>> > be
>> > greatly appreciated.
>> >
>> > Thank you very much for your time,
>> >
>> > Frank
>>
>>
>>
.
- Follow-Ups:
- References:
- Read inboxes of various mailboxes on Exchange Server
- From: Frank
- Re: Read inboxes of various mailboxes on Exchange Server
- From: Henning Krause [MVP - Exhange]
- Re: Read inboxes of various mailboxes on Exchange Server
- From: Frank
- Prev by Date: Re: Read inboxes of various mailboxes on Exchange Server
- Next by Date: Re: Read inboxes of various mailboxes on Exchange Server
- Previous by thread: Re: Read inboxes of various mailboxes on Exchange Server
- Next by thread: Re: Read inboxes of various mailboxes on Exchange Server
- Index(es): | http://www.tech-archive.net/Archive/Exchange/microsoft.public.exchange2000.development/2005-06/msg00036.html | crawl-002 | refinedweb | 823 | 69.92 |
Summary: in this tutorial, you’ll learn how to create a
DataFrame directly from JSON files.
JSON is supported out of the box by many programming languages across various platforms, which makes it one of the most popular way to store datasets.
JSON-based data can be read with Pandas
pd.read_json() function.
Read JSON file
In order to properly import data from a JSON file, the first thing you have to do is examine the contents of the JSON file.
Data can be stored in many different JSON structure or orient in Pandas terms.
Most of the time, the JSON is a list of dictionaries with the same keys.
[ { "name": "Afghanistan", "continent": "Asia", "area": 652.23, "population": " 25.500.100 " }, { "name": "Albania", "continent": "Europe", "area": 28.748, "population": " 2.831.741 " }, { "name": "Algeria", "continent": "Africa", "area": " 2.381.741 ", "population": " 37.100.000 " }, { "name": "Andorra", "continent": "Europe", "area": 468, "population": 78.115 }, { "name": "Angola", "continent": "Africa", "area": " 1.246.700 ", "population": " 20.609.294 " } ]
We can quickly import the above JSON with
orient=records parameter.
import pandas as pd dframe = pd.read_json("example.json", orient="records") dframe
Output:
For other JSON files that has a deeply nested structure, like the New York Philharmonic Performance History data, you may want to use
json_normalize to flatten it out and quickly load into Pandas.
import json import pandas as pd from pandas.io.json import json_normalize # Load JSON into Python objects with open('../input/raw_nyc_phil.json') as f: loaded = json.load(f) # Get the actual array that contains data actual_data = loaded['programs'] # Specify the actual data as the main array # record_path is the children which contains the necessary field # meta is the list of data from parent object that we want to include works_data = json_normalize(data=actual_data, record_path='works', meta=['id', 'orchestra','programID', 'season']) works_data.head(3)
Output:
Read JSON from URL
Pandas
read_json() can read the data directly from an URL, which automatically handles the process of making the request, validating data and error catching.
read_json() accepts a handful of URL schemes : http, ftp, s3, file. A local file could be read using its file URL :.
import pandas as pd url = "" df = pd.read_json(url) print(df)
You can also read JSON files directly from Amazon S3 using
s3:// URLs (you’ll have to install s3fs first).
import pandas as pd df = pd.read_json("s3://bucket....csv") print(df)
Summary: using
read_json() method, one can easily import the data from local JSON files as well as remotely located files. | https://monkeybeanonline.com/pandas-read-json/ | CC-MAIN-2022-27 | refinedweb | 418 | 58.48 |
That's fine by me.
Best regards,
Jean Marie
Type: Posts; User: jean_marie
That's fine by me.
Best regards,
Jean Marie
Hi again,
i have a question on PHP Session Handling.
I have extended my Ext.Direct apllication () with a session handling on PHP backend side.
...
100% ;-). I got it.
I tried it without specifying the namespace on server side within the PHP stack implementation and than it works like the documentation example.
But i would prefer the...
Thanks, using the defined namespace makes sense and works!
When i
console.log(Ext.app);Firebug tells me:
13975
I ran into this error because i followed the official Ext.Direct description...
Hi,
i'm exploring Ext.Direct and stumble when calling the API actions in JavaScript. I'm using this PHP stack.
On server side i have coma_api.php... | https://www.sencha.com/forum/search.php?s=b6bad430789c922d91644162da9a5fe4&searchid=20263378 | CC-MAIN-2018-09 | refinedweb | 139 | 71.31 |
Table Of Content
Inheritance and polymorphism in Python
1- Introduction
- Inheritance and polymorphism - this is a very important concept in Python. You must understand it better if you want to learn Python.
- Before you start learning about "Inheritance in Python", make sure you have the concept of "Class and object", if not, let's learn it:
- This document is based on:
Python 3.x
2- Inheritance in Python
- Python allows you to create a class extended from one or more other classes. This class is called a derived class, or a subclass.
The child class inherits the attributes, methods, and other members from the parent class. It can also override methods from the parent class. If the child class does not define its own constructor, by default, it will inherit the constructor of the parent class.
- Unlike Java, CSharp and several other languages, Python allows multiple inheritance. A class can be extended from one or more parent classes.
- We need a few classes to participate in examples.
- Animal: Class simulate an animal.
- Duck: Subclass of Animal.
- Cat: Subclass of Animal.
- Mouse: Subclass of Animal.
- In Python, constructor of class used to create an object (instance), and assign the value for the attributes.
Constructor of subclasses always called to a constructor of parent class to initialize value for the attributes in the parent class, then it start assign value for its attributes.
- Example:
- animal.py
class Animal : # Constructor def __init__(self, name): # Animal has one attribute: 'name' self.name= name # Method def showInfo(self): print ("I'm " + self.name) # Method def move(self): print ("moving ...")
- Cat is the class that inherits from the Animal class, it also has its attributes.
- cat.py
from animal import Animal # Cat class extends from Animal. class Cat (Animal): def __init__(self, name, age, height): # Call to contructor of parent class # to assign value to attribute 'name' of parent class. super().__init__(name) self.age = age self.height = height # Override method. def showInfo(self): print ("I'm " + self.name) print (" age " + str(self.age)) print (" height " + str(self.height))
- catTest.py
from cat import Cat tom = Cat("Tom", 3, 20) print ("Call move() method") tom.move() print ("\n") print ("Call showInfo() method") tom.showInfo()
- Running catTest module:
- What's happened when you create an object from constructor . How does it call up a constructor of the parent class? Please see the illustration below:
- With the above illustration you see that, constructor of parent class is called in constructor of subclass, it will assign values to the attributes of the parent class, then the attributes of the subclass.
3- Override method
- By default, child classes inherit methods from the parent class, but parent classes can override the method of the parent class.
- mouse.py
from animal import Animal # Mouse class extends from Animal. class Mouse (Animal): def __init__(self, name, age, height): # Call to contructor of parent class # to assign value to attribute 'name' of parent class. super().__init__(name) self.age = age self.height = height # Override method. def showInfo(self): # Call method of parent class. super().showInfo() print (" age " + str(self.age)) print (" height " + str(self.height)) # Override method. def move(self): print ("Mouse moving ...")
- Test
- mouseTest.py
from mouse import Mouse jerry = Mouse("Jerry", 3, 5) print ("Call move() method") jerry.move() print ("\n") print ("Call showInfo() method") jerry.showInfo()
4- Abstract Method
- The concept of an abstract method or abstract class is defined in languages such as Java, C#. But it is not clearly defined in Python. However, we have a way to define it.
- A class called as abstract defines abstract methods and child class must override these methods if you want to use them. The abstract methods always throw the exception NotImplementedError.
- abstractExample.py
# An abstract class class AbstractDocument : def __init__(self, name): self.name = name # A method can not be used, because it always throws an error. def show(self): raise NotImplementedError("Subclass must implement abstract method") class PDF(AbstractDocument): # Override method of parent class def show(self): print ("Show PDF document:", self.name) class Word(AbstractDocument): def show(self): print ("Show Word document:", self.name) # ---------------------------------------------------------- documents = [ PDF("Python tutorial"), Word("Java IO Tutorial"), PDF("Python Date & Time Tutorial") ] for doc in documents : doc.show()
- The example above demonstrates Polymorphism in Python. A Document object can be represented in various forms (PDF, Word, Excel, ...).
- Another example illustrates polymorphism: When I talk about an Asian people, it's quite abstract, he can be Japanese, Vietnamese, or Indian. However, there are features of Asian people.
5- Multiple inheritance
- Python allows multiple inheritance, which means you can create an extension class from two or more other classes. The parent classes can have the same attributes, or the same methods, ....The child class will prioritize to inherit attributes, methods, ... of the first class in a list of inheritance
- multipleInheritanceExample.py
class Horse: maxHeight = 200; # centimeter def __init__(self, name, horsehair): self.name = name self.horsehair = horsehair def run(self): print ("Horse run") def showName(self): print ("Name: (House's method): ", self.name) def showInfo(self): print ("Horse Info") class Donkey: def __init__(self, name, weight): self.name = name self.weight = weight def run(self): print ("Donkey run") def showName(self): print ("Name: (Donkey's method): ", self.name) def showInfo(self): print ("Donkey Info") # Mule inherits from Horse and Donkey class Mule(Horse, Donkey): def __init__(self, name, hair, weight): Horse.__init__(self, name, hair) Donkey.__init__(self, name, weight) def run(self): print ("Mule run") def showInfo(self): print ("-- Call Mule.showInfo: --") Horse.showInfo(self) Donkey.showInfo(self) # ---- Test ------------------------------------ # 'maxHeight' inherit from Horse. print ("Max height ", Mule.maxHeight) mule = Mule("Mule", 20, 1000) mule.run() mule.showName() mule.showInfo()
mro() method
- The mro() method lets you view the list of parent classes of a certain class. Let's see the example below:
- mroExample.py())
- Note: In Python, the pass statement is like a null (or empty) statement, it does nothing, if the class or method has no content, you still need at least one statement, let's use pass.
6- issubclass and isinstance function
- Python has two useful functions:
- isinstance
- issubclass
isinstance
- The isinstance function helps you to check whether "something" is an object of a certain class or not.
issubclass
- The issubclass function checks whether this class is the child of another class or not.
- isinstancesubclass.py
class A: pass class B(A): pass # True print ("isinstance('abc', object): ",isinstance('abc', object)) # True print ("isinstance(123, object): ",isinstance(123, object)) b = B() a = A() # True print ("isinstance(b, A): ", isinstance(b, A) ) print ("isinstance(b, B): ", isinstance(b, B) ) # False print ("isinstance(a, B): ", isinstance(a, B) ) # B is subclass of A? ==> True print ("issubclass(B, A): ", issubclass(B, A) ) # A is subclass of B? ==> False print ("issubclass(A, B): ", issubclass(A, B) )
7- Polymorphism with function
- Here I create two classes such as English and French. Both of the classes have the greeting() method. Both create different greetings. Create two corresponding objects from the two classes above and call the actions of these two objects in the same function ( intro function).
- people.py
class English: def greeting(self): print ("Hello") class French: def greeting(self): print ("Bonjour") def intro(language): language.greeting() flora = English() aalase = French() intro(flora) intro(aalase)
- Run the example: | http://o7planning.org/en/11417/inheritance-and-polymorphism-in-python | CC-MAIN-2017-30 | refinedweb | 1,210 | 58.89 |
This article is aimed at developers who deep down know that they do not really understand events and delegates even though they use them every day...
Many developers tend to use events and delegates "as is" without truly understanding the internal stuff - which, trust me, once understood, can help you do many cool stuff. When I first started .NET coding, I used to just double click the "Button" or "DataGrid" control, go to the code-behind, and write my code inside the event handler. Well, then a few years ago, I decided enough is enough, and I dug deep to really understand .NET events and delegates: This article is an attempt to share with you what I came up with.
Button
DataGrid
This article tries to help developers “truly” understand .NET events and delegates by real examples. By illustrating the ideas presented via business examples, I will hopefully succeed in explaining the concept. So, let’s start…
As a smooth start, let us understand delegates from a high level approach by comparing it to the Observer (also called the Publish-Subscribe) pattern:
The Observer pattern is one of the most well known patterns used in software engineering. This pattern states that a non-determined number of business entities – called subscribers – are interested in a change of state of another business entity – called publisher – and that the publisher does not care who these subscribers are or what and why they are concerned with its change of state.
For example, two business entities called “Employee” and “Manager” are interested to know if the business entity “Owner” encounters any bad change of state in health. Now, while the “Owner” does not really care or even know anything about who wants to know if he is sick, the “Employee” and “Manager” will definitely want to prepare get-well notes and flower packets for the beloved company “Owner”. Of course, they will have a hidden agenda behind that, but this is out of the scope of this article.
.NET uses Delegates between business entities to achieve this behavior.
A delegate is a type safe “Function Pointer” which holds references to static or instance methods. Delegates are used to call methods dynamically at runtime (do not scratch your head; you will understand this by examples).
In .NET, a delegate is declared as follows:
public delegate int TestDelegate(int quantity);
The above line declares a delegate called “TestDelegate” which can dynamically call any method which has a return type of “int” and accepts a single parameter also of type “int”. This makes .NET delegates “type safe” in that they can only call methods that match their signatures.
TestDelegate
int
Internally, the “delegate” keyword causes the compiler to generate a class that derives from System.MulticastDelegate, which is the base class for .NET delegates. The MulticastDelegate class, in turn, derives from the System.Delegate class. The MulticastDelegate class was an addition to the .NET Framework which first included only the Delegate class. The MulticastDelegate class added the ability of chaining a linked list of delegates called the “invocation list”. Translation: MulticastDelegate represents a delegate that can call more than one method.
delegate
System.MulticastDelegate
MulticastDelegate
System.Delegate
Delegate
OK, enough with the boring theory. Next, you will see examples that clear up the concepts discussed in this action and much more…
Actually, this example is not that trivial. Although – as you will see – this example does not hold any real business value, it will actually give you a clear indication about how delegates work and how they can be used to call multiple methods through their invocation list.
Consider the code below:
public delegate void MyDelegate(string text);
protected void Page_Load(object sender, EventArgs e)
{
MyDelegate d = new MyDelegate(MyMethod);
//d += new MyDelegate(MyMethod1);
d("hello");
}
private void MyMethod(string text)
{
Response.Write(text);
}
//private void MyMethod1(string text)
//{
// Response.Write("--" + text);
//}
Let us examine the example:
public delegate void MyDelegate(string text);
This line declares a delegate called “MyDelegate” which can call any method that has a return of type void and accepts a single string parameter.
MyDelegate
void
string
MyDelegate d = new MyDelegate(MyMethod);
This line creates an instance of “MyDelegate” called “d” and adds a method “MyMethod” to its invocation list. This means that now delegate “d” will call the method “MyMethod” dynamically at runtime. How is this done? Keep going…
d
MyMethod
d(“hello”);
This line causes the delegate “d” to call the methods on its invocation list. In this case, the method “MyMethod” will be called. You can verify this by running the page, and you will see the value “hello” printed.
Now, let us see how delegates can be used to invoke multiple methods. For this, uncomment the commented lines.
d += new MyDelegate(MyMethod1);
This line adds a new method “MyMethod1” to delegate d's invocation list. This means that delegate “d” will now call methods “MyMethod” and “MyMethod1” because they are both on its invocation list (linked list). This time, if you run the code, you will see the value “hello--hello" printed as an indication that both methods were called at runtime.
MyMethod1
d”
Delegates internally have two important properties: Target and Method. Target points to an object instance, while Method points to a method inside the object instance. Invoking a delegate means to call the method referenced in the Method property which belongs to the object instance referenced by the Target property. To clear things up, see how this explanation fits into the trivial sample given above:
Target
Method
This representation indicates that since in our code we added two methods “MyMethod” and “MyMethod1” to delegate’s d's invocation list, both methods are added to the data structure linked list. In both cases, the Target property is set to “this”, which is the page instance itself, while the Method property is set to the appropriate method name. Also notice how the order in which we added methods to the invocation list is apparent in the representation of the linked list: first, “MyMethod” is added where the Previous pointer is null, and then “MyMethod1” is added where the Previous pointer points to “MyMethod”.
this
null
OK, so by now, I bet you have learned a lot about delegates; however, you have every right to ask the following questions: What is the benefit of using delegates in the previous sample? Couldn’t I implement the previous example with simple old school method calls?
Well, actually if you do ask the above questions, then you are 100% correct. There is absolutely no reason why you would use delegates in such a scenario. I only included the sample to clear up the confusion around delegates, but as I indicated previously, it has no real business value. Next, let’s look at a more realistic sample where the use of delegates will start to make much more sense.
Consider a case where a developer is writing a component that performs some calculation logic for its consumers. The catch, however, is that the developer wants to make this component reusable because he wants to sell it to more than one customer, and each customer might have his own calculation logic. How can the developer write such a .NET component? The answer is obviously by using .NET delegates. Examine the code below:
public class Algorithm
{
public delegate double Function(double x, double y);
public static double Calculate(Function f, double x, double y, double z)
{
return f(x, y) + z;
}
}
The above code illustrates the component written by the developer. He first creates a delegate called “Function” which can invoke methods that return a “double” type and accept two “double” parameters. Next, the developer defines a method called “Calculate” that accepts a parameter of type “Function” and three “double” parameters. Now, notice the key line of the code:
Function
double
Calculate
return f(x, y) + z;
The above line allows the component to accept, at runtime, any method that has its signature matching that of the delegate. This provides the generic behavior that the developer is looking for. Now, let’s see the component in action in order to appreciate more the power of delegates:
protected void Page_Load(object sender, EventArgs e)
{
Algorithm.Function f = new Algorithm.Function(MyImplementation);
Response.Write(Algorithm.Calculate(f, 3, 4, 5));
}
protected double MyImplementation(double x, double y)
{
return x * y;
}
One of the developers working for a customer uses the component as follows: first, she creates an instance of the delegate “Function” and adds her own method called “MyImplementation” to the invocation list. Of course, notice how the signature of the method “MyImplementation” matches that of the delegate “Function”. Now, by using the line below:
MyImplementation
Response.Write(Algorithm.Calculate(f,3,4,5));
the developer is actually utilizing the power of delegates since she is using the logic that suits her business (MyImplementation, in this case) to pass to the component.
Another developer for another customer can use the same component to fulfill his business needs, for example, by changing the implementation of the method “MyImplementation” to (x + y) instead of (x * y).
OK, so up until now, you have been introduced to .NET delegates as a powerful mechanism to perform dynamic method invocation, and you have seen some details about .NET delegates' internal representation and invocation lists. Next, I will start discussing how the .NET Framework actually utilizes delegates to implement one of its coolest (and most important) features: Events and Event Handlers.
In the beginning of the article, I explained the Observer pattern, and said that it is also called the Publish-Subscribe pattern and that .NET delegates are the mechanism to achieve this behavior. While you have been introduced to delegates, I have yet to tackle how delegates achieve this Publish-Subscribe design pattern: Enter .NET Event and Event Delegates.
Enough theory; trust me that the best way to quickly and efficiently understand all that there is about Event Delegates is to follow me up during the remaining two sections of this article. Off we go to the practical implementation…
Consider a sample business scenario: a typical company has two departments of concern, namely the Human Resources (HR) and the Employee Care (EC) departments. The HR department is responsible for recruiting, and whenever they do recruit a new employee, the EC department needs to be notified so that they can do some administration stuff related to the new employee…
First, let us examine the class defined for the first business entity: the HR class.
HR
public delegate void NewEmployeeEventHandler(object sender, NewEmployeeEventArgs e);
class HR
{
public event NewEmployeeEventHandler NewEmployee;
protected virtual void OnNewEmployee(NewEmployeeEventArgs e)
{
if (NewEmployee != null)
NewEmployee(this, e);
}
public void RegisterEmployee(string name, string sex, int age)
{
NewEmployeeEventArgs e = new NewEmployeeEventArgs(name, sex, age);
OnNewEmployee(e);
}
}
Let’s start analyzing the code:
First, a delegate called “NewEmployeeEventHandler” is created. This delegate can invoke methods that return a void and accept a parameter of type object and another parameter of type “NewEmployeeEventArgs”. NewEmployeeEventArgs is a custom class that we will examine shortly; for now, just know that this class holds information about the hired employee like her name.
NewEmployeeEventHandler
object
NewEmployeeEventArgs
Then, an event is declared as follows:
public event NewEmployeeEventHandler NewEmployee;
The above line declares an event called “NewEmployee”. So, what is “NewEmployeeEventHandler” doing in a declaration of an event? Well, as we will see later, once an event is raised, it invokes its delegate (NewEmployeeEventHandler, in this case), and the delegate then calls the method(s) – called Event Handlers – in the invocation list.
NewEmployee
Next, a method “OnNewEmployee” is declared. This method accepts a parameter of type “NewEmployeeEventArgs”. It then raises the event as follows:
OnNewEmployee
NewEmployee(this, e);
When the above line is called, the event invokes its delegate, which in turn does the method invocation of its corresponding invocation list. One more thing to notice is that raising the event “NewEmployee” conforms to the signature of its delegate “NewEmployeeEventHandler”.
Info: Before raising an event, we need to check whether there are any event listeners. In other words, we need to make sure that the invocation list is not null. This check is done via the following line of code:
if (NewEmployee != null)
Info: Before raising an event, we need to check whether there are any event listeners. In other words, we need to make sure that the invocation list is not null. This check is done via the following line of code:
if (NewEmployee != null)
Finally, there is the “RegisterEmployee” method which creates an instance of “NewEmployeeEventArgs” and calls the “OnNewEmployee” method.
RegisterEmployee.
Next, we will examine the NewEmployeeEventArgs class:
public class NewEmployeeEventArgs
{
public string Name;
public string Sex;
public int Age;
public NewEmployeeEventArgs(string name, string sex, int age)
{
Name = name;
Sex = sex;
Age = age;
}
}
This class is simple. As stated before, it holds information about the newly hired employee.
The final piece of the puzzle before running the program is the EmployeeCare class:
EmployeeCare
class EmployeeCare
{
public EmployeeCare(HR hr)
{
hr.NewEmployee += CallEmployee;
}
private void CallEmployee(object sender, NewEmployeeEventArgs e)
{
Console.WriteLine("Sender of event: " + sender.ToString());
Console.WriteLine("Cusomer Info: " + e.Name +
"," + e.Sex + "," + e.Age.ToString());
//do call Employee stuff
}
}
The constructor of the EmployeeCare class accepts an HR object. Then, it hooks itself to the “NewEmployee” event. The syntax of event hooking is:
hr.NewEmployee += CallEmployee;
The above line does the following: The EmployeeCare class is saying that it is concerned to be notified whenever the “NewEmployee” event of the HR class is raised. Now, whenever the “NewEmployee” event gets actually raised, the EmployeeCare class is assigning a method called “CallEmployee” to be the Event Handler. Again, notice that the signature of the “CallEmployee” method matches that of the delegate “NewEmployeeEventHandler” of the HR class.
CallEmployee
So, if you are new to delegates, then the amount of information so far might be confusing, so let’s summarize where we have reached so far:
In business terms, an HR department recruits new people, and directly sends a notification that it just did. An Employee Care department is interested to receive this notification in order to do some administration tasks. In technical terms, this behavior can be achieved by using .NET Delegates an Events. The HR class – being the publisher – defines a delegate “NewEmployeeEventHandler” and an event related to this delegate “NewEmployeeEventHandler”. It then exposes a method “RegisterEmployee” which, when called, raises the event. How does the EmployeeCare class get notified whenever the event is raised? It actually defines an event handler “CallEmployee” that matches the signature of the delegate, and hooks this event handler to the HR event by using the “+=” syntax.
+=
Finally, we are ready to run the program. The code below does just that:
static void Main(string[] args)
{
HR hr = new HR(); //line1
EmployeeCare cc = new EmployeeCare(hr); //line2
hr.RegisterEmployee("mohamad", "male", 26); //line3
Console.ReadLine(); //line4
}
Now, let’s clearly understand what is going on to kill the topic: line1 simply creates a new instance of the HR class. Line2 creates an instance of the EmployeeCare class. This will cause the EmployeeCare class to declare itself interested in the “NewEmployee” event. Recall that the constructor of the EmployeeCare class uses the following line:
This means that the EmployeeCare class wants to be notified whenever the “NewEmployee” event is raised, and that it has assigned the method “CallEmployee” to be the event handler.
Line3 actually raises the event by calling the method “RegisterEmployee” of the HR class. Once this line is executed, the “RegisterEmployee” method will populate “NewEmployeeEventArgs” with the supplied information (name, sex, age) and then internally raises the “NewEmployee” event. At this moment, the event invokes its corresponding delegate “NewEmployeeEventHandler”, which in turn invokes its invocation list. The invocation list contains the method “CallEmployee” of the EmployeeCare class because it was registered as en event handler.
That is all there is about .NET Delegates and Event Delegates. In the final section of the article, I will show you how to map what you have just learned into the .NET Framework internal use of delegates.
I am sure that as .NET developers, you actually have found some familiar naming in the previous example. Precisely, the following names have definitely rang a bell (I have italicized the bell ringing portion of the word):
sender
e
Let’s tackle this by a couple of examples:
Example1:
protected void btn_Click(object sender, EventArgs e)
{
}
The above is an event handler of an ASP.NET button “Click” event. When compared to the “CallEmployee” event handler of the EmployeeCare class, some interesting points can be outlined:
Click
btn_Click
EventArgs
btn.Click
EventHandler
public delegate void EventHandler(object sender, EventArgs e);
In our example, I named the delegate “NewEmployeeEventHandler” to match the naming convention of the properties class “NewEmployeeEventArgs”.
Example2:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
The above code shows the event handler of a GridView “RowDataBound” event. In this case, note that the information class is called “GridViewRowEventArgs” because it contains special information such as the current “Row”. The corresponding delegate is defined as follows:
GridView
RowDataBound”
GridViewRowEventArgs
Row
public delegate void GridViewRowEventHandler(object sender, GridViewRowEventArgs e);
Now, you can compare the “GridViewRowEventArgs” and the “GridViewRowEventHandler” with “NewEmployeeEventArgs” and “NewEmployeeEventHandler”.
GridViewRowEventHandler
Example3:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
The above code shows the “OnLoad” overridable method of the ASP.NET Page object. This method internally invokes the Page “Load” event which causes the familiar “Page_Load” event handler to get fired. This method is overridable because it gives the developer – for some reason – the power to change the behavior, for example, by commenting the line “base.OnLoad(e)” and thus not firing the “Load” event.
OnLoad
Page
Load
Page_Load
base.OnLoad(e)
This behavior is implemented in our example by implementing the method “OnNewEmployee” which – being overridable – gives the ability to perform additional logic such as not firing the “NewEmployee” event.
This article tackled the subject of .NET Delegates and Event Delegates. First, we saw how delegates can be used outside the context of events and event delegates as a mechanism to dynamic method calling. We also discussed a delegate’s method invocation list which allows calling more than one method at a time.
We also saw a delegate implementation with events and event delegates and how it can be used to achieve the Publish-Subscribe pattern. Finally, we demonstrated how the .NET Framework implements this pattern within its. | http://www.codeproject.com/Articles/26936/Understanding-NET-Delegates-and-Events-By-Practice?fid=1406281&df=90&mpp=10&sort=Position&spc=None&tid=4340927 | CC-MAIN-2015-48 | refinedweb | 3,068 | 52.8 |
datacrypt-project/hitchhiker-tree[web search]
Hitchhiker tree
This document will attempt to sketch out the big ideas in the hitchhiker tree. It will also attempt to call out various locations in the implementation where features are built.
High-level understanding
The goal of the hitchhiker tree is to wed three things: the query performance of a B+ tree, the write performance of an append-only log, and convenience of a functional, persistent datastructure. Let’s look at each of these in some detail.
B+ trees win at queries
You might remember an important theorem from data structures: the best-performing data structure for looking up sorted keys cannot do those queries faster than
O(log(n)) .
Since sorted trees provide a solution for this, we’ll start with them.
Now, a common sorted tree for this purpose is the Red-Black tree, whose actual query performance is between
log2(n) and
2*log2(n) (the write performance is
log2(n) ).
The factor of 2 comes from the partial imbalances (which are still asymptotically balanced) that the algorithm allows, and the base 2 of the log comes from the fact that it’s a binary search tree.
A less popular sorted tree is the AVL tree—this tree achieves
log2(n) query performance, at the cost of always paying
2*log2(n) for inserts.
We can already see a pattern—although many trees reach the asymptotic bound, they differ in their constant factors.
The tree that the hitchhiker tree is based off of is the B+ tree, which achieves
logb(n) query performance.
Since
b can be very large (on the order of 100s or 1000s), these trees are especially great when each node is stored on higher latency media, like remote storage or a disk.
This is because each node can contain huge numbers of keys, meaning that by only keeping the index nodes in memory, we can access most keys with fewer, often just one, data accesses.
Unlike the above sorted trees (and B trees, which we won’t discuss), B+ trees only store their data (i.e. the values) in their leaves—internal nodes only need to store keys.
Event logs win at writing data
Do you know the fastest way to write data? Append it to the end of the file. There’s no pointers, no updating of data structures, no extra IO costs incurred.
Unfortunately, to perform a query on an event log, we need to replay all the data to figure out what happened.
That replay costs
O(n) , since it touches every event written.
So, how can we fix this?
Unifying B+ trees and event logs
The first idea to understand is this: how can we combine the write performance of an event log with the query performance of a B+ tree? The answer is that we’re going to "overlay" an event log on the B+ tree!
The idea of the overlay is this: each index node of the B+ tree will contain an event log. Whenever we write data, we’ll just append the operation (insert or delete) to the end of the root index node’s event log. In order to avoid the pitfall of appending every operation to an ever-growing event log (which would leave us stuck with linear queries), we’ll put a limit on the number of events that fit in the log. Once the log has overflowed in the root, we’ll split the events in that log towards their eventual destination, adding those events to the event logs of the children of that node. Eventually, the event log will overflow to a leaf node, at which point we’ll actually do the insertion into the B+ tree.
This process gives us several properties:
log(n)nodes.
Thus we dramatically improve the performance of insertions without hurting the IO cost of queries.
Functional Persistence
Now that we get the sketch of how to combine event logs and B+ trees, let’s see the beauty of making the whole thing functional and persistent! Since the combined B+/log data structure primarily only modifies nodes near the root, we can take advantage of the reduced modification to achieve reduced IO when persisting the tree. We can use the standard path-copying technique from functional, persistent data structures. This gives great performance, since the structure is designed to avoid needing to copy entire paths—most writes will only touch the root. Furthermore, we can batch many modifications together, and wait to flush the tree, in order to further batch IO.
Code Structure
The hitchhiker tree’s core implementation lives in 2 namespaces:
hitchhiker.tree.core and
hitchhiker.tree.messaging .
hitchhiker.tree.core implements the B+ tree and its extensibility hooks;
hitchhiker.tree.messaging adds the messaging layer (aka log) to the B+ tree from
core .
Protocols
In
hitchhiker.tree.core , we have several important protocols:
hitchhiker.tree.core/IKeyCompare
This protocol should be extended to support custom key comparators. It’s just like
clojure.core/compare.
hitchhiker.tree.core/IResolve
This protocol is the functionality for a minimal node. Not only will every node implement this, but also backends will use this to implement stubs which automatically & lazily load the full node into memory during queries.
last-keyis used for searches, so that entire nodes can remain unloaded from memory when we only need their boundary key.
dirty?is used to determine whether the IO layer would need to flush this node, or whether it already exists in the backing storage.
resolveloads the node into memory—this could return itself (in the case of an already loaded node), or it could return a new object after waiting on some IO.
hitchhiker.tree.core/INode
This protocol implements a node fully in-memory. Generally, this shouldn’t need to be re-implemented; however, if the hitchhiker was to be enhanced with key & value size awareness during splits and merges, you’d want to adjust the methods of this protocol.
hitchhiker.tree.core/Config
This structure must be passed to the
hitchhiker.tree.core/b-treeconstructor, which is the only way to get a new tree. The
index-bis the fanout on index nodes; the
data-bis the key & value fanout on data nodes, and the
op-buf-sizeis the the size of the log at each index node. The internet told me that choosing
sqrt(b)for the
op-buf-sizeand
b-sqrt(b)for the
index-bwas a good idea, but who knows?
hitchhiker.tree.core/IBackend
This protocol implements a backend for the tree.
new-sessionreturns a "session" object, which is a convenient way to capture backend-specific stats.
write-nodewill write a a node to storage, returning the stub object which implements
IResolvefor that backend. It can record stats by mutating or logging to the session.
anchor-rootis called by the persistence functionality to ensure that the backend knows which nodes are roots; this is a hint to any sorts of garbage collectors.
delete-addrremoves the given node from storage.
TestingBackendis a simple implementation of a backend which bypasses serialization and is entirely in memory. It can be a useful reference for the bare minimum implementation of a backend.
hitchhiker.tree.messaging/IOperation
This protocol describes an operation to the tree. Currently, there are only
InsertOpand
DeleteOp, but arbitrary mutation is supported by the data structure.
Useful APIs
hitchhiker.tree.core/flush-tree
This takes a tree, does a depth-first search to ensure each node’s children are durably persisted before flushing the node itself. It returns the updated tree & the session under which the IO was performed.
flush-treedoes block on the writing IO—a future improvement would be to make that non-blocking.
hitchhiker.tree.messaging/enqueue
This is the fundamental operation for adding to the event log in a hitchhiker tree.
enqueuewill handle the appending, overflow, and correct propagation of operations through the tree.
hitchhiker.tree.messaging/apply-ops-in-path
This is the fundamental operation for reading from the event log in a hitchhiker tree. This finds all the relevant operations on the path to a leaf node, and returns the data that leaf node would contain if all the operations along the path were fully committed. This is conveniently designed to work on entire leaf nodes, so that iteration is as easy as using the same logic as a non-augmented B+ tree, and simply expanding each leaf node from the standard iteration.
lookup,
insert,
delete,
lookup-fwd-iter
These are the basic operations on hitchhiker trees. There are implementations in
hitchhiker.tree.coreand
hitchhiker.tree.messagingwhich leverage their respective tree variants. They correspond to
get,
assoc,
dissoc, and
subseqon sorted maps.
hitchhiker.core.b-tree
This is how to make a new hitchhiker or B+ tree. You should either use the above mutation functions on it from one or the other namespace; it probably won’t work if you mix them.
Related Work
Hitchhiker trees are made persistent with the same method, path copying, as used by Okasaki The improved write performance is made possible thanks to the same buffering technique as a fractal tree index. As it turns out, after I implemented the fractal tree, I spoke with a former employee of Tokutek, a company that commercialized fractal tree indices. That person told me that we’d actually implemented fractal reads identically! This is funny because there’s no documentation anywhere about how exactly you should structure your code to compute the query. | https://jaytaylor.com/notes/node/1470414750000.html | CC-MAIN-2020-05 | refinedweb | 1,585 | 62.17 |
suported..
Examples
GVariant *value1, *value2, *value3, *value4; value1 = g_variant_new ("y", 200); value2 = g_variant_new ("b", TRUE); value3 = g_variant_new ("d", 37.5): value4 = g_variant_new ("x", G_GINT64_CONSTANT (998877665544332211)); { gdouble floating; gboolean truth; gint64 bignum; g_variant_get (value1, "y", NULL); /* ignore the value. */ g_variant_get (value2, "b", &truth); g_variant_get (value3, "d", &floating); g_variant_get (value4, "x", &bignum); }
Strings
Characters:
s,
o,
g
String conversions occur to and from standard nul-terminated C strings. Upon encountering an
'
s', '
o' or '
g' in a format string,
g_variant_new() takes a
(const
gchar *) and makes a copy of it.
NULL is not a valid string.).
Examples
GVariant *value1, *value2, *value3; value1 = g_variant_new ("s", "hello world!"); value2 = g_variant_new ("o", "/must/be/a/valid/path"); value3 = g_variant_new ("g", "iias"); #if 0 g_variant_new ("s", NULL); /* not valid: NULL is not a string. */ #endif { gchar *result; g_variant_get (value1, "s", &result); g_print ("It was '%s'\n", result); g_free (result); }.
Examples
GVariantBuilder *builder; GVariant *value; builder = g_variant_builder_new (G_VARIANT_TYPE ("as")); g_variant_builder_add (builder, "s", "when"); g_variant_builder_add (builder, "s", "in"); g_variant_builder_add (builder, "s", "the"); g_variant_builder_add (builder, "s", "course"); value = g_variant_new ("as", builder); g_variant_builder_unref (builder); { GVariantIter *iter; gchar *str; g_variant_get (value, "as", &iter); while (g_variant_iter_loop (iter, "s", &str)) g_print ("%s\n", str); g_variant_iter_free (iter); } g_variant_unref (value);.
Examples
GVariant *value1, *value2, *value3, *value4, *value5, *value6; value1 = g_variant_new ("ms", "Hello world"); value2 = g_variant_new ("ms", NULL); value3 = g_variant_new ("(m(ii)s)", TRUE, 123, 456, "Done"); value4 = g_variant_new ("(m(ii)s)", FALSE, -1, -1, "Done"); /* both '-1' are ignored. */ value5 = g_variant_new ("(m@(ii)s)", NULL, "Done"); { GVariant *contents; const gchar *cstr; gboolean just; gint32 x, y; gchar *str; g_variant_get (value1, "ms", &str); if (str != NULL) g_print ("str: %s\n", str); else g_print ("it was null\n"); g_free (str); g_variant_get (value2, "m&s", &cstr); if (cstr != NULL) g_print ("str: %s\n", cstr); else g_print ("it was null\n"); /* don't free 'cstr' */ /* NULL passed for the gboolean *, but two 'gint32 *' still collected */ g_variant_get (value3, "(m(ii)s)", NULL, NULL, NULL, &str); g_print ("string is %s\n", str); g_free (str); /* note: &s used, so g_free() not needed */ g_variant_get (value4, "(m(ii)&s)", &just, &x, &y, &cstr); if (just) g_print ("it was (%d, %d)\n", x, y); else g_print ("it was null\n"); g_print ("string is %s\n", cstr); /* don't free 'cstr' */ g_variant_get (value5, "(m*s)", &contents, NULL); /* ignore the string. */ if (contents != NULL) { g_variant_get (contents, "(ii)", &x, &y); g_print ("it was (%d, %d)\n", x, y); g_variant_unref (contents); } else g_print ("it was null\n"); }
Tuples
Characters:
()
Tuples are handled by handling each item in the tuple, in sequence. Each item is handled in the usual way.
Examples
GVariant *value1, *value2; value1 = g_variant_new ("(s(ii))", "Hello", 55, 77); value2 = g_variant_new ("()"); { gchar *string; gint x, y; g_variant_get (value1, "(s(ii))", &string, &x, &y); g_print ("%s, %d, %d\n", string, x, y); g_free (string); g_variant_get (value2, "()"); /* do nothing... */ }
Dictionaries
Characters:
{}
Dictionary entries are handled by handling first the key, then the value. Each.
Examples
GVariant *value1, *value2; value1 = g_variant_new ("(i@ii)", 44, g_variant_new_int32 (55), 66); /* note: consumes floating reference count on 'value1' */ value2 = g_variant_new ("(@(iii)*)", value1, g_variant_new_string ("foo")); { const gchar *string; GVariant *tmp; gsize length; gint x, y, z; g_variant_get (value2, "((iii)*)", &x, &y, &z, &tmp); string = g_variant_get_string (tmp, &length); g_print ("it is %d %d %d %s (length=%d)\n", x, y, z, string, (int) length); g_variant_unref (tmp); /* quick way to skip all the values in a tuple */ g_variant_get (value2, "(rs)", NULL, &string); /* or "(@(iii)s)" */ g_print ("i only got the string: %s\n", string); g_free (string); }. | http://developer.gnome.org/glib/unstable/gvariant-format-strings.html | crawl-003 | refinedweb | 568 | 50.2 |
Socorro 1.3 deployment instructions:
These instructions are an edited version of
This upgrade requires downtime. Please follow typical process (maintenance UI, clear caches when finished, etc)
Push is scheduled for Thursday evening Jan 7th, 2010.
Socorro Server
= Database =
1) ADU
We have a new database table that metrics will populate.
We should create this and start populating ASAP
Doesn't require downtime
Copied from
1.1) A new table has been added for the ADU information. To add it manually, execute this SQL:
CREATE TABLE raw_adu (
adu_count integer,
date timestamp without time zone,
product_name text,
product_os_platform text,
product_os_version text,
product_version text
);
1.2)
CREATE INDEX raw_adu_1_idx ON raw_adu (date,
product_name,
product_version,
product_os_platform,
product_os_version);
1.3)
Grant access from cm-metricsetl01 and cm-metricsetl02.
1.4) Nagios Postgres DB alarm
Create a Nagios check on raw_adu.date. Take the max value. It should never be more than 48 hours out off from the current time.
2) New index for 'top_crashers_by_signature' table
CREATE INDEX top_crashes_by_signature_window_end_productdims_id_idx on top_crashes_by_signature (window_end desc, productdims_id);
*** New Index for 'build' column on the reports partitions
-- Be on the lookout for a separate IT bug ***
= Services =
3) Deploy AduByDay
3.1) updated to the latest from trunk
3.2) Update webapiconf.py config
The string 'adubd.AduByDay?' needs to be added to the 'servicesList' configuration parameter in webapiconf.py. In addition there needs to be a import for that service.
import socorro.services.topCrashBySignatureTrends as tcbst
import socorro.services.signatureHistory as sighist
import socorro.services.aduByDay as adubd
servicesList = cm.Option()
servicesList.doc = 'a python list of classes to offer as services'
servicesList.default = [tcbst.TopCrashBySignatureTrends, sighist.SignatureHistory, adubd.AduByDay]
= Processor =
4) Update from trunk
A minor change to the processor will require that it be updated to the latest code from trunk. This change is from Bug 520230 that increased the size of a field in the 'extensions' table.
= Collector =
5) Same as step 4, The collector should have its code updated to the latest from trunk.
Bug 534656 The collector now accepts floating point percentages in the configuration parameter 'throttleConditions'. This will be useful for the anticipated flood when client side throttling changes in FF 3.6.
the Crons
A new configuration parameter called 'truncateUrlLength' has been added to the configuration file 'topCrashesByUrlConfig.py'. Use topCrashesByUrlConfig.py.dist as a template to add this new parameter. The actual recommended value has yet to be determined.
= Socorro UI =
6) Copy and edit daily.php in order enable ADU.
cp application/config/daily.php-dist application/config/daily.php
corrections:
3.2 - 'adubd.AduByDay?' should be 'adubd.AduByDay' - a wiki artifact?
4 - drop it, i was never able to get the database change made without disrupting everyone else. I'll get griswolf to revert the processor source code change
as per my note in Comment #1 regarding 4 - no source checkin reversion is required
The separate IT bug mentioned in #0 2) is Bug 538313
= Crons =
7) Update and configure crons
7.1) Process Bug#537841 for updates to startTopCrashesByUrl.py
3.3) Grant Socorro db user/pass read access to raw_adu
All done. Code should sync out to the prod webheads in about 10 minutes.
(In reply to comment #6)
Thanks Aravind. Verified release in prod. | https://bugzilla.mozilla.org/show_bug.cgi?id=538261 | CC-MAIN-2017-09 | refinedweb | 539 | 50.84 |
This is a comprehensive (but simplified) guide for absolute Redux beginners, or any who wants to re-evaluate their understanding of the fundamental Redux concepts.
For an expanded Table of Contents please visit this link, & for more advanced Redux concepts check out my Redux books.
Introduction
This article (which is actually a book) is the missing piece if you’ve long searched for how to master Redux .
Before getting started, I should tell you that the book a certificate.
When I asked for his honest feedback on the program, his words were along the lines of:
The course was pretty good, but I still don’t think Redux was well explained to a beginner like me. It wasn’t explained that well.
You see, there are many more like my friend, all struggling to understand Redux. They perhaps use Redux, but they can’t say they truly understand how it works.
I decided to find a solution. I was going to understand Redux deeply, and find a clearer way to teach it.
What you are about to read took months of study, and then some more time to write and build out the example projects, all while keeping a daily job and other serious commitments.
But you know what?
I’m super excited to share this with you!
If you’ve searched for a Redux guide that won’t talk over your head, this is it. Look no further.
I have taken into consideration my struggles and those of many others I know. I’ll make sure to teach you the important stuff — and do so without getting you confused.
Now, that’s a promise.
My Approach to Teaching Redux
The real problem with teaching Redux — especially for beginners — isn’t the complexity of the Redux library itself.
No. I don’t think that is it. It is just a tiny 2kb library — including dependencies.
Take a look at the Redux community as a beginner, and you’re going to lose your mind fast. There’s not just Redux, but a whole lot of other supposed “associated libraries” needed — all at once.
Gosh! That is overwhelming.
The “Redux tutorial” often isn’t so much about Redux, but all the other stuff that comes with it.
There’s got to be a more sane approach tailored towards beginners. If you’re a humanoid developer, you certainly wouldn’t have issues with this. Guess what? Most of us are actually humans.
So, here’s my approach to teaching Redux.
Forget about all the extra stuff for a bit, and let’s just do Redux. Yeah!
I will only introduce the barest minimum you need for now. There will be no React-router, Redux-form, Reselect, Ajax, Webpack, Authentication, Testing, none of those — for now!
And guess what? That’s how you learned to do some of the important life “skills” you’ve got.
How did you learn to walk?
Did you begin to run in one day? No!
Let me walk you through a sane approach to learning Redux — without the hassles.
Sit tight.
“A rising tide lifts All boats”
Once you get the hang of how the basics of Redux works (the rising tide), everything else will be easier to reason about (it lifts all boats).
A Note on Redux’s Learning Curve
Redux does have a learning curve. I am not saying otherwise.
Learning to walk also had a learning curve to it. However, with a systematic approach to learning, you overcame that.
You did fall a few times, but that was okay. Someone was always around to hold you up, and help you get on your feet.
Well, I’m hoping to be that person for you — as you learn Redux with me.
What You will Learn
After all is said and done, you’ll come to see that Redux isn’t as scary as it seems from the outside.
The underlying principles are so darn easy!
First off, I’ll teach you the fundamentals of Redux in plain, easy to approach language.
Then, we’ll build a few simple applications. Starting with a basic Hello World app.
But those won’t suffice.
I’ll include exercises and problems I think you should tackle as well.
Effective learning isn’t about just reading and listening. Effective learning is mostly about practice!
Think of these as homework, but without the angry teacher. While practicing the exercises, you can Tweet me with the hashtag #UnderstandingRedux and I’ll definitely have a look!
No angry teachers, eh?
Exercises are good, but you also need to watch me build a bigger application. This is where we wrap things up by building Skypey, a sweet messaging app kinda like a Skype clone.
Skypey’s got features such as editing messages, deleting messages, and sending messages to multiple contacts.
Hurray!
If that didn’t get you excited, I don’t know what will. I’m super excited to show you these!
Prerequisite
The only prerequisite is that you already know React. If you don’t, Dave Ceddia’s Pure React is my personal recommendation if you have some $$ to spare. I’m no affiliate. It’s just a good resource.
Download PDF & Epub for Offline Reading
The video below highlights the process involved in getting your PDF and Epub versions of the book.
The crux is this:
- Visit the book sales page .
- Use the coupon FREECODECAMP to get 100% off the price so that you get a $29 book for $0.
- If you want to say thanks, please recommend this article by sharing it on social media.
Now, let’s get started.
Chapter 1 : Getting to know Redux
Some years back, developing front-end applications seemed like a joke to many. These days, the increasing complexity of building decent front-end applications is almost overwhelming.
It seems that to meet the pressing requirements of the ever-demanding user, the gentle cute cat has overgrown the confines of a home. It’s become a fearless lion with 3-inch claws and a mouth that opens wide enough to fit a human head.
Yeah, that’s what modern front-end development feels like these days.
Modern frameworks like Angular, React and Vue have done a great job at taming this “beast”. Likewise, modern philosophies such as those enforced by Redux also exist to give this “beast” a chill pill.
Follow along as we have a look at these philosophies.
What is Redux?
The official documentation for Redux reads:
Redux is a predictable state container for JavaScript apps.
Those 9 words felt like 90 incomplete phrases when I first read them. I just didn’t get it. You most likely don’t, either.
Don’t sweat it. I’ll go over that in a bit, and as you use Redux more, that sentence will get clearer.
On the bright side, if you read the documentation a little longer, you’ll find the more explanatory stuff somewhere in there.
It reads:
It helps you write applications that behave consistently…
You see that?
In lay-man’s terms, that’s saying, “it helps you tame the beast”. Metaphorically.
Redux takes away some of the hassles faced with state management in large applications. It provides you with a great developer experience, and makes sure that the testability of your app isn’t sacrificed for any of those.
As you develop React applications, you may find that keeping all your state in a top-level component is no longer sufficient for you.
You may also have a lot of data changing in your application over time.
Redux helps solve these kinds of problems. Mind you, it isn’t the only solution out there.
Why use Redux?
As you already know, questions like “Why should you use A over B?” boil down to your personal preferences.
I have built apps in production that don’t use Redux. I’m sure that many have done the same.
For me, I was worried about introducing an extra layer of complexity for my team members. In case you’re wondering, I don’t regret the decision at all.
Redux’s author, Dan Abamov, also warns about the danger of introducing Redux too early into your application. You may not like Redux, and that is fair enough. I have friends who don’t.
That being said, there are still some very decent reasons to learn Redux.
For example, in larger apps with a lot of moving pieces, state management becomes a huge concern. Redux ticks that off quite well without performance concerns or trading off testability.
One other reason a lot of developers love Redux is the developer experience that comes with it. A lot of other tools have begun to do similar things, but big credits to Redux.
Some of the nice things you get with using Redux include logging, hot reloading, time travel, universal apps, record and replay — all without doing so much on your end as the developer. These things will likely sound fancy until you use them and see for yourself.
Dan’s talk called Hot Reloading with Time Travel will give you a good sense of how these work.
Also, Mark Ericsson, one of Redux’s maintainers, says that over 60% of React apps in production use Redux. That’s a lot!
Consequently, and this is just my thought, a lot of engineers like to show potential employers that they can maintain larger production codebases built in React and Redux, so they learn Redux.
If you want some more reasons to use Redux, Dan, the Redux creator, has a few more reasons highlighted in his article on Medium.
If you don’t consider yourself a senior engineer, I advise you to learn Redux — largely because of some of the principles it teaches. You’ll learn new ways of doing common things, and this will likely make you a better engineer.
Everyone has different reasons for picking up different technologies. In the end, the call is yours. But it definitely doesn’t hurt to add Redux to your skill set.
Explaining Redux to a 5 year Old
This section of the book is really important. The explanation here will be referenced through out the book. So get ready.
Since a 5-year old doesn’t have the time for technical jargon, I’ll keep this very simple but relevant to our purpose of learning Redux.
So, here we go!
Let’s consider an event you’re likely familiar with — going to the bank to withdraw cash. Even if you don’t do this often, you’re likely aware of what the process looks like.
You wake up one morning, and head to the bank as quickly as possible. While going to the bank there’s just one intention / action you’ve got in mind: to
WITHDRAW_MONEY.
You want to withdraw money from the bank.
Here’s where things get interesting.
When you get into the bank, you then go straight to the Cashier to make your request known.
Wait, you went to the Cashier?
Why didn’t you just go into the bank vault to get your money?
After all, it’s your hard earned money.
Well, like you already know, things don’t work that way. Yes, the bank has money in the vault, but you have to talk to the Cashier to help you follow a due process for withdrawing your own money.
The Cashier, from their computer, then enters some commands and delivers your cash to you. Easy-peasy.
Now, how does Redux fit into this story?
We’ll get to more details soon, but first, the terminology.
1. The Bank Vault is to the bank what the
Redux Store is to Redux.
The bank vault keeps the money in the bank, right?
Well, within your application, you don’t spend money. Instead, the
state of your application is like the money you spend. The entire user interface of your application is a function of your state.
Just like the bank vault keeps your money safe in the bank, the state of your application is kept safe by something called a
store. So, the
store keeps your “money” or
state intact.
Uh, you need to remember this, okay?
The Redux Store can be likened to the Bank Vault. It holds the state of your application — and keeps it safe.
This leads to the first Redux principle:
Have a single source of truth: The state of your whole application is stored in an object tree within a single Redux store.
Don’t let the words confuse you.
In simple terms, with Redux, it is is advisable to store your application state in a single object managed by the Redux
store. It’s like having
one vaultas opposed to littering money everywhere along the bank hall.
2. Go to the bank with an
action in mind.
If you’re going to get any money from the bank, you’re going to have to go in with some intent or action to withdraw money.
If you just walk into the bank and roam about, no one’s going to just give you money. You may even end up been thrown out by the security. Sad stuff.
The same may be said for Redux.
Write as much code as you want, but if you want to update the state of your Redux application (like you do with
setState in React), you need to let Redux know about that with an
action.
In the same way you follow a due process to withdraw your own money from the bank, Redux also accounts for a due process to change/update the state of your application.
Now, this leads to Redux principle #2.
State is read-only:
The only way to change the state is to emit an action, an object describing what happened.
What does that mean in plain language?
When you walk to the bank, you go there with a clear action in mind. In this example, you want to withdraw some money.
If we chose to represent that process in a simple Redux application, your action to the bank may be represented by an object.
One that looks like this:
{ type: "WITHDRAW_MONEY", amount: "$10,000" }
In the context of a Redux application, this object is called an
action! It always has a
type field that describes the action you want to perform. In this case, it is
WITHDRAW_MONEY.
Whenever you need to change/update the state of your Redux application, you need to dispatch an action.
Don’t stress over how to do this yet. I’m only laying the foundations here. We’ll delve into lots of examples soon.
3. The Cashier is to the bank what the
reducer is to Redux.
Alright, take a step back.
Remember that in the story above, you couldn’t just go straight into the bank vault to retrieve your money from the bank. No. You had to see the Cashier first.
Well, you had an action in mind, but you had to convey that action to someone — the Cashier — who in turn communicated (in whatever way they did) with the vault that holds all of the bank’s money.
The same may be said for Redux.
Like you made your action known to the Cashier, you have to do the same in your Redux application. If you want to update the state of your application, you convey your
action to the
reducer — our own Cashier.
This process is mostly called dispatching an
action.
Dispatch is just an English word. In this example, and in the Redux world, it is used to mean sending off the action to the reducers.
The
reducer knows what to do. In this example, it will take your action to
WITHDRAW_MONEY and ensure that you get your money.
In Redux terms, the money you spend is your
state. So, your reducer knows what to do, and it always returns your
new state.
Hmmm. That wasn’t so hard to grasp, right?
And this leads to the last Redux principle:
To specify how the state tree is transformed by actions, you write pure reducers.
As we proceed, I’ll explain what a “pure” reducer means. For now, what’s important is to understand that, to update the state of your application (like you do with
setState in React,) your actions must always be sent off (dispatched) to the reducers to get your
new state.
With this analogy, you should now have an idea of what the most important Redux actors are: the
store, the
reducer and an
action.
These three actors are pivotal to any Redux application. Once you understand how they work, the bulk of the deed is done.
Chapter 2: Your First Redux Application
We learn by example and by direct experience because there are real limits to the adequacy of verbal instruction.
Malcom Gladwell
Even though I have spent ample time explaining the Redux principles in a way you won’t forget, verbal instructions have their limits.
To deepen your understanding of the principles, I’ll show you an example. Your first Redux application, if you want to call it that.
My approach to teaching is to introduce examples of increasing difficulty. So, for starters, this example is focused on refactoring a simple pure React app to use Redux.
The aim here is to understand how to introduce Redux in a simple React project, and deepen your understanding of the fundamental Redux concepts too.
Ready?
Below is the trivial “Hello World” React app we will be working with.
Don’t laugh it off.
You’ll learn to flex your Redux muscles from a “known” concept such as React, to the “unknown” Redux.
The Structure of the React Hello World Application
The React app we’ll be working with has been bootstrapped with
create-react-app. Thus, the structure of the app is one you’re already used to.
You may grab the repo from Github if you want to follow along — which I recommend.
There’s an
index.js entry file that renders an
<App /> component to the
DOM.
The main
App component is comprised of a certain
<HelloWorld />component.
This
<HelloWorld /> component takes in a
tech prop, and this prop is responsible for the particular technology displayed to the user.
For example,
<HelloWorld tech="React" /> will yield the following:
Also, a
<HelloWorld tech="Redux" /> will yield the following.
Now, you get the gist.
Here’s what the
App component looks like:
src/App.js
import React, { Component } from "react"; import HelloWorld from "./HelloWorld"; class App extends Component { state = { tech : "React" } render() { return <HelloWorld tech={this.state.tech}/> } } export default App;
Have a good look at the
state object.
There’s just one field,
tech, in the
state object and it is passed down as
prop into the
HelloWorld component as shown below:
<HelloWorld tech={this.state.tech}/>
Don’t worry about the implementation of the
HelloWorld component — yet. It just takes in a
tech prop and applies some fancy CSS. That’s all.
Since this is focused mainly on Redux, I’ll skip the details of the styling.
So, here’s the challenge.
How do we refactor our
App to use
Redux ?
How do we take away the state object and have it entirely managed by Redux? Remember that Redux is the state manager for your app.
Let’s begin to answer these questions in the next section.
Revisiting your Knowledge of Redux
Remember the quote from the official docs ?
Redux is a predictable state container for JavaScript apps.
One key phrase in the above sentence is state container.
Technically, you want the
state of your application to be managed by Redux.
This is what makes Redux a state container.
Your React component state still exists. Redux doesn’t take it away.
However, Redux will efficiently manage your overall application state. Like a bank vault, it’s got a
store to do that.
For the simple
<App/> component we’ve got here, the state object is simple.
Here it is:
{ tech: "React" }
We need to take this out of the
<App /> component state, and have it managed by Redux.
From my earlier explanation, you should remember the analogy between the Bank Vault and the Redux Store. The Bank Vault keeps money, the Redux
store keeps the application state object.
So, what is the first step to refactoring the
<App /> component to use Redux?
Yeah, you got that right.
Remove the component state from within
<App />.
The Redux
store will be responsible for managing the App’s
state. With that being said, we need to remove the current state object from
App/>.
import React, { Component } from "react"; import HelloWorld from "./HelloWorld"; class App extends Component { // the state object has been removed. render() { return <HelloWorld tech={this.state.tech}/> } } export default App;
The solution above is incomplete, but right now,
<App/> has no state.
Please install Redux by running
yarn add redux from the command line interface (CLI). We need the
redux package to do anything right.
Creating a Redux Store
If the
<App /> won’t manage it’s state, then we have to create a Redux Store to manage our application state.
For a Bank Vault, a couple mechanical engineers were probably hired to create a secure money-keeping facility.
To create a manageable state-keeping facility for our application, we don’t need mechanical engineers. We’ll do so programmatically using some of the APIs Redux avails to us.
Here’s what the code to create a Redux
store looks like:
import { createStore } from "redux"; //an import from the redux library const store = createStore(); // an incomplete solution - for now.
First we import the
createStore factory function from Redux. Then we invoke the function,
createStore() to create the store.
Now, the
createStore function takes in a few arguments. The first is a
reducer.
So, a more complete store creation would be represented like this:
createStore(reducer)
Now, let me explain why we’ve got a
reducer in there.
The Store and Reducer Relationship
Back to the bank analogy.
When you go to the bank to make a withdrawal, you meet with the Cashier. After you make your
WITHDRAW_MONEY intent/action known to the Cashier, they do not just hand you the requested money.
No.
The Cashier first confirms that you have enough money in your account to perform the withdrawal transaction you seek.
The Cashier first makes sure you have the money you say you do.
From the computer, they can see all that — kind of communicating with the Vault, since the Vault keeps all the money in the bank.
In a nutshell, the Cashier and Vault are always in sync. Great buddies!
The same may be said for a Redux
STORE (our own Vault,) and the Redux
REDUCER (our own Cashier)
The Store and the Reducer are great buddies. Always in sync.
Why?
The
REDUCER always “talks” to the
STORE. Just like the Cashier stays in sync with the Vault.
This explains why the creation of the store needs to be invoked with a
Reducer, and that is mandatory. The
Reducer is the only mandatory argument passed into
createStore()
In the following section we will have a brief look at Reducers and then create a
STORE by passing the
REDUCER into the
createStore factory function.
The Reducer
We will go into greater details pretty soon, but I’ll keep this short for now.
When you hear the word, reducer, what comes to your mind?
Reduce?
Yeah, that’s what I thought.
It sounds like reduce.
Well, according to the Redux official docs:
Reducers are the most important concept in Redux.
Our Cashier is a pretty important person, huh?
So, what’s the deal with the Reducer. What does it do?
In more technical terms, a reducer is also called a reducing function. You may not have noticed, but you probably already use a reducer — if you’re conversant with the
Array.reduce() method.
Here’s a quick refresher.
Consider the code below.
It is a popular way to get the sum of values in a JavaScript Array:
let arr = [1,2,3,4,5] let sum = arr.reduce((x,y) => x + y) console.log(sum) //15
Under the hood, the function passed into
arr.reduce is called a
reducer.
In this example, the reducer takes in two values, an
accumulator and a
currentValue , where
x is the
accumulator and
y is the
currentValue.
In the same manner, the Redux Reducer is just a function. A function that takes in two parameters. The first being the
STATE of the app, and the other the
ACTION .
Oh my gosh! But where does the
STATE and
ACTION passed into the
REDUCER come from?
When I was learning Redux, I asked myself this question a few times.
First, take a look at the
Array.reduce() example again:
let arr = [1,2,3,4,5] let sum = arr.reduce((x,y) => x + y) console.log(sum) //15
The
Array.reduce method is responsible for passing in the needed arguments,
x and
y into the function argument, the
reducer . So, the arguments didn’t come out of thin air.
The same may be said for Redux.
The Redux reducer is also passed into a certain method. Guess what is it?
Here you go!
createStore(reducer)
The
createStore factory function. There’s a little more involved in the process as you’ll soon see.
Like
Array.reduce(),
createStore() is responsible for passing the arguments into the reducer.
If you aren’t scared of technical stuff, here’s the stripped down version of the implementation of
createStore within the Redux source code. } }
Don’t beat yourself up if you don’t get the code above. What I really want to point out is within the
dispatch function.
Notice how the
reducer is called with
state and
action
With all that being said, the most minimal code for creating a Redux
store is this:
import { createStore } from "redux"; const store = createStore(reducer); //this has been updated to include the created reducer.
Getting back to the Refactoring Process
Let’s get back to refactoring the “Hello World” React application to use Redux.
If I lost you at any point in the previous section, please read the section just one more time and I’m sure it’ll sink in. Better still, you can ask me a question.
Okay so here’s all the code we have at this point:
import React, { Component } from "react"; import HelloWorld from "./HelloWorld"; import { createStore } from "redux"; const store = createStore(reducer); class App extends Component { render() { return <HelloWorld tech={this.state.tech}/> } } export default App;
Makes sense?
You may have noticed a problem with this code. See Line 4.
The
reducer function passed into
createStore doesn’t exist yet.
Now we need to write one. The reducer is just a function, remember?
Create a new directory called
reducers and create an
index.js file in there. Essentially, our reducer function will be in the path
src/reducers/index.js .
First export a simple function in this file:
export default () => { }
Remember, that the
reducer takes in two arguments — as established earlier. Right now, we’ll concern ourselves with the first argument,
STATE
Put that into the function, and we have this:
export default (state) => { }
Not bad.
A reducer always returns something. In the initial
Array.reduce()reducer example, we returned the sum of the accumulator and current value.
For a Redux
reducer, you always return the
new state of your application.
Let me explain.
After you walk into the bank and make a successful withdrawal, the current amount of money held in the bank’s vault for you is no longer the same. Now, if you withdrew $200, you are now short $200. Your account balance is down $200.
Again, the Cashier and Vault remain in sync on how much you now have.
Just like the Cashier, this is exactly how the
reducer works.
Like the Cashier, the
reducer always returns the
new state of your application. Just in case something has changed. We don’t want to issue the same bank balance even though a withdrawal action was performed.
We’ll get to the internals of how to change/update the state later on. For now, blind trust will have to suffice.
Now, back to the problem at hand.
Since we aren’t concerned about changing/updating the state at this point, we will keep
new statebeing returned as the same
state passed in.
Here’s the representation of this within the
reducer:
export default (state) => { return state }
If you go to the bank without performing an action, your bank balance remains the same, right?
Since we aren’t performing any
ACTION or even passing that into the reducer yet, we will just
return the same
state.
The Second
createStore Argument
When you visit the Cashier in the bank, if you asked them for your account balance, they’ll look it up and tell it to you.
But how?
When you first created an account with your bank, you either did so with some amount of deposit or not.
Let’s call this the Initial Deposit into your account.
Back to Redux.
In the same way, when you create a redux
STORE (our own money keeping Vault), there’s the option of doing so with an initial deposit.
In Redux terms, this is called the
initialState of the app.
Thinking in code,
initialState is the second argument passed into the
createStore function call.
const store = createStore(reducer, initialState);
Before making any monetary
action, if you requested your bank account balance, the Initial Deposit will always be returned to you.
Afterwards, anytime you perform any monetary
action, this initial deposit will also be updated.
Now, the same goes for Redux.
The object passed in as
initialState is like the initial deposit to the Vault. This
initialState will always be returned as the
state of the application unless you update the state by performing an
action.
We will now update the application to pass in an
initial state:
const initialState = { tech: "React " }; const store = createStore(reducer, initialState);
Note how
initialState is just an object, and it is exactly what we had as the default state in the React App before we began refactoring.
Now, here’s all the code we have at this point — with the
reducer also imported into
App.
App.js
import React, { Component } from "react"; import HelloWorld from "./HelloWorld"; import reducer from "./reducers"; import { createStore } from "redux"; const initialState = { tech: "React " }; const store = createStore(reducer, initialState); class App extends Component { render() { return <HelloWorld tech={this.state.tech}/> } } export default App;
reducers/index.js
export default state => { return state }
If you’re coding along and try to run the app now, you’ll get an error. Why?
Have a look at the
tech prop passed into
<HelloWorld />. It still reads,
this.state.tech.
There’s no longer a state object attached to
<App />, so that will be
undefined.
Let’s fix that.
The solution is quite simple. Since the
store now manages the state of our application, this means the application
STATEobject must be retrieved from the
store. But how?
Whenever you create a store with
createStore(), the created store has three exposed methods.
One of these is
getState().
At any point in time, calling the
getState method on the created
store will return the current state of your application.
In our case,
store.getState() will return the object
{ tech: "React"} since this is the
INITIAL STATE we passed into the
createStore() method when we created the
STORE.
You see how all this comes together now?
Hence the
tech prop will be passed into
<HelloWorld /> as shown below:
App.js
import React, { Component } from "react"; import HelloWorld from "./HelloWorld"; import { createStore } from "redux"; const initialState = { tech: "React " }; const store = createStore(reducer, initialState); class App extends Component { render() { return <HelloWorld tech={store.getState().tech}/> } }
Reducers/Reducer.js
export default state => { return state }
And that is it! You just learned the Redux basics and successfully refactored a simple React app to use Redux.
The React application now has its state managed by Redux. Whatever needs to be gotten from the
state object will be grabbed from the
store as shown above.
Hopefully, you understood this whole refactoring process.
For a quicker overview, have a look at this Github diff.
With the “Hello World” project, we have taken a good look at some essential Redux concepts. Even though it’s such a tiny project, it provides a decent foundation to build upon!
Possible Gotcha
In the just concluded Hello World example, a possible solution you may have come up with for grabbing the
state from the
store may look like this:
class App extends Component { state = store.getState(); render() { return <HelloWorld tech={this.state.tech} />; } }
What do you think? Will this work?
Just as a reminder, the following two ways are correct ways to initialize a React component’s state.
(a)
class App extends Component { constructor(props) { super(props); this.state = {} } }
(b)
class App extends Component { state = {} }
So, back to answering the question, yes, the solution will work just fine.
store.getState() will grab the current state from the Redux
STORE.
However, the assignment,
state = store.getState() will assign the state gotten from Redux to that of the
<App /> component.
By implication, the return statement from
render such as
<HelloWorld tech={this.state.tech} /> will be valid.
Note that this reads
this.state.tech not
store.getState().tech.
Even though this works, it is against the ideal philosophy of Redux.
If, within the app, you now run
this.setState(), the App’s state will be updated without the help of Redux.
This is the default React mechanism, and it isn’t what you want. You want the
state managed by the Redux
STORE to be the single source of truth.
Whether you’re retrieving state, as in
store.getState() or updating/changing
state (as we’ll cover later), you want that to be entirely managed by Redux, not by
setState().
Since Redux manages the app’s
state, all you need to do is feed in
state from the Redux
STORE as props to any required component.
Another big question you’re likely asking yourself is “Why did I have to go through all this stress just to have the state of my App managed by Redux?”
Reducer, Store, createStore blah, blah, blah …
Yeah, I get it.
I felt that way too.
However, consider the fact that you do not just go to the bank and not follow a due process for withdrawing your own money. It’s your money, but you do have to follow a due process.
The same may be said for Redux.
Redux has it’s own “process” for doing things. We’ve got to learn how that works — and hey, you’re not doing badly!
Conclusion and Summary
This chapter has been exciting. We focused mostly on setting a decent foundation for the more interesting things to come.
Here are a few things you learned in this chapter:
- Redux is a predictable state container for JavaScript apps.
- The
createStorefactory function from Redux is used to create a Redux
STORE.
- The
Reduceris the only mandatory argument passed into
createStore()
- A
REDUCERis just a function. A function that takes in two parameters. The first is the
STATEof the app, and the other is an
ACTION.
- A
Reduceralways returns the
new stateof your application.
- The Initial State of your application,
initialStateis the second argument passed into the
createStorefunction call.
Store.getState()will return the current state of your application. Where
Storeis a valid Redux
STORE.
Introducing Exercises
Please, please, please, don’t skip the exercises. Especially if you’re not confident about your Redux skills and really want to get the best out of this guide.
So, grab your dev hats, and write some code :)
Also, if you want me to give you feedback on any of your solutions at any point in time, tweet at me with the hashtag #UnderstandingRedux and I’ll be happy to have a look. I’m not promising to get to every single tweet, but I’ll definitely try!
Once you get the exercises sorted out, I’ll see you in the next section.
Remember that a good way to read long content is to break it up into shorter digestible bits. These exercises help you do just that. You take some time off, try to solve the exercises, then you come back to read on. That’s an effective way to study.
Want to see my solutions to these exercises? I have included the solutions to the exercises in the book package. You’ll find instructions on how to get the accompanying code and exercise solutions once you download the (free) Ebook (PDF & Epub).
So, here’s the exercise for this section.
Exercise
(a) Refactor the user card app to use Redux
In the accompanying code files for the book, you’ll find a user card app written solely in React. The state of the App is managed via React. Your task is to move the state to being managed solely by Redux.
Chapter 3 : Understanding State Updates with Actions
Now that we’ve discussed the foundational concepts of Redux, we will begin to do some more interesting things.
In this chapter, we will continue to learn by doing as I walk you through another project — while explaining every process in detail.
So, what project are going to work on this time?
I’ve got the perfect one.
Please, consider the mockup below:
Oh, it looks just like the previous example — but with a few changes. This time we will take account of user actions. When we click any of the buttons, we want to update the state of the application as shown in the GIF below:
Here’s how this is different from the previous example. In this scenario, the user is performing certain actions that influence the state of the application. In the former example, all we did was display the initial state of the app with no user actions taken into consideration.
What is a Redux Action?
When you walk into a bank, the Cashier receives your action, that is, your intent for coming into the bank. In our previous example, it was
WITHDRAWAL_MONEY . The only way money leaves the bank Vault is if you make your action or intent known to the Cashier.
Now, the same goes for the Redux Reducer.
Unlike
setState() in pure React, the only way you update the state of a Redux application is if you make your intent known to the REDUCER.
But how?
By dispatching actions!
In the real world, you know the exact action you want to perform. You could probably write that down on a slip and hand it over to the Cashier.
This works almost the same way with Redux. The only challenge is, how do you describe an action in a Redux app? Definitely not by speaking over the counter or writing it down on a slip.
Well, there’s good news.
An action is accurately described with a plain JavaScript object. Nothing more.
There’s just one thing to be aware of. An action must have a
type field. This field describes the intent of the action.
In the bank story, if we were to describe your action to the bank, it’d look like this:
{ type: "withdraw_money" }
That’s all, really.
A Redux action is described as a plain object.
Please have a look at the action above.
Do you think only the
type field accurately describes your supposed action to make a withdrawal at a bank?
Hmmm. I don’t think so. How about the amount of money you want to withdraw?
Many times your action will need some extra data for a complete description. Consider the action below. I argue that this makes for a more well-described action.
{ type: "withdraw_money", amount: "$4000" }
Now, there’s sufficient information describing the action. For the sake of the example, ignore every other detail the action may include, such as your bank account number.
Other than the
type field, the structure of your Redux Action is really up to you.
However, a common approach is to have a
type field and
payload field as shown below:
{ type: " ", payload: {} }
The
type field describes the action, and all other required data/information that describes the action is put in the
payload object.
For example:
{ type: "withdraw_money", payload: { amount: "$4000" } }
So, yeah! That’s what an action is.
Handling Responses to Actions in the Reducer
Now that you successfully understand what an action is, it is important to see how they become useful in a practical sense.
Earlier, I did say that a reducer takes in two arguments. One
state, the other
action.
Here’s what a simple Reducer looks like:
function reducer(state, action) { //return new state }
The
action is passed in as the second parameter to the Reducer. But we’ve done nothing with it within the function itself.
To handle the actions passed into the reducer, you typically write a
switch statement within your reducer, like this:
function reducer (state, action) { switch (action.type) { case "withdraw_money": //do something break; case "deposit-money": //do something break; default: return state; } }
Some people seem not to like the
switch statement, but it’s basically an
if/else for possible values on a single field.
The code above will
switch over the action
type and do something based on the type of action passed in. Technically, the do something bit is required to return a new state.
Let me explain further.
Assume that you had two hypothetical buttons, button #1 and button #2, on a certain webpage, and your state object looked something like this:
{ isOpen: true, isClicked: false, }
When button #1 is clicked, you want to toggle the
isOpen field. In the context of a React app, the solution is simple. As soon as the button is clicked, you would do this:
this.setState({isOpen: !this.state.isOpen})
Also, let’s assume that when #2 is clicked, you want to update the
isClicked field. Again, the solution is simple, and along the lines of this:
this.setState({isClicked: !this.state.isClicked})
Good.
With a Redux app, you can’t use
setState() to update the state object managed by Redux.
You have to dispatch an action first.
Let’s assume the actions are as below:
#1 :
{ type: "is_open" }
#2 :
{ type: "is_clicked" }
In a Redux app, every action flows through the reducer.
All of them. So, in this example, both action #1 and action #2 will pass through the same reducer.
In this case, how does the reducer differentiate each of them?
Yeah, you guessed right.
By switching over the
action.type , we can handle both actions without hassle.
Here is what I mean:
function reducer (state, action) { switch (action.type) { case "is_open": return; //return new state case "is_clicked": return; //return new state default: return state; } }
Now you see why the
switch statement is useful. All actions will flow through the reducer. Thus, it is important to handle each action type separately.
In the next section, we will continue with the task of building the mini app below:
Examining the Actions in the Application
As I explained earlier, whenever there’s an intent to update the application state, an
action must be dispatched.
Whether that intent is initiated by a user click, or a timeout event, or even an Ajax request, the rule remains the same. You have to dispatch an action.
The same goes for this application.
Since we intend to update the state of the application, whenever any of the buttons is clicked, we must dispatch an action.
Firstly, let’s describe the actions.
Give it a try and see if you get it.
Here’s what I came up with:
For the React button:
{ type: "SET_TECHNOLOGY", text: "React" }
For the React-Redux button:
{ type: "SET_TECHNOLOGY", text: "React-redux" }
And finally:
{ type: "SET_TECHNOLOGY", text: "Elm" }
Easy, right?
Note that the three actions have the same
type field. This is because the three buttons all do the same thing. If they were customers in a bank, then they’d all be depositing money, but different amounts of money. The
type of action will then be
DEPOSIT_MONEY but with different
amount fields.
Also, you’ll notice that the action type is all written in capital letters. That was intentional. It’s not compulsory, but it’s a pretty popular style in the Redux community.
Hopefully you now understand how I came up with the actions.
Introducing Action Creators
Take a look at the actions we created above. You’ll notice that we are repeating a few things.
For one, they all have the same
type field. If we had to dispatch these actions in multiple places, we’d have to duplicate them all over the place. That’s not so good. Especially because it’s a good idea idea to keep your code DRY.
Can we do something about this?
Sure!
Welcome, Action Creators.
Redux has all these fancy names, eh? Reducers, Actions, and now, Action Creators :)
Let me explain what those are.
Action Creators are simply functions that help you create actions. That’s all. They are functions that return action objects.
In our particular example, we could create a function that will take in a
text parameter and return an action, like this:
export function setTechnology (text) { return { type: "SET_TECHNOLOGY", tech: text } }
Now we don’t have to bother about duplicating code everywhere. We can just call the
setTechnology action creator at any time, and we’ll get an action back!
What a good use of functions.
Using ES6, the action creator we created above could be simplified to this:
const setTechnology = text => ({ type: "SET_TECHNOLOGY", text });
Now, that’s done.
Bringing Everything Together
I’ve discussed all important components required to build the more advanced Hello World app in isolation in the earlier sections.
Now, let’s put everything together and build the app. Excited?
Firstly, let’s talk about folder structure.
When you get to a bank, the Cashier likely sits in their own cubicle/office. The Vault is also kept safe in a secure room. For good reasons, things feel a little more organized that way. Everyone in their own space.
The same may be said for Redux.
It is a common practice to have the major actors of a redux app live within their own folder/directory.
By actors, I mean, the
reducer,
actions,and
store.
It is common to create three different folders within your app directory, and name each after these actors.
This isn’t a must — and inevitably, you decide how you want to structure your project. For big applications, though, this is certainly a pretty decent practice.
We’ll now refactor the current app directories we have. Create a few new directories/folders. One called
reducers, another,
store, and the last one,
actions
You should now have a component structure that looks like this:
In each of the folders, create an
index.js file. This will be the entry point for each of the Redux actors (reducers, store, and actions). I call them actors, like movie actors. They are the major components of a Redux system.
Now, we’ll refactor the previous app from Chapter 2: Your First Redux Application, to use this new directory structure.
store/index.js
import { createStore } from "redux"; import reducer from "../reducers"; const initialState = { tech: "React " }; export const store = createStore(reducer, initialState);
This is just like we had before. The only difference is that the store is now created in its own
index.js file, like having separate cubicles/offices for the different Redux actors.
Now, if we need the store anywhere within our app, we can safely import the store, as in
import store from "./store";
With that being said, the
App.js file for this particular example is slightly different from the former.
App.js
import React, { Component } from "react"; import HelloWorld from "./HelloWorld"; import ButtonGroup from "./ButtonGroup"; import { store } from "./store"; class App extends Component { render() { return [ <HelloWorld key={1} tech={store.getState().tech} />, <ButtonGroup key={2} technologies={["React", "Elm", "React-redux"]} /> ]; } } export default App;
What is different?
In line 4, the store is imported from it’s own ‘cubicle’. Also, there’s now a
<ButtonGroup /> component that takes in an array of technologies and spits out buttons. The
ButtonGroup component handles the rendering of the three buttons below the “Hello World” text.
Also, you may notice that the
App component returns an array. That’s a
React 16 goodie. With React 16, you don’t have to wrap adjacent
JSX elements in a
div. You can use an array if you want — but pass in a
key prop to each element in the array.
That is it for the
App.js component.
The implementation of the
ButtonGroup component is quite simple. Here it is:
ButtonGroup.js
import React from "react"; const ButtonGroup = ({ technologies }) => ( <div> {technologies.map((tech, i) => ( <button data-tech={tech} key={`btn-${i}`} {tech} </button> ))} </div> ); export default ButtonGroup;
ButtonGroup is a stateless component that takes in an array of technologies, denoted by
technologies.
It loops over this array using
map and renders a
<button></button for each of the tech in the array.
In this example, the buttons array passed in is
["React", "Elm", "React-redux"]
The buttons generated have a few attributes. There’s the obvious
className for styling purposes. There’s
key to prevent the pesky React warning about rendering multiple items without a key prop. Gosh, that error haunts me every time :(
Lastly, there’s a
data-tech attribute on each
button too. This is called a data attribute. It is a way to store some extra information that doesn’t have any visual representation. It makes it slightly easier to grab certain values off of an element.
A completely rendered button will look like this:
<button data- React </button>
Right now, everything renders correctly, but upon clicking the button, nothing happens yet.
Well, that’s because we haven’t provided any click handlers yet. Let’s do that now.
Within the
render function, let’s set up an
onClick handler:
<div> {technologies.map((tech, i) => ( <button data-tech={tech} key={`btn-${i}`} className="hello-btn" onClick={dispatchBtnAction} > {tech} </button> ))} </div>
Good. Let’s write the
dispatchBtnAction now.
Don’t forget that the sole aim of this handler is to dispatch an action when a click has happened.
For example, if you click the React button, dispatch the action:
{ type: "SET_TECHNOLOGY", tech: "React" }
If you click the React-Redux button, dispatch this action:
{ type: "SET_TECHNOLOGY", tech: "React-redux" }
So, here’s the
dispatchBtnAction function.
function dispatchBtnAction(e) { const tech = e.target.dataset.tech; store.dispatch(setTechnology(tech)); }
Hmmm. Does the code above make sense to you?
e.target.dataset.tech will get the data attribute set on the button,
data-tech . Hence,
tech will hold the value of the text.
store.dispatch() is how you dispatch an action in Redux, and
setTechnology() is the action creator we wrote earlier!
function setTechnology (text) { return { type: "SET_TECHNOLOGY", text: text } }
I have gone ahead and added a few comments in the illustration below, just so you understand the code.
Like you already know,
store.dispatch expects an action object, and nothing else. Don’t forget the
setTechnology action creator. It takes in the button text and returns the required action.
Also, the
tech of the button is grabbed from the dataset of the button. You see, that’s exactly why I had a
data-tech attribute on each button. So we could easily grab the tech off each of the buttons.
Now we’re dispatching the right actions. Can we tell if this works as expected now?
Actions Dispatched. Does this Thing Work?
Firstly, here’s a short quiz question. Upon clicking a
button and consequently dispatching an action, what happens next within Redux? Which of the Redux actors come into play?
Simple. When you hit the bank with a
WITHRAW_MONEY action, to whom do you go? The Cashier, yes.
Same thing here. The actions, when dispatched, flow through the reducer.
To prove this, I’ll log whatever action comes into the reducer.
reducers/index.js
export default (state, action) => { console.log(action); return state; };
The reducer then returns the new sate of the app. In our particular case, we’re just returning the same initial
state .
With the
console.log() in the reducer, let’s have a look at what happens when we click.
Oh, yeah!
The actions are logged when the buttons are clicked. Which proves that the actions indeed go through the Reducer. Amazing!
There’s one more thing though. As soon as the app starts, there’s a weird action being logged as well. It looks like this:
{type: "@@redux/INITu.r.5.b.c"}
What’s that?
Well, do not concern yourself so much about that. It is an action passed by Redux itself when setting up your app. It is usually called the Redux
init action, and it is passed into the reducer when Redux initializes your application with the initial state of the app.
Now, we are sure that the actions indeed pass through the Reducer. Great!
While that’s exciting, the only reason you go to the Cashier with a withdrawal request is because you want money. If the Reducer isn’t taking the action we pass in and doing something with our action, of what value is it?
Making the Reducer Count
Up until now, the reducer we’ve worked on hasn’t done anything particularly smart. It’s like a Cashier who is new to the job and does nothing with our
WITHDRAW_MONEY intent.
What exactly do we expect the reducer to do?
For now, here’s the
initialState we passed into
createStore when the
STORE was created.
const initialState = { tech: "React" }; export const store = createStore(reducer, initialState);
When a user clicks any of the buttons, thus passing an action to the reducer, the new state we expect the reducer to return should have the action text in there!
Here’s what I mean.
Current state is
{ tech: "React"}
Given a new action of type
SET_TECHNOLOGY, and text,
React-Redux :
{ type: "SET_TECHNOLOGY", text: "React-Redux" }
What do you expect the new state to be?
Yeah,
{tech: "React-Redux"}
The only reason we dispatched an action is because we want a new application state!
Like I mentioned earlier, the common way to handle different action types within a reducer is to use the JavaScript
switch statement as shown below:
export default (state, action) => { switch (action.type) { case "SET_TECHNOLOGY": //do something. default: return state; } };
Now we
switch over the
action type. But why?
Well, if you went to see a Cashier, you could have many different actions in mind.
You could want to
WITHDRAW_MONEY, or
DEPOSIT_MONEY or maybe just
SAY_HELLO.
The Cashier is smart, so they take in your action and respond based on your intent.
This is exactly what we’re doing with the Reducer.
The
switch statement checks the
type of the action.
What do you want to do? Withdraw, deposit, whatever…
After that, we then handle the known
cases we expect. For now, there’s just one
case which is
SET_TECHNOLOGY.
And by default, be sure to just return the
state of the app.
So far so good.
The Cashier (
Reducer) now understands our action. However, they aren’t giving us any money (
state) yet.
Let’s do something within the
case.
Here’s the updated version of the reducer. One that actually gives us money :)
export default (state, action) => { switch (action.type) { case "SET_TECHNOLOGY": return { ...state, tech: action.text }; default: return state; } };
Aw, yeah!
You see what I’m doing there?
I’ll explain what’s going on in the next section.
Never Mutate State Within the Reducers
When returning
state from reducers, there’s something that may put you off at first. However, if you already write good React code, then you should be familiar with this.
You should not mutate the
state received in your Reducer. Instead, you should always return a new copy of the state.
Technically, you should never do this:
export default (state, action) => { switch (action.type) { case "SET_TECHNOLOGY": state.tech = action.text; return state; default: return state; } };
This is exactly why the reducer I’ve written returned this:
return { ...state, tech: action.text };
Instead of mutating (or changing) the state received from the reducer, I am returning a new object. This object has all the properties of the previous state object. Thanks to the ES6 spread operator,
...state. However, the
tech field is updated to what comes in from the action,
action.text.
Also, every Reducer you write should be a pure function with no side-effects — No API calls or updating a value outside the scope of the function.
Got that?
Hopefully, yes.
Now, the Cashier isn’t ignoring our actions. They’re in fact giving us cash now!
After doing this, click the buttons. Does it work now?
Gosh it still this doesn’t work. The text doesn’t update.
What in the world is wrong this time?
Subscribing to Store Updates
When you visit the bank, let the Cashier know your intended
WITHDRAWAL action, and successfully receive your money — so what’s next?
Most likely, you will receive an alert via email/text or some other mobile notification saying you have performed a transaction, and your new account balance is so and so.
If you don’t receive mobile notifications, you’ll definitely receive some sort of “personal receipt” to show that a successful transaction was carried out on your account.
Okay, note the flow. An action was initiated, you received your money, you got an alert for a successful transaction.
We seem to be having a problem with our Redux code.
An action has been successfully initiated, we’ve received money (state), but hey, where’s the alert for a successful state update?
We’ve got none.
Well, there’s a solution. Where I come from, you subscribe to receive transaction notifications from the bank either by email/text.
The same is true for Redux. If you want the updates, you’ve got to subscribe to them.
But how?
The Redux store, whatever store you create has a
subscribe method called like this:
store.subscribe().
A well-named function, if you ask me!
The argument passed into
store.subscribe() is a function, and it will be invoked whenever there’s a state update.
For what it’s worth, please remember that the argument passed into
store.subscribe() should be a function. Okay?
Now let’s take advantage of this.
Think about it. After the state is updated, what do we want or expect? We expect a re-render, right?
So, state has been updated. Redux, please, re-render the app with the new state values.
Let’s have a look at where the app is being rendered in
index.js
Here’s what we’ve got.
ReactDOM.render(<App />, document.getElementById("root")
This is the line that renders the entire application. It takes the
App/> component and renders it in the DOM. The
root ID to be specific.
First, let’s abstract this into a function.
See this:
const render = function() { ReactDOM.render(<App />, document.getElementById("root") }
Since this is now within a function, we have to invoke the function to
render the app.
const render = function() { ReactDOM.render(<App />, document.getElementById("root") } render()
Now, the
<App /> will be rendered just like before.
Using some ES6 goodies, the function can be made simpler.
const render = () => ReactDOM.render(<App />, document.getElementById("root")); render();
Having the rendering of the
<App/> wrapped within a function means we can now subscribe to updates to the store like this:
store.subscribe(render);
Where
render is the entire render logic for the
<App /> — the one we just refactored.
You understand what’s happening here, right?
Any time there’s a successful update to the store, the
<App/> will now be re-rendered with the new state values.
For clarity, here’s the
<App/> component:
class App extends Component { render() { return [ <HelloWorld key={1} tech={store.getState().tech} />, <ButtonGroup key={2} technologies={["React", "Elm", "React-redux"]} /> ]; } }
Whenever a re-render occurs,
store.getState() on line 4 will now fetch the updated state.
Let’s see if the app now works as expected.
Yeah! This works, and I knew we could do this!
We are successfully dispatching an action, receiving money from the Cashier, and then subscribing to receive notifications. Perfect!
Important Note on Using store.subscribe()
There are a few caveats to using
store.subscribe() as we’ve done here. It’s a low-level Redux API.
In production, and largely for performance reasons, you’ll likely use bindings such as
react-redux when dealing with larger apps. For now, it is safe to continue using
store.subscribe() for our learning purposes.
In one of the most beautiful PR comments I’ve seen in a long time, Dan Abramov, in one of the Redux application examples, said:.
I believe the same.
When learning Redux, especially if you’re just starting out, you can do away with as many “extras” as possible.
Learn to walk first, then you can run as much as you want.
Okay, Are We Done Yet?
Yeah, we’re done, technically. However, there’s one more thing I’d love to show you. I’ll bring up my browser Devtools and enable paint-flashing.
Now, as we click and update the state of the app, note the green flashes that appear on the screen. The green flashes represent parts of the app being re-painted or re-rendered by the Browser engine.
Have a look:
As you can see, even though it appears that the
render function is invoked every time a state update is made, not the entire app is re-rendered. Just the component with a new state value is re-rendered. In this case, the
<HelloWorld/> component.
One more thing.
If the current state of the app renders,
Hello World React, clicking the
Reactbutton again doesn’t re-render since the state value is the same.
Good!
This is the React Virtual DOM
Diff algorithm at work here. If you know some React, you must have heard this before.
So, yeah. We’re done with this section! I’m having so much fun explaining this. I hope you are enjoying the read, too.
Conclusion and Summary
For a supposedly simple application, this chapter was longer than you probably anticipated. But that’s fine. You’re now equipped with even greater knowledge on how Redux works.
Here are a few things you learned in this chapter:
- Unlike
setState()in pure React, the only way you update the state of a Redux application is by dispatching an action.
- An action is accurately described with a plain JavaScript object, but it must have a
typefield.
- In a Redux app, every action flows through the reducer. All of them.
- By using a
switchstatement, you can handle different action types within your Reducer.
- Action Creators are simply functions that return action objects.
- It is a common practice to have the major actors of a redux app live within their own folder/directory.
- You should not mutate the
statereceived in your Reducer. Instead, you should always return a new copy of the state.
- To subscribe to store updates, use the
store.subscribe()method.
Exercises
Okay, now it’s your time to do something cool.
- In the exercise files, I have set up a simple React application that models a user’s bank application.
Have a good look at the mockup above. In addition to the the user being able to view their total balance, they can also perform withdrawal actions.
The
name and
balance of the user are stored in the application state.
{ name: "Ohans Emmanuel", balance: 1559.30 }
There are two things you need to do.
(i) Refactor the App’s state to be managed solely by Redux.
(ii) Handle the withdrawal actions to actually deplete the user’s balance (that is, on clicking the buttons, the balance reduces).
You must do this via Redux only.
As a reminder, upon downloading the Ebook, you’ll find instructions on how to get the accompanying code files, exercise files, and exercise solutions as well.
2. The following image is that of a time counter created as a React application.
The state object looks like this:
{ days: 11, hours: 31, minutes: 27, seconds: 11, activeSession: "minutes" }
Depending on the active session, clicking any of the “increase” or “decrease” buttons should update the value displayed in the counter.
There are two things you need to do.
(i) Refactor the App’s state to be managed solely by Redux.
(ii) Handle the increase and decrease actions to actually affect the displayed time on the counter.
Chapter 4: Building Skypey: A More Advanced Example.
We’ve come a long way, and I salute you for following along.
In this section, I will walk you through the process of building a more advanced example.
Even though we’ve covered a lot of ground on the basics of Redux, I really think this example will give you a deeper perspective as to how some of the concepts you’ve learned work on a much broader scale.
We will talk about planning your application, designing and normalizing the state object, and a lot more. Real apps require much more than just Redux. You’ll still need some CSS and React as well.
Buckle up, as this will be a long worthy ride!
Planning the Application
Okay. Here’s the big question. What do you generally do first when starting a new React application?
Well, we all have our preferences.
Do you break down the entire application into components and build your way up?
Do you start off with the overall layout of the application first?
How about the state object of your app? Do you spend sometime thinking about that too?
There’s indeed a lot to put into consideration. I’ll leave you with your preferred way of doing things.
In building Skypey, I’ll take a top-down approach. We’ll discuss the overall layout of the app, then the design of the app’s state object, then we’ll build out the smaller components.
Again, there isn’t a perfect way to do this. For a more complex project, perhaps, a bottom-top approach would suit that.
One more time, here’s the finished result we are gunning for:
Resolving the Initial App Layout
From the CLI, create a new react app with
create-react-app, and call it
Skypey.
create-react-app Skypey
Skypey’s layout is a simple 2-column layout. A fixed width sidebar on the left, and on the right a main section that takes up the remaining viewport width.
Here’s a quick note on how this app is styled.
If you’re a more experienced Engineer, be sure to use whatever CSS in JavaScript solution works for you. For simplicity, I’ll style the Skypey app with good ‘ol CSS — nothing more.
Let’s get cracking.
Create two new files,
Sidebar.js and
Main.js within the root directory.
As you may have guessed, by the time we build out the
Sidebar and
Main components, we will have it rendered within the
App component like this:
App.js
const App = () => { return ( <div className="App"> <Sidebar /> <Main /> </div> ); };
I suppose you’re familiar with the structure of a
create-react-app project. There’s the entry point of the app,
index.js which renders an
App component.
Before moving on to building the Sidebar and Main components, first some CSS house-keeping. Make sure that the DOM node where the app is rendered,
#root , takes up the entire height of the viewport.
index.css
#root { height: 100vh; }
While you’re at it, you should also remove any unwanted spacing from
body:
body { margin: 0; padding: 0; font-family: sans-serif; }
Good!
The layout of the app will be structured using Flexbox.
Get the Flexbox juice running by making
.App a
flex-container and making sure it takes up 100% of the available height.
App.css
.App { height: 100%; display: flex; color: rgba(189, 189, 192, 1); }
Now, we can comfortably get to building the
Sidebar and
Main components.
Let’s keep it simple for now.
Sidebar.js
import React from "react"; import "./Sidebar.css"; const Sidebar = () => { return <aside className="Sidebar">Sidebar</aside>; }; export default Sidebar;
All that is rendered is the text
Sidebar within an
<aside> element. Also, note that a corresponding stylesheet,
Sidebar.css , has been imported too.
Within
Sidebar.css we need to restrict the width of the Sidebar, plus a few other simple styles.
Sidebar.css
.Sidebar { width: 80px; background-color: rgba(32, 32, 35, 1); height: 100%; border-right: 1px solid rgba(189, 189, 192, 0.1); transition: width 0.3s; } /* not small devices */ @media (min-width: 576px) { .Sidebar { width: 320px; } }
Taking a mobile-first approach, the
width of the Sidebar will be
80px and
320px on larger devices.
Okay, now on to the
Main component.
Like before, we’ll keep this simple.
Simply render a simple text within a
<main> element.
While developing apps, you want to be sure to build progressively. In other words, build in bits, and make sure that the app works.
Below’s the
<Main> component:
import React from "react"; import "./Main.css"; const Main = () => { return <main className="Main">Main Stuff</main>; }; export default Main;
Again, a corresponding stylesheet,
Main.css , has been imported.
With the rendered elements of both
<Main /> and
<Sidebar />, there exist the CSS class names,
.Main and
.Sidebar .
Since the components are both rendered within
<App /> , the
.Sidebarand
.Main classes are children of the parent class,
.App.
Remember that
.App is a flex-container. Consequently,
.Main can be made to fill the remaining space in the viewport like this:
.Main { flex: 1 1 0; }
Now, here’s the full code:
.Main { flex: 1 1 0; background-color: rgba(25, 25, 27, 1); height: 100%; }
That was easy :)
And here’s the result of all the code we’ve written up until this point.
Not so exciting. Patience. We’ll get there.
For now, the basic layout of the application is set. Well done!
Designing the State object
The way React apps are created is that your entire App is mostly a function of the
state object.
Whether you’re creating a sophisticated application, or something simple, a lot of thought should be put into how you’ll structure the state object of your app.
Particularly when working with Redux, you can reduce a lot of complexity by designing the state object correctly.
So, how do you do it right?
First, consider the Skypey app.
A user of the app has multiple contacts.
Each contact in turn has a number of messages, making up their conversation with the main app user. This view is activated when you click any of the contacts.
By association, you wouldn’t be wrong to have a picture like this in your mind.
You may then go on to describe the state of the app like this.
Okay, in plain JavaScript, here’s what you’d likely have:
const state = { user: [ { contact1: 'Alex', messages: [ 'msg1', 'msg2', 'msg3' ] }, { contact2: 'john', messages: [ 'msg1', 'msg2', 'msg3' ] } ]
Within the
state object above is a
user field represented by a giant array. Since the user has a number of contacts, those are represented by objects within the array. Oh, since there could be many different messages, these are stored in an array, too.
At first glance, this may look like a decent solution.
But is it?
If you were to receive data from some back-end, the structure may look just like this!
Good, right?
No mate. Not so good.
This is a pretty good representation of data. It seems like it shows the relationship between each entity, but in terms of the state of your front-end application, this is a bad idea. Bad is a strong word. Let’s just say, there’s a better way to do this.
Here’s how I see it.
If you had to manage a football team, a good plan would be to pick out the best scorers in the team, and put them in the front to get you goals.
You can argue that good players can score from wherever — yes. I bet they’ll be more effective when they are well positioned in front of the opposition’s goal post.
The same goes for the state object.
Pick out the front runners within the state object, and place them in “front”.
When I say “front runners”, I mean the fields of the state object you’ll be performing more CRUD actions on. The parts of the state you’ll be Creating, Reading, Updating and Deleting more often than others. The parts of the state that are core to the application.
This is not an iron-clad rule, but it is a good metric to go by.
Looking at the current state object and the needs of our application, we can pick out the “front runners” together.
For one, we’ll be reading the “Messages” field quite often — for each user’s contact. There’s also the need to edit and delete a user’s message.
Now, that’s a front runner right there.
The same goes for “Contacts” too.
Now, let’s place them “in front.”
Here’s how.
Instead of having the “Messages” and “Contacts” fields nested, pick them out, and make them primary keys within the state object. Like this:
const state = { user: [], messages: [ 'msg1', 'msg2' ], contacts: ['Contact1', 'Contact2'] }
This is still an incomplete representation, but we have greatly improved the representation of the app’s state object.
Now let’s keep going.
Remember that a user can message any of their contacts. Right now, the
messages and
contact field within the state object are independent.
After making these fields primary keys within the state object, there’s nothing that shows the relationship between a certain message and the associated contact. They are independent, and that’s not good because we need to know what list of messages belongs to whom. Without knowing that, how do we render the correct messages when a contact is clicked?
No way. We can’t.
Here’s one way to handle this:
const state = { user: [], messages: [ { messageTo: 'contact1', text: "Hello" }, { messageTo: 'contact2', text: "Hey!" } ], contacts: ['Contact1', 'Contact2'] }
So, all I’ve done is make the
messages field an array of message objects. objects with a
messageTo key. This key shows which contact a particular message belongs to.
We are getting close. Just a bit of refactoring, and we are done.
Instead of just an array, a user may be better described by an object — a
user object.
user: { name, email, profile_pic, status:, user_id }
A user will have a name, email, profile picture, fancy text status and a unique user ID. The user ID is important — and must be unique for each user.
Think about it. The contacts of a person may also be represented by a similar user object.
So, the
contacts field within the state object may be represented by a list of user objects.
contacts: [ { name, email, profile_pic, status, user_id }, { name, email, profile_pic, status, user_id_2 } ]
Okay. So far so good.
The
contacts field is now represented by a huge array of
user objects.
However, instead of using an array, we can have the
contacts represented by an object, too. Here’s what I mean.
Instead of wrapping all the user contacts in a giant array, they could also be put in an object.
See below:
contacts: { user_id: { name, email, profile_pic, status, user_id }, user_id_2: { name, email, profile_pic, status, user_id_2 } }
Since objects must have a key value pair, the unique IDs of the contacts are used as keys to their respective user objects.
Makes sense?
There’s some advantages to using objects over arrays. There’s also downsides.
In this application, I’ll mostly be using objects to describe the fields within the state object.
If you’re not used to this approach, this lovely video explains some of the advantages to it.
Like I said earlier, there are a few disadvantages to this approach, but I’ll show you how to get over them.
We have resolved how the
contacts field will be designed within the application state object. Now, let’s move unto the
messages field.
We currently have the
messages as an array with message objects.
messages: [ { messageTo: 'contact1', text: "Hello" }, { messageTo: 'contact2', text: "Hey!" } ]
We will now define a more appropriate shape for the message objects. A message object will be represented by the message object below:
{ text, is_user_msg };
The
text is the displayed text within the chat bubble. However,
is_user_msg will be a Boolean — true or false. This is important to differentiate if a message is from a contact or the default app user.
Looking at the graphic above, you’ll notice that the user’s messages and those of a contact are styled differently in the chat window. The user’s messages stay on the right, and the contact, on the left. One is blue, the other is dark.
You now see why the boolean,
is_user_msg is important. We need it to render the messages appropriately.
For example, the message object may look like this:
{ text: "Hello there. U good?", is_user_msg: false }
Now, representing the
messages field within the state with an object, we should have something like this:
messages: { user_id: { text, is_user_msg }, user_id_2: { text, is_user_msg } }
Notice how I’m also using an object instead of an array again. Also, we’re going to map each message to the unique key,
user_id of the contact.
This is because a user can have different conversations with different contacts, and it is important to show this representation within the state object. For example, when a contact is clicked, we need to know which was clicked!
How do we do this? Yes, with their
user_id.
The representation above is incomplete but we’ve made a whole lot of progress! The
messages field we’ve represented here assumes that each contact (represented by their unique user id) has only one message.
But, that’s not always the case. A user can have many messages sent back and forth within a conversation.
So how do we do this?
The easiest way is to have an array of messages, but instead, I’ll represent this with objects:
messages: { user_id: { 0: { text, is_user_msg }, 1: { text, is_user_msg } }, user_id_2: { 0: { text, is_user_msg } } }
Now, we are taking into consideration whatever amount of messages are sent within a conversation. One message, two messages, or more, they are now represented in the
messages representation above.
You may be wondering why I have used numbers,
0,
1 and so on to create a mapping for each contact message.
I’ll explain that next.
For what it’s worth, the process of removing nested entities from your state object and designing it like we’ve done here is called “Normalizing the State Object”. I don’t want you confused in case you see that somewhere else.
The Major Problem with Using Objects Over Arrays
I love the idea of using objects over arrays — for most use cases. There are some caveats to be aware of, though.
Caveat #1 : It’s a lot easier to iterate over Arrays in your view logic
A common situation you’ll find yourself in is the need to render a list of components.
For example, to render a list of users given a
users prop, your logic would look something like this:
const users = this.props.users; users.map(user => { return <User /> })
However, if
users were stored in the state as an object, when retrieved and passed on as
props,
users will remain an object. You can’t use
map on objects — and it’s a lot harder to iterate over them.
So, how do we resolve this?
Solution #1a:
Use
Lodash for iterating over objects.
For the uninitiated,
Lodash is a robust JavaScript utility library. Even for iterating over arrays, many would argue that you still use
Lodash as it helps deal with falsey values.
The syntax for using
Lodash for iterating over objects isn’t hard to grasp. It looks like this:
//import the library import _ from "lodash" //use it _.map(users, (user) => { return <User /> })
You call the
map method on the
Lodash object,
_.map(). You pass in the object to be iterated over, and then pass in a callback function like you would with the default JavaScript
map function.
Solution #1b:
Consider the usual way you’d map over an array to create a rendered list of users:
const users = this.props.users; users.map(user => { return <User /> })
Now, assume that
users was an object. This means we can’t
map over it. What if we could easily convert
users to an array without much hassle?
Lodash to the rescue again.
Here’s what that would look like:
const users = this.props.users; //this is an object. _.values(users).map(user => { return <User /> })
You see that?
_.values() will convert the object to an array. This makes
map possible!
Here’s how that works.
If you had a
users object like this:
{ user_id_1: {user_1_object}, user_id_2 {user_2_object}, user_id_3: {user_3_object}, user_id_4: {user_4_object}, }
_.values(users) will convert that to this:
[ {user_1_object}, {user_2_object}, {user_3_object}, {user_4_object}, ]
Yes! An array with the object values. Exactly what you need to iterate over. Problem solved.
There’s one more caveat. It’s perhaps a bigger one.
Caveat #2 : Preservation of Order
This is perhaps the number one reason people use arrays. Arrays preserve the order of their values.
You have to see an example to understand this.
const numbers = [0,3,1,6,89,5,7,9]
Whatever you do, fetching the value of
numbers will always return the same array, with the order of the inputs unaltered.
How about an object?
const numbers = { 0: "Zero", 3: "Three", 1: "One", 6: "Six", 89: "Eighty-nine", 5: "Five", 7: "Seven", 9: "Nine" }
The order of the numbers is the same as in the array before.
Now, watch me copy and paste this in the browser console, and then try to retrieve the values.
Ok, you might have missed that. Look below:
See the highlights in the image above. The order of the object values aren’t returned in the same way!
Now, depending on the kind of application you’re building, this can cause very serious problems. Especially in apps where order is paramount.
You know any examples of such app?
Well, I do. A chat application!
If you’re representing user conversations as an object, you sure care about the order in which the messages are displayed!
You don’t want a message sent yesterday, showing like it was sent today. Order matters.
So, how would you solve this?
Solution #2:
Keep a separate array of IDs to denote order.
You must have seen this before, but you perhaps didn’t pay attention.
For example, if you had the following object:
const numbers = { 0: "Zero", 3: "Three", 1: "One", 6: "Six", 89: "Eighty-nine", 5: "Five", 7: "Seven", 9: "Nine" }
You could keep another array to denote the order of values.
numbersOrderIDs: [0, 3, 1, 6, 89, 5, 7, 9]
This way you can always keep track of the order of values — regardless of the behavior of the object. If you need to add values to the object, you do so, but push the associated ID to the
numbersOrderIDs as well.
It is important to be aware of these things as you may not always have control over some things. You may pick up applications with state modeled in this way. And even if you don’t like the idea, you definitely should be in the know.
For the sake of simplicity, the IDs of the messages for the Skypey application will always be in order — as they are numbered in increasing values from zero upwards.
This may not be the case in a real app. You may have weird auto generated IDs that looks like gibberish such as
y68fnd0a9wyb.
In such cases, you want to keep a separate array to track the order of values.
That is it!
It is worth stating that the entire process of normalizing the state object may be summarized as follows:
• Each type of data should have its own key in the state object.
• Each key should store the individual items in an object, with the IDs of the items as keys and the items themselves as the values.
• Any references to individual items should be done by storing the item’s ID.
• Ideally, keep an array of IDs to indicate ordering.
Recap on the Design of the State Object
Now I know this has been a long discourse on the structure of the state object.
It may not seem important to you now, but as you build projects you’ll come to see how invaluable putting some thought into designing your state can be. It’ll help you perform CRUD operations much more easily, will reduce a lot of overly complex logic within your reducers, and will also help you take advantage of Reducer Composition, a term I’ll describe later in this book.
I wanted you to understand the reason behind my decisions, and be able to make informed decisions as you build your own applications. I believe you’re now empowered with the right information.
With all said and done, here’s a visual representation of the Skypey state object:
The image assumes just two user contacts. Please have a good look at it.
Building the List of Users
Moving on, it’s time to write some code. First, here’s the goal of this section. To build the list of users shown below:
What is needed to build this?
From a high level, it should be pretty clear that within the
Sidebar component, there’s the need to render a list of a user’s contacts.
Presumably, within
Sidebar, you may have something like this:
contacts.map(contact => <User />)
Got that?
You map over some
contacts data from the state, and for each
contact, you render a
User component.
But where does the data for this come from?
Ideally, and in a real world scenario, you will fetch this data from the server with an Ajax call. For our learning purposes, this brings in a layer of complexity we can avoid — for now.
So, as opposed to fetching data remotely from a server, I have created a few functions that will handle the creation of data for the App. We will be using this static data to build the Application.
For example, there’s a
contacts variable already created within static-data.js, that will always return a randomly generated list of contacts. All you have to do is import this into the App. No Ajax calls.
Thus, create a new file in the root directory of the project and call it
static-data.js
Copy the contents of the gist here into that file. We’ll be making use of it pretty soon.
Setting up the Store
Let’s quickly go over the process of setting up the store of the App so we can retrieve the data required to build the list of users within the sidebar.
One of the first steps when creating a Redux app is setting up the Redux store. Since this is where data will be read from, it becomes imperative to resolve this.
So, please install
redux from the
cli with:
yarn add redux
Once the installation is done, create a new folder called
store and in the directory, create a new
index.js file.
Don’t forget the analogy of having the major Redux actors in their own directories.
Like you already know, the store will be created via the
createStore factory function from
redux like this:
store/index.js
import { createStore } from "redux"; const store = createStore(someReducer, initialState); export default store;
The Redux
createStore needs to be aware of the reducer (remember the store and reducer relationship I explained earlier).
Now, edit the second line to look like this:
const store = createStore(reducer, {contacts});
Now, import the
reducer , and
contacts from the static data:
import reducer from "../reducers"; import { contacts } from "../static-data";
Since we actually haven’t created any
reducers directory, please do so now. Also create an
index.js file with this
reducers directory.
Now, create the reducer.
reducers/index.js
export default (state, action) => { return state; };
A reducer is just a function that takes in
state and
action, and returns a new
state.
If I lost you in the creation of the store,
const store = createStore(reducer, {contacts}); you should remember that the second argument in
createStore is the initial state of the app.
I have set this to the object
{contacts}.
This is an ES6 syntax, similar to this:
{contacts: contacts} with a
contacts key and a value of
contacts from
static-data.
There’s no way to know that what we’ve done is right. Let’s attempt to fix that.
In
Index.js , here’s what you should have now:
Index.js
import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; import registerServiceWorker from "./registerServiceWorker"; ReactDOM.render(<App />, document.getElementById("root")); registerServiceWorker();
Like we did with the first example, refactor the
ReactDOM.render call to sit inside a
render function.
const render = () => { return ReactDOM.render(<App />, document.getElementById("root")); };
Then involve the render function to have the App render correctly.
render()
Now, import the
store you created earlier …
import store from "./store";
And make sure any time the store is updated, the
render function is invoked.
store.subscribe(render);
Good!
Now, let’s take advantage of this setup.
Each time the store updates and invokes
render , let’s log the
state from the store.
Here’s how:
const render = () => { fancyLog(); return ReactDOM.render(<App />, document.getElementById("root")); };
Just call a new function,
fancyLog() , that you’ll soon write.
Here’s the
fancyLog function:
function fancyLog() { console.log("%c Rendered with ? ??", "background: purple; color: #FFF"); console.log(store.getState()); }
Hmmm. What have I done?
console.log(store.getState()) is the bit you’re familiar with. This will log the state retrieved from the store.
The first line,
console.log("%c Rendered with ? ??", "background: purple; color: #fff"); will log the text, “Rendered with …”, plus some emoji, and some CSS style to make it distinguishable. The
%c written before the “Rendered with …” text makes it possible to use the CSS styling.
Enough talking. Here’s the complete code:
index.js
import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; import registerServiceWorker from "./registerServiceWorker"; import store from "./store"; const render = () => { fancyLog(); return ReactDOM.render(<App />, document.getElementById("root")); }; render(); store.subscribe(render); registerServiceWorker(); function fancyLog() { console.log("%c Rendered with ? ??", "background: purple; color: #fff"); console.log(store.getState()); }
Here’s the state object being logged.
As you can see, within the state object is a
contacts field that holds the contacts available for the particular user. The structure of the data is as we discussed before now. Each contact is mapped with their
user_id
We’ve made decent progress.
Passing the Sidebar data via Props
If you take a look at the entire code now, you’ll agree that the entry point of the app remains
index.js .
Index.js then renders the
App component. The
App component is then responsible for rendering the
Main and
Sidebar components.
For
Sidebar to have access to the required contacts data, we’ll pass in the data via props.
In
App.js, retrieve
contacts from the store, and pass it on to
Sidebar like this:
App.js
const App = () => { const { contacts } = store.getState(); return ( <div className="App"> <Sidebar contacts={contacts} /> <Main /> </div> ); };
As I have done in the screenshot above, inspect the Sidebar component and you’ll find the
contacts passed as a prop. Contacts are an object with mapped IDs to user objects.
Now we can proceed to rendering the contacts.
First, install
Lodash from the
cli:
yarn add lodash
Import
lodash in
App.js
import _ from lodash
I know. The underscore looks funny, but it’s a nice convention. You’ll get to love it :)
Now, to use any of the utility methods
lodash avails to us, call the methods on the imported underscore, such as
.fakeMethod().
Now, put
Lodash to good use. Using one of the
Lodash utility functions, the
contacts object can be easily converted to an array when passed in as props.
Here’s how:
<Sidebar contacts={_.values(contacts)} />
You can read more about the
Lodash .values method if you want. In a nutshell, it creates an array out of all key values of the object passed in.
Now, let’s really render something in the Sidebar.
Sidebar.js
import React from "react"; import User from "./User"; import "./Sidebar.css"; const Sidebar = ({ contacts }) => { return ( <aside className="Sidebar"> {contacts.map(contact => <User user={contact} key={contact.user_id} />)} </aside> ); }; export default Sidebar;
In the code block above, we map over the contacts prop and render a
Usercomponent for each
To prevent the React warning key, the contact’s
user_id is used as a key. Also, each contact is passed in as a
user prop to the
User component.
Building the User Component
We are rendering a
User component within the
Sidebar , but this component doesn’t exist yet.
Please create a
User.js and
User.css file within the root directory.
Done that?
Now, here’s the content of the
User.js file:
User.js
import React from "react"; import "./User.css"; const User = ({ user }) => { const { name, profile_pic, status } = user; return ( <div className="User"> <img src={profile_pic} alt={name} <div className="User__details"> <p className="User__details-name">{name}</p> <p className="User__details-status">{status}</p> </div> </div> ); }; export default User;
Don’t let the big chunk of code fool you. It is actually very easy to read and understand. Have a second look.
The
name,
profile_pic URL and
status of the user are gotten from the props via destructuring:
const { name, profile_pic, status } = user;
These values are then used in the return statement for proper rendering, and here’s the result of that:
The result above is super ugly, but it is an indication that this works!
Now, let’s style this.
First, prevent the list of users from overflowing the Sidebar container.
Sidebar.css
.Sidebar { ... overflow-y: scroll; }
Also, the font is ugly. Let’s change that.
Index.css
@import url(""); body { ... font-weight: 400; font-family: "Nunito Sans", sans-serif; }
Finally, handle the overall display of the
User component.
User.css
.User { display: flex; align-items: flex-start; padding: 1rem; } .User:hover { background: rgba(0, 0, 0, 0.2); cursor: pointer; } .User__pic { width: 50px; border-radius: 50%; } .User__details { display: none; } /* not small devices */ @media (min-width: 576px) { .User__details { display: block; padding: 0 0 0 1rem; } .User__details-name { margin: 0; color: rgba(255, 255, 255, 0.8); font-size: 1rem; } }
Since this is not a CSS book, I’m skipping some of the styling explanations. However, if anything confuses you, just ask me on Twitter, and I’ll be happy to help.
Voila!
Here’s the beautiful display we’ve got now:
Amazing!
We’ve gone from nothing to having a beautiful list of users rendered on the screen.
If you’re coding along, resize the browser to see the beautiful view on mobile as well.
Hang In there!
Got questions?
It’s perfectly normal to have questions.
The quickest way to reach me will be to tweet your question via Twitter, with the hashtag, #UnderstandingRedux. This way I can easily find and answer your question.
You don’t have to Pass Down Props
Have a look at the high level structure of the Skypey UI below:
In traditional React apps (without using the context API), you are required to pass down props from
<App /> to
<Sidebar /> and
<Main />
With Redux however, you are not bound by this rule.
If a certain component needs access to a value from the state object, you can simply reach out to the store and retrieve the current state.
For instance,
<Sidebar /> and
<Main /> can access the Redux store without the need to depend on
<App />
The only reason I haven’t done so here is because
<App /> is a direct parent, with
<Sidebar /> and
<Main /> NOT more than one level deep in component hierarchy.
As you’ll see in later sections, for components that are nested deeper in the component hierarchy, we will reach out directly to the Redux store to retrieve the current state.
There’s no need to pass down props.
You’ll love the graphic below. It goes even further to describe the need not to pass down props when working with Redux.
Container and Component Folder Structure
There’s a bit of refactoring you need to do before we move on to coding the Skypey application.
In Redux applications, it is a common pattern to split your components into two different directories.
Every component that talks directly to Redux, whether that is to retrieve state from the store, or to dispatch an action, should be moved to a
containersdirectory.
Other components, those that do not talk to Redux, should be moved over to a
components directory.
Well, well, well. Why go through the hassle?
For one, your codebase becomes a little cleaner. It also becomes easier to find certain components as long as you know if they talk to Redux or not.
So, go ahead.
Have a look at the components in the current state of the application, and reshuffle accordingly.
So you don’t screw things up, remember to move the components’ associated
CSS file.
Here’s my solution:
- Create two folders:
containersand
components.
App.jsattempts to retrieve
contactsfrom the store. So, move
App.jsand
App.cssto the
containersfolder.
- Move
Sidebar.js,
Sidebar.css,
Main.jsand
Main.cssto the
componentsfolder. They do not talk to Redux directly for anything.
- Please do not move
Index.jsand
Index.css. Those are the entry point of the App. Just leave those at the root of the project directory.
- Please move
User.jsand
User.cssto the
containersdirectory. The
Usercomponent does NOT talk to Redux yet but it will. Remember that when the App is completed, upon clicking a user from the sidebar, their messages will be shown. By implication, an action will be dispatched. In the coming sections, we’ll build this out.
- By now, a lot of your import URLs will be broken, that is, the components that imported these moved components. You have to change their import URL. I’ll leave this up to you. It’s an easy fix :)
Here’s an example solution for #6 above: In
App.js, change the
Sidebar and
Main imports to this:
import Sidebar from "../components/Sidebar"; import Main from "../components/Main";
As opposed to the former:
import Sidebar from "./Sidebar"; import Main from "./Main";
Got that?
Here are some tips to solve the challenge yourself:
- Check the
Sidebar.jsimport statement for the
Usercomponent.
- Check
Index.jsimport statement for the
Appcomponent.
- Check
App.jsimport statement for the
store
Once that is done, you’ll have Skypey working as expected!
Refactoring to Set Initial State from the Reducer
Firstly, please have a look at the creation of the
store in store/index.js. In particular, consider this line of code:
const store = createStore(reducer, { contacts });
The initial state object is passed directly into
createStore. Remember that the store is created with the signature,
createStore(reducer, initialState). In this case, the initial state has been set to the object,
{contacts: contacts}
Even though this approach works, this is typically used for server side rendering (don’t bother if you don’t know what this means). For now, understand that this approach of setting an initial state in
createStore is more used in the real world for server side rendering.
Right now, remove the initial state in the
createStore method.
We’ll have the initial state of the application set solely by the reducer.
Trust me, you’ll get the hang of this.
Here’s what the
store/index.js file will look like once you remove the initial state from
createStore.
import { createStore } from "redux"; import reducer from "../reducers"; const store = createStore(reducer); export default store;
And here’s the current content of the
reducer/index.js file:
export default (state, action) => { return state; };
Please change that to this:
import { contacts } from "../static-data"; export default (state = { contacts }, action) => { return state; };
So, what’s happening here?
Using ES6 default parameters, we have set the state parameter to an initial value of
{contacts}.
This is essentially the same as
{contacts: contacts}.
Hence, the
return state statement within the reducer will return this value,
{contacts: contacts} as the initial state of the application.
At this point, the app now works — just like before. The only difference here is that the initial state of the application is now managed by the Reducer.
Let’s keep refactoring.
Reducer Composition
In all the apps we’ve create so far, we have used just one reducer to manage the entire state of the applications.
What’s the implication of this?
It is like having just one Cashier in the entire bank hall. How scalable is that?
Even if the Cashier can do all the work effectively, it may be more manageable — and perhaps a better customer experience — to have more than one Cashier in the bank hall.
Someone’s got to attend to everybody, and it’s a lot of work for just one person!
The same goes with your Redux applications.
It is common to have multiple reducers in your application as opposed to one reducer handling all the operations of the state. These reducers are then combined into one.
For example, there could be 5 or 10 Cashiers in the bank hall, but all of them combined all serve one purpose. That’s how this works as well.
Consider the state object of the Hello World app we built earlier.
{ tech: "React" }
Pretty simple.
All we did was have one reducer manage the entire state updates.
However, consider the state object of the more complex Skypey application:
Having a single reducer manage the entire state object is doable — but not the best approach.
Instead of having the entire object managed by one reducer, what if we had one reducer manage one field in the state object?
Like a one to one mapping?
You see what we’re doing there? Introducing more Cashiers!
Reducer composition requires that a single reducer handles the state update for a single field in the state object.
For example, for the
messages field, you have a
messagesReducer. For a
contacts field, you also have a
contactsReducer and so on.
One more important thing to point out is that the return value from each of the reducers is solely for the field they represent.
So, if I had
messagesReducer written like this:
export const function messagesReducer (state={}, action) { return state }
The
state returned here is not the state of the entire application.
No.
It is only the value of the
messages field.
The same goes for the other reducers.
Got that?
Let’s see this in practice, and how exactly these reducers are combined for a single purpose.
Refactoring Skypey to Use Multiple Reducers
Remember how I talked about multiple reducers handling each field in the state object?
Right now, you can tell we’ll have the following multiple reducer as seen in the figure below:
Now, for every field in the state object, we will create a corresponding reducer. The current ones at this stage are,
contacts and
user.
Let’s go over how this affects our code first. Then I’ll take a step back to explain how it works again.
Take a look at
reducer/index.js:
import { contacts } from "../static-data"; export default (state = contacts, action) => { return state; };
Rename this file to
contacts.js.
This will become the contacts reducer.
Create a
user.js file within the
reducers directory.
This will be the user reducer.
Here’s the content:
import { generateUser } from "../static-data"; export default function user(state = generateUser(), action) { return state; }
Again, I have created a
generateUser function to generate some static user information.
Using ES6 default parameters, the initial state is set to the result of invoking this function. Therefore
return state will now return a user object.
Right now, we have two different reducers. Let’s combine them for the greater good :)
- Create an
index.jsfile within the reducers directory
Firstly, import the two reducers,
user and
contacts:
import user from "./user"; import contacts from "./contacts";
To combine these reducers, we need the helper function
combineReducersfrom
redux
Import it like this:
import { combineReducers } from "redux";
Now,
index.js will export the combination of both reducers like this:
export default combineReducers({ user, contacts, });
Notice that the
combineReducers function takes in an object. An object whose shape is exactly like the state object of the application.
The code block is the same as this:
export default combineReducers({ user: user, contacts: contacts })
The object has keys
user and
contacts, just like the state object we’ve got in mind.
What about the values of these keys?
The values come from the reducers!
It is important to understand this. Okay?
I’m Lost. How does this work again?
Let me take a step back and explain how reducer composition works again. This time, from a different perspective.
Consider the JavaScript object below:
const state = { user: "me", messages: "hello", contacts: ["no one", "khalid"], activeUserId: 1234 }
Now, assume that instead of having the values of the keys hardcoded, we wanted it to be represented by function calls. That may look like this:
const state = { user: getUser(), messages: getMsg(), contacts: getContacts(), activeUserId: getID() }
This assumes that
getUser() will also return the previous value,
“me”. The same goes for the other replaced functions.
Still following?
Now, let’s rename these functions.
const state = { user: user(), messages: messages(), contacts: contacts(), activeUserId: activeUserId() }
Now, the functions have names identical to their corresponding object keys. Instead of
getUser(), we now have
user().
Let’s get imaginative.
Imagine that there existed a certain utility function imported from some library. Let’s call this function,
killerFunction.
Now,
killerFunction makes it possible to do this:
const state = killerFunction({ user: user, messages: messages, contacts: contacts, activeUserId: activeUserId })
What has changed?
Instead of invoking each of the functions, you just write the function names.
killerFunction will take care of invoking the functions.
Now using ES6, we can simplify the code further:
const state = killerFunction({ user, messages, contacts, activeUserId })
This is the same as the previous code block. Assuming the functions are in scope, and have the same name (identifier) as the object key.
Got that?
Now, this is kind of how
combineReducer from
Redux works.
The values of every key in your state object will be gotten from the
reducer. Do not forget that a reducer is just a function.
Just like
killerFunction,
combineReducers is capable of making sure the values are gotten from invoking the passed functions.
All the key and values put together will then result in the state object of the application.
That is it!
An important point to always remember is that when using
combineReducers, the value returned from each reducer is not the state of the application.
It is only the
value of the particular key they represent in the state object!
For example, the
user reducer returns the value for the
user key in the state. Likewise, the
messages reducer returns the value for the
messages key in the state.
Now, here’s the complete content of
reducers/index.js:
import { combineReducers } from "redux"; import user from "./user"; import contacts from "./contacts"; export default combineReducers({ user, contacts });
Now if you inspect the logs, you’ll find
user and
contacts right there in the state object.
Building the Empty Screen
Right now, the
Main component just displays the text,
main stuff. This isn’t what we want.
The end goal is to show an empty screen, but show user messages when a contact is clicked on.
Let’s build the empty screen.
For this, we’ll need a new component called,
Empty.js. While you’re at it, also create a corresponding CSS file,
Empty.css.
Please create these in the
components directory.
<Empty /> will render the markup for the empty screen. To do this, it will require a certain
user prop.
Definitely, the
user is to be passed in from the state of the application. Don’t forget the overall structure of the state object we resolved earlier:
So, here’s the current content of the
<Main /> component:
import React from "react"; import "./Main.css"; const Main = () => { return <main className="Main">Main Stuff</main>; }; export default Main;
It just returns the text,
Main Stuff.
The
<Main /> component is responsible for displaying the
<Empty />component when no user is active. As soon as a user is clicked,
<Main />renders the conversations of the clicked user. This could be represented by a component,
<ChatWindow />.
For this render toggle to work and for
<Main /> to render either
<Empty /> or
<ChatWindow />, we need to keep track of certain
activeUserId.
For example, by default
activeUserId will be null, then
<Empty /> will be shown.
However, as soon as a user is clicked, the
activeUserId becomes the
user_idof the clicked contact. Now,
<Main /> will render the
<ChatWindow />component.
Cool, huh?
For this to work, we will keep a new field in the state object,
activeUserId
By now, you should know the drill already. To add a new field to the state object, we’ll have this set up in the reducers.
Create a new file,
activeUserId.js in the
reducers folder.
And here’s the content of the file:
reducers/activeUserId.js
export default function activeUserId(state = null, action) { return state; }
By default, it returns
null.
Now, hook this newly created reducer to the
combineReducer method call like this:
... import activeUserId from "./activeUserId"; export default combineReducers({ user, contacts, activeUserId });
Now if you inspect the logs, you’ll find
activeUserId right there in the state object.
Let’s move on.
In
App.js, retrieve the
user and
activeUserId from the store, like this:
const { contacts, user, activeUserId } = store.getState();
What we had previously was this:
const { contacts } = store.getState();
Now, pass on these values as props to the
<Main /> component.
<Main user={user} activeUserId={activeUserId} />
What we had previously was this:
<Main />
Now, let’s have the render logic fleshed out in
<Main />
before:
import React from "react"; import "./Main.css"; const Main = () => { return <main className="Main">Main Stuff</main>; }; export default Main;
now:
import React from "react"; import "./Main.css"; import Empty from "../components/Empty"; import ChatWindow from "../components/ChatWindow"; const Main = ({ user, activeUserId }) => { const renderMainContent = () => { if (!activeUserId) { return <Empty user={user} activeUserId={activeUserId} />; } else { return <ChatWindow activeUserId={activeUserId} />; } }; return <main className="Main">{renderMainContent()}</main>; }; export default Main;
What has changed isn’t difficult to grasp.
user and
activeUserId are received as props. The return statement within the component has the function
renderMainContent invoked.
All
renderMainContent does is check if
activeUserId doesn’t exist. If it doesn’t, it renders the empty screen. If it does exist, then the
ChatWIndow is rendered.
Great!
We don’t have the
Empty and
ChatWindow components built out yet.
Forgive me, I’m going to paste in a lot of code at once.
Edit the
Empty.js file to contain this:
import React from "react"; import "./Empty.css"; const Empty = ({ user }) => { const { name, profile_pic, status } = user; const first_name = name.split(" ")[0]; return ( <div className="Empty"> <h1 className="Empty__name">Welcome, {first_name} </h1> <img src={profile_pic} alt={name} <p className="Empty__status"> <b>Status:</b> {status} </p> <button className="Empty__btn">Start a conversation</button> <p className="Empty__info"> Search for someone to start chatting with or go to Contacts to see who is available </p> </div> ); }; export default Empty;
Oops. What’s all that code???
Take a step back, it’s not as complex as it seems.
The
<Empty /> component takes in a
user prop. This user prop is an object that has the following shape:
{ name, email, profile_pic, status, user_id: }
Using the ES6 destructuring syntax, grab the
name,
profile_pic and
statusfrom the user object:
const { name, profile_pic, status } = user;
For most users, the
name contains two words such as
Ohans Emmanuel. Grab the first word and assign it to the variable
first_name like this:
const first_name = name.split(" ")[0];
The return statement just spits out a chunk of markup.
You’ll see the result of this very soon.
Before we go ahead, let’s not forget to create a
ChatWindow component within the
containers directory.
ChatWindow will be responsible for displaying the conversations for an active user contact, and it’s going to do a lot of direct talking to Redux!
In
ChatWIndow.js write the following:
import React from "react"; const ChatWindow = ({ activeUserId }) => { return ( <div className="ChatWindow">Conversation for user id: {activeUserId}</div> ); }; export default ChatWindow;
We will come back to flesh this out. Right now, this is good enough.
Save all the changes we’ve made so far, and here’s what I’ve got!
You should have something very similar too.
The empty screen works, but it is ugly, and no one loves ugly apps.
I have written the CSS for the
<Empty /> component.
Empty.css
.Empty { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; } .Empty__name { color: #fff; } .Empty__status, .Empty__info { padding: 1rem; } .Empty__status { color: rgba(255, 255, 255, 0.9); border-bottom: 1px solid rgba(255, 255, 255, 0.7); } .Empty__img { border-radius: 50%; margin: 2rem 0; } .Empty__btn { padding: 1rem; margin: 1rem 0; font-weight: bold; font-size: 1.2rem; border-radius: 30px; outline: 0; } .Empty__btn:hover { background: rgba(255, 255, 255, 0.7); cursor: pointer; }
Just good ol’ CSS. I bet you can figure out the styles.
Now, here’s the result of that:
Here’s the result with the devtools docked:
Now, that definitely looks good!
Building the Chat Window
Have a look at the logic within the
<Main /> component.
<ChatWindow /> will only be displayed when
activeUserId is present.
Right now,
activeUserId is set to
null.
We need to make sure that the
activeUserId is set whenever a contact is clicked.
What do you think?
We need to dispatch an action, right?
Yeah!
Let’s define the shape of the action.
Remember than an action is just an object with a
type field and a
payload.
The
type field is compulsory, while you can call
payload anything you like.
payload is a good name though. Very common, too.
Thus, here’s a representation of the action:
{ type: "SET_ACTION_ID", payload: user_id }
The type or name of the action will be called
SET_ACTION_ID.
In case you were wondering, it is pretty common to use the snake case with capital letters in action types such as
SET_ACTION_ID and not
setactionid or
set-action-id.
Also, the action payload will be the
user_id of the user to be set as active.
Let’s now dispatch actions upon user interaction.
Since this is the first time we’re dispatching actions in this application, create a new
actions directory. While at it, also create a
constants folder.
In the
constants folder, create a new file,
action-types.js.
This file has the sole responsibility of keeping the action type constants. I’ll explain why this is important, shortly.
Write the following in
action-types.js.
constants/action-types.js
export const SET_ACTIVE_USER_ID = "SET_ACTIVE_USER_ID";
So, why is this important?
To understand this, we need to investigate where action types are used in a Redux application.
In most Redux applications, they will show up in two places.
1. The Reducer
When you do
switch over the action type in your reducers:
switch(action.type) { case "WITHDRAW_MONEY": doSomething(); break; }
2. The Action creator
Within the action creator, you also write code that resembles this:
export const seWithdrawAmount = amount => ({ type: "WITHDRAW_MONEY, payload: amount })
Now, have a look at the reducer and action creator logic above. What is common to both?
The
”WITHDRAW_MONEY” string!
As your application grows and you have lots of these strings flying around the place, you (or someone else) may someday make the mistake of writing
”WITDDRAW_MONEY” or
”WITHDRAW_MONY” instead of
”WITHDRAW_MONEY_”
The point I’m trying to make is that using raw strings like this makes it easier to have a typo. From experience, bugs that come from typos are super annoying. You may end up searching for so long, only to see the problem was caused by a very small miss on your end.
Prevent yourself from having to deal with this hassle.
A good way to do that is to store the strings as constants in a separate file. This way, instead of writing the raw strings in multiple places, you just import the string from the declared constant.
You declare the constants in one place, but can use them in as many places as possible. No typos!
This is exactly why we have created the
constants/action-types.js file.
Now, let’s create the action creator.
action/index.js
import { SET_ACTIVE_USER_ID} from "../constants/action-types"; export const setActiveUserId = id => ({ type: SET_ACTIVE_USER_ID, payload: id });
As you can see, I have imported the action type string from the constants folder. Just like I explained earlier.
Again, the action creator is just a function. I have called this function
setActiveUserId. It’ll take in an
id of a user and return the action (that is, the object) with the type and payload rightly set.
With that in place, what’s left is dispatching this action when a user clicks a user, and doing something with the dispatched action within our reducers.
Let’s keep moving.
Take a look at the
User.js component.
The first line of the
return statement is a
div with the class name,
User:
<div className="User">
This is the right place to set up the click handler. As soon as this
div is clicked, we will dispatch the action we just created.
So, here’s the change:
<div className="User" onClick={handleUserClick.bind(null, user)}>
And the
handleUserClick function is right here:
function handleUserClick({ user_id }) { store.dispatch(setActiveUserId(user_id)); }
Where
setActiveUserId has been imported from where? The action creator!
import { setActiveUserId } from "../actions";
Now, below’s all the
User.js code you should have at this point:
containers/User.js
import React from "react"; import "./User.css"; import store from "../store"; import { setActiveUserId } from "../actions"; const User = ({ user }) => { const { name, profile_pic, status } = user; return ( <div className="User" onClick={handleUserClick.bind(null, user)}> <img src={profile_pic} alt={name} <div className="User__details"> <p className="User__details-name">{name}</p> <p className="User__details-status">{status}</p> </div> </div> ); }; function handleUserClick({ user_id }) { store.dispatch(setActiveUserId(user_id)); } export default User;
To dispatch the action, I also had to import the
store and called the method,
store.dispatch().
Also note that I have used the ES6 destructuring syntax to grab the
user_idfrom the
user argument in
handleUserClick.
If you’re coding along, as I recommend, click any of the user contacts and inspect the logs. You can add a console log to the
handleUserClick like this:
function handleUserClick({ user_id }) { console.log(user_id); store.dispatch(setActiveUserId(user_id)); }
You’ll find the logged user id of the user contact.
As you may have already noticed, the action is being dispatched, but nothing is changing on the screen. The
activeUserId isn’t set in the state object. This is because right now, the reducers know nothing about the dispatched action.
Let’s fix this, but don’t forget to remove the
console.log(user_id) after inspecting the logs.
Have a look at the
activeUserId reducer:
export default function activeUserId(state = null, action) { return state; }
reducer/activeUserId.js
import { SET_ACTIVE_USER_ID } from "../constants/action-types"; export default function activeUserId(state = null, action) { switch (action.type) { case SET_ACTIVE_USER_ID: return action.payload; default: return state; } }
You should understand what’s going on here.
The first line imports the string,
SET_ACTIVE_USER_ID.
We then check if the action passed in is of
type
SET_ACTIVE_USER_ID . If yes, then the new value of
activeUserId is set to
action.payload.
Don’t forget that the action payload contains the
user_id of the user contact.
Let’s see this in action. Does it work as expected?
Yes!
Now, the
ChatWindow component is rendered with the right
activeUserId set.
As a reminder, it is important to remember that with reducer composition, the returned value of each reducer is the value of the state field they represent, and not the entire state object.
Breaking the ChatWindow into smaller components
Have a look at what the completed chat window looks like:
For a more sane development approach, I have broken this into three sub components,
Header,
Chats and
MessageInput:
So, in order to complete the
chatWindow component, we will build these three sub components. We’ll then compose them to form the
chatWindowcomponent.
Ready?
Let’s begin with the Header component.
The current content of the
chatWindow component is this:
import React from "react"; const ChatWindow = ({ activeUserId }) => { return ( <div className="ChatWindow">Conversation for user id: {activeUserId}</div> ); }; export default ChatWindow;
Not very helpful.
Update the code to this:
import React from "react"; import store from "../store"; import Header from "../components/Header"; const ChatWindow = ({ activeUserId }) => { const state = store.getState(); const activeUser = state.contacts[activeUserId]; return ( <div className="ChatWindow"> <Header user={activeUser} /> </div> ); }; export default ChatWindow;
What’s changed?
Remember that the
activeUserId is passed as props into the
ChatWindowcomponent.
Now, instead of rendering the text, Conversation for user id: … , render the
Header component.
The Header component cannot be rendered properly without having knowledge of the clicked user. Why?
The
name and
status rendered in the
Header are those of the clicked user.
To keep track of the active user, a new variable,
activeUser is created, and the value retrieved from the state object like this:
const activeUser = state.contacts[activeUserId].
How does this work?
First, we grab the state from the Redux store:
const state = store.getState().
Now, remember that every contact of the application user is stored in the
contacts field. Also, every user is mapped by their
user_id.
Thus, the active user can be retrieved by fetching the user with the corresponding id field from the
contacts object:
state.contacts[activeUserId].
All good?
At this point we need to build out the rendered
Header component.
Create the files,
Header.js and
Header.css within the
components directory.
The content of
Header.js is simple. Here it is:
import React from "react"; import "./Header.css"; function Header({ user }) { const { name, status } = user; return ( <header className="Header"> <h1 className="Header__name">{name}</h1> <p className="Header__status">{status}</p> </header> ); } export default Header;
It’s a stateless functional component that renders a
header element and
h1and
p tags to hold the name and status of the active user.
Remember that the active user is the clicked user from the sidebar.
The styles for the
<Header /> component are equally simple. Here they are:
.Header { padding: 1rem 2rem; border-bottom: 1px solid rgba(189, 189, 192, 0.2); } .Header__name { color: #fff; }
Now, we’ve got this baby kicking!
Amazing. If you’re still here, you’re doing really great!
Let’s move on to building the
<Chats /> component.
The
<Chats /> component is essentially a rendered list of a user’s conversations.
So, where do we get these conversations from?
Yeah, from the state of the application.
Like I explained earlier, a real world app will fetch the user conversations from a server. However, my approach to learning Redux is that you eliminate as many complexities as possible when learning the fundamentals.
To that effect, there’ll be no server fetching resource here. We’ll hook up the data using some helper functions I have created for random user data generation.
Let’s start by hooking up the required data to the state of the application.
The process is the same as we’ve done multiple times already.
- Create a Reducer
- Using ES6, add a default parameter value to the reducer
- Include the reducer in the
combineReducersfunction call.
Will you try that out before moving on to my solution?
Here comes my solution, anyway.
Create a new file,
messages.js in the
reducers directory. This will be the messages reducer.
Here is the content of the messages reducer.
reducers/messages.js
import { getMessages } from "../static-data"; export default function messages(state = getMessages(10), action) { return state; }
To generate random messages, I have imported the
getMessages function from
static-data
This function takes an amount, represented by a number. The
getMessagesfunction will then generate that amount of messages for each user contact.
For example,
getMessages(10) will generate 10 messages per user contact.
Now, include the reducer in the
combineReducers function call in
reducers/index.js
reducers/index.js
import messages from "./messages"; export default combineReducers({ user, messages, contacts, activeUserId });
Doing this will include a
messages field in the state object.
Here’s a look at the logs. You’ll now find
messages as seen below:
With that in place, we can safely resume building the
Chats component.
If you haven’t already, create the files,
Chats.js and
Chats.css in the components directory.
Now, import
Chats and render it below the
<Header /> component in
ChatWindow.
containers/ChatWindow.js
... import Chats from "../components/Chats"; ... return ( <div className="ChatWindow"> <Header user={activeUser} /> <Chats /> </div> );
The
<Chats/> component will take the list of messages from the state object, map over these, and then render them beautifully.
Remember that the messages passed into
Chats are specifically the messages for the active user!
Whereas
state.messages holds all the messages for every user contact,
state.messages[activeUserId] will fetch the messages for the active user.
This is why every conversation is mapped to the user id of the user — for easy retrieval as we have done.
Grab the active user’s messages and pass them as props in
Chats.
containers/ChatWindow.js
... import Chats from "../components/Chats"; ... const activeMsgs = state.messages[activeUserId]; return ( <div className="ChatWindow"> <Header user={activeUser} /> <Chats messages={activeMsgs} /> </div> );
Now, remember that the messages of each user is a giant object with each message having a number field:
For easier iteration and rendering, we’ll convert this to an array. Just like we did with the list of users in the Sidebar.
For that, we’ll need
Lodash.
containers/ChatWindow.js
... import _ from "lodash"; import Chats from "../components/Chats"; ... const activeMsgs = state.messages[activeUserId]; return ( <div className="ChatWindow"> <Header user={activeUser} /> <Chats messages={_.values(activeMsgs)} /> </div> );
Now, instead of passing
activeMsgs, we pass in
_.values(activeMsgs).
There’s one more important step before we view the results.
The component
Chats has not been created.
In
Chats.js, write the following. I’ll explain afterwards.
containers/Chat.js
import React, { Component } from "react"; import "./Chats.css"; const Chat = ({ message }) => { const { text, is_user_msg } = message; return ( <span className={`Chat ${is_user_msg ? "is-user-msg" : ""}`}>{text}</span> ); }; class Chats extends Component { render() { return ( <div className="Chats"> {this.props.messages.map(message => ( <Chat message={message} key={message.number} /> ))} </div> ); } } export default Chats;
It isn’t too much to comprehend, but I’ll explain what’s going on.
Firstly, have a look at the the
Chats component. You’ll notice that I have used a class-based component here. You’ll see why later on.
In the render function, we
map over the
messages props and for each
message , we return a
Chat component.
The
Chat component is super simple:
const Chat = ({ message }) => { const { text, is_user_msg } = message; return ( <span className={`Chat ${is_user_msg ? "is-user-msg" : ""}`}>{text}</span> ); };
For each message that’s passed in, the
text content of the message and the
is_user_msg flag are both grabbed using the ES6 destructuring syntax,
const { text, is_user_msg } = message;
The return statement is more interesting.
A simple
span tag is rendered.
Strip out some of the
JSX magic, and here’s the simple form of what is rendered:
<span> {text} </span>
The text content of the message is wrapped in a
span element. Simple.
However, we need to differentiate between the application user’s message, and the contact’s message.
Don’t forget that a conversation happens with at least two people sending messages back and forth.
If the message being rendered is the user’s message, we want the rendered markup to be this:
<span className="Chat is-user-msg"> {text} </span>
And if not, we want this:
<span className="Chat is-user-msg"> {text} </span>
Note that what’s changed is the
is-user-msg class being toggled.
This way we can specifically style the user’s message using the css selector shown below:
.Chat.is-user-msg { }
So, this is why we have some fancy
JSX for rendering the class names based on the presence or absence of the
is_user_msg flag.
<span className={`Chat ${is_user_msg ? "is-user-msg" : ""}`}>{text}</span>
The real sauce is this:
${is_user_msg ? "is-user-msg" : “”
That’s the ternary operator right there!
You can make sense of all the code within
containers/Chats.js now, huh?
Here’s the result so far.
The messages are rendered but it doesn’t look so good. This is because all the messages are rendered in
span tags.
Since
span tags are inline elements, all the messages just render in a continuous line, looking squashed.
This is where my homeboy CSS shines.
Let’s sprinkle on some CSS goodness and get this party started :)
Starting with the Chat Window, create a new file,
ChatWindow.css in the
containers directory.
Do not forget to import it in
ChatWindow.js like this:
import "./ChatWindow.css"
Write this in there:
.ChatWindow { display: flex; flex-direction: column; height: 100vh; }
This will make sure that the
ChatWindow takes up all available height,
100vh. I have also made it a flex container so I can use some flex goodies while aligning its items, namely,
Header,
Chats and
You can see the
ChatWindow with a red border below:
Let’s move on to styling the
Chat Messages.
components/Chats.css
.Chats { flex: 1 1 0; display: flex; flex-direction: column; align-items: flex-start; width: 85%; margin: 0 auto; overflow-y: scroll; } .Chat { margin: 1rem 0; color: #fff; padding: 1rem; background: linear-gradient(90deg, #1986d8, #7b9cc2); max-width: 90%; border-top-right-radius: 10px; border-bottom-right-radius: 10px; } .Chat.is-user-msg { margin-left: auto; background: #2b2c33; border-top-right-radius: 0; border-bottom-right-radius: 0; border-top-left-radius: 10px; border-bottom-left-radius: 10px; } @media (min-width: 576px) { .Chat { max-width: 60%; } }
Gosh! This is looking so good already!
Let me explain some of the importance style declarations in there.
With
flex: 1 1 0,
.Chats is made to grow (take up available space) and shrink accordingly within
ChatWindow.
.Chats is also made of a flex-container with
display: flex. By setting
flex-direction: column all the chat messages are aligned vertically. They are no longer inline elements but flex items!
Chats that aren’t those of the user are given a blueish background gradient with
background: linear-gradient(90deg, #1986d8, #7b9cc2);
This is overridden if the message is the user’s:
.Chat.is-user-msg { background: #2b2c33; }
I believe you can make sense of everything else.
So far so good!
I’m really excited about how far we’ve come. One last step, and the chat window is completely built!
Let’s build the Message Input component.
We’ve had to build more difficult components. This one won’t be difficult to build.
However, there’s one point to consider.
The Input component will be a controlled component. Therefore we will be storing the input value in the application state object.
For this, we’ll need a new field called
typing in the state object.
Let’s get that in there.
For our considerations, whenever a user types, we will dispatch a
SET_TYPING_VALUE action type.
Be sure add this constant in the
constants/action-types.js file:
export const SET_TYPING_VALUE = "SET_TYPING_VALUE";
Also, the shape of the dispatched action will look like this:
{ type: SET_TYPING_VALUE, payload: "input value" }
Where the
payload of the action is the value typed in the input. Let’s create an action creator to handle the creation of this action:
actions/index.js
import { SET_ACTIVE_USER_ID, SET_TYPING_VALUE } from "../constants/action-types"; … export const setTypingValue = value => ({ type: SET_TYPING_VALUE, payload: value })
Now, let’s create a new
typing reducer, one that will take this created action into consideration.
reducers/typing.js
import { SET_TYPING_VALUE } from "../constants/action-types"; export default function typing(state = "", action) { switch (action.type) { case SET_TYPING_VALUE: return action.payload; default: return state; } }
The default value for the typing field will be set to an empty string.
However, when an action with type
SET_TYPING_VALUE is dispatched, the value in the payload will be returned.
Otherwise, the default state
"" will be returned.
Before I forget, be sure to include this newly created reducer in the
combineReducers function call.
reducers/index.js
... import typing from "./typing"; export default combineReducers({ user, messages, typing, contacts, activeUserId });
Be sure to inspect the logs and confirm that a
typing field is indeed attached to the state object.
Okay. Let’s now create the actual
MessageInput component. Since this component will talk directly to the Redux store for setting and getting its typing value, it should be created in the
containers directory.
While at it, also create a
MessageInput.css file as well.
containers/MessageInput
import React from "react"; import store from "../store"; import { setTypingValue } from "../actions"; import "./MessageInput.css"; const MessageInput = ({ value }) => { const handleChange = e => { store.dispatch(setTypingValue(e.target.value)); }; return ( <form className="Message"> <input className="Message__input" onChange={handleChange} value={value} </form> ); }; export default MessageInput;
Nothing magical happening up there.
Whenever the user types into the input box, the
onChange event is fired. This is turn fires the
handleChange function.
handleChange in turn dispatches the
setTypingValue action we created earlier. This time, passing the required payload,
e.target.value.
We’ve created the component, but to show up in the chat window we need to include it in the return statement of
ChatWindow.js:
... import MessageInput from "./MessageInput"; const { typing } = state; return ( <div className="ChatWindow"> <Header user={activeUser} /> <Chats messages={_.values(activeMsgs)} /> <MessageInput value={typing} /> </div> );
And now, we’ve got this working!
Uh, but it is really ugly :(
Let’s make it beautiful.
containers/MessageInput.css
.Message { width: 80%; margin: 1rem auto; } .Message__input { width: 100%; padding: 1rem; background: rgba(0, 0, 0, 0.8); color: #fff; border: 0; border-radius: 10px; font-size: 1rem; outline: 0; }
That should be enough to do the Magic!
Looking better?
I bet it is!
Submitting the Form
Right now, when you type a message and hit enter, it doesn’t show up in the conversation list, and the page reloads.
Terrible!
Let’s handle the form submission.
In
MessageInput.js, add a
handleSubmit event handler as shown below:
... <form className="Message" onSubmit={handleSubmit}> ... </form> ...
Think about it for a minute. To update the list of messages in the conversation…we need to dispatch an action!
This action needs to take the
value in the input box, and add it to the messages of the active user.
Okay, so this looks like a good shape for the action:
{ type: "SEND_MESSAGE", payload: { message, userId } }
Got that?
Now, let’s write the
handleSubmit function:
//first retrieve the current state object const state = store.getState(); const handleSubmit = e => { e.preventDefault(); const { typing, activeUserId } = state; store.dispatch(sendMessage(typing, activeUserId)); };
Here’s what is going on within the
handleSubmit function:
With
e.preventDefault(), I think you already know what that does. The
typing value and
activeUserId are fetched from the
state since they’ll both be used to create the dispatched action.
And finally, the action is dispatched with
store.dispatch(sendMessage(typing, activeUserId)).
Oops, but with an action creator,
sendMessage.
In
actions/index.js, create the
sendMessage action creator:
import { ... SEND_MESSAGE } from "../constants/action-types"; export const sendMessage = (message, userId) => ({ type: SEND_MESSAGE, payload: { message, userId } })
That also means the
SEND_MESSAGE action type constant needs to be created in
constants/action-types.js.
export const SEND_MESSAGE = "SEND_MESSAGE";
Before testing the code, you should not forget to update the action creator imports in
MessageInput.js to include
sendMessage.
import { setTypingValue, sendMessage } from "../actions";
So try it out. Does the code work?
Uh, no it doesn’t.
The form is submitted, the page doesn’t reload due to the form submission, the action is dispatched, but still no updates.
We’ve done nothing wrong, except that the action type hasn’t been catered for in any of the reducers.
The reducers know nothing about this newly created action of type,
SEND_MESSAGE.
Let’s fix that next.
Updating the Message State
Here’s a list of all the reducers we’ve got at this point:
activeUserId.js contacts.js messages.js typing.js user.js
Which of these do you think should be concerned with updating the messages in a user conversation?
Yes, the
messages reducer.
Here’s the current content of the
messages reducer:
import { getMessages } from "../static-data"; export default function messages(state = getMessages(10), action) { return state; }
Not so much going on in there.
Import the
SEND_MESSAGE action type, and let’s begin to handle that in this
messages reducer.
import { getMessages } from "../static-data"; import { SEND_MESSAGE } from "../constants/action-types"; export default function messages(state = getMessages(10), action) { switch (action.type) { case SEND_MESSAGE: return ""; default: return state; } }
Now, we are handling the the action type,
SEND_MESSAGE but an empty string is returned.
This isn’t what we want, but we’ll build this up from here. In the mean time, what do you think is the consequence of returning an empty string here?
Let me show you.
All the messages disappear! But why? That’s because as soon as we hit enter, the
SEND_MESSAGE action is dispatched. As soon as this action reaches the reducer, the reducer returns an empty string
“”.
Thus, there are no messages in the state object. It’s all gone!
This is definitely unacceptable.
What we want is to retain whatever messages are in state. However, we want to add a new message only to the messages of the active user.
Okay. But how?
Remember that every user has their messages mapped to their ID. All we need to do is target this ID and ONLY update the messages in there.
Here’s what that looks like graphically:
Please take a look at the console in the graphic above. The graphic assumes that a user has submitted the form input three times with the text,
Hi.
As expected the text,
Hi shows up three different times in the chat conversations for the particular contact.
Now, have a look at the console. It’ll give you an idea of what we’re aiming for in the code solution to come.
In this application, every user has 10 messages. Each of the messages has a number that ranges from
0 to
9.
Thus, whenever a user submits a new message, we want to add a new
message object but with increasing numbers!
In the console in the graphic above, you’ll notice that the number increases.
10 ,
11 and
12.
Also, the message shape remains the same, having the
number ,
text and
is_user_msg fields.
{ number: 10, text: "the text typed", is_user_msg: true }
is_user_msg will always be true for these messages. They come from the user!
Now, let’s represent this with some code.
I’m going to explain this well, because the code may look complex at first.
Anyway, here is the representation within the
switch block of the
messagesreducer:
switch (action.type) { case SEND_MESSAGE: const { message, userId } = action.payload; const allUserMsgs = state[userId]; const number = +_.keys(allUserMsgs).pop() + 1; return { ...state, [userId]: { ...allUserMsgs, [number]: { number, text: message, is_user_msg: true } } }; default: return state; }
Let’s go over this line by line.
Just after the
case SEND_MESSAGE:, we keep a reference to the
message and
userId passed in from the action.
const {message, userId } = action.payload
To go on, it’s also important to grab the active user’s messages. That is done on the next line with:
const allUserMsgs = state[userId];
As you may already know,
state here isn’t the overall state object of the application. No. It is the state managed by the reducer for the
messages field.
Since every contact’s message is mapped with their user ID, the code above gets the messages for the specific user ID passed in from the action.
Now, every message has a
number. This acts like a unique ID of some sorts. For incoming messages to have a unique ID,
_.keys(allUserMsgs) will return an array of all the keys of the user’s messages.
Okay let me explain.
_.keys is like
Object.keys(). The only difference here is that I’m using the helper from
Lodash. You can use
Object.keys() if you want.
Also,
allUserMsgs is an object that contains all of the user’s messages. It will look something like this:
{ 0: { number: 0, text: "first message" is_user_msg: false }, 1: { number: 0, text: "first message" is_user_msg: false } }
This will continue until the 10th message!
When we do
_.keys(allUserMsgs) or
Object.keys(allUserMsgs), this will return an array of all the keys. Something like this:
[ 0, 1, 2, 3, 4, 5]
The
Array.pop() function is used to retrieve the last item in the array. This is the largest number already existing for the contact’s messages. Kind of like the last contact’s message ID.
Once that is retrieved, we add
+ 1 to it. Making sure that the new message gets
+ 1 of the highest number of the available messages.
Here’s all the code responsible for that again:
const number = +_.keys(allUserMsgs).pop() + 1;
If you’re wondering why there’s a
+ before the
_.keys(allUserMsgs).pop() + 1, this is to make sure that the result is converted to a Number instead of a String.
That is it!
On to the meat of the code block:
return { ...state, [userId]: { ...allUserMsgs, [number]: { number, text: message, is_user_msg: true } } };
Take a look closely, and I’m sure you’ll make sense out of it.
...state will make sure we don’t mess with the previous messages in the application.
Because we are using Object notations, we can easily grab the message with the particular user ID with
[userID]
Within the object, we make sure that all of the user’s messages are untouched:
...allUserMsgs
Finally, we add the new message object with the previously computed number!
[number]: { number, text: message, is_user_msg: true }
It may look complex, but it isn’t. Hopefully, you have experience with this sort of non-mutating state computations from your React development.
Still confused?
Have a look at the return statement again. This time, with some code colours. That may help breathe life into the code:
And that, my friend, is the end of updating the conversation when an input is entered!
We have just a few tweaks to make.
Tweaks to Make the Chat Experience Natural
Here’s what the current state of things looks like when I write
Hello! and submit three times.
You’ll quickly notice two problems.
- Even though the inputs are submitted, and the messages rightly added to the conversations, I have to scroll down to see the messages. This isn’t how chat apps work. The chat window should automatically scroll down.
- It would be nice to clear the value of the input when submitted. This way the user gets some immediate feedback that their input has been submitted.
The second is a much easier fix. Let’s start with that.
We are already dispatching a
SEND_MESSAGE action. We can listen for this action and clear the input value in the
typing.js reducer.
Let’s do just that.
Add this within the switch block of the
typing.js reducer:
case SEND_MESSAGE: return "";
Which brings all the code to this:
reducer/typing.js
import { SET_TYPING_VALUE, SEND_MESSAGE } from "../constants/action-types"; export default function typing(state = "", action) { switch (action.type) { case SET_TYPING_VALUE: return action.payload; case SEND_MESSAGE: return ""; default: return state; } }
Now, once the action gets here, the
typing value will be cleared and an empty string will be returned.
Here’s that in action:
It works!
As expected, the input value is now cleared.
Okay, let’s make sure the chat window scrolls when updated.
To do this we’ll need a bit of DOM manipulation. This is the reason I insisted on making
<Chats /> a class component.
Okay, let’s talk code.
Firstly, we need to create a
Ref to hold the Chats DOM Node.
constructor(props) { super(props); this.chatsRef = React.createRef(); }
If you’re not familiar with
React.createRef(), it is perfectly normal. This is because React 16 introduced a new way to create Refs.
We keep a reference to this
Ref via
this.chatsRef.
In the DOM rendered, we then update the ref like this:
<div className="Chats" ref={this.chatsRef}>
We now have a reference to the
div that holds all the chat conversations.
Let’s make sure this is always scrolled to the bottom when updated.
Say hello to the lifecycle methods!
componentDidMount() { this.scrollToBottom(); } componentDidUpdate() { this.scrollToBottom(); }
So, as soon as the component mounts, we invoke a
scrollToBottom function. We do the same whenever the app updates, too!
Now, here’s the
scrollToBottom function:
scrollToBottom = () => { this.chatsRef.current.scrollTop = this.chatsRef.current.scrollHeight; };
All we are doing is updating the
scrollTop property to match the
scrollHeight
Not so difficult. The
this.chatsRef.current refers to the DOM node in question.
Here’s all the code for
Chats.js at this point.
... class Chats extends Component { constructor(props) { super(props); this.chatsRef = React.createRef(); } componentDidMount() { this.scrollToBottom(); } componentDidUpdate() { this.scrollToBottom(); } scrollToBottom = () => { this.chatsRef.current.scrollTop = this.chatsRef.current.scrollHeight; }; render() { return ( <div className="Chats" ref={this.chatsRef}> {this.props.messages.map(message => ( <Chat message={message} key={message.number} /> ))} </div> ); } } export default Chats;
Hey! With that we have Skypey working as expected!
Here’s a Demo. Note how the scroll position updates as soon the component mounts, and when a messaged is typed, the component also updates.
Awesome stuff!
So, excited!
We’ve come so far :)
Conclusion and Summary
Oh my! This has been an awesome experience for me. Building Skypey was a lot of fun.
Did you love it? I’d love to see your own version of Skypey. Change the colors, tweak the design, and build something better!
When you’re done, send me a tweet and I’ll be delighted to cheer you up.
Here’s a summary of some of the things we’ve learned so far:
- It is a good practice to always plan your application development process before jumping into the code.
- In your state object, avoid nested entities at all cost. Keep the state object normalized.
- Storing your state fields as objects does have some advantages. Be equally aware of the issues with using objects, mainly the lack of order.
- The
lodashutility library comes very handy if you choose to use objects over arrays within your state object.
- No matter how little, always take some time to design the state object of your application.
- With Redux, you don’t always have to pass down props. You can access state values directly from the store.
- Always keep a neat folder structure in your Redux apps, like having all major Redux actors in their own folders. Apart from the neat overall code structure, this makes it easier for other people to collaborate on your project as they are likely conversant with the same folder structure.
- Reducer composition is really great especially as your app grows. This increases testability and reduces the tendency for hard-to-track errors.
- For reducer composition, make use of
combineReducersfrom the
reduxlibrary.
- The object passed into the
combineReducersfunction is designed to resemble the state of your application, with each value gotten from the associated reducers.
- Always break larger components into smaller manageable bits. It’s a lot easier to build your way up that way.
Catch you later!
Exercises
The Skypey app we’ve built here isn’t all there is to the app. There are two more tasks for you.
- Extend the Skypey app we built to handle editing a user’s message as shown below.
- Extend the Skypey app we built to also handle the deletion of a user’s message. Just as shown below.
Those should be fun to implement!
Chapter 5: What Next?
The book you’re currently reading is one out of three in the Redux Trio sequel.
In the second book, Understanding Redux 2, I explain in great detail the tricky advanced Redux concepts such as Middlewares, Higher Order components, Making Ajax calls, and more.
It doesn’t end there.
I’ll also show you around some of the most loved community Redux libraries for solving common problems. Reselect, Redux-form, Redux-thunk, Recompose, and many more.
The following section is an excerpt from, Understanding Redux 2.
Introducing React-Redux
Going to the bank each time you need to make a withdrawal from your account is such a pain. Well, don’t sweat it. This is 2018. We’ve got internet banking, right?
Back to Redux.
Setting up the Reducer, subscribing to the Store, listening and re-rendering upon state changes … we can reduce some of the hassles.
Like Internet banking brings a breath of fresh air to the process of withdrawing money from your account, ‘bindings’ such as React-redux also make it slightly easier to use Redux with React — without performance concerns.
How sweet.
Ready?
I cover this deeply in the follow up book, Understanding Redux 2.
And lots more!
Until then, I’ll catch you later!
Hey, keep coding!
Much love ?? | https://www.freecodecamp.org/news/understanding-redux-the-worlds-easiest-guide-to-beginning-redux-c695f45546f6/ | CC-MAIN-2021-49 | refinedweb | 25,034 | 67.35 |
Implements an object which is a group of polygons (Triangles). More...
#include <polyhedron.h>
Inherits rtl_groupobj.
List of all members.
A polyhedron is defined as a mesh of polygons. This class implements
such a mesh. It is important though that you use it correctly. If you
build a polyhedron from a stream containing the appropriate information
everything is correct however if you specify the mesh programmatically
using addvertex and compute normals you should follow these steps:
Note: if you construct a polyhedron programmatically it is important to ensure that all vertices are added before any of the triangles are constructed. Polygons are added as Triangles through the
Builds a polyhedron with room for the given number of vertices.
v_cntThe number of vertices in this polyhedron
Builds a polyhedron that references another.
Adds a vertex to the polyhedron. This function should not be called
if the polyhedron was built from a stream.
x
y
zobject space corrdinate for this vertex.
u
vtexture space coordinate for this vertex.
Sets the normal for the ith vertex. Using this function will usurp automatic normal calculation for the vertex.
Computes the vertex normals. This function should not be called if the polyhedron was built from a stream. Also this function should be called after the last call to addvertex.
Returns the material which is the tri-linear combination of the materials of the vertices of the last triangle hit. If there has not been a triangle struck then the base class material is returned.
Reimplemented from rtl_subobject.
Scale the model so that it fits inside -1..1 in the widest dimension.
Returns the ith vertex for you to play with.
Returns the number of vertices there are in the model.
Reimplemented from rtl_object.
[protected]
Reimplemented from rtl_subobject.
[protected]
Reimplemented from rtl_subobject.
[protected]
Reimplemented from rtl_object.
[protected]
Sets the material for this object.
Reimplemented from rtl_object.
[protected]
Number of vertices in the model.
[protected]
Table of vertices.
[protected]
rtl_material for triangles to compute the interpolated material into.
[protected]
Specifies the vertex order used to compute normals. | http://pages.cpsc.ucalgary.ca/~jungle/software/jspdoc/rtl/class_rtl_polyhedron.html#a3 | crawl-003 | refinedweb | 340 | 53.27 |
- Start Date: 2015-05-24
- RFC PR:
- Ember Issue:
Summary
This RFC outlines a new strategy for the registration of helpers in Ember 1.13. In previous versions of Ember, helper lookup was a two-phase process of:
- Look in a whitelist of registered helpers. If in the whitelist, resolve that path in the container.
- If the path has a dash, try to resolve it in the container
- If the container does not have a factory for this path, treat the path as a bound value.
This logic runs for every
{{somePath}} in an Ember application.
This proposal attempts to simplify and unify that logic in a a single pass
against a whitelist, thus removing the special behavior of dashed paths.
Additionally, it attempts to design a solution that removes the current
registerHelper ceremony for undashed helpers.
Motivation
In RFC #53 a new API for helpers is outlined. This RFC presumes helpers will continue to have the naming requirement of including a dash character.
The dash requirement for helpers exists for two reasons:
- For every
{{path}}in an Ember application, it must be decided if that path is a bound value, component, or helper. Component and helper lookup (the discovery of a class or template) is lazy in Ember, thus for every
{{path}}a lookup for that string in the container is required. Container lookups (the first time) are fairly slow, and performing this lookup for every path may significantly impact initial render time. Thus, helpers are either added to a whitelist (with
registerHelper) or require a way to differentiate themselves from the majority of data-binding cases (the dash).
- In Ember 1.x, components were treated as helpers for certain code paths. This made the dash requirement for components a natural extension to helpers.
The Glimmer engine has removed some of these concerns and limitations.
Addon authors and app authors have both felt a need for non-dashed helper
names, for example
{{t 'some-string-to-translate'}}. New developers to Ember
often find the dash requirement arbitrary and the
registerHelper work around
difficult to understand and use.
For the new helper API to provide feature parity with APIs available to addon authors in 1.12, a path to dashless helpers must be present in 1.13.
Given that a solution exists that addresses the performance concern, dropping the dash requirement would resolve a significant amount of developer pain and confusion.
Detailed design
At application boot, all known helper items (according to the resolver) are
iterated and added to a
helper-listing service. This service is merely a
Set object with the names of all helpers.
When handling a
{{path}}, the
helper-listing service is consulted for the
presence of that
path. If it is present, the path is looked up
on the container as a helper and the helper is used. Dashed paths are treated
no differently than any other path (for helpers).
Boot time discovery
To discover what paths may be helpers in Ember-CLI, the module names are iterated. For example:
not helper: app/components/foo-bar/component not helper: app/controllers/foo-bar not helper: app/foo-bar/route helper "t": app/t/helper helper "t": app/helpers/t helper "foo-bar": app/helpers/foo-bar helper "foo/bar": app/helpers/foo/bar
In a globals-mode application, The app namespace is iterated:
not helper: App.FooBarComponent not helper: App.FooBarController not helper: App.FooBarRoute helper "t": App.THelper helper "foo-bar": App.FooBarHelper <- should dasherize
In both cases the resolver is responsible for providing a list of modules
by type. The proposed API is
eachOfType, here with Ember-CLI as an example:
// Given helperListing as a Set: resolver.eachOfType(‘helper’, function(parsedName, item) { helperListing.add(parsedName.fullName); })
In Ember-CLI, the
app/ tree of an addon is merged with the app tree of an
application. This means for a helper like
t to be discovered, nothing besides
adding it to
app/helpers/t.js must be done.
In 1.13, this will impact existing apps by discovering all helpers regardless
of if
registerHelper has been called. This is a small behavior change that
should match intent, and will not impact sanely written apps.
Note that only the path of the helper is added to the listing. During discovery, the helper is not looked up from the container, instead lookup still occurs at render time.
The helper listing is intended to be a private service in Ember, and will be
registered at
services:-helper-listing. If the discovery semantics described
here are not sufficient for some edge-cases, wrapping this service in a
public API on application instances may be required.
Render-time lookup and use
Let us consider how a path is rendered. For example:
{{date}}
- The
service:-helper-listingservice is fetched
- The path
dateis checked for on the listing:
helperListing.has(path)
- If the path is not in the listing,
dateis treated like a bound value
- If the path is in the listing, the helper is looked up from Ember's container as
helper:date
- depending on the instance returned from the factory (a helper, shorthand helper, or legacy
Ember.Handlebarsor
Ember.HTMLBars._registerHelperhelper) the proper invocation for that helper is executed
Every rendered path will hit the
helper-listing service, but the check
against a well-implemented Set should be inexpensive.
Drawbacks
Removing the dash requirement will likely result in a larger number of naming conflicts between addons and apps than has existed before now. In general, encouraging verbose helper names may mitigate this concern. Long term, there have been several discussions to date about how to implement namespaces in Ember templates and for Ember engines.
That the helper listing is eagerly discovered at application boot time may impact the design of Ember engines and lazy-loading parts of an app. The discovery cache may need to be flushed and re-generated, however this limitation already exists for the container lookup itself (which caches failures).
That the helper listing is not based on the container means helpers registered, but not added to the listing because of non-standard naming, may need to manually register against the private helper listing API.
Alternatives
Instead of a new across-the-board solution, Ember could continue to use a
registerHelper pattern very similar to what exists today. This would
perpetuate the existing pain, but would perhaps be more similar to what devs
already know.
Unresolved questions
The exact timing of helper discovery in Ember-CLI and globals mode has not been decided. | https://emberjs.github.io/rfcs/0058-helper-listing.html | CC-MAIN-2019-43 | refinedweb | 1,085 | 53.92 |
New Papervision3D Components!
Requirements: Flash CS3 (9)
Ready to get started?
Download it here
You’ll needs some docs with that sauce:
DOCS
Wanna see it in real world action? I used it for the slide presentations at the class this last weekend at RMI.
Here are the demo files and the project for the Jedi Training Sphere slide show
NOTE: You must replace the component in all of the FLA’s – I didn’t go back and do this because of time 😉 Just drag a fresh copy on to the stage, say “yes” to the overwrite in the library, and you’ll be good to go. Otherwise, you’ll see an error about JSFL.
Or get them separately:
demoFiles
JediTrainingSphere
Go here for an explanation of all of the demo files
In case you wanted to see the Jedi Sphere in action, and thus, the slides from the classes:
Developer’s slides
Designer’s slides
And of course, you can find all of that stuff out on Google code:
Papervision3D google home
[ new settings panel: To get started, select a local directory. Then, select the COLLADA file you want to render ]
ROCKS
Drums hitting.
Rocked new component. Simplicity as a fact of life.
as you said 0/
Oh wow! This looks great!
Sweet! The OFLA2 presentation already looked promising, and now we can all use the magic, thanks!
I’ll try it out soon, but first I need some sleep and kitesurfing 🙂
Another time John drives others crazy. Rock on!
This is so great, can’t wait to try it out. Saw the component in action on osflash conf and couldn’t believe my eyes.
btw perfect timing just before the weekend.
Thanks a lot John
I hate to be a the bearer of bad news – maybe I’m just doing it wrong – but I get JSFL errors whenever I try to open any of teh demo files – and when I start from scratch the PV3D panel doesn’t seem to correctly connect to the Collada Scene component on stage – i managed to load a file by typing paths in the component parameters panel – the browse functionality in the PV3D panel didn’t work at all – not even an error – and when I typed things in they were removed when I changed away from that ‘tab’ in the panel – the scale slider threw a massive message into the output panel and made the model complete disappear – even when I reset the scale. The only thing that did seem to work ok was the rotation sphere.
I’m not criticising at all – this is clearly a fantastic component, just thought I’d let you know what has happened here when I tried to use it (PC, Windows Vista Ultimate)
I will try it at work (XP) and let you know if any problems arise there (in which it is probably just me lol)
The demos look awesome, I’m so impressed, I can’t wait to use this for real – huge thanks to you John, the other guys (you know who they are) and to the PV3D discussion list guys
Great, you are my hero !
Do you plan to make something for directly animed things on flash IDE ?
Great work John. Another reason to not clean my apartment.
@Jon B: What version of Flash IDE are you using? I just have to confirm since your description sounds like total melt down 😉
Flash CS3 Professionl (final release, not beta)? I don’t think Professional has anything to do with it, but thought i’d ask.
Did the install go ok? no errors? Did you use the latest Extension manager for CS3?
Thanks for the heads up Jon!
Hey John,
Thanks for this great component. I’m hoping this is the “updated” version since the RMI class. Anyhow, I just want to thank you for the great PaperVision workshop at RMI and I learned a lot. I’m building a school project that uses the Papervision3D engine, and the stuff I learned at your workshop helps immensely. You were great. Keep up the Excellent Work!
Thanks Ruperto – really appreciate that very much
and yes, the components are updated since the class, so get the latest versions
You are seriously the man John. I had such great time at both days of training, and really enjoyed learning first hand, about something this cool. It was awesome just to meet you, and thank you for rocking so hard. I was the PC guy, set-up on the left side of the room with the shark video demo, if you can remember. Anyhow, I downloaded the updated component, and I think the JSFL errors John B might be talking about only occur when you try to load a Collada file that’s outside the local directory. Otherwise, the component looks great, and works like a charm. The addition you made to the rotating feature is also pretty sweet, and makes it easier to maneuver.
Great! I’m amazed, now flash and 3D are married together.
Super work!
Ok – tried at work (xp) and this is what I did.
Downloaded the latest extension manager, installed that – installed your extension. Opened one of the demo files (Xwing.fla) and then opened the PV3D panel – got teh following error:
—————————
Adobe Flash CS3
—————————
The following JavaScript error(s) occurred:
At line 82 of file “C:\Documents and Settings\xxx\Local Settings\Application Data\Adobe\Flash CS3\en\Configuration\Commands\papervision3d\setValues.jsfl”:
TypeError: getParameter(parms, “colladaFile”) has no properties
—————————
OK
—————————
I’ve played around now and managed to laod a DAE file if I start from scratch – the file browser part of the PV3D Panel threw a few javascript errors about unterminated string literals tho the first couple of times I treid to select a file.
Not sure if that is any help to you.
@JonB -YES, that helps 😉 I’m not sure why the error occured, but I’m guessing it’s because the component in the Xwing.fla is older than the one I pushed out yesterday and it doesn’t have a property called “colladaFile” (It used to be called fileRef).
So, replace the component in the FLA with a fresh copy from the components panel, and that error will go away!
@marco: DOOD I so remember you and I owe you $20 for turning in a project over night!!! I was telling R Blank that I forgot to hand out the award and felt bad ;(
Thanks for being there and it was a ton of fun, I really enjoyed both days with you guys!
Hey John the component is great. Only issue I found is that I worked with it yesterday and left it running to come into my machine that had a Flash javascript out of memory error. Although this could be from many things it seems if you leave hte panel open in the middle of work it gets this after many hours. I am not sure if that is just CS3 madness or not but that is the only issue I found.
Thanks, there are similar loading issues with a lot of the demo files which makes sense now.
I have a question for you – what version of PV3D is packaged with your component and what is the plan for keeping it updated with the latest PV3D developments?
I love this component – I can only imagine it getting better too – seriously well done and many thanks.
this is so sick! i cannot belive this is possible at design time! yer the man man!
@Jon: It’s using the latest SVN version. So the idea will be to make sure the component is revised with each release of the package etc.
Great question btw!
@Ryan: Thanks for letting me know. I saw that on one occasion, but then it didn’t happen again. So, I’m not sure what I need to do with that. Basically, I’m pinging the stage to see if there’s a PV3D component selected. Since we can’t make CustomUI’s in Flash9/AS3 Swf’s (because they didn’t put that into the new version), I had to resort to making my CustomUI through JSFL calls with a custom panel
[…] john has really outdone himself this time. this takes alot of the tedium of testing and retesting your 3D scenes to make sure the objects are positioned correctly. […]
Yeah, great news for today, finally v 1.0 !! Thanks!
John, you freakin’ rock.
I’ll stick to java , this leaks memory
Hey! Can an animated MovieClip be used as the “skin” showed in the video ?
@Rafeo: Yes!!! that’s the whole point 😉 If you look at the skins for the Jedi Sphere, one is a MovieClip and it includes a blinking light – which is just a movieclip going back and for between frame1 and 2.
It’s cake!
@Bobby: What does?
John, I don’t know what you mean by you can’t make custom UIs in CS3 or AS3, I just did it easy, and it worked just like in AS2/8.
Either way, the component looks sharp.
@Andrew: You can assign a Flash9 Swf, but you can’t access the xch object because it wasn’t added to AS3 (If I remember what the answer was from adobe correctly). Adobe confirmed, you can’t use a Flash9/as3 swf as a CustomUI. You can assign it via the Component settings panel, but it won’t be able to interact with the properties of the component because it doesn’t have access to the xch object (which is the flux-capacitor of customUI/Component work)
Are you serious? My bad, I assumed since you could add it, it would work. This kind of makes me very upset. So with your workaround, was it something comparable?
@Andrew: yeah, here’s the blurb from another list:
Adobe says:
“I looked into it briefly, and it looks like this works exactly the same way it did before with AS2, but is not possible with AS3. This does not mean it cannot be done for AS3 components–it can. It just means the custom UI needs to be in AS2. A bit of a hassle i know. Since we weren’t doing this, no one ever looked at how it would work. We can probably make simple changes in the future to get AS3 custom UI working in cs4 and beyond.”
@Andrew: Yeah, the workaround I did involves JSFL of course and a custom panel. I don’t like having to go through JSFL like that, but it DOES allow me to create the CustomUI in Flex2 – which rocks and saves me time on that development end. So, after you get the JSFL setup and running, you don’t really have to mess with it after that. But all values are passed as strings, so you have to work with it from there.
Hey – the component looks awesome! great work! – Unfortunately the new component has tons of javascript errors on a mac and does not work with any of the demo examples – even when the component on stage is replaced with the newer version (Using Flash CS3). The old pre-release component, however works perfect on a mac.
you my son are a jedi knight indead. amazing! p;)
I get JSFL errors if the local directory is different to the location of the DAE, seems to be some sort of split removing the slashes in the directory for the collada file. Im guessing that this may have been created on a MAC.
Its all candy when the local folder is the same folder in which the dae resides however.
AAAAAA+++++++++ excellent papervisioner!!!!!!
Amazing Component.
But how can I control it, like rotate at run time.
make sure you give your component an instance name like ‘scene3d’
Then, at runtime, just use yaw(), pitch() or roll() methods to itterate a move on the y/x/z axis’
if you want to set it to a specific degree, use the rotationX, rotationY, rotationZ properties of the collada object.
So:
scene3d.yaw(1) – increments the model by 1 on the Y axis
scene3d.rotationX = 20 – sets the rotation on the X axis to 20
scene3d.yaw(1) – increments the model by 1 on the Y axis
scene3d.rotationX = 20 – sets the rotation on the X axis to 20
That doesn’t work for me John. Just gives me the error message:
1119: Access of possibly undefined property rotationX through a reference with static type org.papervision3d.components.as3.flash9:PV3DColladaScene.
I’m an idiot:
scene3d.collada.yaw(1);
scene3d.collada.rotationX += 1;
That’s what it should be 😉 Thanks for pointing that out
Papervisoon3d v1.5 is alreadu out.
When should we epxect to see your papervision component being updated ?
amazing! time for adobe to make include native 3d support in flash.
welldone~
if dont mind.would you show us some about how to use as3 to control the 3d obj???thank all
have you made something with alternativa 3d flash engine too? they have a lot of things beeing discussed here
still looking for whats going on here… sorry for my english
ah! link
Hi, my name is Matias Morales, I am a beginner in papervision issue. I want to know about: .dae files.
.dae extension
Thank you
how to installe the component
@wddaa: you need to have the Extension Manager for flash installed. you can download it from adobe’s site
Thanks for the great tutorial. I’m able to see the green Xwing in Flash, but when I try to export, I get this error:
1119: Access of possibly undefined property sceneRotation through a reference with static type org.papervision3d.components.as3.flash9:PV3DColladaScene.
If you’re FLA is pointing to the new 2.0 Papervision3d branch, then yeah it breaks the component. You need to remove that class reference and just compile with the code in the component
Thanks for the quick reply John. That fixed it!
…..
am i missing something here? i create a simple cube in 3D Studio max, and do NOTHING but export it to a collada DAE file.
when i try loading it via your panel, i get several errors like this:
DisplayObject3D: objMesh2
Collada material FrontColor not found.
DisplayObject3D: objMesh10
Collada material FrontColor not found.
what gives? the exact same thnig happens if i try this via code:
var newmodel = new Collada(“thecube.DAE”);
any explanation?
yeah again, don’t point the FLA to any of the PV3D source directories or repositories – the component has it’s own version baked in. Try removing any src folder pointers and try again and let me know.
this problem occurs even if i dont use your component, and go strictly with coding it literally using the new Collada() class…
do i need to do somethnig fancy to my stupid Cube primitive in 3DS before i export it to DAE?
when you export from 3DS, you need to check “triangulate” and maybe go ahead and assign a colored material to it.
if other models work with DAE, then it must be how your exporting. Also make sure that your model is an editable mesh. So if you created something with lines etc, you need to convert to editable mesh before exporting.
Great work on this! i was wondering how you could translate the parameters to code, especially the material stuff, do you have any examples? – Thanks!
@JP: yeah, I was going to do a feature that would export what the component was setup up with to pure code for you to use if you needed to. Next version 😉
Your demos are excellent , very impressed. I can wait to see what the following developments will be. This will truly alter the landscape of online gaming.
This is really great, but I can’t publish the files. I got a blank screen when published. I got this error:
DisplayObject3D: null
Papervision3D Beta RC1.1 (18.06.07)
DisplayObject3D: null
Papervision3D Beta RC1.1 (18.06.07)
DisplayObject3D: null
COLLADA file load error Error #2032: Stream Error. URL:
(167)
Collada failed to load scene
xwing.DAE
—————————————————————
I updated the collada component to 1.5 . This does not render properly during authortime.
when published I got this error:
1119: Access of possibly undefined property sceneRotation through a reference with static type org.papervision3d.components.as3.flash9:PV3DColladaScene.
I am getting frustrated with PV3D. I try to follow the demo using the demo files, but nothing shows up. I play with all the controls, but nothing. I have been trying to load a COLLADA file for the last 3 days with no success whatsoever.
Also, is there a certain configuration a COLLADA file needs to be exported with? I have tried multiple configurations from Modo and Blender both of which throw errors.
PV3D has a lot of potential, but is becoming seriously frustrating to use.
Any help would be appreciated. Thanks.
I get the same error:
1119: Access of possibly undefined property sceneRotation through a reference with static type org.papervision3d.components.as3.flash9:PV3DColladaScene.
@vic: if you have your FLA pointing to the Papervision3D repository files, you’ll get that error depending on the version of the repo you are using.
Make sure you’re just using the component without pointing to any class files of papervision and it should work
@Chris: if you’re trying to use the component, use a DAE file (Collada) that you know works with Papervision first. If you’ve gotten the DAE from Blender, It probably won’t work unless you really know what you’re doing with Blender.
email me and I’ll send you a test DAE to try if you like
Thanks John, that was exactly the problem!
So essentially I cannot point to the repository files (classpath) when using the component? Another question would be, is the entire papervision codebase still available to me for use in AS3 VIA the component?
Vic
@John: Last night I was trying with the xwing DAE file included with the other demo files, nothing. I just couldnt get the model to show up in the IDE or the SWF.
Also, what is the best workflow for exporting a COLLADA file? I’ve noticed that the errors are most likely occuring from a poorly exported model, but with no actual instructions on proper exporting, its all touch and go.
just a quick thank you
its I don , how can rotate by mouse
I was getting the same error as VicM, but as soon as I did like you said and took out the AS3 compile settings looking for the pv3d source files (in the publish settings) it worked great!
John, I’m an experienced ActionScripter, but a beginner 3-d modeler. I was saddened a bit to hear you say that you have to really know what you are doing in blender in order to get this to work 😦
I use blender bc it is free, are there other free programs out there that will let you export a good dae file? Or can you tell me what I need to do to make the Collada files play nicely with pv3d from blender?
thanks!!
bryce
@Bryce: yeah get Swift3D for $250 🙂 it imports 3DS files (3DStudio Max), is a decent modeler and it outputs good Collada. It’s the cheapest Collada exporter besides Blender. Blender, IMHO, sucks as far as it’s UI is concerned. Talk about hitting something with the ugly stick – yipes.
I have seen many designers place a camera in the center of a sphere, and map a 360 degree panoramic picture to that picture. Then the direction of the camera is controlled by the mouse or a button on stage. Does anyone know if you can use the papervision component to achieve this functionality? If yes, how would I do it or how would I go about learning?
I am very new to paper vision I have downloaded the files and can get a collada file from 3ds max ,in this case a basic ball as an editable mesh with a basic colour applied .I have saved the collada file in a separate file on my desk top ,opened a 3d component in flash cs3 and I get no image .
Error code
Display object 3d null
Display object 3d sphere01
Collada Material 1- Default not found .
I must be doing something wrong .
Can you please assist me
Regards Peter
Peter, make sure all your files are in the same folder. That means the collada file the textue file and the flash file. Also, you want your texture to already in that file when you apply the material in 3ds.
How do you make it auto rotate, zoom, etc. Are there any very basic scripts to reference?
I exported a maya model as .dae but when I try to use it in the pv3d component i receive an error message. How can I get my Maya files into PV3D?
Flash 3D had never been so easy !
John Grden, you are so generous for sharing your work with us.
I’m going to sing praise of you in my blog. ha ha ha
How do you preload this with a progress bar? I’ve search every where for a tutorial on it.
@george: you can use these events:
import org.papervision3d.core.components.as3.flash9.PV3DColladaScene;
import org.papervision3d.events.InteractiveScene3DEvent;
import org.papervision3d.events.FileLoadEvent;
scene3d.addEventListener(PV3DColladaScene.SCENE_COMPLETE, handleInit);
scene3d.addEventListener(PV3DColladaScene.SCENE_LOAD_PROGRESS, handleProgress);
scene3d.addEventListener(PV3DColladaScene.SCENE_LOAD_ERROR, handleLoadError);
I get these errors & I don’t see the folder Adobe\Adobe Flash CS3\en\Configuration\Components
did it properly install?
Any news on a version of this component for Great White?
when trying to use the load progress functions i get:
ReferenceError: Error #1069: Property scene3d not found on org.papervision3d.components.as3.flash9.PV3DColladaScene and there is no default value.
What is that is wrong?
I’ve pasted what I’m trying but it doesn’t seem to do anything…
[compoent_instancename].collada.addEventListener(PV3DColladaScene.SCENE_COMPLETE, handleInit);
[compoent_instancename].collada.addEventListener(PV3DColladaScene.SCENE_LOAD_PROGRESS, handleProgress);
[compoent_instancename].collada.addEventListener(PV3DColladaScene.SCENE_LOAD_ERROR, handleLoadError);
function handleProgress()
{
this.ppvloadtext.text = “Loading 3d elements”;
}
function handleInit():void
{
// this.ppvloadtext.visible = false;
this.ppvloadtext.text = “3d elements loaded”;
trace(“Complete”);
}
function handleLoadError()
{
// this.ppvloadtext.visible = false;
this.ppvloadtext.text = “error Loading 3d elements”;
}
figured it out… I changed [compoent_instancename].collada.addEventListener(PV3DColladaScene.SCENE_COMPLETE, handleInit);
to
[compoent_instancename].addEventListener(PV3DColladaScene.SCENE_COMPLETE, handleInit);
Best tutorial I have found to date. It works great.
How I just want more.
I am new to papervision and flash, I’m a Maya Max girl.
Is there a way to get character animation into Papervision/Flash?
Can I use collada or do I need a different exporter. Thanks, Irene
Wow man, great job on this…wish I could have been there to see the presentation!
Hi John !
I’m very interested in your work ! I’m currently developping a custom panel for a specific component. Would it be possible to get the source of the panel ? I checked everywhere on papervision googlecode website and didn’t find 😦
thanks
cheers
Yann
This seems great. One question though, which version of Papervision 3D is this supposed to be used with?
I have a very basic JSFL extension to quickly set up your papervision files for CS3 if anyone would like the source tell me, and I’ll send it to you, and maybe some one can add to it. you can download it from me site.
Please help i have no clue what I am doing wrong! Please see error below!
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at org.papervision3d.objects::Collada/parseScene()
at org.papervision3d.objects::Collada/buildCollada()
at org.papervision3d.objects::Collada/onComplete()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
@Kenny, that means there’s something wrong with your Collada file – something in it is unsupported. If you created the collada file, make sure you have the triangulate option turned on. Other than that, you’ll just have to mess with the settings or check the papervision3d.org blog for tips on exporting collada for PV3D
Hey john, youre work is saving my life and keeping me from completely jumping out the window. (im only hanging out of it currently)
i was curious as to how the component gets the collada to load its materials even without a material list.
what is the code that would do that?
Thank you!
I followed the steps but nothing appears in the collada scene.
1) I open a new .fla file in flash
2) Drag a collada scene component to the stage
3) Open the PV3D panel, select the directory where I have my .dae file and then select the .dae file.
The output windows pops up with all the info being downloaded but nothing appears in the collada scene component. It doesn’t output any errors. What am I doing wrong?
hey there, getting the same error as some others
TypeError: Error #1009: Cannot access a property or method of a null object reference.
ive tried with the sample dae files and ones ive created with no change…anyone have a suggestion or 2?
hmm looks like this is only a prob on 64 bit server os
Activation context generation failed for “C:\Program Files (x86)\Autodesk\Maya2008\bin\plug-ins\COLLADAMaya.mll”. Dependent Assembly Microsoft.VC80.MFC,processorArchitecture=”x86″,publicKeyToken=”1fc8b3b9a1e18e3b”,type=”win32″,version=”8.0.50727.4053″ could not be found. Please use sxstrace.exe for detailed diagnosis.
anyone got 64 bit windows they’ve got this working ? .. | https://rockonflash.wordpress.com/2007/06/28/new-papervision3d-components/?replytocom=2166 | CC-MAIN-2020-05 | refinedweb | 4,286 | 64.81 |
In many cases our embedded projects have to deal with various constants or arrays that aren’t changed during program execution. So why put them in RAM if we can store constant data in flash memory and leave RAM untouched. RAM is precious in micro-controllers so leave it for stack and heaps. For instance you are using an LCD in your project and want to send “Hello World” to it you simply grab one of common LCD libraries and use command like:
LCDstring("Hello World");
By using this innocent action we end up in storing this string in flash memory during compilation and loading it to RAM during program start-up routines in microcontroller. When LCDstring() command is executed string is read from SRAM not from FLASH. So we end up with two copies of same string (flash and SRAM) and worse – we occupy SRAM with constants. AVR flash memory locations can be read by program so this feature can be used to read constants directly from flash without loading them to RAM. Before doing this wee need to use one special library:
#include <avr/pgmspace.h>
This library contains all necessary tools that make possible to store data inside flash memory and read from it.
Ways to work with program memory
Let’s begin with a simple example. We often need to store some data array like a text message, signal table or tone data. So any string can be stored in flash memory this way:
const char message[] PROGMEM = “Hello World”
We used a special PROGMEM modifier that indicates compiler to store this string in flash memory. This is nothing more than replacement of __attribute__((__progmem__)) earlier used in WinAVR. It simply indicates linker to put data in the progmem section that lies in flash memory. To read this string from Flash memory, we need to use a special routine that uses LPM command. Luckily pgmspace.h library has already done this for us. To read one byte from Flash, we have to use pgm_read_byte(address) command. As you can see our previous LCDstring(“Hello World”); command won’t work as it only deals with strings stored in RAM. To make it possible we have couple of options. If we need to send string once we can use PSTR macro that allows creating inline strings like this:
LCDstring(PSTR("Hello World"));
But it allows using this string only once. If you need to use same string multiple times then you should go with the second option – write a small routine that reads whole string byte by byte and sends to LCD like this:
void LCDFstring(const uint8_t *flashstring) { uint8_t i; for (i=0; pgm_read_byte(&flashstring[i]); i++) { LCDchar(pgm_read_byte(&flashstring[i])); } }
As our string always ends with ‘\0’ – null. For loop will terminate at this point. In our example, we read single bytes and send to LCD byte by byte. When we need to send a string to LCD we call this function like this:
LCDFstring(&message[0]);
or simply
LCDFstring(message);
because the array variable always holds the address of the first element.
If you look at pgmspace.h library you will find more functions. For instance, you can work with words and double words with commands pgm_read_word(); pgm_read_dword().
Using PROGMEM pointers
Your program probably won’t be dealing with one or couple strings stored in Flash memory. In many cases you may decide to build multilevel menu or multiple messages for various situations. In order to make your program modular you will need to deal with pointers to arrays. It may sound complex but in fact it puts some order in your program.
Let us say wee are building a simple menu system. We put each menu text in program memory. And then make another array that holds pointers to each menu[] = {Menu1, Menu2, Menu3}; //menu item number volatile uint8_t Item; int main (void) { while (1) //Loop { //get menu Item value during some interrupt LCDFstring(Menu[Item]); } }
Now we can send any menu string to LCD by changing only an array index of Menu. Everything seems quite OK, but pointers to arrays are loaded in RAM. Of we make this array quite big – it may also take a significant amount of RAM. Since this array of pointers doesn’t change, we can also put it to Flash with some minor changes in[] PROGMEM= {Menu1, Menu2, Menu3}; //menu item number volatile uint8_t Item; int main (void) { while (1) //Loop { //get menu Item value during some interrupt LCDFstring((uint8_t*)pgm_read_word(&Menu[Item])); } }
First of all we added a PROGMEM attribute to our array of pointers. It tells to store pointers into Flash memory. Then we made some changes to LCDFstring() function:
LCDFstring((uint8_t*)pgm_read_word(&Menu[Item]));
We have to read a pointer value from Flash memory by using pgm_read_word() function. Why reading word if your array is defined as byte? This is because GCC compiler uses two bytes for pointers. So in order to avoid compiler warning we need to read these pointers as words and then typecast to a byte-sized pointers.
Short overview of pgmspace.h
Take a look at pgmspace.h library for more interesting stuff. As I mentioned you can store and read bytes, words, double words and floats. When defining arrays instead of using you can use specially defined types like prog_uint8_t that replaces uint8_t PROGMEM. This way expressions become shorter, like:
const prog_uint8_t Menu1[] = "Menu1";
This will place string in Flash memory. Personally me, I would not recommend using such expressions as it brings more confusion than benefit. Better stick with PROGMEM keyword as it is more visible and easy to track.
Also in pgmspasce.h you will find several handy functions and macros that allows to deal with strings stored in program memory. Normally string functions operate with strings stored in RAM. But what if you want to compare couple strings where one is placed in RAM and another in FLASH. For this you would use following function:
strcmp_P("ram string", PSTR("flash string"));
You will find other string functions that operate in same manner as standard ones. Each of them has a post-fix “_P” indicating that this function deals with strings stored in flash.
Hopefully, I covered the basics of using PROGMEM to get started. Fell free to comment or suggest corrections.
re: const char message[] PROGMEM = “Hello World”
This doesn’t need the since the double quotes tells the compiler it is a string and therefore gets a terminating null added anyway.
(re:post since the form deleted the [backslash] zeroes)
const char message[] PROGMEM = “Hello World\0”
This doesn’t need the \0 since the double quotes tells the compiler it is a string and therefore gets a terminating null added anyway.
Thanks. Fixed that.
Actually this isn’t an error – adding “\0” to the end of string doesn’t affect compiler – it adds one terminating null with or without it in code. I notice some people do add this “\0” in strings while some don’t.
Actually it generates two nulls (and should do since that’s what you’re telling the compiler to do). Sorry, it’s an error!
OK didn’t checked that before. Now I looked at hex and really it generates two nulls at the end of string. Somehow I supposed that compiler understands this and adds single null. Thanks again.
Pingback: Electronics-Lab.com Blog » Blog Archive » Store constants and arrays in program memory
I tried your example and it did not work. After much work, I discovered that for your example to work that the NVM_CMD register must be set to 0x00. It would be helpful for this to be mentioned in your article. Otherwise, the article is good. | https://embedds.com/store-constants-and-arrays-in-program-memory/ | CC-MAIN-2020-24 | refinedweb | 1,290 | 70.73 |
This year is shaping up to be an earth shattering one for Microsoft folks and Web Developers, which means it’s an especially interesting year if you are a Web Developer using Microsoft tools, like me. Firstly, Windows 10 was announced for this summer. I’m already using the Technical Preview. Windows 10 comes with WMF5 and that gives you a new version of PowerShell to work with. Microsoft is also open sourcing the .NET framework and ASP.NET and the next revision is coming likely this year. ECMAScript 6 hits the shelves this year. Finally, Web Components seems to be coming out of the shadows (pun intended) and looks like it will go main stream with supporting projects like Polymer and Aurelia. Wrap all that around a new version of Visual Studio and I can’t wait.
Not everyone likes Visual Studio, though. It definitely forces you into a method of working. Maybe you like picking your tools and Visual Studio forces you into using Grunt or Gulp, or maybe you like following the various instructions you find on the web and Visual Studio does things behind the scenes that prevents you from doing that. Whatever the reason, you don’t have to use Visual Studio. It just takes a little setting up.
Let’s start with writing ASP.NET vNext applications without Visual Studio. Doing this in Visual Studio is easy – you click-install Visual Studio, start it up and then say New -> Project… Nothing could be simpler. Let’s take a look at what that means without Visual Studio in the picture.
Install Git
Firstly, I have to install Git. I get my Git implementation from Chocolatey. So before I can install Git I have to add Chocolatey. Open up a PowerShell prompt with Administrative privileges (Right click and select Run As Administrator). The install of Chocolatey is fairly simple:
# For servers without WMF5 iex ((new-object net.webclient).DownloadString('')) choco install binroot -y # For servers with WMF5 Get-PackageProvider chocolatey -ForceBootstrap -ErrorAction SilentlyContinue
Now that I have Chocolatey I can install Git easily:
# For servers without WMF5 choco install git.install choco install posh-git # For servers with WMF5 Install-Package -Verbose -Force git.install Install-Package -Verbose -Force posh-git
That’s it for administrator type things so exit out of that PowerShell prompt and start a new one that isn’t running as Administrator.
In order to use what I have just installed, I’ve included the following in my PowerShell profile:
Import-Module PathUtils Add-Path -Directory "${env:ProgramFiles(x86)}\Git\bin" Import-Module posh-git first thing I do is alter my path to add git so I can easily run it from the command line. I’ve got a module called PathUtils that includes the Add-Path. The other thing I do is include the code necessary to alter my prompt according to what Git is telling me. This allows me to verify whether I need to check anything in – it’s strictly optional but extremely useful when I am using Git as a source code control mechanism. You can find these files in my Github repository.
Once I have those in place, I closed down my Administrative PowerShell prompt and opened a new non-Administrative PowerShell prompt. Just in case you were wondering, I pretend cmd doesn’t exist these days – everything is PowerShell.
Install the KPM
The next step is to get some files necessary for running ASP.NET from the repository. I like to clone repositories into ~\Source\Github – Visual Studio clones repositories into ~\Source\Repos so it makes sense to put the Github repositories somewhere else. This is a one-time deal, just like installing Git.
cd ~ mkdir Source mkdir Source\Github mkdir Source\Github\aspnet cd Source\Github\aspnet git clone
That last line does the actual cloning. I now have a directory Home. Change the directory into Home. Note the prompt now contains [master] – that’s posh-git telling you the state of the git repository. The cyan indicates that my repository has no pending pushes. Run kvminstall.ps1:
cd Home; .\kvminstall.ps1
Once that is all over I have a ~\.k\bin directory containing a kvm command and that directory has been added to my path. However, the path is not read automatically. I need to close down my PowerShell prompt and re-open it. Run kvm list and I can see the image below:
I should arrange to run kvm upgrade to upgrade your install when new versions come out. If you have multiple versions installed then you can use kvm use to switch between them. This is useful when your main production code is on one version but you are trying out the code on a new version.
Get an Editor
Ok – technically, you COULD write all this in Notepad. Seriously, are you insane? There are a lot of good editors on Windows so you will be spoiled for choice. Here are options on the free end of the scale:
None of these has intellisense. You have been warned. That means that everything needs to be researched and added by hand. I prefer Sublime Text as an editor, but could easily go Notepad++ as Sublime Text costs money.
If you like the integrated stuff, you can’t go wrong with WebStorm. However there is no C# support. It’s great if you are the front end developer and integrating with someone elses ASP.NET code. Webstorm is $49 for a personal license, but open source projects, Microsoft MVPs, students and teachers all get it for free.
Writing a Simple ASP.NET Application
In the Visual Studio environment, I can scaffold my application using New -> Project… There is no scaffolding now – just a KPM environment. So I need to do that myself.
The first thing I need to do is write my project.json file. I’ve switched to my blog-code repository which is in ~\Source\Github\blog-code and created a new directory called BaseAspNetApplication – my intent is that it is a little bit bigger than the Empty ASP.NET application, but smaller than the Starter project. Inside I’ve created a new project.json with the following content:
{ "webroot": "wwwroot", "version": "0.0.1-alpha", "authors": [ "Adrian Hall" ], "dependencies": { "Microsoft.AspNet.Hosting": "1.0.0-beta3", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta3", "Microsoft.AspNet.StaticFiles": "1.0.0-beta3", "Microsoft.AspNet.Diagnostics": "1.0.0-beta3" }, "frameworks": { "aspnet50": { } }, "commands": { "web": "Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=" } }
The commands section may be new to you. Here I can specify additional commands to the K runtime. Much like you would with java – run java somepackage. Here I am running a new web server instead of the IIS Express that I am used to running. I get to specify the URL and the port it is running on so I don’t conflict with anything else.
Did you notice something when you were typing that in? No intellisense. That means I had to go to Nuget and find the packages I wanted, then copy the version in. Intellisense was pretty much the thing I missed when I was doing this without Visual Studio.
Before you go further, make sure you run a package restore. It’s done for you in Visual Studio, but not here. To do a package restore, use the following:
kpm restore
Next up is my Startup.cs which I’ve shown you a few times already:
using Microsoft.AspNet.Builder; using Microsoft.Framework.DependencyInjection; using Microsoft.AspNet.Diagnostics; namespace BaseAspNetApplication { public class Startup { public void Configure(IApplicationBuilder app) { app.UseErrorPage(ErrorPageOptions.ShowAll); app.UseStaticFiles(); } } }
Before I can produce anything, I need a HTML page to display. Place the following in wwwroot/index.htlm – yes, you will need to create the wwwroot directory.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My First Page</title> </head> <body> <h1>Hello World!</h1> </body> </html>
It’s basically the same code that comes for free when you scaffold a new HTML page in Visual Studio. Except no scaffolding. Also there was no auto-indent. You will miss these things when you don’t use Visual Studio.
Run your Application
You are now ready to run your application. There is no handy “start debugging” key – I get to do it by hand. First of all, start the web server:
k web
It should respond with a single word – Started. Nothing else. Now open a browser and point it to. Note that there is no auto-loading of index.html at the root – I needed to specify the page name. I can probably write a controller in the ASP.NET page to do that for me, but out of the box that’s not going to work.
You should get a nice friendly “Hello World!”.
Press Ctrl+C to shut the server down.
Integrate Bower, NPM and Gulp
Over the past few weeks I’ve become a fan of ECMAScript 6 and LESS to the point where I am going to deal with this up front in my base environment. To do that I need to actually install bower, npm and gulp from scratch. It’s done for you in Visual Studio. Luckily for me this is a one shot thing.
First up is NPM. NPM comes along for the ride with Node. I can use Chocolatey to install Node. First up, open up a PowerShell prompt with Administrative privileges and type the following:
# For servers without WMF5 choco install nodejs.install # For servers with WMF5 Install-Package -Verbose -Force nodejs.install
If you’ve got your work PowerShell prompt open, close it and re-open it to get the new PATH. You should now have access to the npm command. I’m doing the rest of the work in a normal PowerShell prompt.
Next on my list is bower. Take a look at the Install Bower page. It gives you precise instructions on how to install bower. It’s a one-liner. Of course, Visual Studio has this installed but it doesn’t give you access to the raw command. You just edit bower.json (by hand) and magic things happen. Once you have bower installed you should be able to just run it. Let’s install something with bower – like bootstrap.
bower install bootstrap
Nice and simple. I got that from the Bootstrap github repository. It didn’t create a bower.json file though. For that I need to use bower init. Walk through the questions – here is what mine looks like:
That’s quite a bit more than Visual Studio gives you. Some of it is not strictly needed because I am doing this as a private repo, but it’s still good to install.
My final piece is gulp. I can install this the same way as bower, but again – read the Getting Started Guide on their website for full details.
I do need a Gulpfile.js which I am going to copy from one of my other projects for now:
var gulp = require('gulp'), babel = require('gulp-babel'), bower = require('main-bower-files'), del = require('del'), eslint = require('gulp-eslint'), less = require('gulp-less'), path = require('path'), sourcemaps = require('gulp-sourcemaps'); var wwwroot = "wwwroot"; gulp.task("lint", function() { return gulp.src(["src/js/**/*.js"]) .pipe(eslint({ globals: { "require": true, "console": true, "$": true }, envs: { browser: true, es6: true } })) .pipe(eslint.format()) .pipe(eslint.failOnErrro()); }); gulp.task("build:css", function() { return gulp.src(["src/less/application.less"]) .pipe(sourcemaps.init()) .pipe(less({ paths: [ "src/less" ] })) .pipe(sourcemaps.write(".")) .pipe(gulp.dest(path.join(wwwroot, "css"))); }); gulp.task("build:js", function() { return gulp.src([ "src/js/**/*.js"]) .pipe(sourcemaps.init()) .pipe(babel({ modules: "amd" })) .pipe(sourcemaps.write(".")) .pipe(gulp.dest(path.join(wwwroot, "js"))); }); gulp.task("build:lib", function () { return gulp.src(bower(), { base: 'bower_components' }) .pipe(gulp.dest(path.join(wwwroot, "lib"))); }); gulp.task("build", [ "build:lib", "build:css", "build:js" ]); gulp.task("clean", function(cb) { del([ path.join(wwwroot, "lib/**"), path.join(wwwroot, "js/**"), path.join(wwwroot, "css/**")], cb); });
That’s a lot of code, but basically it compiles ES6 code into ES5 code, converts LESS stylesheets into CSS stylesheets and installs the library dependencies all in the wwwroot area. I have no package.json file yet. To create that I use npm init which is similar to bower init. First of all, I have to install my dev dependencies:
npm install --save-deps gulp del gulp-less gulp-eslint main-bower-files gulp-babel gulp-sourcemaps
Now that I have some dependencies install I can run npm init. It will ask me a series of questions and at the end it will create the package.json for me. If I come back I can just run npm install and it will restore all the packages for me.
Some final closing things. Firstly, I’ve done the same changes I’ve done in previous articles to bower.json and package.json. The package.json changes were done to support eslint and the bower.json changes were done to support main-bower-files. Secondly, I added the RequireJS dependency to the bower.json file since I’m using it so often.
I also added a small src/js/application.js and src/less/application.less. This was more to test the build system.
The good news is that I can now use this repository as a starting point for my applications. I just have to clone it and then edit the individual JSON files plus Startup.cs for the new names. I can also import this project into Visual Studio if I wish. You can check out all the work on my GitHub Repository.
Now, are you sure you don’t want to follow me back to use Visual Studio? | https://shellmonger.com/2015/03/27/building-asp-net-vnext-apps-without-visual-studio/ | CC-MAIN-2017-13 | refinedweb | 2,305 | 68.16 |
load_all
Percentile
Load complete package.
load_all loads a package. It roughly simulates what happens
when a package is installed and loaded with
library.
- Keywords
- programming
Usage
load_all(pkg = ".", reset = TRUE, recompile = FALSE, export_all = TRUE, quiet = FALSE, create = NA)
Arguments
- pkg
package description, can be path or package name. See
as.packagefor more information.
- reset
clear package environment and reset file cache before loading any pieces of the package. This is equivalent to running
unloadand is the default. Use
reset = FALSEmay be faster for large code bases, but is a significantly less accurate approximation.
- recompile
force a recompile of DLL from source code, if present. This is equivalent to running
clean_dllbefore
load_all
- export_all
If
TRUE(the default), export all objects. If
FALSE, export only the objects that are listed as exports in the NAMESPACE file.
- quiet
if
TRUEsuppresses output from this function.
- create
only relevant if a package structure does not exist yet: if
TRUE, create a package structure; if
NA, ask the user (in interactive mode only)
Details
Currently
load_all:
Loads all data files in
data/. See
load_datafor more details.
Sources all R files in the R directory, storing results in environment that behaves like a regular package namespace. See below and
load_codefor more details.
Compiles any C, C++, or Fortran code in the
src/directory and connects the generated DLL into R. See
compile_dllfor more details.
Runs
.onAttach(),
.onLoad()and
.onUnload()functions at the correct times.
If you use testthat, will load all test helpers so you can access them interactively.
Namespaces.
Shim files
load_all also inserts shim functions into the imports environment
of the laded package. It presently adds a replacement version of
system.file which returns different paths from
base::system.file. This is needed because installed and uninstalled
package sources have different directory structures. Note that this is not
a perfect replacement for
base::system.file.
Aliases
- load_all
Examples
#) # } | https://www.rdocumentation.org/packages/devtools/versions/1.13.5/topics/load_all | CC-MAIN-2018-26 | refinedweb | 313 | 51.65 |
Hi friends, here i am going to make an Application "how can take Print Receipt and save data in database in windows Forms application".This project is very helpful for your Real Time Project Development and you can achieve more knowledge from this projects. You can download whole Application from the bottom of this page.
Step7:- Create Studentdetail1 table in SQL Database for save the Form1 data on click on Submit Button.
see it:
See it:-
Step9:- Now go Form2.cs(Design) File-> Double click on Preview button-> write the following code which are given below:-
see it:-
see it:-
Step11: Now you can see the studentdetail1 table data after the printout of the form.
see it:-
To Get the Latest Free Updates Subscribe
Click below for download whole application
DOWNLOAD
There are some steps ,Please follow it
Step1:- Open your visual studio-> File->Click New Project->Select Windows Forms Application -> Select c# language from left window->write your application name->click OK.
Step2:- Now open Form1.cs(Design) File->Drag and drop label ,Text Box and Button Control from Toolbox-> change the label name as shown below
Step3:- Add New Form form solution Explorer windows->go Form2.cs(Design) File->Drag and drop TableLayoutPanel From Toolbox-> go Property of TableLayoutPanel and change the RowCount =7.
SEE IT:->
Step4:- Drag and drop label control from Toolbox-> change the Label Name as below: see it:-
Step5:- Now go Property o each label (9,10,11,12,13,14,15) and change Each label Modifiers=Public
SEE IT:-
Step6:- Now drag and drop printDocument1 and printPreviewDialog1 control from the Toolbox on the Form 2-> go property of printPreviewDialog1 and select Document = printDocument1.
see it:-
Step7:- Create Studentdetail1 table in SQL Database for save the Form1 data on click on Submit Button.
see it:
Step8:- Now go Form 1->Double click on Submit Button -> Write the following codes which are given below:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace print_recipt { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlDataAdapter da; DataSet ds; SqlConnection con; private void button1_Click(object sender, EventArgs e) { con = new SqlConnection("data source=RAMASHANKER-PC;Integrated Security=Yes;Database=master"); da = new SqlDataAdapter("insert into studentdetail1 values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "')", con); ds = new DataSet(); da.Fill(ds); //MessageBox.Show("Fee has been successfully Submitted"); Form2 f2 = new Form2(); this.Hide(); f2.label9.Text = textBox1.Text.ToString(); f2.label10.Text = textBox2.Text.ToString(); f2.label11.Text = textBox3.Text.ToString(); f2.label12.Text = textBox4.Text.ToString(); f2.label13.Text = textBox5.Text.ToString(); f2.label14.Text = textBox6.Text.ToString(); int n1 = int.Parse(textBox5.Text); int n2 = int.Parse(textBox6.Text); int total = n1 + n2; f2.label15.Text = total.ToString(); f2.Show(); } } }
- Write the above code on the Form1.cs File.
Step9:- Now go Form2.cs(Design) File-> Double click on Preview button-> write the following code which are given below:-
using System; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Drawing.Printing; namespace print_recipt { public partial class Form2 : Form { public Form2() { InitializeComponent(); } = this.CreateGraphics(); Size s = this.Size; memoryImage = new Bitmap(s.Width, s.Height, mygraphics); Graphics memoryGraphics = Graphics.FromImage(memoryImage); IntPtr dc1 = mygraphics.GetHdc(); IntPtr dc2 = memoryGraphics.GetHdc(); BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376); mygraphics.ReleaseHdc(dc1); memoryGraphics.ReleaseHdc(dc2); } private void button1_Click(object sender, EventArgs e) { CaptureScreen(); printPreviewDialog1.ShowDialog(); } private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) { e.Graphics.DrawImage(memoryImage, 0, 0); } } }
- Write the above code on the Form2.cs File.
Step10:-
- Now Run The Application(Press F5)-> Fill the data on the Form1.cs(Design) File.
- Click the Submit button-> then you will go to the Form 2.
see it:
- Now click the Preview button -> Take printout on click on print button.
see it:-
see it:-
For more:
- Add sql Database(.mdf) in Asp.Net ApplicationPrint the Grid Data in Windows FormsApplication
- Create .dll File and Use in Asp.netApplication
- Create a Setup File
- File Handling Real Application
- Ado.Net Application
- Make Captcha image for Asp.NetApplication
- E-Post System Project
- How to use application state and global.asax file in asp.net
- How to use binding Navigator controls in asp.net
- Web Form controls in asp.net
- How to solve sql server database (.mdf) file problems
- How to make custom login and Registration page
- Call by value and call by reference in c#
- Data set and Data adopter in c#
Click below for download whole application
DOWNLOAD
[System.Runtime.InteropServices.DllImport("gdi32.dll")] in this error occur
@Sunny Dhiman ,there are some missing .dll file in your visual studio.follow the below steps
open your solution Explorer -->right click on project--->Add Reference--> .NET--> select all InteropServices one by one-->ok .then you can run this application without error.
I need to do a textile billing application.. how can i use the printing . here it takes the screen shot fully.. i need just the contents.. what to do?
you can use session variable to transfer value from one page to another page and use java script code for printing.
How could i do this website?
first use session variable for transfer the control value to another page and use java script or j query for printing this page.
Hii i have an application where there are lots of lables and textboxes here i want to print the text of lables and text inside the textbox and i did it but only printing the content which is fitting in one page in preview im unable to extend the content to print to next page ...so how can I do it Please help me
Hi Muzammil tell me,which type of application you are using windows Forms or asp.net.you can send snapshot of your page on my Email-ramashanker@outlook.com .then i can help you.
thanks it s really nice. i have one doubt from datagridview. i save student details name,id,phone. and show in gridview . then i doubleclick the any row in gridview another form need to open and get value form datagrid selected value and display on name field name, id field id, and so on. guide me my mail id manojija007@gmail.com
Mine data is not shown in the print page..data is being inserted but not shown when i click on the preview button,its shows me blank page to print
@Ravinder singh saini, follow step 5 carefully .it will work definetly......
I have followed it sir,i used try-catch now it gives invalid printer exception.
hey sir when i click on print button it doesn't show any preview...
hi suraj,go properties of each control on form2,change Modifier==public,see step 5 ,i have already mentioned it.
DEAR SIR THIS CODE ONLY USE IN WEB FORM , THAN HOW USE THIS CODE FOR WEB APPLICATION DATA ENTRY IN C#
BECAUSE MY DATA ENTRY FORM IN WEB APPLICATION
PLEASE GUIDE ME
hi sandesh, you can use same concepts in web application also but you need to write same code as web application using c#.i have already posted many post please read it and implement in your projects.
Thank you so much for your post because this is very useful for me at the end time of my project...
tc...gn
sir i need ado.net material will plzz forward to this mail id.
raja.sekhar0011@gmail.com
I am going to write a code for print page and receipts in asp.net,c#. whenever we works on any website and software – we need to print some report and date using printer. So now we are going to learn write thing on write place.
So for this execution we need to follow some step. You can also find here attached application here Print demo application
Firstly we creates a new website and a newpage and create new app_code folder .
Here we writes a code for print in app_code folder that is work as class file.
Add a class file in app_code folder with te name of PrintHelper.cs.
Code for PrintHelper.cs in App_code : -
hi sir,
thank u for sending me the material. And one more request will please guide how can i prepare the ado.net and get succeed in get the job please give some guide lines.....
hi sekhar ! only focus on your concepts.If you know concepts very well ,I hope ,you will get job definitely.There are some points which you have to follow.
1.) English communication
2.) Technical Knowledge(aptitude,reasoning)
3.) Language knowledge(c or c++ or c# or java)
Attention :-Now days English communication is more important......
you can learn aptitude,reasoning and other technical things from below url.
if any query ask again.....
i sir may i knw where r u from and will please give me ur phne no to contact if u dnt mine i wan clarify my douts through call.
its also showing button on print
hiiiiiiii,Actually i have done integration part of camera in c# windows application through metricam. now i want code for capturing image and that images is save in Database.Please Help me. send me that code on my email id
vaibhavb029@gmail.com
Refer below link it may be helpful for you...
error from sql server
hi Krishnan ! it may be version problem,so you have to create your own sql database on your system .
hello sir i have tried ur code but i am getting print of half windows form nly plzzz help?
hi alex ! Follow step 5 carefully.you can print only visible screen on your desktoponly in windows form application.
hello mr.ramashanker i put your code in my form which has textbox so its not working why??? ...
hello mr.ramashankar .. i want to print form which has textbox and picturebox with image but this code not working ... how to print colorful form with images form
hi priyank ! follow step 5 ,6 carefully,set all control's modifier = public,.Then you can print whole form without any problem,For color print, you have to use color printer...
this doesn't work, errer "document does not contain any pages", i think the Form2 you post lost a little code. :|
bhaii apni chaii ki dukaan hai , ye sofware bnaya , but wo peela wala form kaise bnauu, koi btaega to usko free chaii pilaunga
in place of sql server db want to use ms excel, can you help to get the method
Hi,
For me data is not shown in the print page..data is getting inserted in database also but not shown when i click on the preview button,its shows me blank page to print
and I am getting these errors
Could not copy "obj\x86\Debug\PrintReceipt1.exe" to "bin\Debug\PrintReceipt1.exe".Exceeded retry count of 10.Failed.
Unable to copy file "obj\x86\Debug\PrintReceipt1.exe" to "bin\Debug\PrintReceipt1.exe".The process can not access the file "bin\Debug\PrintReceipt1.exe" because it is being used by another process.
Hi, I have web Application,recently i am using crystal report to print report
but As per requirement I want to print report using min printer, so is it need to use different concept to print report
Thanks | http://www.msdotnet.co.in/2012/06/how-can-take-print-receipt-and-save.html | CC-MAIN-2017-26 | refinedweb | 1,911 | 59.09 |
Subject: Re: [boost] [Foreach] Supporting range adaptors for temporary containers
From: Jeffrey Lee Hellrung, Jr. (jeffrey.hellrung_at_[hidden])
Date: 2011-04-21 16:32:19
On Thu, Apr 21, 2011 at 1:07 PM, Michel MORIN <mimomorin_at_[hidden]> wrote:
> Sometimes it is convenient to apply range adaptors to a temporary container
> and iterate over it:
>
> // `using namespace boost::adaptors;` is assumed
> BOOST_FOREACH(auto x, std::string("Hello, world!") | reversed) {...}
>
> However, the lifetime of the temporary container ends before the loop body
> begins.
[...]
I believe BOOST_FOREACH correctly accounts for rvalue range expressions.
See second-to-last example from
Does this address your concern?
- Jeff
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2011/04/180592.php | CC-MAIN-2019-43 | refinedweb | 125 | 51.14 |
Auto load folder of images to material [SOLVED]
On 29/05/2015 at 12:24, xxxxxxxx wrote:
Hi everyone!
I don't know python at all but I'm trying to figure out how to automate part of a process for a job I'm working on.
My goal is to load images from the "tex" folder into the color channel of the material on my object, keyframe it, move to the next image, then next frame, keyframe, etc., until all images in that folder have a keyframe on the same material. I've been doing it by hand for this job for folders with 160 images and making mistakes, and now the job requires me to do that for folders much larger! ARgh!
I know you can use the animate function on a material to pull a folder of images but it doesn't import the image path nor does it create an actual keyframe which I need for my project to work correctly.
I've been pulling python code from various places and trying to toy around and get something to work but I just lack the knowledge and experience. Had I more time I could maybe flesh it out but as I don't have a ton of time I am turning to you :-)
I found this code that loads an image from the desk top. It seems to work but I can't seem to change the path to, say, the tex folder in my job....but on top of that I need it to do more.
import c4d
import os
def main() :
fn = c4d.storage.GeGetC4DPath(c4d.C4D_PATH_DESKTOP) #Gets the desktop path
pathToTexture = os.path.join(fn,'01.jpg') #Gets the specific texture image on your desktop
mat = doc.GetActiveMaterial() #Assign the active material a variable
shdr_texture = c4d.BaseList2D(c4d.Xbitmap) #Create a bitmap shader in memory
shdr_texture[c4d.BITMAPSHADER_FILENAME] = pathToTexture #Assign the path to the texture image to your shader
mat[c4d.MATERIAL_COLOR_SHADER]= shdr_texture #Assign the shader to the color channel in memory only
mat.InsertShader(shdr_texture) #Insert the shader into the color channel
mat.Update(True, True) #Re-calculate the thumbnails of the material
if __name__=='__main__':
main()
I've also pulled some other code that might get the job done but I am not sure how to implement it.
imageList = os.listdir(folder) # get folder contents frame = document.GetFrame() # determin the current frame offset = 0 # define frame offset frameOffset = frame+offset # calculate the offset material[c4d.imageSlot] = imagelist[frameOffset] # set image in material Any help would be greatly appreciated.
On 29/05/2015 at 17:20, xxxxxxxx wrote:
Hi and welcome ibycus!
this code should answer your question.
If something is nonspecific or you have other questions feel free to ask.
Best wishes
Martin
import c4d, os from c4d import gui, bitmaps def main() : #_________________________________________________ #assuming your scene was saved before abspath= doc.GetDocumentPath()+"/"+"tex" imageList = os.listdir(abspath) if imageList == []: return #_________________________________________________ #validate pictures fast #just check the extensions #ensure that there is no hidden .DS_Store etc ext = (".jpg", ".png", ".gif") #and so on for f in imageList: if not any(f.endswith(e) for e in ext) : imageList.remove(f) if imageList == []: return #_________________________________________________ #validate pictures slow #initialize every picture with c4d #""for i in imageList: #""orig = bitmaps.BaseBitmap() #""if orig.InitWith(abspath+"/"+i)[0] != c4d.IMAGERESULT_OK: #""imageList.remove(i) #""if imageList == []: #""return #_________________________________________________ #validate material and shader mat = doc.GetActiveMaterial() if not mat: return shader = mat[c4d.MATERIAL_COLOR_SHADER] if not shader: shader = c4d.BaseList2D(c4d.Xbitmap) shader[c4d.BITMAPSHADER_FILENAME] = imageList[0] mat[c4d.MATERIAL_COLOR_SHADER] = shader mat.InsertShader(shader) if shader.GetType() != c4d.Xbitmap: print "No valid bitmapshader in the slot! Please remove the current shader." return #_________________________________________________ #validate animation track and curve tracks = shader.GetCTracks() track = [] if tracks != []: #if there is any track for tr in tracks: if tr.GetDescriptionID()[0].id == c4d.BITMAPSHADER_FILENAME and tr.GetObject() == shader :#check if there already exists a filetrack at the shader track = tr curve = track.GetCurve() if not track: #if not build it descid = c4d.DescID(c4d.DescLevel(c4d.BITMAPSHADER_FILENAME,c4d.DTYPE_FILENAME)) track = c4d.CTrack(shader,descid) shader.InsertTrackSorted(track) curve = track.GetCurve() else: #if there is no track at all, build a file track descid = c4d.DescID(c4d.DescLevel(c4d.BITMAPSHADER_FILENAME,c4d.DTYPE_FILENAME)) track = c4d.CTrack(shader,descid) shader.InsertTrackSorted(track) curve = track.GetCurve() #_________________________________________________ #store current time and ensure the document takes long enough lenList = len(imageList) intime = doc.GetTime() fps = doc.GetFps() inframe = intime.GetFrame(fps) maxtime = doc.GetMaxTime().GetFrame(fps) if maxtime < lenList: newtime =c4d.BaseTime(float(lenList)/fps) doc.SetMaxTime(newtime) doc.SetLoopMaxTime(newtime) #_________________________________________________ #for every item in imagelist set a key to the shaders curve for i in xrange(lenList) : frame = i keyTime = c4d.BaseTime(frame,fps) #set up the basetime object addPicture = curve.AddKey(keyTime) #try to add a key to the curve if addPicture: shader[c4d.BITMAPSHADER_FILENAME] =imageList[i] #assign the image to the shader keyPicture = addPicture["key"] #grab the key variable from the key dict keyPicture.SetGeData(curve, imageList[i]) #assign imagedata to the key track.FillKey(doc, shader, keyPicture) #fill the key on track #_________________________________________________ #go to the stored frame and animate everything at this frame to update the scene doc.SetTime(intime) doc.ExecutePasses(None, True, False, False, 0) c4d.EventAdd() if __name__=='__main__': main()
On 01/06/2015 at 07:55, xxxxxxxx wrote:
Holy Moly!
Thanks a lot! That was a little more involved than I thought it would be. Thanks so much for taking the time to look at this and leaving notes so I can see whats going.
You have set up a "fast load" and a "slow load", the slow load is disabled. What exactly is the difference between the two? I couldn't get the slow load to do anything for me.
Also, it seems to be loading the image list in a random order. Is there anyway to force is to load alphabetically?
Thanks again,
Ashly
On 01/06/2015 at 11:40, xxxxxxxx wrote:
Hi Ashly,
you´re welcome!
Here everything works as expected.
You might use some python sort routine to sort your list alphabetically.
sorted(imageList, key=str.lower)
The slow load is way overdone, it initializes every bitmap in c4d.
The fast load just checks if file endings match the types you defined in the extension list.
They both should do the same with your imageList, if the extension list is well defined.
But with the slow load you´ll be absolutely sure that c4d can handle your files.
(There might be cases where your file has e.g. a .tif ending but is no picture at all.)
Furthermore you can manipulate the bitmaps in c4d.
Hope this helps!
Best wishes
Martin
On 02/06/2015 at 09:13, xxxxxxxx wrote:
Thanks Martin!
You are a gentlemen and a scholar.
I ended up getting it to work with
imageList.sort() | https://plugincafe.maxon.net/topic/8774/11568_auto-load-folder-of-images-to-material-solved/4 | CC-MAIN-2020-24 | refinedweb | 1,150 | 60.01 |
Recently in my day job, I came across some C code that just felt inefficient. It was code that appeared to take a 16-bit integer and split the high and low bytes in to two 8-bit integers. In all my years of C coding, I had never seen it done this way, so obviously it must be wrong.
NOTE: In this example, I am using modern C99
uint8_t bytes[2]; uint16_t value; value = 0x1234; bytes[0] = *((uint8_t*)&(value)+1); //high byte (0x12) bytes[1] = *((uint8_t*)&(value)+0); //low byte (0x34)
This code just felt bad to me because I had previously seen how much larger a program becomes when you are accessing structure elements like “foo.a” repeatedly in code. Each access was a bit larger, so it you used it more than a few times in a block of code you were better off to put it in a temporary variable like “temp = foo.a” and use “temp” over and over. Surely all this “address of” and math (+1) would be generating something like that, right?
Traditionally, the way I always see this done is using bit shifting and logical AND:
uint8_t bytes[2]; uint16_t value; value = 0x1234; bytes[0] = value >> 8; // high byte (0x12) bytes[1] = value & 0x00FF; // low byte (0x34)
Above, bytes[0] starts out with the 16-bit value and shifts it right 8 bits. That turns 0x1234 in to 0x0012 (the 0x34 falls off the end) so you can set bytes[0] to 0x12.
bytes[1] uses logical AND to get only the right 8-bits, turning 0x1234 in to 0x0034.
I did a quick test on an Arduino, and was surprised to see that the first example compiled in to 512 bytes, and the second (using bit shift) was 516. I had expected a simple AND and bitshift to be smaller, but apparently, on this processor/compiler, getting a byte from an address was smaller. (I did not tests to see which one used more clock cycles, and did no experiments with compiler optimizations.)
On a Windows PC under GNU-C, the first compiled to 784 bytes, and the second to 800. Interesting.
I ran across this code in a project targeting the Texas Instruments MSP430 processor. The MSP430 Launchpad is very Arduino-like, and previous developers had to do many tricks to get the most out of the limited RAM, flash and CPU cycles of these small devices.
I do not know if I can get in the habit of doing my integer splits this way, but perhaps I should retrain myself since this does appear incrementally better.
Update: Timing tests (using millis() on Arduino, and clock() on PC) show that it is also faster.
Here is my full Arduino test program. Note the use of “volatile” variable types. This prevents the compiler from optimizing them out (since they are never used unless you uncomment the prints to display them).
#define OURWAY void setup() { volatile char bytes[2]; volatile uint16_t value; //Serial.begin(9600); value = 0x1234; #ifdef OURWAY // 512 bytes: bytes[0] = *((uint8_t*)&(value)+1); //high byte (0x12) bytes[1] = *((uint8_t*)&(value)+0); //low byte (0x34) #else // 516 bytes: bytes[0] = value >> 8; // high byte (0x12) bytes[1] = value & 0x00FF; // low byte (0x34) #endif //Serial.println(bytes[0], HEX); // 0x12 //Serial.println(bytes[1], HEX); // 0x34 } void loop() { // put your main code here, to run repeatedly: }
The method using addresses is not portable. You would at least need to #ifdef based on the endianness of your processor.
Also, it’s hard to say which would be faster or smaller from such a small sample of code. You’ve disabled some optimization by declaring the variable volatile. For example, on x86 it’s possible that 0x1234 could be loaded into %eax and then value >> 8 could be directly accessed as %ah and value & 0xff as %al. No extra operations needed at all. This might be harder for the compiler to recognize with the address approach. (It might not be allowed to keep the variable in a register since its address is taken; I’d have to read the spec to be sure.) Or, if you’re dealing with a constant, the compiler could recognize that fact and treat the individual bytes as constants also.
I’d recommend that you stick with your old, portable method.
Hey Greg, long time no hear! The coders that came before me went to this approach, no doubt, due to the very constrained memory on the system I am working with. In my other tests, volatile was not used (I printed the variables, forcing them to stay around). Benchmarking the Arduino showed it 68% faster, and on the PC/x86 it was not quite that much of a jump, but still faster.
I would wonder if some architectures might not allow accessing the odd-byte and would generate more code.
While I try to write as strict-ANSI as I can, in constrained systems (like Arduino, or the MSP430 at work) I have been turning to things like this. That code, versus the bitshift/AND, saved 144 bytes. Considering my project has already required me to add various compression methods to even fit in the remaining space, every byte counts.
I am just surprised it seems to generate smaller and faster code on the two test systems. I am looking for one where it is slower and/or larger. I wish I had Ultra-C setup to see how it deals with it. (I have tested GNU C and some MSP430 compiler that is proprietary.)
The code to avoid gratuitous SEX in Ultra C would turn too & 0xff into (unsigned char) foo, so it would, if too were in a d register, do a mov.b to get the LSB. I’m not sure whether we made the x86 back end notice getting the MSB of an unsigned short. If we did, I’m pretty sure that if value were in ax, it would just mov al and then mov ah, about as good as it gets. | http://subethasoftware.com/2014/12/16/splitting-a-16-bit-value-to-two-8-bit-values-in-c/ | CC-MAIN-2018-22 | refinedweb | 1,010 | 69.41 |
35250/access-using-django-contrib-models-user-latest-release-django
Hi all. I am trying to figure it out but I am unable to do so and I am stuck.
My requirement is that I want to know how to get the name of any user from the django model - django.contrib.auth.models.User, and doing this only solely on the basis of ID. I also want to delete the user in case I choose to do so, hence I'm trying to use this to do it:
User.objects.get(id=request.POST['id'])
The thing is it returns a straight-up error and I am presen
User matching query does not exist.
Do note that in this case I am using the ID which is sent by AJAX:
$("#dynamic-table").on('click','.member_delete_btn', function() {
if (confirm("Are you sure? the member will be deleted...") == true) {
$.ajax({
type: "POST",
url: "/panel/member/delete/",
data: { id: $(this).attr('data-id'), 'csrfmiddlewaretoken': '{{ csrf_token }}' },
success: function (data) {
if(data.success) {
$('#result').html('<div class="alert alert-success"> <strong>Well done!</strong> Member deleted.</div>');
list_members();
}else{
$('#result').html('<div class="alert alert-warning"> <strong>Warning!</strong> Member not deleted.</div>');
}
},
error: function (data) {
alert("failure:" + data.error);
}
});
}
else {
return false;
}
return false;
});
But where I am confused is that when I go ahead and debug it it seems to be perfectly alright, the user actually exists in the database tables and the other thing is that the ID is perfect and intact (correct)
So my question is simple, how do I do this? Is there any particular delete method meant solely for Django User instances? Or how I go about this on a whole?
Appreciate all the help, thanks!
Hi, there is only that way and to do it and whatever you are doing is perfectly correct.
But, there is a problem here if you have noticed yet. What if the user you requested does not exist in the schema at all? You have not handled this case at all. I suggest you use the following piece of code for this purpose and it should help with the error, it is a simple exception try/catch block as you can see:
try:
user_id = int(request.POST['id'])
user = User.objects.get(id=user_id)
except User.DoesNotExist:
//This is to actually handle the faulty case when the user does not exist in the database.
There is one last step. You need to convert the ID to an integer to get the required output.
Hope this helps!
lets say we have a list
mylist = ...READ MORE
$ to match the end of the ...READ MORE
Hi,
You can use dedicated hooks(decorators) called before ...READ MORE
Hey @Jinu,
Try something like this:
import turtle
star = ...READ MORE
Hi all, with regard to the above ...READ MORE
Hello @kartik,
To turn off foreign key constraint ...READ MORE
Hello @kartik,
Let's say you have this important ...READ MORE
Hello @kartik,
You can use the add filter:
{{ object.article.rating_score|add:"-100" }}
Thank ...READ MORE
Hi, it is pretty simple, to be ...READ MORE
Hi, good question. If you are considering ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/35250/access-using-django-contrib-models-user-latest-release-django?show=35251 | CC-MAIN-2021-21 | refinedweb | 534 | 69.07 |
I want to share with you my progress while i’m working on a web app, this project is mainly for (my) learning purposes, and by sharing this with you i’m aiming to get your help, advices or criticism, or maybe you are trying to build something similar, in the other side you may be just curious about creating something with the mentioned technologies and willing to see a (somehow) beginner trying his best to find the way through.
I’m still learning and experimenting and trying to get comfortable in the Clojure ecosystem, which is really awesome, but has a significant lack of documentations, and you can tell what does that mean for a beginner.
So, this will be a series of articles, in which i will talk about problems i face, and good things i discover or build.
The project is about a news social network “O2SN”, that will have the following features :
- Getting news by location.
- News will be ranked using various criteria : author’s honesty, objectivity … all those will be calculated automatically.
- Seeing a (nearly) real time news ranks changes (highly ranked news get higher)
- Everyone can post a story (which should be true and objective, otherwise the writer’s reputation will be affected, and his future news won’t rank well)
- In case you want to post a story but a similar one already exists, you can claim it, the two stories (or more) will be merged (their ranks…), and people can see all the versions of (the newly) one story
- People can mark a story as truth or lie (which will impact its ranking)
- When a person marks a story as truth or lie its properties change according to the person’s reputation, and geographical distance between him and the story’s or event’s occurrence location.
- And more ...
I created this project using luminus template, but i added some other libraries as well, so this is my current toolbox :
:dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.10.238" :scope "provided"] [org.clojure/tools.cli "0.3.6"] [org.clojure/tools.logging "0.4.0"] [org.clojure/data.json "0.2.6"] [org.clojure/tools.trace "0.7.9"] [org.clojure/tools.namespace "0.2.11"] [org.clojure/test.check "0.10.0-alpha2"] [buddy "2.0.0"] [ch.qos.logback/logback-classic "1.2.3"] [cider/cider-nrepl "0.15.1"] [clj-oauth "1.5.5"] [clj-time "0.14.3"] [cljs-ajax "0.7.3"] [compojure "1.6.0"] [cprop "0.1.11"] [funcool/struct "1.2.0"] [luminus-aleph "0.1.5"] [luminus-nrepl "0.1.4"] [luminus/ring-ttl-session "0.3.2"] [markdown-clj "1.0.2"] [metosin/compojure-api "1.1.12"] [metosin/muuntaja "0.5.0"] [metosin/ring-http-response "0.9.0"] [mount "0.1.12"] [org.webjars.bower/tether "1.4.3"] [cljsjs/semantic-ui-react "0.79.1-0"] [cljsjs/react-transition-group "2.3.0-0"] [cljsjs/react-motion "0.5.0-0"] [re-frame "0.10.5"] [reagent "0.7.0"] [ring-webjars "0.2.0"] [ring/ring-core "1.6.3"] [ring/ring-defaults "0.3.1"] [secretary "1.2.3"] [selmer "1.11.7"] [com.arangodb/arangodb-java-driver "4.3.4"] [day8.re-frame/http-fx "0.1.6"] [com.draines/postal "2.0.2"]]
At the end this the only working part right now ^ ^
It's just the beginning, and i hope i can end up with something that works (maybe few months later), and your help will be highly appreciated after two months or so, until i finish the backbone of the project and clean it up.
Finally, this is the project repository on Github : O2SN
Posted on May 14 '18 by:
Discussion
Why not simply mark the story as annotated by a person and let the viewers decide for themselves the value it has, based or the reported situation of that person at that time?
(it sounds like a good use case for Datomic!)
i'm not sure i understand what do you mean by "annotated", as i said, every one can review a piece of news, however, the impact of each person on that piece of news won't be the same, and the purpose of that, is to reduce biases and the possibility of taking down a post just because people from another part of the world marked it as a lie.
well, i'm still trying to find the best way to do that.
I'm planning to save all the locations inside that database as a graph, so that the user can subscribe to locations as big as a country or as small as a city, do you think this can be done with Datomic ?!
What I wanted to say is basically that from people's perspective, there is no 'one truth'. By that, I mean that people's beliefs are in the general case always conflicting.
As soon as you design a system that is judging a story's credibility, you are dividing your audience between people who agree your system and people who don't.
Each person has his own weighted trust network, you can't go against that as trust is not something you can force onto people.
I was suggesting to keep the original story and attach additional information to it, and let people decide by themselves (knowing the full data) what credibility they give to a story marked by some as a lie and by others as a truth.
In other words, I was suggesting to keep your app's data immutable and append only - which is what Datomic (among other things) does.
i think you've got a point, i will take that into consideration, thank you very much ^ | https://practicaldev-herokuapp-com.global.ssl.fastly.net/elarouss/a-beginners-journey-inside-the-clojureclojurescript-web-dev-ecosystem-1-2nm0 | CC-MAIN-2020-29 | refinedweb | 968 | 62.78 |
I have been trying to implement an event_detect for one of the ODROID C1.
The error I am getting is
Code: Select all
GPIO.add_event_detect(DRDY_pin, GPIO.FALLING, callback=acquisition) RuntimeError: Failed to add edge detection
Code: Select all
import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.cleanup() GPIO.setmode(GPIO.BCM) # Numbers GPIOs by chip numbering scheme DRDY_pin = 23 #PIN 16 of the ODROID GPIO.setup(DRDY_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set LedPin's mode is output def acquisition(channel): n = 8 bits = 24 received = spi.read(24+n*bits) # Read 24 bits status word + nrChanels*24bits print received GPIO.add_event_detect(DRDY_pin, GPIO.FALLING, callback=acquisition)
I have tried a bunch of things but so far nothing worked.
If someone can help me it would be great!
Best,
Sofia | https://forum.odroid.com/viewtopic.php?t=35250&p=258284 | CC-MAIN-2019-26 | refinedweb | 132 | 51.14 |
import "go.chromium.org/luci/client/archiver"
Package archiver implements the pipeline to efficiently archive file sets to an isolated server as fast as possible.
archiver.go checker.go directory.go doc.go tar_archiver.go tarring_archiver.go upload_tracker.go uploader.go
Archiver is an high level interface to an isolatedclient.Client.
Uses a 4 stages pipeline, each doing work concurrently:
- Deduplicating similar requests or known server hot cache hits. - Hashing files. - Batched cache hit lookups on the server. - Uploading cache misses.
New returns a thread-safe Archiver instance.
If not nil, out will contain tty-oriented progress information.
ctx will be used for logging.
Cancel implements common.Canceler
CancelationReason implements common.Canceler
Channel implements common.Canceler
Close waits for all pending files to be done. If an error occured during processing, it is returned.
func (a *Archiver) Push(displayName string, source isolatedclient.Source, priority int64) *PendingItem
Push schedules item upload to the isolate server. Smaller priority value means earlier processing.
func (a *Archiver) PushFile(displayName, path string, priority int64) *PendingItem
PushFile schedules file upload to the isolate server. Smaller priority value means earlier processing.
Stats returns a copy of the statistics.
type BundlingChecker struct { Hit, Miss CountBytes // contains filtered or unexported fields }
BundlingChecker uses the isolatedclient.Client to check whether items are available on the server. BundlingChecker methods are safe to call concurrently.
func NewChecker(ctx context.Context, client *isolatedclient.Client, maxConcurrent int) *BundlingChecker
NewChecker creates a new Checker with the given isolated client. maxConcurrent controls maximum number of check requests to be in-flight at once. The provided context is used to make all requests to the isolate server.
func (c *BundlingChecker) AddItem(item *Item, isolated bool, callback CheckerCallback)
AddItem adds the given item to the checker for testing, and invokes the provided callback asynchronously. The isolated param indicates whether the given item represents a JSON isolated manifest (as opposed to a regular file). In the case of an error, the callback may never be invoked.
func (c *BundlingChecker) Close() error
Close shuts down the checker, blocking until all pending items have been checked with the server. Close returns the first error encountered during the checking process, if any. After Close has returned, Checker is guaranteed to no longer invoke any previously-provided callback.
func (c *BundlingChecker) PresumeExists(item *Item)
PresumeExists causes the Checker to report that item exists on the server.
type Checker interface { AddItem(item *Item, isolated bool, callback CheckerCallback) PresumeExists(item *Item) Close() error }
A Checker checks whether items are available on the server. It has a single implementation, *BundlingChecker. See BundlingChecker for method documentation.
type CheckerCallback func(*Item, *isolatedclient.PushState)
CheckerCallback is the callback used by Checker to indicate whether a file is present on the isolate server. If the item not present, the callback will be include the PushState necessary to upload it. Otherwise, the PushState will be nil.
ConcurrentUploader uses an isolatedclient.Client to upload items to the server. All methods are safe for concurrent use.
func NewUploader(ctx context.Context, client *isolatedclient.Client, maxConcurrent int) *ConcurrentUploader
NewUploader creates a new ConcurrentUploader with the given isolated client. maxConcurrent controls maximum number of uploads to be in-flight at once. The provided context is used to make all requests to the isolate server.
func (u *ConcurrentUploader) Close() error
Close waits for any pending uploads (and associated done callbacks) to complete, and returns the first encountered error if any. Uploader cannot be used once it is closed.
func (u *ConcurrentUploader) Upload(name string, src isolatedclient.Source, ps *isolatedclient.PushState, done func())
Upload uploads an item from an isolated.Source. Upload does not block. If not-nil, the done func will be invoked on upload completion (both success and failure).
func (u *ConcurrentUploader) UploadBytes(name string, b []byte, ps *isolatedclient.PushState, done func())
UploadBytes uploads an item held in-memory. UploadBytes does not block. If not-nil, the done func will be invoked on upload completion (both success and failure). The provided byte slice b must not be modified until the upload is completed. TODO(djd): Consider using Upload directly and deleting UploadBytes.
func (u *ConcurrentUploader) UploadFile(item *Item, ps *isolatedclient.PushState, done func())
UploadFile uploads a file from disk. UploadFile does not block. If not-nil, the done func will be invoked on upload completion (both success and failure). TODO(djd): Consider using Upload directly and deleting UploadFile.
CountBytes aggregates a count of files and the number of bytes in them.
func (cb *CountBytes) Bytes() int64
Bytes returns total byte count.
func (cb *CountBytes) Count() int
Count returns the file count.
type IsolatedSummary struct { // Name is the base name an isolated file with any extension stripped Name string Digest isolated.HexDigest }
IsolatedSummary contains an isolate name and its digest.
type Item struct { Path string RelPath string Size int64 Mode os.FileMode Digest isolated.HexDigest }
Item represents a file or symlink referenced by an isolate file.
type PendingItem struct { // Immutable. DisplayName string // Name to use to qualify this item // contains filtered or unexported fields }
PendingItem is an item being processed.
It is caried over from pipeline stage to stage to do processing on it.
PushDirectory walks a directory at root and creates a .isolated file.
It walks the directories synchronously, then returns a *PendingItem to signal when the background work is completed. The PendingItem is signaled once all files are hashed. In particular, the *PendingItem is signaled before server side cache lookups and upload is completed. Use archiver.Close() to wait for completion.
relDir is a relative directory to offset relative paths against in the generated .isolated file.
blacklist is a list of globs of files to ignore.
func (i *PendingItem) Digest() isolated.HexDigest
Digest returns the calculated digest once calculated, empty otherwise.
func (i *PendingItem) Error() error
Error returns any error that occurred for this item if any.
func (i *PendingItem) SetErr(err error)
SetErr forcibly set an item as failed. Normally not used by callers.
func (i *PendingItem) WaitForHashed()
WaitForHashed hangs until the item hash is known.
type Stats struct { Hits []units.Size // Bytes; each item is immutable. Pushed []*UploadStat // Misses; each item is immutable. }
Stats is statistics from the Archiver.
TotalBytesHits is the number of bytes not uploaded due to cache hits on the server.
TotalBytesPushed returns the sum of bytes uploaded.
TotalHits is the number of cache hits on the server.
TotalMisses returns the number of cache misses on the server.
TarringArchiver archives the files specified by an isolate file to the server, Small files are combining into tar archives before uploading.
func NewTarringArchiver(checker Checker, uploader Uploader) *TarringArchiver
NewTarringArchiver constructs a TarringArchiver.
func (ta *TarringArchiver) Archive(deps []string, rootDir string, isol *isolated.Isolated, blacklist []string, isolated string) (IsolatedSummary, error)
Archive uploads a single isolate.
UploadStat is the statistic for a single upload.
UploadTracker uploads and keeps track of files.
NewUploadTracker constructs an UploadTracker. It tracks uploaded files in isol.Files.
func (ut *UploadTracker) Files() map[string]isolated.File
Files returns the files which have been uploaded. Note: files may not have completed uploading until the tracker's Checker and Uploader have been closed.
func (ut *UploadTracker) Finalize(isolatedPath string) (IsolatedSummary, error)
Finalize creates and uploads the isolate JSON at the isolatePath, and closes the checker and uploader. It returns the isolate name and digest. Finalize should only be called after UploadDeps.
func (ut *UploadTracker) UploadDeps(parts partitionedDeps) error
UploadDeps uploads all of the items in parts.
type Uploader interface { Close() error Upload(name string, src isolatedclient.Source, ps *isolatedclient.PushState, done func()) UploadBytes(name string, b []byte, ps *isolatedclient.PushState, done func()) UploadFile(item *Item, ps *isolatedclient.PushState, done func()) }
Uploader uploads items to the server. It has a single implementation, *ConcurrentUploader. See ConcurrentUploader for method documentation.
Package archiver imports 28 packages (graph) and is imported by 9 packages. Updated 2018-08-14. Refresh now. Tools for package owners. | https://godoc.org/go.chromium.org/luci/client/archiver | CC-MAIN-2018-34 | refinedweb | 1,298 | 52.97 |
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
After some time brewing on my machines, I’m happy to have released a new version of my permute package for R. This release took quite a while to polish and get right as there was a lot of back-and-forth between vegan and permute as I tried to get the latter working nicely for both useRs and developers, whilst Jari worked on using the new permute API within vegan itself. All these changes were prompted by Cajo ter Braak taking me to task (nicely of course) over the use in previous versions of permute of the term “blocks” for what were not true blocking factors. Cajo challenged me to add true blocking factors (these restrict permutations within their levels and are never permuted, unlike plots), and the new version of permute is the result of my attempting to meet that challenge.
The changes to the design of permutations meant that I had to break code that used previous versions of permute and wasn’t something I did lightly. But it did need to be done. I took that opportunity to make the package easier to use too and decided I didn’t like typing
permControl() each time I wanted to define a permutation design, resulting in the new
how().
Version 0.8-0 represents a major update to permute, the salient details of which are given below, cropped from the new
NEWS.Rd file. You can get the new version of permute now from CRAN.
General
Version 0.8-0 represents a major update of permute, with some backwards-incompatible changes to the main functions. The main addition is the availability of block-level restrictions on the permutations, which are required for whole- and split-plot designs.
New Features
how(), a new function to create permutation designs. This replaces the deprecated function
permControl().
permute gains the addition of true blocking structures with which to restrict the permutations. Blocks sit as the outermost layer of the permutations, and can contain plots which in turn contain samples. In contrasts to plots, blocks are never permuted and samples are never shuffled between blocks. Permutation only ever happens within blocks.
To facilitate this, plot-level strata are now specified via
Plots()instead of via the old
strataargument of
how(). Blocks are specified via a new argument
blocks, which takes a factor variable.
A new suite of extractor and replacement functions is provided with which to interact with permutation designs created by
how(). Extractor functions have names
getFoo(), where
Foois a component of the design. Replacement functions have names
setFoo. The replacement function are especially for use by package authors wishing to alter permutation within their functions. The extractor functions are recommended for all users wishing to extract features of the permutation design.
As a convenience for users, the
update()function will now work with objects of classes
“how”,
“Plots”or
“Within”to allow quick updating of features of the permutation design. This approach is intended for interactive use at the top-level and not within functions, where the new
setFooreplacement functions should be used.
shuffleSet()is enhanced in this version. Firstly, the function now returns a classed object which has a
print()method to allow for compact printing of the design elements used to generate the set of permutations. Second,
shuffleSet()will sample
nsetpermutations from the entire set of permutations should a small number of possible permutations trigger generation of the entire set. This avoids the generation of a set of non-unique permutations. Finally the random seed that generated the set is stored as an attribute.
allPerms()no longer assumes that samples are in block and/or plot ordering.
The package vignette is much expanded in this version with new sections on using permute within functions that will be of interest to package authors wishing to use permute in their packages.
Deprecated
permControl()is deprecated in favour of
how().
permuplot()is broken and effectively defunct given the changes to the way permutation are defined and the addition of blocks.
permuplotis no longer exported from the package namespace.. | https://www.r-bloggers.com/new-version-of-permute-on-cran/ | CC-MAIN-2020-05 | refinedweb | 697 | 54.12 |
Auk, an image slideshow for iOS / Swift
This is an iOS library that shows an image carousel with a page indicator. Users can scroll through local and remote images or watch them scroll automatically.
scrollView.auk.show(url: "") scrollView.auk.show(url: "") if let image = UIImage(named: "local_bird.jpg") { scrollView.auk.show(image: image) }
- Uses Auto Layout and supports animated transition during screen orientation change.
- Allows to specify placeholder and error images for remote sources.
- Includes caching and logging for remote images.
- Supports right-to-left languages.
- Allows to specify accessiblity labels for the images.
- Includes ability to simulate and verify image download in unit tests.
Drawing of the great auk by John Gerrard Keulemans, circa 1900. Source: Wikimedia Commons.
Setup
There are multiple ways you can add Auk to your Xcode project.
Add source (iOS 7+)
Simply add two files to your project:
- Moa image downloader MoaDistrib.swift.
- Auk image slideshow AukDistrib.swift.
Setup with Carthage (iOS 8+)
- Add
github "evgenyneu/Auk" ~> 10.0to your Cartfile.
- Run
carthage update.
- Add
moaand
Aukframeworks into your project.
Setup with CocoaPods (iOS 8+)
If you are using CocoaPods add this text to your Podfile and run
pod install.
use_frameworks! target 'Your target name' pod 'moa', '~> 11.0' pod 'Auk', '~> 10.0'
Setup with Swift Package Manager
- In Xcode 11+ select File > Packages > Add Package Dependency....
- Enter moa project's URL (image downloader dependency):
- Repeat for Auk URL:
Legacy Swift versions
Setup a previous version of the library if you use an older version of Swift.
Usage
- Add
import Aukto your source code ((unless you used the file setup method)).
- Add a scroll view to the storyboard and create an outlet property
scrollViewin your view controller.
- Clear the Adjust Scroll View Insets checkbox in the Attribute Inspector of your view controller.
Auk extends UIScrollView class by creating the
auk property.
// Show remote images scrollView.auk.show(url: "") scrollView.auk.show(url: "") // Show local image if let image = UIImage(named: "bird.jpg") { scrollView.auk.show(image: image) } // Return the number of pages in the scroll view scrollView.auk.numberOfPages // Get the index of the current page or nil if there are no pages scrollView.auk.currentPageIndex // Return currently displayed images scrollView.auk.images
Scrolling from code
// Scroll to page scrollView.auk.scrollToPage(atIndex: 2, animated: true) // Scroll to the next page scrollView.auk.scrollToNextPage() // Scroll to the previous page scrollView.auk.scrollToPreviousPage()
Auto scrolling
// Scroll images automatically with the interval of 3 seconds scrollView.auk.startAutoScroll(delaySeconds: 3) // Stop auto-scrolling of the images scrollView.auk.stopAutoScroll()
Note that auto scrolling stops when the user starts scrolling manually.
Accessibility
One can pass an image description when calling the
show methods. This description will be spoken by the device in accessibility mode for the current image on screen.
// Supply accessibility label for the image scrollView.auk.show(url: "", accessibilityLabel: "Picture of a great auk.")
Removing pages
// Remove a page at given index scrollView.auk.removePage(atIndex: 0, animated: true, completion: {}) // Remove the currently shown page scrollView.auk.removeCurrentPage(animated: true, completion: {}) // Remove all pages scrollView.auk.removeAll()
Updating pages
One can change existing image by calling
updateAt methods and supplying the page index.
// Replace the image on a given page with a remote image. // The current image is replaced after the new image has finished downloading. scrollView.auk.updatePage(atIndex: 0, url: "") // Replace the image on a given page with a local image. if let image = UIImage(named: "bird.jpg") { scrollView.auk.updatePage(atIndex: 1, image: image) }
If your remote image URLs are not https you will need to add an exception to the Info.plist file. This will allow the App Transport Security to load the images from insecure HTTP hosts.
Configuration
Use the
auk.settings property to configure behavior and appearance of the scroll view before showing the images. See the configuration manual for the complete list of configuration options.
// Make the images fill entire page scrollView.auk.settings.contentMode = .scaleAspectFill // Set background color of page indicator scrollView.auk.settings.pageControl.backgroundColor = UIColor.gray.withAlphaComponent(0.3) // Show placeholder image while remote image is being downloaded. scrollView.auk.settings.placeholderImage = UIImage(named: "placeholder.jpg") // Show an image AFTER specifying the settings scrollView.auk.show(url: "")
Preloading remote images
By default remote images are loaded after they become visible to user. One can ask the library to preload remote images by setting the property
preloadRemoteImagesAround.
// Set the property before showing remote images scrollView.auk.settings.preloadRemoteImagesAround = 1 // Add remote images. The first two images will start loading simultaneously. scrollView.auk.show(url: "") scrollView.auk.show(url: "") // The third image will start loading when the user scrolls to the second page. scrollView.auk.show(url: "")
The
preloadRemoteImagesAround property defines the number of remote images to preload around the current page. For example, if
preloadRemoteImagesAround = 2 and we are viewing the first page it will preload images on the second and third pages. If we are viewing 5th page then it will preload images on pages 3, 4, 6 and 7 (unless they are already loaded). The default value is 0.
Note that images are loaded all at the same time, therefore, using large values for
preloadRemoteImagesAround may result in the first image being delayed on slow networks because the limited bandwidth will be shared by many image downloads.
Size change animation
Read size animation manual if you need to animate the scroll view during device orientation change.
Image caching
Auk uses moa image downloader for getting remote images. You can configure its caching settings by changing the
Moa.settings.cache.requestCachePolicy property. Add
import moa to your source code if you used Carthage or CocoaPods setup methods.
import moa // for Carthage and CocoaPods // ... // By default images are cached according to their response HTTP headers. Moa.settings.cache.requestCachePolicy = .useProtocolCachePolicy // Use local cache regardless of response HTTP headers. Moa.settings.cache.requestCachePolicy = .returnCacheDataElseLoad
Note: moa image downloader offers other features including request logging and HTTP settings.
Logging
If you want to know when the remote images are being loaded you can log the network activity to console, as shown in the following example. Please refer to the moa logging manual for more information.
import moa // for Carthage and CocoaPods // ... // Log to console Moa.logger = MoaConsoleLogger // Show an existing image scrollView.auk.show(url: "") // Attempt to show a missing image scrollView.auk.show(url: "")
Remote image unit testing
One can simulate and verify remote image download in your unit tests. Please refer to the moa unit testing manual for more information. Add
import moa to your source code if you used Carthage or CocoaPods setup methods.
// Autorespond with the given image MoaSimulator.autorespondWithImage("", image: UIImage(named: "35px.jpg")!)
Respond to image tap
Here is what you need to do to add an image tap handler to the scroll view.
- In the Storyboard drag a Tap Gesture Recognizer into your scroll view.
- Show assistant editor with your view controller code.
- Do the control-drag from the tap gesture recognizer in the storyboard into your view controller code.
- A dialog will appear, change the Connection to action and enter the name of the method.
- This method will be called when the scroll view is tapped. Use the
auk.currentPageIndexproperty of your scroll view to get the index of the current page.
Detect page scrolling
You can run some code when the scroll view is being scrolled by using
UIScrollViewDelegate. See the detect page scrolling manual for details.
Using Auk from Objective-C
This manual describes how to use Auk in Objective-C apps.
Common problems
Page control is not visible
Make sure the scrollView is added to the view tree before you call the
show method. Otherwise the page control will not be created. Quick check:
print(scrollView.superview) // should not be `nil` scrollView.auk.show(url: "")
The page control is added to the superview of the scroll view when the
show method is called. That's why page control is not created when the scroll view has no superview.
If
scrollView.superview is
nil then you may need to move that code that shows the images to the
viewDidAppear method.
Remote images are not loading
One can turn on the logger to see the network activity in the Xcode console and find the problem with image download.
Page control is not changing / second remote image is not shown
If you are assigning the scroll view delegate please make sure it is done before showing the images.
// Assign the delegate BEFORE showing the images scrollView.delegate = self scrollView.auk.show(url: "") scrollView.auk.show(url: "")
Demo app
The project includes a demo iOS app.
Alternative solutions
Here is a list of other image slideshow libraries for iOS.
- kimar/KIImagePager
- kirualex/KASlideShow
- nicklockwood/iCarousel
- nicklockwood/SwipeView
- paritsohraval100/PJR-ScrollView-Slider
- zvonicek/ImageSlideshow
Thanks 👍
Image credits
- The Great Auk drawing by John James Audubon, 1827-1838. Source: Wikimedia Commons.
- Great auk with juvenile drawing by John Gerrard Keulemans, circa 1900. Source: Wikimedia Commons.
- The Great Auk drawing from Popular Science Monthly Volume 62, 1902-1903. Source: Wikimedia Commons.
- Great Auk egg, U. S. National Museum, in a book by Arthur Cleveland Bent, 1919. Source: Wikimedia Commons.
- Only known illustration of a Great Auk frawn from life by Olaus Wormius, 1655. Source: Wikimedia Commons.
- The Great Auks at Home, oil on canvas by John Gerrard Keulemans. Source: Wikimedia Commons.
- Alca impennis by John Gould: The Birds of Europe, vol. 5 pl. 55, 19th century. Source: Wikimedia Commons.
- Great Auks in summer and winter plumage by John Gerrard Keulemans, before 1912. Source: Wikimedia Commons.
License
Auk is released under the MIT License.
Feedback is welcome
If you notice any issue, got stuck or just want to chat feel free to create an issue. I will be happy to help you.
•ᴥ•
This code is dedicated to the great auk, a flightless bird that became extinct in the mid-19th century.
Github
Help us keep the lights on
Dependencies
Used By
Total: 0 | https://swiftpack.co/package/evgenyneu/Auk | CC-MAIN-2019-43 | refinedweb | 1,659 | 60.31 |
I am trying to get a program I wrote to work but I am having a problem. The program is supposed to make use of multiple levels of indirection so that I can get more familiar and comfortable with pointers, but when I run it I get the error: "Debug Assertion Failed! Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse).
The program is supposed to take a file, read the input from it into an array and a vector, then output the data. The vector is to be accessed by a pointer to a pointer to a pointer to the vector, and the array by a pointer to a pointer to the array.
Here is part of the program; I am fairly certain that the error is in here. The rest just outputs the data and deletes the dynamic memory. I may be doing the dereferencing incorrectly at some point; I'm not sure. If someone could take a look and point me in the right direction, that'd be great.
Code:#include <iostream> #include <fstream> #include <vector> #include <string> #include <new> using namespace std; bool readInput(vector<string>***, string**, int); bool allocateArray(string**, int&, int); int main() { vector<string>*** p = new vector<string>**; //Defines the pointers to the vector *p = new vector<string>*; string** r = new string*; //Defines the pointers to the array int size = 10; //For the array size bool flag = true; flag = readInput(p, r, size); //The rest is omitted } // Defines the vector, calls the allocateArray function, and puts the data //into the vector and array. bool readInput(vector<string>*** vec, string** arr, int s) { bool flag = true; int count = 0; ifstream inFile; string name, input; inFile.open("TopicAin.txt"); while (!inFile) { cout << "Please enter a valid file name" << endl; cin >> name; inFile.open(name); } **vec = new vector<string>; //Define the vector flag = allocateArray(arr, s, count); //Define the array if (!flag) { cout << "Error allocating array." << cout; return false; } while(!(inFile.eof())) { inFile >> input; (***vec).push_back(input); //Put the word into the vector if (count == s) //Call the allocateArray function if the array is full { flag = allocateArray(arr, s, count); if (!flag) { cout << "Error allocating array." << cout; return false; } } *((*arr) + count) = input; //Put the word into the array count++; } if(inFile.fail()) flag = false; inFile.close(); //Close the file return flag; } //Allocates the array and reallocates it as necessary bool allocateArray(string** arr, int &size, int count) { if (count == 0) //Runs the first time through { *arr = new (nothrow) string[size]; if (*arr == 0) //Tests if the allocation was successful return false; else return true; } if (count != 0) //Runs every time after the first { string *ptr = new string[size]; for (int i = 0; i < size; i++) //Allocates a new array to hold the current words ptr[i] = *((*arr) + i); delete *arr; size *= 2; *arr = new string[size]; //Allocates a new array double the size of the old one for (int i = 0; i < (size/2); i++) //Puts the words back into the array *((*arr) + i) = ptr[i]; delete ptr; } if (*arr == 0) //Tests if allocation was successful return false; else return true; } | http://cboard.cprogramming.com/cplusplus-programming/134217-debug-assertion-failed.html | CC-MAIN-2015-35 | refinedweb | 510 | 65.46 |
Let's see how to get started and work with them.
# (don't forget to first have Python headers installed, e.g. apt-get install python-dev on Debian)
$ virtualenv test
Running virtualenv with interpreter /usr/bin/python2
New python executable in /home/test/test/bin/python2
Also creating executable in /home/test/test/bin/python
Installing setuptools, pkg_resources, pip, wheel...done.
$ . test/bin/activate
# install ZODB + wendelin.core
(test) $ pip install 'ZODB<5.0.0dev' wendelin.core
Collecting wendelin.core
Downloading wendelin.core-0.6.tar.gz (2.6MB)
100% |████████████████████████████████| 2.6MB 287kB/s
Collecting numpy (from wendelin.core)
Downloading numpy-1.11.0-cp27-cp27mu-manylinux1_x86_64.whl (15.3MB)
100% |████████████████████████████████| 15.3MB 47kB/s
Collecting ZODB3>=3.10 (from wendelin.core)
Downloading ZODB3-3.11.0.tar.gz (55kB)
100% |████████████████████████████████| 61kB 5.2MB/s
...
Successfully installed BTrees-4.3.1 ZConfig-3.1.0 ZEO-4.2.0b1 ZODB-4.3.1 ZODB3-3.11.0
numpy-1.11.0 persistent-4.2.1 psutil-4.2.0 six-1.10.0 transaction-1.6.1 wendelin.core-0.6
zc.lockfile-1.2.0 zdaemon-4.1.0 zodbpickle-0.6.0 zope.interface-4.2.0
(test) $ pip install ipython # for interactive testing
Now all is installed and we are ready to play.
$]: <wendelin.bigarray.array_zodb.ZBigArray at 0x7fcd7dcea5d0>
In [9]: a = A[:]
In [10]: a
Out[10]: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
In [11]: type(a)
Out[11]: numpy.ndarray
So we initialized test.fs ZODB database and setup top-level object in it
keyed A to be a ZBigArray instance. We can see in [10] a is
numpy.ndarray view of A, which is initially all zeros.
In [12]: a[:] = np.arange(10)
In [12]: a[7] = 22
In [13]: a
Out[13]: array([0, 1, 2, 3, 4, 5, 6, 22, 8, 9])
In [14]: transaction.commit()
In [15]: dbclose(root)
In [16]: exit
(test) $
$ ipython
# imports as [1-4] in previous session
In [1]: from wendelin.bigarray.array_zodb import ZBigArray
In [2]: from wendelin.lib.zodb import dbopen, dbclose
In [3]: import transaction
In [4]: import numpy as np
In [5]: root = dbopen('test.fs')
In [6]: A = root['A']
In [7]: A
Out[7]: <wendelin.bigarray.array_zodb.ZBigArray at 0x7f313416b150>
In [8]: a = A[:] # notice the data is the same as we set it above
In [9]: a
Out[9]: array([ 0, 1, 2, 3, 4, 5, 6, 22, 8, 9])
In [10]: type(a)
Out[10]: numpy.ndarray
In [11]: np.mean(a)
Out[11]: 6.0
Notice, above we call C-function mean() implemented in NumPy library. It does
not know it works on a ZBigArray data - all it sees is regular
numpy.ndarray object with memory.
# in another terminal
$ cat myeven.pyx
cimport numpy as np
def counteven(np.ndarray[np.int_t, ndim=1] a):
cdef int n = a.shape[0]
cdef int i, neven=0
i = 0
while i < n:
if a[i] % 2 == 0:
neven += 1
i += 1
return neven
$ cat setup.py
from numpy.distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize("myeven.pyx"))
$ pip install cython
$ python setup.py build_ext -i
running build_ext
building 'myeven' extension
... myeven.so extension is built
now back to ipython session:
In [12]: from myeven import counteven
# verify counteven() accepts only ndarrays
In [13]: counteven([1, 2, 3])
...
TypeError: Argument 'a' has incorrect type (expected numpy.ndarray, got list)
# verify counteven() accepts only ndarrays with dtype numpy.int
In [14]: counteven(np.arange(2, dtype=np.int16))
...
ValueError: Buffer dtype mismatch, expected 'int_t' but got 'short'
In [15]: counteven(np.arange(2, dtype=np.int))
Out[15]: 1
# call counteven() on ZBigArray data - it works correctly
In [16]: counteven(a)
Out[16]: 6
First of all, before doing computations on arrays bigger than RAM, we should be
able to somehow produce them. Wendelin.core allows both
in all cases the amount of modifications to array's data in one transaction
have to be less than available RAM. The strategy to ingest data into an array
is thus to do so in parts.
For reading, on the other hand, the amount of data which can be read in one
transaction is limited only by virtual address-space size, which is ~ 127TB on
Linux/amd64.
In [17]: for i in range(4):
....: A.append( np.arange(4*1024*1024) )
....: transaction.commit()
In [18]: A.shape
Out[18]: (16777226,)
In [19]: A[:]
Out[19]: array([ 0, 1, 2, ..., 4194301, 4194302, 4194303])
Doing enough such iterations we can eventually get to array whose size is
bigger than local RAM.
Notice: contrary to NumPy, where numpy.append() works by copying data to newly
allocated array (thus working in O(len(array) + δ) time), ZBigArray objects
can be appended in-place without copying, thus ZBigArray.append() works
in O(δ) time.
In [20]: a = A[:]
In [21]: np.mean(a)
Out[21]: # works -> some value depending on size of A
In [22]: counteven(a)
Out[22]: # works -> some value depending on size of A
When, for example np.mean(a) runs,
the system will be loading array parts from database and reclaiming
least-recently-accessed memory pages for new accesses when the amount of loaded data
is close to amount of local RAM. All this happens transparent to client code,
so it thinks it just accesses plain memory.
In the previous section we already saw how to work with arrays bigger than local
RAM by using ZODB database located on local disk. Going beyond local disk is
possible by using distributed ZODB storage which shards data in a cluster of
nodes.
In [5]: root = dbopen('neo://dbname@master')
And install NEO client library (via pip install neoppod[client]).
The system will be then reading and writing data from/to networked distributed
database, which scales in size the more storage nodes we add to its cluster.
Full cluster setup is documented in NEO readme.
One can setup a simple NEO cluster to play with neosimple command (after pip install neoppod).
wendelin.core is Free Software; The project home page is here: | https://www.erp5.com/latest/wendelin-Front.Page/wendelin-Core.Tutorial.2016 | CC-MAIN-2019-30 | refinedweb | 1,025 | 59.7 |
Java example for Reading file into byte array. You can then process the byte array as per your business needs.
This example shows you how to write a program in Java for reading file into byte array. Sometimes it becomes necessary to read a file into byte array for certain type of business processing. This Java code example explains the process of reading file into byte array.
In this example we will use the java.io.InputStream class which provides the methods for reading from the input stream. The java.io.InputStream class provides the following methods which is useful in reading the file into byte arry.
Methods of java.io.InputStream class:
available()
This method returns the number of bytes which can be read.
This method is used to close the input stream and releases all the system resources associated with it.
mark(int readlimit)
You can use this method to mark the current position in the associated input stream.
markSupported()
This method is used to find if the stream supports the mark and reset methods. So, you can find out if your stream supports mark and reset or not.
read()
This method is used to read the data from input stream into byte array.
read(byte[] b)
This method is used to read bytes from the input stream. It then stores into the buffer array b.
read(byte[] b, int off, int len)
This method is used to read up to len bytes of data. It reads the data from input stream and then stores into an array of bytes.
reset()
This method is used to reset the position to the mark which was set earlier.
skip(long n)
This method is used to skip over the n bytes from the input stream while reading.
Example code of reading file stream into byte array:
In our example are using java.io.InputStream class discussed above. Here is the complete code of the program:
import java.io.*; /** * This class shows you how to read * file content into byte array */ public class ReadFileIntoByteArray { public static void main(String[] args) { System.out.println("Example of Reading file into byte array"); try{ //Instantiate the file object File file = new File("test.text"); //Instantiate the input stread InputStream insputStream = new FileInputStream(file); long length = file.length(); byte[] bytes = new byte[(int) length]; int offset = 0, n = 0; //Read the data into bytes array while (offset < bytes.length && (n = insputStream.read(bytes, offset, bytes.length - offset)) >= 0) { offset += n; } insputStream.close(); String s = new String(bytes); System.out.println(s); }catch(Exception e){ System.out.println("Error is:" + e.getMessage()); } } }
Other examples of reading file into byte array:
Read more at Java File - Example and Tutorials.
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial
Discuss: Java example for Reading file into byte array
Post your Comment | http://www.roseindia.net/java/javafile/java-read-file-into-byte-array.shtml | CC-MAIN-2015-06 | refinedweb | 486 | 67.96 |
how to make rospy.Subscriber("/camera/rgb/image_raw", Image, image_callback) work?
I tried to change this code here using ROS but I can't.
it is working without ros.
I only modified this code:
(more)(more)
import rospy from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError import numpy as np import cv2 import os import threading import time import sys from Tkinter import * # Library for slider widgets import tkFileDialog from PIL import Image from PIL import ImageTk from imutils.video import FPS import time bridge = CvBridge() _current_image = None def image_callback(ros_image): global _current_image _current_image = ros_image def start_video(): global videostarted, stopEvent, cap, thread global bridge , _current_image if _current_image is not None: try: aa = bridge.imgmsg_to_cv2(_current_image, "bgr8") except CvBridgeError as e: print(e) # Create video camera object and start streaming to it. # cap = cv2.VideoCapture(0) # 0 == Continuous cap = aa fps = FPS().start() # The video_image loop must use tkinter threading or the sliders # won't work, so this sets up threading before calling video_image() if videostarted == False: videostarted = True stopEvent=threading.Event() thread=threading.Thread(target=video_image,args=()) thread.start() else: print "Video already running" def video_image(): # grab a reference to the image panels global panelV1 try: while not stopEvent.is_set(): # Capture a still image from the video stream ret, frame = cap.read() # Read a new frame frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5) ''' Keep for debug ''' # Canny test code, only called w/ imshow() below #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #edged = cv2.Canny(gray, 50, 100) # Convert image to HSV hsvframe = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # Set up the min and max HSV settings lower=np.array([barH.get(),barS.get(),barV.get()]) upper=np.array([barH2.get(),barS2.get(),barV2.get()]) mask=cv2.inRange(hsvframe, lower, upper) mask=Image.fromarray(mask) mask=ImageTk.PhotoImage(mask) ''' Keep for debug ''' #cv2.imshow("Original",frame) #cv2.imshow("Edged",edged) #cv2.imshow("HSV",hsvframe) #cv2.imshow("Mask", mask) # convert the images to PIL format... #pilframe=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) #pilframe=Image.fromarray(pilframe) #pilframe=ImageTk.PhotoImage(pilframe) #If the panels are None, initialize them if panelV1 is None: print "enter panelV1 None" # the first panel will store our original image panelV1 = Label(master,image=mask) panelV1.image = mask #panelV1.pack(side="right", padx=10,pady=10) panelV1.pack() # otherwise, update the image panels else: # update the panels #print "enter panelV1 update" panelV1.configure(image=mask) panelV1.image = mask panelV1.pack() ch=cv2.waitKey(10) # 1 == capture every 10 millisec if ch & 0xFF == ord('q'): # "q" to exit loop break # Required to release the device and prevent having to reset system cap.release() cv2.destroyAllWindows() print "exit video_image()" except RuntimeError, e: print "runtime error()" def slider_init(): global barH, barH2, barS, barS2, barV, barV2 ''' Set up sliders ''' #H value barH = Scale(master, from_=0, to=255, orient=HORIZONTAL, label="H min", length=600, tickinterval=128) barH.set(30) barH.pack() barH2 = Scale(master, from_=0, to=255, orient=HORIZONTAL, label="H max", length=600, tickinterval=128) barH2.set(250) barH2.pack() #S value barS ...
It would be helpful if you could add what commands you tried to run, what the output was (especially any errors), and what you mean when you say it's not working?
@ Thomas D, there are not any errors but I can't see the video when use the
cv_bridge. So, I asked here, I don't know the reason, you can download the original code, then run it. there is not an error in both original and modified code.
What commands are you running? What is the output that makes you think something is not working? Do you have any publishers providing
/camera/rgb/image_raw? You can check that with
rostopic info /camera/rgb/image_raw.
@Thomas, thank you so much for your help. I used this subscriber
rospy.Subscriber("/camera/rgb/image_raw", Image, image_callback)
I think that it needs to use
class then definstead of
many def.
I skipped it and used another code for the same purpose. | https://answers.ros.org/question/336453/how-to-make-rospysubscribercamerargbimage_raw-image-image_callback-work/ | CC-MAIN-2019-51 | refinedweb | 671 | 50.53 |
.
Memory leaks are relatively easy to introduce into your programs when coding in C or C++ (no-one could have enjoyed having to write destructors for every single one of their C++ classes). However, when you code in a .NET language, such as C#, you are working in managed code, with automatic garbage collection, so memory management becomes a bit of a non-issue, right?
That certainly pretty much describes my mindset when I developed the brand new C# 2005 desktop version of my company's sales and CRM application. I was new to C#, and while I was aware that there could still be problems if references weren't cleaned up properly, I hadn't given memory management much thought during development. I certainly wasn't expecting it to be a major issue. As it turns out, I was wrong.
I knew I was in trouble the first time my customer called with specific memory use numbers from the Windows Task Manager. Jack is a salesperson by trade, but by volunteering to beta-test my new desktop application, he had unknowingly put himself in line for a crash course in memory leak awareness. "The memory is up to five hundred thousand K since restarting this morning", he said, "What should I do?"
It was a Friday afternoon and I was at an out of town wedding for the weekend. Jack had noticed this issue the day before and I had advised the temporary fix of close-out-and-come-back-in. Like all good beta testers he was happy to accept the temporary solution, but like all excellent beta testers he wasn't going to accept having to do a temporary fix over and over.
Jack wasn't even the heaviest user of the application and I knew that the installed memory of his machine was above average, so going live wouldn't be possible until I could trace and fix this leak. The problem was growing by the minute: the scheduled go-live date was Monday and I'd been on the road, so I hadn't been able to look through the code since the memory issue had arisen.
I got back home on Sunday evening and scoured the search engines, trying to learn the basics of C# memory management. My company's application was massive, though, and all I had was the Task Manager to tell me how much memory it was using at any given time.
Displaying an invoice seemed to be part of the problem; this was a process that involved a large number of different elements: one tab page, a usercontrol on the page, and about one hundred other controls within that usercontrol, including a complicated grid control derived from the .Net ListView that appeared on just about every screen in the application. Every time an invoice was displayed, the memory use would jump, but closing the tab wouldn't release the memory. I set up a test process to show and close 100 invoices in series and measure the average memory change. Oh no. It was losing at least 300k on each one.
By this point it was about 8pm on Sunday evening and needless to say, I was beginning to sweat. We HAD to go live the next day. We were already at the tail end of our original time estimate, other projects were building up, and the customer was already starting to question the wisdom of the entire re-design process. I was learning a lot about C#'s memory management, but nothing I did seemed to keep my application from continuing to balloon out of control.
At this point, I noticed a banner ad for ANTS Profiler, a memory profiler for .NET. I downloaded and installed the free trial, mentally composing the apologetic 'please give me a few more days' email I would need to write the next morning if I didn't find a resolution.
How ANTS worked was pretty clear as soon as I opened it. All it needed was the path to the . exe, after which it launched the system with memory monitoring turned on. I ran through the login process in my application, and then used the main feature in ANTS to take a 'snapshot' of the application's memory profile before any invoices or other screens had been shown.
Browsing that first profile snapshot, I was stunned at the amount of information available. I had been trying to pinpoint the problem using a single memory use number from the Task Manager, whereas now I had an instance-by-instance list of every live object my program was using. ANTS allowed me to sort the items by namespace (the .NET ones as well as my own), by class, by total memory use, by instance count, and anything else I could possibly want to know.
Armed with this information, I mentally put my apology email on hold, brought up my application, ran the process that displayed 100 invoices, and then took another snapshot. Back in ANTS, I checked the list for instances of the main invoice display usercontrol. There they were 100 instances of the control along with 100 instances of the tab and 100 instances of everything else, even though the tabs themselves had all been closed on the screen.
In my research I had learned that the .NET memory management model uses an instance's reference tree to determine whether or not to remove it. With a bit more clicking in ANTS, I found that it could show me all of the references both to and from every instance in my program.
Using ANTS to navigate forward and backward through the maze of linked references, I was quickly able to find a static ArrayList to which all displayed tabs were added, but from which they were never removed.
ArrayList
After adding a few lines of code to remove each tab from this collection as it was closed, I re-ran the profiler and the 100 invoice process and voilà; the tabs, the main usercontrol, and nearly all of the sub-controls were gone. It got even better too: the memory increase after each invoice was down to a fifth of what it had been, which changed the memory leak from a major concern down to a minor annoyance. The next day we went live, and although issues of all sizes arose, none of them was caused by the leak.
Later that week, however, Jack's calls resumed: "The memory is still slowly creeping up; what's going on?" I didn't know, but at least I knew where to look now. I used ANTS Profiler to see if I could locate the remaining leak. What I found was that one of the sub-controls of the main invoice usercontrol, the ListView-based one that formed a primary part of the interface, was being held in the reference tree by what appeared to be standard event handlers like OnClick and MouseMove, hooks that had been added using the Visual Studio IDE and that would have been, I thought, cleared automatically.
ListView
OnClick
MouseMove
This was really puzzling to me, and I wrote to Red Gate Software, the developers of the ANTS system, asking for some additional help. Their support staff promptly responded and explained that in situations with lots of complex references and event handlers, the .NET runtime can leave event handlers in place when they should be disposed. They suggested manually removing each handler in the Dispose method of the usercontrol that was causing the problem.
I added the 20 or so minus-equals statements to remove each handler, and for good measure, I added a System.GC.Collect() statement after the tab closing process.
System.GC.Collect()
Re-running the ANTS Profiler and the 100 invoice process, I found that the memory use remained rock solid. Then, when re-checking the ANTS Profiler snapshot, I could see that all of the invoice-related controls had been released, and the memory use numbers in the task manager never moved.
I re-compiled and uploaded the new version. Now it was my turn to call Jack.
What did I learn from all this? Firstly, that the "it's managed code so we don't have to worry about memory leaks" assumption falls short of the mark.
Although automatic memory management in .NET makes our lives as .NET developers a whole lot easier, it is still easy to introduce memory leaks into your application. Even in managed memory, there can be issues. The memory manager cannot free memory that is still 'live' – and it will still be considered live if it is referenced directly or indirectly through the "spider's web" of references that link the various objects. Also, when complex reference trees and event handlers are involved, the memory manager doesn't always deregister these event handlers, and so the memory will never be released unless you forcibly release it.
Secondly, I learned that tracking down these sorts of issues equipped only with Task Manager was simply not possible – certainly not in the timeframe I had. Tools such as Task Manager (and Performance Monitor) were able to tell me that my application was using up a lot of memory, but I needed a dedicated memory profiler like ANTS Profiler to really show me what objects made up that memory and why they were still there.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
mammorysam wrote:Sorry to be pedantic, but this is about memory management not leaks.
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/17628/Tracing-memory-leaks-in-NET-applications-with-ANTS?msg=4261386&PageFlow=FixedWidth | CC-MAIN-2015-35 | refinedweb | 1,632 | 66.17 |
How to convert a positive number into a Negative in Python
In this tutorial, I will teach you to convert positive numbers into negatives in Python. There are basically four ways to implement this thing. However, I will show the method which I use mostly to convert positive numbers to negative numbers.
Nowadays, Developers need to implement this type of mechanism into various applications especially gaming apps.
In Python, how do you turn a positive number into a negative number?
Let’s begin with the first method,
This method is the simplest method and developers use frequently to implement in the program.
for i in range(1,4): print(-abs(i))
Output:
-1 -2 -3
In this method, I have used -abs() method which converts 1 to 4 numbers into negative integers ( as you can see in output).
Second method,
This is also a well-known way but not used much but anyway let’s look at it
for i in range(1,10): i='-' + str(i).strip() print(i)
Output:
-1 -2 -3 -4 -5 -6 -7 -8 -9
Here, I have used strip() keyword to join converted (int to string) number to “-” sign.
Third method,
This method is logically good to implement
list=[1,2,3,4] for i in list: neg = i * (-1) print(neg)
Output:
-1 -2 -3 -4
Here, just simply I have multiplied the list of numbers with -1 so, it returns negative numbers at the end.
Fourth method,
This method is similar to the third one,
import random array1 = [] arrayLength = 4 for i in range(arrayLength): array1.append((random.randint(0, arrayLength)*-1)) print(array1)
Output:
[-4, 0, -3, -3]
However, this method is also good as it returns random values with a list of negative numbers. so, sometimes developers need to use such type of mechanism while developing applications/websites. | https://www.codespeedy.com/convert-a-positive-number-into-a-negative-in-python/ | CC-MAIN-2021-43 | refinedweb | 308 | 57.81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.