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
Date: Mon, 16 Aug 1999 23:29:48 -0700 (PDT) From: Linus Torvalds <torvalds@transmeta.com> To: Andrea Arcangeli <andrea@suse.de> Subject: Re: [bigmem-patch] 4GB with Linux on IA32 On Tue, 17 Aug 1999, Andrea Arcangeli wrote: > > This incremental (against bigmem-2.3.13-L) patch will fix the ptrace and > /proc/*/mem read/writes to other process VM inside the kernel. Andrea, you really need to clean these things up. The bigmem patches look fine _except_ for the fact that they have these #ifdef CONFIG_BIGMEM turds all over the place. That's NOT how to do it. Instead, you should unconditionally always do #include <linux/bigmem.h> which in turn does something like this: #ifdef CONFIG_BIGMEM #include <asm/bigmem.h> #else #define kmap(page) page_address(page) #define kunmap(page) do { } while (0) #endif and then there is not a _single_ #ifdef inside any actual code. Remember: if you have to have #ifdef's in actual functional code, you're doing something wrong. I don't see why you can't just abstract the thing away with zero performance degradation for the non-bigmem case by just making the mapping function the existing identity function. I'd like you to do the above cleanup, and then the bigmem patches look like they could easily be integrated into the current 2.3.x series. But with #ifdef's it won't. Linus - To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.rutgers.edu Please read the FAQ at
http://lwn.net/1999/0819/a/lt-bigmem.html
crawl-002
refinedweb
260
65.62
multi_key_dict 1.1.0 Multi key dictionary implementation Implementation of a multi-key dictionary, i.e.: (key1[,key2, ..]) => value This dictionary has a similar interface to the standard dictionary => but is extended to support multiple keys referring to the same element. If element is created using multiple keys, e.g.: from multi_key_dict import multi_key_dict k = multi_key_dict() k[1000, 'kilo', 'k'] = 'kilo (x1000)' print k[1000] # will print 'kilo (x1000)' print k['k'] # will also print 'kilo (x1000)' # the same way objects can be updated, deleted: # and if an object is updated using one key, the new value will # be accessible using any other key, e.g. for example above: k['kilo'] = 'kilo' print k[1000] # will now print 'kilo' as value was updated These elements can be accessed using either of those keys (e.g for read/update/deletion). Multi-key dict provides also extended interface for iterating over items and keys (e.g. by the key type), which might be useful when creating, e.g. dictionaries with index-name key pair allowing to iterate over items using either: names or indexes. It can be useful for many many other similar use-cases, and there is no limit to the number of keys used to map to the value. There are few other useful methods, e.g. to iterate over dictionary (by/using) selected key type, finding other keys mapping to the same value etc. Refer to example/test code to see it in action. - Downloads (All Versions): - 102 downloads in the last day - 785 downloads in the last week - 2633 downloads in the last month - Author: Lukasz Forynski - License: License :: OSI Approved :: MIT License () - Categories - Package Index Owner: Lukasz.Forynski - DOAP record: multi_key_dict-1.1.0.xml
https://pypi.python.org/pypi/multi_key_dict/1.1.0
CC-MAIN-2015-32
refinedweb
288
53.92
tcsetsid() Make a terminal device a controlling device Synopsis: #include <termios.h> int tcsetsid( const int fd, const pid_t pid ); Since: BlackBerry 10.0.0 Arguments: - fd - A file descriptor that's associated with the device that you want to make a controlling device. - pid - The ID of the process that you want to associate with the controlling device. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The tcsetsid() function makes the terminal device associated with the file descriptor argument fd into a controlling terminal that's associated with the process pid. If successful, this call causes subsequent hangup conditions on the terminal device fd to generate a SIGHUP signal on the given process. This call is equivalent to calling ioctl( fd, TIOCSCTTY ) to set the controlling terminal to the current process. You can clear the controlling terminal by passing -1 as fd. Errors: - EBADF - Invalid file descriptor. - EINVAL - The argument pid is invalid. - ENOSYS, ENOTTY - The argument fd isn't associated with a terminal device. Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/t/tcsetsid.html
CC-MAIN-2015-48
refinedweb
201
50.84
The problem: Python’s slow overall performance, and its limited threading and multiprocessing capabilities, remain major roadblocks to its future development. Python has long valued ease of programming over runtime speed. This tradeoff is not the worst thing in the world when so many performance-intensive tasks can be accomplished in Python by tapping high-speed, external libraries written in C or C++, such as NumPy or Numba. Still, Python’s out-of-the-box performance is an order of magnitude behind other languages with equally straightforward syntaxes, like Nim or Julia, that compile to machine code. One of Python’s longest-lived performance shortcomings is its poor use of multiple cores or processors. While Python does have threading facilities, they’re effectively limited to a single core. And while Python also supports multiprocessing by way of launching sub-instances of its runtime, dispatching and synchronizing the results from those subprocesses isn’t always efficient. The solution(s): Right now, there is no single, top-down, holistic solution to Python’s performance issues. Rather, there is a patchwork of initiatives to speed up Python, each contributing improvements in a specific area. Some examples: - Improving CPython’s internal behaviors. CPython improvements provide modest but universal speed-ups. For instance, Python 3.8’s Vectorcall protocol provides a faster calling convention for Python objects. While these improvements aren’t dramatic, they’re measurable and predictable, they don’t break backward compatibility, and they benefit existing Python apps without rewriting. - Improving CPython’s subinterpreter functionality. A new programmatic interface to instances of Python’s interpreter may in time allow more elegant sharing of data between interpreters for multi-core processing. Right now the proposal is set to be adopted in Python 3.9, so the relevant bits won’t even show up for at least one more Python version. - Improving object sharing among multiple processes. Multiprocessing in Python starts a new interpreter instance for each core for maximum performance, but many of those performance gains are lost when the interpreters try to operate on the same memory object. New functionality like the SharedMemory class and the new pickle protocol can reduce the amount of copying or serialization needed to pass data between interpreters, a source of performance issues. Projects outside of Python itself also offer ways to improve performance, but again only in specific ways: - PyPy. An alternative Python interpreter, PyPy just-in-time-compiles Python to native machine code. It’s long worked best with pure-Python projects, but it now works reasonably well with popular binary-dependent libraries like NumPy. Best for long-running services rather than one-off applications, however. - Cython. Cython lets you incrementally translate Python code into C. The project was originally devised for scientific and numerical computing, but it can be used in most any scenario. Biggest downside is the syntax, which is unique to Cython and makes the conversion something of a one-way process. Best for “hot spot” portions of code that benefit best from optimizing rather than whole programs. - Numba. Numba just-in-time-compiles Python to machine code for selected functions. Like Cython, Numba is mainly for scientific computing. It works best for code that is run in-place rather than redistributed. - Mypyc. Mypyc is a work-in-progress that generates C from Python code decorated with mypytype annotations. Mypyc is promising, since it uses Python’s native typing, but it is still some distance from being useful in production. - Optimized Python distributions. Some third-party versions of Python, like Intel’s Python distribution, have specially compiled versions of math and stats libraries that take advantage of Intel processor extensions (e.g., AVX512). Note that while they can speed up specific math functions dramatically, they don’t provide across-the-board speed boosts. Longtime Python programmers also talk about getting rid of the Global Interpreter Lock (GIL), which serializes access to objects and ensures threads don’t stomp on each others’ workloads. In theory, ditching the GIL could improve performance. But a GIL-less Python is, by and large, a backward-incompatible Python (especially with Python C extensions). Thus far, all attempts to remove the GIL have either reached dead ends or slowed down Python instead of speeding it up. One ongoing Python initiative that should unlock many speed improvements is the refactoring of the implementation of Python’s internal C APIs. A less messy API set is intended to make it easier to add many kinds of performance improvements in the long run: a reworked or eliminated GIL, hooks for powerful just-in-time compilations, better ways to federate data between interpreter instances, and so on. Python packaging and standalone executables The problem: Even after 30 years, Python still has no good way to take a program or script, turn it into a self-contained executable, and deploy it across multiple platforms. There are ways to do that, but they’re mainly third-party tools that aren’t a native part of Python, and they can be difficult to work with. The best-known and best-supported of these tools, PyInstaller, is still quite useful. PyInstaller can package up apps that use many of the most popular third-party extensions, like NumPy. But PyInstaller must be kept in sync manually with those third-party extensions, a tough job in an ecosystem as sprawling as Python’s. Also, PyInstaller generates outsized app packages, as it bundles everything asked for in the program’s import statements and doesn’t determine which components are actually used at runtime. Nor can PyInstaller package programs cross-platform; you have to create the package on the platform you’re deploying for. The solution: With all due respect to PyInstaller, what we need is a solution that is native to Python—either in the standard library or as a built-in—and that allows us to package and deliver Python apps efficiently as standalone binaries for the most common platforms. Ideally, this built-in packager would use runtime code-coverage information to bundle only the libraries needed (instead of everything asked for) and would be kept in sync with the rest of Python automatically. Right now, nothing like that exists. But hints about how to build such a tool keep popping up. The PyOxidizer project uses the Rust language to generate binaries that embed Python, as one way to create standalone Python apps. It’s a long way from being a full-blown solution for app delivery, but it suggests how influences from outside the Python ecosystem could lead to a solution. Python installation, package management, and project management The problem: You know what’s far too complicated? Setting up a workspace for a pro-level Python project, with a directory structure and scaffolding; and managing the environment, packages, and dependencies associated with that project; and redistributing the source for the project in a reproducible way; and not ending up eating your keyboard while trying to do all of the above over and over. One thing the Rust and Go languages set out to do from the beginning was provide a single, canonical way to set up a project and manage it throughout its lifecycle. What Rust and Go developers lost in flexibility, they won back in consistency, predictability, and manageability. Python’s tools and methods for managing installs, packages, and projects accrued over time, a legacy of its 30-year lifespan. It’s a crazy quilt. There’s pip for package management, venv/ virtualenv for creating virtual environments, virtualenvwrapper and Pipenv to meta-manage both of those things, pip-tools for generating project dependencies, distutils and setuptools for creating Python code distributions, and so on. Then there’s the welter of other parts needed to define a project: setup.py, requirements.txt, setup.cfg, MANIFEST.in, Pipfile ... the list goes on. The solution: Again, what’s needed is one tool and process to supersede this hodgepodge, offered as a canonical solution by the core Python development team, and capable of elegantly migrating projects that use any of the existing methods. It’s a tough bill to fill, to be sure, but the more popular Python becomes, the more crucial it is to lower barriers of entry and maintenance, and to provide consistent and approachable tooling. A few steps have already been taken in this direction. Build dependencies for Python are being consolidated into the pyproject.toml file format as per PEP 518. And third-party tools like poetry inch closer to an all-in-one management offering, even if they merely wrap existing tools. In time, one of those solutions may catch on with the community at large, and become a de facto standard or even a candidate for an actual accepted standard. — Read more about Python: - The best new features in Python 3.8 - How to get started with Python - 24 Python libraries for every Python developer - 13 Python web frameworks compared - 5 essential Python tools for data science—now improved - Virtualenv and venv: Python virtual environments explained - Python virtualenv and venv do’s and don’ts - What is Cython? Python at the speed of C - What is PyPy? Faster Python without pain - Why you should use Python for machine learning
https://www.infoworld.com/article/3429565/3-major-python-shortcomings-and-their-solutions.html
CC-MAIN-2021-43
refinedweb
1,534
52.29
Recently one of the other XML MVPs and I were discussing some of the new XML parsing ideas that have been making the circuit lately, and we were lamenting the fact that we were having a hard time communicating some of our ideas to others, and we aren't even trying to bridge a language barrier. The XML MVPs have been throwing around a bunch ideas that would require major design changes to the System.Xml namespace. That isn't something I would expect Microsoft to do without knowing the benefits of those changes, and without access to the System.Xml code and the ability to play with it openly, we would have a hard time expressing our ideas. Then it hit me, why don't we use the Rotor code? It was created with the idea of using it as a teaching tool, so why couldn't we use it to help "teach" others about some of our ideas. Another problem with the different ideas we had was that we couldn't easily determine the ease of use of some of our proposed designs, which is even more important than just making things run faster and better. So, I downloaded the Rotor source code, and pulled the System.Xml namespace classes into VS.Net 2K3. Unfortunately, the way the code was written, you can't just add the source files in the System.Xml directories, and compile the code. For whatever reason, I had to add the System namespace to several classes, and I couldn't find the static class that the System.Xml classes use to get the error messages out of the resource file. So I had to write the utility class, and then write a quick project to that would read the resource file and generate all the static members of the utility class. But now we have the Rotor System.Xml namespace as a complete VS.Net project. If you want to see how System.Xml does some of its magic, or if you have some ideas you want to try out, go ahead and download the project. We added it to the Mvp-Xml project that is hosted on SourceForge, and will use it as our code base, and fork the different ideas off of it.
http://weblogs.asp.net/donxml/archive/2004/03/13/89159.aspx
crawl-003
refinedweb
382
77.37
Data Partitioning with Chunks¶ On this page MongoDB uses the shard key associated to the collection to partition the data into chunks. A chunk consists of a subset of sharded data. Each chunk has a inclusive lower and exclusive upper range based on the shard key. MongoDB splits chunks when they grow beyond the configured chunk size. Both inserts and updates can trigger a chunk split. The smallest range a chunk can represent is a single unique shard key value. A chunk that only contains documents with a single shard key value cannot be split. Initial Chunks¶ Populated Collection¶ - The sharding operation creates the initial chunk(s) to cover the entire range of the shard key values. The number of chunks created depends on the configured chunk size. - After the initial chunk creation, the balancer migrates these initial chunks across the shards as appropriate as well as manages the chunk distribution going forward. Empty Collection¶ If you define zones and zone ranges defined for an empty or non-existing collection (Available starting in MongoDB 4.0.3): - The sharding operation creates empty. If you do not have zones and zone ranges defined for an empty or non-existing collection: For hashed sharding: - The sharding operation creates empty chunks to cover the entire range of the shard key values and performs an initial chunk distribution. By default, the operation creates 2 chunks per shard and migrates across the cluster. You can use numInitialChunksoption to specify a different number of initial chunks. This initial creation and distribution of chunks allows for faster setup of sharding. - After the initial distribution, the balancer manages the chunk distribution going forward. For ranged sharding: - The sharding operation creates a single empty chunk to cover the entire range of the shard key values. - After the initial chunk creation, the balancer migrates the initial chunk across the shards as appropriate as well as manages the chunk distribution going forward. Chunk Size¶ The default chunk size in MongoDB is 64 megabytes. You can increase or reduce the chunk size. Consider the implications of changing the default chunk size: - Small chunks lead to a more even distribution of data at the expense of more frequent migrations. This creates expense at the query routing ( mongos) layer. - Large chunks lead to fewer migrations. This is more efficient both from the networking perspective and in terms of internal overhead at the query routing layer. But, these efficiencies come at the expense of a potentially uneven distribution of data. - Chunk size affects the Maximum Number of Documents Per Chunk to Migrate. - Chunk size affects the maximum collection size when sharding an existing collection. Post-sharding, chunk size does not constrain collection size. For many deployments, it makes sense to avoid frequent and potentially spurious migrations at the expense of a slightly less evenly distributed data set. Limitations¶ Changing the chunk size affects when chunks split but there are some limitations to its effects. - Automatic splitting only occurs during inserts or updates. If you lower the chunk size, it may take time for all chunks to split to the new size. - Splits cannot be "undone". If you increase the chunk size, existing chunks must grow through inserts or updates until they reach the new size. Chunk Splits¶ Splitting is a process that keeps chunks from growing too large. When a chunk grows beyond a specified chunk size, or if the number of documents in the chunk exceeds Maximum Number of Documents Per Chunk to Migrate, MongoDB splits the chunk based on the shard key values the chunk represent. A chunk may be split into multiple chunks where necessary. Inserts and updates may trigger splits. Splits are an efficient meta-data change. To create splits, MongoDB does not migrate any data or affect the shards. Splits may lead to an uneven distribution of the chunks for a collection across the shards. In such cases, the balancer redistributes chunks across shards. See Cluster Balancer for more details on balancing chunks across shards. Chunk Migration¶ MongoDB migrates chunks in a sharded cluster to distribute the chunks of a sharded collection evenly among shards. Migrations may be either: - Manual. Only use manual migration in limited cases, such as to distribute data during bulk inserts. See Migrating Chunks Manually for more details. - Automatic. The balancer process automatically migrates chunks when there is an uneven distribution of a sharded collection's chunks across the shards. See Migration Thresholds for more details. For more information on the sharded cluster balancer, see Sharded Cluster Balancer. Balancing¶ The balancer is a background process that manages chunk migrations. If the difference in number of chunks between the largest and smallest shard exceed the migration thresholds, the balancer begins migrating chunks across the cluster to ensure an even distribution of data. You can manage certain aspects of the balancer. The balancer also respects any zones created as a part of configuring zones in a sharded cluster. See Sharded Cluster Balancer for more information on the balancer. Indivisible/Jumbo Chunks¶ In some cases, chunks can grow beyond the specified chunk size but cannot undergo a split. The most common scenario is when a chunk represents a single shard key value. Since the chunk cannot split, it continues to grow beyond the chunk size, becoming a jumbo chunk. These jumbo chunks can become a performance bottleneck as they continue to grow, especially if the shard key value occurs with high frequency. Starting in MongoDB 5.0, you can reshard a collection by changing a document's shard key. Starting in MongoDB 4.4, MongoDB provides the refineCollectionShardKey command. Refining a collection's shard key allows for a more fine-grained data distribution and can address situations where the existing key insufficient cardinality leads to jumbo chunks. For more information, see: moveChunk directory¶ In MongoDB 2.6 and MongoDB 3.0, sharding.archiveMovedChunks is enabled by default. All other MongoDB versions have this disabled by default. With sharding.archiveMovedChunks enabled, the source shard archives the documents in the migrated chunks in a directory named after the collection namespace under the moveChunk directory in the storage.dbPath. If some error occurs during a migration, these files may be helpful in recovering documents affected during the migration. Once the migration has completed successfully and there is no need to recover documents from these files, you may safely delete these files. Or, if you have an existing backup of the database that you can use for recovery, you may also delete these files after migration. To determine if all migrations are complete, run sh.isBalancerRunning() while connected to a mongos instance.
https://docs.mongodb.com/v5.0/core/sharding-data-partitioning/
CC-MAIN-2021-39
refinedweb
1,099
56.86
Read/initialize full python libraries stored in the cloud (eg Dropbox) Sorry for the strange question but it makes me curious. It is not related to Pythonista app, but maybe to any Python distribution. The question: with only Python programming language and an online device can I (does a script exist to): - read the full content of a compressed folder named "A" where: - the folder "A" is a compressed (zip, tar, gz, rar, ...) folder which contains python sources like a common library, like the ones you find here; - the compressed folder "A" is saved in a cloud service, for example dropbox, and it has a valid shared link. - for read full content I mean read all files (pure-python sources) - save the full content in the ram memory of the python environment. - interpret/execute the source files of the folder "A" as if they were saved in the local memory (for example in site-packages). - use in python console the definitions, functions, everything available with the library in the cloud in the same way I can import everything from a correctly locally installed library inside my python environment? I expect you can ask me why? I don't know (but I know that in this way the speed for importing libraries will be decreased compared to have the libraries properly installed in the local memory/storage). I'm only curious to know if it is possibile by a theoretical point of view and with a full python 2.7.12 environment. Thanks Hi. Since nobody answered I suppose the question was difficult to understand (or maybe not interesting). Anyway I post here a fast solution I tried yesterday (I have not done a lot of tests but for now it works with the example that I show here). Well, suppose I want to import a package/library (named “A” for example) without installing it in Pythonista with the common “pip install …”. Let’s say, only to test it without full installation. Let’s suppose also that I want to import the lib “A” in the remote server provided by SageMathCell (available through internet browser or python interface). For now, I know it is not possible to install python packages/libraries (pure-python) in SageMathCell with pip install. But it is possibile to import temporary them using only RAM (at least pure-python, maybe also not-pure-python, SageMathCell works with a Linux distribution and maybe some not-pure-python libs compiled for Linux could be imported by server). This kind of magic is available with httpimport script written by John Torakis (). The example I tested: Lib “A” is a pure python lib to perform linear programming with simplex algorithm (). The script for Pythonista or for SageMathCell is this. You can download it executing: import urllib url = "" filename = "httpimport test.py" urllib.urlretrieve(url, filename) It works with Pythonista and with SageMathCell (so it works with sage_interface). I can’t use it with any python packages saved in dropbox. The script is not tested, so most likely it doesn’t work always. I will perform some tests. Bye For those interested, httpimport author John Torakis is updating his library to support more features. This is the link of his project on GitHub. Thanks
https://forum.omz-software.com/topic/4543/read-initialize-full-python-libraries-stored-in-the-cloud-eg-dropbox
CC-MAIN-2018-13
refinedweb
542
60.45
Last time I looked at setting up my development environment to allow me to develop for the Microsoft HoloLens Emulator. This time, I’m going to create a project in Unity, add in a simple primitive object, and use some C# to do something interesting with this object. Creating a new Unity 5 project If you’ve installed Unity correctly, you’ll be shown a screen like the one below after you open Unity 5 HTP for the first time. Click on the “New project” button, and the screen should change to one similar to the one below. I’ve chosen the name “HelloWorld” for my project, and I’ve saved it to my desktop. After entering the name and location of the new Unity project, I clicked the “Create project” button and Unity shows the screen below. This is an (almost) empty project, which only has the project’s main camera and the default directional light. The next step is to update the scene with some settings which make sense for a HoloLens app. Updating the scene for the HoloLens The default camera is set about 10m behind the origin point of the scene. We’re going to make a few changes to this camera using the Inspector tab on the right hand). These ensure that the camera – i.e. the point through which we will view the world with the HoloLens – is at the origin point. Also, we’ve removed the default Skybox (i.e. background image), and any pixels rendered as black in our scene will appear as transparent in the HoloLens. Add a cube Now that we have the scene configured for the HoloLens, it’s time to add a simple object to our scene. First, we right click on our Hierarchy pane on the left and side, select “3d Object”, and then select “Cube” from the sub-menu that appears. A simple cube should appear in the centre of the scene, like in the image below. If the image does not appear in the correct place, make sure that the cube object appears in the Hierarchy menu at the same level of indentation as the Main Camera and the Directional Light. Create a material I’d like my cube to be a little more interesting than just a grey block – I’d like it to have a red colour. In Unity, we can achieve this by creating a Material asset and adding this component to the grey cube. To create a material, I right click on the Assets node in the Project panel in the bottom left of the screen. From the context menu that appears, I select “Create”, and from the next menu that appears I select “Material”. A new item is created and appears in the Assets panel – the cursor and focus are on this item, and I entered the value “Red”. Also, a grey ball appears in the bottom right hand corner. In the Inspector panel, I clicked on the color picker beside the “Albedo” label. In the pop up that appears, I selected a red colour, which updates the colour of the ball in the bottom right hand corner, as shown below. Now that I’ve created a material, I can assign this to the cube. First I selected the Cube object in the Hierarchy panel. Next, I dragged the material named “Red” onto the Inspector panel on the right hand side. This is a surface that I can drag and drop components to. As soon as I drag the Red material to the Inspector for the cube, the cube turns red. Moving the cube It’s not very useful to have this cube surrounding our point of view – it makes more sense to have this sitting out in front of our point of view. The easiest way to move the cube is to use the draggable axis which point outwards from the visible faces of the block. I clicked on the blue arrow – corresponding to the Z-direction – and dragged it forward about 3.5 units. Just to make this block a little more visually interesting, I’d like to rotate it about its axes. To do this, I click on the rotate button in the top left hand corner (it’s the third button in the group of five, and is selected in the image below). The red cube now has a set of circles surrounding it, rather than the three arrows. You can click on these circles, and drag them to rotate the cube, as shown below. That’s about it for the first section. You can preview what you’re going to see through the HoloLens by clicking on the Play button in the top-centre of the screen, which will show something like the screen below. The rotated cube floats in a black world, directly in front of our point of view. Finally I saved the scene by hitting Ctrl+S, and typed in HelloWorld – you can see this in the assets panel. Create a C# script to make the object rotate Let’s take the complexity up a notch. We can write C# scripts and apply them to objects in our virtual world. It’s very straightforward to create a script – right click on the Assets note in the Projects panel, and create a C# script from the context menus, as shown below. I created a script called RotatorScript. To edit this, I double click on it. This opens VS2015 for me, though on your install it might open MonoDevelop. I entered the code below: using UnityEngine; public class RotationScript : MonoBehaviour { public float YAxisRotationSpeed; // Update is called once per frame void Update () { this.transform.Rotate(0, YAxisRotationSpeed * Time.deltaTime, 0, Space.Self); } } The code above does one thing – each time the frame is updated by the rendering engine, the object that the script is applied to rotates a little around it’s own axes. Specifically in this case, I’ve specified the X-axis rotation and Z-axis rotation to be zero, and the rotation around the Y-axis will be YAxisRotationSpeed degrees per second. The code above refers to Time.deltaTime – this is a built in Unity function to tell us how long it has been since the last frame. Therefore if we multiply the speed – YAxisRotationSpeed – by the amount of time that passed – Time.deltaTime – the result is the number of degrees to rotate our cube by. Once I saved the script in Visual Studio, I switched back to Unity. I selected my Cube in the Hierarchy panel, and then dragged the RotationScript to the Inspector for the Cube. In the property page which appears in the Inspector, I changed the value of the “Y Axis Rotation Speed” to be 50. Now when I click on the Play button in Unity, I’m able to see the Game view of the scene again, but this time the cube is rotating about its own Y-axis. Hello World! It occurred to me that with the simple skills learned in this post that I could do something quite interesting with Unity – instead of a rotating cube, I could add a sphere to the scene, apply a material which was an image of Earth, and show a rotating globe, which would be a much more appropriate “Hello, World” project. I could even add a second sphere to rotate around this one, which could represent the Moon. I’m sure I’m not the first person to do this in Unity in a blog post – I’m sure there are many like it, but this one is mine. - As a first step, I clicked on the Cube object in my hierarchy and deleted it. This removed the red cube from my scene. - Next, I right-clicked on the Hierarchy panel, and selected “Create Empty”. This created an empty GameObject to the hierarchy. - Using the Transform panel in the Inspector for the GameObject, I changed the Z-position to be 4, thus placing the GameObject 4m in front of my point of view. - Next, I right clicked on the GameObject in the Hierarchy and added a sphere 3d Object. I renamed this “Earth”, and changed the X, Y, and Z scale values to be 2 (i.e. doubling its size). Notice how this is indented under GameObject, and also how its position in the Transform box in the Inspector is at (0, 0, 0). This means that its centre is at the origin of the parent GameObject, and changes to the position will move it relative to the parent GameObject. - Following this, I right clicked on the GameObject in the Hierarchy again, and added another 3d sphere – I named this object “Moon”, and changed the X, Y, and Z scale values to be 0.5 (i.e. halving its size). I also changed the X-position value to be 2, thus moving its centre 2m to the right of the centre of the “Earth” object. - Finally for this part, I selected the parent GameObject in the Hierarchy view, and dragged the “RotationScript” to the Inspector surface. In the property page which appears on the Inspector, I change the “Y Axis Rotation Speed” to be 50. When I hit the Play button, I can see the animation rendered, and show a scene from this below. I can see that both objects are rotating correctly – the larger central sphere is rotating about its own central vertical axis, and the smaller sphere is orbiting that same axis. However, it doesn’t look very good with the default white colour. I can improve this by using some free assets from the Unity Asset Store. Downloading assets from the Unity Asset Store I searched the Unity Asset store through a browser – at – for free renderings of Earth, and found the resource shown below (and linked to here). I clicked on the “Open in Unity” button, and this switched my in-focus application to Unity. The Asset Store tab was open, and I was able to click on the “Download” button to acquire this resource (I did see a compatibility warning about how this was created with Unity 4). After a couple of pop-ups, I was shown the window below and chose to import one of the Earth material files, shown below. After clicking on the “Import” button, this jpeg file appeared in my list of Assets, using its original directory structure. I was able to select this from the Assets/EarthSimplePlanets/Textures folder in the Project panel, and drag the “EarthSimple1.jpg” file to the Inspector surface for the Earth sphere, and, the surface of this sphere updates to look much more like more characteristic world. Finally, I selected the GameObject from the Hierarchy, and tilted the Z-axis by -15 degrees, to give a slight planetary tilt. After hitting the Play button, the animation shows a white sphere rotating around a planet. We could enhance this further by downloading more assets from the store for the Moon – a good candidate is the moon landscape linked to here – but for right now, I think this will look pretty good in our HoloLens mixed reality world. Wrapping up That’s it for this post – so far, we’ve: - created a new project with Unity, - added some primitive objects to this world, - changed these object’s colour with materials, - added a C# script to make this object move, - arranged objects to make them orbit an axis outside the object, and - used the Unity Asset Store to download assets that make our model more realistic. Next time, we’ll talk about actually deploying to the HoloLens emulator – there are a few tips and gotchas that I want to share to make other people’s journey a little smoother than mine.
https://jeremylindsayni.wordpress.com/2016/07/15/coding-for-the-hololens-with-unity-5-part-2-creating-a-simple-hello-world-project/
CC-MAIN-2017-26
refinedweb
1,965
68.1
Collections Section Index | Page 2 What is the purpose of the CopyOnWriteArrayList and CopyOnWriteArraySet collections? Synchronized operations are costly and if you aren't modifying a collection much, it is best not to synchronize all collection accesses. The CopyOnWriteXXX collections avoid concurrent modificatio...more How do I make a copy of an array? The arraycopy method of System allows you to do this but... starting in Java 6, there is a new copyOf() method added to the Arrays class that is slightly more flexible. How can I insert an element into a List? In order to insert an element into a List add(int index, E element) must be used since the List interface does not provide an insert method. If the index is out of rage ie. index < 0 || index &...more What is the difference between a Stack and a Queue? First things first. Where can Stacks and Queue's be found? Java provides a Stack class, which can be found within the java.util namespace. Within the same namespace you will find a Queue interf...more How can I create an immutable List consisting of n Copies of an Object? nCopies(int n, T o) can be used to create an immutable List which contains a specific number of copies of an Object. Care must be taken when trying to add elements to or extract elements from the...more How can I find the maximum element contained within a Collection? Finding the maximum element within a Collection is easy. The following method can be used which can be found within the Collections class. public static <T extends Object & Comparable<? s...more What is the easiest way to obtain a Map Entry? The easiest way to obtain a Map Entry or (key-value pair) is by invoking the following method provided by the Map interface. Set<Map.Entry<K,V>> entrySet(); The entrySet() metho...more Is there a way determine how many times an Object occurs within a Collection? Is there a way determine how many times an Object occurs within a Collection? How can I create a read only Collection? Unmodifiable Collections can be easily created using various static methods which the Collections class provides. Any attempts to modify the returned Collection, whether direct or via its iterat...more How can I get a sorted list of keys that are contained within a Map? The Map interface defines a method named keySet() which concrete classes such as HashMap and TreeMap implement. Depending on the implementation on which keySet() is invoked the returned Set migh...more How can I traverse a List backwards? In order to traverse a List backwards a ListIterator must be used. The List interface provides a method, which returns a ListIterator. ListIterator<E> listIterator() Using a returned L...more How can i tell if two Collections contain the same elements or have no elements in common? Two methods are needed in this case. boolean containsAll(Collection<?> c) boolean disjoint(Collection<?>c1 Collection<?>c2) Since containsAll(Collection<?> c) is define...more How can I shuffle the elements of a Collection? The Collections class which can be found within the java.util namespace provides two methods which suffle the elements of a Collection. static void shuffle(List<?> list) static void shuffl...more What are Generics and how can I use them? One of the biggest additions since the creation of the Collections framework is Generics.This long awaited update to the type system is a welcomed feature, which C++ developers have had in their ...more How can I define my own Comparable type so that it can be naturally sorted within a List? When taking a peek at the Java docs you will notice certain classes implement an interface named Comparable. Take a look at some of the subclasses of Number such as Byte, Integer, Long, Float or ...more
https://www.jguru.com/faq/core-java-technology/collections?page=2
CC-MAIN-2020-50
refinedweb
642
59.7
Three Names to Include in Your User Model (None of them is the username) The term “username” is ambiguous. When designing a user model there are several kinds of names that are useful to include. It’s time to start a new project. You want users, so the first thing you do is add a user model with username and password fields and – whoa, hold up. What’s that username again? Is it the user’s email address? Is it an arbitrary nickname that the user can choose? Is it an automatically generated identifier that should never change? A Rose by Any Other Name Would Not Be Able To Log InCopy permalink to “A Rose by Any Other Name Would Not Be Able To Log In” It’s not for nothing that they say naming things is one of the hard problems in computer science. For modeling user accounts there are three different name fields that you probably want, and for the sake of avoiding confusion let’s not call any of them the username: - The user id. This is the permanent, unchanging identifier of a particular user. It may be generated randomly or it may be an incrementing number, but the important thing is that it should not have any inherent meaning, and it should never change. That makes it safe for use internally throughout the system as a foreign key to refer to the user. - The display name or screen name. This is what will actually be shown when referring to the user in the UI and notifications (to the user themself or to other users). This should be chosen by the user with few limitations (except perhaps on length or to avoid excessive whitespace). That gives users full flexibility to use their offline name (including in other writing systems), nickname, stage name, or even emoji. If it will be shown to multiple users, consider making it be unique to avoid confusion. It should be editable. - The login. This is what the user will type to log in to the system (or what their password manager will type for them). You may be tempted to let users choose their own login, but we prefer to use their email address because it makes it less likely that the user will forget their login. Whatever it is, it must be unique among all the users, and should be editable. If it’s the email address, changing it should require responding to a verification email to verify control of the email account. (Some systems may want to allow a user to set up multiple logins including various email addresses, phone numbers, or social accounts.) You probably noticed I did not include the user’s given and family names (and middle name and maiden name and…). Avoid collecting these as separate fields unless you need to, i.e. for official or legal purposes. Keep in mind that the preferred order of these names varies in different cultures (so avoid calling them “first name” and “last name”). And keep in mind that they may change over time. Names are hard. Building this User Model in DjangoCopy permalink to “Building this User Model in Django” We like Django for building backends. There are a number of ways to extend Django’s default user model. Here’s our custom User model that meets the above guidelines: from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser class User(AbstractBaseUser, PermissionsMixin): name = models.CharField("name", max_length=30, blank=True, unique=True) date_joined = models.DateTimeField(_("date joined"), auto_now_add=True) is_active = models.BooleanField(_("active"), default=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def get_full_name(self): return self.name def get_short_name(self): return self.name Like all Django models, it has a default id field which meets our criteria for user id. There is a single name field which is used when Django needs to display the user’s name via the get_full_name and get_short_name methods. And it has an (Note: This model requires a custom UserManager – I won’t include that here; see Vitor Freitas’ helpful How to Extend the Django User Model article for details.) Add this model to a new Django project (it’ll be easiest if you use it from the start), configure it using the AUTH_USER_MODEL setting, and you’ll be well on your way to never having to say the word “username” again. Did we miss anything important? Let us know via Twitter!
https://www.oddbird.net/2017/04/11/usernames/
CC-MAIN-2022-40
refinedweb
750
64.2
Not logged in Log in now Recent Features LWN.net Weekly Edition for December 5, 2013 Deadline scheduling: coming soon? LWN.net Weekly Edition for November 27, 2013 ACPI for ARM? LWN.net Weekly Edition for November 21, 2013 On Sun, Dec 5, 2010 at 2:38 AM, Casey Schaufler <casey@schaufler-ca.com> wrote: > The end to which the controls are put does not change the character > of those controls. If the attribute of the file being used is the > name component of the name/inode pair in a directory entry than what > you have is a pathname based control mechanism. It will have all of > the downsides, including mount points and hard links, that any other > name based scheme will suffer from. I think this is a misunderstanding. The mechanism that Eric is proposing (which btw is something that has long since been discussed among the SELinux developers and agreed to in principle, so this is not a point of contention among SELinux developers) is to allow the last component name of a newly created file to be used as an optional additional input into the decision logic for computing the new label of that inode. You can already use the security contexts of the creating process and the parent directory along with the type of file (security class) as inputs into that logic, so this merely adds one additional factor that can be leveraged by policy writers. It is only used as an input when the file is created (file access is still based solely on its previously determined security context) and namespace manipulation has no effect on it (creating a hard link to the file does not involve this logic, nor does renaming it nor mounting the containing filesystem elsewhere). > These "userspace hacks" are no "worse" than restorecond from a > security perspective. They have the unpleasant characteristic that > they are outside the control of the primary distributor of SELinux. > I will admit that the suggested changes will make SELinux better. > That does not make them any less pathname based. I don't follow this logic. restorecond and udev relabeling of kernel-created dev nodes are inherently racy - the file is not created in the desired security context initially, and must be relabeled by some userspace component that notices that the file has been created. Kernel support for incorporating the last component name as an additional input enables us to label certain files correctly upon creation and thus avoids that problem entirely. And as for being outside the control of a given distributor, I think that is both a fallacy (it is no harder to replace or extend userspace than it is to replace/extend policy) and irrelevant. > Initial labeling of objects is critical. There is no point in > talking about the access control decision if you can't say good > things about how the label gets set initially. That's true, and precisely why this is beneficial - it gives us an additional input to use when labeling objects initially that improves our accuracy of labeling at file creation time. BTW, this isn't as novel to SELinux as you seem to think. That fact that we are already using the parent directory context as an input in computing the security context of a new files means that our file labeling logic is already "path-based" in a certain sense. It isn't solely path-based (either before or after this change), but it is already taking into account the placement of the file when it is created. This just refines the granularity at which we can make such decisions. > My point is roughly centered around the distinction between a Linux > kernel with SELinux configured and a policy installed and an SELinux > system with the aforementioned and a complete SELinux runtime that > includes goodies like restorecond. The former is strictly label based, > while the latter is definitely not. I really think that you should > leave the name based bits in userspace unless you are willing to > accept their general value in the kernel. SELinux remains label-based in its access control enforcement mechanism in the kernel even after this change. In any event, you are free to configure your policy to not use this extension just as you are free to not ship/run restorecond - there is no real difference there. With regard to the pathname hooks, they aren't suitable because they don't have anything to do with assigning labels to new inodes - they are about enforcing access control upon file accesses based on the pathname used to reach the file. That doesn't support what we want. The only real question for this particular patch IMHO is whether the changes being made here are sensible from a vfs and fs point of view. Most of your comments seem more directed at whether or not SELinux should be extended in this manner (i.e. the 2nd patch), and that's a question for the SELinux developers, who have already come to consensus on the matter. -- To unsubscribe from this list: send the line "unsubscribe linux-security-module" in the body of a message to majordomo@vger.kernel.org More majordomo info at Linux is a registered trademark of Linus Torvalds
http://lwn.net/Articles/419219/
CC-MAIN-2013-48
refinedweb
875
57.3
When using WPF for 3D graphics, many people have concerns over the performance. Following the guidelines from Microsoft online help, I built a 3D surface chart, as shown in the picture above. The surface chart has more than 40,000 vertices and more than 80,000 triangles. The performance is still fine. The project also includes 3D scatter plot which has a large number of data points. You can build the project, feel the performance of WPF 3D and decide whether WPF 3D is suitable for your 3D data visualization. This section briefly goes through the steps for building 3D graphics using WPF. Although there are many tutorials on WPF 3D, I still give a brief review here to help understand the class structure of this project. The WPF 3D is displayed within the Viewport3D UI elements. The three basic components are: Viewport3D For 3D chart, we are not concerned too much about the camera and light. Those properties are set in the XAML file, as shown below. The 3D model will be set in C# code. <Window x:Class="WPFChart.Window1" xmlns="" xmlns: <Grid> <Viewport3D Name="mainViewport" > <Viewport3D.Camera> <OrthographicCamera x: </Viewport3D.Camera> <Viewport3D.Children> <ModelVisual3D x: <ModelVisual3D.Content> <DirectionalLight Color="White" Direction="1,1,-1"/> </ModelVisual3D.Content> </ModelVisual3D> </Viewport3D.Children> </Viewport3D> </Grid> </Window> The root element is a Window. Inside the window, we use Grid layout. Those two elements are provided by Visual Studio when we build the project. Inside the grid, we add a Viewport3D to hold the 3D object. Under the Viewport3D, we have a camera, a directional light. Window window Grid grid We added the camera and light in the XAML file. Now, we add the 3D model in C# code. The mesh structure (type System.Windows.Media.Media3D.MeshGeometry3D) consists of four parts of data: System.Windows.Media.Media3D.MeshGeometry3D The vertices location is represented by a Point3D structure. Point3D System.Windows.Media.Media3D.Point3D point0 = new Point3D(-0.5, 0, 0); System.Windows.Media.Media3D.Point3D point1 = new Point3D(0.5, 0.5, 0.3); System.Windows.Media.Media3D.Point3D point2 = new Point3D(0, 0.5, 0); Those points are put into Positions array of the mesh structure. Positions System.Windows.Media.Media3D.MeshGeometry3D triangleMesh = new MeshGeometry3D(); triangleMesh.Positions.Add(point0); triangleMesh.Positions.Add(point1); triangleMesh.Positions.Add(point2); Three vertices make a triangle. The vertices connections are described by three integers, which are the indices of the 3 vertices in the Positions array. int n0 = 0; int n1 = 1; int n2 = 2; The 3 indices of a triangle are added to the TriangleIndices array. TriangleIndices triangleMesh.TriangleIndices.Add(n0); triangleMesh.TriangleIndices.Add(n1); triangleMesh.TriangleIndices.Add(n2); The order of the indices decides whether the triangle is front surface or back surface. The front surface and back surface usually have different properties. The WPF 3D display also needs to know the normal direction of the vertices. System.Windows.Media.Media3D.Vector3D norm = new Vector3D(0, 0, 1); triangleMesh.Normals.Add(norm); triangleMesh.Normals.Add(norm); triangleMesh.Normals.Add(norm); We will discuss the texture mapping in a later section. The above code only shows one triangle. By combining many triangles, we can get a mesh structure. Now, we will attach material properties to the mesh surface. System.Windows.Media.Media3D.Material frontMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Blue)); Combining mesh and material, we can get a 3D model. System.Windows.Media.Media3D.GeometryModel3D triangleModel = new GeometryModel3D(triangleMesh, frontMaterial); The GeometryModel3D object also has a transform property. We will discuss it in the next section. GeometryModel3D transform triangleModel.Transform = new Transform3DGroup(); The 3D model we created will be attached to a visual element: System.Windows.Media.Media3D.ModelVisual3D visualModel = new ModelVisual3D(); visualModel.Content = triangleModel; The ModelVisual3D object will be displayed in Viewport3D: ModelVisual3D this.mainViewport.Children.Add(visualModel); This involves quite a lot of steps. Model3D class in this project helps to generate a ModelVisual3D object. If we run the program, we will see a blue triangle. We cannot rotate it yet. In the next section, we will show how to rotate this 3D model. Model3D In this section, we will use the mouse to rotate the 3D model. Rotating the 3D model in WPF is easy, but we want to implement our own selection function later. Therefore, we need to keep a track of the transform when we rotate the 3D model. In order to catch the mouse event, we cover the Viewport3D with a transparent Canvas. The mouse down, move and up events handlers of the canvas will be added to the window class. Viewport3D Canvas window We can either change the camera location or change the transform property of the 3D model to rotate the 3D object. For this project, we will modify the transform property of the 3D model. The transform property of a 3D model can be described as System.Windows.Media.Matrix3D. We will build a special transform class to use this matrix. System.Windows.Media.Matrix3D public class TransformMatrix { public Matrix3D m_viewMatrix = new Matrix3D(); private Point m_movePoint; } The Matrix3D member variable m_viewMatrix is used to rotate the 3D object. The TransformMatrix class will handle the mouse events and rotate the model. Matrix3D m_viewMatrix TransformMatrix public class TransformMatrix { public void OnMouseMove(Point pt, System.Windows.Controls.Viewport3D viewPort) { double width = viewPort.ActualWidth; double height = viewPort.ActualHeight; if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) { } else { double aY = 180 * (pt.X - m_movePoint.X) / width; double aX = 180 * (pt.Y - m_movePoint.Y) / height; m_viewMatrix.Rotate(new Quaternion(new Vector3D(1, 0, 0), aX)); m_viewMatrix.Rotate(new Quaternion(new Vector3D(0, 1, 0), aY)); m_movePoint = pt; } } } The 3D rotation is implemented in the mouse move event. The view matrix will rotate according to the offset of the current mouse position and previous mouse position m_movePoint. We scale the rotate so the model moves 180 degrees when we move the mouse from one side of the window to another side. You can change this rotation sensitivity. m_movePoint To use the TransformMatrix class, we can add a TransformMatrix variable to the window class, and call the mouse event handler of TransformMatrix object at the corresponding mouse events of the window class. TransformMatrix public partial class Window1 : Window { public WPFChart.TransformMatrix m_transformMatrix = new WPFChart.TransformMatrix(); public void OnViewportMouseMove(object sender, System.Windows.Input.MouseEventArgs args) { Point pt = args.GetPosition(mainViewport); if (args.LeftButton == MouseButtonState.Pressed) { m_transformMatrix.OnMouseMove(pt, mainViewport); Transform3DGroup group1 = triangleModel.Transform as Transform3DGroup; group1.Children.Clear(); group1.Children.Add(new MatrixTransform3D(transformMatrix.m_ m_viewMatrix)); } } } After we modify the transform matrix, we need to set a new view matrix to the 3D model’s transform property. The triangle we used in the previous two sections has the data range -0.5 ~ 0.5. The camera we used has a default width of 2. Camera center is at (0, 0). So the triangle is in the camera view range. If the 3D object is out of camera range, the 3D object will not be shown in Viewport3D. We can change the camera position to keep the 3D object in camera view. Here, we use a different approach. We will add another matrix to project the 3D object into the camera view range. public class TransformMatrix { private Matrix3D m_viewMatrix = new Matrix3D(); private Matrix3D m_projMatrix = new Matrix3D(); public Matrix3D m_totalMatrix = new Matrix3D(); } The projection matrix will transform the 3D model into camera view range. The 3D object then goes through the view matrix, as discussed in the previous section. The total matrix will be set into the 3D model transformation. The projection matrix is set by the data range of the 3D object. public class TransformMatrix { public void CalculateProjectionMatrix(double xMin, double xMax, double yMin, double yMax, double zMin, double zMax, double k) { double xC = (xMin + xMax) / 2; double yC = (yMin + yMax) / 2; double zC = (zMin + zMax) / 2; m_projMatrix.SetIdentity(); m_projMatrix.Translate(new Vector3D(-xC, -yC, -zC)); double sX = k*2 / (xMax - xMin); m_projMatrix.Scale(new Vector3D(sX, sX, sX)); m_totalMatrix = Matrix3D.Multiply(m_projMatrix, m_viewMatrix); } } The last parameter of the function is a scale factor. A value of 0.5 means we want data to take 50% of the screen. Each time, we change the view matrix or projection matrix, we need to calculate the total matrix. We also need to change our code in the window class. Instead of setting the view matrix m_viewMatrix to the 3D model transform property, we will set the total matrix m_totalMatrix to the 3D object transformation. m_totalMatrix The WPF provides the mouse hit test function. However, it may not be suitable for a 3D chart. For example, a 3D scatter plot may have several thousand data points. Running hit test on those data points is not practical in terms of performance. Therefore, we should turn off the IsHitTestVisible property of the Viewport3D. IsHitTestVisible To implement our own selection function, we need to know where a 3D point is projected on the 2D screen. In the previous section, we add a matrix transform to the 3D object. In addition to this transform, the 3D object also goes though other transforms before it is projected onto 2D screen. For example, the camera has its own transform. The orthographic camera we used keeps the default width of 2. It points to the –z direction. You can check the camera transform matrix and will find out that it is an identity matrix. Therefore, we will ignore the camera transform. However, we still have one transform that has not been discussed yet, i.e. the final transform which projects the camera range to Viewport3D. Following those rules, the VertexToScreenPt() function of the TransformMatrix class calculates the screen location of a 3D point. VertexToScreenPt() public class TransformMatrix { public Point VertexToScreenPt(Point3D point, System.Windows.Controls.Viewport3D viewPort) { Point3D pt2 = m_totalMatrix.Transform(point); double width = viewPort.ActualWidth; double height = viewPort.ActualHeight; double x3 = width / 2 + (pt2.X) * width / 2; double y3 = height / 2 - (pt2.Y) * width / 2; return new Point(x3, y3); } } The input Point3D parameter is the 3D location of a point, the return Point value is its location on the 2D screen. To test this function, we will move the mouse onto one corner of the triangle, and compare the actual screen coordinate with predicated position by the VertexToScreenPt() function. Point A text block is added to the bottom of the window and acts as a status pane. At the mouse move event, we can hold the mouse left button and rotate the triangle to different location, as we did in the previous section. We can then move the mouse to the top-right corner of the triangle. The actual mouse position can be obtained from the mouse event argument. We will compare this reading with the calculated position of the triangle vertex. public partial class Window1 : Window { public void OnViewportMouseMove(object sender, System.Windows.Input.MouseEventArgs args) { Point pt = args.GetPosition(mainViewport); if (args.LeftButton == MouseButtonState.Pressed) { } else { String s1; Point pt2 = m_transformMatrix.VertexToScreenPt (new Point3D(0.5, 0.5, 0.3), mainViewport); s1 = string.Format("Screen:({0:d},{1:d}), Predicated:({2:d}, H:{3:d})", (int)pt.X, (int)pt.Y, (int)pt2.X, (int)pt2.Y); this.statusPane.Text = s1; } } } Look at the status pane display, we know TransformMatrix.VertexToScreenPt() function returns the correct screen position. We can rotate the triangle to a different location, and still get matching results. Based on the TransformMatrix.VertexToScreenPt() function, we implement the select function in this project. TransformMatrix.VertexToScreenPt() Understanding the screen transformation also helps us implement the drag function in mouse move event. The mouse will be used to drag the 3D model when the shift key is down. We want the 3D model to move exactly by the same amount as that mouse move on the screen. Therefore, we use camera width to Viewport3D width ratio as the scale factor when we drag the model. public class TransformMatrix { public void OnMouseMove(Point pt, System.Windows.Controls.Viewport3D viewPort) { double width = viewPort.ActualWidth; double height = viewPort.ActualHeight; if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) { double shiftX = 2 *(pt.X - m_movePoint.X) /( width); double shiftY = -2 *(pt.Y - m_movePoint.Y)/( width); m_viewMatrix.Translate(new Vector3D(shiftX, shiftY, 0)); m_movePoint = pt; } m_totalMatrix = Matrix3D.Multiply(m_projMatrix, m_viewMatrix); } } In the previous section, we displayed a triangle. A 3D object consists of many triangles. Mesh3D and ColorMesh3D classes in this project are used for single color 3D models and color 3D models respectively. For single color 3D objects, we have the Mesh3D class: Mesh3D ColorMesh3D public class Mesh3D { private Point3D [] m_points; // x, y, z coordinate private Triangle3D [] m_tris; // triangle information private Color m_color; // mesh color public double m_xMin, m_xMax, m_yMin, m_yMax, m_zMin, m_zMax; } The single color mesh model consists of an array of 3D points and array of triangle’s vertices’ indices. The whole mesh model has a single color which is described by the third member variable m_color. The last six member variables are the data range of the mesh model. m_color The Triangle3D class defines the vertex index of a triangle. Triangle3D public class Triangle3D { public int n0, n1, n2; } Based on Mesh3D class, we can build different basic shapes, such as, cube, cylinder, cone, and sphere. They are child classes of Mesh3D class. Those basic shapes are need in 3D charts. The Mesh3D class is for data processing. We have to convert it into WPF ModelVisual3D type for 3D display. We also want to merge different mesh models into a single 3D model to enhance the performance of 3D display. The Model3D class is designed for this purpose. The picture below describes the class structure of this project. The 3D data in a different 3D chart has a different form. This project only demos the scatter plot and surface plot. They are represented by ScatterChart3D and SurfaceChart3D classes. The 3D chart data goes through a few conversions before the pass to the Viewport3D. First, it generates an array of Mesh3D (or ColorMesh3D) objects. This Mesh3D array is then passed to the Model3D class and produces a single ModelVisual3D object. The ModelVisual3D object is added to the Viewport3D for display. ScatterChart3D SurfaceChart3D WPF 3D model can set the color using brush. If a 3D chart has many color objects, creating many brushes of different colors will degrade the performance. Instead we can create an image brush for color mapping. The image has a different color at different locations. We can use different mapping coordinates for different colors. The true color has 2563 = 16777216 colors. Those colors need a 4096x4096 mapping image. Normally, the 3D charts only use limited number of colors. For different 3D charts, we will use different color layouts. For bar chart and scatter plot, we use 16 color values in each channel. There will be 163 = 4096 colors. This should be enough to mark different categories. The size of the mapping image will be 64x64. For surface charts, we often pseudo color the surface according to the z value of the 3D plot, as shown in the first picture of this article. The picture below shows the color mapping method we use for pseudo color. The x axis is normalized z value. The y axis shows the RGB color that corresponds to the z value. The TextureMapping class implements both color layouts. Here, we only discuss the color layout for scatter plot. You can check the source code of the TextureMapping class for pseudo color mapping. The mapping image has a size of 64x64. The blue channel has 16 values, so the blue channel takes 1/4 of each row. We then change the green channel. For each red value, the green and blue values take 4 rows. TextureMapping The WritableBitmap will be used in the image brush. WritableBitmap public class TextureMapping { public DiffuseMaterial m_material; private void SetRGBMaping() { WriteableBitmap writeableBitmap = new WriteableBitmap(64, 64, 96, 96, PixelFormats.Bgr24, null); writeableBitmap.Lock(); First, we set up a 64x64 RGB bitmap. In order to access the bitmap memory, we need to lock the bitmap. unsafe { byte* pStart = (byte*)(void*)writeableBitmap.BackBuffer; int nL = writeableBitmap.BackBufferStride; for (int r = 0; r < 16; r++) { for (int g = 0; g < 16; g++) { for (int b = 0; b < 16; b++) { int nX = (g % 4) * 16 + b; int nY = r*4 + (int)(g/4); *(pStart + nY*nL + nX*3 + 0) = (byte)(b * 17); *(pStart + nY*nL + nX*3 + 1) = (byte)(g * 17); *(pStart + nY*nL + nX*3 + 2) = (byte)(r * 17); } } } } In order to access the bitmap memory directly, we need to use unsafe code. We also need to enable the unsafe mode in the project setting. For each channel, we use 16 levels. The pixel location in the bitmap is calculated from RGB value. The color at the corresponding pixel is set. writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, 64, 64)); writeableBitmap.Unlock(); ImageBrush imageBrush = new ImageBrush(writeableBitmap); imageBrush.ViewportUnits = BrushMappingMode.Absolute; m_material = new DiffuseMaterial(); m_material.Brush = imageBrush; } } After the color pixels are set, we set the dirty flag so the WPF will update the bitmap element. Once we finish accessing the bitmap memory, we need to unlock the bitmap so the WPF can update the bitmap display. We then create an image brush using the bitmap. At last, we create a material using image brush. Later, when we use mapping image for color painting, we need know the mapping location of a certain color. This is provided by the GetMappingPosition() function of the TextureMapping class. GetMappingPosition() public class TextureMapping { public Point GetMappingPosition(Color color) { int r = (color.R) / 17; int g = (color.G) / 17; int b = (color.B) / 17; int nX = (g % 4) * 16 + b; int nY = r * 4 + (int)(g / 4); return new Point((double)nX /63, (double)nY /63); } } To use the mapping image for color, we get the color of the each vertex, then find the mapping coordinate of that color, and add the mapping coordinate to the TextureCoordinates array of the MeshGeometry3D object. This is implemented in the SetModel() function of the Model3D class. TextureCoordinates MeshGeometry3D SetModel() This project provides some base classes for high performance 3D charts. It is not a complete library. You still need to add more classes to display grid, label, title. The picture below shows the testing program. The data is generated randomly within a certain range. Therefore, it does not look real, You can plugin your data. Check the code in the window class to see how to use those classes. The project provides the following functions: Check the message handler for "Test" button to see how to generate the display model for 3D chart. Hold the mouse left button to rotate the 3D model. Hold the mouse left button and shift key to drag the model. Press "+" or "-" key to zoom Use mouse right button to draw a rectangle and select data in the 3D chart. Finally, you can change the data number, (then click test button) to test the performance of the WPF3D. WPF is very easy to use to display some simple objects. However, you need to do a lot of work if you want to display a larger amount of data. Those performance enhancement tasks seem trivial, but need a lot of testing and debugging. I hope this project helps you decide whether you want to use WPF for your 3D data display, or continue using other techniques, such as Open.
http://www.codeproject.com/Articles/42174/High-performance-WPF-3D-Chart?fid=1548990&df=90&mpp=25&sort=Position&spc=Relaxed&tid=4088892
CC-MAIN-2016-36
refinedweb
3,221
51.14
SnapKit is a DSL to make Auto Layout easy on both iOS and OS X.', '~> 5.6.0' end Then, run the following command: $ pod install Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. You can install Carthage with Homebrew using the following command: $ brew update $ brew install carthage To integrate SnapKit into your Xcode project using Carthage, specify it in your Cartfile: github "SnapKit/SnapKit" ~> 5.0.0 Run carthage update to build the framework and drag the built SnapKit.framework into your Xcode project. Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies. Xcode 11+ is required to build SnapKit using Swift Package Manager. To integrate SnapKit into your Xcode project using Swift Package Manager, add it to the dependencies value of your Package.swift: dependencies: [ .package(url: "", .upToNextMajor(from: "5.0.1")) ] If you prefer not to use either of the aforementioned dependency managers, you can integrate SnapKit into your project manually. import SnapKit class MyViewController: UIViewController { lazy var box = UIView() override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(box) box.backgroundColor = .green box.snp.makeConstraints { (make) -> Void in make.width.height.equalTo(50) make.center.equalTo(self.view) } } } You can try SnapKit in Playground. Note: To try SnapKit in playground, open SnapKit.xcworkspaceand build SnapKit.framework for any simulator first. SnapKit is released under the MIT license. See LICENSE for details. Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics
https://swiftpack.co/package/SnapKit/SnapKit
CC-MAIN-2022-27
refinedweb
266
50.33
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Where-ever a right pointer is NULL, it is used to store inorder successor. Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads. Following is structure of single threaded binary tree. struct Node { int key; Node *left, *right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. bool isThreaded; }; How to convert a Given Binary Tree to Threaded Binary Tree? We++ program to convert a Binary Tree to Threaded Tree */ #include <iostream> #include <queue> using namespace std; /* Structure of a node in threaded binary tree */ struct Node { int key; Node *left, *right; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. bool isThreaded; }; // Converts tree with given root to threaded // binary tree. // This function returns rightmost child of // root. Node *createThreaded(Node *root) { // Base cases : Tree is empty or has single // node if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) return root; // Find predecessor if it exists if (root->left != NULL) { // Find predecessor of root (Rightmost // child in left subtree) Node* l = createThreaded(root->left); // Link a thread from predecessor to // root. l->right = root; l->isThreaded = true; } // If current node is rightmost child if (root->right == NULL) return root; // Recur for right subtree. return createThreaded(root->right); } // A utility function to find leftmost node // in a binary tree rooted with 'root'. // This function is used in inOrder() Node *leftMost(Node *root) { while (root != NULL && root->left != NULL) root = root->left; return root; } // Function to do inorder traversal of a threadded // binary tree void inOrder(Node *root) { if (root == NULL) return; // Find the leftmost node in Binary Tree Node *cur = leftMost(root); while (cur != NULL) { cout << cur->key << " "; // If this Node is a thread Node, then go to // inorder successor if (cur->isThreaded) cur = cur->right; else // Else go to the leftmost child in right subtree cur = leftMost(cur->right); } } // A utility function to create a new node Node *newNode(int key) { Node *temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp; } // Driver program to test above functions int main() { /* 1 / \ 2 3 / \ / \ 4 5 6 7 */ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); createThreaded(root); cout << "Inorder traversal of creeated " "threaded tree is\n"; inOrder(root); return 0; } Output: Inorder traversal of creeated threaded tree is 4 2 5 1 6 3 7 This algorithm works in O(n) time complexity and O(1) space other than function call stack. This article is contributed by Gopal.
http://www.geeksforgeeks.org/convert-binary-tree-threaded-binary-tree-set-2-efficient/
CC-MAIN-2017-13
refinedweb
488
56.39
I've been poring over the scheme48-0.36 stuff for the last week or so, and I finally got to the point where I can read some of the code, and I've got a bunch of ideas and questions. I'm coming at this from the comp.lang.* background, with an eye toward selecting technology for collaborative development of WWW applications. I am concerned with the trend of developing "killer apps" using limited technology and/or hopelessly un-reusable code. The Mosaic code is kinda messy. There was an outcry to rewrite it as a Tcl app. But tcl doesn't lend itself to any sort of static analysis or optimization. I see scheme48 as a basis for developing correct, well-abstracted code that can run efficiently. This is the only kind of code that has the potential to solve a given problem "once and for all." (or at least well enough that for the next 5 or 6 years, we will only have to retarget/recompile -- not rewrite -- the code). The scheme48vm seems to be very fast, and since it supports full continuations, it should be able to support any of the popular interpreted programming languages -- python, perl, icon, tcl, smalltalkd, etc. (as well as ML, prologue, and other functional/logic languages), with suitable bytecode compilers and runtime libraries. I like lisp and scheme, and the combination of one bright person and a good lisp/scheme development environment can produce some great things. I'm not so optimistic about what happens when you get a hundred folks, some bright and some not-so-bright, and task them with writing an application in scheme. I'm interested in integrating mechanisms into scheme48 to support such collaborative engineering. lisp/scheme code is notoriously difficult to read and maintain. I have heard this claim at least a hundred times, and I used to dismiss it as rhetoric. But when I contrast my initial experience with Modula-3 (and it's wannabe-workalike, python) with my voyage through the scheme code in the scheme48-0.36 distribution, I think I have some real issues to back this claim. scheme48 has a module system, but the namespace is still essentially flat! Consider: [Perhaps I've missed something... perhaps it's possible to rename identifiers in an interface definition...] Also, it's not the case that once I've found a suitably unique interface/package/module name that I can use any name I want within the package. I still have to worry about collisions between names I make up and names from other packages that folks might want to use with this one. Reading this style of code is no picnic either. If I print out some scheme source file foo.scm and come across: (define (foo-func a1 a2) (bar-func (+ a1 a2))) there is nothing in foo.scm that tells me where to find bar-func. I have to discover the config file(s?) that include foo.scm, and then I have to search each of the structures that are open with foo.scm is included. Basically, to find the definition of bar-func, I have to search ALL names defined in the whole application! And if grep finds "(define (bar-func ..." more than once, I have to determine which structures are open when compiling foo.scm, and discover which of the bar-func's is the right one. Are there mechanisms in the scheme48 development environment to help in this area? I see that there is work being done on some "infix" language or dialect of scheme. I like this idea, and I strongly suggest that it support a Modula-3/python style namespace, using import X, Y, Z import X as xx, Y as yy from X import a,b,c But for the purpose of static analysis, leave out python's: from X import * This doesn't address the issue of how to make effective use of existing bodys of code written in scheme. Hmmm.... The scheme macro system is nifty. scheme48 uses it to represent a zillion different (define-xxx ...) forms. Those forms get real hard to read real fast. The ubiquitous (define-record-type ...) form is a good example. Is it possible/practical to use keyword arguments, if not in real functions, then at least in the syntactic macros? I wouldn't mind seeing: (define-record-type rec :brand :rec :constructor (make-rec f1 f2) :fields (f1 rec-f1 rec-set-f1!) (f2 rec-f2 rec-set-f2!) ) Is there anything preventing somebody using record-set! on pretty much any record object? If not, it seems that the language does not support information hiding, and it seems that it would be very difficult to develop "safe" interfaces. When developing large applications, my experience is that static type checking reduces the net time to develop correct implementations, even though it increases the time to write the initial code. I don't fully grok ML, but I understand that it has a powerful type system, and I gather it could be compiled for the scheme48 vm. I'm looking into that... I saw some code in the scheme48 distribution that appeared to do static type checking of scheme programs. This looks interesting. At least with scheme, there is the possibility of static analysis and optimization, unlike tcl and python. I understand that there are many ways to do object-oriented programming in scheme. But I doubt code can be reused across techniques. So in order to build a large code base of reusable smalltalk-like objects, a community must choose one technique. The namespace for interfaces, classes, methods, variables, types, and such is also an issue for "programming in the large." obj.meth(arg1, arg2, arg3) ((python-getattr obj 'meth) arg2 arg3)) Several descriptions of Scheme48 imply that scheme48 has a powerful and easy-to-use FFI. I have experience with the Tcl FFI, which is simple but limited because all data is represented as strings, and the Python FFI, which is powerful, but difficult to use (an unsuitable for multi-threaded programs) because of reference counting. Why were the socket functions coded using vm extensions in stead of foreign functions? How does a C function create an manipulate objects in the VM heap? Since the heap "address" of an object can change during garbage collection, how does a C object refer to a scheme stob?
http://www.w3.org/People/Connolly/technologies/scheme48-review.html
crawl-002
refinedweb
1,069
64.61
Control fit-statUSB devices Project description pystatusb Control a fit-statUSB from python The statUSB is a tiny, USB LED that can be set display various colors and sequences. This library allows easy control of it from python. Use one of the simple helpers to set a color or sequence. After sending the configuration, the device will keep it without the python program running, and persist until a different color command is sent or the device is unplugged. from pystatusb import StatUSB, Colors led = StatUSB() # Auto-detect the device led.set_transistion_time(200) # Set the fade time to 200ms between each color led.set_color_rgb(0xff0000) # 100% bright red led.set_color(Colors.VIOLET, 20) # 20% bright violet led.set_sequence("#0000FF-0500#00FFFF-0250#000000-0250") # Blue for 0.5 sec, cyan for 0.25 sec, off for 0.25 sec Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/pystatusb/
CC-MAIN-2021-21
refinedweb
167
60.11
Notes: public interface PlanetMBean { public int getMercury(); public String getVenus(); public void setVenus(String x); public BigInteger getEarth(); public void setEarth(BigInteger x); public boolean isMars(); public double getJupiter(); public byte getSaturn(); public short getUranus(); public void setUranus(short x); public long getNeptune(); public void neptune(); public void uranus(int x); public int saturn(int x, int y); public short jupiter(int x, long y, double z); public void mars(boolean x); public BigInteger earth(); public String venus(); public int mercury(); } As you can see, it defines a set of attributes and operations with random types, but names in a very definite and familiar order. If we create a Standard MBean like this, using JDK 5.0, then it will look like this in JConsole. However, if we run the same program on JDK 6, then it looks like this: Observe that the planets are no longer in astronomical order, but in alphabetical order. Aside: what about Pluto? You might have noticed that I omitted Pluto from my list. That's because Pluto is not a Planet. A rare victory in the ongoing and hopeless war against Stupidism was won earlier this year when theInternational Astronomical Union voted to recognize logic and common sense and ignore inertia, nostalgia, and welearneditinschoolsoitmustbetrueforeveria. More details than anyone could possibly want to know are inWikipedia. Beyond just astronomical reality, computer scientists will surely be happier that there are eight planets, divided into four big ones and four small ones, and with each group of four further divisible into two big and two small. Or maybe that's just me. It turns out that this reordering is an unintended side-effect of myrewrite of the MBean Server internals. I had intended to preserve the order from the MBean interface, but in a moment of distraction I used aTreeMap instead of aLinkedHashMap. Nothing in the JMX specification requires that attributes and operations in a Standard MBean appear in the same order in theMBeanInfo as they do in the MBean interface, so none of our automated tests check that. We only discovered it recently, as a side-effect of some unrelated tests being coded by one of our Quality Engineers, Sandra Lions. Sandra loggedbug 6486655 to track this. This looks like something we would obviously want to fix, right? Perhaps you thought carefully about the order you want to present your attributes in, and followed that order in your MBean interface. Perhaps you want to group related operations together, for example addThingy() followed immediately by removeThingy() (example due toDaniel Fuchs). So, since I broke it, I started the process of fixing it. The fix itself is completely trivial - just replace two TreeMaps with LinkedHashMaps. But then things got interesting. The JDK has a clearly-defined engineering process. One rule in that process is that every time we fix a bug, there must be a regression test that fails without the fix and passes with the fix. So I duly coded a regression test. It was pretty much what you would expect. In outline: public class MethodOrderTest { public static interface PlanetMBean { ...same as above... } private static final String[] planets = { "mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune" }; public static void main(String[] args) throws Exception { ...create a Standard MBean using the PlanetMBean interface... MBeanInfo mbi = ...the MBeanInfo of this MBean...; MBeanAttributeInfo[] mbais = mbi.getAttributes(); ...check that mbais[] is in the same order as planets[]... MBeanOperationInfo[] mbois = mbi.getOperations(); ...check that mbois[] is in the opposite order as planets[]... } } After fixing the usual stupid mistakes in the test, the attribute check passed. But the operation check failed! What was different about operations? I went back and looked at the introspection code but could see nothing. What's more, the order the operations were appearing in was surprising. I would have understood if they were in alphabetical order. That would have meant that something else besides the TreeMaps I had removed was causing them to be sorted. But the operations were in astronomical order, from Mercury to Neptune, even though the interface declared them in reverse astronomical order, from Neptune to Mercury. What could be reversing them? I won't get into the details of the painstaking investigation that followed. Suffice it to say that I ended up boiling the test failure down to this program: public class MethodOrderTest { public static interface PlanetMBean { ...same as above... } private static final String[] planets = { "mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune" }; public static void main(String[] args) throws Exception { System.out.println(Arrays.asList(PlanetMBean.class.getMethods())); } } Notice that there's no JMX stuff at all here. It's just a call to the Reflection API. And it shows the methods in the following order: [public abstract int MethodOrderTest$PlanetMBean.mercury(), public abstract java.lang.String MethodOrderTest$PlanetMBean.venus(), public abstract java.math.BigInteger MethodOrderTest$PlanetMBean.earth(), public abstract void MethodOrderTest$PlanetMBean.mars(boolean), public abstract short MethodOrderTest$PlanetMBean.jupiter(int,long,double), public abstract int MethodOrderTest$PlanetMBean.saturn(int,int), public abstract void MethodOrderTest$PlanetMBean.uranus(int), public abstract void MethodOrderTest$PlanetMBean.neptune(), public abstract int MethodOrderTest$PlanetMBean.getMercury(), public abstract java.lang.String MethodOrderTest$PlanetMBean.getVenus(), public abstract void MethodOrderTest$PlanetMBean.setVenus(java.lang.String), public abstract java.math.BigInteger MethodOrderTest$PlanetMBean.getEarth(), public abstract void MethodOrderTest$PlanetMBean.setEarth(java.math.BigInteger), public abstract boolean MethodOrderTest$PlanetMBean.isMars(), public abstract double MethodOrderTest$PlanetMBean.getJupiter(), public abstract byte MethodOrderTest$PlanetMBean.getSaturn(), public abstract short MethodOrderTest$PlanetMBean.getUranus(), public abstract void MethodOrderTest$PlanetMBean.setUranus(short), public abstract long MethodOrderTest$PlanetMBean.getNeptune()] OK. So the getters and setters appear in the same order as in the interface, but the other methods have been reordered and appear earlier. Does reflection treat getters and setters differently from other methods? What on earth...what the devil is going on? The next, surprising step is to comment out the definition of the planets[] array. Lo and behold, the methods are now printed out in the same order as they appear in the interface! Further investigation shows that if I include just the strings "mercury", "venus", "earth" in the planets[] array, then the three methods mercury, venus, earth appear first in the list, and the remaining methods appear in the same order as in the interface. If we go back and look at the documentation forClass.getMethods(), we learn that "the elements in the array returned are not sorted and are not in any particular order". I had read that text long ago, but I had also observed that in practice the elements were in the order that the methods were declared in the class. So I wasn't too uneasy about assuming they would be. But the investigation above shows that this assumption is false. In fact, the order of methods is the order in which the JVM first encountered the method name strings. If your interface has methods called mercury and venus, then that will often be the first time the JVM is seeing those strings, especially in small test programs trying to determine how Class.getMethods() behaves. So the Method[] array will have the methods in the same order as in the interface. But if you have previously loaded another class that also has those method names, or even that happens to contain those names as string constants, then the order will be determined by that other class and could be completely different! The implications are wide-ranging. In particular,JUnit runs the various testFoo() methods in a class in the order that they show up in Class.getMethods(). It's good practice to write tests so that they work no matter what order they are run in - in fact it's vital because you don't know what that order will be. It turns out that this surprising order is recorded if you look very hard. For examplebug 4789197 includes the text "In the HotSpot VM, the order is actually dependent on the order in which the VM's UTF-8 constants are created, i.e., order will be different if a program loads other classes which uses the same name-type id's in random order." Anyway, now I'm faced with a dilemma. I'd quite like to restore the previous behaviour of Standard MBeans, where attributes and operations show up in the same order as the methods in the MBean interface. Code that depends on this is surely broken, but code like JConsole that presents the attributes and operations in a user interface would surely be better served by this arrangement. Except that now I know that that order can be perturbed by unrelated classes that happen to be loaded earlier. Is it still worth trying to preserve this fragile order? I'd be interested in what people think. - Login or register to post comments - Printer-friendly version - emcmanus's blog - 2730 reads
https://weblogs.java.net/node/236578/atom/feed
CC-MAIN-2015-35
refinedweb
1,472
57.37
I recently started off learning Ruby using the version 1.8.4 of the Ruby interpreter. After some time spent on trying out different Ruby’s specific features I now may say that it has really impressed me. It’s fun and less coding than other programming languages which is what I’m looking for. However, there is something related to OO concepts that I think, in Ruby, is looking for troubles. More exactly, the encapsulation can be broken using reflection. Here is a piece of cod that illustrates this: class Song attr :count def initialize(name, artist, duration) @name = name @artist = artist @duration = duration @count = 0 end … def incCount @count += 1 puts @count end … private :incCount end song1 = Song.new(“Ruby Tuesday”, “ff”, 10) m = song1.method( :incCount ) 2.times do m.call puts “#”*5 end Suppose the variable @count is part of the internal state of the object and it should not be changed from outside the world. As you can see, I declared the method incCount private as it changes the object’s internal state But, surprise, the method is not quite genuine private. It can be called outside the class using reflection. My question is if it’s OK to let code outside the class to change the internal state of an instance of that class? I mean why should we bother making methods private in the first place if they can be called outside the class anyway? Is it a known behaviour or it has just gone unnoticed so far?
https://www.ruby-forum.com/t/reflection-brakes-encapsulation/96537
CC-MAIN-2022-05
refinedweb
255
73.07
I have been killing myself trying to get Meteor to do what I can do on Nodejs. all I want to do is upload files to my public folder. I can do it if I run Nodejs alone. but can’t get the same functionality from meteor. Meteor is making my work harder. I don't want to use a collection like CollectionsFS (dead or will be dead.) If anyone knows how to get files uploaded into the public folder from a form or input, then please share with me. If I figure this out I will be posting it everywhere I can. there are no documents on the meteor site that touches this You do realize Meteor is built on Node, uses Node modules (that are available to you as well) and can run NPM packages right? Anything that you can do in Node, you can do in Meteor. You can also run an express server on a different port within the same process. I don't really understand. What's the issue? You can use WebApp.connectHandlers and npm formidable. WebApp.connectHandlers formidable See this code : import {Meteor} from 'meteor/meteor'; import {WebApp} from 'meteor/webapp'; import pathToRegexp from 'path-to-regexp'; import formidable from 'formidable'; import util from 'util'; import fs from 'fs'; import path from 'path'; WebApp.connectHandlers.use('/', (req, res, next) => { const matchPath = matchPathFactory(req); if (matchPath('/server/upload')) { const form = new formidable.IncomingForm(); form.parse(req, (err, {namespace, status = 'new'}, files) => { //Here, we already have the files. //Then save your files to your folder. saveFilesToFolder(files); }); } }); //If we just return matchPath, it doesn't work. //So we use this hack. function matchPathFactory(req) { if (req.keys || req.segments || req.params) { throw 'keys or segments or params already defined'; } return matchPath.bind(req); function matchPath(pattern) { if (this.url === undefined) { throw 'Please bind this to req'; } this.keys = []; this.segments = pathToRegexp(pattern, this.keys).exec(this.url); this.params = {}; if (this.segments && this.segments.length > 1) { this.keys.forEach((item, index) => { this.params[item.name] = this.segments[index + 1]; }); } return this.segments; } } function saveFilesToFolder(files){ //Code to save files to folder } Thank you for the helping hand. Had this same question. Thank you @agusputra for the lead. Basically, you can import Express, create a new express app instance, and pass it into WebApp.connectHandlers: ... import express from 'express'; const app = express(); WebApp.connectHandlers.use(app); ... In case it's helps, I wrote a tutorial about setting up Express within a Meteor app:
https://forums.meteor.com/t/meteor-express-should-work-the-way-nodejs-works-with-express/27578
CC-MAIN-2017-26
refinedweb
417
61.22
Type Design Guidelines in .NET From the CLR perspective, there are only two categories of types—reference types and value types—but for the purpose of framework design discussion we divide types into more logical groups, each with its own specific design rules. Figure 4. Extensibility and base classes are covered in Chapter 6. this book. Figure 4-1: The logical grouping of types 4.1. 4.1.1 Standard Subnamespace Names Types that are rarely used should be placed in subnamespaces to avoid cluttering the main namespaces. We have identified several groups of types that should be separated from their main namespaces. 4.1.1.1.
http://www.informit.com/articles/article.aspx?p=423349&amp;seqNum=7
CC-MAIN-2018-43
refinedweb
107
54.93
Talk:Code Completion Design Contents - 1 Should be added to the article page soon - 2 Parseth meet as follow: clear m_Str just clear the m_strbecause the parser believe the token has been recognized correctly . e.g. int a; delete . -> skip the tokens until it meet ; or } e.g. delete p; e.g. MyClass .fun(); e.g. MyClass->fun(); deal with { skip the context between { and } if the usebuffer or the bufferskipblock is true in the option. e.g. int main() {cout <<endl;} deal with } clear the scope and relation it belong to . : set the scope . while if do else for switch skip the context until it meet ;or } if the usebuffer or the bufferskipblock is true in the option. typedef call HandleTypedef to deal with it if the option handletypedef is true. otherwise,it will skip the context until it meet ;or } return : skip the context until it meet the ; or } const just clear th e m_str extern call DoParse if the next token is "c",otherwise,skip the context until it meet ; __asm skip the context until it meet ; static virtual inline do nothing # handle include if the next token is include handle define if the next token is define otherwise handle the preprocessor block using skip the context until it meet ;or } namespace skip context between < and > if the next token is < class handle class if the option handleclass is true.otherwise skip it struct the same to class enum the same to class untion skip the context until it meet }or; call DoParse to analyze the context in the untion. operator eg. MyClass operator () (size_t param); MyClass operator += (MyClass param); others It means that the current token is not any one above . According to the next token ,it can be divided into several situation as followed . 1) the next one's fisrt char is (. eg. Macro(a, b) fun(int a , int b); eg. e.g. MyClass MyClass ::fun() {} 6) ;
http://wiki.codeblocks.org/index.php?title=Talk:Code_Completion_Design&oldid=5978
CC-MAIN-2020-16
refinedweb
323
68.81
Hi, im writing a little app that will run a stroed procedure on my sql database and whip the results (a list of email addresses) in to a new mail items "to" box. I have my connection strings working and can extract the data fine. I can create the new mail item fine. What i cant do is the bit in the middle!! i need to take the results of the SP and populate them in to the "to" field of the mail item. I have tried various things with no sucess.. This is my code: namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click_1(object sender, EventArgs e) { #region SqlConnection conn = new SqlConnection("Data Source=LIVESERVER;Database=Live_DB;UID=admin;PWD=testing;"); SqlCommand command = new SqlCommand("SP_email_addresses", conn); SqlDataAdapter adapter = new SqlDataAdapter(command); DataSet ds = new DataSet(); adapter.Fill(ds, "emails"); this.dataGridView1.DataSource = ds; this.dataGridView1.DataMember = "emails"; conn.Close(); conn.Dispose(); Outlook.Application outlookApp = new Outlook.Application(); Outlook.MailItem message = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem); message.Subject = "System Message"; message.Recipients.Add(); message.Display(true); #endregion } as you can see there is nothing in "to()" as yet - i can figure out how to take the result of the SP and get them in here.. any help would be great. thanks!
https://www.daniweb.com/programming/software-development/threads/260514/taking-stored-procedure-results-as-string-in-to-interop-object
CC-MAIN-2017-43
refinedweb
219
50.43
Normal Distribution in C++ In this tutorial, we will learn about normal distribution and its implementation in C++. Before proceeding further let’s first understand what is a normal distribution. Normal Distribution: - It is a continuous probability distribution. - A continuous random variable X is said to follow the normal distribution with parameters μ (called mean) and σ² (called variance) if its probability density function is given by P(x)= (1/√2πσ²)* e-( x-μ )²/2σ² where μ is the mean of the distribution σ is the standard deviation and σ² is the variance. Note for implementation: - Make sure C++11 support is enabled in the compiler of your IDE. Otherwise, it will give you errors. I am using Dev C++ so I will tell you the steps of enabling c++11 support in Dev C++. These steps will be similar for other IDE. So the steps are as follows: 1) Go to file -> create new project 2) Select Empty Project 3) Type project name and click ‘ok’ 4) Type filename and click ‘save’ 5) Go to Project -> Project Options 6) Go to parameters tab and type “-std=c++11” under C++ compiler section. 7) Type and run the below code. - It is not necessary that you will get the same output that I have got. Each time when you run below code you will get different output (distribution). Program to implement Normal Distribution in C++ #include<iostream> #include<chrono> #include<random> using namespace std; int main() { /* Create random engine with the help of seed */ unsigned seed = chrono::steady_clock::now().time_since_epoch().count(); default_random_engine e (seed); /* declaring normal distribution object 'distN' and initializing its mean and standard deviation fields. */ /* Mean and standard deviation are distribution parameters of Normal distribution. Here, we have used mean=5, and standard deviation=2. You can take mean and standard deviation as per your choice */ normal_distribution<double> distN(5,2); int n; cout<<"\nEnter no. of samples: "; cin>>n; cout<<"\nNormal distribution for "<<n<<" samples (mean=5, standard deviation=2) =>\n"; for (int i=1; i<=n; i++) { cout<<i<<". "<<distN(e)<<"\n"; } return 0; } Input/Output: Enter no. of samples: 10 Normal distribution for 10 samples (mean=5, standard deviation=2) => 1. 6.01492 2. 7.18826 3. 4.44432 4. 6.03708 5. 5.93383 6. 4.43706 7. 8.45193 8. 3.75018 9. 1.58229 10. 4.0596 You may also learn:
https://www.codespeedy.com/normal-distribution-in-cpp/
CC-MAIN-2020-40
refinedweb
400
54.22
QMargins The QMargins class defines the four margins of a rectangle. More... #include <QMargins> This class was introduced in Qt 4.6. Public Functions Related Non-Members Detailed Description The QMargins class defines the four margins of a rectangle. QMargin defines a set of four margins; left, top, right and bottom, that describe the size of the borders surrounding a rectangle. The isNull() function returns true only if all margins are set to zero. QMargin objects can be streamed as well as compared. Member Function Documentation QMargins::QMargins () Constructs a margins object with all margins set to 0. QMargins::QMargins ( int left, int top, int right, int bottom ) Constructs margins with the given left, top, right, bottom See also setLeft(), setRight(), setTop(), and setBottom(). int QMargins::bottom () const Returns the bottom margin. bool QMargins::isNull () const Returns true if all margins are is 0; otherwise returns false. int QMargins::left () const Returns the left margin. int QMargins::right () const Returns the right margin. void QMargins::setBottom ( int bottom ) Sets the bottom margin to bottom. void QMargins::setLeft ( int left ) Sets the left margin to left. void QMargins::setRight ( int right ) Sets the right margin to right. void QMargins::setTop ( int Top ) Sets the Top margin to Top. int QMargins::top () const Returns the top margin. Related Non-Members bool operator!= ( const QMargins & m1, const QMargins & m2 ) Returns true if m1 and m2 are different; otherwise returns false. bool operator== ( const QMargins & m1, const QMargins & m2 ) Returns true if m1 and m2 are equal;
https://developer.blackberry.com/native/reference/cascades/qmargins.html
CC-MAIN-2015-18
refinedweb
253
59.3
for connected embedded systems MsgSendvnc(), MsgSendvnc_r() Send a message to a channel (non-cancellation point) Synopsis: #include <sys/neutrino.h> int MsgSendvnc( int coid, const iov_t* siov, int sparts, const iov_t* riov, int rparts ); int MsgSendvnc_r( int coid, const iov_t* siov, int sparts, const iov_t* riov, int rparts ); Arguments: - coid - The ID of the channel to send the message on, which you've established by calling ConnectAttach(). - siov - An array of buffers that contains the message that you want to send. - sparts - The number of elements in the siov array. - riov - An array of buffers where the reply can be stored. - rparts - The number of elements in the riov array. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The MsgSendvnc() and MsgSendvnc_r() kernel calls send a message to a process's channel identified by coid. These functions are identical except in the way they indicate errors. See the Returns section for details. The number of bytes transferred is the minimum of that specified by both the sender and the receiver. The send data isn't allowed to overflow the receive buffer area provided by the receiver. The reply data isn't allowed to overflow the reply buffer area provided. The sending thread becomes blocked waiting for a reply. If the receiving process has a thread that's RECEIVE-blocked on the channel, the transfer of data into its address space occurs immediately, and the receiving thread is unblocked and made ready to run. The sending thread becomes REPLY-blocked. If there are no waiting threads on the channel, the sending thread becomes SEND-blocked and is placed in a queue (perhaps with other threads). In this case, the actual transfer of data doesn't occur until a receiving thread receives on the channel. At this point, the sending thread becomes REPLY-blocked. MsgSendv() is a cancellation point for the ThreadCancel() kernel call; MsgSendvvnc() and MsgSendvnc_r() functions is the way they indicate errors: - MsgSendvnc() - - MsgSendvINTR - The call was interrupted by a signal. - ESRCH - The server died while the calling thread was SEND-blocked or REPLY-blocked. - ESRVRFAULT - A fault occurred in a server's address space when accessing the server's message buffers. - ETIMEDOUT - A kernel timeout unblocked the call. See TimerTimeout(). Classification: See also: ConnectAttach(), MsgReceive(), MsgReceivev(), MsgReply(), MsgReplyv(), MsgSend(), MsgSendnc(), MsgSendPulse(), MsgSendsv(), MsgSendsvnc(), MsgSendv(), MsgSendvs(), MsgSendvsnc(), TimerTimeout()
http://www.qnx.com/developers/docs/6.3.2/neutrino/lib_ref/m/msgsendvnc.html
crawl-003
refinedweb
401
55.84
Hi, Okay, I really need help with this program please... I have to create a program which; Contains a function called sumN() which takes an int n as an argument and returns an int which is the sum of all integers between 1 and n. In the main() it asks the user; How many values (s)he wants to enter (maximum 50); Asks for the values and stores them into an array int a[]. Prints to the console sumN(a) for all the elements of a[] that have been entered by the user. I've started it, but I don't know how to do the rest because I'm sooo confused. Here's what I have so far; #include <iostream> using namespace std; int main() { double temp, set[50]; int size, t, i,]; cout << "Here are your values:\n"; for (t=0; t<size; t++) cout << set[t] << "\n"; return 0; } I'd be very grateful if someone could help me as soon as possible! Thanks :)
https://www.daniweb.com/programming/software-development/threads/325255/arrays-with-sums
CC-MAIN-2018-30
refinedweb
167
70.67
13 April 2012 03:52 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The exact restart date has yet to be finalised, he added. The state-owned refining firm was earlier forced to shut the cracker following a pipeline leak that led to an explosion at the site. Following the outage, CPC had raised the operating rate at its two other naphtha crackers in Linyuan to 100% capacity, the same source said ealier. The 230,000 tonne/year No 3 cracker and 385,000 tonne/year No 4 cracker are currently running at full rates compared with 85% capacity prior to the outage. CPC was also forced to reduce ethylene and propylene supplies to domestic customers in the wake of the unplanned shutdown. However, the company did not import any ethylene and propylene spot cargoes to make up for the shortfall,
http://www.icis.com/Articles/2012/04/13/9549941/taiwans-cpc-eyes-kaohsiung-cracker-restart-next-week.html
CC-MAIN-2013-48
refinedweb
140
60.75
Tutorials > C++ > References A reference is basically an alias for a variable. It allows more than one variable to reference the same piece of data in memory or on the stack. Pointers point to a part of memory. A pointer is a memory address. A reference is an actual variable and can be used without dereferencing the variable. References take the form : data type &variable name; Contents of main.cpp : #include <iostream> #include <stdlib.h> using namespace std; int main() { In our example below, a reference y is created and is made to reference x. A reference can only be set to reference a variable when it is declared. In other words, y can now not be used to reference any other variable but x. int x = 5; int &y = x; int z = 20; We now increase x by 10. When printing out the values of x and y, we find that they both equal 15. This is because they both reference the same data in memory. If you change the value of one, you change the value of the other. x += 10; cout << "x : " << x << endl; cout << "y : " << y << endl; Remember me saying that a reference can never reference another variable? In the example below, z is assigned to y. This does not make y reference z. It only assigns the value of z to y. Because y references x, x now also has the value of z. y = z; cout << "x : " << x << endl; cout << "y : " << y << endl; To try and make things more clear, you can output the memory address of each variable. You will notice that x and y reference the same memory address where z has a different memory address. This strongly shows how references work. cout << "x addr : " << &x << endl; cout << "y addr : " << &y << endl; cout << "z addr : " << &z << endl; system("pause"); return 0; } You should now have a basic understanding of what references are and how they can be used. You may also be wondering why you would ever need references. An example is shown in the next tutorial. Please let me know of any comments you may have : Contact Me Back to Top Read the Disclaimer
http://www.zeuscmd.com/tutorials/cplusplus/22-References.php
CC-MAIN-2015-18
refinedweb
363
74.39
> module Control.Hmk.Concurrent where > > import {-# SOURCE #-} Control.Hmk > import Control.Concurrent > import Control.Monad.State > import Control.Applicative > import qualified Data.Map as MapMap the dependency graph to a tree of concurrent threads, where each thread encapsulates a recipe to execute after having waited for the completion of the threads of each prerequesite. It is up to the runtime to schedule the execution of the threads as it best sees fit. However, interleaving the execution of potentially many thousands threads simultaneously, which are usually all I/O bound, is a bad idea. So we do enforce some rate limiting of the number of threads that can run simultaneously by making all threads wait on the same quantity semaphore. The quantity semaphore can be thought of as making available a fixed amount of slots. So long as slots remain, threads may take a slot and run. But if slots run out, the remaining threads must wait until existing threads have finished their job. Because one cannot wait for a thread to finish directly, we signal job completion by means of MVar's. A finished thread writes some inessential value to its MVar, which unblocks threads waiting on that MVar. Note that there are two distinct monadic levels here. One level is the IO monad to which a state transformer is applied. This level constructs and combines monadic values that form the process tree. This process tree is then pulled out of the state transformed IO monad and executed. > data Done = Done > > processTree :: (Ord a, Show a) => Int -> DepGraph IO a -> IO () > processTree slots gr = do > sem <- newQSem slots > join $ evalStateT (sequence_ <$> mapM (aux sem) gr) Map.empty > where aux sem (Node x ps rule) = do > ws <- mapM (wait sem) ps > signal <- liftIO $ newEmptyMVar > modify (Map.insert x signal) > return $ do > sequence ws > waitQSem sem > result <- maybe (return TaskSuccess) ($ prereqs rule) (recipe rule) > case result of > TaskSuccess -> do > signalQSem sem > putMVar signal Done > TaskFailure -> error $ "Recipe for " ++ show x ++ " failed." > wait sem n@(Node x _ _) = do > seen <- get > case Map.lookup x seen of > Just signal -> return $ do > readMVar signal > return () > Nothing -> do > work <- aux sem n > signal <- (Map.! x) <$> get > return $ do > tid <- forkIO work > readMVar signal > killThread tid
http://hackage.haskell.org/package/hmk-0.9.7.1/docs/src/Control-Hmk-Concurrent.html
CC-MAIN-2015-35
refinedweb
371
64.81
could you check my code to see if I have everything set up correctly Why do you have two routers? good question. i thought links and routers needed to both be wrapped by routers. i guess ill put the router higher up in the components app.js nav bar yup still nothing i added it to app.js and removed from main and nav yeah, wrap all your <Route /> tags in one place of your project, typically all under the <BrowserRouter />, links can be then used in any of your other components to access the routes you set up in your main file , example: import { Link } from 'react-router-dom' <Link to="/about">About</Link> where /about would be defined and linked to the component in your main router definition they have pretty good docs this is the doc that im following. could you give my code a look over and let me know exactly what wrong? In main.js try adding exact to line 18: <Route path="/" exact component={Intro} /> This worked. any idea why or what exact does? -edit- exact: bool When true , will only match if the path matches the location.pathname exactly . Actually it’s this one: next issue is can I switch to a new page without changing the url? I guess you could use render in the <Route/> instead of component and render component conditionally: render or component makes no difference im gonna try adding some GET requests for those url’s in the server but I know there must be a nicer way. All I want to do is click on a nav button and change the page keeping the components in the same order yup that’s what i had to do and it works for every url. i wish i didn’t have to touch the server By doing this you made the use of react router useless. yeh so how can i reload my page from a link other than "/". without the change then if im at "/about" then it wont render to the browser. how do i fix that without messing with the server? Your server should have one route: app.get('*', (req, res) => { res.render('index', data); }); last thing (probably not), I can’t get my favicon to work i have the link commented out in the index file but that tag doesnt work anyway. any idea why? Favicon should be in public still doesn’t work both my viewsand public folder get served so it shouldn’t have mad a difference anyway
https://forum.freecodecamp.org/t/why-is-my-react-router-not-working/257114
CC-MAIN-2021-10
refinedweb
425
77.27
I am trying to link FMOD to my project, which I did very easily in the past in Visual Studio 2008…. I am re using the same files that I had in said project, I’m wondering if that’s maybe the problem (incompatible with VS2010?)… So I have placed the fmodex_vc.lib and the fmodex.dll file in my project directory, added them to my project’s solution explorer, then created a SoundMgr.h file which includes the fmod.h file include "include\fmod\fmod.h" Where fmod.h has been placed in the include\fmod folder and opens ok if i right click on the above code and click "Open Document"… But if I try to write any code at all, including a simple "using namespace FMOD" it tells me that it FMOD is undeclared or unidentified….And any sample code simply wont be recognised…. am I missing any step? - neo187 asked 5 years ago - You must login to post comments Right so I eventually fixed it by removing the Additional Dependency in the Input section of the Linker and instead adding Include and Library directories in in Configuration Properties\VC++ directories…. Most articles I found advise to use the actual full path to the FMOD installation folder, but since I want this project to be portable and self contained, i created a "lib" and "include" folder in my project and put those files in them… (used the directories "\lib" and "\include" in the project properties which I am assuming links to the project folder, have never done this before but am hoping it won’t cause dependency issues if I compile this on a different machine)… And on top of this I’ve added the .dll to the project root folder and now it compiles ok! - neo187 answered 5 years ago
http://www.fmod.org/questions/question/forum-36864/
CC-MAIN-2017-13
refinedweb
304
68.91
I once did an experiment to see how easy I could wrap HTMLUnit with Selenium for automated software testing. In my experiment I created a wrapper by extending the DefaultSelenium class and then using eclipse to create wrapper functions for all the methods. Then inject that HTMLUnitSelenium class into my abstraction layer and voila - your Selenium tests run with HTMLUnit (*cough* well, in theory). Then I recently discovered that someone else had done the same thing. Frank Cohen, at a recent workshop, mentioned a wrapper that already existed in PushToTest. So I hunted it out, and I tried to use it... Please Explain HTMLUnit?HTMLUnit acts a 'headless' browser - a browser without a renderer - which lets you test the functionality of a website without necessarily testing the visual aspects. By having a wrapper I could run tests quickly without having to amend the tests just by creating an HTMLUnit browser. Where Do I get the wrapper?I did a Google search and found the original code created by Denali. Denali passed this code over to PushToTest to productionize, and it now forms part of the PushToTest distribution. So you can either checkout the whole code base from svn: Or install push to test and use the selenium-ptt.jar from the lib folder. Add the HtmlUnit jars to your project and the selenium-ptt.jar to your project How do I use it? import be.denali.test.SeleniumHTMLUnit;Easy! // And instead of creating a normal Selenium object // Do the following public static SeleniumHTMLUnit selSession = null; selSession = new SeleniumHTMLUnit(); // Then use selSession as normal // If you built it yourself from the source then you also // generated extensive JavaDocs during the build process Warning Possible Fixes RequiredSadly just downloading this and incorporating it into your project doesn't guarantee a complete instant Selenium wrapper. If you scan the source then you will see a few "Action not implemented" e.g. openWindow - but if the actions you want to use do exist then you can quickly run your selenium tests against HTMLUnit. Contributing some incomplete methods would seem a really useful way to add back to the open source project. public void answerOnNextPrompt(String answer) { // TODO Auto-generated method stub logger.warning("Action not implemented: answerOnNextPrompt"); } But you can easily scan your source code and check if any of the ones that you rely on have already undergone some implementation work. I found that most of the methods that I really needed did have implementations. Those that did not have implementations did not really matter to me because HTMLUnit works slightly differently to Selenium, and I could amend my abstraction layer to compensate. Things I had to do to get it working that you may not need to - Resolve a Rhino conflict - Stop using DefaultSelenium - Stop using openWindow Resolve a Rhino conflictEvery time I ran it I received a missing method exception from Rhino (The Javascript interpreter that HTMLUnit uses). Upon typing the error message into Google I discovered that I had a Rhino conflict from one of the other things in my classpath. So I did what I should have done ages ago and cleared out a whole bunch of extraneous jars that we inherited from the development team. Quite what caused the conflict I did not find out since I did not take a disciplined approach to removing the items from the classpath - I just wanted the darn thing to start working - I'll have to go back later and find that out. Stop using DefaultSeleniumWe used the DefaultSelenium in our tests at work, so I amended our abstraction layer use: seleniumSession = new SeleniumHTMLUnit() ; seleniumSession.setBaseURL("..."); Stop using openWindowSeleniumHTMLUnit has an incomplete implementation of openWindow. Rather than add additional code to SeleniumHTMLUnit (because I tried to get something up and running quickly) I changed my abstraction layer to use open instead of openWindow. Good to GoI had my tests running quickly, and using HTMLUnit. ...and failing. HTMLUnit displays more warning messages about your html pages than Selenium does so you can find errors on your site by reading the HTMLUnit logs that you would not find by using Selenium or reading the Selenium logs. Not Quite The Same Behaviour Out of the BoxNote: see Frank's comment below for workarounds for my next point. HTMLUnit as a direct plug-in replacement for Selenium didn't work straight out of the box in terms of behaviour. After running my tests using HTMLUnit instead of Selenium - a few more failed than normal, reasons for this: - Selenium forgives (because the browser forgives) if your page has missing javascript files, but HTMLUnit throws an exception if your webpage has a missing .js file. So some of my tests failed on opening a page. In some ways this helped me as it identified a misconfiguration between production and test. In other ways it does not help because Selenium does not pick up this error so a test that runs in Selenium does not run using HTMLUnit. - Calling a selSession.check on a checkbox works in selenium but not in HTMLUnit "java.lang.ClassCastException: com.gargoylesoftware.htmlunit.html.HtmlRadioButtonInput cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput at be.denali.test.SeleniumHTMLUnit.check(SeleniumHTMLUnit.java:727)". Since my usage of .check passes in Selenium I consider this a bug in SeleniumHTMLUnit, but since SeleniumHTMLUnit runs as an Open Source project I can raise this in their Trac system, or contribute a fix. - Other errors I found appear related to timing issues due to HTMLUnit working slightly differently than Selenium. I need to investigate this further. But Why would you want to do this?Well, Selenium does run quite slowly. And not all tests really need to run in a 'real' browser to add some valuable feedback. Ideally I would like a subset of basic tests that run on the Continuous Integration server without compromising the integrity of that box by spawning a slew of browsers. Currently we have a set of Hudson slaves and run the test on 'other' boxes, or just trigger the tests manually on our local desktops. Having Selenium tests run quickly on the same server as part of the build seems like a really useful goal to aim for. So what next?Obviously I just spent an couple of hours hacking around but the basic principle of a Selenium HTMLUnit abstraction seems sound - at least to me. SeleniumHTMLUnit really impressed my since all my tests ran, and that I didn't have to build this abstraction layer myself (I can score it off my todo list now). I will definitely add this to my abstraction layer. I will immediately create a testNG group for SeleniumHTMLUnit tests that cover basic page structure and link checking since these run much faster in SeleniumHTMLUnit than Selenium, and these don't really need to run cross browser as much. If I have to amend SeleniumHTMLUnit to get my tests working fully then I shall certainly contribute my code to the PushToTest team. The PushToTest development team, and Denali team, responded really quickly to some out of the blue emails I sent and answered some questions I had and pointing me to the up to date code base. Hopefully this post achieves a 2 goals: - makes it even easier for anyone else to investigate this really important wrapper. - makes more people aware of this hidden gem inside the PushToTest source code - I wonder what else they have hidden in there? Try it out for yourself and get some headless tests going. Great write-up. HTMLUnit 2.3 offers some utility APIs to handle the missing JavaScript files in the WebClient API. We find these all the time in our customer's sites. We added the following commands to TestMaker. These are in the 5.3 code base: loglevel = "off", "info", "debug" controls the Selenium HTMLUnit logging throwExceptionOnFailingStatusCode, when set to true HTMLUnit will ignore errors when the source of an external script cannot be loaded throwExceptionOnScriptError, when set to true HTMLUnit will ignore JavaScript? execution errors -Frank Thanks Frank - now I have to do even less to improve the abstraction layer :) This looks promising. I'm at a project where we want to migrate lots of existing Selenium tests (in HTML format) to HTMLUnit. I'll use this code as a basis, and also add a HTML parser that can parse Selenium HTML tests and invoke the com.thoughtworks.selenium.Selenium API. In practive the instance will be be.denali.test.SeleniumHTMLUnit. For the HTML parsing I might base some of the code on In order to be able to commit my work, I might put this up on a Git repository - probably at GitHub. Send me an email if you want to discuss this further. Whoa - before doing that - consider that PushToTest already has a Selenese parser in it, you might be able to just use PushToTest out of the box - we don't write our Selenium tests in Selenese so I had to dig into the source to get the part I needed - you might find PushToTest an even easier solution.
http://blog.eviltester.com/2008/12/selenium-and-htmlunit-the-abstraction-layer.html
CC-MAIN-2017-26
refinedweb
1,516
51.68
Creating a Hovering Control Posted by Gilad Novik on November 5th, 2002 Environment: VC6 SP5, WIN2K SP2 This is a template class for creating hovering controls. It uses the _TrackMouseEvent method to recieve notifications regarding mouse events. In the demo project, I've created two simple classes; one is derived from CButton and the other one is derived from CEdit. They both react to mouse events. #include "TrackControl.h" class CHoverButton : public CTrackControl<CButton> { public: virtual void OnHoverEnter() { Invalidate(); } virtual void OnHoverLeave() { Invalidate(); } } DownloadsDownload demo project - 24 Kb Download source - 1 Kb it's awesome!Posted by Legacy on 01/07/2004 12:00am Originally posted by: jjm simple but works fine!Reply _TrackMouseEvent() is not Win95 compliant.Posted by Legacy on 04/27/2003 12:00am Originally posted by: Mouse Controls that use _TrackMouseEvent() fail when run on Windows95. The best way to go about catching a "MouseLeave()" event is to use set a timer on the MouseOver event and use WindowFromPoint() API on the timer fire to check if it is still over the control.
http://www.codeguru.com/cpp/controls/controls/article.php/c5321/Creating-a-Hovering-Control.htm
CC-MAIN-2017-09
refinedweb
177
53
JavaScript Stacked bar charts are charts with Y values stacked over one another in the series order. Shows the relation between individual values to total sum of the points.. Allows grouping a series with another series separately using a different group name. The stacked bar chart provides an option to customize spacing between two bars and the width of the bar. Modernize the UI by applying rounded corners to the stacked bar Customize the look and feel of the stacked bar chart using built-in APIs. import { Chart, StackingBarSeries, Category } from '@syncfusion/ej2-charts'; Chart.Inject(Chart, StackingBarSeries, Category); let chart: Chart = new Chart({ primaryXAxis: { valueType: 'Category' }, series:[{ type: 'StackingBar', dataSource: [ { x: '2014', y: 111.1 }, { x: '2015', y: 127.3 }, { x: '2016', y: 143.4 }, { x: '2017', y: 159.9 }], xName: 'x', width: 2, yName: 'y', name: 'UK' }, { type: 'StackingBar', dataSource: [ { x: '2014', y: 76.9 }, { x: '2015', y: 99.5 }, { x: '2016', y: 121.7 }, { x: '2017', y: 142.5 }], xName: 'x', width: 2, yName: 'y', name: 'Germany', }, { type: 'StackingBar', dataSource: [ { x: '2014', y: 66.1 }, { x: '2015', y: 79.3 }, { x: '2016', y: 91.3 }, { x: '2017', y: 102.4 }], xName: 'x', width: 2, yName: 'y', name: 'France', }, ], }, '#Chart'); <!DOCTYPE html> <html> <head></head> <body style = 'overflow: hidden'> <div id="container"> <div id="Chart"></div> </div> <style> #control-container { padding: 0px !important; } </style> </body> </html> Stacked Bar Chart User Guide Learn the available options to customize JavaScript stacked bar chart. Stacked Bar Chart API Reference Explore the JavaScript stacked bar chart APIs.
https://www.syncfusion.com/javascript-ui-controls/js-charts/chart-types/stacked-bar-chart
CC-MAIN-2020-45
refinedweb
255
77.64
Provided by: manpages-dev_4.16-1_all NAME iconv - perform character set conversion SYNOPSIS #include <iconv.h> size_t iconv(iconv_t cd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft); DESCRIPTION The VALUE The iconv() function returns the number of characters converted in a nonreversible way during this call; reversible conversions are not counted. In case of error, it sets errno and returns (size_t) -1. ERRORS The following errors can occur, among others: E2BIG There is not sufficient room at *outbuf. EILSEQ An invalid multibyte sequence has been encountered in the input. EINVAL An incomplete multibyte sequence has been encountered in the input. VERSIONS This function is available in glibc since version 2.1. ATTRIBUTES For an explanation of the terms used in this section, see attributes(7). ┌──────────┬───────────────┬─────────────────┐ │Interface │ Attribute │ Value │ ├──────────┼───────────────┼─────────────────┤ │iconv() │ Thread safety │ MT-Safe race:cd │ └──────────┴───────────────┴─────────────────┘ The iconv() function is MT-Safe, as long as callers arrange for mutual exclusion on the cd argument. CONFORMING TO POSIX.1-2001, POSIX.1-2008. NOTES. SEE ALSO iconv_close(3), iconv_open(3), iconvconfig(8) COLOPHON This page is part of release 4.16 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
http://manpages.ubuntu.com/manpages/cosmic/man3/iconv.3.html
CC-MAIN-2019-30
refinedweb
206
57.87
Formatting comments in the XML editor now adheres to two new preferences. The Format comments preference allows users to disable comment formatting entirely. The Join lines preference allows for comments to have their lines joined when a particular line's text does not exceed the maximum line width. These preferences can be accessed via the XML Editor's preference page. The XPath View now has the ability to select between XPath 1.0 and XPath 2.0 as the language to be used during evaluation of the expression. The XPath View for XPath 1.0 uses Xalan's XPath engine for evaluation. For XPath 2.0, the PsychoPath XPath 2.0 processor is used.' The XPath view now supports editing the namespace prefixes to be used during the evaluation of the expression. This provides the ability to assign xpath expressions to the default namespace as well as specify specific prefixes for various namespaces in an XML document used during the evaluation. The PsychoPath XPath 2.0 processor now supports the schema aware features of the ElementTest and AttributeTest during instance of evaluation. Back to the top
http://www.eclipse.org/webtools/development/news/3.2M5/sourceediting.php
CC-MAIN-2016-50
refinedweb
186
60.92
Hi, When I copy paste a text in the command prompt for one of the "cin" the text will gets in the other too and loops 3 or 4 times. Its a text without space so it shouldn't get fragmented. I tried to use cin.ignore(); and fflush(stdin); but it won't change a thing. What's happening here? Edit: apparently its the new line that causes it but wouldn't cin.ignore(); and fflush(stdin); should empty what's in "cin" ? Code:#include <string> #include <iostream> using namespace std; int main() { string response; char buf[1255]; while(1) { cin >> response; cout << "string: "<<response << endl; cin >> buf; cout << "buf: "<< buf << endl; } return 0; }
http://cboard.cprogramming.com/cplusplus-programming/153241-cin-plus-copy-paste.html
CC-MAIN-2013-20
refinedweb
115
83.76
The program below is supposed to calculate and show the time it takes for light to travel from the sun to the earth. It contains some logical errors. Fix the program so that it will compile and show the intended value when run. // Filename: Sunlight.java public class Sunlight { public static void main(String[] args) { // Distance from sun (150 million kilometers) int kmFromSun = 150000000; int lightSpeed = 299792458; // meters per second // Convert distance to meters. int mFromSun = kmFromSun * 1000; int seconds = mFromSun / lightSpeed; System.out.print("Light will use "); printTime(seconds); System.out.println(" to travel from the sun to the earth."); } public static void printTime(int sec) { int min = sec / 60; sec = sec - (min*60); System.out.print(min + " minute(s) and " + sec + " second(s)"); } } Create two method that both takes an int as an argument and returns a String object representing the binary representation of the integer. Given the argument 42, it should return "101010". The first method should calculate the binary representation manually, and the other should use the functionality available in the Java class libraries. Create a program that will print every other argument given on the command line. If the program was executed with the following on the command line, java ArgumentSkipper one two three a b c d the program would print one three b d Consider how your program would operate when no arguments are given.
https://etutorials.org/cert/java+certification/Chapter+3.+Operators+and+Assignments/Programming+Exercises/
CC-MAIN-2022-05
refinedweb
232
54.52
There's no one right way to style your React components. It all depends on how complex your front-end application is, and which approach you're the most comfortable with. There are four different ways to style React application, and in this post you will learn about them all. Let’s start with inline styling. Inline Styling React components are composed of JSX elements. But just because you’re not writing regular HTML elements doesn’t mean you can’t use the old inline style method. The only difference with JSX is that inline styles must be written as an object instead of a string. Here is a simple example: import React from "react"; export default function App() { return ( <h1 style={{ color: "red" }}>Hello World</h1> ); } In the style attribute above, the first set of curly brackets will tell your JSX parser that the content between the brackets is JavaScript (and not a string). The second set of curly bracket will initialize a JavaScript object. Style property names that have more than one word are written in camelCase instead of using the traditional hyphenated style. For example, the usual text-align property must be written as textAlign in JSX: import React from "react"; export default function App() { return ( <h1 style={{ textAlign: "center" }}>Hello World</h1> ); } Because the style attribute is an object, you can also separate the style by writing it as a constant. This way, you can reuse it on other elements as needed: import React from "react"; const pStyle = { fontSize: '16px', color: 'blue' } export default function App() { return ( <p style={pStyle}>The weather is sunny with a small chance of rain today.</p> ); } If you need to extend your paragraph style further down the line, you can use the object spread operator. This will let you add inline styles to your already-declared style object: import React from "react"; const pStyle = { fontSize: "16px", color: "blue" }; export default function App() { return ( <> <p style={pStyle}> The weather is sunny with a small chance of rain today. </p> <p style={{ ...pStyle, color: "green", textAlign: "right" }}> When you go to work, don't forget to bring your umbrella with you! </p> </> ); } Inline styles are the most basic example of a CSS in JS styling technique. One of the benefits in using the inline style approach is that you will have a simple component-focused styling technique. By using an object for styling, you can extend your style by spreading the object. Then you can add more style properties to it if you want. But in a big and complex project where you have a hundreds of React components to manage, this might not be the best choice for you. You can’t specify pseudo-classes using inline styles. That means :hover, :focus, :active, or :visited go out the window rather than the component. Also, you can’t specify media queries for responsive styling. Let’s consider another way to style your React app. CSS Stylesheets When you build a React application using create-react-app, you will automatically use webpack to handle asset importing and processing. The great thing about webpack is that, since it handles your assets, you can also use the JavaScript import syntax to import a .css file to your JavaScript file. You can then use the CSS class name in JSX elements that you want to style, like this: .paragraph-text { font-size: 16px; color: 'blue'; } import React, { Component } from 'react'; import './style.css'; export default function App() { return ( <> <p className="paragraph-text"> The weather is sunny with a small chance of rain today. </p> </> ); } This way, the CSS will be separated from your JavaScript files, and you can just write CSS syntax just as usual. You can even include a CSS framework such as Bootstrap in your React app using this approach. All you need to is import the CSS file into your root component. This method will enable you to use all of the CSS features, including pseudo-classes and media queries. But the drawback of using a stylesheet is that your style won’t be localized to your component. All CSS selectors have the same global scope. This means one selector can have unwanted side effects, and break other visual elements of your app. Just like inline styles, using stylesheets still leaves you with the problem of maintaining and updating CSS in a big project. CSS Modules A CSS module is a regular CSS file with all of its class and animation names scoped locally by default. Each React component will have its own CSS file, and you need to import the required CSS files into your component. In order to let React know you’re using CSS modules, name your CSS file using the [name].module.css convention. Here is an example: .BlueParagraph { color: blue; text-align: left; } .GreenParagraph { color: green; text-align: right; } import React from "react"; import styles from "./App.module.css"; export default function App() { return ( <> <p className={styles.BlueParagraph}> The weather is sunny with a small chance of rain today. </p> <p className={styles.GreenParagraph}> When you go to work, don't forget to bring your umbrella with you! </p> </> ); } When you build your app, webpack will automatically look for CSS files that have the .module.css name. Webpack will take those class names and map them to a new, generated localized name. Here is the sandbox for the above example. If you inspect the blue paragraph, you’ll see that the element class is transformed into _src_App_module__BlueParagraph. CSS Modules ensures that your CSS syntax is scoped locally. Another advantage of using CSS Modules is that you can compose a new class by inheriting from other classes that you’ve written. This way, you’ll be able to reuse CSS code that you’ve written previously, like this: .MediumParagraph { font-size: 20px; } .BlueParagraph { composes: MediumParagraph; color: blue; text-align: left; } .GreenParagraph { composes: MediumParagraph; color: green; text-align: right; } Finally, in order to write normal style with a global scope, you can use the :global selector in front of your class name: :global .HeaderParagraph { font-size: 30px; text-transform: uppercase; } You can then reference the global scoped style like a normal class in your JS file: <p className="HeaderParagraph">Weather Forecast</p> Styled Components Styled Components is a library designed for React and React Native. It combines both the CSS in JS and the CSS Modules methods for styling your components. Let me show you an example: import React from "react"; import styled from "styled-components"; // Create a Title component that'll render an <h1> tag with some styles const Title = styled.h1` font-size: 1.5em; text-align: center; color: palevioletred; `; export default function App() { return <Title>Hello World!</Title>; } When you write your style, you’re actually creating a React component with your style attached to it. The funny looking syntax of styled.h1 followed by backtick is made possible by utilizing JavaScript’s tagged template literals. Styled Components were created to tackle the following problems: - Automatic critical CSS: Styled-components keep track of which components are rendered on a page, and injects their styles and nothing else automatically. Combined with code splitting, this means your users load the least amount of code necessary. - No class name bugs: Styled-components generate unique class names for your styles. You never have to worry about duplication, overlap, or misspellings. - Easier deletion of CSS: It can be hard to know whether a class name is already used somewhere in your codebase. Styled-components makes it obvious, as every bit of styling is tied to a specific component. If the component is unused (which tooling can detect) and gets deleted, all of its styles get deleted with it. - Simple dynamic styling: Adapting the styling of a component based on its props or a global theme is simple and intuitive, without you having to manually manage dozens of classes. - Painless maintenance: You never have to hunt across different files to find the styling affecting your component, so maintenance is a piece of cake no matter how big your codebase is. - Automatic vendor prefixing: Write your CSS to the current standard and let styled-components handle the rest. You get all of these benefits while still writing the same CSS you know and love – just bound to individual components. If you’d like to learn more about styled components, you can visit the documentation and see more examples. Conclusion Many developers still debate the best way to style a React application. There are both benefits and drawbacks in writing CSS in a non-traditional way. For a long time, separating your CSS file and HTML file was regarded as the best practice, even though it caused a lot of problems. But today, you have the choice of writing component-focused CSS. This way, your styling will take advantage of React’s modularity and reusability. You are now able to write more enduring and scalable CSS.
https://www.freecodecamp.org/news/react-styled-components-inline-styles-3-other-css-styling-approaches-with-examples/
CC-MAIN-2020-29
refinedweb
1,491
62.98
Type on Your iPhone or iPad Using Your Mac Keyboard Your iPhone’s tiny screen doesn’t make for a great keyboard. Fortunately, you can use your MacBook or Apple keyboard to type on your iPhone or iPad, without wrestling with the touchscreen. With iOS 8, Apple finally introduced third-party keyboards for iPhones and iPads. Also, iPadOS has a flexible onscreen keyboard. No doubt, these options do make typing easier. But it still doesn’t match up to the experience of typing on your MacBook. What we are looking for here is a seamless shift between typing on your computer and typing on your phone or tablet. And they should work with any Mac keyboard, like some of the best wireless all-in-one keyboards. Connecting A Bluetooth Keyboard These apps function by posing as real Bluetooth keyboards, so it helps if you know how to connect a Mac to your iPhone or iPad. It’s pretty simple. - Click the Bluetooth icon in the customizable Mac Menu Bar and make sure Bluetooth is On. - On your iPhone or iPad, go to Settings > Bluetooth and switch it On too. You can also use Control Center (accessed by swiping up from the bottom of the screen) to access a Bluetooth toggle. - On your Mac, click the Bluetooth icon in your menu bar then Open Bluetooth Preferences > Pair. - You’ll get a confirmation message on your iPhone or iPad, tap “Pair” again. That’s it! Couldn’t be easier, right? Follow our Mac Bluetooth troubleshooting guide 7 Fixes When Bluetooth Is Not Available on Your Mac Is Bluetooth not available on your Mac? Here's how to troubleshoot Mac Bluetooth problems and get your devices working again. Read More if you have any trouble. 1Keyboard ($9.99) 1Keyboard is our favourite option for sharing your Mac’s keyboard with your iPhone. Install the app and it sits quietly in the Menu bar. It’s best to keep it there and have it become one of your favourite Mac Menu bar utilities. Connect your iPhone or iPad to your Mac via Bluetooth and 1Keyboard will recognise it. You can connect multiple devices too, and easily toggle between them using the menu bar icon. Click the menu bar item, select the device, and start typing. Your letters will show up on the selected device. Click somewhere on your Mac’s screen and start typing to switch back to the computer. It’s one of those “it just works” apps that is an absolute delight to use. 1Keyboard also adds the ability to copy and paste clipboard content to your touchscreen device. For example, if you copied a few lines of text online, you could press Shift+Command+V to paste it on your iPhone. It’s a nice useful feature, but not as powerful as other tools to share and sync the clipboard between iOS and Mac Sync Your Mac & iOS Clipboard With Command-C & Scribe Transferring the contents of your Mac's clipboard to your iPhone or iPad usually involves sending yourself an email or message, but that's cumbersome and inefficient. Read More . You can set a custom shortcut to activate 1Keyboard, as well as further shortcuts for each device, toggling between all as needed. Type2Phone ($5.99) In many ways, Type2Phone works like 1Keyboard. Download the app, connect your phone via Bluetooth, fire it up and start typing. It even automatically disconnects when not in use, and reconnects to the last device when you start using it. More importantly, Type2Phone offers a whole lot of control over Function keys and lets you set small key sequences, like deleting a word to the left or right of where your cursor is. You can already use Option+Backspace on your Mac keyboard, and now you can do the same on your iPhone. Neat! Of course, it’s not got the full power of all the , but it’s still pretty good. This app also includes voice dictation, but that doesn’t seem to be particularly useful, especially since Siri already does a fantastic job of it on iOS 8 Type Superfast With Real Time Voice Dictation in iOS 8 It's time to do less typing and more talking with the new real time voice-to-text feature in iOS 8. Read More . The only problem with Type2Phone is that it seems more intrusive than 1Keyboard, what with its floating window and the big icon sitting in your dock. What Should You Get? If you have a Mac and an iPhone or iPad, and if you type often on the latter, then these apps are worth it. For example, if you’re having a long conversation on WhatsApp, you’d be stuck. But while Android users can get WhatsApp on their PC, you can now use your Mac keyboard to type directly into WhatsApp on your iPhone or iPad. Of the two apps, my preferred choice is 1Keyboard, but that’s purely because of its unobtrusive nature. Type2Phone’s shortcuts and control over function keys seems like it might be the better tool for power users. And if you’re looking to turn things around, here’s how to remotely access your Mac from your iPhone How To Remotely Access Your Mac From Your iOS Device Read More . Image credit: Denys Prykhodov / Shutterstock.com Explore more about: Bluetooth, Keyboard. does the return key work? I paired my keyboard with my iPhone, but never was able to use the return (enter) key. So had to do it manually every time. Also when my iPhone's Bluetooth is on, I can not access the on-screen keyboard on my phone. Then I have to manually turn off my bluetooth Option 1 that you described didn't work. I got to paired the bluetooth but that's it... Never got the keyboard of my Mac to work with my iPad Layouts of 1keyboard are wrong. Money wasted.
https://www.makeuseof.com/tag/type-iphone-ipad-using-mac-keyboard/
CC-MAIN-2020-16
refinedweb
991
71.14
Testing is a very important process in the development cycle of an application. It is necessary to find out bugs which may be present in any program. Testing is largely the main process which ensures that a software developer or company is actually delivering a quality product to their client. Now, there are many frameworks used mainly for testing units of code. In this article, we will explore JUnit as a testing framework and how it can be implemented in a Java application. What is JUnit? JUnit is actually a very powerful testing framework meant for Java applications. JUnit puts an emphasis on testing before implementing the code. For this, the first task is to set up the testing environment for the code. After that, the coding part has to be implemented in the application. As every part of the program is tested and coded separately, the application developed runs quite efficiently. Also, debugging a program is much easier as every part of the code is separately checked for the presence of bugs. The JUnit framework is a part of a family of Java frameworks known as the xUnit. All the frameworks present in the xUnit are used for unit testing in Java. Background As already stated above, JUnit primarily happens to be a testing framework that’s meant for unit testing of code. It is also basically a framework that allows for test-driven development, i.e. the repetition of short development cycles, with the requirements being turned into exclusive test cases. JUnit was said to have been first developed in 1997. Kent Beck, Erich Gamma, David Saff and Mike Clark are credited with being the creators of this testing framework. The framework is a cross-platform framework that is written in Java and falls under the Eclipse Public License. It also happens to be one of the most commonly used frameworks for unit testing. Why JUnit is important? Unit testing is perhaps one of the most important ways that should be implemented to deliver quality software. It is basically meant to test code in way that allows the testing of each and every unit separately. As for JUnit, it is pretty much like every other testing framework, one that assists in finding bugs in code snippets. A unit testing framework ensures that each component of the complete software works optimally, which makes it very important in the development cycle of any software. However, it does not test the connection between different components, which is the case with integration testing frameworks. What are the features? There are many features of JUnit that we shall take a look at. - Firstly, it is a completely open-source project, so it can be used quite easily. - It uses Annotations which helps in the identifying the methods to be used in testing. - JUnit offers tests runners which are useful for running tests. - With JUnit, one can also make use of Assertions, in order to test expected results. - JUnit is very simple and allows very fast and flexible testing. - The tests running on JUnit can be scheduled to run automatically and then it checks and offers feedback on the tests too. - Tests in this framework can be converted into test suites that contain numerous test cases. It is also applicable for other test suites. - A green bar shows the progress of the test, which turns red on a failure. Pros and cons of using JUnit 1. What are the pros? JUnit is considered as one of the best testing frameworks for Java; so naturally, it has many pros. JUnit makes software testing very flexible. For example, if you make any kind of modification to a part of the code in the program, you can actually test if that code will run properly without even running the whole code. Also, you can create your own unit test case suite, in order to easily test similar programs. The unit tests made in JUnit are very light and can be adapted according to the code quite easily. Another thing is that it is extremely easy to use, even for beginners. 2. What are the cons? Every testing framework has some problems. The main problem in JUnit is the fact that it tests code by calling some methods and then it compares the outputs with those which should have come. While this may work perfectly with methods that return the outputs only, not all methods work in this way. For testing, if the methods actually carry out the output, you’ll have to capture them, and this is a really long piece of programming process. Another major con of JUnit is that for testing using methods that change the state of the object being tested, the code has to be adapted according to that state. Testing GUI code in units can be really hard. So, it is a good idea to write tests yourself for validating the objects. Installation and configuration As we have already discussed that JUnit is a testing framework for Java based applications, so JDK must be installed first. Let us check the configuration steps one by one. Step 1: Download and install Java Software Development Kit (SDK). The JDK version should be 1.5 and above. It can be downloaded from the following link. JDK down load link: Step 2: After download and installation, set up JAVA_HOME environment variable pointing to jdk version in your local file system. For example, JAVA_HOME = C:\Program Files\Java\jdk1.6.0_38 Step 3: Download JUnit and set up the environment. Latest version can be downloaded from the following link. JUnit download link: After this, set up JUNIT_HOME environment variable and point to the JUnit jar in your local system. For example JUNIT_HOME = C:\JUnit Now the environment setup is complete and we can run a sample Java application to test it. Sample application In this sample example, we will create a test unit class and a test runner class. Test runner class will check the test unit class and produce an output in Boolean value (true/false). Listing 1: Test unit class sample // This is the unit test class to be tested import org.junit.Test; import static org.junit.Assert.assertEquals; public class JunitTest { @Test public void testJunit() { String strtst= "Testing with JUnit is OK"; assertEquals("Testing with JUnit is OK",strtst); } } Listing 1: Test runner class to check the output //This is the test runner class import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class JUnitTstRunner { public static void main(String[] args) { Result tstresult = JUnitCore.runClasses(JunitTest.class); for (Failure tstfailure : tstresult.getFailures()) { //Printing output System.out.println(tstfailure.toString()); } //Printing output System.out.println(tstresult.wasSuccessful()); } } To test the result, first compile both the classes as shown below C:\JUNIT_TEST_WORKSPACE>javac JunitTest .java C:\JUNIT_TEST_WORKSPACE>javac JUnitTstRunner.java After this, execute the test runner class as shown below C:\JUNIT_TEST_WORKSPACE>java JUnitTstRunner The output will be displayed on the console as shown below. true Conclusion JUnit is a very powerful testing framework belonging to the xUnit family of unit testing frameworks developed for Java. It is really very useful for those developers using Java who want their program to be completely devoid of any kind of bug. JUnit is a unit testing framework, so it allows the testing of every snippet of code before even actually implementing it to the main application. This allows the developer to easily search for and resolve any kind of bugs, even if it is hidden deep inside the coding. Nowadays, more and more developers are using JUnit, not only for the ease of use but also because it does not produce any heavy strain on the system on which the code is being tested. Thus, it is one of the most popular unit testing frameworks for Java app development.
https://blog.eduonix.com/java-programming-2/learn-write-tests-using-junit/
CC-MAIN-2021-21
refinedweb
1,310
56.66
Is anyone available to help me? Type: Posts; User: Rain_Maker Is anyone available to help me? I just found out creating a giant array is not going to work per my professor???? :confused: I'm finding common elements in a collection of arrays. This is my code so far. import java.util.ArrayList; import java.util.List; public class CommonElements //< T extends... Why are you using Object class objects instead of the class that has the retrieveArray() method?[/QUOTE] My teachers wants us to use object Arrays for this assignment and compare them to a int... Could you elaborate on that? If I created my array objects shouldn't my data be recoverable from my objects? I'm not quite sure what I need to code. Norm, I was able to find my error in my syntax but I have another problem. I'm trying to use the compareTo method. I'm comparing an integer and another integer from an object array. If I try to... It located here....Don't know what else to really do..Should I move it?3194 Microsoft Windows [Version 6.0.6001] C:\Users\.....>cd Documents C:\Users\......\Documents>dir Volume in drive C has no label.... Let me try that....one moment please --- Update --- I just rqn my code via the command prompt.(Learned something new :cool:) C:\Users\......>javac Module5 error: Class names, 'Module5',... Norm, BlueJ will not allow me to copy the error message as text. I can only write out the error message or provide a screen shot. Is there anyway else to help. FYI I was able to rename my class... 3192 I'm using BlueJ as my IDE. So I hope this error message is able for you to answer my question. Hello Community, I'm working on an assignment for my data structure & algorithm class. My whole summer of not programming in java made me a extremely rusty. I need help creating an array of... Okay Thanks! Hello Everyone, I need help understanding on where I should be begin with this assignment my teacher gave me. I will be honest and drop the ball on doing this assignment. I also don't expect to... Well, I know you need to insert an object into the node lets say Node1. Node1 will have my data and a reference point which will point to null. Sense there is only node in the list. When I create... One of the main reason I'm having trouble understanding about this LinkList concept is iteration through the LinkList. It just a little hard for me to grasp. I know each node has reference to the... Hey I'm back. I made some progress. I know you told me not to use any type of counter but I'm just really stuck on the whole linklist concepts. I guess I'm thinking about arrays and array lists to... So what your saying is if I create null1 assigned to null and then create null2 and assign it to null. I can then use the "next" method to reference to my new null1 value to null2 value. Which will... Well if I do that will it be possible to iterator through my null list? I want to eventually add a remove method and some other methods. I just want to make sure I'm able to access the content of the... Hello Everyone, Thanks for the quick reply. KevinWorkman...I been drawing pictures and diagrams. I know what my end result is but I just don't know what to write in code correctly. int I =... public class LinkList { public class Node { public Node next; public Object data; Computer programmer teaches homeless to code Computer programmer teaches homeless to code - YouTube...
http://www.javaprogrammingforums.com/search.php?s=23dd6102fc3fdca83799411cca4f7937&searchid=1583614
CC-MAIN-2015-22
refinedweb
627
78.04
Install the J2SE JDK. See Java Development Kit (JDK). public class InitialTest { . . . } It must be saved in a file called InitialTest.java . Put it in the directory you created previously. There no critical preferences that need changing, but they can be set by selecting the Configure > Preferences menu item. Some things you might wish to set: Configure menu > Preferences... > Document Classes > Java > Tabulation Startupdirectory to where your files are normally located. Configure > Preferences... > Tools > Run Java Application. Set the value in the Parameters text field to -ea $BaseName. "-ea" is the abbreviation for Enable Assertions. If you don't know what assertions are yet, don't bother with this. A: When TextPad can't find the Java compiler, there are two common causes. C:\Program Files\Java\jdk1.5.0_04 There will also be a "JRE" (Java Runtime Environment), which is appropriate, but be sure there is a "jdk" (Java Development Kit). A: Check the Configure > Preferences > Tools > Compile Java > Parameters field. You only need $File in it. Reinstalling TextPad might clear it up. When I reinstall it I get the following. -Xlint:unchecked $File You don't need the -Xlint option (which notes situations where you could take advantage of Java 5 generics), but you do need the $File. Put blanks in front and after the $File value. Exception in thread "main" java.lang.NoClassDefFoundError: A: The most common cause at this point is that the file name doesn't match the class name. Make sure the names agree exactly first. Another, much less likely, problem could be that the parameters are set wrong in TextPad. Look at Configure menu > Preferences... > open Tools > Run Java Application. The Parameter field should have $BaseName (with blanks around it). You can skip the "-ea", which stands for "enable assertions". The Initial Folder should have $FileDir in it. A: No. TextPad translates the .java files into .class files which can not be run by double-clicking them. Some IDE's (eg, NetBeans) will produce double-clickable .jar files, and there are programs which will package your Java files into a .exe file.
http://www.roseindia.net/java/java-tips/background/30java_tools/50textpad.shtml
CC-MAIN-2013-20
refinedweb
349
69.99
So I'm programming another calculator, and this time I'm trying to do exponents (ex. 3^4=81). This program runs fine, but when I try to do the exponent, I get the wrong number. Usually it happens like this:This program runs fine, but when I try to do the exponent, I get the wrong number. Usually it happens like this:Code:#include <iostream> using namespace std; int main () { int w=1; do { cout << "\nEnter an expression.\n"; //instructions for the user cout << "Key: \n"; cout << "* = multiply\n"; cout << "/ = divide\n"; cout << "+ = add\n"; cout << "- = subtract\n"; cout << "^ = x to the yth power\n"; cout << "Enter your expression.\n"; int x,z; char y; cin >> x >> y >> z; //get the expression switch (y) { case '+': //calculate answer(s) cout << "The answer is " << x+z << ".\n"; break; case '-': cout << "The answer is " << x-z << ".\n"; break; case '*': cout << "The answer is " << x*z << ".\n"; break; case '/': cout << "The answer is " << x/z << ".\n"; case '^': for (z; z >= 2; z=z-1) { int Q; Q=x*x; } cout << "The answer is " << x << ".\n"; break; default : cout << "The expression is invalid.\n"; break; } cout << "To run function again, press 1. Otherwise, press 0.\n"; //Optional Continuation cin >> w; } while (w==1); cin.get(); } 3^4 = 3 6^2 = 6 etc. So basically I just get my x value back. How do I fix this? Thanks
https://cboard.cprogramming.com/cplusplus-programming/155286-quick-question.html
CC-MAIN-2017-47
refinedweb
233
84.78
Introduction: MultiSlot Clipboard The Visual Studio IDE is one of the most advanced development environments that allow the development any type of software. However, even this complex and multipurpose tools still can receive some improvements. This Instructable focus on a specific feature that Visual Studio (and many other Windows tools) lack: more than one clipboard slot to store data. Although the traditional clipboard is very useful, in particular to those who edit code in the text format, almost every tool for the Windows, Linux or Mac OS platform only provide one slot to cut/copy and pasta data. The advantages of having more than one clipboard slot are twofold: allow the user to retain more data in memory for later use and avoid the non-intentional replacement of what is already on the only clipboard slot. Despite the fact that developers are accustomed to work with a single copy/past container, there is no technical reason to provide only one area that store temporary data that can be used when working with code. Based on this context, this Instructable explain how to create the MultiSlotClipboard, an extension to Visual Studio 2013 that allows five extra clipboard slots to copy/cut and paste data on the code. Each new slot contains a circular history of the last ten data items stored. The code for this project can be found here: Step 1: What You Will Need To create the MultiSlotClipboard extension you will need two simple softwares: 1) Visual Studio 2013 community edition. This edition is free and can be obtained on the following address: 2) The Visual Studio 2013 SDK, which is also free and available at this address: First install Visual Studio 2013 and make sure everything is working. You do not need any extra packages and a simple installation with only the C# language will be enough. Next install the Visual Studio SDK, which is a set of libraries needed to develop and extension for Visual Studio. Both installations are straightforward and require an internet connection. Step 2: Setting Up the Environment The second step is to setup the environment by creating a new project. We are going to use one of the templates provided by the Visual Studio 2013 SDK. First, open Visual Studio and click the File menu, chose the New option and then the Project…, as the Figure bellow shows. You will see the New project window. On the left side chose the Extensibility option under the Templates, Visual C# hierarchy. On the right side panel of the screen choose the Visual Studio Package. Don’t forget to name the project and the solution MultiSlotClipboard and store it on a convenient folder using the text boxes on the bottom part of the window. Click on the OK button to create the solution and the project, as the Figure bellow shows. After the New Project Window a wizard will ask some questions about the project. The first window just present general information and you can click the Next button. The next window of the Wizard asks for the language on which the package will be created and if you want to generate a new key file. Choose the options “Visual C#” and “Generate the new key file to sign the assembly” and click Next button, as the Figure bellow shows. The Next Window asks for metada information about the project. Fill in the field VSPackage name with the MultiSlotClipboard value and feel free to add any extra data to identify the package, as the next Figure shows. We are almost done with the Wizard. The next Window asks what type of package you want to create. For this project we are going to create a new Tool Window that will contain controls to cut, copy, and paste the data for the extra five slots. Therefore, make sure the “Tool Window” checkbox is market. Since our project has a Window we have to named it and provide an identifier for the Command ID, which is the name of an internal variable. You can use the default value for the Command ID and insert the MultiSlotClipboard value for the Window name field, as the shown on the next Figure. The last window of the Wizard asks for the generation of tests. Since this is a simple project we will not create any test. Therefore we must uncheck the two check boxes of this last Window. After some processing Visual Studio will create all the necessary files for the project, including some code, configuration, and design files that are going to be changed on the next steps of this Instructable. The basic structure of the project is provided by the MultiSlotlipboardPackage.cs, which is a class that inherits from the Package class. The project also has a control, named MyControl, which has the MyControl.xaml and MyControl.xaml.cs files. These are the three files we are going to change to implement our solution. Before we change anything on the project we need to add some references. Although the template and the Wizard added the references for some files, there are additional references that need to inserted on the project manually. The files needed are usually stored in the folder \Microsoft Visual Studio 12.0\VSSDK\VisualStudioIntegration\Common\Assemblies\v4.0\ · Microsoft.VisualStudio.CoreUtility (File: Microsoft.VisualStudio.CoreUtility.dll) · Microsoft.VisualStudio.Editor (File: Microsoft.VisualStudio.Editor.dll) · Microsoft.VisualStudio.Text.Data (File: Microsoft.VisualStudio.Text.Data.dll) · Microsoft.VisualStudio.Text.Logic (File: Microsoft.VisualStudio.Text.Logic.dll) · Microsoft.VisualStudio.Text.UI (File: Microsoft.VisualStudio.Text.UI.dll) · Microsoft.VisualStudio.Text.UI.Wpf (File: Microsoft.VisualStudio.Text.UI.Wpf.dll) · System.ComponentModel.Composition (File: C:>\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.ComponentModel.Composition.dll) With the references added to the Project open the MultiSlotlipboardPackage.cs file and insert the following references on the beginning of the file. using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using EnvDTE; Additionally, open the MyControl.xaml.cs and insert the following references on the beginning of the file. using System.Windows.Markup; using System.Reflection; using System.Xml; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using EnvDTE; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; This finishes the required steps to setup the project. Test the project by compiling and running it. You should see a new instance of Visual Studio open with a new window on the top bottom part of the interface, just like the Figure bellow. Note the title of this Visual Studio instance: Experimental Instance. The Visual Studio that has the project is on running mode and when you close the Experimental Interface the extension stops running. Make sure that you know exactly which Visual Studio you are working on to avoid mistakes. Step 3: The User Interface Next, let’s see how we create the user interface for the control. We UI for the project is going to be very simple: we need a template grid that will contain five controls: a label to identify the slot number, Cut, Copy and Paste buttons and a ListView that will show the history for each slot. We will create a template grid will all these controls. Inside the code we will dynamically create the same grid and its controls five times. But first we need to delete the existing grid and button on the Mycontrol.xaml file, which has the following default layout. We need to change the file so it will contain our template grid with the label, buttons and ListView. Therefore, the new grid will be just like the following layout: What we did on the previous layout was first name the external grid grdMain. Next, we created the template grid named grdTemplate that has some columns for the layout. The other controls are the Paste and Copy buttons, named bntSlotPaste and bntSlotCopy, respectively. The ListVview named lstSlot1_Copy is created next followed but the label lblSlot2 and the Cut button bntSlotCut. The names and order of the controls inside the grid grdTemplate are very important and will be used on the next steps of this Instructable. The following Figure show how this interface looks like when we run the project. We will clone the template grid on our code on a future step. But before that we need to add some methods on the package class MultiSlotClipboardPakage. Step 4: Package Methods The package class created by the Wizard needs some fields and methods to allow our control to access in runtime the internal object that handle the text shown in code editor. We also need some access methods. Open the file MultiSlotClipboardPackage.cs file and insert the static field named thePackage just after the definition of the class: static public MultiSlotClipboardPackage thePackage; Now find out the Initialize() method and insert the following line at the end of this method to get the reference of the object of this class. MultiSlotClipboardPackage.thePackage = this; Make sure to NOT change anything that is already there on the Initialize() method, which should look like this: protected override void Initialize() { Debug tool window CommandID toolwndCommandID = new CommandID(GuidList.guidMultiSlotClipboardCmdSet, (int)PkgCmdIDList.cmdidMyTool); MenuCommand menuToolWin = new MenuCommand(ShowToolWindow, toolwndCommandID); mcs.AddCommand( menuToolWin ); } MultiSlotClipboardPackage.thePackage = this; } Next, we need to add two methods that will expose the text manager and DTE objects. Inside the class MultiSlotClipboardPackage add the following two methods: public IVsTextManager getTextManager() { return (IVsTextManager) GetService(typeof(SVsTextManager)); } public DTE Dte { get { return (DTE)GetService(typeof(DTE)); } } This finishes the modifications needed on the Package class MultiSlotClipboardPackage. Now we will focus our efforts on the MyControl class to get the selected text and insert what’s inside the slot on the source code file. Step 5: Slot Data Structures and Methods This step will create the data structure needed to store the data on the extra slots. But first, open the MyControl.xaml.cs file and remove the method button1_Click() created by the wizard to show a message box when the original button was there. Since we removed the button from the XAML file we can erase that method. After erasing the button1_Click() method the MyControl class should be almost empty and look like this: public partial class MyControl : UserControl { public MyControl() { InitializeComponent(); } } Let´s create some private fields for this class to store the data. First, we will create two constants that will store the maximum number of slots (5) and the maximum number of history that each slot have (10). private const int MAX_SLOTS = 5; private const int MAX_SLOT_HISTORY = 10; Next, we need a field to store the view that allow the access to the current code window. This variable has the datatype of an interface: iWpTextView. private IWpfTextView view; The following field is the data structure that will contain all the data for the slots. It is an array where each element is a list of strings. The size of the array is obtained from the MAX_SLOTS constant. private List[] aClipboadSlotData = new List[MAX_SLOTS]; These four fields are all that we need so far. Now we need to initialize the aClipboardSlotData with empty strings. We will do that on a new method called InitializeClipBoard(), which has the following source code: //, ""); } } } The content of the InitializeClipBoard() is basically two nested for loops. The external for loop use the i integer variable to go to each element of the array, which are the slots. For each slot we instantiate a new list of strings. The internal for loop insert an empty string on aClipboadSlotData[i] the using the Insert() method of the List datatype. We must call the InitializeClipBoard() inside the constructor of the MyControl class just after the call to InitializeComponent(). So far, the MyControl class looks like this. public partial class MyControl : UserControl { private const int MAX_SLOTS = 5; private const int MAX_SLOT_HISTORY = 10; private IWpfTextView view; private List[] aClipboadSlotData = new List[MAX_SLOTS]; public MyControl() { InitializeComponent(); // Add the empty slots IntilializeClipBoard(); } //, ""); } } } } Step 6: Reading the Selected Text The extra clipboard slots will behave just like the regular clipboard: the user selects a text on the code window and copy (or cut) the text. This action copy the selected text to the internal memory storage. After that the user can move the cursor (caret) and paste the value whenever he/she wants. To capture the selected text we need first to get the current code window. We do that by creating a new method named GetActiveTextView(), which return an object of the datatype IWpfTextView that will be stored on the view internal field created on the previous step. The code for the GetActiveTextView() is show bellow: private IWpfTextView GetActiveTextView() { IWpfTextView view = null; IVsTextView vTextView; var txtMgr = MultiSlotClipboardPackage.thePackage.getTextManager(); txtMgr.GetActiveView(1, null, out vTextView); var userData = vTextView as IVsUserData; if (null != userData) { object holder; var guidViewHost = DefGuidList.guidIWpfTextViewHost; userData.GetData(ref guidViewHost, out holder); var viewHost = (IWpfTextViewHost)holder; view = viewHost.TextView; } return view; } This method starts by defining some internal variables. The view variable will be returned if the active view is the code window; otherwise, it will contain null. The vTextView is an auxiliary variable and the txtMgr gets the current view from the Package class MultiSlotClipboardPackage using the getTextManager() created on the Step 4. This method need to check if the active Window is actually the code Window. We do that by calling the GetData() method of the IVsUserData interface. The rest of the code is just casting the variable to the correct datypes in a way that we have an object that represents the TextView of the editor that has the source code. Now that we have a method to obtain the current text code view we need to extract the text that is selected. We do that by using three new methods: GetTextForPastie(), SelectionIsAvailable() and GetSelectedText(). // Get the SelectedText private static string GetTextForPastie(ITextView view) { if (SelectionIsAvailable(view)) return GetSelectedText(view); else return ""; } // Check to see if there is selected text private static bool SelectionIsAvailable(ITextView view) { if (view == null) throw new ArgumentNullException("view"); return !view.Selection.IsEmpty && view.Selection.SelectedSpans.Count > 0; } // Get the current selected text private static string GetSelectedText(ITextView view) { return view.Selection.SelectedSpans[0].GetText(); } The GetTextForPastie() method receive the view as a parameter and check if there is any selected text by calling the SelectionIsAvailable() method, which returns a boolean value that indicates if there is any selected text. The selected text is then obtained inside the GetSelectedText() that used the Selection property of the view object to get the text of the first SelectedSpan. The following link contains the documentation of the ITextSelection interface, which is the datatype of the Selection property. Step 7: Replicating the UI So far we created some fields to store the data and some methods to initialize the data structure and get the selected text. Now we must dynamically create the user interface to show five sets of the template grid. We need to store the five grids on an array so we can access the grid using an index inside the control’s events. To store the dynamically created grids we need to create the aGroupGrids array as private field of the MyControl class. The datatype of this array is Grid (System.Windows.Controls.Grid) and maximum number of elements is stored on the constant MAX_SLOTS. private Grid[] aGroupGrids = new Grid[MAX_SLOTS]; Before we initialize the array of grids we have to create a method to clone the existing grid grdTemplate we created on Step 3. Unfortunately, the .NET framework does not have a built in function to clone a UI control, so we have to create our own. Therefore, we must create the CloneControls() method as show bellow. private Grid CloneControls(Grid myGrid) { string gridXaml = XamlWriter.Save(myGrid); StringReader stringReader = new StringReader(gridXaml); XmlReader xmlReader = XmlReader.Create(stringReader); Grid newGrid = (Grid)XamlReader.Load(xmlReader); return newGrid; } The CloneControls() method receive a Grid object as a parameter and returns another Grid object, which is a clone of parameter. Inside this method, we use the classes that serialize objects on the XML format to get all the properties, values and other elements stored inside the control. The following link contains a good explanation about XML serialization with the XamlWriter and XMlReader classes on the .NET Framework 4.0. Now that we have the aGroupGrids array to store the dynamic created controls and the CloneControls() method to clone the grid objects we need to initialize the elements, i.e. create them. We will do that inside a new method called InitializeInteface(). This method should be called inside the MyControl’s constructor just after the InitializeClipboard() call. The constructor of the MyControl class should look like this: public MyControl() { InitializeComponent(); // Add the empty slots IntilializeClipBoard(); // Initilizae the interface InitializeInterface(); } Inside the InitializeInterface() we should do the following tasks: · Hide the grdTemplateGrid; · For each new slot clone the grdTemplateGrid grid: o Insert the new cloned grid on the aGroupGrid array. o Set the visibility for the new cloned grid. o Set the position of the cloned grid to a new margin so the grids do not overlap visually. o Change the caption of the label to show which grid correspond to each slot. o Set the Tag property of the controls and the ListView to store the index of the cloned grid. o Set the delegate methods to the click events of the buttons. Also, set the delegate method to the double click event of the ListView. o Add the new cloned grid to the container grid grdMain. The complete code for the InitializeInterface() method is shown below: private void InitializeInterface() { Double left_initial = -170; this.grdTemplate.Visibility = Visibility.Hidden; for (int i = 0; i < MAX_SLOTS; i++) { aGroupGrids[i] = CloneControls(this.grdTemplate); aGroupGrids[i].Visibility = Visibility.Visible; left_initial = left_initial + 180.0; aGroupGrids[i].Margin = new System.Windows.Thickness(left_initial, -5.0, 0.0, 0.0); // Need to change the Slot label + add the events to the buttons and the list // Order of elements // 0 -> Button Paste // 1 -> Button Copy // 2 -> ListView // 3 -> Label // 4 -> Button Cut aGroupGrids[i].Tag = i; // Set the Label caption ((Label)aGroupGrids[i].Children[3]).Content = "Slot " + (i + 1).ToString(); // Set the Tags properties with the index of this grid in the array // This is gonna be usefull latter on (for the events) Button Paste = ((Button)aGroupGrids[i].Children[0]); Button Copy = ((Button)aGroupGrids[i].Children[1]); Button Cut = ((Button)aGroupGrids[i].Children[4]); ListView lstData = ((ListView)aGroupGrids[i].Children[2]); Paste.Tag = i; Copy.Tag = i; Cut.Tag = i; lstData.Tag = i; // Set the Buttons Events (Click) Copy.Click += Copy_Click; Paste.Click += Paste_Click; Cut.Click += Cut_Click; // Set the ListView Event (MouseDoubleClick) lstData.MouseDoubleClick += lstData_MouseDoubleClick; // Add this grid to the parent Grid grdMain.Children.Add(aGroupGrids[i]); } } How all we have to do is fill in the delegate methods for the buttons (Copy_Click, Pastle_Click, Cut_Click) and the method for the double click on the ListView (lstData_MouseDoubleClick), which will show a simple MessageBox with the content of the selected item. Step 8: Coding the Events In this step we need to fill in the code for the events of the buttons and the ListView. These events are generic, which means that all the dynamically generated controls will call these events. So, to know which slot called the event we will read the Tag property of the control, which contains the correct index of the array aClipboardSlotData. Let’s start with the event that handles the double click on the ListView. When the user double click a ListViewItem we should show a message box with the content of the selected elements. If the SelectedIndex of the ListView property is greater than -1 this means that an item was selected and we will be use the value of this property as an index for the array that store the clipboard data (aClipboardSlotData). The following code shows the content of the lstData_MouseDoubleClick() delegate method. void lstData_MouseDoubleClick(object sender, MouseButtonEventArgs e) { ListView v = (ListView)sender; int index = Convert.ToInt32(v.Tag); if (v.SelectedIndex != -1) MessageBox.Show(aClipboadSlotData[index].ElementAt(v.SelectedIndex).ToString()); } The next delegate method we need to create is the event that handle the click on the Copy button. This delegate method is called Copy_Click() and we need to first get the active code window with the GetActiveView() method created on Step 6 and check if the view is the correct one. Next, we must read the current selected text with the GetTextForPastie() method that was also created on Step 6. After we get the text we need to check if it is empty. If the selected text is not empty, we need to insert it on the array aClipboardSlotData. We perform this insertion in a new method called InsertDataHistory(). Finally, we must update the ListView using another new method called AccomodateDataListView(). But first let’s see the code for the Copy_Click() delegate method. void Copy); } } } The Copy_Click() starts by reading the value of the Tag property of the button that was clicked. This property contain the index that we are going to use as the slot number. Next we call the GetActiveTextView() method and check the return value to see if we got the correct window. The following lines of code get the selected text with the GetTextForPastie() method. We then check to see if there is any selected text and if so we call the InsertDataHistory() method to insert the data on the aClipboardSlotData array. Finally, we change the elements of the ListView with the AccomodateDataListView() method. The InsertDataHistory() method has a simple job. First, it receives the index of the clipboard slot and the selected text. Then is should insert the selected text on the first position of the aClipboardSlotData array, which should work like a stack or LIFO data structure (). Instead of implement a stack data structure from scratch we just create a new List and insert the selected text value sent as a parameter in its first position. Next, we traverse the existing aClipboardSlotData array starting from the second element and inserting the data on the new created List. Finally, we override the existing List on aClipboardSlotData with the one we just created. The following code shows how these operations are performed. private void InsertDataHistory(int indexSlot, String sData) { List list_temp = new List(); list_temp.Insert(0, sData); for (int i = 0; i < aClipboadSlotData[indexSlot].Count - 1; i++) { list_temp.Insert(i + 1, aClipboadSlotData[indexSlot].ElementAt(i).ToString()); } aClipboadSlotData[indexSlot].RemoveRange(0, aClipboadSlotData[indexSlot].Count); aClipboadSlotData[indexSlot].InsertRange(0, list_temp); return; } Now that we inserted the selected text on the correct position of the List stored inside the aClipboardSlotData array we must update the elements of the ListView. We do that inside the AccomodateDataListView() method that receive the index of the array as a parameter. The AccomodateDataListView() is straightforward: we erase all the ListViewItem elements and inserted new ones in the order of the List stored inside the aClipboardSlotData. We just make sure to insert only the 15 characters of each text to avoid cut the text. Finally, we ask for a refresh on the UI and select the first element of the ListView. private void AccomodateDataListView(int indexSlot) { ListView v = (ListView)aGroupGrids[indexSlot].Children[2]; v.Items.Clear(); foreach (String s in aClipboadSlotData[indexSlot]) { if (!s.Equals("")) { if (s.Length > 15) v.Items.Add(s.Substring(0, 15)); else v.Items.Add(s); } } v.Items.Refresh(); v.SelectedIndex = 0; } We are almost done. We need to create the code for the events that handle the click in the Cut and the Paste buttons. The event for the Cut button is almost the same as the Copy button: the only difference is that after we get the selected text we need to erase the text that is selected from the code window and remove the text’s selection. To erase the selected text we must use the object that implement the ITextEdit interface. We get this object from the CreateEdit() method of the TextBuffer property found on the view variable that represents the current code editor view. Once we get the ITextEdit object we use the Delete() method to erase the characters and the Apply() method to change the text. Finally, we remove the selection using the Clear() method of the Selection property of the view. But there is a catch when we use the Delete() method: we must provide the position we want to start deleting the characters and how many characters we need to delete. To get the position of the current selection we use the Position property from the Selection.Start property, which represents the start place where selection begin. In a similar way, we use the Selection.End property to get the exact integer position of the end of the selection. The code for the delegate method Cut_Click() is shown below. void Cut); Microsoft.VisualStudio.Text.ITextEdit edit = view.TextBuffer.CreateEdit(); edit.Delete(view.Selection.Start.Position.Position, view.Selection.End.Position.Position - view.Selection.Start.Position.Position); edit.Apply(); view.Selection.Clear(); } } } The final delegate method we must create is the one that handle the click event on the Paste button. However, before we create this method we must first develop a way to extract the text element from the array aClipboardSlotData, which is the data structure that store the slots and their history. The new method that extracts the text from a slot history is called getSelectedItem() and it receives the index of the slot as a parameter. This method must return the data value from the slot’s history that corresponds to the selected item on the ListView. If no item is selected on the ListView the method should return the first element of the ListView. The first task of the getSelectedItem() is to get the corresponding ListView with the index and the aGroupGrids array. Next, the method verifies if the obtained ListView is empty and if it is not the SelectedIndex property is used with the aClipboardSlodData array to get the element from the correct slot and the correct history position. private String getSelectedItem(int indexSlot) { String ret = ""; ListView v = (ListView)aGroupGrids[indexSlot].Children[2]; if (v.Items.Count > 0) { if (v.SelectedIndex >= 0) { ret = aClipboadSlotData[indexSlot].ElementAt(v.SelectedIndex).ToString(); } else ret = aClipboadSlotData[indexSlot].ElementAt(0).ToString(); } return ret; } Finally, the last piece of code we must implement is the delegate method that handle the click on the Paste button. The method Paste_Click() first get the current view using the GetActiveTextView() and check if the current view is the code editor, just like the Copy_Click() and Cut_Click() delegate methods. The method then calls the getSelectedItem() sending as a parameter the index valued obtained from the Tag property of the button that was clicked. If there is some data on the corresponding history and slot position, this text must be inserted in the current cursor (caret) position. To insert the text value in the exact cursor position we use again the object that implement the ITextEdit interface obtained from the CreateEdit() method of the TextBuffer property, just like we did on the Cut event method. However, here we should use the Insert() method instead of the Delete() and provide the current carret position obtained from the Position property of the Caret.Position.BufferPostion property of the view object. The final piece of code of this Instructable is show below void Paste_Click(object sender, RoutedEventArgs e) { int index = Convert.ToInt32(((Button)sender).Tag); view = GetActiveTextView(); if (!(this.view == null || MultiSlotClipboardPackage.thePackage.Dte.ActiveDocument == null)) { String sData = getSelectedItem(index); if (!sData.Equals("")) { Microsoft.VisualStudio.Text.ITextEdit edit = view.TextBuffer.CreateEdit(); edit.Insert(view.Caret.Position.BufferPosition.Position, sData); edit.Apply(); } } } Step 9: Testing Now that we finished the coding let’s start or Visual Studio extension. Compile and Run the project and check the Window shown on the new instance of Visual Studio that appears. The control we develop should look like the following Figure. Open a new project and start testing the cut, copy and paste buttons when working with some code. Note that only the selected value that from a ListView is pasted on the code area. 2 Discussions I have made this an instructable. Thanks. This is excellent!
https://www.instructables.com/id/MultiSlot-Clipboard/
CC-MAIN-2018-34
refinedweb
4,696
55.34
Gantry::Plugins::SOAP::Doc - document style SOAP support In a controller: use Your::App::BaseModule qw( -PluginNamespace=YourApp SOAP::Doc ); # This exports these into the site object: # soap_out # do_wsdl # return_error do_a_soap_action { my $self = shift; my $data = $self->get_post_body(); my $parsed_data = XMLin( $data ); # Use data to process the request, until you have a # structure like: my $ret_struct = [ { yourResponseType => [ { var => value }, { var2 => value2 }, { var3 => undef }, # for required empty tags { nesting_var => [ { subvar => value }, ] } ] } ] ); return $self->soap_out( $ret_struct, 'prefix', 'pretty' ); } This module supports document style SOAP. If you need rpc style, see Gantry::Plugins::SOAP::RPC. This module must be used as a plugin, so it can register a pre_init callback to take the POSTed body from the HTTP request before the engine can mangle it, in a vain attempt to make form parameters from it. The document style SOAP request must find its way to your do_ method via its soap_action URL and Gantry's normal dispatching mechanism. Once the do_ method is called, your SOAP request is available via the get_post_body accessor exported by each engine. That request is exactly as received. You probably want to use XML::Simple's XMLin function to extract your data. I would do that for you here, but you might need to set attributes of the parsing like ForceArray. When you have finished processing the request, you have two choices. If it did not go well, call return_error to deliver a SOAP fault to client. Using die or croak is a bad idea as that will return a regular Gantry error message which is obviously not SOAP compliant. If you succeeded in handling the request, return an array of hashes. Each hash is keyed by XML tag (not including namespace prefix). The value can be a scalar or an array of hashes like the top level one. If the value is undef, an empty tag will be generated. Generally, you need to take all of the exports from this module, unless you want to replace them with your own versions. If you need to control the namespace of the returned parameters, call soap_namespace_set with the URL of the namespace before returning. If you don't do that the namespace will default to. For use by non-web scripts. Call this with a hash of attributes. Currently only the target_namespace key is used. It sets the namespace. Once you get your object, you can call soap_out on it as you would in a Gantry conroller. Only for use by Gantry.pm. This is used to register steal_post_body as a pre init callback with Gantry. Not for external use. Just a carefully timed call to consume_post_body exported by each engine. This is registered as a pre_init callback, so it gets the body before normal form parameter parsing would. You may retrieve with the post body with get_post_body (also exported by each engine). No processing of the request is done. You will receive whatever the SOAP client generated. That should be XML, but even that depends on the client. Returns the UTC in SOAP format. This method is registered as a callback. Durning the post_init phase it will create a hash from the $self->get_post_body() and store the result in $self->params(); Called internally to retrieve the namespace for the XML tags in your SOAP response. Call soap_namespace_set if you need to set a particular namespace (some clients will care). Otherwise, the default namespace will be used. Use this to set the namespace for your the tags in your XML response. The default namespace is. Parameters: actual data to send to the client. See SYNOPSIS and DESCRIPTION. prefix or internal. Use prefix to define the namespace in the soap:Envelope declaration and use it as a prefix on all the return parameter tags. Use internal if you want the prefix to be defined in the outer tag of the response parameters. To set the value of the namespace, call soap_namespace_set before calling this method. true if you want pretty printing, false if not By default returned XML will be whitespace compressed. If you want it to be pretty printed for debugging, pass any true value to this method as the second parameter, in a scenario like this: my $check_first = $self->soap_out( $structure, 'prefix', 'pretty_please' ); warn $check_first; return $check_first; Call this with the data to return to the client. If that client cares about the namespace of the tags in the response, call soap_namespace_set first. See the SYNOPSIS for an example of the structure you must pass to this method. See the DESCRIPTION for an explanation of what you can put in the structure. You should return the value returned from this method directly. It turns off all templating and sets the content type to text/xml. Mostly for internal use. soap_out uses this to turn your structure of return values into an XML snippet. If you need to re-implement soap_out, you could call this directly. The initial call should pass the same structure soap_out expects and (optionally) a pretty print flag. The returned value is the snippet of return params only. You would then need to build the SOAP envelope, etc. This method returns a fault XML packet for you. Use it instead of die or croak. This method uses the wsdldoc.tt in your template path to return a WSDL file to your client. The view.data passed to that template comes directly from a call to get_soap_ops, which you must implement (even it it returns nothing). For clients. Sends the xml to the SOAP server. You must have called new with action_url and post_to_url for this method to work. In particular, servers which use this as a plugin cannot normally call this method. First, they must call new to make an object of this class. Parameters: an object of this class, the xml to send (get it from calling soap_out). Returns: response from remote server (actually whatever request on the LWP user agent retruns, try calling content on that object) Phil Crow, <crow.phil@gmail.com> Tim Keefer, <tim@timkeefer.com<gt> This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.6 or, at your option, any later version of Perl 5 you may have available.
http://search.cpan.org/~tkeefer/Gantry/lib/Gantry/Plugins/SOAP/Doc.pm
CC-MAIN-2017-04
refinedweb
1,046
74.19
The colours of the sky are caused by a complex interplay between our sun and our planet’s atmosphere. Artists have long painted the sky in all its guises, and storytellers have often taken inspiration from it. Ancient Greeks like Plato and Aristotle were the first to write their theories about colour and its relation to meteorological phenomena. Yet, it took scientists many centuries to unravel the science behind the colours we see in the sky. Machine learning models learn their behaviour from data. So, finding the right data is a big part of the work to build machine learning into your products. Exactly how much data you need depends on what you’re doing and your starting point. There are techniques like transfer learning to reduce the amount of data you need. Or, for some tasks, pre-trained models are available. Still, if you want to build something more than a proof-of-concept, you’ll eventually need data of your own to do so. That data has to be representative of the machine learning task, and its collection is one of the places where bias creeps in. Building a dataset that’s balanced on multiple dimensions requires care and attention. Data for training a speech recognition system has to represent aspects like different noisy environments, multiple speakers, accents, microphones, topics of conversation, styles of conversation, and more. Some of these aspects, like background noise, affect most users equally. But some aspects, like accent, have an outsized impact on particular groups of users. Sometimes, though, bias is built deeper into the data than in the composition of the dataset. Text scraped from the web, for example, results in a dataset that embeds many of society’s stereotypes because those are present in text from the web and can’t be scrubbed. … Since the launch of Alexa, Siri, and Google Assistant, we’re all becoming much more used to talking to our devices. Beyond these virtual assistants, voice technology and conversational AI have increased in popularity over the last decade and are used in many applications. One use of Natural Language Processing (NLP) technology is to analyse and gain insight from the written transcripts of audio— whether from voice assistants or from other scenarios like meetings, interviews, call centres, lectures or TV shows. Yet when we speak, things are more complicated than a simple text transcription suggests. … There are several Python libraries available that make it very easy to view waveforms in different ways. In this post, I’ll go through some of the ways to get started. To begin, import the key libraries: import matplotlib.pyplot as plt import numpy as np import pysptk from scipy.io import wavfile For the audio, I used Audacity to record the short phrase “What’s today’s weather?” as a wave file. I’ll use scipy to read in that wave file, and matplotlib to visualise it. wavfn=”weather.wav” fs, x = wavfile.read(wavfn) y = np.linspace(0,len(x)/float(fs), len(x)) ya = np.max(np.absolute(x)) plt.plot(y, x, color="#004225") plt.xlabel("Time (seconds)") plt.ylabel("Amplitude") plt.ylim(-ya, ya) plt.xlim(0, … The majority of folks who build technology don’t intend to be biased. Yet we all have our own unique perspective on the world, and we can’t help but bring that into our work. We make decisions based on our views and our experiences. Those decisions may each seem small in isolation, but they accumulate. And, as a result, technology often reflects the views of those who build it. Here are a few of the places I’ve seen where bias creeps into technology. With the recent success of machine learning (ML) and AI algorithms, data is becoming increasingly important. ML algorithms learn their behaviour from a dataset. … During my time working at Amazon Alexa, I designed and ran an Alexa Skills workshop to encourage teenagers into coding. This workshop can be adapted to all levels and ages — our youngest participant was 12 — and all you need is a computer with a browser and an internet connection. When you finish, you’ll have an Alexa skill which can tell you facts about famous folk along with some of their quotes. NB: A more in-depth instruction booklet is available here, from a collaboration with Feminist Internet, which taught undergraduate students to build a skill about famous feminists. Each participant should set these up before the… Companies are investing millions of pounds to develop Artificial Intelligence (AI) technology. Many people use that AI technology daily to make their lives easier. But search Google for images of “Artificial Intelligence”, and you’ll be faced with a sea of glowing, bright blue, connected brains. The imagery used to illustrate AI is a far cry from the more mundane reality of how AI looks to its users, where it powers services like navigation, voice assistants and face recognition. The disconnect makes it hard to grasp the reality of AI. Artificial Intelligence (AI) is a fast growing field. The 2018 AI Index report illustrates just how fast it is growing. It reports that published research papers in AI have increased 7x since 1996, university enrolment on AI courses has increased 5x since 2012, investment in AI startups in the US has increased 113% since 2012 and mentions of AI and machine learning (ML) in the earnings calls of tech companies have increased more than 100x since 2012. These statistics show how AI is growing not just in academia, but the technology is rapidly being adopted by businesses and becoming commercialised. Yet, AI is an ambiguous term which has no well defined and agreed upon definition. It’s typically used as an umbrella term covering a variety of techniques that make computers appear to have human-like intelligence. … In the past few years, machine learning (ML) has become commercially successful and AI firmly established as a field. With its success, more attention is being paid specifically to the gender gap in AI. Compared to the general population, men are overrepresented in technology. While this has been the case for several decades, the opposite was true in the early days of computing when programming was considered a woman’s job. Diversity has been shown to lead to good business outcomes like improved revenue. … The “long hours” culture is glorified in many industries, including the tech industry where I work. Rachel Thomas writes clearly about how this is discriminatory and counter-productive, so this post is in response to her tweet: For anyone in a job with a healthy work culture, consider blogging about it: - offer lessons learned & advice for other companies - with many high profile examples of toxic overwork, it can feel like “everyone” is doing it. Helpful to see counterexamples - good for recruiting - Rachel Thomas (@math_rachel) January 25, 2019. … About
https://catherinebreslin.medium.com/?source=post_internal_links---------4----------------------------
CC-MAIN-2021-04
refinedweb
1,144
62.88
0 I'm trying to learn using pointers, and in the code below I can send variables to a function. But the return is obviously wrong and I can't seem to figure it out. What I want the function to return is the number of even number occurrences. Any suggestions to where I go wrong would be much appreciated. I've tried to comment to indicate where I'm struggling, although I'm sure you would see it anyway. #include <stdio.h> int countEven (int* numbers) { int even[7]; int i=0, j=0; for(i=0;i<7;i++) { if(numbers[i]%2 == 0) { even[j]=numbers[i]; j++; } } printf ("%i\n", j); //Checking if function works return; } int main (void) { int numbers[] = {2, 5, 10, 16, 31, 17, 30}; int size=7; int j=0; countEven(&numbers); printf ("%i\n", countEven(numbers)); //return output causing problems system ("pause"); return 0; }
https://www.daniweb.com/programming/software-development/threads/320164/need-some-pointers-here
CC-MAIN-2017-26
refinedweb
153
66.88
I gave this problem to return the change back from an input. However, this code a few students wrote produces in correct results. It seems to have an "off by one error". This is for a C exam I gave. I cannot see the error- it has been a long day. Comments would help Code: #include <stdio.h> void change (float total, int *dlrs, int *quart, int *nick, int *hlfdoll, int *dimes, int *cents); int main() { float total; int dollar, quarter, nickel, dime, cent, halfdollar = 0; printf("Please enter an amount in change:\n"); scanf("%f",&total); change(total, &dollar,&quarter,&nickel,&halfdollar,&dime,¢); printf("The breakdown for $%.2f is as follows: \n\n", total); printf ("Dollars %d\n", dollar); printf ("Half Dollars %d\n", halfdollar); printf ("Quarters %d\n", quarter); printf ("Dimes %d\n", dime); printf ("Nickels %d\n", nickel); printf ("Pennies %d\n", cent); return 0; } void change (float total, int *dlrs, int *quart, int *nick, int *hlfdoll, int *dimes, int *cents) { int calc; calc = (int)(total * 100.0); *dlrs = calc / 100; calc -= (*dlrs * 100); *hlfdoll = calc / 50; calc -= (*hlfdoll * 50); *quart = calc / 25; calc -= (*quart * 25); *dimes = calc / 10; calc -= (*dimes * 10); *nick = calc / 5; calc -= (*nick * 5); *cents = calc; return; }
http://cboard.cprogramming.com/c-programming/29264-check-code-out-tired-today-printable-thread.html
CC-MAIN-2014-15
refinedweb
204
76.15
A Python module of Meta-Analysis, usually applied in systemtic reviews of Evidence-based Medicine. Project description PythonMeta Info Name = PythonMeta Version = 1.11 Author = Deng Hongyong (dhy) URL = Date = 2019.7.23 Import Import the PythonMeta module in your code: import PythonMeta Functions and Classes There are four functions/classes in PythonMeta package: Help()(function): Show help information of PythonMeta. Data()(class): Set and Load data to analysis. - datatype (attribute, string): set the data type:'CATE' for CATEgorical/count/binary/dichotomous data, or 'CONT' for continuous data. - studies (attribute, array): Array to store the study data. - subgroup (attribute, array): Array to store the subgroup. - nototal (attribute, binary): Flag of do NOT calculate the total effect. - readfile(filename) (method): Read data file. Input: filename(string) (e.g. "c:\1.txt"); Output: lines array (always as input of method getdata()). (See Sample code and data files) - getdata(lines) (method): Load data into attribute array of 'studies'. Input: lines array (always from method readfile()); Output: attribute 'studies'. (See Sample code and data files) Meta()(class): Set and perform the Meta-Analysis. - datatype (attribute, string): set the data type:'CATE' for CATEgorical/count/binary/dichotomous data, or 'CONT' for continuous data. Attention: this attribute should same to Data().datatype. - studies (attribute, array): Array of study data to meta-analysis. - subgroup (attribute, array): Array to store the subgroup. Attention: this attribute should same to Data().subgroup. - nototal (attribute, binary): Flag of do NOT calculate the total effect. Attention: this attribute should same to Data().nototal. - models (attribute, string): set effect models as 'Fixed' or 'Random'. - effect (attribute, string): set effect size as 'OR':odds ratio; 'RR': risk ratio; 'RD':risk difference; 'MD':weighted mean diff; 'SMD':standard mean diff. - algorithm (attribute, string): set the algorithms of meta-analysis: 'MH':Mantel-Haenszel;'Peto';'IV':Inverse variance;'IV-Heg'(DEFAULT),'IV-Cnd','IV-Gls':for SMD algorithms - meta(studies, nosubgrp=False) (method): perform the meta-analysis. Input: 1, studies array (always from Data().getdata); 2, nosubgrp flag, False as default. Output: result array [[Total...],[study1...],[subgroup1,...],[studyn,...]...[subgroupk,...]]. (See Sample code for more information) Fig()(class): Set and draw the result figures. - size (attribute, integer): set the canvas size in inchs, default [6,6]. - dpi (attribute, integer): set the resolution of figure (dot per inch), default 80pts. - title (attribute, string): set the title of figure. - nototal (attribute, binary): Flag of do NOT show the total effect, default False. - forest(results) (method): drawing the forest plot. Input: results array, always from Meta().meta (See Sample code for more information). - funnel(results) (method): drawing the funnel plot. Input: results array, always from Meta().meta (See Sample code for more information). Example Sample code: sample.py import PythonMeta as PMA def showstudies(studies,dtype): #show continuous data if dtype.upper()=="CONT": text = "%-10s %-30s %-30s \n"%("Study ID","Experiment Group","Control Group") text += "%-10s %-10s %-10s %-10s %-10s %-10s %-10s \n"%(" ","m1","sd1","n1","m2","sd2","n2") for i in range(len(studies)): text += "%-10s %-10s %-10s %-10s %-10s %-10s %-10s \n"%( studies[i][6], #study ID str(studies[i][0]), #mean of group1 str(studies[i][1]), #SD of group1 str(studies[i][2]), #total num of group1 str(studies[i][3]), #mean of group2 str(studies[i][4]), #SD of group2 str(studies[i][5]) #total num of group2 ) return text #show dichotomous data"%( # for each study"%( # for total effect(stys,settings): d = PMA.Data() #Load Data class m = PMA.Meta() #Load Meta class f = PMA.Fig() #Load Fig class #You should always tell the datatype first!!! d.datatype = settings["datatype"] #set data type, 'CATE' for binary data or 'CONT' for continuous data studies = d.getdata(stys) #load data #studies = d.getdata(d.readfile("studies.txt")) #get data from a data file, see examples of data files print(showstudies(studies,d.datatype)) #show studies m.datatype=d.datatype #set data type for meta-analysis calculating m.models = settings["models"] #set effect models: 'Fixed' or 'Random' m.algorithm = settings["algorithm"] #set algorithm, based on datatype and effect size m.effect = settings["effect"] #set effect size:RR/OR/RD for binary data; SMD/MD for continuous data results = m.meta(studies) #performing the analysis print(m.models + " " + m.algorithm + " " + m.effect) print (showresults(results)) #show results table f.forest(results).show() #show forest plot f.funnel(results).show() #show funnel plot if __name__ == '__main__': samp_cate=[ #this array can be stored into a data file by lines, and loaded with d.readfile("filename") binary data with subgroup.", "#Syntax: study name, e1, n1, e2, n2", "#e1,n1: events and number of experiment group;", "#e2,n2: events and number of control group.", "#And you can add a line of <nototal> to hide the Overall result."] samp_cont=[ #this array can be stored into a data file by lines, and loaded with d.readfile("filename") 1: dichotomous data settings={"datatype":"CATE", #for CATEgorical/count/binary/dichotomous data "models":"Fixed", #models: Fixed or Random "algorithm":"MH", #algorithm: MH, Peto or IV "effect":"RR"} #effect size: RR, OR, RD main(samp_cate,settings) #sample 2: continuous data settings={"datatype":"CONT", #for CONTinuous data "models":"Fixed", #models: Fixed or Random "algorithm":"IV", #algorithm: IV "effect":"MD"} #effect size: MD, SMD main(samp_cont,settings) Or you can load data from a file, like: studies = d.getdata(d.readfile("studies.txt") Here are some examples of data file: (Please remember all lines start with # are comment lines, which will be ignored while loading.) Sample of continuous data of dichotomous data. Sample of data with subgroup subgroup. #Cumulative meta-analysis and Senstivity analysis will blind to all <subgroup> tags. #And you can add a line of <nototal> to hide the Overall result. Deng Hongyong Ph.D Shanghai University of Traditional Chinese Medicine Shanghai, China 201203 Web: Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/PythonMeta/1.11/
CC-MAIN-2021-43
refinedweb
978
51.34
For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: Buy and Hold example - monthly cash being added twice? From the buy and hold blog post: Buy and Hold Why is the self.p.monthly_cash added first to self.broker.add, and then again to calculate the target_value for the current order? Isn't this adding the cash twice? def notify_timer(self, timer, when, *args, **kwargs): # Add the influx of monthly cash to the broker self.broker.add_cash(self.p.monthly_cash) # buy available cash target_value = self.broker.get_value() + self.p.monthly_cash self.order_target_value(target=target_value) @gretzteam I believe you are adding the cash twice. First using: self.broker.add_cash(self.p.monthly_cash) Then here: self.broker.get_value() + self.p.monthly_cash get_valuewill have the first cash addition in it. @gretzteam No my error, get_value is returning the value of a datas, or if no datas provide then all the market value of the datas. Backtrader's blog is correct. See the comments here
https://community.backtrader.com/topic/3388/buy-and-hold-example-monthly-cash-being-added-twice
CC-MAIN-2021-10
refinedweb
172
53.37
Hello I am trying to improve the method I post below in order to stop the track previously selected before the next starts, so that they dont play simultaneously... I cannot find a way to do so... (because this is part of an exercise of a book I am studying, I can only use a while-loop) * A class to hold details of audio tracks. * Individual tracks may be played. public class MusicOrganizer { // An ArrayList for storing music tracks. private ArrayList<Track> tracks; // A player for the music tracks. private MusicPlayer player; // A reader that can read music files and load them as tracks. private TrackReader reader; [I]constructor and some methods omitted[/I] /** * Play a track in the collection. * @param index The index of the track to be played. */ public void playTrack(int index) // call the indexValid method to check if the parameter is a valid index number. if(indexValid(index)) { Track track = tracks.get(index); player.startPlaying(track.getFilename()); // increments by 1 every time a track is played track.incrementCount(); System.out.println("Now playing: " + track.getArtist() + " - " + track.getTitle()); } } the Player class has this method: stop() to stop playing the track.
http://www.javaprogrammingforums.com/whats-wrong-my-code/38243-how-improve-method.html
CC-MAIN-2016-18
refinedweb
193
58.79
[Advanced Search] Despite programmers' best efforts, software releases usually contain some bugs. Regretfully, fv is no exception. Here are the bugs we are aware of, along with how to avoid or fix them. NOTE: When referring to a file, we will use <fv> to mean the path to the top of your fv source tree, which contains subdirectories such as pow and fitsTcl (or under Windows: bin and lib; or under Mac OS: fv Sources and pow Sources). If you are using the standalone fv package, this will be one level below where you untarred the package. If you are using the FTOOLS 4.1 (or later) package, <fv> will be <ftools>/src/tcltk2, where now <ftools> refers to the top of your FTOOLS source tree. ALSO, we will assume that you have already successfully built the software and have the environment variable FV (or FTOOLS, as appropriate) set as described in the INSTALL instructions. If you have not already built the software, simply make the changes described below and then follow the INSTALL instructions normally; DO NOT execute any of the 'make' commands described here if this is the case. Don't see your problem here? Send us a bug report via the FTOOLS help desk. If possible, include the information reported by the "Stack Dump" button in the error dialog. Not all errors cause this dialog to appear. The Windows and Mac OS versions contain a number of "peculiarities" which are either due to limitations/bugs in the tcl/tk language or the Windows/Mac operating system. Read the windows or macintosh README file for a list of these before reporting a bug. 24-bit displays: When run on some architectures supporting TrueColor mode, fv fails to identify that fact and enters the wrong video mode, giving an error message similar to: X Error of failed request: BadMatch (invalid parameter) Major opcode of failed request: (X_CreateWindow) Serial number of failed request: nnn or: no display name and no $DISPLAY environment variable SkyView: After submitting a skyview or catalog database request, fv will freeze and/or report an error. Fv is attempting to connect to a computer visible only within Goddard. The solution is to modify lines 350 and 636 of the file <fv>/lib/fv/class/FVSkyview.tcl to read: set token [::http::geturl "skyview.gsfc.nasa.gov/cgi-bin/pskcall" \ Table Column Selection: With v2.6, fv displays all columns of a table by default when the Table button in the summary window is pressed. Previous versions brought up a column selection dialog box. To get this dialog box in fv 2.6.x, right-click the Table button instead. Under Mac OS a command-click was also supposed to be available but this was not implemented. The solution is to insert the following lines at line 1109 of "<fv>:fv Sources:class:FitsFile.tcl": bind $subwin.tab$i { tkButtonDown %W } bind $subwin.tab$i \ "[code $this setNewTable 1]; tkButtonUp %W" XPA access: Use of fv's XPA scripting feature requires one to build XPA's tcl library and put it where fv can find it. This can be done by using the following commands in XPA's source directory to configure/build XPA after having installed fv... ./configure --prefix=$FV --with-tcl=$FV/lib make make install 24-bit displays: When run on some architectures supporting TrueColor mode, fv fails to identify that fact and enters the wrong video mode, giving an X Error: BadMatch message. The solution is to force fv into true color mode by running fv with a "-cmap 2" option (ie, type 'fv -cmap 2 file.fits'). RA/Dec Labels: Shortly after the release of fv 2.6, a bug was found in which all column-column plots would have RA/Dec axis labels. A bug fix release (v2.6.1) was made available late on February 11, 2000. For those who already downloaded and installed 2.6, the solution is to edit the file <fv>/fv/class/Table.tcl. Before line 784 (reading, } else { ) insert the lines } elseif { [lindex $wcsinfo 7] == "none" } { set powWCS($graphHandle) "" make fv1 Paths with spaces: After opening a file with a path which contains spaces, fv will report an error like Called openFitsKwds with too many arguments when trying to view an extension. The solution is to either move the file to a directory without spaces, or upgrade to the latest version of fv. RedHat 6.x: The version 6 releases of RedHat Linux are incompatible with the original fv2.5 release dated April 30, 1999. An updated tar file, dated July 12, 1999, has been placed on the FTP site, fixing the incompatibility. For those who have already downloaded the file, the solution is the edit the file <fv>/tcl8.0.4/generic/tclPosixStr.c. Change lines 339 and 786 from #ifdef EOPNOTSUPP #if defined(EOPNOTSUPP) && (!defined(ENOTSUP) || (EOPNOTSUPP != ENOTSUP)) Windows Environment Space: Running fv requires the creation of several environment variables at startup. On some systems (Windows only), this fills up the environment space, causing an error like "couldn't read file \fedit" when trying to run fv. The solution is to tell Windows to allocate more space. To do this, edit your system file C:\CONFIG.SYS and add the following line at the end of the file: SHELL=C:\COMMAND.COM /E:4096 /P missing USERNAME: Some Windows systems do not define the environment variable USERNAME which fv uses to write a History keyword to fits files when they are modified, so one encounters the error "can't read "env(USERNAME)": no such element in array". The solution is to either (1) turn off the "Write History Keyword" option in the Option menu of the file summary window; or (2) replace line 558 of <fv>\lib\fv\class\FitsHeader.tcl and line 2567 of <fv>\lib\fv\class\Table.tcl (both of which read "set uname $env(USERNAME)") with the following lines: if { [info exists env(USERNAME)] } { set uname $env(USERNAME) } else { set uname "???" } This does not affect any system other than Windows-based PCs. Undefined symbol: When starting fv under SunOS 4, you will likely encounter the error Undefined symbol: _Itcl_ReleaseData. Although we do not know why this occurs (something to do with the old Sun linker, maybe), we do have a simple fix. The solution is to edit two files in the <fv>/fv directory. First, edit fv (ie, <fv>/fv/fv). The last line begins with $FV/bin/wish8.0. Change this to $FV/bin/itkwish3.0. Second, edit fedit. Delete lines 15-18 which contain package and namespace commands. Finally, go to the <fv> directory and type Copy Table to ASCII file (part 1): When selecting this File menu item from the FITS table window, you will encounter the error message "invalid command 'feedback'". The solution is to edit the file <fv>/fv/class/Table.tcl and modify line 2443 to read: iwidgets::feedback ${fileWin}.f.fb -labeltext "Saved" Copy Table to ASCII file (part 2): After fixing the preceding bug, this command will execute but it will only copy (repeatedly) the first 1000 lines of the table to the ASCII file. The solution is to edit the file <fv>/fitsTcl/fitsUtils.c and replace all instances of the line m+1, m+fRow, make fitstcl1 install-fitstcl Startup error: The original unix standalone distribution of fv 2.4 contains an error in the startup script. It incorrectly uses the FTOOLS variable instead of the FV variable when setting the necessary paths to the fv binaries and libraries. The solution is to edit the file <fv>/fv/fv and change all references to FTOOLS with FV. Then, in the <fv> directory, type the following command: Note: This only affects the standalone version of fv. The version contained within the FTOOLS themselves, either built using the source distribution or the binary plus GUI distribution, should be using the FTOOLS variable in the <fv>/fv/fv file. Printing Images (windows): It is not possible to print (either to a printer or a file) images from POW under windows. This is due to a limitation in the TK software from which POW is built. It is still possible to print graphs containing line plots. Any images will simply be ignored. Unfortunately, there is no solution to this problem. Printing (all): When printing POW graphs, only the visible part of the window gets printed, so if part of a graph falls outside the window, it will get clipped. To avoid this, either (1) make sure the entire graph (or graphs) are visible before printing, or (2) replace lines 781-792 of file <fv>/pow/pow.tcl with the following lines: proc powPrint { type name orient } { set bbox [.pow.pow bbox all] set width [expr [lindex $bbox 2]-[lindex $bbox 0]] set height [expr [lindex $bbox 3]-[lindex $bbox 1]] if [string match "Print*" $type] { set fnam "[pid]tmp.ps" .pow.pow postscript -colormode color -rotate $orient -file $fnam \ -width $width -height $height \ -x [lindex $bbox 0] -y [lindex $bbox 1] set comm "cat $fnam | $name" exec /bin/sh -c $comm catch {exec rm $fnam} } elseif [string match "File*" $type] { .pow.pow postscript -colormode color -rotate $orient -file $name \ -width $width -height $height \ -x [lindex $bbox 0] -y [lindex $bbox 1] } powShowHandles 1 } make install-pow A service of the Astrophysics Science Division at NASA/GSFC and the High Energy Astrophysics Division of the Smithsonian Astrophysical Observatory (SAO)
http://heasarc.gsfc.nasa.gov/ftools/fv/fv_bugs.html
CC-MAIN-2015-48
refinedweb
1,575
62.68
's the problem with Python 3.x? It was first released in 2008, but web hosting companies still seem to offer Python 2.x rather. For example, Google App Engine only offers Python 2.7. What's wrong?... There's nothing wrong with Python 3, but as Kiran says, it takes time for people to migrate. Most cheap web hosts don't offer Python _at all_, but those that do have the choice of which version(s) to provide. It may be possible to call up either a 2.x or a 3.x by looking for "python" or "python3" - give it a try. I'm starting a new project from scratch so I think its finally a time to switch to the latest and greatest Python 3.4. But I'm puzzled with MySQL support for Python 3. So far the only stable library I've found it pymysql. All others are either abandoned work-in-progress projects or do not support Python 3: So what library do you use for MySQL access in Python 3? I'm specifically interested in async support (like in psycopg2 for PostgreSQL) since I'm planning to use Tornado. I need a command that will make threads created by "multiprocessing.Process()" wait for each other to complete. For instance, I want to do something like this: job1 = multiprocessing.Process(CMD1()) job2 = multiprocessing.Process(CMD2()) jobs1.start(); jobs2.start() PY_FUNC() The command "PY_FUNC()" depends on the end result of the actions of CMD1() and CMD2(). I need some kind of wait command for the two threads that will not let the script continue until job1 and job2 are complete. Is this possible in Python3? I seem to stumble upon a situation where "!=" operator misbehaves in python2.x. Not sure if it's my misunderstanding or a bug in python implementation. Here's a demo code to reproduce the behavior - From __future__ import unicode_literals, print_function class DemoClass(object): def __init__(self, val): self.val = val def __eq__(self, other): return self.val == other.val x = DemoClass('a') y = DemoClass('a') print("x == y: {0}".format(x == y)) print("x != y: {0}".format(x != y)) print("not x == y: {0}".format(not x == y)) In python3, the output is as expected: x == y: True x != y: False not x == y: False In python2.7.3, the output is: x == y: True x != y: True not x == y: False which is not correct!!? 2018 © Queryhome
https://www.queryhome.com/tech/28315/whats-the-problem-with-python-3-x
CC-MAIN-2020-24
refinedweb
408
76.93
#include "orconfig.h" #include <stddef.h> Go to the source code of this file. Length of a buffer to allocate to hold the results of tor_inet_ntoa. Definition at line 21 of file inaddr.h. Referenced by fmt_addr32(), and tor_addr_parse_PTR_name(). Set *addr to the IP address (in dotted-quad notation) stored in *str. Return 1 on success, 0 if *str is badly formatted. (Like inet_aton(str,addr), but works on Windows and Solaris.) Definition at line 38 of file inaddr.c. References tor_sscanf(). Referenced by router_find_exact_exit_enclave(), tor_addr_parse_PTR_name(), and tor_inet_pton(). Given an IPv4 in_addr struct *in (in network order, as usual), write it as a string into the buf_len-byte buffer in buf. Returns a non-negative integer on success. Returns -1 on failure. Definition at line 58 of file inaddr.c. References tor_snprintf(). Referenced by fmt_addr32(), and tor_inet_ntop(). Given af==AF_INET and src a struct in_addr, or af==AF_INET6 and src a struct in6_addr, try to format the address and store it in the len-byte buffer dst. Returns dst on success, NULL on failure. (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it: Tor sometimes needs to format ipv6 addresses even on platforms without ipv6 support.) Definition at line 77 of file inaddr.c. References tor_inet_ntoa(), and tor_snprintf(). Referenced by tor_addr_to_str(), and tor_dup_ip(). Given af==AF_INET or af==AF_INET6, and a string src encoding an IPv4 address or IPv6 address correspondingly, try to parse the address and store the result in dst (which must have space for a struct in_addr or a struct in6_addr, as appropriate). Return 1 on success, 0 on a bad parse, and -1 on a bad af. (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor sometimes needs to format ipv6 addresses even on platforms without ipv6 support.) Definition at line 166 of file inaddr.c. References tor_assert(), tor_inet_aton(), and tor_sscanf(). Referenced by string_is_valid_ipv4_address(), and string_is_valid_ipv6_address().
https://people.torproject.org/~nickm/tor-auto/doxygen/inaddr_8h.html
CC-MAIN-2019-04
refinedweb
322
60.31
Disclaimer Before starting, it is very important to remember that at the time of writing, Deno is still under development. Therefore, any produced code must be considered unstable due to potential unanticipated changes in the API. We will therefore use version 0.21.0 as a basis for the next step. Finally, it should also be noted that Deno is not intended to replace Node or merge with it. Introduction & Architecture Deno is a cross-platform runtime, i.e. a runtime environment, based on Google's V8 engine, developed with the Rust language, and built with Tokio library for the event-loop system. Node's problems: Deno was presented by its creator, Ryan Dahl (@ry ) at the European JSConf in June 2018, just 1 month after the first commits. During this presentation, Dahl exposed ten defects in Node's architecture (to which he blames himself). In summary: - Node.js has evolved with callbacks at the expense of the Promise API that was present in the first versions of V8 - Security of the application context - GYP (Generate Your Projects), the compilation system forcing users to write their bindings (links between Node and V8) in C++while V8 no longer uses it itself. - The dependency manager, NPM, intrinsically linked to the Node requiresystem. NPM modules are stored, until now, on a single centralized service and managed by a private company. Finally, the package.jsonfile became too focused on the project rather than on the technical code itself (license, description, repository, etc). - The node_modulesfolder became much too heavy and complex with the years making the module resolution algorithm complicated. And above all, the use of node_modulesand the requirementioned above is a divergence of the standards established by browsers. - The requiresyntax omitting .jsextensions in files, which, like the last point, differs from the browser standard. In addition, the module resolution algorithm is forced to browse several folders and files before finding the requested module. - The entry point named index.jsbecame useless after the require became able to support the package.jsonfile - The absence of the windowobject, present in browsers, preventing any isomorphism Finally, the overall negative point is that Node has, over time, unprioritize the I/O event saturation system to the benefit of the module system. Deno's solutions: Dahl then began to work in Deno with the aim of solving most of Node's problems. To achieve this, the technology is based on a set of rules and paradigms that allow future developments to follow the guideline: Native TypeScript support One of the top most creator's goals, who has a very special interest in the language. Over the years, we have seen Node struggle with maintaining support for new V8and ECMAScriptfeatures without having to break the existing API. It's over with Deno, which gives you the ability to use TypeScript right away without initial configuration of your application. The use is limited to the native configuration of the default compiler. However, a tsconfig.json file can be given to the compiler using the flag --config=<file>. Isomorphism with the Web by supporting ECMAScriptmodule syntax and by banishing the require()function As mentioned above, Node suffers from ineffective dependency resolution; Deno solves the problem by being more explicit, simple, and direct, while complying with standards. (import * as log from "";) The distant code is retrieved and cached locally Like the node_modules, the dependencies that are necessary for the proper working project are downloaded and retrieved locally. However, they will not be stored at the project level but rather in Deno's global cache folder. ( ~/.deno/srcby default) The same version of a dependency does not need to be re-downloaded regardless of the number of local projects requiring it. Note that this feature is similar to yarn plug'n'play. Specific permissions must be explicitly given by the end user Today, security is foundamental in every applications. For that, Deno contains the executable in a sandbox mode where each operation outside the execution context must be authorized. A network access for example must be granted by an explicit "yes" from the user in the CLI or with the --allow-netflag. Once again, Deno wants to move closer to Web paradigms. (access to the webcam by website for example) One delivrable, one executable In order to ensure efficient distribution, Deno offers its own bundler ( deno bundle) creating a single consumable (.js) at the time of delivery and later, a single executable binary ( deno compile). Last but not least... Deno also aims to always terminate the program in case of unprocessed errors; to have generated JavaScript code compatible with current browsers; to support Promises at the highest level of the application ( top-level await, supported by V8, on wait on the TypeScript side); to be able to serve over-HTTP at an efficient speed (if not faster than Node). What Deno doest not target (at all): The use of a package.json-like manifest A dependency management manifest is not required for a code that retrieves its dependencies itself. The use of an package manager like npm For the same reasons, npm(or equivalent) is not and should not be essential to the development of a Deno application. Deno / Node isomorphism Even if the two technologies use the same language, the designs are not the same and therefore do not allow isomorphic code. Le architectural model: Rust Rust is the language used to encapsulate the V8 engine. It is he who exposes the isolated functionalities through an API that can be used in JavaScript. This link, or binding, called libdeno, is delivered as is, independently of the rest of Deno's infrastructure, thanks to a Rust module called deno-core (a crate;) consumed by the command line, the deno-cli. This crate can be used in your own Rust app if you want to. The deno-cli is the link between the crate core, the TypeScript compiler (hot compilation and cache of the final code), and Tokyo (an event-loop library). To summarize, here is a diagram of the execution process: Tokio This library written in Rust gives the language the capability of asynchronous programming and event-oriented programming. Natively, Rust does not support event loop management, and has, until 2014, used the libuv library to perform its I/O operations asynchronously and cross-platform and thus remedy this flaw. It should be noted that Node still uses libuv today in its V8 process. Thus, Tokio became the reference library for all asynchronous event-driven programming in Rust. From Deno's point of view, Tokio is therefore in charge of parallelizing all the asynchronous I/O performed by the V8 bindings exposed in the deno-core isolate (as a reminder, deno-core is the standalone Rust crate) V8 Finally, as mentioned several times earlier, the entire architecture is based on the JavaScript interpretation engine. It is regularly updated to follow the needs of the latest versions of TypeScript, among other things. At the time of writing, the version used by Deno is version 7.9.304 from October 14, 2019. Ecosystem & First Developments Installation : For several versions now, Deno is available via Scoop for Windows, and via Homebrew for OSX. Installation can also be done manually via cURL under Shell, especially for Linux which only has this solution for the moment, or via iwr under PowerShell for Windows. In the same philosophy as the code, Deno is delivered as a single executable. # Shell curl -fsSL | sh # PowerShell iwr -useb | iex # Scoop scoop install deno # Homebrew brew install deno Once the installation is complete, launch the command deno to test its proper functioning. deno-cli The command-line interface provides a set of integrated features that allow you to remain immersive in Deno's proprietary development environment. It also and above all allows you to stay in line with standards when you need to offer your library to the community. Here is a list of the commands currently available: deno infoallowing to inspect the dependencies of a program from its entry point deno fmtallowing the code to be formatted with an integrated Prettier deno bundlementioned earlier, allowing to transpile our application into a single deliverable with dependencies, into an .jsfile (usable by the browser) deno installallowing to install a Deno app in home folder ( ~/.deno/binby default) from an URL or from local code deno typesallowing to generate Deno's TypesScript types for development deno testallowing to execute the integrated test tool. (Deno integrates its own test library) deno completionsallowing to add autocomplete in the terminal (normally already added during the Deno installation) deno evalallowing to interpret a file or string containing code executable by Deno deno xeval(named on the same idea as xargs) allowing deno evalto run code, but by taking each line coming from stdin "HelloWorld.ts" Now let's talk about our first program. At the moment, even if the Deno ecosystem itself offers a range of development tools that can be used on the command line, the VSCode extension catalog (or other editor) remains very poor in features. Don't expect a complete developer experience during your first lines of code. Example 1: Grep This first example is a simple reproduction of grep's behavior and highlights the import of Deno standard libraries, their usage, as well as the manipulation of files and arguments. In order to group them, dependencies can be declared in a file conventionally called deps.ts: import * as path from ""; export { path }; export { green, red, bold } from ""; Then be imported classically into its mod.ts (equivalent to the index.js in Node): import { path, green, red, bold } from "./deps.ts"; An "http" import from Deno is the retrieval of a web resource at the time of compilation. Deno currently only supports http://, https://, and file:// protocols. Then, we validate the arguments passed and retrieved directly from the Deno global object: if (Deno.args.length != 3) { if (Deno.args.length > 3) { throw new Error("grep: to much args."); } else { throw new Error("grep: missing args."); } } const [, text, filePath] = Deno.args; Finally, we parse and iterate the file to bring out the lines containing the pattern you are looking for: try { const content = await Deno.readFile(path.resolve(Deno.cwd(), filePath)); let lineNumber = 1; for (const line of new TextDecoder().decode(content).split("\n")) { if (line.includes(text)) { console.log( `${green(`(${lineNumber})`)} ${line.replace(text, red(bold(text)))}` ); } lineNumber++; } } catch (error) { console.error(`grep: error during process.\n${error}`); } Finally, to launch the application, execute the command deno grep/mod.ts foo grep/test.txt foo being the pattern, and test.txt a file containing strings. Exemple 2 : Overkill Gues-A-Number This second example is a mini game where the goal is to find a number between 0 and 10 from "more" or "less" clues. It highlights the use of a third-party framework, the import of React, and JSX compatibility. The import of a third party is almost identical to the import of a standard: import Home from "./page.tsx"; import { Application, Router, RouterContext } from ""; import { App, GuessSafeEnum, generate, log } from "./misc.ts"; A .tsx file being imported, React must be used to be able to run the whole thing. The page.tsx file is completed as follows: import React from ""; import ReactDOMServer from ""; Thanks to the .tsx extension and React, we can use JSX to export a component rendered on the server side for example : export default (props: HomeProps = {}) => `<!DOCTYPE html> ${ReactDOMServer.renderToString(( <> <Home {...props} /> <hr /> <Debug {...props} /> </> ))}`; You can run this example with the command deno guessanumber/mod.ts Finally, you can find the complete examples on Github or even run them directly from their "raw.githubusercontent" URLs. () Production & Futur Right now, Deno is not ready-to-prod. The main uses being to create command line tools, background task managers, or web servers (like Node), Deno's performance is not at the level Dahl wants it to be. However, it is possible to start experimenting with the development of internal tools such as batch scripts for example. A real-time benchmark is available on Comit after comit, the benchmarks are updated and compare Deno's performance to that of Node on several levels, such as the number of requests per second (which is the first bottleneck blocking production use), maximum latency, input-output interactions, memory consumption, etc. Deno is already better than Node on a few points and keeps improving over time, hoping to finish first in all the tests performed. v1.0 In addition to performance, Deno completes the developer experience with a set of essential features and tools for the release of version 1.0 that can be considered ready for production use. Debug It is not currently possible to debug or inspect an application; something that can be constraining during development. This major feature is mandatory for version 1.0. Taking advantage of V8, the debug will rely on the V8InspectorClient and the Chrome Devtools allowing to use the same tools as with any other JavaScript development. API Stabilization There are and still are some bugs in the API, either in the TypeScript layer or in the deno-core. These bugs, although minor, are still blocking the good stability of the whole. Being stable does not only mean having a smooth execution, but also having consistent and uniform entry points. Some functions must therefore be reviewed in terms of their name or even their signatures. Clear and explicit documentation The common problem with any project starting in the background - the Deno documentation is still very light and lacks use cases or explanations on specific topics. The official website is currently being redesigned and will soon be completed. Futur Decoupled from the first stable release, additions to the CLI will be made, support for adding native functionality (via modules called "ops" crates in Rust) will be provided, as well as, among many other things, ever closer compatibility with the Web world and ECMA standards (e.g. by supporting WebAssembly modules). Concerning the CLI, here is a non-exhaustive list of the planned functionalities: deno compileallowing to compile its entire application into a purely independent binary. deno docallowing to generate a JSON structure of the whole code documentation. This JSON will then be standard to Deno and can then be consumed by a visual documentation tool that includes said standard. deno astallowing to generate a JSON structure of the Abstract Syntax Tree (AST) of the code from a given entry point. The AST can be used by tools like ESLintto programmatically analyze the code structure and identify, for example, potential code flaws or memory leaks. - The deno lintwhich, in combination with deno fmt, will make it possible to make the code produced consistent between all the developers and also to improve the quality by ensuring that it is in line with Deno standards. Please note that the linter configuration will not be accessible or modifiable at the moment. Version 1.0 is very close and the fast pace of development has allowed the team to estimate a release for the end of the year or early January. It is important to remember that Deno remains an open source and community project, and that it is up to the community to help by experimenting with the technology, pushing it to its limits, and providing as much data as possible to the developers. Community & Contribution Due to its relatively young age, the Deno community is still small. Nevertheless it is growing every day and many developers from Rust or Node are more and more interested in the technology. The biggest communities today are Polish (which includes one of the major contributors through Bartek Iwańczuk (@biwanczuk) ), Korean, Chinese or Japanese. Meetup groups are therefore gradually being created like Deno Poland (@denopoland), or Denoland Korea (@denoland_kr). France is not to be outdone and already has its first group, Paris Deno (@ParisDeno). A newsletter is also available on From a contribution point of view, there is a lot to be done. Pull requests on official repositories are "simple" to do as a list of missing features and bugs is available at. In addition, the contribution rules have been written and completed for the occasion. The TypeScript layer consists of a core, a set of standard deno_std libraries (), and a set of third-party libraries combined into a single directory to simplify URLs (). Contributions made to the standard and the core must respect the rules, but this is not the case for third-party libraries. Contributions can also be made at the development tool level. Indeed, there is still a lot missing to be comfortable and productive such as VSCode extensions or test libraries equivalent to Jest or fast-check (whether they are ported, "isomorphized", or rewritten). Deno needs you, feel free to go ahead and submit your content; many of the libraries offered are ports of existing libraries from Node, Rust, or even Go. In conclusion, Deno is still in its early stages, but Ryan Dahl is not at his first try. Thanks to the new features of version 1.0, the usability of TypeScript, the more and more interesting performances, and last but not least, because of the confident and growing community, Deno will undoubtedly become one of the potential trending technologies to capitalize on for 2020/2021. Stay tuned! Discussion Hi! Thank you for the article! Deno indeed seems very interesting, and it's a project I'll keep an eye on. However I do have some questions regarding dependency resolution: package-lock.jsonfile, so all of my installations are identical? Hello :) 1/ 3/ So dependency management is not the main goal of Deno. Dependencies should be handled and maintained by the source where the dependency file is fetched (e.g. raw.githubuser). Basically dependencies are "locked" with git ref (branch, sha, tag). But, to ease the process, Deno recently released a new feature in 0.23 (the article is for 0.21): lockfile ! github.com/denoland/deno/pull/3231 1/ 2/ If you want to have a more centralized way to handle all your dependencies, you can have a file named deps.tsthat act as a dependency barrel (e.g. github.com/bios21/deno-intro-progr... ) ; also, import map is another option deno.land/std/manual.md#import-maps If you're interested in Deno, another interesting project to watch is Entropic. It's a new package registry being developed as an alternative to npm. One of its main goals is to enable a decentralized environment so developers aren't beholden to a single organization/company. It's also written in Rust and I'm excited about how Deno and Entropic could reshape the web development space. Hi, thanks for the excellent intro to Deno. Please can you direct me on how to create a meet-up group?
https://dev.to/lsagetlethias/deno-first-approach-4d0
CC-MAIN-2020-50
refinedweb
3,133
53.41
#include it. #include <stdio.h> #include <search.h> #include <string.h> #include <stdlib.h> struct info { /* this is the info stored in table */ int age, room; /* other than the key */ }; #define NUM_EMPL 5000 /* # of elements in search table */ main( ) { /* space to store strings */ char string_space[NUM_EMPL*20]; /* space to store employee info */ struct info info_space[NUM_EMPL]; /* next avail space in string_space */ char *str_ptr = string_space; /* next avail space in info_space */ struct info *info_ptr = info_space; ENTRY item, *found_item; /* name to look for in table */ char name_to_find[30]; int i = 0; /* create table */ (void) hcreate(NUM_EMPL); while (scanf("%s%d%d", str_ptr, &info_ptr−>age, &info_ptr−>room) != EOF && i++ < NUM_EMPL) { /* put info in structure, and structure in item */ item.key = str_ptr; item.data = (void *−>key, ((struct info *)found_item−>data)−>age, ((struct info *)found_item−>data)−>room); } else { (void)printf("no such employee %s\n", name_to_find) } } return 0; }.
http://docs.oracle.com/cd/E36784_01/html/E36874/hsearch-3c.html
CC-MAIN-2015-48
refinedweb
142
54.22
Relay is an irc micro-framework that smells too much like a web framework Project Description Release History Download Files An irc micro-framework that smells too much like a web framework. Relay is a toy project, its goals were for me to try out framework design, learn more about the IRC protocol, and to be a replacement for the available irc python libraries: most of them did not please me. Installation I suggest you use a virtualenv $ pip install relay-framework Example This is an example of a bot that sends whatever is send after ‘!echo ‘ in a PRIVMSG: from relay import Relay, auto_join, auto_pong from relay.constants import privmsg bot = Relay("echobot") @bot.handler(privmsg) def echo(target, message, sender, *args, **kwargs): if not message.startswith("!echo "): return sender_nick = sender.split('@')[0].split('!')[0] # We just want the nick message = message[6:] # We just want whatever is after '!echo ' if target == bot.client['nick']: result = "PRIVMSG {sender_nick} :{sender_nick}: {message}" else: result = "PRIVMSG {{target}} :{sender_nick}: {message}" yield result.format(sender_nick=sender_nick, message=message) if __name__ == "__main__": bot.register(auto_pong) bot.register(auto_join(['#tests'])) bot.config(from_env=True).run() And to run it: $ RELAY_HOST=irc.example.net RELAY_NICK=echobot python echobot.py Changelog Todo - Write a decent IRC client implementation - Write tests for the Relay class - Write documentation - Subclass Relay to allow regexp routes Download Files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/relay-framework/
CC-MAIN-2017-51
refinedweb
245
57.37
Introduction: bags of an unknown amount and weight of uncrushed cans, I decided to make a machine that would crush the cans, count the cans, and tell the weight of the number of cans that it has crushed. I searched the internet and have found no machines that count the cans that have been crushed or tells the weight of the total crushed weight and could also be made from low cost and recycled materials. Once" the motor--it should spin continuously (use a bolt on the motor to attach the ground). Step 3: Part 2: Building the Chasis square gives you the width of the final part as well as the the distance between the 4 1/4" smooth rods. Towards the outercenter of the boards the actuators will be mounted. I placed the one of the boards on the other to make the holes in line. Drill out the outer holes (actuator mounting holes) to 5/8" in one board and 1/2". Next, place a 1/2" coupler in the 5/8" from the back, and add some epoxy. The inner four holes should be 1/4" for the rods to be mount into on the board with 1/2" holes on the outside (the other should be slightly larger), this will act as a can retainer/guide. The top and bottom portions of the boards should be trimmed to the diameter of a can. After the epoxy dries you can now run the 1/2" threaded rods through the boards and install the pulleys on the rods. Now place the belt on the pulleys along with the motor, then measure the distance from the bottom of the board to the top of the pulley, on the motor add about an inch and you have the height of the next board you need to cut for the front wall of the "box" the width is 12". Remove the pulleys from the rods and place the board with the 1/2" holes (the can retainer mount [not the one with the couplers in it]) and use it as a template to make holes in the front wall. Drill it out to 1/2" using the can retainer mount board as a retainer, remove the template then drill the holes to 5/8" so that the sleeves fit in them. Use some epoxy on the sleeves to keep them in the board. This should be flat on the side that meets the can retainer mount and should stick out on the other side (this will work to reduce friction). You can use this board's width and height for the back wall of the box. motor is plus the thickness of the back wall of the box. This will be used to draw an outline of the back part and to make a bottom for box. The outline should be drawn including the front part of the machine as well. This should look similar to the bottom on image 11 and 12. Now cut a square hole wider than the diameter of a can and length slightly smaller than the diameter of the can. Add some supports fot the back and side walls to the bottom as shown in image 14. Now place the motor with the pulley on the belt, pull the belt tight and mark the top of the front board. Measure the distance and now make a 1/4" hole in the back wall so the fence pole connector around the motor will hold the pulley up to the measurement on the back board that was taken from the front board. Use the 1/4" threaded rod, lock washers, large OD washers, and nuts to mount the motor to the back wall. Measure the distance from the front and back wall and make top supports, side walls and top. Also be sure to drill a 1/2" hole in the bottom for the wires. Step 4: Part 3: Programing and Circuit Design The Program : #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2); // LCD on pins 12, 11, 10, 5, 4, 3, 2. int StartPin = 9; // switch input int motor1Pin = 7; // H-bridge leg 1 (pin 2, 1A) int motor2Pin = 6; // H-bridge leg 2 (pin 7, 2A) int enablePin = 8; // H-bridge enable pin int DirPin = 13; // Motor direction select int DirSwCounter = 0; int LastDirState = 15; int Dir = 14; int cansCrushed; // Initial number of cans crushed set to 0 void setup() { // INITIALIZE pinMode(StartPin, INPUT); pinMode(DirPin, INPUT); pinMode(motor1Pin, OUTPUT); pinMode(motor2Pin, OUTPUT); pinMode(enablePin, OUTPUT); digitalWrite(enablePin, LOW); lcd.begin(16, 2); lcd.print("Can Crusher MKII"); delay(3000); lcd.clear(); lcd.setCursor(0, 0); lcd.print("Crushed:"); lcd.setCursor(10, 0); lcd.print((int)cansCrushed); lcd.setCursor(0, 1); lcd.print("Weight:"); lcd.setCursor(9, 1); lcd.print((int)cansCrushed*.034375); pinMode(StartPin, INPUT); pinMode(DirPin, INPUT); pinMode(motor1Pin, OUTPUT); pinMode(motor2Pin, OUTPUT); pinMode(enablePin, OUTPUT); digitalWrite(enablePin, LOW); cansCrushed = 0; } void loop() { // READ PINS int DirState = digitalRead(DirPin); if (LastDirState == LOW && DirState == HIGH) { DirSwCounter++; } LastDirState = DirState; // PROCESS if (DirSwCounter % 2 == 0) { digitalWrite(Dir, LOW); cansCrushed++; } else { digitalWrite(Dir, HIGH); } if (digitalRead(StartPin) == HIGH && digitalRead(Dir) == LOW) { digitalWrite(enablePin, HIGH); digitalWrite(motor1Pin, HIGH); digitalWrite(motor2Pin, LOW); } else if (digitalRead(StartPin) == HIGH && digitalRead(Dir) == HIGH) { digitalWrite(enablePin, HIGH); digitalWrite(motor1Pin, LOW); digitalWrite(motor2Pin, HIGH); } else { digitalWrite(enablePin, LOW); } } The wiring diagram for the machine is shown below. For this design I used Fritzing, it is pretty awesome. Build the circuit board from this design, but don't add the switches yet. Step 5: Part 4: Making a Home for the Electronics.. Grap the piece of metal that came with the project box and bend one edge to make it j-shaped. From here on we will call this the control box. Step 6: Part 5: Sanding and Painting the Machine If you want to make everything match you will need a can of flat black spray paint and some sand paper. The whole thing needs to be sanded well before you try to paint it. Remember to remove the motor, the threded rods, and cover everything you don't want covered in paint with tape. Now paint away! Once the paint is dry and looks good, remove the tape, replace the motor, and insert the threaded rods. Step 7: Part 6: Adding the Control Box and Hopper Mount the control box on to the j-shaped piece of metal with a screw and then mount the other end of the j to the bottom of the chasis. Run the wire wrap along the bottom and attach the wires from the motor to the wires from the motor controller. Connect the DirPin switches to the wires that correspond to the them and hot glue them to the points where you want them to be triggered (ie: DirPin switches should be at the full open position and the other should be to about 1/2" to 1" from the can ejection hole (square hole in the bottom board). Now grab an empty soda box and cut a hole in it so there is a cool looking window; this is now our can hopper.. This can be made with small scraps of lumber. I made one from a small rectangular piece and a square piece. Cut a slot in it so the switch can fit in it. After you sand it down and paint it insert the switch and use a piece of cardboard to lengthen the switch.! Lets start with the DirPin switches, these badboys are wired to act like one switch. Wire the power (5 volts) to a common terminal on the closer switch, then make a jumper from the common pin from that switch to the common pin of the other DirPin switch. Now wire pin13 of the arduino to the normally open teminal of the closer switch, then like the power terminals, jumper the normaly closed terminals together. Now you are almost ready to try it out. Step 8: Part 7: Attaching an External Power Supply and Finnishing Up Find an old 12v power supply that meets the needs of the motor and doesn't exceed the limits of the motor controller, and wire the positive to pin 16 of the motor controller and the negative to pin 4, 5, 12, or 13 of the motor controller. The Wire should be fed through the wire wrap and into the control box. Step 9: Bonus Points! Keep all of your receipts and calculate how much it costed to build this machine. Call the local recycling center and get the price of aluminum, then: 1) Add code to the program that will tell you how many cans you are away from paying for the parts. 2) Add code that will tell you how many cans away from buying solar panels to power the machine you are. 3) Add code that will tell you how many can you are away from paying for more soda.. Step 10: Build Improvements I had some ideas after building this that can improve performance and building time: 1.. Always make pilot holes. 6. Use some old Powerwheels motors along with relays to control the direction instead of the motor controller. 7. Use a chain and sprockets instead of a belt and pulleys. Step 11: Thanks: I wanted to dedicate a part to thanking those who helped me along the way: My dad for the parts, Dr. Manning for looking at my code and addon ideas, Brandi for not killing me, robtillaart and AWOL from the arduino forum for helping me get the code working, my brother for giving me input, and anyone who builds one of these machines. Finalist in the MakerBot Challenge First Prize in the Spring Cleaning Contest 43 Discussions. Im technician new to this (using Arduino), and trying to do the same thing as you im good electronically, and mechanically but not with programming this is way new to me I can get some examples uploaded in sketch but not yours do you have any hints, im getting allot of compiling errors. when im done ill post mine with my schematic thanks in advance. Hey dude! I would like to ask you if you could put up a video on how this works if you don't mind :3 You could simplify this to a battery, a switch, and a motor. But it makes it so much easier to go without the screen. To do what you want to do, you will need a motor controller to go with the arduino so you can control the direction of the motor. If I were to redo this machine, I would use gears instead of a belt (it slips too much). I took the machine apart and threw most of it away. I am going to use the motor and arduino for a plastic recycler, but I can walk you through it. hi i would like to know is there any motor that can crusher 5tins at once? Thanks for the question, I wish I knew what you were asking. You could crush 5 cans at once but it would be better if it was chain driven instead of belt. the crushing part would have to be wider. Great idea and instructable. How do you get the weight of the crushed cans? The weight of the crushed is number of crushed cans multiplied by the weight of one aluminum can. Thanks for the commment. How cool! I was so pleased to see you included safety goggles :) One question- what is arduino? Way to go! Love Your cousins in Alabama An arduino is a micro-controller, which serves as the "brains" which controls the electronics--giving the machine instructions what to do when an event happens. WOW!! A video? Awesome idea! Good luck with the votes!! Thanks! Great idea! You get my vote! Thanks for the vote and the comment! its so cool how it has a "magazine" of cans. great instructable! i hope you dont mind me asking but are you using Circuit Wizard? (first pic - step 4) It is made by a program called fritzing, which can be found at fritzing.org. Thanks for the comment. I love 3, 4, and 7. XD... Great project!!! Thanks!
https://www.instructables.com/id/Arduino-Controlled-Can-Crusher-With-LCD-readout/
CC-MAIN-2018-34
refinedweb
2,052
77.06
In Oriley's C++ in a Nutshell, a namespace is defined as: A namespace is a named scope. This means that if you enclose something (like a class) inside a namespace, you can use multiple classes or packages of the same name by using a differnet scope for each package. For example you can write code like this: namespace1::fraction namespace2::fraction namespace3::fraction The use of namespaces can be useful to both experienced and begging programers. I will explain both of these points in more detail later, but for now, lets look at how to construct a namespace. Namespaces are alot like structures except they can hold functions and are not data types. You set up namespaces like structures as well, and the function deffinitions are the same as function deffinitions in classes. So without any further explination, you are now ready to construct a namespace. You can place a namespace into one file, but we will be using a header file and an extra .ccp file for this namespace. So first we will construct the header file. open a new header file in your compiler and type in the following. #include <iostream> using namespace std; namespace newnspace { void describe(void); int addNums(int, int); } The first two lines are the same as in most programs. They are included so that the describe function can be used (shown later). The fourth line is the namespace declaration. All you have to do is type namespace followed by the name of the namespace. Once completed, you fill the namespace with any functions you want to put in it and then close up the bracket. Name this file newnspace.h and save it for later. For the second file we will use, open a new .cpp file and name it newnspace.cpp. I find it helpful to name my files according to their contents but I do not believe it is neccessary. In this file we will define the functions that we previously set up. So here is what we type into the new file. #include "newnspace.h" void newnspace::display(void) { cout << "This is a namespace" << endl; cout << "They are like classes except you do not" << endl; cout << "Need to declare an object to access their members" << endl; return; } int newspace::addNums(int num1, int num2) { return num1 + num2; } To use the namespace, you have to include the header file, as if you were defining class member functions. First we define display and then we define addNums. Nothing else is needed for this file so we can save it and move on. The last file we have to write is main.cpp. The code for this is simple. #include <iostream> #include "newnspace.h" using namespace std; using namespace newnspace; int main(void) { display(); cout << addNums(1, 3) << endl; system("pause"); } Notice how you have to include the header file of the namespace and the "using namespace newnspace" statement. Also notice how you can call functions without having to declare an object of the namespaces type. Save and compile all three files and you should see data output to your screen. If this dosen't work, main.cpp and newnspace.cpp example files are attatched for convenience. Now many beggining programers will not be creating packages or using multiple classes with the same name in a program. So you may be asking "Why would this be practical?" Well let's say that you have a bunch of functions. Functions for manipulating strings, for searching arrays, for sorting arrays, all kinds of reusable functions. Now lets say you want to put them in a class. Well first you have to declare an object of the class type and then use that object to access the classes members. This process is tedious and inconvenient not to mention somewhat of a misuse of classes. If you were to put these functions into an external namespace however, you could just use the namespace and call the functions whenever you want! In longer programs, this will lead to less errors and less code. In conclusion, namespaces are a powerful part of the C++ language for both beginning and experienced programmers. The code for this tutorial was written and compiled in Dev-C++ so you may need to alter it to make it work in other compilers. I hope that you enjoyed my second tutorial. If you have any revisions, or would like to contribute to the information, please post a reply.
http://forum.codecall.net/topic/44717-namespaces-an-introduction/
CC-MAIN-2018-13
refinedweb
744
73.17
Opened 4 years ago Closed 4 years ago #18720 closed Uncategorized (needsinfo) Code sample for views.html template causes NoReverseMatch error Description The page in question is The code sample for views.html will cause a NoReverseMatchError due to the single quotes in the argument to the bolded url tag below: {% extends "base.html" %} {% load url from future %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="{% url 'django.contrib.auth.views.login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> {% endblock %} Removing the quotes fixes the error. Change History (3) comment:1 Changed 4 years ago by prseshad@… - Needs documentation unset - Needs tests unset - Patch needs improvement unset comment:2 Changed 4 years ago by charettes comment:3 Changed 4 years ago by aaugustin - Resolution set to needsinfo - Status changed from new to closed Are you sure you put the {% load url from future %} in your template?
https://code.djangoproject.com/ticket/18720
CC-MAIN-2016-22
refinedweb
191
58.48
This post by David King on inline Graphviz graphs inspired me to write my first Rack middleware in a long time. David's code uses PHP on the server-end coupled with javascript to parse out Graphviz data from script tags, and then render the graphs with the appropriate Graphviz tool and serve up the image. It's a great solution for "graphviz-as-a-service" if you want a really generic way of service up Graphviz graphs from "anywhere". However for my own use, I don't tend to like doing stuff like this client side, and I don't want to run PHP when the rest of my blog is all Ruby. I also don't need a very generic solution. My blog runs through a multi-stage pipeline that parses an augmented Markdown variation anyway, so I decided I wanted a solution that does it all server-side and simply caches the output. So I figured I'd like something that let me pass in the graph that my filters extract, and get either a url to an inline graph back, or optionally inline SVG, combined with a Rack middleware to handle requests for the graph image (if not using the inline option) and render it and cache it in a file. The dot code: digraph G { graph [ truecolor=true bgcolor="#FFFFFF00" ]; edge [ color=blue; ]; node [ style=filled; fillcolor=blue; ]; this -> that -> more; }; And the inline graph: And another example using a record: digraph structs { node [ style=filled; fillcolor=green; ];; } And the resulting graph: You can find the code below in this GIST rather than trying to cut and paste it together. Lets dive straight in: require 'digest' module GViz CACHE_PATH = "/tmp/gviz/" ENGINES = %w{dot neato twopi circo fdp sfdp} XSLTPROC = `which xsltproc`.chomp notugly = File.dirname(__FILE__)+"/notugly.xsl" NOTUGLY = (File.exists?(notugly) && XSLTPROC != "") ? notugly : nil CONVERT = `which convert` The CACHE_PATH is where we'll store the cached images. ENGINES is a list of the Graphviz tools to use for layout/rendering. The rest of this chunk is used to detect the pre-requisites to process the Graphviz output using my XSL for prettying up Graphviz SVG output - it requires the notugly.xsl file from those articles, as well as xsltproc. If you also want to be able to convert the cleaned up SVG to PNG, it requires a convert equivalent to that from ImageMagick (if my XSL isn't used, the code will get Graphviz to render directly to PNG). class Graph def initialize(graph) @graph = graph end def slug # The MD5 hash is not for security, since I'm not accepting posted graphs, # nor keeping any private graphs. @slug ||= Digest::MD5.hexdigest(@graph) end def write(fname) `mkdir -p #{CACHE_PATH}` File.open(fname,"w") do |f| f.write(@graph) end end def cache fname = "#{CACHE_PATH}#{slug}.dot" write(fname) if !File.exists?(fname) slug end def self.dot_file(slug) "#{CACHE_PATH}#{slug}.dot" end end This small class just contains the code needed to cache the graph somewhere. The graph needs to be available in a file when rendering it, but if you want to store the extracted graph fragments somewhere else, like in a database, replacing this class is an easy way - only the cache and Graph.dot_file methods are called from elsewhere. class Cache def initialize hash,engine,format @hash = hash @engine = engine @format = format raise "Unsupported layout" if !ENGINES.member?(@engine.to_s) end def layout(format, src, dest) system("#{@engine.to_s} -T#{format.to_s} #{src} -o #{dest}") end def xsl(src,dest) system("#{XSLTPROC} --nonet #{NOTUGLY} #{src} >#{dest}") end def convert(src,dest) system("convert #{src} #{dest}") end The above methods layout, xsl and convert covers the conversion. Note: You want to make sure that if you expose this via a web server, that format is sanitized - in my Rack code, I limit this to the strings "png" and "svg". For that matter, this applies to src and dest too, but in my code those never comes from the client. This is just used to determine the target cache filename: def target_file(format=nil) format ||= @format CACHE_PATH+@hash+".#{format.to_s}" end This handles the rendering, including conditionally applying my XSL: def render(format=nil) format ||= @format src = CACHE_PATH+@hash+".dot" dest = target_file(format) if (format.to_sym == :svg && NOTUGLY) layout(format,src,dest +".tmp") xsl(dest+".tmp",dest) elsif NOTUGLY && CONVERT != "" layout(:svg, src, dest+".tmp") xsl(dest+".tmp",dest+".tmp.svg") convert(dest+".tmp.svg",dest) else layout(format,src,dest) end File.read(dest) rescue nil end If you want to change how the URL is formatted (but note if you want to use the Rack handler, you need to change a Regexp for that as well: def url(url_base) "#{url_base}#{@engine}_#{@hash}.#{@format}" end For any external images, we create an image link: def img_link(url_base) "<img src='#{url(url_base)}' class='gviz' />" end While if the format given is :inline_svg, we render it with :svg, and then read back the generated SVG and strip off the XML declaration and DOCTYPE: def to_html(url_base="/images/gviz/") return img_link(url_base) if @format != :inline_svg svg = render(:svg) svg = svg.split("\n")[2..-1] # Strip xml declaration and doctype svg.join("\n") end This simply reads the final cached file, def file file = File.read(target_file) rescue nil return file if file render end end # # Cache the graph, and return either a link, or inline SVG depending # on the preferred format # def self.graph_to_html(engine,graph,preferred_format=:inline_svg, url_base="/images/gviz/") hash = Graph.new(graph).cache Cache.new(hash,engine,preferred_format).to_html(url_base) end end I put the above in lib/gviz in my blog app - adjust the require accordingly if not: require 'lib/gviz' require 'rack' module GViz class Controller def initialize app, base = "/images/gviz/" @app = app @base = base @uri_regexp = /^(#{ENGINES.join("|")})_([0-9a-f]{32}).(png|svg)$/ end The regexp above is used to extract the engine and an MD5 of the cached graph file, and the image format from the URL if you use server side rendered images. If the URL doesn't start with the specified base, pass the URL on to the next in the chain: def call env uri = env["REQUEST_URI"] if (uri[0.. @base.size-1] != @base) return @app.call(env) if @app return Rack::Response.new("(empty)").finish end If it doesn't match the Regexp, give an error - someone is being naughty: match = uri[@base.size .. -1].match(@uri_regexp) if !match return Rack::Response.new("Invalid URL",403) end Otherwise, get the file from the cache: engine = match[1] hash = match[2] format = match[3] cache = GViz::Cache.new(hash,engine,format) file = cache.file return Rack::Response.new("No such graph",404) if !file r = Rack::Response.new r["Content-Type"] = format == "png" ? "image/png" : "image/svg+xml" r.write(file) r.finish end end end As example of how to call it from your code, my markdown filter calls this: GViz.graph_to_html(format, graph, :png) ... to generate the HTML for any graphviz graphs embedded in my pages. Since I've specified PNG output, it will cache the graph to file if not already present, and just outputs an image link. And my config.ru simply includes this: use GViz::Controller .
https://hokstad.com/inline-graphviz
CC-MAIN-2021-21
refinedweb
1,211
63.9
im trying to make my program draw lines from the top right corner of the JFrame which is 400 x 400, to the bottom of it making what looks like a curve but really is just lines. i think i know the basic idea of how to do this which would be to subtract 1 from x and add 1 to y and loop that in a for loop. i just cant get my syntax right or sumthin (im a first year java student) so far i have (and i dont really understand these code tag things so forgive me) import javax.swing.*; import java.awt.*; public class DrawingColor{ public static void main(String[] args) { DrawingColor d = new DrawingColor(); } public DrawingColor(){ JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new MyComponent()); frame.setSize(400,400); frame.setVisible(true); } public class MyComponent extends JComponent{ public void paint(Graphics g){ int height = 200; int width = 120; // and here is where my loop would start } } }
https://www.daniweb.com/programming/software-development/threads/237339/looping-the-drawline-method
CC-MAIN-2018-39
refinedweb
165
63.02
Downloaded and tested FERN today. Excellent work! Welcome to the forum. We will all expect great future activity from you on the forum! A Printable View Downloaded and tested FERN today. Excellent work! Welcome to the forum. We will all expect great future activity from you on the forum! A Looks absolutely great. I'd also recommend removing the matrix 1 and 0 background...it just kind of looks bad overall. Everything else looks great though. That looks great, I'll be downloading it when I get home. Thanks! Thank you very very much fellas .. for your contributions and encouragement. Ill try my best with the peak of any knowledge i have in contributing to this wonderful community. Thanks. Excellent, I am glad to see a more welcoming attitude emerging here. My offer to make the backgrounds a bit less intrusive still stands, all you need to do is send me the images ;) Thank you citruspas, for helping with the darkening of the binary image: If you think the binary image is too intrusive. You can replace it with the darker image. the new image is at the same Google page where the project is hosted. replace it in this directory /usr/local/bin/Fern-Wifi-Cracker/resources/ or any directory you choose to place it. the picture name is binary_2.png replace the old with the new but with the same name "binary_2.png" I know it's not much, but it kind of bothered me. Figured I might as well try and help out (can't really code except some bash scripting but I can do some photoshopping) :) I was running fern.py directly... tried running execute.py and it seems to work correctly... maybe a short "README" to suggest how to run it? Also it needs a function to shut down and clean up after itself. There is no good way to shut down WEP cracking after it is started without leaving aireplay-ng and airodump-ng running... so if you want to change attack modes or if you don't find the WEP key you have to manually clean up. Also it creates new VAPs every time its started - not necessarily a bad thing but another thing to manually clean up. A "stop" function that would kill all the stray processes would be very helpful, along with a button to manually create the VAPs would be good. But I do think this is a very good start on a useful tool. NOTICE Killall airodump-ngNOTICE Killall airodump-ngCode: def key_found(self): self.cracking_label.setEnabled(True) self.cracking_label.setText('<font color=yellow>Cracking Encryption</font>') self.finished_label.setEnabled(True) self.finished_label.setText('<font color=yellow>Finished</font>') self.wep_key_label.setEnabled(True) self.wep_key_label.setText('<font color=red>%s</font>'%(WEP)) self.wep_status_label.setEnabled(True) self.wep_status_label.setText('<font color=yellow>Wep Encryption Broken</font>') commands.getstatusoutput('killall airodump-ng') commands.getstatusoutput('killall airmon-ng') It does not kill processes until attack wep key is found.. which is logical.. it the dump files were deleted during attack.. wep key would never be found.. You find "killall" command on numerous lines in the source code. And the cleanup is also always done.. But when a new attack is initiated attack.. this is logical beacause there would be times where aircrack was not able to find key from your dictionary file, and you need to get the dump file so you can use it with an exetrnal cracker.. The dump file will be there until you press the new attack button On line 498 you can find something like that The cleanup "rm" is also found in some numerous sections.The cleanup "rm" is also found in some numerous sections.Code: def scan_wep(self,arg,arg2): monitor = str(reader('/tmp/fern-log/monitor.log')) commands.getstatusoutput('rm -r /tmp/fern-log/*.csv') commands.getstatusoutput('rm -r /tmp/fern-log/*.cap') commands.getstatusoutput('rm -r /tmp/fern-log/WPA/*.csv') commands.getstatusoutput('rm -r /tmp/fern-log/WPA/*.cap') THE README file i completely forgot.. The Scan Button is a dual button, it can also be used to stop scan by pressing again
http://www.backtrack-linux.org/forums/printthread.php?t=34517&pp=10&page=4
CC-MAIN-2014-41
refinedweb
692
60.51
tool man page tool — Dictionary Tools Synopsis package require Tcl 8.6 package require sha1 package require dicttool package require oo::meta package require oo::dialect tool::define class_method arglist body tool::define array name contents tool::define array_ensemble methodname varname ?cases? tool::define dict_ensemble methodname varname ?cases? tool::define method methodname arglist body tool::define option name dictopts tool::define property ?branch? field value tool::define variable name value object cget option object configure ?keyvaluelist? object configure field value ?field? ?value? ?...? object configurelist ?keyvaluelist? object forward stub forward object graft stub forward object InitializePublic object Eval_Script ?script? object Option_Default field Description This module implements the Tcl Object Oriented Library framework, or TOOL. It is intended to be a general purpose framework that is useable in its own right, and easily extensible. TOOL defines a metaclass with provides several additional keywords to the TclOO description langauge, default behaviors for its consituent objects, and top-down integration with the capabilities provided by the oo::meta package. The TOOL metaclass was build with the oo::dialect package, and thus can be used as the basis for additional metaclasses. As a metaclass, TOOL has it's own "class" class, "object" class, and define namespace. # tool::class workds just like oo::class tool::class create myclass { } # tool::define works just like oo::define tool::define myclass method noop {} {} # tool::define and tool::class understand additional keywords tool::define myclass array_ensemble mysettings mysettings {} # And tool interoperates with oo::define oo::define myclass method do_something {} { return something } # TOOL and TclOO objects are interchangeable oo::class create myooclass { superclass myclass } Several manual pages go into more detail about specific keywords and methods. tool::array_ensemble tool::dict_ensemble tool::method_ensemble tool::object tool::option_handling Keywords TOOL adds new (or modifies) keywords used in the definitions of classes. However, the new keywords are only available via calls to tool::class create or tool::define - tool::define class_method arglist body Defines a method for the class object itself. This method will be passed on to descendents of the class, unlike self method. - tool::define array name contents Declares a variable name which will be initialized as an array, populated with contents for objects of this class, as well as any objects for classes which are descendents of this class. - tool::define array_ensemble methodname varname ?cases? Declares a method ensemble methodname which will control access to variable varname. Cases are a key/value list of method names and bodies which will be overlaid on top of the standard template. See tool::array_ensemble. One method name is reserved: initialize. initialize Declares the initial values to be populated in the array, as a key/value list, and will not be expressed as a method for the ensemble. - tool::define dict_ensemble methodname varname ?cases? Declares a method ensemble methodname which will control access to variable varname. Cases are a key/value list of method names and bodies which will be overlaid on top of the standard template. See tool::dict_ensemble. One method name is reserved: initialize. initialize Declares the initial values to be populated in the array, as a key/value list, and will not be expressed as a method for the ensemble. - tool::define method methodname arglist body If methodname contains ::, the method is considered to be part of a method ensemble. See tool::method_ensembles. Otherwise this command behaves exactly like the standard oo::define method command. - tool::define option name dictopts Declares an option. dictopts is a key/value list defining parameters for the option. See tool::option_handling. tool::class create myclass { option color { post-command: {puts [list %self%'s %field% is now %value%]} default: green } } myclass create foo foo configure color purple > foo's color is now purple - tool::define property ?branch? field value Defines a new leaf in the class metadata tree. With no branch, the leaf will appear in the const section, accessible by either the object's property method, or via oo::meta::info class get const field: - tool::define variable name value Declares a variable name which will be initialized with the value value for objects of this class, as well as any objects for classes which are descendents of this class. Public Object Methods The TOOL object mother of all classes defines several methods to enforces consistent behavior throughout the framework. - object cget option Return the value of this object's option option. If the property options_strict is true for this class, calling an option which was not declared by the option keyword will throw an error. In all other cases if the value is present in the object's options array that value is returned. If it does not exist, the object will attempt to retrieve a property of the same name. - object configure ?keyvaluelist? - object configure field value ?field? ?value? ?...? This command will inject new values into the objects options array, according to the rules as set forth by the option descriptions. See tool::option_handling for details. configure will strip leading -'s off of field names, allowing it to behave in a quasi-backward compatible manner to tk options. - object configurelist ?keyvaluelist? This command will inject new values into the objects options array, according to the rules as set forth by the option descriptions. This command will perform validation and alternate storage rules. It will not invoke trigger rules. See tool::option_handling for details. - object forward stub forward A passthrough to oo:objdefine [self] forward - object graft stub forward Delegates the <stub> method to the object or command designated by forward tool::object create A tool::object create B A graft buddy B A configure color red B configure color blue A cget color > red A <buddy> cget color > blue Private Object Methods - object InitializePublic Consults the metadata for the class to ensure every array, option, and variable which has been declared but not initialized is initialized with the default value. This method is called by the constructor and the morph method. It is safe to invoke multiple times. - object Eval_Script ?script? Executes a block of text within the namespace of the object. Lines that begin with a # are ignored as comments. Commands that begin with :: are interpreted as calling a global command. All other Tcl commands that lack a "my" prefix are given one, to allow the script to exercise internal methods. This method is intended for configuration scripts, where the object's methods are intepreting a domain specific language. tool::class myclass { constructor script { my Eval_Script $script } method node {nodename info} { my variable node dict set node $nodename $info } method get {args} { my variable node return [dict get $node $args] } } myclass create movies { # This block of code is executed by the object node {The Day the Earth Stood Still} { date: 1952 characters: {GORT Klatoo} } } movies get {The Day the Earth Stood Still} date: > 1952 - object Option_Default field Computes the default value for an option. See tool::option_handling. Authors Sean Woods Bugs, Ideas, Feedback This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category tool of the Tcllib Trackers []. Please also report any ideas for enhancements you may have for either package and/or documentation. Keywords TOOL, TclOO Category Utility
https://www.mankier.com/n/tool
CC-MAIN-2017-34
refinedweb
1,196
52.39
This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python. integratepackage), and matplotlib. import numpy as np import scipy.integrate as spi import matplotlib.pyplot as plt %matplotlib inline m = 1. # particle's mass k = 1. # drag coefficient g = 9.81 # gravity acceleration xand y(two dimensions). We note $\mathbf{u}=(x,y)$. The ODE we are going to simulate is: $$\ddot{\mathbf{u}} = -\frac{k}{m} \dot{\mathbf{u}} + \mathbf{g}$$ where $\mathbf{g}$ is the gravity acceleration vector. In order to simulate this second-order ODE with SciPy, we can convert it to a first-order ODE (another option would be to solve $\dot{\mathbf{u}}$ first before integrating the solution). To do this, we consider two 2D variables: $\mathbf{u}$ and $\dot{\mathbf{u}}$. We note $\mathbf{v} = (\mathbf{u}, \dot{\mathbf{u}})$. We can express $\dot{\mathbf{v}}$ as a function of $\mathbf{v}$. Now, we create the initial vector $\mathbf{v}_0$ at time $t=0$: it has four components. # The initial position is (0, 0). v0 = np.zeros(4) # The initial speed vector is oriented # to the top right. v0[2] = 4. v0[3] = 10.] odeint, defined in the scipy.integratepackage. plt.figure(figsize=(6. plt.plot(v[:,0], v[:,1], 'o-', mew=1, ms=8, mec='w', label='k={0:.1f}'.format(k)); plt.legend(); plt.xlim(0, 12); plt.ylim(0, 6); The most outward trajectory (blue) corresponds to drag-free motion (without air resistance). It is a parabola. In the other trajectories, we can observe the increasing effect of air resistance, parameterized with $k$. You'll find all the explanations, figures, references, and much more in the book (to be released later this summer). IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).
http://nbviewer.jupyter.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter12_deterministic/03_ode.ipynb
CC-MAIN-2017-47
refinedweb
307
53.07
RequestFactory Grid with FilterPagingLoadConfig. There is one example of how to use a grid with RF and FilterPagingLoadConfig?. Thank you. Yes. Look at the source code for the Paging Grid demo: Specifically, look for RpcProxy. You construct your paging loader with an instance of this class. Wow, totally missed this. You may want to also try the RequestFactory grid example: The source in that example (specifically PostRequest) really highlights the lack of generics support in RequestFactory. There are a few bugs filed against GWT that address this: Ahhh, but wouldn't you agree that the alternative provides quite a dearth of generics? PagingLoader, I'm looking in your direction... I don't follow - is there a generics issue with PagingLoader, or is the concern that the generics in PagingLoader can be onerous? The latter. :-) But actually, LoadResultListStoreBinding is even more impressive, wouldn't you agree: public class LoadResultListStoreBinding<C, M, D extends ListLoadResult<M>> implements LoadHandler<C, D> This might need to be a separate thread, but: I had to write my own implementation because we needed to be able to execute a callback after the LoadHandler.onLoad event was fired. I realize that this will cause the ListStore to fire a StoreDataChangeEvent but that event (in fact, no event fired from the ListStore does) does not provide access to the list of beans in the store and we needed a (read-only) reference to this list. Incidentally, since the LoadResultListStoreBinding.onLoad method calls ListStore.replaceAll, would you not agree that an enhancement might include read-only access to the list from that event? Sorry to change the topic... StoreDataChangedEvent deliberatly does not provide that list, as it is, by definition, the contents of the store itself. Other events (remove, add, update) do provide references to the modified items. ListStore.getAll() returns an unmodifiable list of the current items in the store. The Loader<->Store binding classes are meant to be simple ways to perform common tasks, but for uncommon cases, additional work will be required. Building your own load handler could be done inline, using an anonymous subclass for especially custom code that is unlikely to ever be reused. The generics of LoadResultListStoreBinding are verbose - one of the few classes that require three arguments to make sense, but I think that it does make sense and is required - if you have another way to look at this, I'd be happy to discuss it. LoadResultListStoreBinding<C, M, D extends ListLoadResult<M>> implements LoadHandler<C, D> C is the config type - this alone could be cleaned out, as it is not used internally, but it would need to be specified as Object to be as permissive as possible. With that change, anything that would consume this instance (passed to loader.addListHandler) would need to be ? super C, which then gets hairy when the config is passed into the event and actually consumed by other event handlers. M is obviously required, to make it clear what kind of data the store and loader hold in common. D then represents the load result instance - again, we could make this concrete as ListLoadResult<M>, but then we would need to use wildcards when adding this handler to the loader - same problem as C. My only concern was centered around custom UI components where the list store is not exposed because, technically, it didn't need to be. How then, does one get access to the data store? Once of the really nice things about event handling in general is it allows code to not be tightly coupled, i.e., the fired events provide all the data needed in the event handling method. I just think this makes for cleaner code. I wasn't suggesting that the LoadResultListStoreBinding class was bad or poorly designed. I was merely commenting on the generics - they, of course, make sense. It does make for verbose code and I've given up trying to stay in the 80-character line boundary when dealing with certain classes due to the generics involved. Asthetics, in my opinion, are not an area where Java wins any points. Java 7, with its diamond notation, might help shorten some of those terrible lines though....
https://www.sencha.com/forum/showthread.php?186912-RequestFactory-Grid-with-FilterPagingLoadConfig
CC-MAIN-2015-40
refinedweb
700
61.87
Web Development Apps in Go Programming – Welcome to my next blog, fellow go programmers. In this blog, we will be talking about the Google’s awesome Golang language. In my previous blog, you might have seen how Golang has evolved over years, and has given a tough competition to Java and C++. But in this blog, we would be talking about its real world applications. Golang is Google’s official programming language. Google has kept its license Open source. It means that anyone can modify, copy, paste or change it as per their needs. Golang is a high level programming language. Though Go has a lot of characteristics similar to C or Java, its hardly anything like either C or Java. In fact, Go Programming was intended to be a language, which could be a combination of Python, C and Java. Even though it can never replace these languages, but still other languages cannot do what Go can, and to speak the truth, its actually much faster than C or Python. Enough about how GO programming works now, lets see the real world applications of it besides being of a lot of help to Google, and how it has actually dominated the world of web development. Through out this blog, I will be assuming that you have some basic knowledge in programming C, Java or atleast Django. If not, you can read my other blogs, to get a deeper understanding of it and then come back here and continue with this one. The Go Programming Language Examples- Origin of GO Remember I told you that Go received its characteristics from web development languages like C and python, but the truth is, it actually borrowed a lot than just characteristics. It has the agility of the compilation speed of python without losing the safe polarity of C. The miniature builds of GO are spot on, for example you can compile large programs in just seconds. The speeds of these bytecodes are almost similar to that of the C’s. The main reason GO Programming was developed because Google had very large data critical servers and the programmers invested, or the better term would be wasted, long time waiting for the programs to compile. Even though the code was compiled and parallelized, it still took a very long time to build a single program. 4.8 (1,263 ratings) ₹19999 View Course Even incremental builds were slow (Incremental builds means just updating old builds with new features or cleansing its bugs). It was then they realized that they need something different, something with the power of C and the speed of python. They also decided the tools used in these basic systems language were slow. So they wanted to start something from scratch, something to write those kinds of programs that they needed to write at Google in a way that the builds could be really smart and short without losing its efficiency. Web development, concurrencies and GO Now the thing is, how does web development work with GO? How does it gain from its concurrency. The thing is theoretically, with parallel processing, the server’s resources could be put to better use. For example if you run 2 independent sql queries in parallel, it will give a quick response. Isn’t this amazing? Now lets take a look at this the other way round Normally when you hear the word concurrency, you start to think, that you can work on multiple threads at once. But we are not extreme professionals, for our piece of code to be perfect. So, a more precise way to put this would be, that instead of doing multiple tasks, you could actually end up just mangling things around you. So, this unfortunately develops a lot of hiccups on our way, which is actually not good because concurrency can lead to better visual arrangement and more clear code. In short, it can be relied on for one reason, which you wouldn’t want: low-performance. But, inspite of all this, we are actually ignoring the main part. If we actually have a good set of hardware, or faster computing techniques to be more precise, GO would actually work faster in a multi-core processor environment. Now let’s take a look at how GO is different from other languages. So, what we need to do is, step one: pick any global mutable state that you wish to change, then step two: implement locking. Now, this is a combination of two proper steps and two wrong things. Developers that have decent experience would agree with me that global mutable state is a bad thing. As a matter of fact, many coders try to remove this in the best way possible. So the utmost fact that you have step one looks like some refactoring is in order to begin with. Step two on the other hand, i.e locking, is capable of achieving its goal, but at the same time it introduces gigantic amounts of boilerplate that is extremely hard to write it down in a proper manner and then debug it correctly. Thus, such kind of languages might have one http request reading a specific variable and another writing it. Which happened when? Is it important enough? Does it need an order to the reads and writes? Does your code have this kinda logic? If so, why? Recommended courses The Way to GO The threads of GO are not what you might be used to when writing these kernels. These are actually somewhat similar to the processes of Erlang. They are extremely lightweight & both have similar goals. This does not say that GO and Erlang are the same since they have many differences of their own. Concurrency and the channels; both go together hand-in-hand in GO programming. It can however be said that these channels have the real horsepower to make our automations work. And because of this nature they prevent the routines in GO from being duplicated. Nuf said, now you can run your codes without the help of locks and mutexes. If you have time worth googling, then you will find a lot of people trying the same methods in the form of UNIX pipes. Building native GO Apps Now, that we know how GO works lets take a look at building some basic Applications in GO. Lets go through the Pre-requisites first: - Download the go installer from the official go website (you can get it by searching download golang) - Set the GOPATH (This is the most tricky part if you have never set environment variables in your life) a. For Windows Users: set GOROOT=C:\go set GOPATH=C:\Users\testdir set GOBIN=%GOPATH%\bin set PATH=%PATH%;c:\go\bin;%GOBIN% cd %GOPATH%\src In the testdir option above, set the directory you want to use (name it whatever you want) as the working directory. This will set all the directories and when you type in the last cd (change firectory) command, it should take you to the default working directory, i.e in our case its testdir. If it does, it means it works. b. For Linux Users: export GOROOT=/usr/local/go export GOPATH=$HOME/go export PATH=$PATH:$GOROOT/bin:$GOPATH/bin Following are the required packages that you would need to download (these are optional, depends upon what you need to build): You can install (or update) these packages by running the following command in your console: go get -u <import_path> For example, if you want to install Negroni, then you can use the following command: go get -u github.com/codehub/negroni For me, building web applications mean building Http servers. Http or Hypertext Transfer protocol is a protocol that was originally built to transport only user-specific HTML documents from a specific server to a client side web browser. As of today, Http is used to transport more than just plain texts. I won’t be getting in deep actually, you can refer to github where you can find more details about this project. Now to get you started lets begin by creating a new project in our GOPATH cd GOPATH/src mkdir testserver cd testserver Now, we can create a main.go by typing: package main import “net/http” func main() { } Now since everything is setup, all we need to do is to import http package, and then it will work. And now, its time to write our testserver code: http.ListenAndServe(“:2964”, http.FileServer(http.Dir(“.”))) The http.ListenAndServer is a function used to run the server. It will run on the address given to it i.e. port 2964 in this case, and when it receives a response, it will transfer it the http.handler that we supplied as the second argument, which again in this case is the built-in http-FileServer. We created the http.Handler with the http.FileServer which will act as a server for an entire directory of files and will automatically respond with the file which needs to be served on the request path. As for this piece of code we ran above, we told the server to respond with the current working directory i.e. http.Dir(“.”) The whole Program will then look like this: package main import “net/http” func main() { http.ListenAndServe(“:2964”, http.FileServer(http.Dir(“.”))) } Now to execute and make our fileserver live, we can run it whenever we want by typing: go build ./testserver And, now if we open this in our browser- localhost:2964/main.go or , we should be able to see the packages inside our main.go file in our web browser. The best part is, we can run this program from anywhere from within our computer and serve that directory as the basic homepage for the localhost. All of this is possible in just one line of Go programming. Speaking of which, you should actually check out the web applications developed in github, and you will be actually astonished to see what all apps people have developed with GO programming. GO language is more than just your regular programming. Once you get a hang of this language, it is highly unlikely that you will actually go to back to your regular C, C++ or Java. So, that will be it as for now. Stay tuned for more on GO programming. First Image Source: pixabay.com Related Articles:- - You Should Learn about Web Services Interview Questions and Answers - Best & helpful points of Java Web Services Interview Questions - New 10 Benefits Web Development Tools For Beginner (Free) - Important On Scratch Programming examples - How To Build Superb Career as Web Development Software Professional? - Software Development vs Web Development Software Development Course - All in One Bundle 600+ Online Courses 3000+ Hours Verifiable Certificates Lifetime Access
https://www.educba.com/web-development-with-go-programming/
CC-MAIN-2019-22
refinedweb
1,805
70.02
Project Motivation Scheduling is a critical part of an OS since it directly affects performance of a multitasking Operating System. In particular, Linux and Android were chosen since they are open source and are widely used In embedded applications. LINUX AND ANDROID SCHEDULING CPU vs IO Bound Process I/O bound processes spend most of its time submitting and waiting on I/O requests. Processor bound processes spend most of its time executing code. The scheduling policy in Linux tends to favor explicitly I/O bound processes Linux favors I/O bound processes to provide good interactive response and desktop performance. Linux scheduler history Changing Scheduling Priority First determine the range of priority values and then the levels of priority based on min and max priorities. Setting Linux Scheduling Policy Processes can manipulate scheduling policy via sched_getscheduler() and sched_setscheduler() #include <sched.h> int sched_getscheduler (pid_t pid) Int sched_setscheduler (pid_t pid, int policy, const struct sched_param *sp) NOTE: “pid” is the process ID. A value of 0 refers to the invoking process’s scheduling plolicy. Threads can manipulate scheduling as follows: #include <pthread.h> pthread_attr_getschedpolicy(&attr, &policy) pthread_attr_setschedpolicy(&attr, SCHED_FIFO) Problems in previous Scheduler Traditional algorithm Does not support Multiprocessor O(1) scheduling Supports SMP system and Processor affinity Provides load balancing between cores or processors. Based on Big-O Notation. It means the scheduler can work in constant time regardless of the input. But poor response time for interactive processes because it did not favor I/O processes. CMPE 180-194 Nitesh Majji 009422894 Julio Fuentes 008137844 Dibhanshi Dwivedi 009424051 LINUX AND ANDROID SCHEDULING Real Time SCHED_FIFO A process runs until it relinquishes control or it is preempted by a higher priority process. SCHED_RR A process runs until its time slice expires within its class. It can be preempted by a higher priority process. Normal (non-real time) SCHED_OTHER This is the default scheduling class which uses the CFS scheduling algorithm. Tasks at the same priority are round-robined. Scheduling Priorities A FIFO or RR classed process will always run if it is the highest priority process. It will immediately preempt a normal process. The scheduler assigns the RR process a timeslice. When the timeslice expires, the scheduler moves it to the end of the list of processes with the same priority. #include <sched.h> int sched_get_priority_min (int policy); int sched_get_priority_max (int policy) ; Struct sched_param sp; Int policy, max ; policy = sched_getscheduler (pid) ; max = sched_get_priority_max (policy); Memset (&sp, 0, sizeof (struct sched_param)) ; Sp.sched_priority = max ; Other examples: min, (max-min)/2 Precautions with Real-Time Processes If there is no higher-priority process on the system, a CPU-bound loop will run until completion, without interruption. If the loop is infinite, the system can become unresponsive. If a real time process busy-waits for a resource held by a lower priority process, the real time process will busy wait forever. Special attention must be paid to real-time process and their CPU time requirements to avoid starving the system. Red and Black Tree in CFS Self-balanced Insertion and deletion operation in O(log N) where N is the number of processes. Integrated into the Linux 2.6.23 release Assigns a portion of CPU processing time to each task based on the nice value . CFS records how long each task has run by managing the virtual run time variable vruntime . Vruntime =actual running time+ decay factor where decay factor= +ve for lower priority task -ve for high priority task IO bound task vruntime< CPU bound task vruntime Completely Fair Scheduler (CFS) Uses the red-black binary tree data structure to search next process to run based on the vruntime key. Used by non-real time processes with the SCHED_OTHER Class As red black tree is balanced, navigating it to discover the leftmost node will require O(logN) operations(N=number of nodes). For better efficiency, the linux scheduler caches this value in a variable, and thus to determine which task to run next just require retrieving cached value. Based on linux 2.6 kernel and uses CFS scheduling for normal task Priorities of processes Android Scheduling Android Scheduling... Android uses two different scheduling classes Background Foreground Background class is low priority and can maximum utilize ~5% of the CPU Foreground task has better priority and can utilize ~95% of the CPU. We can change the priority by calling Thread.setPriority that is part of the standard Java API and contains a value from MIN_PRIORITY(1) to MAX_PRIORITY(10). Both Android and Linux use the Linux 2.6.23 kernel scheduling. Real time processes always get higher priority than normal processes. Processor affinity is critical for load balancing the scheduler and take care to of performance critical applications. As Android is mainly used in smart phones, their priority depends mainly on whether it is a foreground process or not. Conclusion Processor Affinity Processor affinity can be used to instruct the scheduler with processes to run on each CPU of a multi-processor system. The functions to set the processor affinity are: #include <sched.h> int sched_setaffinity (pid_t pid, size_t setsize, const cpu_set_t *set); int sched_getaffinity (pid_t pid, size_t setsize, cpu_set_t *set); The scheduler is not always able to schedule a process in favor of another because the process may be running in Kernel critical region. This may not be acceptable for a real time process deadline. If there is more than one processor or core. One can be dedicated to real time processes. The init program can be modified as follows: Clear variable to set CPUs or cores Get all available cores Forbid the use of CPU or core to be used by real time processes. Set real time process to run on dedicated CPU or core. CPU Affinity and Real Time Processes #include <sched.h> typedef struct cpu_set_t; Cpu_set_t set ; Int ret; Void CPU_ZERO (cpu_set_t *set) ; Void CPU_SET (unsigned long cpu, cpu_set_t *set) ; Void CPU_CLR (unsigned long cpu, cpu_set_t *set); CPU_ZERO (&set) ; /* clear variable */ ret= sched_getaffinity (0, sizeof (cpu_set_t), &set) ; /* get allowed processors */ If (ret == -1) {perror (“sched_getaffinity error”); return 1; } CPU_CLR (1, &set); /* forbid CPU #1 */ Ret = sched_setaffinity (0, sizeof (cpu_set_t), &set); If (ret == -1) {perror (“sched_setaffinity error”); return 1; } ---------------------------------- Code for real time process ------------------------------------------------ CPU_ZERO (&set) ; /* clear variable */ CPU_SET (1, &set); /* allow CPU #1 */ Ret = sched_setaffinity (0, sizeof (cpu_set_t, &set); If (ret == -1) { perror (“sched_setaffinity”) ; return 1; } Scheduling Classes . LINUX & ANDROID SCHEDULING No description byTweet NITESH MAJJIon 7 May 2014 Please log in to add your comment.
https://prezi.com/ebrz6qfjnjua/linux-android-scheduling/
CC-MAIN-2017-22
refinedweb
1,079
52.7
When preamble contains #undef, indexing code finds the matching #define and uses that during indexing. However, it would only look for local definitions. If the macro was defined in a module, MacroInfo would be nullptr and clangd would crash. This change fixes the crash by looking for definition in module when that happens. The indexing result is then exactly the same whether modules are used or not. The indexing of macros happens for preamble only, so then #undef must be in the preamble, which is why we need two .h files in a test. Note that clangd is currently not ready for module support, but this brings us one step closer. Generally, we prefer to write tests as gunit tests where feasible, this gathers the inputs into one place, avoids too much messing around with the filesystem, and assertions on something a little simpler than the full JSON output. It also make it easier to factor out common bits across tests. If I'm understanding this test right it should be fairly easy to port to a gunit test with TestTU (setting AdditionalFiles and ExtraArgs) which would assert on headerSymbols(). This would probably go in SymbolCollectorTests, similar to e.g. TEST_F(SymbolCollectorTest, NonModularHeader). Obviously this relates to where other tests around indexing modules might live once we have those. If you'd prefer them to be lit tests, it'd be nice to know a bit about that. This looks fairly grungy and I don't totally understand it :-( I guess walking the getPrevious() chain on the macro definition until we hit one with info doesn't work? If we can't reuse something existing for this, we should probably ask rsmith if this is sensible. API quibbles: You don't need to call getMacroInfo() here, getMacroInfoForLatestDefinition() does this. Addressed review comments. So this is late in the game but... maybe we should just not report this case as a reference? #undef foo is valid if foo was never defined, and doesn't refer to anything. If we similarly don't resolve the reference in this case as we only import macros that were used and undef doesn't count as a use... I think that's defensible as a weird edge case. In practice, I doubt anyone cares - AIUI the cases we've seen this, it's defensive claiming of the macro namespace, and not a targeted undef of a particular known macro at all. Changed to just ignore undefs without matching def Resurrecting this, with the ignore #undef when #define is in a module approach. Still worth having a test, especially that it's the first test we have for modules. Note that the test code changed since last version due to introduction of ThreasafeFS since my original change. are the leading slashes here needed, or can we use "bar.h" and have everything be relative to testRoot()? (relative paths in AdditionalFiles are relative to testRoot().) I'm a bit torn on this - this is obviously a bit messy (writing modules to the real filesystem and exposing the whole FS to our test). It's not a huge thing and we could slap a FIXME on it, though you clearly have to plumb it through a few layers. I think the alternative is an explicit module build: TU2.AdditionalFiles["foo.pcm"] = TU1.buildHeaderModule(); TU2.ExtraArgs = {"-fprebuild-module-path=.", "-std=c++20", "-fmodules"}; TU2.HeaderCode = "import foo;\n#undef X"; I guess whether this is actually better probably depends on whether we're likely to go in this direction (explicitly building and managing a module cache ourselves) for modules. If we're likely to let clang implicitly build modules and maybe just put the physical cache storage behind an abstraction, maybe it's best to overlay the FS for now and rip this out later. If we're going to do explicit module builds and schedule them ourselves, then starting to experiment in that direction is useful, and there won't be an obvious time to rip out the OverlayRealFileSystem feature. I think all of which is to say feel free to land it in this form, or experiment further. I think the OverlayRealFileSystem should maybe be ExposeModuleCacheDir or something with a FIXME to come up with a better solution, though. It's not a feature of TesttU we should be using for other purposes (without similar careful consideration)
https://reviews.llvm.org/D80525
CC-MAIN-2020-34
refinedweb
730
62.38
I must be really stupid but after two hours I have not managed to fix the problem that I have I'm currently learning abour romhacking following the "ultimate-tutorial-2", but I'm stuck in the section insert text. I understand a bit how the thing works and I have been trying to change some names: I wrote the .txt file with the pointer of the text to change (these are for iron sword name and item description from FE7). #0x3f3 Cheap blade[X] #0x279 This doesnt work.[X] And added #include "Install Text Data.event" to the buildfile. #include "Install Text Data.event" #include eastdlib.event ORG 0x1000000 #include ".\text\Install Text Data.event" I wrote the changes to the rom and event assembler says that all its fine.The problem its that when i launch the rom, nothing changes. Do you have a file named "textbuildfile.txt" in the same folder as your textprocess.exe or textprocess_v2.exe file? That file dictates what text data the processor should be processing. For example, mine is set up like this: #include "Other/Brown Box Text.txt" #include "Other/Character Names.txt" #include "Other/Chapter Names.txt" #include "Other/Class Names.txt" #include "Other/Descriptions.txt" #include "Other/Item Names.txt" #include "Other/Item Descriptions.txt" #include "Other/Battle Death Quotes.txt" #include "Other/Status Objectives.txt" #include "Other/Misc Text.txt" #include "ChapterTexts.txt" Once you have your textbuildfile.txt set up properly and are #include-ing all the different files you want to insert into the game, then the textprocess.exe will work properly. @FPzero I don't think they need to do that if they only have one file to process. What does Install Text Data.event look like? Install Text Data.event Yes, my file its called "text_buildfile.txt, also the content of Install Text Data.event is: #include "Tools/Tool Helpers.txt" #include "Text Definitions.event" TxtData0x3f3: #incext ParseFile "_textentries\0x3f3.txt" setText(0x3f3,TxtData0x3f3) TxtData0x279: #incext ParseFile "_textentries\0x279.txt" setText(0x279,TxtData0x279) Well it looks like the processor is working fine if the Install Text Data.event file has stuff in it. You are telling your ROM Buildfile to #include that file, right? Yes, my ROM Buildfile text is: ROM Buildfile Well, that looks correct. Stupid questions time!1) Did you assemble to the correct rom, and if yes, are you checking that same rom?2) Did you modify the right text ids? Yes, i use a MAKE HACK.cdm and yes, I have tried different ids from objects, descriptions of objects and characters. On the other hand when I make a writing error in the fileInstall Text Data.event the assembly fails. MAKE HACK.cdm EDIT: Also, i checked the rom with HxD and the data is in the rom. EDIT_2: The ids i tested were:- 0x3f3 (iron sword name).- 0x279 (iron sword description).- 0x537 (Limstella name). If the text is in the rom, then the issue must be that the pointer to the text wasn't updated. That's what the setText macro is supposed to do, though... I'm not quite sure what went wrong. Is the text table in the same place as in a vanilla rom? Based on the fact that you said you changed Limstella's name, I'm going to assume you're working with FE7. If so, what pointer is at 12C88? It should be B808AC. Sorry, i'm a little new with this and i get lost with the second part. What is the "text table"? Can you explain it to me please? I have a folder called tables where i have the nightmare modules to make changes in characters, items but... Also i made some other changes in things like music, units and all work fine. EDIT: I checked the modified rom using HxD and searched in the offset 12C80, i found "B8 08 B4 A5" but im not sure if you are refering to that. 12C88, not 12C80. It's actually a text pointer table; given a text id, say, 0x3F3, the function multiplies this by 4 (because pointers are 4 bytes long) and adds it to the text pointer table to get a pointer (in this case, it should be 0x9000000 since that's where you assembled your text to) to the text itself (Iron Sword). Well, i checked again and this is what i have: Have you installed anti-huffman? It doesn't seem so.Include this into your buildfile. You'll need this, but that wouldn't fix if there's an issue with the text table. No, I do not have it installed. I tried to put it but when I started the rom, it showed me a black screen, I researched a bit about the problem but I could not fix it. I have also tried to open the rom by FEditor to see the status of the modified texts, and these remain unchanged. The pointers must not have been updated, then. Check 0xB808AC + 4*0x3F3 = 0xB81878. This is what i have: Looks like the pointer didn't update. Question is, why? As I said, the setText macro should take care of that for you... setText Out of idle curiosity, if you open Tools/Toll Helpers.txt, what's the chunk of code that defines TextTable look like? It should be on line 15 and look like this: Tools/Toll Helpers.txt #ifndef TextTable #define TextTable 0xB808AC #endif If this is correct, all I can think of is to assemble again and see if anything's changed. Here i think everithing is correct: #ifdef _FE7_ #ifndef TextTable #define TextTable 0xB808AC #endif #ifndef PortraitTable #define PortraitTable 0xC96584 #endif #endif Thats why im lost, I also assemble the rom every time I make a change.As i said im new into this so this maybe sounds stupid but the pointer at 12C88, its "AC08B8", so its the same pointer that you told me before but reversed. 12C88 AC08B8 Right, stuff in the rom is written in little endian, meaning the bytes are written in reversed order (the "most important", or highest, byte appears at the end). So 08B808AC will appear at AC 08 B8 08, as you can see.I really dunno what's going on, though; everything seems to be set up correctly. What version of EA are you using? Im using EA v11.1. Also, i started to read about inserting mugs and they dont show, maybe its because im doing something wrong since i readed it a little bit fast this morning but maybe its related with this problem too.
http://feuniverse.us/t/problem-with-text-processor-using-buildfile-method/3943
CC-MAIN-2018-47
refinedweb
1,104
85.89
By using simple network applications, we can send files or messages over the internet. A socket is an object that symbolize a low-level connection point to the IP stack. This socket can be opened or closed or one of a set amount of intermediate states. A socket can deliver and receive data down this connection. Files is generally sent in blocks of a few kilobytes at a time for effectiveness; each of these blocks is named as a packet . Here are the list of well-known port numbers which usually used. - Port 20, FTP Data - Port 21, FTP Control - Port 25, SMTP (email and outgoing) - Port 53, DNS - Port 80, HTTP (Web) - Port 110, POP3 (email, incoming) - Port 143, IMAP (email, incoming) All packets that travel on the web must use the Internet communications protocol. This means that the source IP address, destination address must be provided in the packet. Some data packets also contain a port number. A port is simply a number around 1 and 65,535 that is used to differentiate higher protocols, such as email or FTP. Ports are crucial when it comes to developing your own network applications because no two software applications can use the same port. It is advised that experimental programs use port numbers above 1024. Packets that contain port numbers come in two flavors: UDP and TCP/IP. UDP has lower latency than TCP/IP, especially on startup. Where data integrity is not of the utmost concern, UDP can prove easier to use than TCP, but it should never be used where data integrity is more important than performance; however, data sent via UDP can sometimes arrive in the wrong order and be effectively useless to the receiver. TCP/IP is more complex than UDP and has typically longer latencies, but it does guarantee that data does not become corrupted when traveling over the Internet. TCP is best suited for file transfer (TCP/IP File Transfer), where a corrupted file is more unacceptable than a slow download; however, it is unsuited to Internet radio, where the odd sound out of place is more acceptable than long gaps of silence. Creating a simple Send/Receive application in C# and VB.net This program will send the words “hello world” over a network. It consists of two executables, one a server, the other a client. These two programs could be physically separated by thousands of kilometers, but as long as the IP addresses of both devices are known, the principle still works. In this example, the data will be delivered using UDP. This means that the words “hello world” will be included with information that will be used by IP routers to make sure that the data can travel anywhere it wishes in the world. UDP data is not included with headers that track message reliability or security. Moreover, the receiving end is not obliged to reply to the sender with acknowledgments as each packet arrives. The elimination of this demand allows UDP data to travel with much lower latency than TCP. UDP is useful for small payload transfers, where all of the data to be sent can be contained within one network packet. If there is only one packet, the out-of-sequence problems related with UDP do not apply; therefore, UDP is the underlying protocol behind DNS. Creating a simple UDP client in C# and VB.net To get started, open Visual Studio .NET, click New Project, then click Visual C# projects, and then Windows Application. Set the name to “ UDP Client ” and press OK. You could alternatively click Visual Basic .NET projects and follow the code labeled VB.NET in the examples. Now, build the form interface as shown above. Name the button button1 and the textbox txtbHost . Click the button and type in the source code as follows: C# Programming Language VB.net From the code, we can see that the first task is creating a UDP Client object. This is a socket that can send UDP packets. A port number is selected arbitrarily. Here, the port number 8080 is used, mainly because it is easy to remember and it is not in the first 1024 port numbers, which are reserved for specific use by IANA. The first argument in the Connect method shows where any data should be sent. Here, I have used txtbHost.Text (i.e., whatever is typed into the textbox). If you have access to only one computer, you would type localhost into this window; otherwise, if you are using two devices, type the IP address of the server. You also need to include some assemblies by adding these lines to just under the lock of the using statements at the top of the code: Now, press F5 to compile and run the application. You should see your application resembling UDP client interface image. Creating a simple UDP server in C# and VB.net The purpose of the UDP server is to detect incoming data sent from the UDP client. Any new data will be displayed in a list box. As before, create a new C# project, but with a new user interface, as shown below. The list box should be named lbConnections . A key feature of servers is multithreading (i.e., they can handle hundreds of simultaneous requests). In this case, our server must have at least two threads: one deals with incoming UDP data, and the main thread of execution may continue to maintain the user program interface, so that it does not appear hung. First, we create the UDP data handling thread: C# Programming language VB.net Again, we use the UdpClient object. Its constructor indicates that it should be bound to port 8080, like in the client. The Receive method is blocking (i.e., the thread does not continue until UDP data is received). In a real-world application, appropriate timeout mechanisms must be in place because UDP does not ensure packet delivery integrity. Once received, the data is in byte array format, which is then converted to a string and displayed onscreen in the form source address: data . There is then the matter of actually invoking the serverThread method asynchronously, such that the blocking method, Receive , does not hang the application. This is fixed using threads as follows: C# Programming Language VB.net Note : It’s unsafe to call directly from a worker thread (InvalidOperationException will show up in debugger), To make safe Thread-safe calls you need to use InvokeRequired check. Here’s how to do thread-safe calls To finish off, the following assemblies are to be added: C# VB.net To test this program, execute it from Visual Studio .NET. On the same computer, start the UDP client and execute it. Input localhost into the textbox and press the button on the UDP client. A message “Localhost:Hello World?” should appear, such as shown below. If you have a other PC, get its IP address and set up the server on this second PC and execute it. Again open the client, but type the IP address into the textbox. When you click the button on the client, the server should display the “Hello World” message. And That’s it !! You have used .NET to deliver data across a network. If you got error while compiling maybe you have to check for common errors. Thank you! Thank you! This article is really going to help me. I was looking for something like this for almost 3 days. Thanks to you, I can now send info from tablet to pc! 🙂 Hey there, may i ask a question? When i run the “Server App” and close it, it keeps working background and i can’t run it again until i close it from task manager. I tried adding “thdUDPServer.Abort()” to formclosing event, but it still working background. thdUDPServer.Abort() only make the thread stop processing. To close the program maybe you can use Exit() Thanks again. I used “End” in formclosed event, looks like it solved the problem. 🙂 Hey. I got an error in the server app. I can recive the data but I can not show it. I try to show it with a list Box and with a label but it doesn’t work. Can you help me please If you followed this tutorial, Check your string returnData or whatever you named it. if it’s null then you need to trace the problem from there Hi i would like to create a client in C# and server in VB or vice-versa but this code is not working. I would appreciate if you would suggest a solution. Can you explain why it’s not working? Try to post your code here Hi Kim thanks for reply! I have got an error massage in VB pointing on this line: Dim udpClient As New UdpClient(8080). The error is saying “Only one usage of each socket address (protocol/network address/port) is normally permitted”(Socket Exception was unhanded). Please find the code i used in both C# and VB below- Note:I used Windows Forms Application when creating the respective projects. Code of UDP client in C# : using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; using System.Net; using System.Net.Sockets; using System.Text; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Lable_Click(object sender, EventArgs e) { } private void button1_Click(object sender, System.EventArgs e) { UdpClient udpClient = new UdpClient(); udpClient.Connect(txtbHost.Text, 0); Byte[] senddata = Encoding.ASCII.GetBytes(“Hello World”); udpClient.Send(senddata, senddata.Length); } } } Code of UDP Server in VB : Imports System.Threading Imports System.Net Imports System.Net.Sockets Imports System.Text Imports System.Net.Sockets.SocketException Public Class Form1 Public Sub serverThread() Dim udpClient As New UdpClient(8080) While True Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0) Dim receiveBytes As Byte() receiveBytes = udpClient.Receive(RemoteIpEndPoint) Dim returnData As String = _ Encoding.ASCII.GetString(receiveBytes) lbConnections.Items.Add( _ RemoteIpEndPoint.Address.ToString() + “:” + _ returnData.ToString()) End While End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim thdUDPServer = New Thread(New ThreadStart(AddressOf serverThread)) thdUDPServer.Start() End Sub End Class Hi Adme, Try to use other port beside 8080 (for example, Dim udpClient As New UdpClient(8071)) and make sure both client and server use same port to communicate. Thanks Hi Kim, I tried with other port addresses, unfortunately it is not working. Thanks! Hi Adme, Make sure you already checked all of these 1. Port are not blocked by firewall. 2. Port are not used by other apps. 3. Sometimes port used by your previous program launch, make sure you close the port before using it again. 4. Or maybe you invoke listenPort twice on different thread. Thanks I like the efforts you have put in this, thank you for all the great blog posts. I just like the helpful info you supply to your articles. I will bookmark your weblog and test once more here regularly. I am somewhat sure I will be informed lots of new stuff proper here! Good luck for the following! Have you ever considered writing an ebook or guest authoring on other blogs? I have a blog based on the same ideas you discuss and would really like to have you share some stories/information. I know my viewers would appreciate your work. If you are even remotely interested, feel free to send me an e mail. hi.. is this how the C# UDP server code is like?? using System.Threading; //using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.Net.Sockets; namespace WinFormUDP_Server { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Thread thdUDPServer = new Thread(new ThreadStart(serverThread)); thdUDPServer.Start(); } public void serverThread() { UdpClient udpClient = new UdpClient(6666); while (true) { //IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse(“127.0.0.1”), 6666); Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); string returnData = Encoding.ASCII.GetString(receiveBytes); listBox1.Items.Add(RemoteIpEndPoint.Address.ToString() + “:” + returnData.ToString()); } } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { } } } i got error.. Please advise. Thanks in advance ” An unhandled exception of type ‘System.InvalidOperationException’ occurred in System.Windows.Forms.dll Additional information: Cross-thread operation not valid: Control ‘listBox1’ accessed from a thread other than the thread it was created on. “
http://technotif.com/creating-simple-udp-server-client-transfer-data-using-c-vb-net/
CC-MAIN-2019-04
refinedweb
2,088
67.45
This is a very brief article about one great feature of the Ruby language - dynamically adding methods to classes at runtime. Basically I have been learning the Ruby language and thought I would share few snippets with people in small articles, so if you are not familiar with Ruby take a quick look and see what you think - you never know it might spark your interest! One great feature of Ruby is that it allows you to add methods to individual class instances on the fly. The code is pretty self explanatory so I won't go into any details. ## ---- Add methods to a class instance at runtime. ---- ## # Create a very simple class. <CODE __designer:class TestAddMethod def method1 puts "Method1 Called." end end </CODE> # Create a new instance of this class. <CODE __designer:t = TestAddMethod.new </CODE> # Add a method to this instance. <CODE __designer:def t.method2 puts "Method2 Called." end</CODE> # Call both methods. <CODE __designer:t.method1 t.method2 </CODE> # Output: # Method1 Called. # Method2 Called. # Override existing method with new functionality. <CODE __designer:def t.method1 puts "I replaced the normal method with this." end</CODE> # Call the modified method. <CODE __designer:t.method1</CODE> # Output: # I replaced the normal method with this. # Add to existing methods. <CODE __designer:def t.method1 puts "Again I replaced the normal method with this, now I am going to call the method on the original class: " # Calls the original method defined at the top (on this instances SuperClass). super end</CODE> # Call the modified method. <CODE __designer:t.method1</CODE> # Output: # Again I replaced the normal method with this, now I am going to call the method on the original class: # Method1 Called. ------- Section below added in response to some questions/comments from Baj22: <CODE __designer:require "benchmark" include Benchmark</CODE> # Define a simple class. <CODE __designer:class TestClass def method1 puts "Called!" end def method2 puts "Called!" end def method3 puts "Called!" end def method4 end end </CODE> # Define a simple class. <CODE __designer:class TestClass2 < TestClass def method4 puts "Called!" end end </CODE> # List the methods supported. <CODE __designer:puts "TestClass supports #{TestClass.methods.length} method(s)" # Result: TestClass supports 76 method(s) TestClass.methods.each do |method| puts "\t #{method}" end</CODE> # Result: # to_a # respond_to? # display # etc, etc # List the methods supported. <CODE __designer:t = TestClass.new() puts "T Instance supports #{t.methods.length} method(s)" #' Result: T Instance supports 46 method(s) t.methods.each do |method| puts "\t #{method}" end</CODE> # Result: # to_a # respond_to? # display # etc, etc # Check if a class supports a method by name. <CODE __designer:puts "r responds to 'Method1' = #{t.respond_to?("method1")}" # Result: true. puts "r responds to 'UNKNOWN' = #{t.respond_to?("UNKNOWN")}" # Result: false.</CODE> # Walk the inheritance tree. <CODE __designer:cls = TestClass2 begin print cls cls = cls.superclass print " < " if cls end while cls</CODE> # Result: TestClass2 < TestClass < Object # Call a method dynimically. <CODE __designer:t.send(:method1)</CODE> # Result: Called! <CODE __designer:method1 = t.method(:method1) method1.call # Result: Called! method4 = t.method(:method4)</CODE> # Test dynamic calls. <CODE __designer:n = 100000 bm(12) {|x| x.report("Method.Call") { n.times { method4.call } } x.report("Instance.send") { n.times { t.send(:method4) } } x.report("Instance.Method") { n.times { t.method4} }</CODE> } #Result # user system total real #Method.Call 0.040000 0.000000 0.040000 ( 0.060000) #Instance.send 0.080000 0.000000 0.080000 ( 0.090000) #Instance.Method 0.050000 0.000000 0.050000 ( 0.051000) There are other ways to add methods to classes - one is to use a mix-in - where you essentially include all of the methods from a module in a class definition. This allows you to mimic some of the multiple inheritance functionality seen in C++. Anyway - thanks for your time. Any comments/questions are welcome. As I play with Ruby more I will try to post more articles on things that I find interesting. Version.
http://www.codeproject.com/Articles/15429/Ruby-Add-class-methods-at-runtime
CC-MAIN-2014-41
refinedweb
653
61.73
Topic 3 Annuities.... Annuities 7. Please type all answers directly in this Assignment below the question it applies to. All Assignments are due by Tuesday at 11:59 PM ET of the assigned Unit. Note: All interest rates are to be assumed to be yearly interest rates. Question 1 (10 points) 1. You wish to deposit $500 per month into an account for 36 months. Assume your interest rate is equal to the prime interest rate. a) How much do you have (total) in the account after 36 months? b) How much of that total is interest? Question 2 (10 points) 2. Two people, Ella and Jane, decide to start saving for retirement. Ella decides to invest $4000 a year into an annuity at the age of 25. At the age of 35 she stops making investments and just leaves the money there. Jane on the other hand, decides to start investing $4000 a year at the age of 40 and invests that money for every year thereafter. Assuming both retire at 70, and that the interest rate both get on their investments is 10% (compounded annually) who has the most money in their account at age 70? Explain why you pick the answer you pick. Question 3 (10 points) 3. At the age of 30 you decide to start saving money. At first you can only afford to deposit $200 per month. However, at the age of 38 you are able to deposit $300 per month. Then at the age of 45 you raise your monthly deposit again to $500 per month. Finally at the age of 50 you get promoted to president of the company and are able to deposit $2000 per month into the account. Assuming your account is earning (prime interest rate + 4%) in interest, compounded monthly, how much do you have in your account at the age of 70? Hint: Treat each time that you change the deposit amount as a seperate annuity, and compute the future value (FV) on each annuity seperately. Assume that each annuity earns compound interest during the time it is not receiving deposits. Essay (15 points) 4. It is commonly assumed that the stock market yields a 10% rate or return (on average) on investments made in the market long term. Write an essay looking at the advantages and disadvantages of investing in the stock market long term. Requirements for essay. The required website counts as one source · You must state at least one clear advantage and one clear disadvantage in your essay. However more references are recommended. · Hint: Some major stock market events to consider are the crash of 1929, the flash crash of 2011, the dot com era of the late 90's, the fast drop in value in 2007-2008 then the market's climb back up in 2009 - 2012. Research into those may help you to get started.). Data needed to answer 1. Using the internet, find a link that will tell you the average price of a gallon of gas for a given time period. 2. Using the internet, find a website that will show you houses for sale. 3. Find a website that shows one how to do fraction to decimal conversions. 4. Using the internet, find a website that one can use to find the national average cost of food for an individual, as well as for a family of 4 for a given month. 5. Find a website for your local city government. dmv.ny.gov6. Bankrate.com. (2015, March 25). Wall Street prime rate. Retrieved from: Please show work Tutor Answer
https://www.studypool.com/questions/180678/topic-3-annuities
CC-MAIN-2018-30
refinedweb
600
74.08
Ruben Rodriguez Santiago's article presents a use case that demonstrates how you can use Oracle Process Cloud Service, Mobile Cloud Service, and Mobile Application Framework can be used together to expose an Oracle PCS process instance as a web service and call it from an external system, web application, or mobile application. by Ruben Rodriguez Santiago Technology Context Oracle Process Cloud Service Oracle Process Cloud Service (PCS), a Platform as a Service (PaaS) provided by Oracle Cloud, allows you to rapidly design, automate, and manage business processes in the cloud. Oracle Mobile Cloud Service Oracle Mobile Cloud Service (MCS) is Oracle's Mobile Backend as a Service (MBaaS) and enables companies to create and deploy scalable, robust, and secure mobile applications quickly and easily. Oracle Mobile Application Framework Oracle Mobile Application Framework (Oracle MAF) is a hybrid mobile framework that provides a visual and declarative development experience for the rapid development of multi-platform applications. Introduction A common way to start an Oracle BPM (Business Process Management) process instance is by exposing it as a web service and calling it from an external system, web application, or mobile application. We can also achieve this in PCS, where start events are automatically exposed as SOAP web services. PCS instances can be also started using the provided REST API. In terms of mobile development, the best practice is to consume REST/JSON web services in order to take advantage of performance benefits; using MCS is a good option. Apart from that, MCS provides analytics as well as many features that will increase development productivity. This article will illustrate how Oracle MCS can be used as the mobile gateway for all Oracle PaaS products by explaining how to: - Create a process in PCS whose instances can be started either by calling a SOAP web service or using the PCS Workspace - Consume Oracle PCS REST API - Consume Oracle PCS SOAP process web services from MCS and create a custom API that will be exposed as a REST service - Create an Oracle MAF application and integrate it with an MCS instance where we will consume the created custom APIs Use Case A client requires the creation of a process in Oracle PCS. Instances of that process will be started using a form in a custom mobile application built on Oracle MAF and using Oracle PCS Workspace. To optimize the communication between the service process and the mobile client, MCS is used to transform SOAP requests into mobile-optimized REST/JSON calls. To achieve this requirement, we will follow these steps: - Design and implement a process in PCS - Deploy the process - Overview of PCS REST API - Create a mobile backend in MCS - Create a connector in MCS - Create, design, and implement a custom API that calls the connector - Create a MAF application - Testing Prerequisites - Active PCS account - Active MCS account - Oracle JDeveloper 12.1.3 - Oracle MAF extension in JDeveloper (2.1.3+) - Android/iOS/Windows 10 device or tester Solution Design and implement a process in Oracle PCS Create an application Before we design and implement the process we have to do a couple of things. - On the PCS home page, click Develop Processes: Figure 1 - Click the Create button and create a new space. (A space is just a way to gather and share applications.) - Fill in the name of the space and click Create. - Next we have to create an application, so click the New Application button. - Fill in the form and click Create. Select the space you just created. Your application has been created; the next step is to create the Register User process that we will start from our mobile application. Create a process As you can see, we can now create a process based on a predefined pattern by clicking one of the options that appears in the middle of the page. - Click Start with a form (see Figure 2, below). Web forms define the user interface that allows end users to interact with business processes. This will allow us to start the process instance with this web form and also from the mobile application (because it can be published as a SOAP web service). Figure 2 - Fill in the name of the process. In this case, let's call it RegisterProcess. - To create the process, just click the Create button at the bottom right. Figure 3 We've created our process, but there are a couple more steps before we can design and implement the process itself. Define business objects - Click Business Types in the left menu. - Click the + icon in the upper right of the page. Figure 4 - In the pop-up, fill the name of the Business Object (in this case, UserBO) and click Next. Business Objects allow you to model and develop the business entities that are part of your process. You can use PCS Composer to create business objects manually, or you can base them on an XML Schema Definition (XSD). Figure 5 - Now we add as many as attributes as we want. In this case, we'll add only four attributes (to keep things simple). Figure 6 Create the form After creating the Business Objects, we have to create the form we'll use to start the instance: - Click on Web Forms on the left menu (see Figure 7, below). - Click the + icon in the upper right. Figure 7 - Give a name to the form and click Create. The form is now created. But now we have to add the fields from the Business Object we just created so we can add Business Object attributes as form fields. - Click the icon indicated in Figure 8. Figure 8 - Select the Business Object and click OK. Figure 9 Now that we have associated the Business Object, we add its fields to the form. - Click the green button next to the Business Object name. The fields will be automatically added to the form. Figure 10 Implement the process Now it's time to move into the process and define the flow. - Click on the Root Directory tab, then click RegisterProcess to open the process diagram. - To implement the form start event, click Start. - Click Implementation. Figure 11 Now we need to associate the form we have just created with the Start activity. - Click the Search icon at the bottom of the page. - Click Register Form. - Give a title to the form. This is the title the user will see when the instance is created through the workspace. Figure 12 We could now run the process as-is. But in order to show you how easy process development is in PCS, we’re going to make a couple of changes. - Right click on the screen and click Add Lane. Figure 13 This will add a new lane to the process, where we will add another activity.After that, on the right hand side of the screen, we have a menu where we can drag and drop components (e.g., gateways, events or system activities) into the process diagram. - Drag and drop an Approve activity to the line that joins the Start and End events. - Move both Approve and End activities to the bottom lane. Figure 14 At this point we already have our process done, but we have to validate it and publish it before we can deploy it and make it available. - Click the Validate button and then the Publish button, as indicated in Figure 15. Deploy the process In PCS, deployment is easy. We have two options for navigating to the Manage Deployed Applications page. - Navigate to the home page and click the Deployed Applications link on the bottom left of the page. Figure 16 - In the process editor, click the Management button. Figure 17 On this page we can see a list of deployed applications. There’s a button that lets us take some actions on the application and also see the exposed and consumed services. - To deploy the application, click the Deploy link on the left-hand side. Figure 18 - In the Deploy pop-up, select the space, the application, and the snapshot to be published. In the next step, we review the deployment; in the last step we will configure the revision id of the application (in this case, this is revision 1.0). This last step is the same that we find when deploying a BPM process in a WebLogic Server; apart from the revision, we can set the revision as default revision and also override an existing revision. Now that we have the application successfully deployed, we need to know the WSDL that we are going to use to make the call to start the instance. - Click the button on the application row in the table and select the Web Services menu option. In the exposed web services we can see a WSDL. Copy that URL, and we are ready to move to Oracle MCS. Figure 19 Overview of Process Cloud Service REST API As mentioned at the beginning of the article, Oracle PCS also provides a REST API. We can manage, for example, processes, tasks and analytics. I am going to make an example call to start an instance of the process we have just created. The URL structure we are going to use in this example is: - example.com is the host of your instance - /bpm/api/3.0/ is the fixed prefix for the REST resources - processes is the resource We have to make a POST call and set a request body as shown below (we can get the values of the parameters that we need by invoking a GET call to /process-definitions resource): Figure 20 As you can see in the image, payload parameter is a string with business object data in XML format. [code} <payload> <formArg> <user:UserBO xmlns:user=\"\"> <user:firstName>Ruben</user:firstName> <user:lastName>Rodriguez</user:lastName> <user:email>rest.test@avanttic.com</user:email> <user:country>Spain</user:country> </user:UserBO> </formArg> </payload> [/code] After setting the request body parameters, we can execute it. Figure 21 You can check all the available APIs in this link: REST API for Oracle Process Cloud Service. Create a Mobile Backend (MBE) in MCS A Mobile Backend (MBE) is the gateway through which we will make all the calls to any Oracle MCS Platform API or Custom API. So the first step is to create an MBE. - In Oracle MCS Portal, navigate to Mobile Backends. Figure 22 - Click the New Mobile Backend button. - Fill in the name of the Mobile Backend and click Create. As soon as we finish step 3, the Mobile Backend settings page will be displayed. On this page we can see information such as Base URL, Mobile Backend ID, Anonymous Key and the Application Keys. We are going to use them at the end of this article, when we head to JDeveloper and start coding the MAF Application. Create a connector in MCS Oracle MCS provides an option to register SOAP and REST services as a named connector configuration. The connector provides an abstraction that allows developers to apply changes to the service configuration without impacting custom code accessing the service. In this case, we are going to create a SOAP connector because Oracle PCS processes are published as SOAP web services. - In the MCS Portal, navigate to Connectors. - On the Connectors page, click New Connector. For type, choose SOAP. - In the pop-up that appears, provide the WSDL endpoint URL that we got after the deployment in PCS, the API name, and the API description. Figure 23 Now the SOAP connector is created—but we need to configure a couple of things before moving to create the Custom API. - In the Security train stop of the connector configuration, add oracle/http_basic_auth_over_ssl_client_policy to selected policies. We must select an existing API key or create a new one by clicking on the keys in the csf-key field. This will allow us to automatically send HTTP basic credentials in the web service call. Figure 24 Apart from these security settings, in the SOAP connector configuration wizard we'll find train stops that will allow us to: - General stop: Configure service connection settings such as HTTP Read Timeout and HTTP Connection Timeout. - Port stop: Modify the endpoint and provide alternate names for all the web service operations. - Test stop: We can use the test client to test the web service call. In test stop, you can see that, although the web service you are trying to call is a SOAP/XML service, you are going to use REST/JSON thanks to the MCS translator that automatically transforms a SOAP/XML to REST/JSON. Figure 25 The automated SOAP to JSON translation has documented limitations that developers need to consider. Known limitations are: - Choice groups with child elements belonging to different namespaces having the same (local) name. JSON does not support namespaces. - Sequence groups with child elements having duplicate local names For example: <Parent><ChildA/><ChildB/>...<ChildA/>...</Parent> This translates to an object with duplicate property names, which is not valid in JSON. - XML Schema Instance (xsi) attributes Figure 26 illustrate an example of a payload that the translator will not be able to convert into JSON. Figure 26 The translator does not add the header namespaces to the XML it produces. In this case, you will still be able to call the web service by circumventing the translator; you just have to use an XML payload and set content-type":"application/xml;charset=UTF-8 and accept":"application/xml as header parameters. By clicking on Test Endpoint, we can test if the process instance is started when the web service operation is executed. We need to select an MBE and a version. We need some information about the connector in order to call it from the custom API: - Connector uri: /mobile/connector/PcsStart_rrs - Web service method: start Create, Design and Implement a Custom API that Calls the Connector Create an API The last step in MCS is to create a Custom API that will make the call to the connector we have just created. Custom APIs are exposed as REST resources and implemented using Node.js. You use custom APIs to implement the business logic for a MBE. - In the MCS Portal, navigate to APIs. - On the APIs page, click the New API button. - In the pop-up that appears, select an existing RAML document or start to build your API from scratch by filling in the API Name, API Display Name and API Description. Figure 27 Define the API Now that we have created the API, we have to start defining it. - Navigate to the Security tab. - Click the Allow Anonymous User Access button. Figure 28 Doing this we don't have to manage users and configure roles. To make the call to the Custom API from our MAF application, we’ll use the Mobile Backend Anonymous Key. After we have modified the security, we start defining the structure of our API. - Go to the Endpoints tab. - Click the New Resource button. - Set a Resource Path, in this case pcsregister. - Click the Methods link on the right side of the resource to create the HTTP methods that we are going to use in our API. - Click the Add Method button. - Select POST. After the method is created, we can set custom response payloads; for example, when a 200 code is sent, the custom message “Process Instance has been successfully started” will also be sent by the API. This is useful when multiple developers are working on the project. While a service developer implements the API, a mobile application developer can consume this API and get the example responses. We must add a new media type in the request body so our API will accept a JSON body. We can also add an example request, as seen in the image below: Figure 31 The sample JSON allows you to run the custom API with mockup data. This allows parallel development of the mobile client application and the business logic in MCS. Implement the API After the API REST endpoints are defined, we have to implement the logic of our API using node.js. - Click the Implementations option on the left (see Figure 31). - Click the JavaScript Scaffold button to download the files to implement the API. The name of the zip file we have just downloaded matches the name of the API, followed by an underscore and the API’s version number. In this case, the name is: pcsapi_rrs_1.0.zip. It also contains a few files: Figure 32 Now it is time to modify the files we have just downloaded. - package.json: Information relative to the project and where, for example, dependencies are managed. - pcsapi_rrs.js: Implementation file. If we open it, we can see that skeleton methods have been created for each endpoint and the methods that we defined for this API in MCS. - In package.json we must add the connector we want to call as a dependency. The URI we have to add can be found in general step in connectors settings in MCS. - Now we must implement our API, so we make the call to the connector. Line 5: First we set connector uri in optionList object. As you can see, you have to use connector uri and the name of the method you are going to call. Line 7-24: We also have to build a JSON object using some values of the request we have received, using req.body[‘myKey’]. Line 25: We add the header content-type parameter and set it to application/json. Line 27-36: The last thing is to execute a POST call and evaluate whether it returns an error. If it does, we will send the client the returned http code and a custom JSON with the error message. If everything is correct, we will send a 200 http code and JSON with a success message. Implementation is now completed. Now we put both files we have modified into the zip file we previously downloaded and upload it to MCS. The last step in MCS is to select the API we have just created in the mobile backend. Figure 36 Create a MAF application The last step in this integration is to create a MAF application that accesses the custom API exposed on the MCS mobile backend. Access is simplified by using the Oracle MAF MCS Utility (mafmcsutility.jar). In MCS, client SDKs exist for Android, iOS, Windows, JavaScript and Xamarin. The MAF MCS Utility is not an official SDK, but provides similar functionality for MAF application developers. Integrate MAF MCS Utility Before creating the application, we'll get everything we need to integrate MCS. We can get mafmcsutility.jar in MAF public samples (e.g., C:\Oracle\Middleware\Oracle_Home\jdeveloper\jdev\extensions\oracle.maf\Samples) or download it from: After we have the library, we are ready to start building the application: - To create the application, click File -> New -> Application. - In the gallery, select Mobile Application Framework Application and click OK. In the next popup, choose the location where you want to place the application and the name of the application. After setting those values, click Finish. - Add mafmcsutility.jar to the ApplicationController project by going to the Libraries and Classpath menu in Project Properties. Create a REST Connection We also have to provide a REST Connection in this method: - In the Application Navigator, go to Application Resources. - Right click on Connections node. In the Edit REST Connection dialog, fill the form with the connection name (in this case, MCS) and with the base URL of the mobile backend that we get in MCS. Figure 38 Create the DataControl - Create a Java class called MCSDataControl.java. We are going to add some methods from the sample application provided for the MAF MCS Utility. - prepareMCSAccess: This method creates a mobile backend object that represents a mobile backend in MCS. Provide the following information about the mobile backend in MCS: - Mobile Backend Id - Anonymous key - Application key - The REST connection we have just created (marked in red, below) Figure 39 - anonymousLogin: as we set the API to allow anonymous login, we must call this method. Figure 40 - invokeCustomMcsAPI: this method uses a Custom API Service Proxy to execute our custom API Figure 41 As we are going to display a pop-up with the result of the API call, we’ll need a couple of methods from this blog post. - registerUser: We are going to call this method from our page as this will be the only method exposed in the DataControl. This method has four parameters, and those are the values we have to send to the API so we also have to build the JSON. We have to get the API URI from MCS and provide it while calling invokeCustoMcsAPI method. Figure 42 - In the Application navigator, right click on MCSDataControl class and click Create Data Control. Create the User Interface Now we just have to create the user interface and call the method we have just created. - In maf-feature.xml file we'll create a new UI. I have called it Register. - After the feature is registered we must create a new AMX Page under the Content tab. - We also have to add popupUtils.js under Includesand set it as JavaScript type. A new file, RegisterForm.amx, has been created. - From the Data Controls palette, drag and drop the registerUser method under MCSDataControl to the page and select MAF Parameter Form. This will create four inputText items, one for each parameter of the method, and the button that will call the action. Because we are displaying a pop-up, we have to add two hidden buttons, as stated in this blog post. Testing To test what we have built, we have to deploy the MAF Application. In JDeveloper, click Application and move the mouse to Deploy. Choose where to deploy the application (iOS/Android emulator, device or package). In this case, I am going to deploy to an Android emulator. (The emulator has to be running before we try to deploy or the deployment will fail.) Figure 45 Once the application has started, fill the form's values and click Register at the top right of the screen. Figure 46 After MCS Custom API has been called, a pop-up will appear with the message. Figure 47 We can check in MCS Analytics and see that a call has been made. Figure 48 Lastly, we can see in PCS that the instance has been started and is now in Approval status. Figure 49 If we open the form, we can see that the values are those that we sent from our application. Figure 50 Conclusion As this article has demonstrated, Oracle Process Cloud Service allows us to quickly and easily build business processes and expose their interfaces as SOAP web services, or we can interact with Oracle PCS using its REST API. Thanks to Oracle Mobile Cloud Service, in addition to features such as Analytics, Storage, and Notifications, we can also integrate any cloud or on-demand system using connectors and expose them as REST services, improving the performance of mobile applications. And with Oracle Mobile Application Framework we can quickly build cross-platform (Android, iOS and Windows 10 in the future) mobile applications with single-code development. About the Author Rubén Rodríguez has been working with Oracle products since getting his degree in Computer Science. Rubén is ADF Technical Lead and Cloud Specialist in a Spanish Platinum Partner, avanttic where he is focusing on Oracle PaaS and Oracle Application Development Tools and Frameworks. A regular contributor to community.oracle.com, Rubén also maintains separate blogs in Spanish and English. This article has been reviewed by the relevant Oracle product team and found to be in compliance with standards and practices for the use of Oracle products.
https://community.oracle.com/docs/DOC-996644
CC-MAIN-2020-05
refinedweb
3,990
61.97
Abstract Perl has a lot of tools for parser generation using Perl. Perl has flexible data structures which makes it easy to generate generic trees. While it is easy to write a grammar and a lexical analyzer using modules like Parse::Yapp and Parse::Lex, these tools are not as fast as I would like. I use the Parse::Yapp syntax parser with the flex lexical analyzer to solve this. 1 Introduction Some time ago, I needed to make a dictionary programming language parser faster. The original programmer had written the parser with a patched Berkeley Yacc (byacc), which can generate Perl from a grammar specification like common yacc. The only difference resides in the semantic actions, written with Perl. He wrote the lexical analyzer with simple Perl regular expressions. This combination works, but loading the complete dictionary took about 27 seconds, which was too long for me. I combined Perl with flex to cut the parsing time in half. 2 Parser structure When I write a program in any language and a compiler interprets source code, a parser is involved. It takes the code I write, splits it out as strings of characters with a special meaning—tokens—and then tries to match these token sequences with a grammar. The process has two parts—lexing and parsing. A lexical analyzer, or lexer, splits a program into pieces called tokens. Regular expressions match each token, which the lexer returns one by one to the caller program. Commonly, it returns the token type with the string which corresponds to the matched token. Another program, a syntactic analyzer, or parser, puts these pieces together to check if their sequence makes any sense. The parser uses a grammar, or a set of rules, to construct a sentence and check if all the necessary tokens are used, and that no more are needed. It builds a tree of the program structure to generate or interpret code. Traditional tools for generating parsers in C are lex and yacc, or their GNU variants, flex and bison. When using Perl, people implement parsers in many ways. 4 Cooking Perl with flex 3 Why flex On my first approach I converted the grammar to a full Perl parser. I could have chosen tools like Parse::RecDescent, Parse::YALALR, or others, but I chose Parse::Yapp because its syntax and function- ality is very similar to the old yacc. In a half an hour I had a new, working version of the parser, but had only reduced the time for the parsing task by one or two seconds. This small speed-up occurs because Parse::Yapp creates full Perl programs, taking advantage of Perl facilities. Next, since I could not make the syntax analyzer quicker, I tried to change the lexical one. I wanted to use Parse::Lex, but since it used Perl regular expressions I decided to find another option. I really like Perl, but started thinking about a C implementation for the Parser. That would take a long time but I heard about the XSUB concept and started working on a flex specification to glue with Parse::Yapp. I could have implemented this glue using different techniques. I could write the lexical analyzer returning integers, where each one represents a different grammar terminal symbol, or I could return a string with the name of the symbol. While the second method can be slower than returning integers, the grammar is more legible, so I went with it. I implemented my flex analyzer and glued it with Parse::Yapp. It ran in about half the original parsing time. Perl is very flexible, and flex is very fast. I can create simple and fast parsers using both of them together. 4 The Recipe To demonstrate what I did I use something a lot more simple than my original problem, although I illustrate all of the major points in the process. I want to create a parser for simple arithmetic problems like “1 + 2”. The lexer will break the string into tokens ( “1”, “+”, “2”), perform the arithmetic operation, and return the result. I need to write two things—the grammar and the lexical analyzer. I like to start with the grammar, although that is personal preference. The Parse::Yapp syntax is like yacc. I can write a grammar for arithmetic expressions, which I put in a file I name myGrammar.yp shown in code listing 1. 6 %% 7 command: exp NL { return $_[1] } 8 ; 9 Next, I write the lexical analyser in C. I create the file named myLex.l in which I put the instructions for lexing the source, shown in code listing 2. 4 char buffer[15]; 5 6 %} 7 8 %% 9 [0-9]+ { return strcpy(buffer, "NUMBER"); } 10 15 %% 16 int perl_yywrap(void) { 17 return 1; 18 } 19 char* perl_yylextext(void) { 20 return perl_yytext; 21 } The first three lines define the prototype for the lexical analyzer. I return strings instead of the integers returned by default. I have to put these strings somewhere. In this example, I allocate a char array named buffer where I will put the token information. The next section is a normal lexical analyzer, returning the name of the token or the character found. The perl yywrap and perl yylextext glue the parser to the lexical analyzer. The perl yywrap function restarts the parsing task while perl yylextext accesses the text which matched the regular expression through perl yytext, which flex creates for me. Now I have the two main tools and I am only missing the glue. The easiest way I can do this is creating a module for my parser. I start with h2xs which creates most of the module structure and files for me. h2xs -n myParser I have to edit some of the files that h2xs creates, and add the files that I just created. I need to add some XSUB code to myParser.xs to the lexer in myLex.l to Perl, add a line to the typemaps file, and adjust the Makefile.PL to correctly compile everything. I copy the flex source to myParser/myLex.l and the Parse::Yapp grammar to myParser/myGrammar.yp to the module directory. Parse::Yapp expects a yylex function that returns a pair—the name of the token and the matched text—so I add a perl lex function to myParser.pm, shown in code listing 3. I wrote perl yylextext in myLex.l (code listing 2), and flex generates perl yylex for me. I also need an error-handling function in myParser.pm. My error function in code listing 4 will simply print the token read and the token it expected if it encounters an error. Once I have that done, I edit myParser.xs file to map the C functions into Perl ones. I leave the code that h2xs generated alone, and add another header file with the others. #include "myLex.h" At the end of the file I add the parts that connect my lex functions with the functions that I call from Perl, shown in code listing 5. The spaces and newlines are significant. The first line of each function is the return type, followed by a line with the name of the function. Then I have two lines showing Perl where to get the return value from the C functions. 6 char* 7 perl_yylextext() 8 OUTPUT: 9 RETVAL I create the myLex.h file, shown in code listing 6, which holds the prototypes for the functions in myLex.l. I have to map data types from C to Perl. Integers are trivial and handled directly by perl, but I also have pointers to characters. I create a file named typemap, shown in code listing 7 that translates pointers to characters to the built-in T PV Perl type. The code is now complete, but I need to modify Makefile.PL so it can compile it. The yapp command from the Parser::Yapp distribution creates myGrammar.pm from myGrammar.yp, and flex creates lex.perl yy.c. I add an additional target to the Makefile through the MY::postamble subroutine. I also add the flex library, fl, to the library list, and name the produced library myLexer.so. Code listing 8 shows my final Makefile.PL. 8 WriteMakefile( 9 ’NAME’ => ’myParser’, 10 ’VERSION_FROM’ => ’myParser.pm’, 11 ’LIBS’ => [’-lfl’], # This is for flex 12 ’MYEXTLIB’ => ’myLexer.so’, # Our lexer 13 ); 14 15 sub MY::postamble { 16 " 17 \$(MYEXTLIB): lex.perl_yy.c myParser.pm myGrammar.pm 18 \t\$(CC) -c lex.perl_yy.c 19 \t\$(AR) cr \$(MYEXTLIB) lex.perl_yy.o 20 \tranlib \$(MYEXTLIB) 21 22 myGrammar.pm: myGrammar.yp 23 \t$YACC_COMMAND 24 25 lex.perl_yy.c: myLex.l 26 \tflex -Pperl_yy myLex.l 27 "; 28 } I compile my new module with the standard Perl module make sequence. perl Makefile.PL make 4.5 Testing I can also test my module with the standard Perl test harness, although I have not added any real tests to test.pl. make test This does not really test if my module really works—only that it compiles and loads without error. I add a test, shown in code listing 9, which takes a string from standard input, parses it, and returns the result of the arithmetic operation. Now, I run make test again and enter “1+4*2+3”, press enter, and end standard input with ˆD (or ˆZ on Windows), and I get the answer 25. 5 Conclusion While Perl is really flexible, some tools are quicker than their Perl equivalents. I can use these tools from Perl with a little bit of work. 6 References Manual pages: Parse::Yapp, ExtUtils::MakeMaker
https://id.scribd.com/document/39917945/perl-flex
CC-MAIN-2019-43
refinedweb
1,612
73.98
DSL (Domain Specific Language) is a programming language or specification language dedicated to a particular problem domain, problem representation or a particular solution technique. So with a few Scala Nuggets on our way we are ready to write a DSL? Not quite but in this post we would touch upon a critical feature in Scala which makes writing DSL’s easy. Let us look at the following code snippet. [sourcecode language=”scala”] println (1+2) println (1 .+(2)) println (1.+(2)) println (1 +(2)) [/sourcecode] and if I tell you that the output is the following 3 3 3.0 3 How do you interpret that? Well, the first one is easy and that is how we do it in Java also. What about println (1 .+(2)). How on earth can I do that? In Scala, all operators are methods. So, in our example, + is actually a method which can be called on 1. Hence what we are essentially doing here is that we are calling 1.someMethod(2) and in our case someMethod happens to be + Aha, and why is there a space between 1 and the period(.) This is because if we do not give the space, the compiler assumes that we are calling the method + on a Double. That is the reason that you see the output of println (1.+(2)) as 3.0 Ok and what the hell is println (1 +(2)). Well, actually it is the same thing as you can see from the output but Scala allows you to omit the period and the parentheses when the method takes only one argument. So we have omitted the period here and in the first line i.e. println (1+2), we have omitted both the period and the parentheses. Also if a method takes no argument but is defined with empty argument list then we can call the method either by including the parentheses or omitting it. Hence the following [sourcecode language=”scala”] def methodWithNoArgs(){ println("No Argument Method") } [/sourcecode] can be accessed with either of the two methodWithNoArgs methodWithNoArgs() However, if the method is defined with no parentheses, something like this [sourcecode language=”scala”] def methodWithNoArgsAndNoParenthesesEither{ println("No Argument No Parantheses Method") } [/sourcecode] then only this methodWithNoArgsAndNoParenthesesEither would work and methodWithNoArgsAndNoParenthesesEither() would not. How does it help with DSL? Lets look at an example. There is a company called Inphina, which has a method call to see whether the Air Conditioning can we switched on or not. [sourcecode language=”scala”] object Inphina { def switchOnACat(n:Int):Boolean={ if (n>35){ return true } else{ return false } } [/sourcecode] As you can see that the AC can be switched on when the temperature is > 35. Let us see how we can invoke it now. One way of calling is the routine way which is [sourcecode language=”scala”] val x = Inphina.switchOnACat(37); println(x) [/sourcecode] Another way is to make it more reader friendly and more like English sentence [sourcecode language=”scala”] println(Inphina switchOnACat 37) [/sourcecode] Since the switchOnACat method takes one argument hence we can omit the period and parentheses and get more readability. What about the following [sourcecode language=”scala”] (List(1, 2, 3, 4).filter(isEven)).foreach(println) def isEven(n: Int) = (n % 2) == 0 [/sourcecode] Applying the above principles of method, period and parentheses, we get the same results with List(1, 2, 3, 4) filter isEven foreach println Cool isn’t it! We will get into advanced DSL on our way by consuming Scala Nuggets one by one! 1 thought on “Scala Nuggets: Look Ma! My First DSL3 min read” The last example could be much more elegantly be written: def switchOnACat(n:Int) = n > 35
https://blog.knoldus.com/scala-nuggets-look-ma-my-first-dsl/
CC-MAIN-2021-04
refinedweb
615
72.05
Json mysql... ...Should be preferred if someone has worked on Google Speech looking for lodash js developer immediatly to fix one issue to access keys in json. my budget is 600 and Need to clean up some data from phpMyAdmin and SQL expert who understands how data is effected. Please see attached for typical SQL Queries] ...Scrapy code in backend part of Django. And then we should save the result of json list in MySQL in Django and generate csv file. All functionalites are working individually. So the source code is ready and i need to integrate Scrapy in Django, so that we can use same MySQL DB in Django and Scrapy can work in Django. This url can be helpful for integrating Build me an angular website with JSON schema form [login to view.... Need a VB expert who can build a simple vb module that capture and store biometric thumb impression in mysql and later on use that thumb impression for login authentication . website for real estate technology : php , mysql, query , newest technology I have ppython script it should be save array into json data and mysql database . some scraping is not work . you need to fix and upload on my server. I am seeking for someone with knowledge of python and selenium import search filter large json file . search edit export data in many ways xls pdf etc.. will provide sample of small file and example data inside it once we discuss. winner of this project who place best bid . thanks I need a Javascript, MySQL, PHP expert for my current projects. If you have knowledge please bid. Details will be shared in message with the freelancers. I need an expert guy in Json and Joomla for my current project. I will give more details in the message. Please experience person can bid.’application de .
https://www.freelancer.com/work/json-mysql/
CC-MAIN-2018-43
refinedweb
308
74.19
BACK This Hash table Program is used for entry set of the values using entry set() method Example Program import java.util.Hashtable; import java.util.Set; public class HashTableSet { public static void main(String[] args) { // create has table Hashtable htable = new Hashtable(); // put value into table htable.put(1, "Dog"); htable.put(2, "Cat"); htable.put(3, "Cow"); htable.put(4, "Donkey"); // create a set view Set nset = htable.entrySet(); // display set result System.out.println("Set result : " + nset); } } Output Set result : [4=Donkey, 3=Cow, 2=Cat, 1=Dog] Explanation public static interface Map.Entry<K,V>. Since: 1.2
http://candidjava.com/hash-table-example-program-using-entry-set-of-the-values/
CC-MAIN-2017-04
refinedweb
102
62.75
Technical Blog Post Abstract Namespaces for fun and profit - why you need one Body Background (optional reading) I've had variations on this conversation several times over the past few months. I guess I should create a proper rant and number it. OTOH making it a blog post means I have a URI, which is way better than a numbered rant ;-) Tom: These Linked Data/OSLC APIs all require namespaces. Where should I put client extensions? Me: In a client-owned namespace. Tom: But I don't know what that value would be/don't have one. Can't I just put them in mine? Me: [1: get back up off of floor. 2: count ten 3: meditate quickly.] No. Tom: Can I just use the deployed server hostname? Me: [1: purge images of Dilbert's Alice and her Fist of Death from brain] No. ... and so on Now before any Tom's I know get all in a huff, names have been changed to protect the guilty. These are not foolish questions or people, not in the least. Anyone schooled in the last 20 years would quite naturally think (in object-oriented terms) that everything is implicitly scoped to the class, database, organization, etc in which it occurs and this is fine. After all, it's worked so far for them. It works in a lot of real-world situations too; but not in all of them. So what's the big deal with namespaces anyway? Simple answer: uniqueness in time and space, across a set of parties that can operate in parallel with zero coordination. Neat, huh? Now what does all that actually mean? Linked Data requires namespaces because the assumption is that the data is going to be available on "the" Web, and it's going to be consumed by code (perhaps in addition to humans) - maybe the Internet, maybe an intranet, but that's an implementation detail in terms of the data. Since it's going on the Web, the assumptions are that it's going to persist (remain available for an extended period), that it can be consumed in ways that the producer never directly considered, that the producer and consumers are loosely coupled, and therefore all identifiers must be unambiguous. Not all integrations meet those criteria; sometimes you just want to ETL data from one place to another, transform it perhaps along the way, and it's throwaway/limited lifetime code. Don't feel obligated to carefully choose namespaces in those situations. Don't feel obligated to even use namespaces in those situations; if you're using a technology (for other reasons) that forces namespaces on you, pick whatever you like off the cuff - since it's throwaway code, no one will care and no Namespace Police are likely to darken your doorway. Use the right tool for the right job. Of course, if it starts as throwaway and later grows into something that needs to be durable, its implementation might need to change. Server consolidation scenario Your business has two on-premise asset management servers, owned and managed at the department level. They both follow an internal corporate standard to use the property name assetnum, but the values (identifiers, to be precise) are assigned independently. You discover that you can save money by consolidating those servers into a single one. - It's useful that the property name assetnum is used in both, but only those aware of the corporate standard know that the property names are intentionally equal. Any code that's written must have that knowledge baked into the code in order to make use of it. Once that knowledge is baked into the code, the code is less general-purpose (so it's less re-usable for other tasks). - It's misleading (at best) that the assetnum values can match for different assets, because the values were assigned independently. Both departments can set an asset number of 100, and all their processes work. Treat two assets as a single one though, and your accountants might become vexed. I darn you to heck (If you don't get that reference, it's another Dilbertism) You might follow Tom's thinking and say "just treat unqualified things (names, identifiers) whose values are equal as the same thing, regardless of where the data came from". - I suspect, pointed out like that, it's pretty obvious that this could work, but it's not reliable without some outside or implicit knowledge...and when that knowledge changes, things break. That risk might be tolerable for a short term one-off project, however not for data intended to be available over time and open to novel or unknown consumers. But let's make that assumption provisionally and see what happens. - When you see asset values, you assume "same value, same thing". Worked brilliantly for property names, not so much for independently assigned values. Those values, of course, have a scope of uniqueness of a department level; in other words, to make them unique within the business you need to know both the assetnum value and the department value... but how does code written to consume "general" data know this? Try some other assumptions on for size, like the ones from the sample conversation. Think about similar scenarios, like a merger: you acquire another business; your executives expect you to be able to report over all assets, not give them two sets of asset reports from separate tools. Who knows what overlaps in the identifiers exist, and which overlaps are intentional (useful) or not (or worse: wrong/misleading)? Here I come to save the day... Let's say you're convinced. What would a reasonable use of namespaces for this problem look like? How do I choose a namespace value? Namespaces are identified by their URI; URIs can be long and ugly (sorry), but they are familiar to any browser user. Friendly namespaces like those used in Linked Data have HTTP URIs that will serve descriptive documents, although strictly speaking the documents are optional. They're also hierarchical, and most use the delegation of authority principle from Web architecture. Here's an example: ; through the magic of the Domain Name System, someone pays ICANN (I'm simplifying a bit here) to own. Whoever that entity (person or organization) is, they then control the allocation of all URIs starting with that hostname. Assumptions: - Our hypothetical business owns, for simplicity. - Internally, the business decides how identifiers get assigned to things in need of unambiguous identification. Not to other things. - Corporate Standards decides the business's namespace allocation policy, which says - is a common prefix for all their namespaces - is a common prefix for all corporate standard terms/namespaces, whose assignments are controlled centrally by Corporate Standards (it delegates to itself, if you like) - is a common prefix for department-level terms/namespaces, whose assignments are controlled by the owning department. Thus, department A is assigned and so on. - Department A decides that asset identifiers it assigns follow the pattern - Department B decides that asset identifiers it assigns follow the pattern (if you need a reason, assume Not Invented Here syndrome). - Corporate Standards decides the the internal standard name for asset number properties is - assetnum, in contexts like relational databases that do not natively support namespace qualification of identifiers - in contexts like Linked Data that natively support namespace qualification Example Resulting URIs that show up in the Linked Data: - as a property name - as department A's identifier for what it calls asset number 100 - as department B's identifier for what it calls asset number 100 Note what has changed, and what has not, compared to the original simple assumption (plus any other variants you tried as homework) - The useful property of a corporate standard property name has not only been preserved, it has been rendered explicit. If you merge with another organization (call it SmallFry.org), even if their namespace allocation policies were identical, their URIs would still be unique (because theirs would start with a different hostname). - The misleading property of "apparently equal" identifier values (100) has been completely fixed. - Humans (and code) still have no way to know whether or not .../A/100 is the same asset as .../B/asset#100 without adding extra knowledge. UID ibm11275868
https://www.ibm.com/support/pages/node/1275868?lang=en
CC-MAIN-2020-16
refinedweb
1,380
60.45
Customizing Element Creation and Movement You can allow an element to be dragged onto another, either from the toolbox or in a paste or move operation. You can have the moved elements linked to the target elements, using the relationships that you specify. An element merge directive (EMD) specifies what happens when one model element is merged into another model element. This happens when: The user drags from the toolbox onto the diagram or a shape. The user creates an element by using an Add menu in the explorer or a compartment shape. The user moves an item from one swimlane to another. The user pastes an element. Your program code calls the element merge directive. Although the creation operations might seem to be different from the copy operations, they actually work in the same way. When an element is added, for example from the toolbox, a prototype of it is replicated. The prototype is merged into the model in the same manner as elements that have been copied from another part of the model. The responsibility of an EMD is to decide how an object or group of objects should be merged into a particular location in the model. In particular, it decides what relationships should be instantiated to link the merged group into the model. You can also customize it to set properties and to create additional objects. An EMD is generated automatically when you define an embedding relationship. This default EMD creates an instance of the relationship when users add new child instances to the parent. You can modify these default EMDs, for example by adding custom code. You can also add your own EMDs in the DSL definition, to let users drag or paste different combinations of merged and receiving classes. You can add element merge directives to domain classes, domain relationships, shapes, connectors, and diagrams. You can add or find them in DSL Explorer under the receiving domain class. The receiving class is the domain class of the element that is already in the model, and onto which the new or copied element will be merged. The Indexing Class is the domain class of elements that can be merged into members of the receiving class. Instances of subclasses of the Indexing Class will also be merged by this EMD, unless you set Applies to subclasses to False. There are two kinds of merge directive: A Process Merge directive specifies the relationships by which the new element should be linked into the tree. A Forward Merge directive redirects the new element to another receiving element, typically a parent. You can add custom code to merge directives: Set Uses custom accept to add your own code to determine whether a particular instance of the indexing element should be merged into the target element. When the user drags from the toolbox, the "invalid" pointer shows if your code disallows the merge. For example, you could allow the merge only when the receiving element is in a particular state. Set Uses custom merge to add provide own code to define the changes that are made to the model when the merge is performed. For example, you could set properties in the merged element by using data from its new location in the model. The following example lets users create an element and a connector at the same time by dragging from the toolbox onto an existing shape. The example adds an EMD to the DSL Definition. Before this modification, users can drag tools onto the diagram, but not onto existing shapes. Users can also paste elements onto other elements. To let users create an element and a connector at the same time Create a new DSL by using the Minimal Language solution template. When you run this DSL, it lets you create shapes and connectors between the shapes. You cannot drag a new ExampleElement shape from the toolbox onto an existing shape. To let users merge elements onto ExampleElement shapes, create a new EMD in the ExampleElement domain class: In DSL Explorer, expand Domain Classes. Right-click ExampleElement and then click Add New Element Merge Directive. Make sure that the DSL Details window is open, so that you can see the details of the new EMD. (Menu: View, Other Windows, DSL Details.) Set the Indexing class in the DSL Details window, to define what class of elements can be merged onto ExampleElement objects. For this example, select ExampleElements, so that the user can drag new elements onto existing elements. Notice that the Indexing class becomes the name of the EMD in DSL Explorer. Under Process merge by creating links, add two paths: One path links the new element to the parent model. The path expression that you need to enter navigates from the existing element, up through the embedding relationship to the parent model. Finally, it specifies the role in the new link to which the new element will be assigned. The path is as follows: ExampleModelHasElements.ExampleModel/!ExampleModel/.Elements The other path links the new element to the existing element. The path expression specifies the reference relationship and the role to which the new element will be assigned. This path is as follows: ExampleElementReferencesTargets.Sources You can use the path navigation tool to create each path: Under Process merge by creating links at paths, click <add path>. Click the drop-down arrow to the right of the list item. A tree view appears. Expand the nodes in the tree to form the path that you want to specify. Test the DSL: Press F5 to rebuild and run the solution. Rebuilding will take longer than usual because the generated code will be updated from text templates to conform to the new DSL Definition. When the experimental instance of Visual Studio has started, open a model file of your DSL. Create some example elements. Drag from the Example Element tool onto an existing shape. A new shape appears, and it is linked to the existing shape with a connector. Copy an existing shape. Select another shape and paste. A copy of the first shape is created. It has a new name and it is linked to the second shape with a connector. Notice the following points from this procedure: By creating Element Merge Directives, you can allow any class of element to accept any other. The EMD is created in the receiving domain class, and the accepted domain class is specified in the Index class field. By defining paths, you can specify what links should be used to connect the new element to the existing model. The links that you specify should include one embedding relationship. The EMD affects both creation from the toolbox and also paste operations. If you write custom code that creates new elements, you can explicitly invoke the EMD by using the ElementOperations.Merge method. This makes sure that your code links new elements into the model in the same way as other operations. For more information, see Customizing Copy Behavior. By adding custom code to an EMD, you can define more complex merge behavior. This simple example prevents the user from adding more than a fixed number of elements to the diagram. The example modifies the default EMD that accompanies an embedding relationship. To write Custom Accept code to restrict what the user can add Create a DSL by using the Minimal Language solution template. Open the DSL Definition diagram. In DSL Explorer, expand Domain Classes, ExampleModel, Element Merge Directives. Select the element merge directive that is named ExampleElement. This EMD controls how the user can create new ExampleElement objects in the model, for example by dragging from the toolbox. In the DSL Details window, select Uses custom accept. Rebuild the solution. This will take longer than usual because the generated code will be updated from the model. A build error will be reported, similar to: "Company.ElementMergeSample.ExampleElement does not contain a definition for CanMergeExampleElement…" You must implement the method CanMergeExampleElement. Create a new code file in the Dsl project. Replace its content with the following code and change the namespace to the namespace of your project. using Microsoft.VisualStudio.Modeling; namespace Company.ElementMergeSample // EDIT. { partial class ExampleModel { /// <summary> /// Called whenever an ExampleElement is to be merged into this ExampleModel. /// This happens when the user pastes an ExampleElement /// or drags from the toolbox. /// Determines whether the merge is allowed. /// </summary> /// <param name="rootElement">The root element in the merging EGP.</param> /// <param name="elementGroupPrototype">The EGP that the user wants to merge.</param> /// <returns>True if the merge is allowed</returns> private bool CanMergeExampleElement(ProtoElementBase rootElement, ElementGroupPrototype elementGroupPrototype) { // Allow no more than 4 elements to be added: return this.Elements.Count < 4; } } } This simple example restricts the number of elements that can be merged into the parent model. For more interesting conditions, the method can inspect any of the properties and links of the receiving object. It can also inspect the properties of the merging elements, which are carried in a ElementGroupPrototype. For more information about ElementGroupPrototypes, see Customizing Copy Behavior. For more information about how to write code that reads a model, see Navigating and Updating a Model in Program Code. Test the DSL: Press F5 to rebuild the solution. When the experimental instance of Visual Studio opens, open an instance of your DSL. Create new elements in several ways: Drag from the Example Element tool onto the diagram. In the Example Model Explorer, right-click the root node and then click Add New Example Element. Copy and paste an element on the diagram. Verify that you cannot use any of these ways to add more than four elements to the model. This is because they all use the Element Merge Directive. In custom merge code, you can define what happens when the user drags a tool or pastes onto an element. There are two ways to define a custom merge: Set Uses Custom Merge and supply the required code. Your code replaces the generated merge code. Use this option if you want to completely redefine what the merge does. Override the MergeRelate method, and optionally the MergeDisconnect method. To do this, you must set the Generates Double Derived property of the domain class. Your code can call the generated merge code in the base class. Use this option if you want to perform additional operations after the merge has been performed. These approaches only affect merges that are performed by using this EMD. If you want to affect all ways in which the merged element can be created, an alternative is to define an AddRule on the embedding relationship and a DeleteRule on the merged domain class. For more information, see Rules Propagate Changes Within the Model. To override MergeRelate In the DSL definition, make sure that you have defined the EMD to which you want to add code. If you want, you can add paths and define custom accept code as described in the previous sections. In the DslDefinition diagram, select the receiving class of the merge. Typically it is the class at the source end of an embedding relationship. For example, in a DSL generated from the Minimal Language solution, select ExampleModel. In the Properties window, set Generates Double Derived to true. Rebuild the solution. Inspect the content of Dsl\Generated Files\DomainClasses.cs. Search for methods named MergeRelate and examine their contents. This will help you write your own versions. In a new code file, write a partial class for the receiving class, and override the MergeRelate method. Remember to call the base method. For example: partial class ExampleModel { /// <summary> /// Called when the user drags or pastes an ExampleElement onto the diagram. /// Sets the time of day as the name. /// </summary> /// <param name="sourceElement">Element to be added</param> /// <param name="elementGroup">Elements to be merged</param> protected override void MergeRelate(ModelElement sourceElement, ElementGroup elementGroup) { // Connect the element according to the EMD: base.MergeRelate(sourceElement, elementGroup); // Custom actions: ExampleElement mergingElement = sourceElement as ExampleElement; if (mergingElement != null) { mergingElement.Name = DateTime.Now.ToLongTimeString(); } } } To write Custom Merge code In Dsl\Generated Code\DomainClasses.cs, inspect methods named MergeRelate. These methods create links between a new element and the existing model. Also, inspect methods named MergeDisconnect. These methods unlink an element from the model when it is to be deleted. In DSL Explorer, select or create the Element Merge Directive that you want to customize. In the DSL Details window, set Uses Custom Merge. When you set this option, the Process Merge and Forward Merge options are ignored. Your code is used instead. Rebuild the solution. It will take longer than usual because the generated code files will be updated from the model. Error messages will appear. Double-click the error messages to see the instructions in the generated code. These instructions ask you to supply two methods, MergeRelateYourDomainClass and MergeDisconnectYourDomainClass Write the methods in a partial class definition in a separate code file. The examples you inspected earlier should suggest what you need. Custom merge code will not affect code that creates objects and relationships directly, and it will not affect other EMDs. To make sure that your additional changes are implemented regardless of how the element is created, consider writing an AddRule and a DeleteRule instead. For more information, see Rules Propagate Changes Within the Model. A forward merge directive redirects the target of a merge operation. Typically, the new target is the embedding parent of the initial target. For example, in a DSL that was created with the component diagram template, Ports are embedded in Components. Ports are displayed as small shapes on the edge of a component shape. The user creates ports by dragging the Port tool onto a Component shape. But sometimes, the user mistakenly drags the Port tool onto an existing port, instead of the component, and the operation fails. This is an easy mistake when there are several existing ports. To help the user to avoid this nuisance, you can allow ports to be dragged onto an existing port, but have the action redirected to the parent component. The operation works as if the target element were the component. You can create a forward merge directive in the Component Model solution. If you compile and run the original solution, you should see that users can drag any number of Input Port or Output Port elements from the Toolbox to a Component element. However, they cannot drag a port to an existing port. The Unavailable pointer alerts them that this move is not enabled. However, you can create a forward merge directive so that a port that is unintentionally dropped on an existing Input Port is forwarded to the Component element. To create a forward merge directive Create a Domain-Specific Language Tools solution by using the Component Model template. Display the DSL Explorer by opening DslDefinition.dsl. In the DSL Explorer, expand Domain Classes. The ComponentPort abstract domain class is the base class of both InPort and OutPort. Right-click ComponentPort and then click Add New Element Merge Directive. A new Element Merge Directive node appears under the Element Merge Directives node. Select the Element Merge Directive node and open the DSL Details window. In the Indexing class list, select ComponentPort. Select Forward merge to a different domain class. In the path selection list, expand ComponentPort, expand ComponentHasPorts, and then select Component. The new path should resemble this one: ComponentHasPorts.Component/!Component Save the solution, and then transform the templates by clicking the rightmost button on the Solution Explorer toolbar. Build and run the solution. A new instance of Visual Studio appears. In Solution Explorer, open Sample.mydsl. The diagram and the ComponentLanguage Toolbox appear. Drag an Input Port from the Toolbox to another Input Port. Next, drag an OutputPort to an InputPort and then to another OutputPort. You should not see the Unavailable pointer, and you should be able to drop the new Input Port on the existing one. Select the new Input Port and drag it to another point on the Component.
http://msdn.microsoft.com/library/bb126573.aspx
CC-MAIN-2014-52
refinedweb
2,669
57.16
sbt-soundsbt-sound An sbt (Simple Build Tool) plugin for adding sounds to sbt's task completions. This plugin allows you to associate sounds with successful and/or failed task completions, giving you audio feedback. Any TaskKey can have a sound association. This is especially useful for: - Long build times - A failing ~compilethat is running in the background/behind other windows - A failing ~test - Drawing your attention to any specific task outcome The reason I wrote this plugin is that I usually code with a running sbt ~compile in the background, and would like to know asap when something breaks. I code in Sublime Text (see my plugin for it), and when I'm not connected to an external monitor I have sbt in the background, periodically checking it to see everything's fine. This plugin solves this problem for me, only drawing my attention when the build breaks. I think others could find this plugin useful in other ways as well. Add PluginAdd Plugin To add sbt-sound functionality to your project add the following to your project/plugins.sbt file: addSbtPlugin("com.orrsella" % "sbt-sound" % "1.0.6") // For sbt 0.12.x, 0.13.x: addSbtPlugin("com.orrsella" % "sbt-sound" % "1.0.4") UsageUsage SoundsSounds The sbt-sound jar comes pre-loaded with 14 sounds (shamelessly copied from Mountain Lion's sounds folder, hope I won't get in trouble for this): - Basso - Blow - Bottle - Frog - Funk - Glass - Hero - Morse - Ping - Pop - Purr - Sosumi - Submarine - Tink You can also specify any .wav or .aiff file on your local machine (maybe other formats work as well, these are the ones I tested with). ConfigurationConfiguration build.sbtbuild.sbt After enabling the plugin, you can configure it by adding any of the following to build.sbt: import SbtSound._ sound.play(compile in Compile, Sounds.Basso) // play the 'Basso' sound whenever compile completes (successful or not) sound.play(compile in Compile, Sounds.None, Sounds.Pop) // play the 'Pop' sound only when compile fails sound.play(test in Test, Sounds.Purr, "/Users/me/Sounds/my-sound.wav") // play 'Purr' when test completes successfully // or the wav file 'my-sound' when it fails You can configure any sbt TaskKey (and as many as you like) in the above way. Build.scalaBuild.scala If you're using a .scala build file, you can add the following: import com.orrsella.sbtsound.SbtSound._ ... object MyBuild extends Build { lazy val main = Project ( "my-proj", file("."), settings = Defaults.defaultSettings ++ ... ++ sound.play(installDevice in AndroidKeys.Android, "/Users/mark/Documents/Quatsch/Hoo.wav") ) } Above example curtsey of @i-am-the-slime – it alerts when an entire build is complete (using the sbt android-plugin to also install on the device). Example full project definition can be found here. StackingStacking The way sbt-sound works is by adding task <<= (task) mapR { ... } to every task's completion. Because the functionality is tucked on every task you configure in build.sbt, running tasks that depend on other tasks (and execute them), will cause all sounds in the chain to play. So if, for example, you specify a sound for compile and test, and when running test the code compiles because of the compile command, both sounds will play. Take that into consideration when configuration which tasks to play sounds for. The easiest way to avoid this problem is to define sounds for failing actions, which usually don't trigger the following tasks, thus solving this "problem". FeedbackFeedback Any comments/suggestions? Let me know what you think – I'd love to hear from you. Send pull requests, issues or contact me: @orrsella and orrsella.com.
https://index.scala-lang.org/orrsella/sbt-sound
CC-MAIN-2022-27
refinedweb
603
57.37
A Comprehensive Introduction to Less: Mixins Mix… what? With Less, we can define so-called "mixins", which have some similarities to functions in programming languages. In Less, they’re used to group CSS instructions in handy, reusable classes. Mixins allow you to embed all the properties of a class into another class by simply including the class name as one of its properties. It’s just like variables, but for whole classes. Any CSS class or id ruleset can be mixed-in that way: .round-borders { border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; } #menu { color: gray; .round-borders; } // Output .round-borders { border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; } #menu { color: gray; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; } As you can see, this output is the mixin itself and the CSS ruleset. If you don’t want mixins to appear in your compiled .css file just add empty parenthesis after the mixin name. you may wonder why I’m using a capitalized letter for the mixin names. This is because CSS class selectors also use the dot symbol and there is no way to differentiate it from a Less mixin name. That’s why I usually use capitalized letters, as in object oriented programming, which uses capitalized letters for classes. Enter Your Arguments, Please Mixins can be made parametric, meaning they can take arguments to enhance their utility. A parametric mixin all by itself is not output when compiled. Its properties will only appear when mixed into another block. The canonical example is to create a rounded corners mixin that works across browsers: .round-borders (@radius) { border-radius: @radius; -moz-border-radius: @radius; -webkit-border-radius: @radius; } And here’s how we can mix it into various rulesets: header { .round-borders(4px); } .button { .round-borders(6px); } Parametric mixins can also have default values for their parameters: .round-borders (@radius: 5px) { border-radius: @radius; -moz-border-radius: @radius; -webkit-border-radius: @radius; } Now we can invoke it like this: header { .round-borders; } And it will include a 5px border-radius. If you have a mixin that doesn’t have any arguments, but you don’t want it to show up in the final output, give it a blank argument list: .hiddenMixin() { color: black; } p { .hiddenMixin() } Which would output: p { color: black; } Within a mixin there is a special variable named @arguments that contain all the arguments passed to the mixin, along with any remaining arguments that have default values. The value of the variable has all the values separated by spaces. This is useful for quickly assigning all the arguments: .box-shadow(@x: 0, @y: 0, @blur: 1px, @color: #000) { box-shadow: @arguments; -moz-box-shadow: @arguments; -webkit-box-shadow: @arguments; } .box-shadow(2px, 5px); Which results in: box-shadow: 2px 5px 1px #000; -moz-box-shadow: 2px 5px 1px #000; -webkit-box-shadow: 2px 5px 1px #000; A Little Matchmaking :) When you mix in a mixin, all the available mixins of that name, in the current scope, are checked to see if they match according to what was passed to the mixin and how it was declared. The simplest case is matching on arity (the number of arguments that the mixin takes). Only the mixins that match the number of arguments passed in are used, with the exception of zero-argument mixins, which are always included. Here’s an example: .mixin() { // this is always included background-color: white; } . Another way of controlling whether a mixin matches, is by specifying a value in place of an argument name when declaring the mixin: .mixin (dark, @color) { color: darken(@color, 10%); } .mixin (light, @color) { color: lighten(@color, 10%); } .mixin (@_, @color) { // this is always included display: block; } @switch: light; .class { .mixin(@switch, #888); } We will get the following CSS: .class { color: #a2a2a2; display: block; } Where the color passed to .mixin was lightened. If the value of @switch was dark, the result would be a darker color. Only mixin definitions that matched were used. Variables match and bind to any value, and anything other than a variable matches only with a value equal to. Guards are useful when you want to match on expressions, as opposed to simple values or arity. We use the when keyword to begin describing a list of guard expressions. .mixin (@a) when (lightness(@a) >= 50%) { background-color: black; } .mixin (@a) when (lightness(@a) < 50%) { background-color: white; } .mixin (@a) { // this is always included color: @a; } .class1 { .mixin(#ddd); } // this matches the first mixin .class2 { .mixin(#555); } // this matches the second mixin Here’s what we’ll get: .class1 { background-color: black; color: #ddd; } .class2 { background-color: white; color: #555; } The full list of comparison operators usable in guards are: >, >=, =, =<, <. If you want to match mixins based on value type, you can use the is* functions. These are—iscolor, isnumber, isstring, iskeyword, and isurl. If you want to check if a value, in addition to being a number, is in a specific unit, you may use one of these—ispixel, ispercentage, isem. Here is a quick example: .mixin (@a) when (iscolor(@a)) { color: @a; } .mixin (@a) when (ispixel(@a)) { width: @a; } body { .mixin(black); } div { .mixin(960px); } // Output body { color: #000000; } div { width: 960px; } Guards can be separated with a comma—if any of the guards evaluates to true, it’s considered a match: .mixin (@a) when (@a > 10), (@a < -10) { ... } Instead of a comma, we can use the and keyword so that all of the guards must match in order to trigger the mixin: .mixin (@a) when (isnumber(@a)) and (@a > 0) { ... } Finally, you can use the not keyword to negate conditions: .mixin (@b) when not (@b > 0) { ... } Think Math is Bad? Think Again. Are some elements in your stylesheet proportional to other elements? Operations let you add, subtract, divide, and multiply property values and colors, giving you the power to create complex relationships between properties. Rather than add more variables, you can perform operations on existing values with Less. You can build expressions with any number, color, or variable. @sidebarWidth: 400px; @sidebarColor: #FFCC00; #sidebar { color: @sidebarColor + #FFDD00; width: @sidebarWidth / 2; margin: @sidebarWidth / 2 * 0.05; } // Output #sidebar { color: #FFFF00; // color is brighter width: 200px; // width is reduced to 200px margin: 10px; // margin is set to 5% of the width } Parentheses can be used to control the order of evaluation. They are required in compound values: border: (@width * 2) solid black; Less also provides you with a couple of handy math functions. These are: round(1.67); // returns 2 ceil(2.4); // returns 3 floor(2.6); // returns 2 And, if you need to turn a value into a percentage, you can do so with the percentage function: percentage(0.5); // returns 50% Here I will show you a little secret trick: how to use the golden ratio in your design. You don’t need any calculator at all. Check this out: @baseWidth: 960px; @mainWidth: round(@baseWidth / 1.618); @sidebarWidth: round(@baseWidth * 0.382); #main { width: @mainWidth; } #sidebar { width: @sidebarWidth; } And the answer is: #main { width: 593px; } #sidebar { width: 367px; } Et voila! You have your layout divided properly with the golden ratio. Do you still think math is bad?! I don’t think so :) Color Alchemy Less provides a variety of functions that transform colors. Colors are first converted to the HSL color-space, and then manipulated at the channel level. All color operations take a color and a percentage as parameters, except spin, which uses integers between 0 and 255 instead of percentages to modify the hue, and mix, which takes two colors as parameters. Here is a quick reference for you: lighten(@color, 10%); // lightens color by percent and returns it darken(@color, 10%); // darkens color by percent and returns it saturate(@color, 10%); // saturates color by percent and returns it desaturate(@color, 10%); // desaturates color by percent and returns it fadein(@color, 10%); // makes color less transparent by percent and returns it fadeout(@color, 10%); // makes color more transparent by percent and returns it fade(@color, 50%); // returns a color with the alpha set to amount spin(@color, -10); // returns a color with amount degrees added to hue mix(@color1, @color2); // return a mix of @color1 and @color2 You can also extract color information from hue, saturation, lightness, and alpha channels: hue(@color); // returns the 'hue' channel of @color saturation(@color); // returns the 'saturation' channel of @color lightness(@color); // returns the 'lightness' channel of @color alpha(@color); // returns the 'alpha' channel of @color This is useful if you want to create a new color based on another color’s channel, for example: @new: hsl(hue(@old), 45%, 90%); If you’d like to explore color alchemy further, we’ve got a new guide on creating Less color schemes and palettes with more details! Do You Love Hierarchy? Yes, I Do. In CSS, we write out every ruleset separately, which often leads to long selectors that repeat parts over and over. Rather than constructing long selector names to specify inheritance, in Less you can simply nest selectors inside other selectors. This makes inheritance clear and stylesheets shorter: header {} header nav {} header nav ul {} header nav ul li {} header nav ul li a {} In Less you can write: header { nav { ul { li { a {} } } } } As you can see, this gives you clean, well-structured code, represented by a strong visual hierarchy. Now you don’t have to repeat selectors over and over ever again. Simply nest the relevant ruleset inside another to indicate the hierarchy. The resulting code will be more concise, and mimics the structure of your DOM tree. If you want to give pseudo-classes this nesting structure, you can do so with the & operator. The & operator represents the parent’s selector. It’s used when you want a nested selector to be concatenated to its parent selector, instead of acting as a descendent. For example, the following code: header { color: black; } header nav { font-size: 12px; } header .logo { width: 300px; } header .logo:hover { text-decoration: none; } Can be written this way: header { color: black; nav { font-size: 12px; } .logo { width: 300px; &:hover { text-decoration: none } } } Or this way: header { color: black; nav { font-size: 12px } .logo { width: 300px; &:hover { text-decoration: none } } } Name It, Use It, and Re-use It. Is It That Simple? What if you want to group mixins into separate bundles for later re-use, or for distributing? Less gives you the ability to do that by nesting mixins inside a ruleset with an ID, like #namespace. For example: #fonts { .serif (@weight: normal, @size: 14px, @lineHeight: 20px) { font-family: Georgia, "Times New Roman", serif; font-weight: @weight; font-size: @size; line-height: @lineHeight; } .sans-serif (@weight: normal, @size: 14px, @lineHeight: 20px) { font-family: Arial, Helvetica, sans-serif; font-weight: @weight; font-size: @size; line-height: @lineHeight; } .monospace (@weight: normal, @size: 14px, @lineHeight: 20px) { font-family: "Lucida Console", Monaco, monospace font-weight: @weight; font-size: @size; line-height: @lineHeight; } } Then, to call a mixin from that particular group, you do this: body { #fonts > .sans-serif; } And the output is: body { font-family: Arial, Helvetica, sans-serif; font-weight: normal; font-size: 14px; line-height: 20px; } Remember to add empty parentheses when you define mixins, which don’t take parameters. This way the initial definition isn’t included in the rendered CSS, only in the code where the mixin is being used. This both shortens your output code and allows you to keep a library of definitions that don’t add to the weight of the output until they are actually used. Some Special Cases String Interpolation String interpolation is a convenient way to insert the value of a variable right into a string literal. Variables can be embedded inside strings with the @{name} construct: @baseURL: ""; border-image: url("@{base-url}/images/border.png"); Escaping Sometimes you might need to output a CSS value that is either invalid CSS syntax, or uses proprietary syntax, which Less doesn’t recognize. If this is the case, just place the value inside a string prefixed with the ~ operator, for example: body { @size ~"20px/80px"; font: @size sans-serif; } This is called an “escaped value”, which will result in: body { font: 20px/80px sans-serif; } I’m Ready. Show Me the Magic, Please. The idea behind Less is to speed up and simplify only the development step. This means what goes live on your final website should be plain, old CSS, not Less. Fortunately, this can be done extremely easy. All you need to do is to get a Less compiler, and let it do its job. I recommend WinLess (for Windows) and LESS.app (for OS X) Here I will explain to you how to work with WinLess. First, download and install it. When you launch WinLess all you need to do is to drag a folder with .less files inside, and you are ready to go. To configure WinLess behavior, open File > Settings. I leave "Minify by default" unchecked because I want my file to be readable and minify my files only when I’m outputting for production. I check the other two options below because I don’t want to compile manually every single time I save a file, and because I want to know whether the compile is successful. By the way, for the training purpose you can use the WinLess Online Less Compiler—ideal if you want to quickly try out something. For working with LESS.app, you can check the video tutorial on its website’s home page. There is one more option for those of you who don’t use PC or Mac. You can get Crunch!, which is a cross-platform AIR application. Crunch is not only a Less compiler, but also a Less editor. This is cool, because Crunch is the only editor, to my knowledge, which gives you syntax highlighting for .less files. Try it to see what I mean. You know what? I’ll tell you my little secret. Actually, I’m using both of them—WinLess for compiling, and Crunch for editing. Sounds cool, huh? OK. I’m Really Fascinated. Where do I Find More? Here is a little bonus for you. This is a short list of Less resources, which can be used in your projects right away. There are some ready for use Less mixins and variables, plus a couple of projects which use Less as their base. - Official Less documentation—OK. This can’t be used in your projects :) However, you should check it regularly for any updates and new features added to the language. - Less Elements—a collection of useful Less mixins. - Preboot.less—another collection of Less mixins and variables. - Semantic Grid System—a simple and easy to use page layout tool. It supports Fixed, Fluid, and Responsive layouts. And, by the way, you can use it with Sass and Stylus too (if you still haven’t fallen in love with Less). - Centage—if you need full fluidity and flexibility, you should definitely check this. - perkins CSS3 Less Framework—a nice and rich Less framework, which uses HTML5 and CSS3. If you want to find even more resources about Less, GitHub is the right place to go. As you will see, there are plenty of Less goodies there. So, what are you waiting for? Go and check them out. A Few Final Words In brief, Less is a fast, easy, and modern way of writing and crafting CSS code. So don’t be too conservative, and just give it a try. Spend some time with Less and you’ll be creating and tweaking complex stylesheets faster and easier than ever before. Wish you happy coding, and always remember—Less is more :) And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Launch into Less. Comments on this article are closed. Have a question about Less? Why not ask it on our forums?
https://www.sitepoint.com/a-comprehensive-introduction-to-less-mixins/
CC-MAIN-2018-39
refinedweb
2,679
64.91
/******************************************************************************/ /* */ /* nhrp-dos - Copyright by Martin Kluge, <mk@elxsi.de> */ /* */ /* Feel free to modify this code as you like, as long as you include the */ /* above copyright statement. */ /* */ /* Please use this code only to check your OWN cisco routers. */ /* */ /* Cisco bug ID: CSCin95836 */ Let's look in code: "./src/modules/proxy/proxy_util.c" long int ap_proxy_send_fb(BUFF *f, request_rec *r, cache_req *c, off_t len, int nowrite, int chunked, size_t recv_buffer_size) { ... size_t buf_size; long remaining = 0; iPrint Client, which can be exploited by malicious people to compromise a user's system. 1) A boundary error in the Novell iPrint ActiveX control (ienipp.ocx) when handling the "GetDriverFile()" method can be exploited to cause a stack-based buffer overflow by passing an overly long string as the third argument. 2) Two boundary errors in the Novell iPrint ActiveX control (ienipp.ocx) when constructing a URI based on input to the "GetPrinterURLList()" and "GetPrinterURLList2()" methods can be use this payload # put retFix in our attack string attackString = fixRet print "\t[*] added fixRet function; attackString is " + str(len(attackString)) + " bytes long" # append enough NOPs to hit either the beginning of the payload or the location of ret if len(payload) <= afterRetSize + 4: # payload will not occupy any space before ret #include <linux/capability.h> #include <sys/utsname.h> #include <sys/mman.h> #include <unistd.h> typedef int __attribute__((regparm(3))) (* _commit_creds)(unsigned long cred); typedef unsigned long __attribute__((regparm(3))) (* _prepare_kernel_cred)(unsigned long cred); _commit_creds commit_creds; _prepare_kernel_cred prepare_kernel_cred; int getroot(void) POC: #include <windows.h> typedef BOOL (WINAPI *INIT_REG_ENGINE)(); typedef LONG (WINAPI *BREG_DELETE_KEY)(HKEY hKey, LPCSTR lpSubKey); typedef LONG (WINAPI *BREG_OPEN_KEY)(HKEY hKey, LPCSTR lpSubKey, PHKEY phkResult); typedef LONG (WINAPI *BREG_CLOSE_KEY)(HKEY hKey); typedef LONG (WINAPI *REG_SET_VALUE_EX)(HKEY hKey, LPCSTR lpValueName, DWORD Reserved, DWORD dwType, const BYTE* lpData, DWORD cbData); BREG_DELETE_KEY BRegDeleteKey = NULL; ... ... while(1) { /* added f:m:o: byMin */ opt = getopt_long(argc, argv, "vhrxtglpo:i:c:s:b:Q:na:f:m:46", long_options, NULL); if(opt == -1) break; switch(opt) { httpdx web server 1.4 is vulnerable to a remote buffer overflow using long GET requests such as... The vulnerability lies in httpdx_src/http.cpp in h_handlepeer() : strcpy(index,client->filereq); Other versions may also be vulnerable. Exploit (0day) (Tested with httpdx 1.4 on WinXP SP3) #include <stdio.h> #include <stdlib.h> Node Manager, which can be exploited by malicious people to compromise a vulnerable system. 1) Various boundary errors in the OpenView5.exe CGI application when processing parameters can be exploited to cause stack-based buffer overflows via HTTP requests to the CGI application with overly long parameter strings. 2) A boundary error in ov.dll can be exploited to cause a stack-based buffer overflow by e.g. sending a HTTP request to the OpenView5.exe CGI application with an overly long parameter string.];. $salt = wp_generate_password(); update_option('secret', $salt); } } // $salt is a seven char long password. $secret_key is null. return apply_filters('salt', $secret_key . $salt); } The wp_salt()'s value is stored here: Application: Soldat Versions: game <= 1.4.2 and dedicated server <= 2.6.2 Platforms: Windows (Linux not affected) Bugs: A] clients crash caused by too long strings on the screen B] denial of service through file transfer port C] easy IP banning Exploitation: remote A] versus clients B] versus server (Windows only) ############################################ Safari for windows Long link DoS Vendor URL: Advisore: Vendor notified:Yes exploit available: YES ############################################ Safari is prone vulnerable to Dos with a very long Link... This issue is exploitable via web links like <a href="very long URL"> click here</a> or similar vectors. Safari fails to render the link Manager, which can be exploited by malicious people to compromise a user's system. 1) A boundary error in the parsing of file names inside torrent files can be exploited to cause a heap-based buffer overflow via an overly long file name. 2) Two boundary errors when parsing names from torrent files can be exploited to cause stack-based buffer overflows via overly long file names.): Remarkably, we can access this interface anonymously via "ncacn_ip_tcp". The following is the IDL of the function of opnum 0x10A: /* opcode: 0x156, address: 0x28EB1C00 */ long sub_28EB1C00 ( [in] handle_t arg_1, [in][string] char * arg_2, [in][string] char * arg_3, [in][string] char * arg_4, [in][string] char * arg_5, user's system. 1) A boundary error in the EML reader (emlsr.dll) when parsing certain headers ("To:", "Cc:", "Bcc:", "From:", "Date:", "Subject:", "Priority:", "Importance:", and "X-MSMail-Priority:") in EML files can be exploited to cause a heap-based buffer overflow via an overly long string. 2) A boundary error in the EML reader (emlsr.dll) when encountering the beginning of RFC2047 encoded-words in headers can be exploited to cause a heap-based buffer overflow via an overly long string. interface is identified by 506b1890-14c8-11d1-bbc3-00805fa6962e v1.0. Opnum 0x10d specifies the vulnerable operation within this interface. Function 0x10d's IDL as follows: long sub_28EA5F70 ( [in] handle_t arg_1, [in, out][size_is(256), length_is(1)] struct struct_2 * arg_2, [in][string] char * arg_3, [in][string] char * arg_4, [in][string] char * arg_5,. Nearly all of LinuxRocket's features are free. Be kind and donate to the cause!
http://www.linuxrocket.net/term/long.htm
crawl-003
refinedweb
855
56.25
Re: [soaplite] Timeouts when using service descriptions Here was my solution -both the wsdl fetch, and the method needed timeouts.patmy $soap = SOAP::Lite ->proxy('http://', timeout => 1) ->service('') ;return (1, $errors{3} . "can not fetch wsdl", '') unless ($soap);...........$result = $soap ->proxy('http://', timeout => 2) ->fMETHOD_FROM_WSDL($data, $profileId, 1, 1, $partnerId, $userId, $transactionId, "");Thanks - I will try this. For some reason the examples using SOAP::Lite->service('...are disappearing as fast as I can find them... has it been deprecated? Am I losing the plot?----- Original Message -----From: Mark KnoopSent: Thursday, August 14, 2008 5:00 AMSubject: [soaplite] Timeouts when using service descriptions Hi I am making SOAP requests in the following way (have had to remove real urls so not runnable as is but hopefully it makes enough sense): ###### package MyService; use strict; use warnings; use Log::Log4perl qw(get_logger) ; use SOAP::Lite; our $service = undef; our $wsdl = '. server.net/ MyServiceDescrip tion?wsdl'; my $MAX_RETRIES = 5; sub service { my $log = get_logger(' MyService' ); unless (defined $service) { $log->debug ("Getting WSDL : $wsdl"); my $retries = 0; WSDL: while ($retries < $MAX_RETRIES) { eval { $log->debug ("Trying $wsdl"); $service = SOAP::Lite-> service($ wsdl); $log->debug ("Got service handle : $service"); }; if ($@) { $log->logwarn ($@); $retries ++; $log->info ("Retrying for the $retries time..."); next WSDL; } else { last WSDL; } } } return $service; } 1; ######### Then calling like this: my $result; eval { $result = MyService::service- >serviceMethod( @params ); }; die if $@; ########### This means I only have to have one service handle and that it will retry a few times before it bombs out. However I have a (very intermittent) situation where method calls hang indefinitely. Is the default to wait indefinitely when calling the method like this? If so is it possible to set a timeout and how? I have had a look at the docs but can only find examples with SOAP::Lite-> proxy ... - should I use this instead of SOAP::Lite-> service? Is there anything else I could be doing better? Any pointers much appreciated. Regards Mark
https://groups.yahoo.com/neo/groups/soaplite/conversations/topics/6190?o=1&source=1&var=1
CC-MAIN-2015-18
refinedweb
325
63.9
I wanted to take a look at the libusb library. But I cant even compile a single file including some functions of this library. This is what I did to install libusb: Code: Select all sudo apt-get install libusb-1.0-0 I even downloaded the latest version from and made the make installation. Code: Select all sudo apt-get install libusb-1.0-0-dev But if I use the compiler error is: Code: Select all #include <libusb.h> If I use this:If I use this:listdevs.c:24:27: fatal error: libusb/libusb.h: No such file or directory compilation terminated. the same error occurs. Code: Select all #include <libusb/libusb.h> or even I get Code: Select all #include </usr/include/libusb-1.0/libusb.h> // this is where the file really is on my Pi! listdevs.c:(.text+0x28): undefined reference to `libusb_get_device_descriptor' What did I do wrong?
https://www.raspberrypi.org/forums/viewtopic.php?p=365115
CC-MAIN-2020-16
refinedweb
154
62.34
Welcome to the first part of our Hello World tutorial! We will start by creating a Starcounter application in Visual Studio by going to New Project -> Templates -> Visual C# -> Starcounter -> Starcounter 2.3 Application. We will name the application HelloWorld. Create a new class called Person with the attribute [Database] in the Program.cs file. This attribute tag will make all instances of the class persistent. Add the properties FirstName and LastName to this class. Your code should now look like this: using Starcounter;namespace HelloWorld{[Database]public class Person{public string FirstName { get; set; }public string LastName { get; set; }}class Program{static void Main(){}}} Add a first instance to the class by defining a new person, its properties, and wrapping it in a Db.Transact(). Using a transaction allows us to access database objects and makes the changes inside the transaction atomic and isolated. class Program{static void Main(){Db.Transact(() =>{var person = Db.SQL<Person>("SELECT p FROM Person p").FirstOrDefault();if (person == null){new Person{FirstName = "John",LastName = "Doe"};}});}} The if statement here checks if you already have a Person in the database by accessing the first result that we get from the query. If that is the case, you do not need to create a new one. Without it, we would create a new instance of Person every time we run the program, which we do not intend to do. Remember to import System.Linq for FirstOrDefault. Start your program with Starcounter by clicking F5 in Visual Studio. To see for yourself, open the administrator at localhost:8181/#/databases/default/sql and enter SELECT * FROM HelloWorld.Person. This will display all the instances, represented as rows, of the Person class. Note that these instances are persistent. You can restart the application, or even the computer, and the instances will still be there. For the next step, we'll add a UI which will help us to display the data in the browser. If you get any errors, check your code against the source code.
https://docs.starcounter.io/hello-world-tutorial/create-a-database-class
CC-MAIN-2019-30
refinedweb
338
66.13
This is the mail archive of the libc-alpha@sources.redhat.com mailing list for the glibc project. > Since the aio implementation relies on pthreads, a build without > linuxthreads needs to skip the aio tests. It was wrong to put this change in, and I've taken it out now. Not all aio implementations will necessarily depend on pthreads. The proper fix is to have the tests exit without complaint when all the aio calls fail with ENOSYS as the stub versions will. I have put that change in. > > 2002-07-06 Bruno Haible <bruno@clisp.org> > > * rt/Makefile (tests): Don't add tst-aio* in a single-threaded build. > > diff -r -c3 glibc-20020627.bak/rt/Makefile glibc-20020627/rt/Makefile > --- glibc-20020627.bak/rt/Makefile Sat Oct 20 20:12:02 2001 > +++ glibc-20020627/rt/Makefile Fri Jul 5 01:17:06 2002 > @@ -38,8 +38,10 @@ > $(clock-routines) $(timer-routines) \ > $(shm-routines) > > -tests := tst-shm tst-clock tst-timer \ > - tst-aio tst-aio64 tst-aio2 tst-aio3 tst-aio4 tst-aio5 tst-aio6 > +tests := tst-shm tst-clock tst-timer > +ifeq ($(have-thread-library),yes) > +tests += tst-aio tst-aio64 tst-aio2 tst-aio3 tst-aio4 tst-aio5 tst-aio6 > +endif > > extra-libs := librt > extra-libs-others := $(extra-libs)
http://sourceware.org/ml/libc-alpha/2002-08/msg00279.html
CC-MAIN-2014-41
refinedweb
212
75.81
Def Leppard Theme 1.0 Sponsored Links Def Leppard Theme 1.0 Ranking & Summary RankingClick at the star to rank Ranking Level User Review: 0 (0 times) File size: 1.39MB Platform: Win98,NT License: Freeware Price: Free Downloads: 1095 Date added: 2006-10-24 Publisher: Def Leppard Theme 1.0 description Sounds and pointers of the Greatest Band on Earth. DEF Def Leppard Theme 1.0 Screenshot Advertisements Def Leppard Theme 1.0 Keywords DEF Greatest Band Def Leppard Theme 1.0 Def Leppard Theme Theme 1.0 Def Leppard Leppard theme pointers sounds greatest band Def Leppard Theme 1.0 Themes Home & Shell & Desktop Bookmark Def Leppard Theme 1.0 Def Leppard Theme 1.0 Copyright WareSeeker periodically updates pricing and software information of Def Leppard Theme 1.0 full version from the publisher, so some information may be slightly out-of-date. You should confirm all information before relying on it. Software piracy is theft, Using crack, password, serial numbers, registration codes, key generators is illegal and prevent future development of Def Leppard def leppard lyrics themes greatest bands of all time def leppard nine lives theme parks def leppard drummer greatest bands def leppard songs from the sparkle lounge def leppard tabs definitions soundscan def leppard pour some sugar on me greatest american hero greatest band of all time deftones Related Software Windows XP sweet blue theme ;). Free Download ForeverBlue XP Theme - Another cool XP Theme. Free Download QuickSilver XP Theme - Another Windows XP Theme :). Free Download "Gothic Fireplace" is an Animated Wallpaper of EleFun Multimedia company devoted to the fireplace theme. Somewhere in the Transylvania Mountains, in the old castle, life goes steadily and slowly. The. Free Download "Mountain Lake" is an Animated Desktop Wallpaper by EleFun Multimedia devoted to the nature theme, namely, to the mountains. Do you enjoy your desktop having beautiful wallpaper? Have a look at this l. Free Download "Mountain River" is an Animated Desktop Wallpaper by EleFun Multimedia devoted to the nature theme, namely, to the rivers. Somewhere far away, among the sky-high mountains, a small river starts its li. Free Download "Savannah Safari" is an Animated Desktop Wallpaper by EleFun Multimedia devoted to the nature theme. Do you enjoy your desktop having beautiful wallpaper? Just have a look at the Animated Desktop Wall. Free Download "Spring Lake" is an Animated Wallpaper by EleFun Multimedia devoted to the nature theme, namely, to the lakes. Do you enjoy your desktop having beautiful and animated wallpaper? Just take a look at th. Free Download "Savannah Camp" is an Animated Desktop Wallpaper by EleFun Multimedia devoted to the nature theme. Nature researchers have fixed a small camp somewhere on the reaches of the African savannah. And now,.
http://wareseeker.com/Home-Shell-Desktop/def-leppard-theme-1.0.zip/396655
crawl-002
refinedweb
455
58.08
Subject: Re: [boost] [container] static_vector: fixed capacity vector update From: Adam Wulkiewicz (adam.wulkiewicz_at_[hidden]) Date: 2013-02-01 09:35:56 Krzysztof Czainski wrote: > 2013/2/1 Adam Wulkiewicz <adam.wulkiewicz_at_[hidden]> > Furthermore I'd like to share some news. >> >> We've decided to slightly change the character of this container and >> highlight it's connection with array. Therefore we changed it's name >> to varray (variable-size array). The implementation with "Strategy" >> template parameter was moved to container_detail namespace. Exposed >> class takes 2 template parameters, exactly like boost::array does. >> >> boost::container::varray<T, N> va; ... > > > For the record, I'd rather the strategy was public. I can imagine using > static_vector in a few places in the same project with different strategies: > 1) In most places I'd probably use the default strategy. > 2) At the time of optimizations I might want to disable all checking > (asserts) only for one specific use. In practice we don't create separate > debug/release builds, since we need the debug version to be fast enough > anyway, and in some places this means disabling asserts. > 3) In some cases temporary cases I might want logic errors to be thrown, so > that the crash of an early version of one module doesn't crash the whole > system. > > Also, I prefer the name static_vector, but that's just my personal approach > - maybe I just got used to it ;-) After the release of 1.53 when everybody has more free time we should probably do some voting. > Although, now that I think of 0-arg emplace_back(), that doesn't > value-initialize types with a trivial constructor - does vector work like > this too? If not, then it's a good argument towards the name varray ;-) Yes, now elements' default ctors aren't called when they're of type with trivial ctor. This is the case when using: - varray(n) - resize(n) - emplace_back() This of course may be changed in the future or it may be tweakable with traits. Regards, Adam 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/2013/02/200656.php
CC-MAIN-2022-21
refinedweb
356
65.32
In order to create a read only application to be run from CD-ROM (or similar) in managed code, there are some issues that must be considered in order to support all current Microsoft Windows platforms (XP (if you can call that “current”) and Vista/Win7), and both x86 and AMD64 (x64) processor architectures. The user will need to have .NET Framework 2.0 installed, it will already be installed if the OS is Vista or later. For the SQL Compact runtime engine, simply include the SQL Compact managed and unmanaged DLL files in the application folder. Make sure to set the platform of your .exe to x86, or include both the x86 and AMD64 runtimes. Doing either of these 2 options will allow the SQL Compact engine to run on all Windows x86 and x64 platforms (XP/2003 and later). For the procedure for including the relevant runtime files in your project, see this blog post: and this sample from Steve Lasker: Running Compact from Read Only Media (DVD, CD, Locked USB Key). As reported here by the SQL Compact team (sadly, not before April 1st (!) 2009), the runtime needs to re-create indexes if a SDF file has been moved from Vista/Server 2008 to XP/Server 2003. On read-only media, this cannot happen, and you will get an obscure “Permission denied” error message. A possible workaround for this would be to open the file on both platforms (using Virtual PC or similar, if need be), and distribute 2 SDF files on the read only media. In order to open a SDF file form read-only media, you also need to add two additional parameters to the connection string in use: “Mode=Read Only” and “Temp Path=<path>” The sample code below illustrates how you could implement the 2 paragraphs above when creating your connection string. In addition, the path to the SDF file is dynamically created. using System; namespace ReadOnly { class Program { static void Main(string[] args) { string connStr; string sdfName; // Choose file based on OS version if (System.Environment.OSVersion.Version.Major < 6) { // This SDF was created on XP or Win2003 sdfName = "Northwind5.sdf"; } else { // This SDF was created on Vista or Win7 sdfName = "Northwind.sdf"; } // Notice the "Mode = Read Only" and "Temp Path=%TEMP%" options added to the connection string connStr = String.Format(@"Data Source = {0}\{1};Mode = Read Only;Temp Path={2}", System.IO.Path.GetDirectoryName(System.Reflection. Assembly.GetExecutingAssembly().GetName().CodeBase), sdfName, System.IO.Path.GetTempPath()); } } }
http://erikej.blogspot.ch/2009_08_01_archive.html
CC-MAIN-2018-22
refinedweb
414
61.67
I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code: from functools import partial if __name__ == '__main__': sequence = ['foo', 'bar', 'spam'] loop_one = lambda seq: [lambda: el for el in seq] no_op = lambda x: x loop_two = lambda seq: [partial(no_op, el) for el in seq] for func in (loop_one, loop_two): print [f() for f in func(sequence)] ['spam', 'spam', 'spam'] ['foo', 'bar', 'spam'] loop_one loop_two el lambda loop_one b = [] for foo in ("foo", "bar"): b.append(lambda: foo) print [a() for a in b] ['bar', 'bar'] foo a b = [] for a in ("foo", "bar"): b.append(lambda: a) print [a() for a in b] [<function <lambda> at 0x25cce60>, <function <lambda> at 0x25cced8>] The function lambda: el used in loop_one refers to a variable el which is not defined in the local scope. Therefore, Python looks for it next in the enclosing scope of the other lambda: lambda seq: [lambda: el for el in seq] in accordance with the so-called LEGB rule. By the time lambda: el is called, this enclosing lambda has (of course) already been called and the list comprehension has been evaluated. The el used in the list comprehension is a local variable in this enclosing lambda. Its value is the one returned when Python looks for the value of el in lambda: el. That value for el is the same for all the different lambda: el functions in the list comprehension: it is the last value assigned to el in the for el in seq loop. Thus, el is always 'spam', the last value in seq. You've already found one workaround, to use a closure such as your loop_two. Another way is to define el as a local variable with a default value: loop_one = lambda seq: [lambda el=el: el for el in seq]
https://codedump.io/share/6DYowzXKcq0x/1/weird-lambda-behaviour-in-loops
CC-MAIN-2017-17
refinedweb
309
71.68
If I have a gallery in a dynamic item page, does each column in the database link to one photo (so really it's not a gallery at all - just 4 images next to each others) or is there a more streamlined way to go about this? Hi hello, It depends on what you wanna do. If you know you are going to have exactly 4 photos for each item in your database, the way you describe is the simplest way to go. If you have a variable number of images per database item, you can use a second collection for images linked to the items of the first. Think about recipes collection and recipe images collection. Given a recipe has fields like _id, title and description, maybe even a main photo, we can, for recipe images collection just create the fields recipeId and photo. So now, for each recipe, we can grab the _id field value, and enter into the recipe photos collection one or more rows for this recipe, each with a single recipe photo. We build a dynamic page for recipes like any other dynamic item page. Once that is done, you add a gallery on the page, another dataset for recipe photos and connect it to the gallery. We are almost done at this point. We just need to set a filter on the second dataset so that it will only show the pictures of the recipe shown on the dynamic page. For this we need a little bit of javascript, that looks like the following Dear Yoav, Thanks for the help, nevertheles it did not worl out, I attached an image of the code I wrote in the dynamic item page where I inserted the Gallery. When I Preview it it gives me the following error: TypeError: $w(...).onReady is not a function Hay Santiago, The problem you see is a problem with element ids. Can you see the three strings marked in red in the code above? This is the IDE telling you that you are using the wrong ids. But don't worry, it is quite simple to fix this. The first id is for the dynamic dataset. Select it on the page and open the properties panel. At the top of the panel is the input for element id. This is the value you should enter instead of #datasetPlaces (with the # prefix). The second red indicator is the same. The third is the second dataset on the page, the one that is connected to the gallery. You should select that one as well, and then use the name from the properties panel. You can read more about ids and the properties panel here. Man, i so want to do that but images dont want to show in the gallery... i dont know what i do... please help i have a collection called Locations, and i created another collection called Albums (for the albums of each locations) How do i set it up?! The thing i did not understand was the part with the reciepes id's and linking the 2 database together with the code.. Thanks in advance Hi, You should use a Reference field in order to connect the databases - add a "location" reference for each album. This way you can then filter via coding or bind the gallery (using the connect button) to the relevant Albums. Thanks, it finally worked! Is there a way to have 2 different album on my dynamic item page? Example i have an album of the pictures i took or the location (the one we got to work) , and i need another album for historical picture. I did another dataset and another collection and did the same code behind the other one but it seems to interfer because now both albums are showing empty space, basically i think they are taking all the pictures i have in my photo collection. Hey Guillaume, Adding another album should not be a problem. It sounds like you're on the right track! Did you get it to work? J. Hi, No it did not work, i dont really know how to do it, i dont think the way i did it was the good way. The images show in both my album, they take is on each good collection, but there is no filter applied because now i see all the photo i have in my collections. Hi! I'm following this - I'm terribly stuck with this same situation Guillaume has....please help? I've created a dynamic page with a wix pro gallery - I want each gallery image/item to link to a separate item page that contains it's own gallery (with detail/more images) of this one item selected. Hey Guillaume, A few things you should make sure you've done: Make sure you have one dataset for your historic pictures and one for the picture you took Make sure each gallery is connected to it's own dataset. If two galleries are connected to the same dataset, they'll display the same information. It sounds like you might be overwriting the filters. Double check the names in your code snippets for typos. By what you described, it should work. Could you add a bit more details or code snippets of what you've done, what you expect to happen and what happened? J. Hi There everyone, I have a problem understanding how to setup the second database with rows for each image I want to display them in an item page gallery - (" So now, for each recipe, we can grab the _id field value, and enter into the recipe photos collection one or more rows for this recipe, each with a single recipe photo.) I can not seem to change the _id field value to match that of the image for each row I've created. Should I 1. Create a new column with a text field value and add the _id in there? or 2. only keep the title and image as is and add a reference field column as Ohad explained above? I dont want to delete more data at this point and trying to keep with only the Title field and image as you've explained above. Thanks in advance*** Hey Jonathan, i finally got it to work! Thanks a lot. 3 collections and 3 dataset, here is the code if someone need it. $w.onReady(function () { }); import wixData from 'wix-data'; $w.onReady(() => { $w('#dynamicDataset').onReady(() => { var locationId = $w("#dynamicDataset").getCurrentItem()._id; $w('#Albumdataset').setFilter( wixData.filter() .eq('locationId', locationId)); }); }); $w.onReady(() => { $w('#dynamicDataset').onReady(() => { var locId = $w("#dynamicDataset").getCurrentItem()._id; $w('#HistoryDataset').setFilter( wixData.filter() .eq('locId', locId)); }); }); dynamicDataset : main dataset of my dynamic item page connected to my main collection locationId : reference field in the second collection connected to the location (example house no1) in the first collection Albumdataset : second dataset connected to the second collection where pictures for the first album is locId : reference field in the third collection connected to the same location (house no1) in the first collection, for the second album HistoryDataset : Third dataset connected to my third collection where are the images for my second album hope i didnt got something wrong, im french so it does not help lol I want to help other newbe like me haha Ser what is the Var recipeid? How to show the image in my database? Using ID This is my dynamic page and my database, now I want to show my image using ID but how? Can you tell me what my mistake? God bless hi Louise did you ever got a solution for your Problem? Gallery in a dinamic item page? I'm stuck her since days and got lost in all above tips, id's and databases names. greets Andi I did exactly as Yoav mentioned about and i connected a gallery to a different database which is also connected to my main database through a Reference id. when i preview my site the gallery shows for a short period and disappears what could be the reason. i get the message Loading the code for the Projects (Title) page. To debug this code, open jz7o9.js in Developer Tools. Solved The way you would have to set up your database for this is really inefficient. Basically you need to put the reference field once for EVERY single image. Like this: Carbonara pic1 Carbonara pic2 Carbonara pic3 Carbonara pic4 Carbonara pic5 Carbonara pic6 So if you have 20 recipes with 10 pictures each, you'll be looking at 200 rows. Instead of having 20 rows with 1+10 columns. Is there a way to make it get the entire ROW and not just the first column? @Yoav (Wix) Change the field type to "media gallery" that way each item can have its own gallery of images, not restricted or even needing code to link to an item page
https://www.wix.com/corvid/forum/community-discussion/adding-a-photo-gallery-in-a-dynamic-page
CC-MAIN-2019-51
refinedweb
1,495
69.82
Form Panel is nothing more than a basic Panel with form handling abilities added. Form Panels can be used throughout an Ext application wherever there is a need to collect data from the user. In addition, Form Panels can use any Container Layout, providing a convenient and flexible way to handle the positioning of their fields. Form Panels can also be bound to a Model, making it easy to load data from and submit data back to the server. Under the hood a Form Panel wraps a Basic Form which handles all of its input field management, validation, submission, and form loading services. This means that many of the config options of a Basic Form can be used directly on a Form Panel. To start off, here's how to create a simple Form that collects user data: This Form renders itself to the document body and has three Fields - "First Name", "Last Name", and "Date of Birth". Fields are added to the Form Panel using the items configuration. The fieldLabel configuration defines what text will appear in the label next to the field, and the name configuration becomes the name attribute of the underlying HTML field. Notice how this Form Panel has a defaultType of 'textfield'. This means that any of its items that do not have an xtype specified (the "First Name" and "Last Name" fields in this example), are Text Fields. The "Date of Birth" field, on the other hand, has its xtype explicitly configured as 'datefield', which makes it a Date Field. Date Fields expect to only contain valid date data and come with a DatePicker for selecting a date. Ext JS provides a set of standard Field types out of the box. Any of the Fields in the Ext.form.field namespace can be used in a Form Panel. For more information see the API documentaion for each Field type: Ext JS has built in support for validation on any type of Field, and some Fields have built in validation rules. For example, if a value is entered into a Date Field and that value cannot be converted into a Date, the Field will have the x-form-invalid-field CSS class added to its HTML element. If necessary, this CSS class can be changed using the invalidCls configuration. Adding the invalidCls adds a red border to the input field (as well as a red "invalid underline" decoration when using the Classic theme): A Field containing invalid data will also display an error message. By default this message displays as a tool tip: It's easy to change the location of a Field's error message using the msgTarget configuration, and the invalidText configuration changes the error message. Each Field provides its own implementation of invalidText, and many support token replacement in the error message. For example, in a Date Field's invalidText, any occurrences of "{0}" will be replaced with the Field's value, and any occurrences of "{1}" will be replaced with the required date format. The following code demonstrates placing the error message directly under the Field, and customizing the error message text: { xtype: 'datefield', fieldLabel: 'Date of Birth', name: 'birthDate', msgTarget: 'under', // location of the error message invalidText: '"{0}" bad. "{1}" good.' // custom error message text } Some validation requirements cannot be met using the built-in validations. The simplest way to implement a custom validation is to use the Text Field's regex configuration to apply validation rules and the maskRe configuration to limit which characters can be typed into the field. Here's an example of a Text Field that validates a time. { xtype: 'textfield', fieldLabel: 'Last Login Time', name: 'loginTime', regex: /^([1-9]|1[0-9]):([0-5][0-9])(\s[a|p]m)$/i, maskRe: /[\d\s:amp]/i, invalidText: 'Not a valid time. Must be in the format "12:34 PM".' } While the above method works well for validating a single field, it is not practical for an application that has many fields that share the same custom validation. The Ext.form.field.VTypes class provides a solution for creating reusable custom validations. Here's how a custom "time" validator can be created: // custom Vtype for vtype:'time' var timeTest = /^([1-9]|1[0-9]):([0-5][0-9])(\s[a|p]m)$/i; Ext.apply(Ext.form.field.VTypes, { // vtype validation function time: function(val, field) { return timeTest.test(val); }, // vtype Text property: The error text to display when the validation function returns false timeText: 'Not a valid time. Must be in the format "12:34 PM".', // vtype Mask property: The keystroke filter mask timeMask: /[\d\s:amp]/i }); Once a custom validator has been created it can be used on Text Fields throughout an application using the vtype configuration: { fieldLabel: 'Last Login Time', name: 'loginTime', vtype: 'time' } See Validation Example for a working demo. For more information on custom validations, please refer to the API Documentation for VTypes. The simplest way to submit data to the server is to use the url configuration of Basic Form. Since Form Panel wraps a Basic Form, we can use any of Basic Form's configuration options directly on a Form Panel: Ext.create('Ext.form.Panel', { ... url: 'add_user', items: [ ... ] }); The Form's submit method can be used to submit data to the configured url: Ext.create('Ext.form.Panel', { ... url: 'add_user', items: [ ... ], buttons: [ { text: 'Submit', handler: function() { var form = this.up('form'); // get the form panel if (form.isValid()) { // make sure the form contains valid data before submitting form.submit({ success: function(form, action) { Ext.Msg.alert('Success', action.result.msg); }, failure: function(form, action) { Ext.Msg.alert('Failed', action.result.msg); } }); } else { // display error alert if the data is invalid Ext.Msg.alert('Invalid Data', 'Please correct form errors.') } } } ] }); In the above example, a button is configured with a handler that handles form submission. The handler takes the following actions: submitmethod is called, and two callback functions are passed - successand failure. Within these callback functions, action.resultrefers to the parsed JSON response. The above example expects a JSON response that looks something like this: { "success": true, "msg": "User added successfully" } The Model class is used throughout Ext JS for representing various types of data as well as retrieving and updating data on the server. A Model representing a User would define the fields a User has as well as a proxy for loading and saving data: Ext.define('MyApp.model.User', { extend: 'Ext.data.Model', fields: ['firstName', 'lastName', 'birthDate'], proxy: { type: 'ajax', api: { read: 'data/get_user', update: 'data/update_user' }, reader: { type: 'json', root: 'users' } } }); Data can be loaded into a Form Panel directly from a Model using the loadRecord method: MyApp.model.User.load(1, { // load user with ID of "1" success: function(user) { userForm.loadRecord(user); // when user is loaded successfully, load the data into the form } }); Finally, instead of using the submit method to save the data, Form Panel's updateRecord method is used to update the record with the form data, and the Model's save method is called to save the data to the server: Ext.create('Ext.form.Panel', { ... url: 'add_user', items: [ ... ], buttons: [ { text: 'Submit', handler: function() { var form = this.up('form'), // get the form panel record = form.getRecord(); // get the underlying model instance if (form.isValid()) { // make sure the form contains valid data before submitting form.updateRecord(record); // update the record with the form data record.save({ // save the record to the server success: function(user) { Ext.Msg.alert('Success', 'User saved successfully.') }, failure: function(user) { Ext.Msg.alert('Failure', 'Failed to save user.') } }); } else { // display error alert if the data is invalid Ext.Msg.alert('Invalid Data', 'Please correct form errors.') } } } ] }); Layouts are used to handle sizing and positioning of components in an Ext JS application. Form Panels can use any Container Layout. For more information on Layouts please refer to the Layouts and Containers Guide. For example, positioning Fields in a form horizontally can easily be done using an HBox Layout:
https://docs.sencha.com/extjs/5.0.0/guides/components/forms.html
CC-MAIN-2018-30
refinedweb
1,332
55.24
Adding external libs and build directories Dear, I'm trying to add an external lib and the readme of that project sais the following: @To use jrtplib and jthread in another project, you must then do the following: - in the project settings, add the include directory c:\local\include to the list of include directories (for debug and release builds) - in the project settings, add c:\local\lib to the list of library directories. - for the release version, add jrtplib.lib, jthread.lib and ws2_32.lib to the list of libraries - for the debug version, add jrtplib_d.lib, jthread_d.lib and ws2_32.lib to the list of libraries. In your program files, include a jrtplib header like this: #include <jrtplib3/rtpsession.h> and a jthread header like this: #include <jthread/jthread.h>@ So I thought adding this to my .pro file would do it: @INCLUDEPATH += "C:\local\include" LIBS += -L/c:\local\lib -lpsapi @ but the includes like he sais are not known. Can someone help me? Kind regards, - sierdzio Moderators To add the README, you need to specify it by name in OTHER_FILES variable of your .pro file. It will show up in Qt Creator then. @ OTHER_FILES += path/to/myReadme.txt @ As for includes, you don't need to escape the quotes. You don't, in fact, need to use them. Also, if the library is part of your project, it's probably better to rely on relative paths.
https://forum.qt.io/topic/22339/adding-external-libs-and-build-directories
CC-MAIN-2017-34
refinedweb
240
74.79
Mic wrote: >>I chose to ignore the "using classes" part. If you like you can turn the >>button_clicked() function into a method of a subclass of Button. You can >>also move the Button configuration done in create_widgets() into the >>__init__() method of that subclass. > > import tkinter as tk > from functools import partial > > def button_clicked(button): > if button["bg"] == "green": > button.configure(bg="red", text="Hi 2") > else: > button.configure(bg="green", text="Hi 1") > > class Window(tk.Frame): > def __init__(self, master): > super (Window, self).__init__(master) > self.grid() > self.create_widgets() > > def create_widgets(self): > for _ in range(2): > button = tk.Button(self) > command = partial(button_clicked, button) > button["command"] = command > button.grid() > command() > > root = tk.Tk() > root.title("Test") > root.geometry("200x200") > app = Window(root) > root.mainloop() > A very elegant solution. Much better than my previous one. However, I am a > bit unfamiliar with your way of > coding, I assume you are used to a version other than Python 3.2? Yes, though I don't think the difference between 2.x and 3.x matters here. > Because, never before have I seen either of those Most tkinter tutorials seem to use from tkinter import * which I don't like because it doesn't make explict which names are put into the current module's namespace. The alternative import tkinter leads to long qualified names. > import tkinter as tk is a popular compromise. > from functools import partial I use this kind of explicit import for a few names that I use frequently, namely defaultdict, contextmanager, everything from itertools... I think of these as my personal extended set of builtins ;) As to the actual partial() function, you probably don't see it a lot because it has been in the standard library for only three years. The older idiom for making a function that calls another function with a fixed argument is command = lambda button=button: button_clicked(button) > I also wonder, if I implement your solution, is there anyway I can place > the buttons in the program as I would like, or will they be played in a > straight, vertical row > always? You can iterate over (row, column) pairs instead of the dummy _ variable: def create_widgets(self): for row, column in [(0, 0), (1, 1), (2, 2), (3, 0)]: button = tk.Button(self) command = partial(button_clicked, button) button["command"] = command button.grid(row=row, column=column) command() > Also, assume that I have a already have a window with a button in it. If > you press this button, this window is supposed to open. > So, if I press the button, will this window open? Because I created the > previous window using > from tkinter import* and not import tkinter as tk. You can make the decision what style you want to use on a per-module basis. In that module you can then access (for example) a tkinter button with either tkinter.Button, tk.Button or just Button. You can even mix styles if you put the respective imports at the beginning of the module (not recommended). What approach you take has no consequences on the execution of the program. > I hope my English is understandable, because it is not my primary > language. Thanks for your help, it is greatly appreciated! Many posters aren't native speakers, so you can never be sure that what you pick up here is actually English ;) I didn't have any problems with your command of the language, but I'm not a native speaker either.
https://mail.python.org/pipermail/tutor/2011-November/086966.html
CC-MAIN-2016-40
refinedweb
580
57.06
.topNCopy Copies the top n elements of the input range source into the random-access range target, where n = target. TRange topNCopy(alias less, SRange, TRange) ( SRange source, TRange target, SortOutput sorted = No .sortOutput.sortOutput ) if (isInputRange!SRange && isRandomAccessRange!TRange && hasLength!TRange && hasSlicing!TRange); Elements of source are not touched. If sorted is true, the target is sorted. Otherwise, the target respects the heap property. Parameters Returns The slice of target containing the copied elements. Example import std .typecons : Yes; int[] a = [ 10, 16, 2, 3, 1, 5, 0 ]; int[] b = new int[3]; topNCopy(a, b, Yes.typecons : Yes; int[] a = [ 10, 16, 2, 3, 1, 5, 0 ]; int[] b = new int[3]; topNCopy(a, b, Yes .sortOutput); writeln(b); // [0, 1, 2].sortOutput); writeln(b); // [0, 1, 2] Authors License Copyright © 1999-2022 by the D Language Foundation | Page generated by ddox.
https://dlang.org/library/std/algorithm/sorting/top_n_copy.html
CC-MAIN-2022-27
refinedweb
144
60.61
Today’s post is dedicated to a library based on reactive functional programming: ScalaRx. The main objective of this library is that, with the use of values (val), we are going to define an operations flow, which will change dynamically when any of the values changes. We call those values reactive variables. To use the library, it is enough to add it as a dependency: libraryDependencies += "com.lihaoyi" %%% "scalarx" % "0.3.0" and to import rx: import rx._ Reactive variables Reactive variables will be the main elements we will be able to work with. To define them, the constructor Var will be used: val reactiveVar = Var(0) This way, we are defining a reactive value containing a 0. As can be observed, we can use val instead of var, even though the value will change. This is so because the state of the reactive variable is handled with ScalaRx. Once we have a reactive variable, we can combine it with other static values or other reactive variables. So that our mastery and expertise can be noticed, we’ll perform a complex operation. We’ll be doing the sum of two reactive variables. val sum1 = Var(1) val sum2 = Var(4) val result = Rx{ sum1() + sum2() } result.now // Returns 5 In order to make reference to the use of the value of the variable in a reactive way, parenthesis are used. Furthermore, given that we want that the value of result changes as a function of the reactive values sum1 and sum2, we enclose it within an Rx block. If we want to evaluate result just after its definition, we’ll be able to do so with the now method. We will obviously be getting a wonderful 5. Everything looks pretty simple right now. Let’s try to see how reactive changes do work. To do so, let’s change the value of the first summand. For that purpose, we will use again the parenthesis to make reference to the fact that we are changing the value contained in the reactive variable. sum1() = 2 This update of the first summand will cause a reactive change that will affect the whole flow defined. In this case, it will only affect the result value. result.now // Returns 6 This has been an extremely simple example. However, more complex flows could be created so that, when the value of a reactive variable is updated and following a ripple effect, a reaction is triggered at the rest of elements. You may now be thinking “I already do this by replacing the reactive variables by our var friends and done”. Well, that’s true. However, Rx is intended to get notifications of the changes in the reactive variables and be able to respond to them (here you will find a more complete explanation). Observables are used for this purpose. We’ll have to wait to the second part of the post to get to them. See you soon! One thought on “A small tour through ScalaRx (Part I)” […] the previous post we saw how reactive variables work. We learned how to declare them, modify them and create Rx […] Me gustaMe gusta
https://scalerablog.wordpress.com/2016/02/22/a-small-tour-through-scalarx-part-i/
CC-MAIN-2018-05
refinedweb
526
73.17
Create div php işler. ...</track> <track kind="subtitles" label="Türkçe" src="[login to view URL]" srclang="tr"></track> </video> Sayfamda da şu şekilde 2 tane kutucuk var; Kod: <div id="en"></div> <div id="tr"></div> Şimdi istediğim şey vide... Bir aspx sayfasının div, table ve panellerle tasarımın iyileştirilmesi ...uygun database ...sayfa şeklinde gidecek peyder pey yüklenecek. - Sayfaya gitme bölümüne bir de sayfayı işaretle diye bir bölüm eklenecek. Basitçe bulunduğun sayfayı javascript ile alıp php dosyasına post etmen yeterli. Sayfanın işaretlendiğine dair bir geri dönüş çıkar ve kaybolur. - [login to view URL] adresinde sol tarafta olduğu gibi URL] HTML Example Code: [wpbb-if post:featured_image] <div class="fl-post-image"> [wpbb post:featured_image <h2 class="fl-post-title">[wpbb post:link text="title"]</h2&... .. [login to view URL], [login to view URL], [login to view URL] date etc. displayed inline ...them better for this. At the bottom, please embed my calendly link: <!-- Calendly inline widget begin --> <div class="calendly-inline-widget" data-</div> <script type="text/javascript" src="[login to view URL]"></script> <!-- %}{{ [login to view URL]|raw }}{% endif %}</div> Build an array with the aforementioned [1] urls [2] alt tags and [3] image... ...object has no attribute 'logo' Error to render compiling AST AttributeError: 'NoneType' object has no attribute 'logo' Template: [login to view URL] Path: /templates/t/t/div/header/nav/div/a/span Node: <span t-field="[login to view URL]" t-options="{'widget': 'image'}" role="img" t-attf-src="d... .. ...And I want you to fix my ...I am trying to achieve: <div id="column1" class="columns"> <div id="5" class="dragbox"> </div> <div id="3" class="dragbox"> </div> <div id="1" class="dragbox"> </div> </div> <div .... Hi its a very easy for Magento expertise. Ok what we are looking ...[login to view!! I need a new website. I need you to design my personal website like [login to view URL] only home page and one inside page like [login to view URL] website. I need you to design my personal website like [login to view URL] only home page and one inside page like [login to view URL] and adds you need to do a div like adds with img .. app made by you) just to see your skill, then only apply for looking to hire php and wordpress developer to hire for 2 small project also i will hire them for future project ...jquery. I need your help with upload the attachment to add the div block that allow me to send the email with attachment. When I click on add attachment and select the file, nothing will happens. I want you to work on it to allow me to upload the attachment using ajax call to add the div block with the file name like the gmail one then send a test email ...the attachment to add the div block that allow me to send the email with attachment and the second thing is change the HTML using document.execCommand. I have got a problem with change the HTML to update the link and email address using inserthtml but it wont update it as it will keep adding the url and email address in the div textbox. I want you to work. I need to capture elements (div blocks) and save it on the visitor device as a jpeg form. There is 10 different div blocks I want to capture with 10 different text links to capture them. *I want it the best quality image* Need a small module to download records from one MySql table with 300 columns and 70000 rows to an excel sheet. On successful completions with award further modules. ... <div class="col-md-3 col-sm-6 label">Code</div> <div class="col-md-9 col-sm-6">input</div> </field-inp> into the following <div [ngClass]="{ ... Our company seeks coding services: 1- To finalize and implement some snippet mainly on the checkout and my account page in order to display inline error messages. We have used some snippet to enable that function, however it does not work on my account page yet. 2- Remove error messages displayed on the top of any form/page (errors only -red frame-, not notification -green frame-). Furthermore,... I want a script similar like bed365 for a cricket. Need a live cricket score with any paid or free API integrated a...script similar like bed365 for a cricket. Need a live cricket score with any paid or free API integrated and also can bet on it. Any ready-made script is preferable. Need on PHP and mysql. Please apply who can make it on 4 to 5 days. Hello, I need a solution to POST data in a HTML script (so its client side), WITHOUT a <form></form> tag, to my server-side PHP script. So, a small demo how it should NOT!!!! look like: <form id="loginForm" method="post" accept- <input type="text" name="field1" id=... Need a php (Laravel) expert for few modifications in a already written script. Details about scope of work are provided in pdf file attached. Full files of script : [login to view URL] . URL to script: [login to view URL] We have already You need to develop a Wordpress plugin that does nothing more than displaying one form field after the other. So after selecting either an option or entering a text and h...more than displaying one form field after the other. So after selecting either an option or entering a text and hit the "next" button, the next step should show up in the same div.
https://www.tr.freelancer.com/job-search/create-div-php/
CC-MAIN-2019-26
refinedweb
931
72.46
19 January 2012 06:20 [Source: ICIS news] By Helen Yan SINGAPORE (ICIS)--Major tyre makers in Asia, stricken with weak exports sales, are putting up a strong resistance to a $300-500/tonne (€234-390/tonne) hike in butadiene rubber prices this week for February and March shipments, industry sources said on Thursday. BR producers are offering $3,600-3,800/tonne CFR (cost and freight) ?xml:namespace> “We are not happy with this situation because when the feedstock BD price fell to around $1,500/tonne last November, the BR producers did not adjust their prices downwards,” said an India-based tyre maker. “Buying sentiment is weak and we will not accept a big price hike for February and March shipments,” he added. BD prices were assessed at $3,050-3,100/tonne CFR northeast BD is the raw material for the production of BR, which in turn, is used in the manufacture of tyres for automobiles. But Asian tyre makers are coping with poor export sales amid a weakening global market condition, affecting Asia is a major tyre production centre, with a good portion of the output being exported to In the EU, new registrations for passenger cars fell by 1.7% in 2011, despite an increase recorded in “In 2011, most of the significant markets declined, from -2.1% in “ Slowing global vehicle sales have prompted tyre makers to adopt a prudent stance. “The first quarter [export sales] is expected to be slow and flat with the ongoing eurozone debt crisis and concerns over a global slowdown. We are very cautious and will not build up our inventories and will not accept a big BR price hike in the first quarter,” said a second tyre producer. In BR producers, on the other hand, are also contending with losses caused by the unabated increase in BD values. “The feedstock BD and BR prices are at about the same price levels. We are losing money and have negative margins as the feedstock BD costs have wiped out all our margins,” said a northeast Asian BR producer. BR prices were assessed at $3,250-3,400/tonne CFR NE Asia in the week ended 12 January, ICIS data showed. BR must at least be priced $600-700/tonne higher than BD for BR producers to generate margins. Some BR producers in “We cannot operate a losing business, so we plan to cut the operating rates of our BR plant to 70% of capacity in February,” said a company source at a Taiwanese BR plant . BR producers
http://www.icis.com/Articles/2012/01/19/9525145/asia-tyre-makers-resist-br-price-hikes-for-february-march.html
CC-MAIN-2014-42
refinedweb
427
54.46