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 |
|---|---|---|---|---|---|
Modular Java: Declarative Modularity
- |
-
-
-
-
-
-
-
Read later
My Reading List
In the fourth of the Modular Java series, we'll cover declarative modularity. We'll describe how we can define components and then hook them up together, without having a programmatic dependency on the OSGi APIs.
The previous instalment, Modular Java: Dynamic Modularity, described how to bring dynamic modularity to an application through the use of services. These are implementations that export one (or more) interfaces that can be discovered dynamically at runtime. Whilst this allows for full de-coupling between client and server, it leads to a question of how (and when) the services start up.
Start ordering
In a fully dynamic system, services can not only come and go as a system runs, they can also start in different orders. Sometimes, this isn't a big problem; regardless of the start ordering between A and B, if no events (or threads) actually occur until the system is in a steady state and is ready to accept events, then it shouldn't matter which service gets started first.
However, there's a number of ways that this simple assumption can be violated. The canonical example is of logging; typically, services will connect to and start writing to a log service during start-up and other operations. If a log service is not available, what happens?
Given that services can dynamically come and go at runtime, clients should be able to cope when the service isn't present. In that case, it might be wise to fallback to another mechanism (like printing output to stdout) or blocking to wait for a service to become available (unlikely to be the right answer for logging systems). However, ensuring that there is a service available before starting would be the ideal solution.
Start levels
OSGi provides a mechanism to control the ordering of bundles at start-up, through the use of start levels. These are based on the concept of UNIX run levels; the system starts at level one, and then monotonically increments until it hits the target start level. Each OSGi container provides a different default target start level; for Equinox, the default is 6, whilst for Felix it is 1.
Start levels can therefore be used to create an ordering between bundles, by putting key bundle services (like logging) into a lower start level than those that require it. However, because there are only a finite number of start levels available, and that installers tend to choose single-digit numbers for start levels, it isn't a strong guarantee that you'll fix problems through start order alone.
The other point worth observing is that bundles in the same start level are started independently (and potentially concurrently), so if you have a bundle which has the same start level as a log service, then there's no guarantees that it will wire up when expected. In other words, start levels are good for solving large problems but not necessarily for all problems.
Declarative services
One solution to this problem is OSGi's declarative services, hereafter referred to as DS. In this approach, components are wired together by an external bundle as and when they become available. Declarative services are wired together as defined in an individual XML configuration file, which declares what services are required (consumed) and provided.
In our last example, we used a
ServiceTracker to acquire, and if necessary, wait for a service to become available. It would be much more useful if we delay creating the
shorten command until the shortening service was available.
DS defines the concept of a
component which is at a finer granularity than a bundle, but a larger granularity than a service (since a component may consume/provide multiple services). Each component has a name, corresponds to a Java class, and may be activated or deactivated by calls to that class' methods. Unlike OSGi Java APIs, DS allows for the component to be developed as a pure Java POJO with no programmatic dependencies on OSGi at all. This has the fringe benefit of also making DS easy to test/mock.
In order to demonstrate the approach, we'll be using our example previously. We'll need two components; one of them will be the shortening service itself, and the other will be the
ShortenComand that invokes it.
The first task is to configure and register the shorten service with DS. Instead of registering the service via the
Bundle-Activator, we can ask DS to register it upon component startup.
So how does DS know to activate or wire this up? Well, we add an entry to the Bundle's Manifest header, which in turn points to one (or more) XML component definition files.
Bundle-ManifestVersion: 2 ... Service-Component: OSGI-INF/shorten-tinyurl.xml [, ...]*
The
OSGI-INF/shorten-tinyurl.xml component definition looks like:
<?xml version="1.0" encoding="UTF-8"?> <scr:component <implementation class="com.infoq.shorten.tinyurl.TinyURL"/> <service> <provide interface="com.infoq.shorten.IShorten"/> </service> </scr:component>
When DS processes this component, it has roughly the same effect as doing
context.registerService( com.infoq.shorten.IShorten.class.getName(), new com.infoq.shorten.tinyurl.TinyURL(), null );. A similar declaration will be needed for the
Trim() service, and is included in the source code below.
A single component can provide multiple services under different interfaces if needed. A bundle may also include multiple components, using the same or distinct classes, each of which provides distinct services.
Consuming the service
To consume the service, we need to modify the
ShortenCommand so that it binds to an instance of the
IShorten service:
package com.infoq.shorten.command; import java.io.IOException; import com.infoq.shorten.IShorten; public class ShortenCommand { private IShorten shorten; protected String shorten(String url) throws IllegalArgumentException, IOException { return shorten.shorten(url); } public synchronized void setShorten(IShorten shorten) { this.shorten = shorten; } public synchronized void unsetShorten(IShorten shorten) { if(this.shorten == shorten) this.shorten = null; } } class EquinoxShortenCommand extends ShortenCommand {...} class FelixShortenCommand extends ShortenCommand {...}
Note that unlike last time, this has no dependencies on the OSGi APIs; and it would be trivial to mock an implementation to verify that it worked correctly. The
synchronized modifier ensures that there's no race conditions when the service gets set.
To tell DS that we need an instance of the
IShorten service bound to our
EquinoxShortenCommand component, we need to define what services it requires. When DS instantiates your component (with the default constructor), it will wire up the
IShorten service by invoking the method defined in the
bind attribute; in other words,
setShorten().
<?xml version="1.0" encoding="UTF-8"?> <scr:component <implementation class="com.infoq.shorten.command.EquinoxShortenCommand"/> <reference interface="com.infoq.shorten.IShorten" bind="setShorten" unbind="unsetShorten" policy="dynamic"
cardinality="1..1" /> <service>
<provide interface="org.eclipse.osgi.framework.console.CommandProvider"/>
</service> </scr:component>
As soon as the
IShorten service is available, this component will be instantiated and wired to the service, regardless of the start ordering between this and the other bundles. The explaination of the policy, cardinality and service provide are covered in the next section.
Policies and cardinality
The policy can be either
static or
dynamic. A
static policy will mean that once set, a service doesn't get changed. If the service goes away, the component is deactivated; and if a new service arrives, then a new instance is created and the service re-bound. This is obviously heavier weight than if we can update the service in place.
With the
dynamic policy, when the
IShorten service is changed, DS will invoke the
setShorten() with the new service, and subsequently
unsetShorten() with the old one.
The reason that DS calls the
set before the
unset is to maintain continuity of the service. If a call came in as the service was being replaced, and the
unset was called first, there would be a chance that the
shorten service could be
null transiently. It's also why the
unset method takes an argument, rather than just setting the service to
null.
The cardinality of the service, which defaults to
1..1, is one of:
- 0..1 Optional, maximum of one
- 1..1 Mandatory, maximum of one
- 0..n Optional, many
- 1..n Mandatory, many
If the cardinality can't be satisfied (for example, it is mandatory there is no shortening service), then the component is deactivated. If many services are required, then the
setShorten() will be called once for each service. Conversely, the
unsetShorten() will be called for each service that goes away.
Not shown here is the ability for the component to do per-instance customisation when it's brought on-line.
In DS 1.1, the
componentelement can also have an
activateand
deactivateattribute, corresponding to the method which is invoked upon component activation (starting) and deactivation (stopping).
Lastly, this component also provides an instance of the
CommandProvider service. This is an Equinox-specific service which allows console commands to be provided, and was formerly done in the bundle's
Activator. The advantages of this model are that as soon as the dependent services are available, the
CommandProvider service will automatically be published; in addition, the code itself doesn't need to depend on any OSGi APIs.
A similar solution needs to be implemented for the Felix-specific implementation; since as yet, there's no standard for OSGi command shells. There is OSGi RFC 147, which is a work in progress to permit commands being used in different consoles. The source code included has the
shorten-command-felix component definition for completness.
Starting the services
The above allows us to start the bundles for providing (and consuming) the shortening service in any order. Once the command service is started, it will bind to the highest priority shortening service available; or, if that's not specified, the one with the lowest service ranking. Should a higher priority service be started afterwards, we currently don't take into account and continue to use the service we are currently bound to. However, should a service go away, then we'll be re-bound to the remaining highest priority shortening service at that time, without interruption from the client.
In order to run the examples, you'll need to download and install some extra bundles for each platform:
- Felix
- Config Admin (
org.apache.felix.configadmin-1.2.4.jar)
- SCR Declarative Services (
org.apache.felix.scr-1.2.0.jar)
- Equinox:
By now, you should be familiar with installing and starting bundles; but if not, refer to the Static Modularity article. We'll need to install the above bundles, as well as our shortening service. This is how it would look in Equinox, with the bundles in
/tmp
$ java -jar org.eclipse.osgi_* -console osgi> install Bundle id is 1 osgi> install Bundle id is 2 osgi> install Bundle id is 3 osgi> install Bundle id is 4 osgi> install Bundle id is 5 osgi> install Bundle id is 6 osgi> install Bundle id is 7 osgi> start 1 2 3 4 5 osgi> shorten ... osgi> start 6 7 osgi> shorten osgi> stop 6 osgi> shorten osgi> stop 7 osgi> shorten ...
Once we've installed and started our dependencies, including the
shorten command, it still doesn't show up in the console. It's only when we start the shortening services that the
shorten command is registered.
When the first shortening service is stopped, the implementation automatically fails back over to the second shortening service. When that's stopped, the
shorten command service gets automatically unregistered.
Notes
Declarative Services makes wiring OSGi services easy. However, there are a few points to be aware of.
- The DS bundle needs to be installed and started in order to wire up components. As such, it's typically installed as part of the OSGi framework start-up, such as Equinox's osgi.bundles or Felix's felix.auto.start property.
- The DS often has other dependencies which need to be installed. In Equinox's case, it includes the
equinox.utilbundle.
- Declarative Services is part of the OSGi Compendium Specification rather than the Core Specification, so it's often the case that a separate bundle needs to be made available for the service interfaces. In Equinox's case, it's provided by
osgi.services, but in Felix, the interface is exported by the SCR (Service Component Registry, aka DS) bundle itself.
- Declarative Services can be configured with properties. It typically makes use of the OSGi Config Admin service; although this is optionally bound/accessed. Therefore, some parts of the DS requires Config Admin to be running; and in fact, Equinox 3.5 has a bug which requires Config Admin to be started before Declarative Services if it is used. This often requires the use of the start-up properties above in order to ensure the correct dependencies are met.
- The OSGI-INF directory (along with XML files) needs to be included in the bundle, as otherwise DS won't be able to see it. You also need to ensure that the
Service-Componentheader is present in the bundle's manifest.
- It's also possible to use
Service-Component: OSGI-INF/*.xmlto include all components rather than listing them individually by name. This also permits fragments to add new components to a bundle.
- The bind and unbind methods need to be
synchronizedin order to avoid potential race conditions, although using compareAndSet() on an
AtomicReferencecan also be used to act as a non-synchronized placeholder for the single service
- DS components needs no OSGi interfaces, and as such, can be mocked for testing or used in other inversion of control patterns like Spring. However, there are both Spring DM and the OSGi Blueprint service which can be used to wire services up, which is the subject for a future topic.
- DS 1.0 didn't define a default XML namespace; DS 1.1 adds the namespace. If no namespace is present, it assumes DS 1.0 compatibility.
Summary
In this article, we've explored how we can decouple our implementations from the OSGi API, and instead use declarative representations of those components. Declarative Services provides both wiring between components and registering of services, which helps to avoid any start-up ordering dependencies. Furthermore, the dynamic nature means that as our dependent services come and go, so too does our component/service come and go as well.
Finally, whether using DS or manually managed services, they all use the same OSGi service layer in order to communicate. Therefore, one bundle could provide services via a manual method, and another could consume it using declarative services (or vice versa). We should be able to mix and match the
1.0.0 and
1.1.0 implementations and they should transparently work.
Installable bundles (also containing source code):
- com.infoq.shorten-1.0.0.jar
- com.infoq.shorten.command-1.1.0.jar
- com.infoq.shorten.tinyurl-1.1.0.jar
- com.infoq.shorten.trim-1.1.0.jar
Rate this Article
- Editor Review
- Chief Editor Action
Hello stranger!You need to Register an InfoQ account or Login or login to post comments. But there's so much more behind being registered.
Get the most out of the InfoQ experience.
Tell us what you think
Minor corrections
by
Neil Bartlett
2. The activate/deactivate attributes are on the top-level component element, not on the reference element. Also the default method names of "activate" and "deactivate" are assumed, so you only really need to use the attributes if your lifecycle methods are named "begin/end", "commence/cease" etc.
Start Levels do not bound or order DS service activation
by
Michael Furtak
As the author mentions, you can sometimes see positive results by fiddling with the start levels, but in essence you are depending on a race condition. As was stated, it is a much better plan to make sure that your services have no start-order dependencies.
In short, my advice is don't depend on start levels. :)
Re: Minor corrections
by
Christopher Brind?
If you create a component that is also a service which happens to have multiple consumers, then start synchronizing the interface methods and code blocks, you instantly create a system bottleneck, since your consumers will have to take it in turns to access the synchronized blocks.
I just had a scan through the spec and it doesn't mention the need for using synchronization at all in DS components.
What am I missing? :)
Cheers,
Chris
Re: Minor corrections
by
Alex Blewitt
IShorten s = this.shorten;
if(s!=null) s.shorten(url)
should suffice. I don't think you need to guard the access to the 'shorten' field by synchronised access at all though; since field lookup will be atomic (and if you're not synchronizing the whole method, then clearly it can change between the access and the invocation.
Thanks for the other correction; will fix the article.
Re: Minor corrections
by
Alex Blewitt
What are the race conditions mentioned in this article? Are there multiple threads creating DS components?
There could be.?
It's more of a general case best practice, rather than this specific example. However, whilst there's (probably) only one thread executing the console, there could be another process that is shutting down my shorten service asynchronously; for example, a failover process that reaps services running every 24h might decide to stop a bundle at the same time I'm using it. So it's something to be aware of, even if it's not directly relevant in this example.
If you create a component that is also a service which happens to have multiple consumers, then start synchronizing the interface methods and code blocks, you instantly create a system bottleneck, since your consumers will have to take it in turns to access the synchronized blocks.
Right, there are potential bottleneck processes in this kind of situation. Another possibility is to store the var in an AtomicRef, which serializes access to the contained variable. The important thing is to ensure that any long-running service processing doesn't hold the lock, only the acquisition of the service.
Alex
Re: Minor corrections
by
Neil Bartlett
Unfortunately that means you will be inside a synchronized block when you call the IShorten service, which is also not recommended; it's better to use the synchronized block only to copy the field into a local variable. Far better to use an AtomicReference (or if the reference is multiple, i.e. 0..n or 1..n, then use a CopyOnWriteArray).
However in this example I would simply use the static policy. The component class is not expensive to (re)create and the reference is mandatory anyway. Static policy means you don't have to worry about concurrency at all.
Re: Minor corrections
by
Neil Bartlett
In OSGi, all bundles are free to create threads -- this is a big difference from, say, J2EE. Therefore service method invocations can occur on any arbitrary thread. Also bundles can call OSGi APIs such as registerService() from any thread, and the events arising from another bundle registering a service are delivered synchronously on that same thread. Therefore the bind/unbind methods in a DS component (when using dynamic policy) can also be called from any arbitrary thread. All this means that, e.g. you might get the unbind called on one of your service references *while you are using it*.
The static policy makes this easier, it simply recreates the component each time the reference change, so you don't have to worry about visibility or locking. But obviously that carries a price tag which might be quite high depending on the resources used by your component, so it's a trade off that you have to think about.
Re: Minor corrections
by
San Dokan
Thanks
by
Lars Vogel
Re: Minor corrections
by
Alex Blewitt
Consider the following. We have two service instances, s1 and s2. Initially, the variable is pointing to s1. When it gets stopped/started, the variable is pointing to s2.
The race condition thus becomes a possibility of (another) thread holding a reference to s1 whilst it is being stopped/started. Consider the call paths:
1. Synchronize Block to acquire
2. Copy into local variable
3. Release block
4. Invoke method on local variable
Now consider the non-synchronized case:
1. Copy value of field into stack
2. Invoke method on stack
Both of these admit the same problem; namely, after point 3 (in the first case) and 1 (in the second) can have the service swapped out. So in both cases, you can still invoke on the 'old' service. In other words, the race condition holds unless you serialize access to all shorten services.
Also, bear in mind that this race condition exists in pretty much all Java code everywhere that uses Threads - it's nothing specific to OSGi (or services, for that matter).
Finally, consider the case where the service is a long-running service (say, one minute). If the service is running whilst the bundle is stopped/started, you're still going to be in the 'old' code path, pinned to the old bundle until it completes. Arguing that a subsequent thread that might come in might not see the same initial starting point is just quibbling on semantics.
Excellent articles
by
Luís Carlos Moreira da Costa | http://www.infoq.com/articles/modular-java-declarative-modules/ | CC-MAIN-2016-18 | refinedweb | 3,556 | 54.52 |
How to achieve auto login and log off on Google accounts on time based . I am using the chat client is EMPATHY
First you'll need a way to schedule tasks. If you're not familiar with cron, and you're using Ubuntu/GNOME then sudo apt-get install gnome-schedule. Then you can open Scheduled Tasks from the System >> Preferences menu and use the GUI to set a specific time for a command to run.
cron
sudo apt-get install gnome-schedule
The simplest way to schedule a time for Empathy to connect and disconnect is to just schedule jobs to start and stop the program (just use the commands empathy and killall empathy). The problem is that if we kill Empathy without logging out then you'll still appear signed in for a few minutes until Google discovers that you've timed out.
empathy
killall empathy
To get around that problem we can use D-Bus to send a signal to Empathy's backend that asks it to disconnect. There are lots of ways to do this including with dbus-send from the command line, but since I'm more familiar with Python I used that.
dbus-send
Instead of configuring your sign-off task to call killall empathy, save the following script somewhere (e.g. ~/empathy_signout.py) and then schedule your task to call that (python ~/empathy_signout.py). Replace the string EXAMPLE in the fourth line with your Google Talk account name before you save the file.
~/empathy_signout.py
python ~/empathy_signout.py
EXAMPLE
#!/usr/bin/env python
# Disconnect Empathy from Google Talk and kill the program.
# Replace EXAMPLE below with your account name (whatever is before @gmail.com)
google_acct_name = 'EXAMPLE'
import os
try:
import dbus
except ImportError:
exit('You need the Python dbus bindings,'
' type "sudo apt-get install python-dbus".')
wkname = ('org.freedesktop.Telepathy.Connection.gabble.jabber.' +
google_acct_name + '_40gmail_2ecom_2fTelepathy')
pathname = '/' + wkname.replace('.', '/')
bus = dbus.SessionBus()
conn_obj = bus.get_object(wkname, pathname)
conn_obj.Disconnect(dbus_interface='org.freedesktop.Telepathy.Connection')
os.system('killall empathy')
This script could be tweaked to avoid the hacky guess of the account name path component, or to sign on also (If quitting the program is a problem). Take a look at the ConnectionManager interface in the Telepathy D-Bus docs if this stuff doesn't fright
1 year ago | http://superuser.com/questions/14352/auto-login-for-gtalk/14775#14775 | crawl-003 | refinedweb | 385 | 54.22 |
Before I explain my issue, I have some experience with entity framework 5 and 6 code first migrations, running
add-migration/
update-database and a few more specific commands from the Package Manager console. All of the migration history was handled out of the box in the
__MigrationHistory table.
I am now writing a UWP app and using
EntityFrameworkCore sqlite. The app is set up to scaffold new migrations and does so correctly.
When applying migrations the app needs to automatically deduce, on install and first startup, if the database exists, and the current database migration version. It can then apply the relevant migration procedures, including creating the database if required.
Currently, I attempt to perform the migrations in my DbContext on startup:
public class MyContext : DbContext { public DbSet<SomeEntity> MyEntities { get; set; } static MyContext() { using(var db = new MyContext()) { db.Database.Migrate(); } }
This works perfectly for a new app on first startup. On second startup however, or after the addition of a new migration, the Migrate() method fails as the tables it is attempting to create already exist.
SQLite Error 1: 'table \"MyEntities\" already exists'
This error comes from rerunning the migration that has been previously applied. The database itself needs to be aware of it's migration history as was previously handled with
__EFMigrationHistory. Currently this table is not being created for me.
I am suspecting that I need to manually build a solution to this, maybe creating my own __MigrationHistory table and keeping it up to date, as per this post here
I wondered what solutions people have used for this issue, or if there is anything out of the box that I'm being silly and missing.
Let me know if more detail needed.
As far as i've come up with while having your same issue, i found out the debug database (inside your \bin\Debug folder) won't have the __EFMigrationsHistory table, while the production database (root of your launching project) has it.
Maybe could be of help for somebody else. | https://entityframeworkcore.com/knowledge-base/42393128/entityframeworkcore-for-sqlite-not-creating---efmigrationhistory-table | CC-MAIN-2022-40 | refinedweb | 337 | 50.77 |
Josh Lee4,707 Points
Not sure what I am doing wrong here...
When comparing to the code in the workspace for the video, this should be working. Not sure what I am doing wrong. I keep getting a compiler error.
namespace Treehouse.CodeChallenges { class Frog { public readonly int TongueLength; public Frog(int length) { TongueLength = length; } } public static void Main() { Frog Frog = new Frog(8); int frogLength = Frog.TongueLength; } }
1 Answer
Steven Parker194,132 Points
You've done all the right things, but also some extras that are not part of the challenge instructions.
For this challenge, you only add to the class definition. You won't need to create a "Main" method or an instance of the class.
For best results with all the challenges, follow the instructions carefully but don't do anything extra! | https://teamtreehouse.com/community/not-sure-what-i-am-doing-wrong-here-7 | CC-MAIN-2020-24 | refinedweb | 135 | 74.19 |
Maildir local mailbox type. More...
#include "config.h"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <utime "hcache/lib.h"
#include "notmuch/lib.h"
Go to the source code of this file.
Maildir maildir.c.
Check for new mail / mail counts.
Checks the specified maildir subdir (cur or new) for new mail or mail counts.
Definition at line 85 of file maildir.c.
Generate the Maildir flags for an email.
Definition at line 186 of file maildir.c.
Commit a message to a maildir folder.
msg->path contains the file name of a file in tmp/. We take the flags from this file's name.
m is the mail folder we commit to.
e is a header structure to which we write the message's new file name. This is used in the mh and maildir folder sync routines. When this routine is invoked from mx_msg_commit(), e is NULL.
msg->path looks like this:
tmp/{cur,new}.neomutt-HOSTNAME-PID-COUNTER:flags
See also maildir_msg_open_new().
Definition at line 237 of file maildir.c.
Sync a message in an MH folder.
Definition at line 331 of file maildir.c.
Sync an email to a Maildir folder.
Definition at line 387 of file maildir.c.
Update our record of the Maildir modification time.
Definition at line 477 of file maildir.c.
Compare two Maildirs by inode number - Implements sort_t.
Definition at line 495 of file maildir.c.
Read a Maildir mailbox.
Definition at line 513 of file maildir.c.
Calculate the length of the Maildir path.
Definition at line 585 of file maildir.c.
This function does the second parsing pass.
Definition at line 597 of file maildir.c.
Read a Maildir style mailbox.
Definition at line 673 of file maildir.c.
Generate the canonical filename for a Maildir folder.
Definition at line 727 of file maildir.c.
Find a message in a maildir folder.
These functions try to find a message in a maildir folder when it has moved under our feet. Note that this code is rather expensive, but then again, it's called rarely.
Definition at line 757 of file maildir.c.
Parse Maildir file flags.
Definition at line 811 of file maildir.c.
Parse a Maildir message.
Actually parse a maildir message. This may also be used to fill out a fake header structure generated by lazy maildir parsing.
Definition at line 882 of file maildir.c.
Actually parse a maildir message.
This may also be used to fill out a fake header structure generated by lazy maildir parsing.
Definition at line 926 of file maildir.c.
Save changes to the mailbox.
Definition at line 946 of file maildir.c.
Find a new.
Definition at line 993 of file maildir.c.
Is the mailbox empty.
Definition at line 1040 of file maildir.c. | https://neomutt.org/code/maildir_8c.html | CC-MAIN-2021-39 | refinedweb | 495 | 81.8 |
Click listener in flatlist
How can I add click listener in
Flatlist?
My code:
renderItem({item, index}){ return <View style = {{ flex:1, margin: 5, minWidth: 170, maxWidth: 223, height: 304, maxHeight: 304, backgroundColor: '#ccc', }}/> } render(){ return(<FlatList contentContainerStyle={styles.list} data={[{key: 'a'}, {key: 'b'},{key:'c'}]} renderItem={this.renderItem} />); } }
Update 1: I used button but it is not working in
Flatlist. However using only button instead of
Flatlist, it works. Why is it not working in
Flatlist renderItem?
_listener = () => { alert("clicked"); } renderItem({item, index}){ return<View> <Button title = "Button" color = "#ccc" onPress={this._listener} /> </View> }
You need to wrap your row element (inside your renderItem method) inside
<TouchableWithoutFeedback> tag.
TouchableWithoutFeedback takes onPress as it's prop where you can provide onPress event.
For
TouchableWithoutFeedback refer this link
FlatList component navigate to new details screen on click, r/reactnative: A community for learning and developing native mobile applications using React Native by Facebook. < FlatList viewabilityConfig = {this. viewabilityConfig} minimumViewTime Minimum amount of time (in milliseconds) that an item must be physically viewable before the viewability callback will be fired.
I used
TouchableWithoutFeedback. For that, you need to add all the renderItem elements (i.e your row) into the
TouchableWithoutFeedback. Then add the
onPress event and pass the FaltList item to the onPress event.
import {View, FlatList, Text, TouchableWithoutFeedback} from 'react-native'; render() { return ( <FlatList style={styles.list} data={this.state.data} renderItem={({item}) => ( <TouchableWithoutFeedback onPress={ () => this.actionOnRow(item)}> <View> <Text>ID: {item.id}</Text> <Text>Title: {item.title}</Text> </View> </TouchableWithoutFeedback> )} /> ); } actionOnRow(item) { console.log('Selected Item :',item); }
[Please Help] Click Event on FlatList items not working , I have a horizontal FlatList, where each time it reaches the end, it automatically adds new elements to the list, so it kind of is an infinite list. I have a horizontal FlatList, where each time it reaches the end, it automatically adds new elements to the list, so it kind of is an infinite list. I want the app to scroll through the list by itself automatically, but during my testing
I used
TouchableOpacity. and it's working great.This will give you click feedback. which will not be provided by
TouchableWithoutFeedback. I did the following:
import { View, Text, TouchableOpacity } from "react-native";
. . .
_onPress = () => { // your code on item press }; render() { <TouchableOpacity onPress={this._onPress}> <View> <Text>List item text</Text> </View> </TouchableOpacity> }
How to highlight and multi-select items in a FlatList component , I have a horizontal FlatList, where each time it reaches the end, RN's own touchable component and implement my own touch event handler. You set an OnClickListener instance (e.g. myListener named object)as the listener to a view via setOnclickListener(). When a click event is fired, that myListener gets notified and it's onClick(View view) method is called. Thats where we do our own task. Hope this helps you.
FlatList · React Native, selected: styles.list;. Next, when we click on any item in our FlatList the selectItem function gets rendered and it changes the styling of that item to Bài này chia sẻ với các bạn cách hiên thị màn hình kiểu Modal, nhập thông tin và thêm một Item vào FlatList SUBSCRIBE TO MY CHANNEL FOR MORE INTERESTING VIDEOS: https
React Native Simple FlatList Component Android iOS Example , Provides a handle to the underlying scroll node. Is this page useful? ← ButtonImage.
How can i change the FlatList item background color when button is , Use FlatList component in react native android iOS application with FlatList Item Separator line, custom Flat List items and get item clicked Importantly, TouchableWithoutFeedback works by cloning its child and applying responder props to it. It is therefore required that any intermediary components pass through those props to the underlying React Native component. | http://thetopsites.net/article/51611284.shtml | CC-MAIN-2020-40 | refinedweb | 620 | 56.96 |
Any developer should be a big fan of unit testing for a multitude of reasons. If a good set of unit tests are written for a software unit, it is possible to verify at any time if the code still behaves as assumed by the developer who has written the unit tests. It allows you, as the developer, to have more confidence in your code. This is because all the assumptions about the code, expressed in different unit tests, can be verified at any point in time. All developers feel this need, especially after some changes are made in the code and the impact of those changes is not foreseeable. It is easier to understand the benefits of unit tests for the longer term, but this is not so obvious in the short term. This is especially the case when tooling support is not so great and you have to spend significant time setting up the framework needed for unit testing.
Luckily, there are multiple tools that help with writing unit tests for .NET code. The most representative is probably NUnit. In many cases, NUnit alone will do the job. In other situations, various extensions have to be used, like ASPUnit, NUnitForms, different mock libraries, etc. Another such extension is NDbUnit, which allows putting a database into a certain state. Unfortunately, when testing database applications, putting the test database into an initial state is only one part of the problem. What is still needed is an easy way to verify the (partial) content of the database after applying some processing on the database. In an ideal situation, this should be as easy as calling an
Assert method from NUnit. However, because the database content might be more complex than an atomic value, checking the content can also be a bit more complex.
This article shows how the DataSet, together with XML and queries expressed in XPath, can be used to express in a compact form the assumptions about the content of the database. Together with NDbUnit they allow development of unit tests that are quite compact and can be written in a relatively short time. I've applied this method to testing multiple SQL Server Integration Service (SSIS) packages in my current project. However, the modules that are processing the database are not relevant for this article because it focuses on inspecting the content of the database to verify that the result of the processing is correct, no matter how the processing is performed. There must only be a way to start the processing of the database from the unit tests. In my project, I had to start SSIS packages from unit tests, but in most cases the processing of databases is performed via ADO.NET. The examples provided in the solution will not process the content of the databases in any way, but will focus on inspecting the content already present in the database. The database content is loaded by using NDbUnit.
In order to illustrate the concepts presented in this article I will use a simplified version of the well known NorthWind database. I will focus on a simplified version of Customers, Orders and OrderDetail tables. The database schema is shown below. In order to re-create the database, you have to execute the TSQL script
CreateTables.SQL included in the solution.
Loading a specific content in the database is very easy with NDbUnit:
SqlDbUnitTest dbUnitTest = new SqlDbUnitTest(connectionString); dbUnitTest.ReadXmlSchema(xsdStream); dbUnitTest.ReadXml(dataStream); dbUnitTest.PerformDbOperation(operation);
In this code segment,
xsdStream must contain the schema of the database while
dataStream is the database content that will be loaded in the database. When loading the data, one of the operations defined by
DbOperationFlag enum will be performed:
public enum DbOperationFlag { /// No operation. None, /// Insert rows into a set of database tables. Insert, /// Insert rows into a set of database tables. Allow identity /// inserts to occur. InsertIdentity, /// Delete rows from a set of database tables. Delete, /// Delete all rows from a set of database tables. DeleteAll, /// Update rows in a set of database tables. Update, /// Refresh rows in a set of database tables. Rows that exist /// in the database are updated. Rows that don't exist are inserted. Refresh, /// Composite operation of DeleteAll and Insert. CleanInsert, /// Composite operation of DeleteAll and InsertIdentity. CleanInsertIdentity }
Generating the typed data set associated with the tested database is easy in Visual Studio. First, a connection to the database must be defined in the Server Explorer panel. Then add a new DataSet file to your project and view it in the designer window. The last step is to drag all the tables from the database connection onto your designer window. After any change of the database schema, the XSD file associated with the typed DataSet must also be updated to reflect the changes of the database schema. If the XSD file is not in sync with the database schema, NDbUnit will not generate any exception that helps you to understand why the database content is not set as expected. The typed data set for the example database is generated in the file DBSchema.Designer.cs.
The XML file that provides the database content can be created with an editor or in Visual Studio. Visual Studio provides Intellisense to help you create this file. However, if you have the desired content already stored in the database, you can export it very easily into the XML file with Altova's XMLSpy, for instance. Just be sure to indicate that you want the export to be created according to the definition from the XSD file you already created.
Many scenarios can be imagined when testing the content of the database. This is caused by the variety of the possible associations that can be created between the fields from the database. I will illustrate two categories here. The first group allows testing of the database's content at the global level, while the second group allows testing the content in detail. Global level testing is useful when you only need to know if everything is behaving as expected. If the test fails, you might not be able find the reason, in which case the second category might be better.
This is the easiest database content to test. It is appropriate for global testing, when the developer would like to verify if the whole content of a table is equal to some expected content. In case of failures, the test will not help to identify the reason for the failures. One example of such a test is
TestCustomers, defined in the fixture
GlobalTesting. The test verifies if the content of the table Customers is the same as defined in the file ExpectedCustomers.xml.
The test can be performed by loading the table content in a dataset and then comparing the fields of the loaded rows with the desired values. However, you would have to write multiple asserts for each row only to test if the row has the expected content. The following 2 helper methods defined in the class
ResultInspector allow testing if 2 rows or tables have equal content:
Method 1
public static bool AreEqual(DataTable expected, DataTable actual) { Assert.AreEqual(expected.Rows.Count, actual.Rows.Count, "Different number of rows"); for(int i=0; i > expected.Rows.Count; i++) { AreEqual(expected.Rows[i], actual.Rows[i], i); } return true; }
Method 2
public static bool AreEqual(DataRow expected, DataRow actual, int rowIndex) { Assert.AreEqual(expected.ItemArray.Length, actual.ItemArray.Length); for (int i = 0; i > expected.ItemArray.Length; i++) { Assert.AreEqual(expected[i], actual[i], "Difference on row:" + rowIndex.ToString() + ", column:" + expected.Table.Columns[i]); } return true; }
Writing an assertion becomes as simple as:
Assert.IsTrue( ResultInspector.AreEqual( ResultInspector.GetExpectedTable( "Schemas.DBSchema.xsd", "TestData.ExpectedCustomers.xml", "Customers" ), GetDatabaseCustomers() ) );
GetDatabaseCustomers loads the table from the database and
GetExpectedTable loads the expected content from an XML resource. For the
GetExpectedTable method, you have to define the content you expect in the database in an XML file. For
GetDatabaseCustomers, you have to write the SQL query that extracts the desired content from the database.
An important note: the method
AreEqual defined with
DataTable parameters is performing the equality check based on the order of the rows in the tables. This means that you have to specify the
ORDER BY clause in the SQL query you are writing and use the same order when creating the XML file where the expected content is specified. The
AreEqual method is performing the equality test only on the fields specified by the expected parameter, even if the actual table from the database contains many more fields. This makes it easier to create and maintain the expected result XML if you are interested only in a few fields.
This sort of test can be extrapolated and performed at the level of the whole data set instead of a single table. However, this is more difficult in general because in most databases the relationships between tables are based on some internal identifiers that have a meaning only inside the database. This makes specifying the expected content of the database difficult. It's more difficult, but not impossible, if you can control how those internal identifiers are created.
Testing related data that is spread across multiple tables and is related via some internal identifiers can be reduced to the previous case if for each test a custom XSD is defined that specifies the fields that are tested. The internal identifiers are hidden by writing an SQL query that joins the tables of relationship identifiers and selects the fields that have to be tested.
To illustrate this approach, let's consider the unit test
MarchOrders. In this test, we want to check that certain employees have created orders in March 2006 on behalf of some customers. We are interested in the fields CompanyName, FirstName, LastName and OrderDate. These come from the tables Employees, Orders, Customers for the period March 1-31, 2006. The test
MarchOrders checks if this is true. The following SQL query defined in the method
GetMarchOrders takes care to retrieve the tested fields and to hide the internal identifiers:
SELECT CompanyName, FirstName, LastName, OrderDate FROM Customers JOIN Orders ON (Customers.CustomerID = Orders.CustomerID ) JOIN Employees ON (Orders.EmployeeID = Employees.EmployeeID) ORDER BY CompanyName, FirstName, LastName, OrderDate"
The associated XSD is defined in the CustomersEmployeesOrders.xsd file, while the expected result is in ExpectedMarchOrders.xml. Even if for each test an XSD file must be defined, this is very simple:
>
The effort to create these XSD files is minimal. Only the sequence of the fields will differ from one test case to another and each field is defined by a very simple line in the XSD file. The same method,
ResultInspector.AreEqual, is used to test that the content of the database is the same as the expected result.
It is good to get the confirmation from the unit test that something is behaving as expected! This might be the indication that you expect in order to release your project for integration testing or to report that you are ready with your implementation. However, if the unit test fails, it will not help you too much to identify the exact place in source code that is causing the error. If the unit tests are well-written, a failing unit test must provide enough information to identify the cause of the error. In one way, a unit test can be seen as a substitute for the debugger: if you write good unit tests, then you don't have to use the debugger because the unit tests will tell you what and where it is failing. This usually means that you have to write more granular tests compared to previous scenarios. XPath can be very helpful with expressing different test conditions in a compact form.
Let's consider the test
AroundTheHornOrderedCPUs defined in the fixture
DetailedTesting. This test checks if the company Around the Horn ordered the product CPU-64X2. In order to do this, the content of all tables except Employees needs to be investigated. Once the content of the database is transformed in the XML format, the following XPath expression can check the test condition:
//Orders[ CustomerID=//Customers[CompanyName='Around the Horn']/CustomerID and OrderID=//OrderDetails[SKU='CPU-64X2']/OrderID ]
If it returns any nodes, then the tested condition is verified. The XPath query is applied on the XmlDocument that is returned by the method:
public static XmlDocument LoadTablesAsXML<typedataset />(string connectionString, bool doNestTableElements, params string[] tableNames)
This method loads the content of the tables specified in the last parameter and transforms the content in an XmlDocument. The parameter
doNestTableElements indicates if the elements in the resultant XML should be nested as indicated by the relationships that exist between tables or not. Note that the method also removes the namespace references from the generated XML to make it easier to write the XPath expressions, without specifying the namespace. Another similar test is
MichelaHasCreatedExactlyOneOrder, which verifies that Michela has created exactly one order.
My experience is that writing complex XPath queries can be challenging. It might take some time to express the right select condition and an XPath debugger proves to be very helpful. XmlSpy can be used to test the XPath expressions in more complex cases. One very common case where XPath expressions can be simplified is when the tables that are tested are structured via parent-child relationships. In this case, the path in the hierarchy of elements can be used instead of the joins between elements. In our case, there are two such hierarchical relationships between Customers-Orders-OrderDetails or Employees-Orders-OrderDetails tables. It is possible to use the parent-child relationships to generate a nested XML from typed DataSet instead of a flat one as in the previous cases. Just use
true for the parameter
doNestTableElements of
LoadTablesAsXML. Be careful when providing the tables from which the XML will be generated, as it is not possible to generate such a nested XML if at least one of the tables has more that one parent.
The test
AroundTheHornHasBigOrders checks if the company Around the Horn has any big orders containing more that 100 items of the same type. Because the elements are nested, the XPath expression is simpler in this case:
//Customers[CompanyName='Around the Horn']/Orders/OrderDetails[Quantity>=100]
The test project was developed in Visual Studio 2005 and tested with a Microsoft SQL Server 2005 database. It will not work exactly in this form in Visual Studio 2003 due to the generics that are used in some methods, but it should work on older versions of Microsoft SQL Server.
In order to run the unit tests:
CreateTables.SQLon the database
DbConnectionStringin the file App.config to match the connection string for the database you just created
2007-06-06
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/database/UnitTestDbAppsWithNDbUnit.aspx | crawl-002 | refinedweb | 2,475 | 53.21 |
Reading large PDB files
If one is using Biopython to work with PDB files that have been produced by molecular dynamics (MD) codes then one quickly runs into problems with missing atoms on reading. The typical error message says that atoms will be missing:
WARNING: Residue (' ', 1, ' ') redefined at line 31. PDBConstructionException: Blank altlocs in duplicate residue SOL (' ', 1, ' ') at line 31. Exception ignored. Some atoms or residues will be missing in the data structure.
The problem is simply that these files can be large with hundreds of thousand of atoms and residues (for instance, each water molecule is a separate residue) and the PDB format has not enough space in the appropriate columns of the ATOM or HETATM record to accommodate atom numbers (serial) >99,999 and residue numbers (resSeq) > 9999. Thus, these numbers are simply written modulo 100,000 (serial) or modulo 10,000 (resSeq). This creates duplicate entries in the chain and the Bio.PDB.PDBParser (or rather, the StructureBuilder) complains. The effect is that not all atoms are read.
The code below derives a new class from
Bio.PDB.StructureBuilder.StructureBuilder that simply increases the resSeq if necessary. Because it is not very careful it is called a
SloppyStructureBuilder.
There's also a new class named
SloppyPDBIO that writes pdb files with serial and resSeq wrapped so that the resulting pdb files are legal PDB format.
Example
Load a big pdb file and write it out again. How to do interesting things to the pdb file such as deleting some water molecules around a ligand is left for another article.
import Bio.PDB import xpdb # read sloppyparser = Bio.PDB.PDBParser(PERMISSIVE=True,structure_builder=xpdb.SloppyStructureBuilder()) structure = sloppyparser.get_structure('MD_system','my_big_fat.pdb') # ... do something here ... # write sloppyio = xpdb.SloppyPDBIO() sloppyio.set_structure(structure) sloppyio.save('new_big_fat.pdb')
Classes
This is the python implementation. Store it as a module
xpdb.py somewhere on your
PYTHONPATH.
# xpdb.py -- extensions to Bio.PDB # (c) 2009 Oliver Beckstein # Relased under the same license as Biopython. # See import sys import Bio.PDB import Bio.PDB.StructureBuilder class SloppyStructureBuilder(Bio.PDB.StructureBuilder.StructureBuilder): """Cope with resSeq < 10,000 limitation by just incrementing internally. # Q: What's wrong here?? # Some atoms or residues will be missing in the data structure. # WARNING: Residue (' ', 8954, ' ') redefined at line 74803. # PDBConstructionException: Blank altlocs in duplicate residue SOL (' ', 8954, ' ') at line 74803. # # A: resSeq only goes to 9999 --> goes back to 0 (PDB format is not really good here) """ # NOTE/TODO: # - H and W records are probably not handled yet (don't have examples to test) def __init__(self,verbose=False): Bio.PDB.StructureBuilder.StructureBuilder.__init__(self) self.max_resseq = -1 self.verbose = verbose def init_residue(self, resname, field, resseq, icode): """ Initiate a new Residue object. Arguments: o resname - string, e.g. "ASN" o field - hetero flag, "W" for waters, "H" for hetero residues, otherwise blanc. o resseq - int, sequence identifier o icode - string, insertion code """ if field!=" ": if field=="H": # The hetero field consists of H_ + the residue name (e.g. H_FUC) field="H_"+resname res_id=(field, resseq, icode) if resseq > self.max_resseq: self.max_resseq = resseq if field==" ": fudged_resseq = False while (self.chain.has_id(res_id) or resseq == 0): # There already is a residue with the id (field, resseq, icode). # resseq == 0 catches already wrapped residue numbers which do not # trigger the has_id() test. # # Be sloppy and just increment... # (This code will not leave gaps in resids... I think) # # XXX: shouldn't we also do this for hetero atoms and water?? self.max_resseq += 1 resseq = self.max_resseq res_id = (field, resseq, icode) # use max_resseq! fudged_resseq = True if fudged_resseq and self.verbose: sys.stderr.write("Residues are wrapping (Residue ('%s', %i, '%s') at line %i)." % (field, resseq, icode, self.line_counter) + ".... assigning new resid %d.\n" % self.max_resseq) residue=Residue(res_id, resname, self.segid) self.chain.add(residue) self.residue=residue class SloppyPDBIO(Bio.PDB.PDBIO): """PDBIO class that can deal with large pdb files as used in MD simulations. - resSeq simply wrap and are printed modulo 10,000. - atom numbers wrap at 99,999 and are printed modulo 100,000 """ # directly copied from PDBIO.py # (has to be copied because of the package layout it is not externally accessible) _ATOM_FORMAT_STRING="%s%5i %-4s%c%3s %c%4i%c %8.3f%8.3f%8.3f%6.2f%6.2f %4s%2s%2s\n" def _get_atom_line(self, atom, hetfield, segid, atom_number, resname, resseq, icode, chain_id, element=" ", charge=" "): """ Returns an ATOM PDB string that is guaranteed to fit into the ATOM format. - Resid (resseq) is wrapped (modulo 10,000) to fit into %4i (4I) format - Atom number (atom_number) is wrapped (modulo 100,000) to fit into %4i (4I) format """ if hetfield!=" ": record_type="HETATM" else: record_type="ATOM " name=atom.get_fullname() altloc=atom.get_altloc() x, y, z=atom.get_coord() bfactor=atom.get_bfactor() occupancy=atom.get_occupancy() args=(record_type, atom_number % 100000, name, altloc, resname, chain_id, resseq % 10000, icode, x, y, z, occupancy, bfactor, segid, element, charge) return self._ATOM_FORMAT_STRING % args # convenience functions sloppyparser = Bio.PDB.PDBParser(PERMISSIVE=True,structure_builder=SloppyStructureBuilder()) def get_structure(pdbfile,pdbid='system'): return sloppyparser.get_structure(pdbid,pdbfile) | http://biopython.org/w/index.php?title=Reading_large_PDB_files&oldid=2877 | CC-MAIN-2015-14 | refinedweb | 841 | 60.41 |
The tabifier plugin vertically aligns various syntactic elements of Java
declarations and assignment statements according to configuration options.
See for complete
details.
27 May 2003 - Version 2.6
-- enhancement: user can control what happens when no selection is made:
tabify entire file, or only the line containing the cursor (default)
-- bug fix: An extra leading space could be emitted when (for example)
variable types were not aligned but variable names were.
-- debugging output now contains version number.
The tabifier plugin vertically aligns various syntactic elements of Java
Dave Kriewall wrote:
I just tested it for the first time. Mostly it gives me exactly the
results I want (thanks!), but it does not seem to handle assigments at
the same line as a statement properly.
Take the following class (just a silly example):
package test;
public class TestMe {
public static void main(String[] args) {
int i;
if (args.length == 0) i = 0;
else i = 1;
}
}
Tabifier wants to remove all indentation from the "if" and "else" lines:
package test;
public class TestMe {
public static void main(String[] args) {
int i;
if (args.length == 0) i = 0;
else i = 1;
}
}
Jonas Kvarnstr?m wrote:
Seems I had tabs in there. What I meant was:
Tabifier wants to remove all indentation from the "if" and "else" lines:
Hi Jonas,
Thanks for the report. I will fix it so indentation is not broken. But
before I do, may I ask you (and the newsgroup) for some feedback?
1) Would you rather have tabifier leave these if/else lines intact or are
you asking that it align the assignment statements after the if/else parts?
Eg.
if (args.length == 0) i = 0;
else i = 1;
(Needs fixed font to be viewed properly but you get the idea.)
2) I never encounter your situation because by convention I have to use
braces even when the block contains only one statement. Does this situation
only occur for you in if/else/else-if sequences? Or can it occur with any
type of statement that contains a statement block (such as for, while, do,
try)? Eg
for (i=0; i < 10; i+) aray = i;
for (j=0; j < k; j++) otherstuf[j] = something;
while (m < n) aray[m++] = n;
Should all these array element assignment statements align?
Thanks-
Dave
Dave Kriewall wrote:
Personally I think I would be satisfied with either, whichever is easier
for you.
I haven't checked other kinds of statements. I'll try to remember to do
that at work tomorrow (then I'll be away for a week so if you get no
more comments that's the reason).
Yep, it'd be a nice idea. But it's not mandatory !
Guillaume
Hi Jonas,
Version 2.7 is available -- give it a try and let me know if you have any more problems.
Thanks for the bug report!
-Dave
Dave Kriewall wrote:
Thanks! I'm away at a conference now but I've downloaded it and will be
testing it soon. I'll get back to you if I find any bugs.
Dave Kriewall wrote:
One more test case, where the first assignment should not be indented:
Hmm, I see. What should the rule be, though -- separate alignment columns for assignment statements with and without preceding tokens?
E.g.
So that lines 1 & 3 are aligned together, and 2 & 4 are aligned together?
If so, do we need another grouping option to separate groups of assignments that have no "prefix" from those that don't? This would allow choice between the above and
where only lines 2 & 3 are aligned.
Or, lines rearranged for example, would result in
where again only lines 2 & 3 are aligned.
If there's some consensus, I hope to have it fixed today.
Thanks, -Dave
Dave Kriewall wrote:
I'd say you can start a new "group" of alignment lines whenever you
switch between having and not having a prefix. That boundary could be
treated just like a blank line, so the result would be as in your second
and third examples, not as in the first example.
But now I see that you've released a new version, so I should probably
just shut up and test it before I say anything :) | https://intellij-support.jetbrains.com/hc/en-us/community/posts/206140909--ANN-Tabifier-2-6-released | CC-MAIN-2020-24 | refinedweb | 705 | 72.16 |
First, let's formulate the problem as a graph problem. We can represent the barns as vertices (we'll call the total number of barns $n$) and the roads as edges (we'll call the total number of roads $m$). Then the farm is fully connected if the remaining vertices all belong to the same connected component.
The simplest solution is to simulate the process. After each barn is closed, remake the graph in adjacency list form. Then, run a flood fill to count the number of connected components. Specifically, if we do a depth first search starting from any open barn and end up visiting all other open barns, the farm is fully connected. Remaking the graph and running the search takes $O(n+m)$ time. Since there are a total of n barn closings, we have a $O(n^2 + nm)$ algorithm, which solves the problem under the silver constraints.
One shortcoming of the simple solution is that it has no memory - after each new barn is closed, we forget everything we learned about connected components from previous iterations. In particular, we aren't making use of the fact that if $(u,v)$ is an edge in the initial graph, then $u$ and $v$ stay connected until either $u$ or $v$ is removed. Therefore, we want a data structure that can keep track of what connected component a vertex lies in and also supports the operation of disconnecting two vertices. Fortunately, there exists a data structure called disjoint-set (DSU) that supports two similar operations efficiently - keeping track of what connected component a vertex lies in and connecting two vertices.
If we want to use DSU, we need to be connecting vertices together, so let's imagine the process is happening in reverse. We start with an empty farm, and reintroduce barns one at a time, adding roads from the new barn to existing barns if they are edges in the initial graph. For each road we add in, use the DSU find operation to check if the barns at the endpoints are in different connected components. If so, use the DSU merge operation to join the two connected components. This gives us a $O(m \log n)$ solution.
My code is below; it incorporates some very concise "standard" routines for all the DSU functions.
#include <iostream> #include <iomanip> #include <stdio.h> #include <set> #include <vector> #include <map> #include <cmath> #include <algorithm> #include <memory.h> #include <string> #include <sstream> #include <cstdlib> #include <ctime> #include <cassert> using namespace std; typedef long long LL; typedef pair<int,int> PII; #define FORN(i, n) for (int i = 0; i < (int)(n); i++) #define FOR1(i, n) for (int i = 1; i <= (int)(n); i++) #define FORD(i, n) for (int i = (int)(n) - 1; i >= 0; i--) #define FOREACH(i, c) for (typeof((c).begin()) i = (c).begin(); i != (c).end(); i++) #define MOD 1000000007 #define INF 2000000000 void union_init(int d[], int s) { for (int i=0; i < s; i++) d[i]=i; } int union_query(int d[], int n) { int res=n; while (d[res]!=res) res=d[res]; int m; while (d[n]!=n) {m=d[n];d[n]=res;n=m;} return res; }; int union_merge(int d[], int x, int y) { x=union_query(d,x); y=union_query(d,y); if (x==y)return -1; d[x]=y; return 1; } const int MAXN = 100010; int order[MAXN], place[MAXN], u[MAXN], v[MAXN], par[MAXN]; bool res[MAXN]; int N, M; vector< vector<int> > adj; int main() { scanf("%d%d", &N, &M); FORN(i, M) scanf("%d%d", &u[i], &v[i]); FORN(i, N) { scanf("%d", &order[i]); place[order[i]] = i; } adj.resize(N+1); FORN(i, M) { if (place[u[i]] > place[v[i]]) adj[v[i]].push_back(u[i]); else adj[u[i]].push_back(v[i]); } union_init(par, N+1); int comps = 0; FORD(i, N) { int u = order[i]; comps++; FORN(j, adj[u].size()) { int v = adj[u][j]; if (union_query(par, u) != union_query(par, v)) { union_merge(par, u, v); comps--; } } res[i] = (comps <= 1); } FORN(i, N) if (res[i]) printf("YES\n"); else printf("NO\n"); return 0; } | http://usaco.org/current/data/sol_closing_gold_open16.html | CC-MAIN-2018-17 | refinedweb | 697 | 69.31 |
Given convertion
Binary Tree after convertion,.
C++
Java
Python3
# Program to change a BST to Binary Tree
# such that key of a Node becomes original
# key plus sum of all smaller keys in BST
# A BST node has key, left child
# and right child */
class Node:
# Constructor to create a new node
def __init__(self, data):
self.key = data
self.left = None
self.right = None
# A recursive function that traverses the
# given BST in inorder and for every key,
# adds all smaller keys to it
def addSmallerUtil(root, Sum):
# Base Case
if root == None:
return
# Recur for left subtree first so that
# sum of all smaller Nodes is stored
addSmallerUtil(root.left, Sum)
# Update the value at sum
Sum[0] = Sum[0] + root.key
# Update key of this Node
root.key = Sum[0]
# Recur for right subtree so
# that the updated sum is
# added to greater Nodes
addSmallerUtil(root.right, Sum)
# A wrapper over addSmallerUtil(). It
# initializes sum and calls addSmallerUtil()
# to recursively update and use value of
def addSmaller(root):
Sum = [0]
addSmallerUtil(root, Sum)
# A utility function to print
# inorder traversal of Binary Tree
def printInorder(node):
if node == None:
return
printInorder(node.left)
print(node.key, end = ” “)
printInorder(node.right)
# Driver Code
if __name__ == ‘__main__’:
# Create following BST
# 9
# /
# 6 15
root = Node(9)
root.left = Node(6)
root.right = Node(15)
print(“Original BST”)
printInorder(root)
print()
addSmaller(root)
print(“BST To Binary Tree”)
printInorder(root)
# This code is contributed by PranchalK
C#
Output:
Original BST 6 9 15 BST To Binary Tree 6 15 30 | https://tutorialspoint.dev/data-structure/binary-search-tree/bst-tree-sum-smaller-keys | CC-MAIN-2021-17 | refinedweb | 260 | 63.49 |
r prefix bug ... or my lack of understanding?
Discussion in 'Python' started by Bill Sneddon, debugging with asp.net (or lack thereof)=?Utf-8?B?dmJNZW50YWw=?=, Jan 3, 2005, in forum: ASP .Net
- Replies:
- 3
- Views:
- 545
- Daniel Fisher\(lennybacon\)
- Jan 4, 2005
lack of .NET project file on web serverkeith russell, Apr 11, 2005, in forum: ASP .Net
- Replies:
- 1
- Views:
- 392
- =?Utf-8?B?QnJhZCBSb2JlcnRz?=
- Apr 11, 2005
"static" prefix - to parallel "this" prefixTim Tyler, Dec 5, 2004, in forum: Java
- Replies:
- 36
- Views:
- 1,624
- Darryl L. Pierce
- Dec 10, 2004
removing a namespace prefix and removing all attributes not in that same prefixChris Chiasson, Nov 12, 2006, in forum: XML
- Replies:
- 6
- Views:
- 698
- Richard Tobin
- Nov 14, 2006
Do I lack understanding or arrays?, May 27, 2007, in forum: Ruby
- Replies:
- 4
- Views:
- 121 | http://www.thecodingforums.com/threads/r-prefix-bug-or-my-lack-of-understanding.327561/ | CC-MAIN-2015-22 | refinedweb | 139 | 68.06 |
Linux Shadow Password HOWTO
Michael H. Jackson, v1.3, 3 April 1996
This e-mail address is being protected from spambots. You need JavaScript enabled to view it
This document aims to describe how to obtain, install, and configure the Linux password Shadow Suite. It also discusses obtaining, and re]installing other software and network daemons that require access to user passwords. This other software is not actually part of the Shadow Suite, but these programs will need to be recompiled to support the Shadow Suite. This document also contains a programming example for adding shadow support to a program. Answers to some of the more frequently asked questions are included near the end of this document.
1. Introduction.
2. Why shadow your passwd file?
- 2.1 Why you might NOT want to shadow your passwd file.
- 2.2 Format of the /etc/passwd file
- 2.3 Format of the shadow file
- 2.4 Review of crypt(3).
3. Getting the Shadow Suite.
- 3.1 History of the Shadow Suite for Linux
- 3.2 Where to get the Shadow Suite.
- 3.3 What is included with the Shadow Suite.
4. Compiling the programs.
- 4.1 Unpacking the archive.
- 4.2 Configuring with the config.h file
- 4.3 Making backup copies of your original programs.
- 4.4 Running make
5. Installing
- 5.1 Have a boot disk handy in case you break anything.
- 5.2 Removing duplicate man pages
- 5.3 Running make install
- 5.4 Running pwconv
- 5.5 Renaming npasswd and nshadow
6. Other programs you may need to upgrade or patch
- 6.1 Slackware adduser program
- 6.2 The wu_ftpd Server
- 6.3 Standard ftpd
- 6.4 pop3d (Post Office Protocol 3)
- 6.5 xlock
- 6.6 xdm
- 6.7 sudo
- 6.8 imapd (E-Mail pine package])
- 6.9 pppd (Point-to-Point Protocol Server)
7. Putting the Shadow Suite to use.
- 7.1 Adding, Modifying, and deleting users
- 7.2 The passwd command and passwd aging.
- 7.3 The login.defs file.
- 7.4 Group passwords.
- 7.5 Consistency checking programs
- 7.6 Dial-up passwords.
8. Adding shadow support to a C program
- 8.1 Header files
- 8.2 libshadow.a library
- 8.3 Shadow Structure
- 8.4 Shadow Functions
- 8.5 Example
9. Frequently Asked Questions.
10. Copyright Message.
11. Miscellaneous and Acknowledgments.
1. Introduction.
This.
1.1 Changes from the previous release.
1.2 New versions of this document.,
< This e-mail address is being protected from spambots. You need JavaScript enabled to view it >. It will also be posted to the newsgroup:
comp.os.linux.answers
This document is now packaged with the Shadow-YYDDMM packages.
1.3 Feedback.
Please send any comments, updates, or suggestions to me: This e-mail address is being protected from spambots. You need JavaScript enabled to view it >'; document.write( '' ); document.write( addy_text48874 ); document.write( '<\/a>' ); //--> This e-mail address is being protected from spambots. You need JavaScript enabled to view it The sooner I get feedback, the sooner I can update and correct this document. If you find any problems with it, please mail me directly as I very rarely stay up-to-date on the newsgroups.
2. Why shadow your passwd file?
By, This e-mail address is being protected from spambots. You need JavaScript enabled to view it >'; document.write( '' ); document.write( addy_text55598 ); document.write( '<\/a>' ); //--> This e-mail address is being protected from spambots. You need JavaScript enabled to viewwdfile.wdfilewdfile first, they only need to encode the dictionary with the
saltvalues actually contained in your
/etc/passwdfile.wdfile also contains information like user ID's and group ID's that are used by many system programs. Therefore, the
/etc/passwdfile must remain world readable. If you were to change the
/etc/passwdfile so that nobody can read it, the first thing that you would notice is that the
ls -lcommand now displays user ID's instead of names!
The Shadow Suite solves the problem by relocating the passwords to another file (usually
/etc/shadow). The
/etc/shadowfile is set so that it cannot be read by just anyone. Only root will be able to read and write to the
/etc/shadowfile.file. Then the program can be run sgid shadow.
By moving the passwords to the
/etc/shadowfile, we are effectively keeping the attacker from having access to the encoded passwords with which to perform a dictionary attack.
Additionally, the Shadow Suite adds lots of other nice features:
- A configuration file to set login defaults (
/etc/login.defs)
- Utilities for adding, modifying, and deleting user accounts and groups
- Password aging and expiration
- Account expiration and locking
- Shadowed group passwords (optional)
- Double length passwords (16 character passwords) NOT RECOMMENDED]
- Better control over user's password selection
- Dial-up passwords
- Secondary authentication programs [NOT RECOMMENDED].
2.1 Why you might NOT want to shadow your passwd file.
There are a few circumstances and configurations in which installing the Shadow Suite would NOT be a good idea:
- The machine does not contain user accounts.
- Your machine is running on a LAN and is using NIS (Network Information Services) to get or supply user names and passwords to other machines on the network. (This can actually be done, but is beyond the scope of this document, and really won't increase security much anyway)
- Your machine is being used by terminal servers to verify users via NFS (Network File System), NIS, or some other method.
- Your machine runs other software that validates users, and there is no shadow version available, and you don't have the source code.
2.2 Format of the /etc/passwd file).
2.3 Format of the::::
2.4 Review of crypt(3). < This e-mail address is being protected from spambots. You need JavaScript enabled to view it > ISBN: 0-471-59756-2
3. Getting the Shadow Suite.
3.1 History of the Shadow Suite for Linux
DO This e-mail address is being protected from spambots. You need JavaScript enabled to view it >'; document.write( '' ); document.write( addy_text48342 ); document.write( '<\/a>' ); //--> This e-mail address is being protected from spambots. You need JavaScript enabled to view it and contains some further enhancements.
shadow-mkwas specifically packaged for Linux.
The
shadow-mk package contains the
shadow-3.3.1 package distributed by
John F.
Haugh II with the
shadow-3.3.1-2 patch
installed, a few fixes made by
This e-mail address is being protected from spambots. You need JavaScript enabled to view it
>';
document.write( '' );
document.write( addy_text48746 );
document.write( '<\/a>' );
//-->
This e-mail address is being protected from spambots. You need JavaScript enabled to view it)
3.2 Where to get the Shadow Suite.
The only recommended Shadow Suite is still in BETA
testing, however the latest versions are safe in a production
environment and don't contain a vulnerable
program.
The package uses the following naming convention:
wherewhere
shadow-YYMMDD.tar.gz
YYMMDDis the issue date of the Suite.
This version will eventually be Version 3.3.3 when it is released from Beta testing, and is maintained by This e-mail address is being protected from spambots. You need JavaScript enabled to view it >'; document.write( '' ); document.write( addy_text70923 ); document.write( '<\/a>' ); //--> This e-mail address is being protected from spambots. You need JavaScript enabled to view it . It's available as: shadow-current.tar.gz.
The following mirror sites have also been established:
-
-
-
-
You should use the currently available version.
You should NOT use a version older than
shadow-960129 as they also have the.
3.3 What is included with the Shadow Suite..
4. Compiling the programs.
4.1 Unpacking the archive.
The
4.2 Configuring with the config.h file.
4.3 Making backup copies of your original programs.
It would also be a good idea to track down and make backup copies of the programs that the shadow suite will replace. On a Slackware 3.0 system these are:
- /bin/su
- /bin/login
- /usr/bin/passwd
- /usr/bin/newgrp
- /usr/bin/chfn
- /usr/bin/chsh
- /usr/bin/id.
4.4 Running make.
5. Installing
5.1 Have a boot disk handy in case you break anything.
If something goes terribly wrong, it would be handy to have a boot disk. If you have a boot/root combination from your installation, that will work, otherwise see the Bootdisk-HOWTO, which describes how to make a bootable disk.
5.2 Removing duplicate man pages:
- /usr/man/man1/chfn.1.gz
- /usr/man/man1/chsh.1.gz
- /usr/man/man1/id.1.gz
- /usr/man/man1/login.1.gz
- /usr/man/man1/passwd.1.gz
- /usr/man/man1/su.1.gz
- /usr/man/man5/passwd.5.gz
There may also be man pages of the same name in the
/var/man/cat[1-9] subdirectories that should also be
deleted.
5.3 Running make install).
5.4 Running pwconv.
5.5 Renaming npasswd and nshadow.
6. Other programs you may need to upgrade or patch
Even).
6.1 Slackware adduser program
6.2 The wu_ftpd Server.
6.3 Standard ftpd
6.4 pop3d (Post Office Protocol 3).
6.5 xlock.
6.6 xdm.
6.7 sudo
6.9 pppd (Point-to-Point Protocol Server).
7. Putting the Shadow Suite to use.
This section discusses some of the things that you will want to know now that you have the Shadow Suite installed on your system. More information is contained in the manual pages for each command.
7.1 Adding, Modifying, and deleting users
The Shadow Suite added the following command line oriented
commands for adding, modifying, and deleting users. You may also
have installed the
adduser program.
useradd
The
useradd command can be used to add users to the
system. You also invoke this command to change the default
settings.
The first thing that you should do is to examine the default settings and make changes specific to your system:
useradd -D
GROUP=1 HOME=/home INACTIVE=0 EXPIRE=0 SHELL= SKEL=/etc/skel
The defaults are probably not what you want, so if you started adding users now you would have to specify all the information for each user. However, we can and should change the default values.
On my system:
- I want the default group to be 100
- I want passwords to expire every 60 days
- I don't want to lock an account because the password is expired
- I want to default shell to be
/bin/bash
useradd -D -g100 -e60 -f0 -s/bin/bash: *******
Now the
.
You should use the supplied commands rather than directly editing
/etc/passwd and
/etc/shadow. If you were
editing the
/etc/shadow file, and a user were to
change his password while you are editing, and then you were to
save the file you were editing, the user's password change would be
lost.
Here is a small interactive script that adds users using
useradd and
passwd:
#!/bin/bash # # /sbin/newuser - A script to add users to the system using the Shadow # Suite's useradd and passwd commands. # # Written my Mike Jackson < This e-mail address is being protected from spambots. You need JavaScript enabled to view it > as an example for the Linux # Shadow Password Howto. Permission to use and modify is expressly granted. # # This could be modified to show the defaults and allow modification similar # to the Slackware Adduser program. It could also be modified to disallow # stupid entries. (i.e. better error checking). # ## # Defaults for the useradd command ## GROUP=100 # Default Group HOME=/home # Home directory location (/home/username) SKEL=/etc/skel # Skeleton Directory INACTIVE=0 # Days after password expires to disable account (0=never) EXPIRE=60 # Days that a passwords lasts SHELL=/bin/bash # Default Shell (full path) ## # Defaults for the passwd command ## PASSMIN=0 # Days between password changes PASSWARN=14 # Days before password expires that a warning is given ## # Ensure that root is running the script. ## WHOAMI=`/usr/bin/whoami` if [ $WHOAMI != "root" ]; then echo "You must be root to add news users!" exit 1 fi ## # Ask for username and fullname. ## echo "" echo -n "Username: " read USERNAME echo -n "Full name: " read FULLNAME # echo "Adding user: $USERNAME." # # Note that the "" around $FULLNAME is required because this field is # almost always going to contain at least on space, and without the "'s # the useradd command would think that you we moving on to the next # parameter when it reached the SPACE character. # /usr/sbin/useradd -c"$FULLNAME" -d$HOME/$USERNAME -e$EXPIRE \ -f$INACTIVE -g$GROUP -m -k$SKEL -s$SHELL $USERNAME ## # Set password defaults ## /bin/passwd -n $PASSMIN -w $PASSWARN $USERNAME >/dev/null 2>&1 ## # Let the passwd command actually ask for password (twice) ## /bin/passwd $USERNAME ## # Show what was done. ## echo "" echo "Entry from /etc/passwd:" echo -n " " grep "$USERNAME:" /etc/passwd echo "Entry from /etc/shadow:" echo -n " " grep "$USERNAME:" /etc/shadow echo "Summary output of the passwd command:" echo -n " " passwd -S $USERNAME echo ""
Using a script to add new users is really much more preferable than
editing the
/etc/passwd or
/etc/shadow
files directly or using a program like the Slackware
adduser program. Feel free to use and modify this
script for your particular system.
For more information on the
useradd see the online
manual page.
usermod
The
usermod program is used to modify the information
on a user. The switches are similar to the
useradd
program.
Let's say that you want to change
fred's shell, you
would do the following::
fred:J0C.WDR1amIt6:9559:0:60:0:0:10119:0
For more information on the
usermod command see the
online manual page.
userdel
userdel does just what you would expect, it deletes
the user's account. You simply use:.
7.2 The passwd command and passwd aging.
The
passwd command has the obvious use of changing
passwords. Additionally, it is used by the root user to:
- Lock and unlock accounts (
-land
-u)
- Set the maximum number of days that a password remains valid (
-x)
- Set the minimum days between password changes (
-n)
- Sets the number of days of warning that a password is about to expire (
-w)
- Sets the number of days after the password expires before the account is locked (
-i)
- Allow viewing of account information in a clearer format (
.
This simply means that if
fred logs in after the
password expires, he will be prompted for a new password at login.
If we decide that we want to warn
fred 14 days before
his password expires and make his account inactive 14 days after he
lets it expire, we would need to do the following:
NowNow
passwd -w14 -i14 fred
fredis changed to:
For more information on theFor more information on the
fred P 03/04/96 0 60 14 14
passwdcommand see the online manual page.
7.3 The login.defs file.
The file
/etc/login is the configuration file for the
login program and also for the Shadow Suite
as a whole.
/etc/login contains settings from what the prompts
will look like to what the default expiration will be when a user
changes his password.
The
/etc/login.defs file is quite well documented just
by the comments that are contained within it. However, there are a
few things to note:
- It contains flags that can be turned on or off that determine the amount of logging that takes place.
- It contains pointers to other configuration files.
- It contains defaults assignments for things like password aging.
From the above list you can see that this is a rather important file, and you should make sure that it is present, and that the settings are what you desire for your system.
7.4 Group passwords.
The
/etc/groups file may contain passwords that permit
a user to become a member of a particular group. This function is
enabled if you define the constant
SHADOWGRP in the
/usr/src/shadow-YYMMDD/config.h file.
If you define this constant and then compile, you must create an
/etc/gshadow file to hold the group passwords and the
group administrator information.
When you created the
/etc/shadow, you used a program
called
pwconv, there no equivalent program to create
the
/etc/gshadow file, but it really doesn't matter,
it takes care of itself.
To create the initial
/etc/gshadow file do the
following:
touch /etc/gshadow chown root.root /etc/gshadow chmod 700 /etc/gshadow
Once you create new groups, they will be added to the
/etc/group and the
/etc/gshadow files. If
you modify a group by adding or removing users or changing the
group password, the
/etc/gshadow file will be changed.
The programs
groups,
groupadd,
groupmod, and
groupdel are provided as
part of the Shadow Suite to modify groups.
The format of the
/etc/group file is as follows:
Where:Where:
groupname:!:GID:member,member,...
groupname
The name of the group
!
The field that normally holds the password, but that is now relocated to the
/etc/gshadowfile..
The groups password can be changed using the
passwd
command by root or anyone listed as an administrator for
the group.
Despite the fact that there is not currently a manual page for
gpasswd, typing
gpasswd without any
parameters gives a listing of options. It's fairly easy to grasp
how it all works once you understand the file formats and the
concepts.
7.5 Consistency checking programs
pwck
The program
pwck is provided to provide a consistency
check on the
/etc/passwd and
/etc/shadow
files. It will check each username and verify that it has the
following:
- the correct number of fields
- unique user name
- valid user and group identifier
- valid primary group
- valid home directory
- valid login shell
It will also warn of any account that has no password.
It's a good idea to run
pwck after installing the
Shadow Suite. It's also a good idea to run it
periodically, perhaps weekly or monthly. If you use the
-r option, you can use
cron to run it on
a regular basis and have the report mailed to you.
grpck
grpck is the consistency checking program for the
/etc/group and
/etc/gshadow files. It
performs the following checks:
- the correct number of fields
- unique group name
- valid list of members and administrators
It also has the
-r option for automated reports.
7.6 Dial-up passwords.
Dial-up passwords are another optional line of defense for systems
that allow dial-in access. If you have a system that allows many
people to connect locally or via a network, but you want to limit
who can dial in and connect, then dial-up passwords are for you. To
enable dial-up passwords, you must edit the file
/etc/login.defs and ensure that
DIALUPS_CHECK_ENAB is set to
yes..
If a user logs into a line that is listed in
/etc/dialups, and his shell is listed in the file
/etc/d_passwd he will be allowed access only by
suppling the correct password.
Another useful purpose for using dial-up passwords might be to setup a line that only allows a certain type of connect (perhaps a PPP or UUCP connection). If a user tries to get another type of connection (i.e. a list of shells), he must know a password to use the line.
Before you can use the dial-up feature, you must create the files.
The command
dpasswd is provided to assign passwords to
the shells in the
/etc/d_passwd file. See the manual
page for more information.
8. Adding shadow support to a C program
Adding shadow support to a program is actually fairly
straightforward. The only problem is that the program must be run
by root (or SUID root) in order for the the program to be able to
access the
/etc/shadow file.
This presents one big problem: very careful programming practices must be followed when creating SUID programs. For instance, if a program has a shell escape, this must not occur as root if the program is SUID root.
For adding shadow support to a program so that it can check
passwords, but otherwise does need to run as root, it's a lot safer
to run the program SUID shadow instead. The
xlock
program is an example of this.
In the example given below,
pppd-1.2.1d already runs
SUID as root, so adding shadow support should not make the program
any more vulnerable.
8.1 Header files
The header files should reside in
/usr/include/shadow.
There should also be a
/usr/include/shadow.h, but it
will be a symbolic link to
/usr/include/shadow/shadow.h.
To add shadow support to a program, you need to include the header files:
#include <shadow/shadow.h> #include <shadow/pwauth.h>
It might be a good idea to use compiler directives to conditionally compile the shadow code (I do in the example below).
8.2 libshadow.a library
When you installed the Shadow Suite the
libshadow.a file was created and installed in
/usr/lib.
When compiling shadow support into a program, the linker needs to
be told to include the
libshadow.a library into the
link.
This is done by:
gcc program.c -o program -lshadow
However, as we will see in the example below, most large programs
use a
Makefile, and usually have a variable called
LIBS=... that we will modify.
8.3 Shadow Structure
The
libshadow.a library uses a structure called
spwd for the information it retrieves from the
/etc/shadow file. This is the definition of the
spwd structure from the
/usr/include/shadow/shadow.h header file:
struct spwd { char *sp_namp; /* login name */ char *sp_pwdp; /* encrypted password */ sptime sp_lstchg; /* date of last change */ sptime sp_min; /* minimum number of days between changes */ sptime sp_max; /* maximum number of days between changes */ sptime sp_warn; /* number of days of warning before password expires */ sptime sp_inact; /* number of days after password expires until the account becomes unusable. */ sptime sp_expire; /* days since 1/1/70 until account expires */ unsigned long sp_flag; /* reserved for future use */ };
The Shadow Suite can put things into the
sp_pwdp field besides just the encoded passwd. The
password field could contain:
username:Npge08pfz4wuk;@/sbin/extra:9479:0:10000::::
This means that in addition to the password, the program
/sbin/extra should be called for further
authentication. The program called will get passed the username and
a switch that indicates why it's being called. See the file
/usr/include/shadow/pwauth.h and the source code for
pwauth.c for more information.
What this means is that we should use the function
pwauth to perform the actual authentication, as it
will take care of the secondary authentication as well. The example
below does this.
The author of the Shadow Suite indicates that since most programs in existence don't do this, and that it may be removed or changed in future versions of the Shadow Suite.
8.4 Shadow Functions
The
shadow.h file also contains the function
prototypes for the functions contained in the
libshadow.a library:
extern void setspent __P ((void)); extern void endspent __P ((void)); extern struct spwd *sgetspent __P ((__const char *__string)); extern struct spwd *fgetspent __P ((FILE *__fp)); extern struct spwd *getspent __P ((void)); extern struct spwd *getspnam __P ((__const char *__name)); extern int putspent __P ((__const struct spwd *__sp, FILE *__fp));
The function that we are going to use in the example is:
getspnam which will retrieve for us a
spwd structure for the supplied name.
8.5 Example
This is an example of adding shadow support to a program that needs it, but does not have it by default.
This example uses the Point-to-Point Protocol Server
(pppd-1.2.1d), which has a mode in which it performs PAP
authentication using user names and passwords from the
/etc/passwd file instead of the PAP or
CHAP files. You would not need to add this code to
pppd-2.2.0 because it's already there.
This feature of pppd probably isn't used very much, but if you
installed the Shadow Suite, it won't work anymore because
the passwords are no longer stored in
/etc/passwd.
The code for authenticating users under
pppd-1.2.1d is
located in the
/usr/src/pppd-1.2.1d/pppd/auth.c file.
The following code needs to be added to the top of the file where
all the other
#include directives are. We have
surrounded the
#includes with conditional directives
(i.e. only include if we are compiling for shadow support).
#ifdef HAS_SHADOW #include <shadow.h> #include <shadow/pwauth.h> #endif
The next thing to do is to modify the actual code. We are still
making changes to the
auth.c file.
Function
auth.c before modifications:
/* * login - Check the user name and password against the system * password database, and login the user if OK. * * ((pw = getpwnam(user)) == NULL) { return (UPAP_AUTHNAK); } /* * XXX If no passwd, let them login without one. */ if (pw->pw_passwd == '\0') { return (UPAP_AUTHACK); } epasswd = crypt(passwd, pw->pw_passwd); if (strcmp(epasswd, pw->pw_passwd)) { return (UPAP_AUTHNAK); }); }
The user's password is placed into
pw->pw_passwd,
so all we really need to do is add the function
getspnam. This will put the password into
spwd->sp_pwdp.
We will add the function
pwauth to perform the actual
authentication. This will automatically perform secondary
authentication if the shadow file is setup for it.
Function
auth.c after modifications to support shadow:
/* * login - Check the user name and password against the system * password database, and login the user if OK. * * This function has been modified to support the Linux Shadow Password * Suite if USE_SHADOW is defined. * *def USE_SHADOW struct spwd *spwd; struct spwd *getspnam(); #endif if ((pw = getpwnam(user)) == NULL) { return (UPAP_AUTHNAK); } #ifdef USE_SHADOW spwd = getspnam(user); if (spwd) pw->pw_passwd = spwd->sp-pwdp; #endif /* * XXX If no passwd, let NOT them login without one. */ if (pw->pw_passwd == '\0') { return (UPAP_AUTHNAK); } #ifdef HAS_SHADOW if ((pw->pw_passwd && pw->pw_passwd[0] == '@' && pw_auth (pw->pw_passwd+1, pw->pw_name, PW_LOGIN, NULL)) || !valid (passwd, pw)) { return (UPAP_AUTHNAK); } #else epasswd = crypt(passwd, pw->pw_passwd); if (strcmp(epasswd, pw->pw_passwd)) { return (UPAP_AUTHNAK); } #endif); }
Careful examination will reveal that we made another change as
well. The original version allowed access (returned
UPAP_AUTHACK if there was NO password in the
/etc/passwd file. This is not good, because a
common use of this login feature is to use one account to allow
access to the PPP process and then check the username and password
supplied by PAP with the username in the
/etc/passwd
file and the password in the
/etc/shadow file.
So if we had set the original version up to run as the shell for a
user i.e.
ppp, then anyone could get a ppp connection
by setting their PAP to user
ppp and a password of
null.
We fixed this also by returning
UPAP_AUTHNAK instead
of
UPAP_AUTHACK if the password field was empty.
Interestingly enough,
pppd-2.2.0 has the same problem.
Next we need to modify the Makefile so that two things occur:
USE_SHADOW must be defined, and
libshadow.a needs to be added to the linking process.
Edit the Makefile, and add:
LIBS = -lshadow
Then we find the line:
COMPILE_FLAGS = -I.. -D_linux_=1 -DGIDSET_TYPE=gid_t
And change it to:
COMPILE_FLAGS = -I.. -D_linux_=1 -DGIDSET_TYPE=gid_t -DUSE_SHADOW
Now make and install.
9. Frequently Asked Questions.
Q::
This e-mail address is being protected from spambots. You need JavaScript enabled to view it.
10. Copyright Message..
11. Miscellaneous and Acknowledgments.
The code examples for
auth.c are taken from
pppd-1.2.1d and ppp-2.1.0e, Copyright (c) 1993 and The Australian
National University and Copyright (c) 1989 Carnegie Mellon
University.
Thanks to Marek Michalkiewicz < This e-mail address is being protected from spambots. You need JavaScript enabled to view it > for writing and maintaining the Shadow Suite for Linux, and for his review and comments on this document.
Thanks to Ron Tidd < This e-mail address is being protected from spambots. You need JavaScript enabled to view it > for his helpful review and testing.
Thanks to everyone who has sent me feedback to help improve this document.
Please, if you have any comments or suggestions then mail them to me.
regards
This e-mail address is being protected from spambots. You need JavaScript enabled to view it >'; document.write( '' ); document.write( addy_text14989 ); document.write( '<\/a>' ); //--> This e-mail address is being protected from spambots. You need JavaScript enabled to view it | https://www.linux.com/learn/docs/ldp/Shadow-Password-HOWTO | CC-MAIN-2014-10 | refinedweb | 4,758 | 66.33 |
19 January 2009 13:32 [Source: ICIS news]
By Nigel Davis
LONDON (ICIS news)--BASF issued a profits warning on Monday saying that the decline in business was greater than expected in November and would negatively affect earnings.
The world’s largest chemicals group said it would introduce short-time working for 1,680 employees at German facilities manufacturing products for the automotive industry.
Such arrangements could be implemented rapidly elsewhere in ?xml:namespace>
BASF said in November in a first warning on 2008 profits that it did not expect full year operating profits before special items (EBIT – earnings before interest and tax - before special items) to reach the 2007 level of €7.6bn ($10.1bn) against the backdrop of the sharp chemicals downturn.
December was not as good as expected in November, a company spokesman said.
The €58bn-turnover chemicals giant generated an operating profit of €6.3bn in the first nine months of the year, driven to a great extent by the high and rising oil price through much of the period.
“The situation remains tough and difficult to predict, CEO Jurgen Hambrecht said. “We do not expect the economic environment to improve in the coming months.”
Average capacity utilisation now is less that 75%, BASF said on Monday. Only demand for crop protection products and chemicals for the good industry remains high, it added.
It cut capacity utilisation at it six major global production sites in mid-November and said capacity utilisation was down between 20% and 25%.
In November 80 of its plants were idled and 100 operating at reduced rates. The downturn currently affects a similar number of units with 50 idled and 130 running at reduced capacity.
The new working arrangements would affect workers in
The company has used flexible working time arrangements, such as reduced overtime and holidays, to cope with the downturn but said these were no longer sufficient to absorb the affects of production cuts everywhere.
Agreements were already in place to allow the rapid introduction of short-time working in
In
Financial analysts at investment bank Cazenove said they were assuming a near 30% sales decline for BASF in its core Chemicals and Plastics businesses and a sharp margin decline.
BASF's shares dropped sharply on the news and were down 4.97% at €22.60 at 12:58GMT on Monday.
( | http://www.icis.com/Articles/2009/01/19/9186043/BASF-issues-profits-warning-introduces-short-time-working.html | CC-MAIN-2014-52 | refinedweb | 391 | 52.39 |
Across Python’s many visualisation libraries, you will find several ways to create scatter plots. Matplotlib, being one of the fundamental visualisation libraries, offers perhaps the simplest way to do so. In one line, we will be able to create scatter plots that show the relationship between two variables. It also offers easy ways to customise these charts, through adding crosshairs, text, colour and more.
This article will plot goals for and against from a season, taking you through the initial creation of the chart, then some customisation that Matplotlib offers. Import the modules and data and off we go.
import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline
table = pd.read_csv("../../Data/1617table.csv") table.head()
Nothing exceptional about our table here. We have exactly the data that we would expect and we are going to plot goals for (GF) and goals against (GA).
Matplotlib’s ‘.plot()’ will make this incredibly easy. We just need to pass it three arguments: the data to plot along each of the axes and the plot type. In this case, the plot type is ‘o’ to show that we want to plot markers. Let’s see what the default chart looks like:
plt.plot(table['GF'],table['GA'],"o")
[<matplotlib.lines.Line2D at 0x2488736de10>]
It is quite plain and has no labels, but you can see just how easy it is to do. It is almost just as easy to add some tiles.
Rather than directly plot the chart, we can create our chart area with the first line below, set its size, then add our features from there. Take a look:
#Create plot area fig, ax = plt.subplots() #Set plot size fig.set_size_inches(7, 5) #Plot chart as above, but change the plot type from 'o' to '*' - givng us stars! plt.plot(table['GF'],table['GA'],"*") #Add labels to chart area ax.set_title("Goals for & Against") ax.set_xlabel("Goals For") ax.set_ylabel("Goals Against") #Display the chart plt.show()
Great work! Just a few lines of code make a massive difference to our charts.
This time, let’s add a crosshair to our chart to display the average line. This should help our viewers to see if a point is performing well or not.
To do this, we can use ‘plt.plot()’ again. Once again, we give it 3 arguments as a minimum:
- Type – ‘k-‘ gives us two instructions to plot with. K means black, – means draw a line
- Start/End X locations – Give these two coordinates in a list. In the example below, we calculate the average to get the coordinate.
- Start/End Y locations – Once again, give these coordinates in a list. Below they are [90,20]
We also give two optional arguments. Linestyle changes the line, in this case “:” gives us a dotted line. Meanwhile, lw dictates the line width.") plt.show()
In our chart above, the crosshairs show the averages and it helps us to group teams accordingly. You may want to classify these quadrants with text on the chart and we add this in a similar way to titles.
Rather than ‘.set_title()’, we instead use ‘.text()’. You must give arguments for the x and y location, in addition to the text that you want to write. Our examples below also give information on the colour and size of the text. Take a look at how this comes up:") ax.text(18,90,"Poor attack, poor defense",color="red",size="8") ax.text(67,20,"Strong attack, strong defense",color="red",size="8") plt.show()
Summary
Head back and compare this last chart with the first one. Not only is the most recent one much, much better looking, it also is much more informative. Simple titles tell us what we are looking at, while crosshairs and text give insight.
This article illustrated the versatility of matplotlib and ‘.plot()’ being able to quickly draw charts and add detail to them. You can see above how we set up a chart area, than draw our chart and additional features. Take a look at the documentation for all of the customisations that you can add with matplotlib.
Create your own scatter plots and crosshair features, and check out some of the other visualisation options Matplotlib offers. | https://fcpython.com/visualisation/scatter-plots-crosshairs-in-matplotlib | CC-MAIN-2018-51 | refinedweb | 711 | 75.61 |
Logging With SLF4J
Logging With SLF4J
Learn how to use the Simple Logging Facade for Java (SLF4J) in your applications.
Join the DZone community and get the full member experience.Join For Free
Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.
The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks. It allows you to code while depending on just one dependency, namely "slf4j-api.jar", and to plug in the desired logging framework at runtime. It is very simple to use slf4 logging in your application. You just need to create a slf4j logger and invoke its methods.
Following is a sample code,
package com.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main { private static final Logger logger = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { logger.info("Testing 123"); } }
You have to add the following dependency in your pom.xml file
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.13</version> </dependency>
This is the bare minimum configuration you need to enable sl4fj logging. But if you run this code. you will get a warning similar to the below.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See for further details.
This is because, it can't find a binding in the class path, by default, if it can't find a binding in the class path, it will bind to no-op logger implementation.
Using java.util.logging
If you want to use the binding for java.util.logging in your code, you only need to add the following dependency in to your pom.file.
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-jdk14</artifactId> <version>1.7.13</version> </dependency>
This will output the following,
INFO: Testing 123
Using Log4j
If you want to use the binding for log4j version 1.2 in your code, you only need to add the following dependency in to your pom.file.
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.13</version> </dependency>
Log4j needs an appender to log. Hence, you have to specify the log4j properties.
Create the file "log4j.properties", in resource directory of your project and add the following into it.
# Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=DEBUG,
This will output the following,
0 [main] INFO com.test.Main - Testing 123
[1]
[2]
Connect any Java based application to your SaaS data. Over 100+ Java-based data source connectors.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/logging-with-slf4j | CC-MAIN-2019-04 | refinedweb | 456 | 52.46 |
Multithreading has always impressed me. Being able to do lots of things at once is really impressive, but we can�t do this if we don�t have the proper hardware. Till now, all we could do is separate the hard CPU work in a background thread and thus leave the user interface unblocked. I wanted to go further than this, exploiting the newest capabilities of new CPUs (at user�s hands) and try to get a real working multithreading example, that is, with more than one thread running in the background.
That is what this article is all about, and have to say, that the results have impressed me. Hope you will find it interesting. Well, in a multi cpu server with 4 CPU�s the benefits are of 280% (in a cpu-intensive job) and on normal machines with non-cpu intensive jobs it can go from 500% to 1000% in performance improvements�
There are a lot of introductory articles to multithreading for .Net 2.0 and, have to say, they have helped me a lot. What I have used is the BackgroundWorker .Net 2.0 component (but there are code implementations for it on Net 1.1 that do the job.Here I put some links to these articles:
Well these are must read articles if you�re new to the threading world or if you�re not but want to get updated with the new Net 2.0�s BackgroundWorker component..
Any kind of problem� being it a processor intensive or a normal task:
Let�s say that if the problem is building the blocks of a web site page, instead of doing these sequentially , taking 1-4 seconds into having all the sections built; the banner, the users online, the last articles, the most voted tools, etc� what if we could build all of these asynchronously and when they�re built up send them to the user? We will save the webservice calls, the database calls and a lot of other precious time� and more on! These calls would be serviced faster and that would mean that the possibilities of coinciding the calls would be reduced, increasing the response times substantially. Interesting?
It is called BackgroundWorker and for our intentions we will subclass it. Background worker helps us to set-up a �Worker� for doing a work in an asynchronous way.
What we want to do is set up a Factory (oops, no design patterns meaning here) where one kind of job will be done, that will mean thaw we will have a kind of job, some process, and some workers that know how to do this job.
Of course, we will need a manager for assigning the jobs to the workers and what to do when they reach a step of the job and when they finish it. And yes, also we want the manager to be able to speak to the workers to stop. They have to take a rest too! And when the manager says so, they must stop!
We will explain thins from bottom to top, beginning from the Worker and then we will see the Manager.
It is a subclass of the
Background worker, we set up the constructor to assign to true two properties of
BackgroundWorker that are
WorkerReportsProgress and
WorkerSupportsCancellation which will enable us to do what the names say, report progress, normally to an UI and cancel the job (and subsequently all jobs) if they take too long. We also assign a id number to each worker. The manager needs to control them, though. Here�s the code:
public class MTWorker : BackgroundWorker { #region Private members private int _idxLWorker = 0; #endregion #region Properties public int IdxLWorker { get { return _idxLWorker; } set { _idxLWorker = value; } } #endregion #region Constructor public MTWorker() { WorkerReportsProgress = true; WorkerSupportsCancellation = true; } public MTWorker(int idxWorker) : this() { _idxLWorker = idxWorker; } #endregion
Also, we will override another of the
BackgroundWorker�s methods. In fact the most interesting one, which does the real Job. And it means it. It�s name is
OnDoWork and it is the method that is called when we invoke or launch the multithreaded task. Here we manage the start-up of the task, its progress, its cancellation and its completion. I have added two possible jobs to do, one �Normal� that emulates with delay�s the waiting time of a non cpu-inensive task with has to ask and wait for filesystem, network, database or webservices calls� and other which is a CPU intensive Job: Calculating the PI number. You can play with it and see the results of giving more or less delay and increasing the thread�s number (Oops, I meant the worker�s numbers�).
Here is the
OnDoWork code:
protected override void OnDoWork(DoWorkEventArgs e) { //Here we receive the necessary data for doing the work... //we get an int but it could be a struct, class, whatever.. int digits = (int)e.Argument; double tmpProgress = 0; int Progress = 0; String pi = "3"; // This method will run on a thread other than the UI thread. // Be sure not to manipulate any Windows Forms controls created // on the UI thread from this method. this.ReportProgress(0, pi); //Here we tell the manager that we start the job.. Boolean bJobFinished = false; int percentCompleteCalc = 0; String TypeOfProcess = "NORMAL"; //Change to "PI" for a cpu intensive task //Initialize calculations while (!bJobFinished) { if (TypeOfProcess == "NORMAL") { #region Normal Process simulation, putting a time delay to emulate a wait-for-something while (!bJobFinished) { if (CancellationPending) { e.Cancel = true; return; //break } //Perform another calculation step Thread.Sleep(250); percentCompleteCalc = percentCompleteCalc + 10; if (percentCompleteCalc >= 100) bJobFinished = true; else ReportProgress(percentCompleteCalc, pi); } #endregion } else { #region Pi Calculation - CPU intensive job, beware of it if not using threading ;) !! //PI Calculation tmpProgress = (i + digitCount); tmpProgress = (tmpProgress / digits); tmpProgress = tmpProgress * 100; Progress = Convert.ToInt32(tmpProgress); ReportProgress(Progress, pi); // Deal with possible cancellation if (CancellationPending) //If the manager says to stop, do so.. { bJobFinished = true; e.Cancel = true; return; } } } bJobFinished = true; #endregion } } ReportProgress(100, pi); //Last job report to the manager ;) e.Result = pi; //Here we pass the final result of the Job }
Here is what has more fun and I am pretty sure that it can be improved a lot � any comment or improvement are welcome! What it does is to generate and configure a Worker for each Thread and then it assigns the jobs to them. By now the only parameter it passes to the worker is a number, but it could pass a class or struct with all the job definition� A possible upgrade would be to implement a strategy pattern here for choosing how to do the internal job.
Well we then call the
InitManager which configures the jobs, its number, the specs of the jobs to do and then creates an array of MultiThread Workers and configures them. The configuration code follows.
private void ConfigureWorker(MTWorker MTW) { //We associate the events of the worker MTW.ProgressChanged += MTWorker_ProgressChanged; MTW.RunWorkerCompleted += MTWorker_RunWorkerCompleted; }
Like this, the Worker�s subclassed thread management Methods are linked to the Methods held by the Manager. Note that with a Strategy pattern implemented we could assign these to the proper manager for these methods.
Then we have the most important method, the
AssignWorkers. What it does is to check all the workers and if there is anyone that is not working it assigns a job to it. That is, if there are jobs left to process. When it finishes checking workers, if we found that there is no worker working (and thus we have not assigned any job too) that will mean the end of the jobs. No more to do, all thing�s done!
Here�s the code:
public void AssignWorkers() { Boolean ThereAreWorkersWorking = false; //We check all workers that are not doing a job... and assign a new one foreach (MTWorker W in _arrLWorker) { if (W.IsBusy == false) { //If there are still jobs to be done... //we assign the job to the free worker if (_iNumJobs > _LastSentThread) { //We control the threads associated to a worker //(not meaning the jobs done) just 4 control. _LastSentThread = _LastSentThread + 1; W.JobId = _LastSentThread; //We assign the job number.. W.RunWorkerAsync(_iPiNumbers); //We pass the parameters for the job. ThereAreWorkersWorking = true; //We have at least this worker we just assigned the job working.. } } else { ThereAreWorkersWorking = true; } } if (ThereAreWorkersWorking == false) { //This means that no worker is working and no job has been assigned. //this means that the full package of jobs has finished //We could do something here... Button BtnStart = (Button)FormManager.Controls["btnStart"]; Button BtnCancel = (Button)FormManager.Controls["btnCancel"]; BtnStart.Enabled = true; BtnCancel.Enabled = false; MessageBox.Show("Hi, I'm the manager to the boss (user): " + "All Jobs have finished, boss!!"); } }
We call this method whenever a job is finished. This way it ensures the completion of all jobs.
We also link the form through a property of this class so we can associate it to any form we want. Well we could want to link it to another class, but this is the most normal thing to do.
Well� improving it we could get a
BackgroundManager for all our application needs..
Last but not less important, we link all this to a form. The code is minimal and it�s pretty simple: we add a reference to the Manager, we configure it on the form�s constructor and on a start button we call the Manager�s
LaunchManagedProcess.
private MTManager LM; public Form1() { InitializeComponent(); LM = new MTManager(this, 25); LM.InitManager(); } private void btnStart_Click(object sender, EventArgs e) { btnStart.Enabled = false; btnCancel.Enabled = true; LM.LaunchManagedProcess(); } private void btnCancel_Click(object sender, EventArgs e) { LM.StopManagedProcess(); btnCancel.Enabled = false; btnStart.Enabled = true; }
This is the funniest part, changing the properties of how many threads to run simultaneously and how many Jobs to be processed and then try it on different CPU�s� ah, and of course, change the calculation method from a CPU-intensive task to a normal task with a operation delay...
I would love to know your results and what have you done with this, any feedback would be great!!
This is not done! It could be a MultiThreadJob Framework if there is being done the following:
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/threads/RealMultiThreading.aspx | crawl-002 | refinedweb | 1,699 | 62.68 |
Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
There’s no doubt that PowerShell is full of punctuation, and much of it has a different meaning in the help files than it does in the shell itself. Here’s what it all means within the shell:
` (backtick)—This is PowerShell’s escape character. It removes the special meaning of any character that follows it. For example, a space is normally a separator, which is why cd c:\Program Files generates an error. Escaping the space, cd c:\Program` Files, removes that special meaning and forces the space to be treated as a literal, so the command works.
~ (tilde)—When used as part of a path, this represents the current user’s home directory, as defined in the UserProfile environment variable.
( ) (parentheses)—These are used in a couple of ways:
Just as in math, parentheses define an order of execution. PowerShell will execute parenthetical commands first, from the innermost parentheses to the outermost. This is a good way to run a command and have its output feed the parameter of another command: Get-Service -computerName (Get-Content c:\computernames.txt)
Parentheses also enclose the parameters of a method, and they must be included even if the method doesn’t require any parameters: ChangeStartMode('Automatic'), for example, or Delete().
[ ] (square brackets)—These have two main uses in the shell:
They contain the index number when you want to refer to a single object within an array or collection: $services[2] gets the third object from $services (indexes are always zero-based).
They contain a data type when you’re casting a piece of data as a specific type. For example, $myresult / 3 -as [int] casts the result as a whole number (integer), and [xml]$data = Get-Content data.xml will read the contents of Data.xml and attempt to parse it as a valid XML document.
{ } (curly braces or curly brackets)—These have three uses:
They contain blocks of executable code or commands, called script blocks. These are often fed to parameters that expect a script block or a filter block: Get-Service | Where-Object { $_.Status -eq 'Running' }
They contain the key-value pairs that make up a new hashtable. The opening brace is always preceded by an @ sign. Notice that in this example I’m using braces both to enclose the hashtable key-value pairs (of which there are two) and to enclose an expression script block, which is the value for the second key, “e”:
$hashtable = @{l='Label';e={expression}}
When a variable name contains spaces, braces must surround the name: ${My Variable}
' ' (single quotation marks)—These contain string values. PowerShell doesn’t look for the escape character, nor does it look for variables, inside single quotes.
" " (double quotation marks)—These contain string values. PowerShell looks for escape characters and the $ character inside double quotes. Escape characters are processed, and the characters following a $ symbol (up to the next white space) are taken as a variable name and the contents of that variable are substituted. For example, if the variable $one contains the value World, then $two = "Hello $one `n" will contain Hello World and a carriage return (`n is a carriage return).
$ (dollar sign)—This character tells the shell that the following characters, up to the next white space, represent a variable name. This can be tricky when working with cmdlets that manage variables. Supposing that $one contains the value two, then New-Variable -name $one -value 'Hello' will create a new variable named two, with the value Hello, because the dollar sign tells the shell that you want to use the contents of $one. New-Variable -name one -value 'Hello' would create a new variable $one.
% (percent sign)—This is an alias for the ForEach-Object cmdlet.
? (question mark)—This is an alias for the Where-Object cmdlet.
> (right angle bracket)—This is a sort of alias for the Out-File cmdlet. It’s not technically a true alias, but it does provide for Cmd.exe-style file redirection: dir > files.txt.
+ - * / (math operators)—These function as standard arithmetic operators. Note that + is also used for string concatenation.
- (dash or hyphen)—This precedes both parameter names and operators, such as -computerName or -eq. It also separates the verb and noun components of a cmdlet name, as in Get-Content, and serves as the subtraction arithmetic operator.
@ (at sign)—This has four uses in the shell:
It precedes a hashtable’s opening curly brace (see curly braces, above).
When used before parentheses, it encloses a comma-separated list of values that form an array: $array = @(1,2,3,4). But both the @ sign and the parentheses are optional, because the shell will normally treat any comma-separated list as an array anyway.
It denotes a here-string, which is a block of literal string text. A here-string starts with @" and ends with "@, and the closing mark must be on the beginning of a new line. Run help about_quoting_rules for more information and examples. Here-strings can also be defined using single quotes.
It is PowerShell’s splat operator. If you construct a hashtable where the keys match parameter names, and those values’ keys are the parameters’ values, then you can splat the hashtable to a cmdlet. The B# .NET Blog has a “Windows PowerShell 2.0 Feature Focus—Splat, Split and Join” article that provides a good example of splatting ().
& (ampersand)—This is PowerShell’s invocation operator, instructing the shell to treat something as a command and to run it. For example, $a = "Dir" places the string "Dir" into the variable $a; & $a will run the Dir command.
; (semicolon)—This is used to separate two independent PowerShell commands that are included on a single line: Dir ; Get-Process will run Dir and then Get-Process. The results are sent to a single pipeline, but the results of Dir aren’t piped to Get-Process.
# (pound sign or hash mark)—This is used as a comment character. Any characters following #, to the next carriage return, are ignored by the shell. The angle brackets, < and >, are used as part of the tags that define a block comment: Use <# to start a block comment, and #> to end one. Everything within the block comment will be ignored by the shell.
= (equal sign)—This is the assignment operator, used to assign a value to a variable: $one = 1. It isn’t used for quality comparisons; use -eq instead. Note that the equal sign can be used in conjunction with a math operator: $var +=5 will add 5 to whatever is currently in $var.
| (pipe)—The pipe is used to convey the output of one cmdlet to the input of another. The second cmdlet (the one receiving the output) uses pipeline parameter binding to determine which parameter or parameters will actually receive the piped-in objects. Chapter 7 has a discussion of this process.
\ or / (backslash or slash)—A forward slash is used as a division operator in mathematical expressions; either the forward slash or backslash can be used as a path separator in file paths: C:\Windows is the same as C:/Windows. The backslash is also used as an escape character in WMI filter criteria and in regular expressions.
. (period)—The period has three main uses:
It’s used to indicate that you want to access a member, such as a property or method, or an object: $_.Status will access the Status property of whatever object is in the $_ placeholder.
It’s used to dot source a script, meaning that the script will be run within the current scope, and anything defined by that script will remain defined after the script completes, for example, c:\myscript.ps1.
Two dots (..) form the range operator, which is discussed later in this chapter. You will also see two dots used to refer to the parent folder in the filesystem, such as in the path ..\.
, (comma)—Outside of quotation marks, the comma separates the items in a list or array: "One",2,"Three",4. It can be used to pass multiple static values to a parameter that can accept them: Get-Process -computername Server1, Server2,Server3.
: (colon)—The colon (technically, two colons) is used to access static members of a class; this gets into .NET Framework programming concepts. [date-time]::now is an example (although you could achieve that same task by running Get-Date).
! (exclamation point)—This is an alias for the -not Boolean operator. | http://my.safaribooksonline.com/book/-/9781617290213/powershell-cheat-sheet/ch28lev1sec1 | CC-MAIN-2014-15 | refinedweb | 1,422 | 62.48 |
D Programming/First Program Examples< D Programming
To be completed.
Contents
Structure of a D programEdit
Every program must have a starting point. In D, this is the function named main except for Windows GUI programs which uses WinMain. You must have one of these functions to create a runnable application.
Note:
- Even though this function is the starting point for the program processing flow, it is possible to have other parts of your code execute before main is given control. These are module and class constructors, and will be discussed later.
- A collection of one or more modules that do not have a main function is known as a library and is not an executable program. Instead, the functions in libraries are used by applications as pre-written functionality.
Simple D ProgramsEdit
Note:
- The main function, in the D programming language, must return either void or int data type. This return value is returned to the operating system.
- If void return type is specified, the application returns an int with the value 0, otherwise the program must supply a return value.
- The main function, in the D programming language, must specify either no arguments or a single argument in the form char[][], which is an array of UTF8 strings that contain the command line parameters.
In summary, the main function can take one of four formats ...
int main() // Application defined return value, ignores command line
int main(char[][] args) // Application defined return value, uses command line
void main() // returns 0, ignores command line
void main(char[][] args) //returns 0, uses command line
Example 1Edit
import std.stdio; void main() { writefln("Hello World!"); }
This program merely prints "Hello World!" on the console, followed by a newline and then exits. The first line imports the standard library module std.stdio. This module defines the function writefln, which is used to write to the standard output. This program does not use the command line arguments and will return zero to the operating system.
You need to compile this to convert it to an executable program. First you save the source code to a text file that has the ".d" extension. Assuming we called this file hw.d, here is the way to compile it using the DigitalMars compiler ...
dmd hw.d
Example 2Edit
import std.stdio; void main(char[][] p_Args) { foreach(char[] l_Arg; p_Args) { writefln("Argument '%s'", l_Arg); } }
This program prints out each of the command line parameters. The argument to main is
char[][] p_Args
which names the argument as p_Args and declares its data type as char[][], which is a variable-length array of UTF8 strings. This is saying that main is passed a set of zero or more character strings.
The foreach statement is a way to process each of the elements in an array. In the format above, it names a temporary variable l_Arg that will receive each element in turn as the foreach moves through the array p_Args. The temporary variable is scoped to the foreach block and thus cannot be seen by code outside the foreach.
The writefln function not only writes out things to the console, it also allows you to format that output. The %s is a formating code that specifies where a subsequent argument will appear in the console output. In this case, if l_Arg contains "abc" then the output will be "Argument 'abc'".
Example 3Edit
This heavily annotated example highlights many of the enhancements over C++.
#!/usr/bin/dmd -run /* sh style script syntax is supported! */ /* Hello World in D To compile: dmd hello.d or to optimize: dmd -O -inline -release hello.d or to get generated documentation: dmd hello.d -D */ import std.stdio; // References to commonly used I/O routines. void main(char[][] args) // 'void' here means return 0 by default. { // Write-Formatted-Line writefln("Hello World, " // automatic concatenation of string literals "Reloaded"); // Strings are denoted as a dynamic array of chars 'char[]' // auto type inference and built-in foreach foreach(argc, argv; args) { // OOP is supported, of course! And automatic type inference. auto cl = new CmdLin(argc, argv); // 'writefln' is the improved 'printf' !! // user-defined class properties. writefln(cl.argnum, cl.suffix, " arg: %s", cl.argv); // Garbage Collection or explicit memory management - your choice!!! delete cl; } // Nested structs, classes and functions! struct specs { // all vars. automatically initialized int count, allocated; } // Note that declarations read right-to-left. // So that 'char[][]' reads as an array of an array of chars. specs argspecs(char[][] args) // Optional (built-in) function contracts. in{ assert (args.length > 0); // assert built in } out(result){ assert(result.count == CmdLin.total); assert(result.allocated > 0); } body{ specs* s = new specs; // no need for '->' s.count = args.length; // The 'length' property is number of elements. s.allocated = typeof(args).sizeof; // built-in properties for native types foreach(argv; args) s.allocated += argv.length * typeof(argv[0]).sizeof; return *s; } // built-in string and common string operations, e.g. '~' is concatenate. char[] argcmsg = "argc = %d"; char[] allocmsg = "allocated = %d"; writefln(argcmsg ~ ", " ~ allocmsg, argspecs(args).count,argspecs(args).allocated); } /** Stores a single command line argument. */ class CmdLin { private { int _argc; char[] _argv; static uint _totalc; } public: /************ Object constructor. params: argc = ordinal count of this argument. argv = text of the parameter *********/ this(int argc, char[] argv) { _argc = argc + 1; _argv = argv; _totalc++; } ~this() /// Object destructor { // Doesn't actually do anything for this example. } int argnum() /// A property that returns arg number { return _argc; } char[] argv() /// A property that returns arg text { return _argv; } wchar[] suffix() /// A property that returns ordinal suffix { wchar[] suffix; // Built in Unicode strings (utf8,utf16, utf32) switch(_argc) { case 1: suffix = "st"; break; case 2: suffix = "nd"; break; case 3: suffix = "rd"; break; default: // 'default' is mandatory with "-w" compile switch. suffix = "th"; } return suffix; } /* ************** * A property of the whole class, not just an instance. * returns: The total number of commandline args added. *************/ static typeof(_totalc) total() { return _totalc; } // Class invariant, things that must be true after any method is run. invariant { assert(_argc > 0); assert(_totalc >= _argc); } } | https://en.m.wikibooks.org/wiki/D_Programming/First_Program_Examples | CC-MAIN-2017-30 | refinedweb | 1,001 | 57.77 |
I wanted to write a piece of code in C for my Stellaris launchpad just to turn on the onboard LED by keeping the library usage to minimum. To my surprise, the compiled code was around 800 bytes in size. So to check what was put in to the compiled code by the compiler, I checked the assembly code using a dissambler. It had a lot of code which I didn't write the C code for. I would like to know what those codes are for and how did it enter the compiler setting. I am trying to learn how a compiler behaves and what behind-the-scenes things the compiler is doing. Please help me.
This is my C program:
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/rom.h"
#include "driverlib/sysctl.h"
#define GPIOFBASE 0x40025000
#define GPIOCLK *((volatile unsigned long *)(0x400FE000 + 0x608))
#define FDIR *((volatile unsigned long *)(GPIOFBASE + 0x400))
#define FDEN *((volatile unsigned long *)(GPIOFBASE + 0x51C))
#define FDATA *((volatile unsigned long *)(GPIOFBASE + 0x3FF))
void main(void) {
ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN);
GPIOCLK |= (1<<5);
FDIR |= 0xE;
FDEN |= 0xE;
FDATA |= 0xE;
while (1);
}
The only API call I used was to set the Clock setting using a Onchip ROM library. Please check the dissambly code at this pastebin: (The main: is at 0x190.)
The additional code will be CPU initialisation and C runtime initialisation. The source code for this start-up is probably provided with your compiler. In GCC for example it is normally called crt0.s
Depending on your CPU and memory it will probably require some initialisation to set the correct clock frequency, memory timing etc. On top of that the C runtime requires static data initialisation and stack initialisation. If C++ is supported additional code is necessary to call the constructors of any static objects.
Cortex-M devices like Stellaris are designed to run C code with minimum overhead, and it is possible to essentially start C code from reset, however the default start-up state is often not what you want to run your application is since for example this is likley to run at a lower and less accurate clock frequency.
Added 06Dec2012:
Your start-up code is almost certainly provided by the CMSIS. The CMSIS folder will contain CoreSupport and DeviceSupport folders containing start-up code. You can copy this code (or the relevant parts of it) to your project, modify it as necessary and link it in place of the provided code. The CMSIS is frequently updated, so there is an argument for doing that in any case.
Your build log and/or map file are useful for determine which CMSIS components are linked. | http://m.dlxedu.com/m/askdetail/3/c6a0e68e4f6715d180571c30f6feeab9.html | CC-MAIN-2019-18 | refinedweb | 446 | 62.68 |
01-27-2017 01:19 AM - edited 01-27-2017 01:27 AM
Hi everyone!
So a reeeally long story short (I can gladly expand upon request) - I added the hbase service, did hbase hbck immediately after this and it already detected one inconsistency:
ERROR: Region { meta => hbase:namespace,,1485505125654.b972bf2653eaa96104d6034591386a60.,
hdfs => null, deployed => hadoop-34.xxxzzz.de,60020,1485505116059;hbase:namespace,,
1485505125654.b972bf2653eaa96104d6034591386a60., replicaId => 0 }
found in META, but not in HDFS, and deployed on hadoop-34.xxxzzz.de,60020,1485505116059
When I do hbase hbck -repairHoles the inconsistency is gone, BUT... so is my hbase:namespace table.
hbase(main):001:0> scan 'hbase:namespace' ROW COLUMN+CELL ERROR: Unknown table hbase:namespace!
Interestingly enough, not gone from HDFS:
hdfs dfs -ls /hbase/data/hbase Found 2 items drwxr-xr-x - hbase hbase 0 2017-01-27 09:18 /hbase/data/hbase/meta drwxr-xr-x - hbase hbase 0 2017-01-27 09:18 /hbase/data/hbase/namespace
...nor from the the zookeeper:
[zk: localhost:2181(CONNECTED) 2] ls /hbase/table [hbase:meta, hbase:namespace]
...and an interesting side effect is that create_namespace function of the hbase shell is now gone:
hbase(main):003:0> create_namespace 'ns1' ERROR: Unknown table ns1!
I did find this ray of hope: HBASE-16294 and this is actually included in latest CDH (I am running 5.9.0 btw).
But!
This seems to concern only replicas. This is the patch code btw:
if (hbi.getReplicaId() == HRegionInfo.DEFAULT_REPLICA_ID) { // Log warning only for default/ primary replica with no region dir LOG.warn("No HDFS region dir found: " + hbi + " meta=" + hbi.metaEntry); }
I have replication disabled, and as one can see from the error message:
replicaId => 0
Now, I would have let this slide, but the real problem is that over time I get a huge number of these inconsistencies and attempt to fix them results in not being able to find tables from hbase shell.
Any ideas would be greatly appreciated!
01-31-2017 08:15 AM
Just a quick update, the issue is still present after upgrading to CDH 5.10.0, so... if you sort of had an idea, but were kind of shy or thought "naaaaah, he probably already thought of that", I strongly encourage you to step forward :)
02-01-2017 11:25 AM
Here's what i suspect happened, will call out supposition.
when you start the hbase service, first the master starts up, finds the meta region in hdfs, waits for the regionserver list to settle, and then assigns meta.
then it onlines all regions defined in meta (including hbase:namespace) in the case of initial startup it would make sense to me that it would online with the namespace configured and then flush to disk. (supposition)
if you do a hbck after meta is online, but before it can flush the namespace it will find them as holes. This is because hbck can only do guesswork based on the current state of HDFS or regionserver or zookeeper.
ALL hbck operations except for hbck and hbck -fixAssignments are dangerous. and fixAssignments isn't always perfect at fixing assignments but unless there is another bug encountered, it is not destructive.
what -repairHoles does is create an EMPTY region in the place of the region that was now gone. This is so that you can at least salvage what is left in the case of a disaster.
It's possible that hbase then sees that the namespace regionfile exists and then will not flush the namespace table. (supposition)
I'd suggest just removing and then re-adding the hbase service (and delete the remnants in hdfs and zookeeper in between those two steps if need be)
02-03-2017 05:45 AM
Hi Ben,
Thanks for your response, much appreciated!
Actually, that is exactly what I did. I messed it up so bad that I had to delete the service. All I described above actually happened after I:
1. Stopped service
2. Deleted the service
3. hdfs -rm -r /hbase
4. echo "rmr /hbase" | zookeeper-client
5. added the service again
At this time incosistencies are piling up, I have 34 of them, and the one described above, found in the namespace table is still there.
02-03-2017 09:28 AM
very interesting!
So hbck says it's in Hbase META but not in HDFS? perhaps there is a HDFS permissions issue for the hbase user? (assumption being that hbase is able to start, but not write the data it needs to HDFS, yet somehow still lives enough to stay running in that weird state.)
02-06-2017 02:52 AM - edited 02-06-2017 03:03 AM
Hm. I'll dig into the permissions issue. However, I'm I doubt that this is the reason behind this weirdness, because, not only that hmaster lives, but on the surface, it appears to be functioning normally. I created a table and filled it with 2 million rows. Did hbase hbck after this. It reported 37 inconsistencies of the same type. hbase:namespace still among them.
EDIT:
Additional info: When i scan 'hbase:namespace'
I get:
ROW COLUMN+CELL default column=info:d, timestamp=1486140313224, value=\x0A\x07default hbase column=info:d, timestamp=1486140313283, value=\x0A\x05hbase 2 row(s) in 0.3760 seconds
...as I should.
More additional info (don't know if relevant), before inconsistency error, in log I get No HDFS region dir found. Looks like this:
No HDFS region dir found: { meta => hbase:namespace,,1486140310904.86d0405303ed58995e1507e33cbf66a2.,
hdfs => null, deployed => hadoop-38.xxxx.xxxxxxxxxxx.de,60020,1486140300341;hbase:namespace,,1486140310904.86d0405303ed58995e1507e33cbf66a2.,
replicaId => 0 } meta={ENCODED => 86d0405303ed58995e1507e33cbf66a2, NAME => 'hbase:namespace,,1486140310904.86d0405303ed58995e1507e33cbf66a2.',
STARTKEY => '', ENDKEY => ''}
It says basically the same thing as the error above, just with the additional hint of No HDFS region dir found and it's marked as warning. The deployed part also contains deployment info that I found in /hbase/WALs folder, namely:
hdfs dfs -ls /hbase/WALs Found 16 items ... drwxr-xr-x - hbase hbase 0 2017-02-06 11:11 /hbase/WALs/hadoop-38.xxxx.xxxxxxxxxxx.de,60020,1486140300341 ...
My next desperate idea is to try to read whatever it is in /hbase/data/hbase/namespace/86d0405303ed58995e1507e33cbf66a2/.regioninfo (following the No HDFS region dir found hint) as soon as I find some command line protobuf reader.
Again, thanks for taking the time to look into this, and as always ANY feedback is much appreciated!
Regards!
02-06-2017 11:23 AM
crazy thought: does the node that you are running hbck on have the HDFS gateway role applied?
could be that hbck can't find the region in HDFS because it doesn't know how to connect to hdfs?
another way to verify would be to check the hdfs location for the hbase tables:
/hbase/data/default/<table>
02-07-2017 06:14 AM
So, the crazy thought you had resolved the days long mistery!
An expension for any poor soul that might encounter a similar issue:
In our setup, we have three machines reserved for master roles m[1-3] and 40 worker machines w[1-40]. I assigned 2 HBase Masters, HBase Thrift server and HBase REST server on m2 and m3, Region Servers on w[20-40].
I ran hbck from m1 that has no HBase roles on it. Normally, this would fail with ConnectException as it does from all other machines that don't have HBase roles on them w[1-19], because they don't have hbase-site.xml on them and don't know where to look for the zookeeper, so they fall back to default - localhost. However, As m1 is also Zookeeper leader, the localhost is actually an OK default and hbase hbck will work. Sort of. As, m1 doesn't have any HDFS roles either.
So, m1 was LITERALLY the only machine in the cluster that would report these inconsistencies. The check would either fail with connection exception or report everything being normal.
Many thanks for your time, it saved a bunch of mine (although I also already lost a lot of it :)).
11-08-2018 01:28 AM
Hello Everyone,
I am seein the below error's in hbase when i checked the inconsistency of hbase.
ERROR: Found inconsistency in table SYSTEM.CATALOG
ERROR: There is a hole in the region chain between and . You need to create a new .regioninfo and region dir in hdfs to plug the hole
Can some one please address the issue and suggest me with valuable inputs.
Thansk in advance.
Vinod
11-09-2018 03:57 AM
Additionally to the previous solution some best practices:
- hbck is basically just an HBase client command
- client commands are recommended to being run from nodes which has the relevant service's client configurations deployed on them. This can be done manually (not recommended, see later why) or via Cloudera Manager
According to these whichever node you are running hbck should have HBase client configs deployed to make sure that it actually uses the cluster's current configs (which have several configs, like heap size for client commands, Zookeeper ensemble hostnames, etc).
To have this done, it's recommended to deploy an HBase GATEWAY role[1] that actually does just this, deploys the active configs of HBase service via Cloudera Manager. Additionally if any HBase client config changes are made later via Cloudera Manager, those will be also delegated automatically just the same way as any config changes are delegated to every node which has HBase role instances installed on.
There are some further reference about using hbck here[2] as this is an advanced topic.
[1] - Gateway roles CDH latest version -...
[2] - Checking and Repairing HBase tables CDH5.15.x -
(please note that in CDH6.0.0 hbck's several options are depreciated) | http://community.cloudera.com/t5/Storage-Random-Access-HDFS/hbase-hbck-reports-inconsistency-immediately-after-adding/td-p/50070 | CC-MAIN-2019-04 | refinedweb | 1,630 | 63.29 |
From: Victor A. Wagner, Jr. (vawjr_at_[hidden])
Date: 2003-03-14 09:30:33
I appreciate the difficulties in getting a release out.
I _am_ puzzled about what behavior you wish people (who use (all | any) of
boost regularly) to use in validating problems they may encounter (most of
the time boost is in a constant state of improvement).
During these times, the usual advice is check the latest out of CVS and
verify the problem exists there.
Now we appear to be told that the "latest" isn't to be used (for filesystem
at any rate) until 1.30 is released.
Is this a rule for ALL of boost for the duration?
Enquiring minds want to know.
_Surely_ you don't want people to _quit_ testing during this pre-release
phase. That would make the whole phase irrelevant.
I suggest further, that perhaps the release mechanism be changed such that
the "how to check the latest" NEVER changes from the point of view of the
user/tester i.e. "cvs update -A -P -d" would ALWAYS get the latest believed
to be working copy.
At Friday 2003/03/14 04:53, you wrote:
>At 11:00 PM 3/13/2003, Victor A. Wagner, Jr. wrote:
>
> ".
>
>I don't know why your run hung, but the '"filesystem" isn't part of
>namespace "boost"' error is a known namespace alias bug in VC++ 7.1 final
>beta. A workaround has been checked into Boost's RC_1_30_0. I'm not
>worrying about the main trunk until 1.30.0 ships.
>
>--Beman
>
>
>_______________________________________________
| https://lists.boost.org/Archives/boost/2003/03/45698.php | CC-MAIN-2020-16 | refinedweb | 260 | 74.29 |
GraphQL Code Generator - Introducing Hooks support for React Apollo plugin
Explore our services and get in touch.
If you follow the React community, you’ll know for sure that React Hooks had been one of the most awaited feature in the ecosystem since their first gist. They have been available since React v16.7-alpha, and many libraries already started adopting them — officially or with auxiliary libraries.
In case you don’t know what hooks are, you may be wondering what all this buzz is about. Let the React docs speak for itself:
Hooks let you use state and other React features without writing a class.
This could be a huge improvement by itself (you know, you create a Functional Component, mess with it and then you need a bit of state so.. let’s refactor this to a class, hooray! 🎉 — sarcasm is intentional), but there is more.
React Apollo and Hooks
tip
If you already know all about hooks and @apollo/react-hooks, and want to see the news about
graphql-code-generator, just skip this section.
If you are interested in the long story instead, keep reading!
There are many hooks, like
useEffect or
useReducer, that may simplify your code, but I’ll leave this to your curiosity. I suggest you to read the Dan Abramov (“Making sense of React Hooks” story if you didn’t already.
What I want to talk about, instead, is
useContext and how you will fall in love with it, especially when talking about
react-apollo.
Note: If you haven’t used Context before, just think of it as a way to pass props down the components tree without passing props down component-by-component. _It should not replace normal React usage, but is useful when talking about cross-application values like state, translations, themes, etc._If
The new hook
useContext allows us to access a React Context (with its Consumer/Provider api) directly from a functional component, without props nor contextType:
// This is our custom hook function useThemeColor() { const theme = useContext(ThemeContext); return theme.color; } function MyComponent(props: Props) { // Here we go const color = useThemeColor(); return <h1 style={{ color }}>{props.title}</h1>; }
Given this sweet feature, we can now think about all our HOCs / Render Props in our codebase, well, almost all: Every time we need to access context (State Management, API Calls, Translations, Localization) we can now use hooks.
Especially using TypeScript, deep HOCs tree-hell or render-props callback hell are a nightmare (Reminding Node.js callback hell, anyone?). Typings are always wrong, you need to define twenty different interfaces, etc.
With hooks, you can just use them in a straight, linear, fashion:
function MyComponent(props: Props) { const translate = useTranslation(); const { user } = useMappedState(state => state.user); return ( // ... ); }
React Apollo fits perfectly the requirements, and it now supports Hooks for your GraphQL operations.
If you are used to
Query component, in the next example you’ll see how we are replacing it with just the
useQuery hook:
import { useQuery } from '@apollo/react-hooks'; const GET_TODOS = gql` { todos { id description } } `; function Todos() { // Here the magic bits const { data, error, loading } = useQuery(GET_TODOS); if (loading) if (error) // ... // ... return ( <ul> {data.todos.map((todo) => ( <li key={todo.id}>{todo.description}</li> ))} </ul> ); }
React Apollo Hooks and GraphQL Code Generator
Since the first time I saw hooks, I thought about removing the callback hell caused by render props in my codebase. Given the awesome work done by Daniel Trojanowski with
react-apollo-hooks, I wanted to use hooks in our projects, replacing React Apollo classic components (render-props based).
However, I love even more the
graphql-code-generator project, since I want proper typings with my Query, Mutation and Subscription components. Accessing
data with proper autocomplete and type checking is definitely a game-changer!
I’m glad to have the honor to announce the next release of GraphQL Code Generator, that will add React Apollo hooks generation to its arsenal
With this enhancement, now you can choose between React Apollo Components, HOCs or Hooks and even mix-and-match if you’ve got an existing project and want to start using Hooks right now!
Just use GraphQL Code Generator’s Typescript-React-Apollo Plugin, set
withHooks: true to your GraphQL Code Generator config, and add
react-apollo-hooks to your dependencies if you already didn’t.
This is an example generated hook, with proper typings:
export function useUserListQuery( baseOptions?: QueryHookOptions<UserListQueryVariables> ) { return useApolloQuery<UserListQueryQuery, UserListQueryVariables>( UserListQueryDocument, baseOptions ); }
And here we can see autocomplete at work:
If you want to see
graphql-code-generator in action, you can look at the awesome WhatsApp-Clone-Client-React project made by The Guild. Here is the diff (thanks to Eytan Manor) showcasing the generated hooks applied to a real codebase.
Conclusions
React Hooks will probably be a powerful tool in our toolbelt, and I’m sure we will see many patterns evolving. Libraries like React Apollo fits perfectly, and I hope having tools to generate typings like GraphQL Code Generator will increase their adoption.
I’d like to thank the awesome team behind The Guild, especially Eytan Manor for its continuous effort reviewing my hooks proposal, Arda TANRIKULU and Dotan Simha for their support and, obviously, the creation of
graphql-code-generator. Thanks indeed to Daniel Trojanowski for the great work on the initial implementation of hooks in
react-apollo-hooks.
Thank you for reading this story, I hope you found it useful/interesting. May the hook be with you! | https://the-guild.dev/blog/graphql-codegen-hooks-support-react-apollo | CC-MAIN-2021-31 | refinedweb | 912 | 51.18 |
Why Not Airflow?Why Not Airflow?
Why should I choose Prefect over Airflow?
Airflow is a historically important tool in the data engineering ecosystem. It introduced the ability to combine a strict Directed Acyclic Graph (DAG) model with Pythonic flexibility in a way that made it appropriate for a wide variety of use cases. However, Airflow’s applicability is limited by its legacy as a monolithic batch scheduler aimed at data engineers principally concerned with orchestrating third-party systems employed by others in their organizations.
Today, many data engineers are working more directly with their analytical counterparts. Compute and storage are cheap, so friction is low and experimentation prevails. Processes are fast, dynamic, and unpredictable. Airflow got many things right, but its core assumptions never anticipated the rich variety of data applications that has emerged. It simply does not have the requisite vocabulary to describe many of those activities.
The seed that would grow into Prefect was first planted all the way back in 2016, in a series of discussions about how Airflow would need to change to support what were rapidly becoming standard data practices. Disappointingly, those observations remain valid today.
We know that questions about how Prefect compares to Airflow are paramount to our users, especially given Prefect’s lineage. We prepared this document to highlight common Airflow issues that the Prefect engine takes specific steps to address. This post is not intended to be an exhaustive tour of Prefect’s features, but rather a guide for users familiar with Airflow that explains Prefect’s analogous approach. We have tried to be balanced and limit discussion of anything not currently available in our open-source repo, and we hope this serves as a helpful overview for the community.
Happy engineering!
OverviewOverview
Airflow was designed to run static, slow-moving workflows on a fixed schedule, and it is a great tool for that purpose. Airflow was also the first successful implementation of workflows-as-code, a useful and flexible paradigm. It proved that workflows could be built without resorting to config files or obtuse DAG definitions.
However, because of the types of workflows it was designed to handle, Airflow exposes a limited “vocabulary” for defining workflow behavior, especially by modern standards. Users often get into trouble by forcing their use cases to fit into Airflow’s model. A sampling of examples that Airflow can not satisfy in a first-class way includes:
- DAGs which need to be run off-schedule or with no schedule at all
- DAGs that run concurrently with the same start time
- DAGs with complicated branching logic
- DAGs with many fast tasks
- DAGs which rely on the exchange of data
- Parametrized DAGs
- Dynamic DAGs
If your use case resembles any of these, you will need to work around Airflow’s abstractions rather than with them. For this reason, almost every medium-to-large company using Airflow ends up writing a custom DSL or maintaining significant proprietary plugins to support its internal needs. This makes upgrading difficult and dramatically increases the maintenance burden when anything breaks.
Prefect is the result of years of experience working on Airflow and related projects. Our research, spanning hundreds of users and companies, has allowed us to discover the hidden pain points that current tools fail to address. It has culminated in an incredibly user-friendly, lightweight API backed by a powerful set of abstractions that fit most data-related use cases.
APIAPI
When workflows are defined as code, they become more maintainable, versionable, testable, and collaborative.
— Airflow documentation
Production workflows are a special creature — they typically involve multiple stakeholders across the technical spectrum, and are usually business critical. For this reason, it is important that your workflow system be as simple and expressive as it can possibly be. Given its popularity and omnipresence in the data stack, Python is a natural choice for the language of workflows. Airflow was the first tool to take this to heart, and actually implement its API in Python.
However, Airflow’s API is fully imperative and class-based. Additionally, because of the constraints that Airflow places on what workflows can and cannot do (expanded upon in later sections), writing Airflow DAGs feels like writing Airflow code.
One of Prefect’s fundamental insights is that if you could guarantee your code would run as intended, you wouldn’t need a workflow system at all. It’s only when things go wrong that workflow management is critical. In this light, workflow systems are risk management tools and, when well designed, should stay out of users’ way until they’re needed.
Therefore, Prefect’s design goal is to be minimally invasive when things go right and maximally helpful when they go wrong. Either way, the system can provide the same level of transparency and detail for your workflows.
One way we achieve this is through our “functional API.” In this mode, Prefect tasks behave just like functions. You can call them with inputs and work with their outputs —you can even convert any Python function to a task with one line of Prefect code. Calling tasks on each other like functions builds the DAG in a natural, Pythonic way. This makes converting existing code or scripts into full-fledged Prefect workflows a trivial exercise.
Not to worry, Prefect also exposes a full imperative API that will be familiar to Airflow users. The imperative API is useful for specifying more complex task dependencies, or for more explicit control. Users can switch between the two styles at any time depending on their needs and preferences.
Scheduling and TimeScheduling and Time
Time is an illusion. Lunchtime doubly so.
— The Hitchhiker’s Guide to the Galaxy
Perhaps the most common confusion amongst newcomers to Airflow is its use of time. For example, were you to run the Airflow tutorial, you might find yourself running:
and wondering what all these different times mean.
Airflow has a strict dependency on a specific time: the
execution_date. No DAG can run without an execution date, and no DAG can run twice for the same execution date. Do you have a specific DAG that needs to run twice, with both instantiations starting at the same time? Airflow doesn’t support that; there are no exceptions. Airflow simply decrees that such workflows do not exist. You’ll need to create two nearly-identical DAGs, or start them a millisecond apart, or employ other creative hacks to get this to work.
More confusingly, the
execution_date is not interpreted by Airflow as the start time of the DAG, but rather the end of an interval capped by the DAG’s start time. This was originally due to ETL orchestration requirements, where the job for May 2nd’s data would be run on May 3rd. Today, it is a source of major confusion and one of the most common misunderstandings new users have.
This interval notion arises from Airflow’s strict requirement that DAGs have well-defined schedules. Until recently, it was not even possible to run a DAG off-schedule — the scheduler would get confused by the off-schedule run and schedule future runs at the wrong time! Ad-hoc runs are now possible as long as they don’t share an
execution_date with any other run.
This means that if you want to:
- run your workflow on an irregular (or no) schedule
- run multiple simultaneous runs of your workflow
- maintain a workflow that only runs manually
then Airflow is the wrong tool.
PrefectPrefect
In contrast, Prefect treats workflows as standalone objects that can be run any time, with any concurrency, for any reason. A schedule is nothing more than a predefined set of start times, and you can make your schedules as simple or as complex as you want. And if you do want your workflow to depend on time, simply add it as a flow parameter.
The Scheduler ServiceThe Scheduler Service
R2-D2, you know better than to trust a strange computer!
— C-3PO
The Airflow Scheduler is the backbone of Airflow. This service is critical to the performance of Airflow and is responsible for:
- reparsing the DAG folder every few seconds
- checking DAG schedules to determine if a DAG is ready to run
- checking all Task dependencies to determine if any Tasks are ready to be run
- setting the final DAG states in the database
Conversely, Prefect decouples most of this logic into separate (optional) processes:
Prefect Flow schedulingPrefect Flow scheduling
Scheduling a flow in Prefect is a lightweight operation. We simply create a new flow run and place it in a
Scheduled state. In fact, when we talk about Prefect Cloud’s “scheduler,” that is its sole responsibility. Our scheduler never gets involved in any workflow logic or execution.
Prefect Flow logicPrefect Flow logic
Prefect Flows themselves are standalone units of workflow logic. There is no reason for a scheduler to ever parse them or interact with the resulting states.
As proof, you can run an entire flow in your local process with no additional overhead:
# run your first Prefect flow from the command line python -c "from prefect import Flow; f = Flow('empty'); f.run()"
Prefect Task schedulingPrefect Task scheduling
When a Prefect flow runs, it handles scheduling for its own tasks. This is important for a few reasons:
- As the source of workflow logic, the flow is the only object that should have this responsibility.
- It takes an enormous burden off the central scheduler.
- It lets the flow make decisions about unique circumstances like dynamically-generated tasks (that result from Prefect’s
mapoperator, for example)
- It lets Prefect outsource details of execution to external systems like Dask.
This last point is important. While Airflow has support for a variety of execution environments, including local processes, Celery, Dask, and Kubernetes, it remains bottlenecked by its own scheduler, which (with default settings) takes 10 seconds to run any task (5 seconds to mark it as queued, and 5 seconds to submit it for execution). No matter how big your Dask cluster, Airflow will still only ask it to run a task every 10 seconds.
Prefect, in contrast, embraces modern technology. When you run Prefect on Dask, we take advantage of Dask’s millisecond-latency task scheduler to run all tasks as quickly as possible, with as much parallelism as the cluster offers. Indeed, the default deployment specification for Prefect Cloud deploys Dask clusters in Kubernetes (this is also customizable).
Besides performance, this has a major implication for how flows are designed: Airflow encourages “large” tasks; Prefect encourages smaller, modular tasks (and can still handle large ones).
Furthermore, when running a flow on Prefect Cloud or with a custom database, Task and Flow Runners are responsible for updating database state, not the scheduler.
SummarySummary
- the centralized Airflow scheduler loop introduces non-trivial latency between when a Task’s dependencies are met and when that Task begins running. If your use case involves few long-running Tasks, this is completely fine — but if you want to execute a DAG with many tasks or where time is of the essence, this could quickly lead to a bottleneck.
- Airflow’s tight coupling of time and schedules with workflows also means that you need to instantiate both a database and a scheduler service in order to run your DAGs locally. These are clearly necessary features of a production environment, but can be burdensome when trying to test and iterate quickly.
- the centralized nature of the Airflow scheduler provides a single point of failure for the system
- reparsing the DAG with every single loop can lead to major inconsistencies (it’s possible for the scheduler to run a task that, when it reinstantiates itself, discovers it doesn’t even exist!)
- central scheduling typically means tasks can’t communicate with each other (no dependency resolution)
DataflowDataflow
It’s a trap!
— Admiral Ackbar
One of the most common uses of Airflow is to build some sort of data pipeline, which is ironic because Airflow does not support dataflow in a first class way.
What Airflow does offer is an “XCom,” a utility that was introduced to allow tasks to exchange small pieces of metadata. This is a useful feature if you want task A to tell task B that a large dataframe was written to a known location in cloud storage. However, it has become a major source of Airflow errors as users attempt to use it as a proper data pipeline mechanism.
XComs use admin access to write executable pickles into the Airflow metadata database, which has security implications. Even in JSON form, it has immense data privacy issues. This data has no TTL or expiration, which creates performance and cost issues. Most critically, the use of XComs creates strict upstream/downstream dependencies between tasks that Airflow (and its scheduler) know nothing about! If users don’t take additional care, Airflow may actually run these tasks in the wrong order. Consider the following pattern:
def puller(**kwargs): ti = kwargs['ti'] # get value_1 v1 = ti.xcom_pull(key=None, task_ids='push')
This task explicitly depends on an action taken by a “push” task, but Airflow has no way of knowing this. If the user doesn’t explicitly (and redundantly) make that clear to Airflow, then the scheduler may run these tasks out of order. Even if the user does tell Airflow about the relationship, Airflow has no way of understanding that it’s a data-based relationship, and will not know what to do if the XCom push fails. This is one of the most common but subtle and difficult-to-debug classes of Airflow bugs.
An unfortunately frequent outcome for Airflow novices is that they kill their metadata database through XCom overuse. We’ve seen cases where someone created a modest (10GB) dataframe and used XComs to pass it through a variety of tasks. If there are 10 tasks, then every single run of this DAG writes 100GB of permanent data to Airflow’s metadata database.
PrefectPrefect
Prefect elevates dataflow to a first class operation. Tasks can receive inputs and return outputs, and Prefect manages this dependency in a transparent way. Additionally, Prefect almost never writes this data into its database; instead, the storage of results (only when required) is managed by secure “result handlers” that users can easily configure. This provides many benefits:
- users can write code using familiar Python patterns
- dependencies cannot be sidestepped, because they are known to the engine. This provide a more transparent debugging experience
- Airflow-style patterns without dependencies are still supported (and sometimes encouraged!); just because Prefect allows for dataflow, doesn’t mean you have to use it!
- because Tasks can directly exchange data, Prefect can support more complicated branching logic, richer Task states, and enforce a stricter contract between Tasks and Runners within a Flow (e.g., a Task cannot alter its downstream Tasks states in the database)
Parametrized WorkflowsParametrized Workflows
I’m sorry Dave, I’m afraid I can’t do that.
—PreDynamicVersion simply to maintain a history of your workflow without polluting your UI.
Local TestingLocal simplyUI
I want to believe.
— Fox Mulder
One of the most popular aspects of Airflow is its web interface. From the UI, you can turn schedules on / off, visualize your DAG’s progress, even make SQL queries against the Airflow database.
Prefect’s UI is not yet available to the public, so we will refrain from making any direct comparisons. However, here is a non-exhaustive preview of features you can expect from the Prefect UI:
- dashboard style pages for operational visibility and critical information
- tabular views for custom queries
- full GraphQL playground for those extra-custom queries
- live updating
- global search
- projects for organizing flows
- keyboard shortcuts
- timezone handling (this one’s for you, Airflow users!)
ConclusionsConclusions. | https://docs.prefect.io/core/welcome/why_not_airflow.html | CC-MAIN-2019-47 | refinedweb | 2,620 | 50.97 |
This is a joint project, that my brother (bluemarlin1134) and I worked on together. My bro. named this project after his best friend which the code’s dialogue is modeled after.
It runs best on full screen and, the weather auto-location function works only when it runs on your computer as a program but, the manual input works like a charm. :)
if you haven't seen in the post down below, we updated the calculator and the thermometer so now the thermometer doesn't print out a bunch of decimal places, and the calculator accepts integers.
I like it! When I tried to play hangman, it had a bunch of error messages with the only comprehensible one being: TypeError: 'str' object is not callable
Besides that, its great!
This was an error
/home/runner/.site-packages/wikipedia/wikipedia.py:389: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.The code that caused this warning is on line 389 of the file /home/runner/.site-packages/wikipedia/wikipedia.py. To get rid of this warning, pass the additional argument 'features="lxml"' to the BeautifulSoup constructor. lis = BeautifulSoup(html).find_all('li')Traceback (most recent call last): File "main.py", line 964, in <module>
whattodo() File "main.py", line 746, in whattodo whattodo() File "main.py", line 746, in whattodo whattodo() File "main.py", line 736, in whattodo
wikipediamod()
File "main.py", line 912, in wikipediamod
topray()
File "main.py", line 897, in topray
wikipediamod()
File "main.py", line 911, in wikipediamod
print(wikipedia.summary(search))
File "/home/runner/.site-packages/wikipedia/util.py", line 28, in call
ret = self._cache[key] = self.fn(*args, **kwargs)
File "/home/runner/.site-packages/wikipedia/wikipedia.py", line 231, in summary
page_info = page(title, auto_suggest=auto_suggest, redirect=redirect)
File "/home/runner/.site-packages/wikipedia/wikipedia.py", line 276, in page
return WikipediaPage(title, redirect=redirect, preload=preload)
File "/home/runner/.site-packages/wikipedia/wikipedia.py", line 299, in init
self.load(redirect=redirect, preload=preload)
File "/home/runner/.site-packages/wikipedia/wikipedia.py", line 393, in load
raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to)
wikipedia.exceptions.DisambiguationError: "Yes" may refer to:
yes and no
YES Prep Public Schools
YES (Your Extraordinary Saturday)
Young Eisner Scholars
Young Epidemiology Scholars
yes (Unix)
Philips :YES
Yes! Roadster
Yasuj Airport
OLT Express
Yale Entrepreneurial Society
YES Snowboards
The YES! Association
Yes! Youth Movement
Young European Socialists
Youth Empowerment Scheme
Youth Energy Squad (Y.E.S)
Youth Entrepreneurship and Sustainability
YES (Lithuanian political party)
Yes! (Hong Kong magazine)
Yes! (U.S. magazine)
Yes! (Philippine magazine)
Yes (novel)
Daniel Bryan
Yes (film)
yes (Israel)
YES Network
Yes TV
WYEZ
Y.E.S. 93.3FM
Yes (band)
Yes Featuring Jon Anderson, Trevor Rabin, Rick Wakeman
Yes (musical)
Yes (Yes album)
The Yes Album
Yes (Alvin Slaughter album)
Yes! (Chad Brock album)
Yes! (Jason Mraz album)
Yes! (k-os album)
Yes (Mika Nakashima album)
Yes (Morphine album)
Yes (Pet Shop Boys album)
Julie Fuchs
Yes L.A.
Amber
"Yes!" (Chad Brock song)
"Yes" (Coldplay song)
"Yes" (LMFAO song)
"Yes" (McAlmont & Butler song)
"Yes" (Sam Feldt song)
A Wolf In Sheep's Clothing
Confident
Yes
Dirty Dancing film soundtrack
Louisa Johnson
Beyoncé Knowles
Billy Swan
Connie Cato
Cornell Campbell
Dee C. Lee
Demi Lovato
The Family
Grapefruit
Jay & The Americans
Johnny Sandon
Manic Street Preachers
Merry Clayton
Peppino Di Capri
Pet Shop Boys
Roy Orbison
Schaffer the Darklord
Tim Moore
All pages beginning with Yes
Yesss (disambiguation)
Edit: We fixed the Weather function from giving you all those decimal places, and now the calculator accepts doubles.
Having so many text files as frames is a messy way to do the scrolling ASCII art. A cleaner approach would be to take a single file and iteratively print substring of each line.
import os, time def cls(): # Clear screen os.system('cls' if os.name=='nt' else 'clear') def marquee(txtart, speed, rtl=True): # Pepperidge Farm remembers <marquee>. '''Display ASCII art scrolling in. Parameters: txtart -- path to ASCII art text file speed -- rate of columns per second to display rtl -- default True for right-to-left, set False for left-to-right ''' with open(txtart) as f: art = f.read().splitlines() # Add trailing whitespace to any line shorter than the longest line. maxline = max(len(line) for line in art) for i in range(len(art)): if len(art[i]) < maxline: art[i] = art[i] + " " * (maxline - len(art[i])) artlength = len(art[0]) for i in range(artlength + 1): cls() for line in art: if rtl: print(" " * (artlength - i) + line[0:i]) else: print(line[-i:0 if i==0 else None]) time.sleep(1 / speed) marquee("goodbye.txt", 10, False)
Edit: Correct assignment for
maxline.
Nice. One comment, though, is that your calculator should accept floats. I looked up the weather for my city and tried to converting it into Fahrenheit using the calculator but got an error when your code tried to convert 1.8 to an integer.
I got this message after sending exit. I got the scrolling ascii art, which was cool :). But then i got this message that i couldnt understand.
You are located at None correct?:
@PYer Thanks for the info! The reason why this happened was: (I'm a messy coder) cough, cough Sometimes ... don't know why, ill head over to the weather function, and try to auto-locate you. Thanks! | https://repl.it/talk/challenge/Chloe/10741 | CC-MAIN-2019-35 | refinedweb | 935 | 57.87 |
Josh Finnie PRO
Software Engineer based out of Washington DC. Working at PBS!
Josh Finnie
Software Maven @ TrackMaven
Functional Programming is the practices of writing code using solely functions avoiding both changing state and mutable data. [1]
[1]
I don't know... and I am sad about choosing it :-)
A standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. [1]
[1]
Prelude> putStrLn "Hello, world!" Hello, world! Prelude> :t putStrLn putStrLn :: String -> IO ()
Above is the "Hello World!" example in Haskell along with showing the definition of the `putStrLn` function.
Prelude> let fac n = if n == 0 then 1 else n * fac (n-1) Prelude> fac 10 3628800
Above is the "fibonacci sequence" example in Haskell. It's pretty cool how it's recursive and easy!
import System.Random import Control.Monad(when) isValidNumber n = do n > 0 && n < 10 testGuessedNumber a b = do if a == b then putStrLn "You're correct!" else putStrLn $ "Sorry, the correct answer was " ++ show a main = do gen <- getStdGen let (randNumber, _) = randomR (1,10) gen :: (Int, StdGen) putStr "Which number in the range from 1 to 10 am I thinking of? " numberString <- getLine when (not $ null numberString) $ do let number = read numberString if isValidNumber number then testGuessedNumber randNumber number else putStrLn $ "Please select a number between 1 and 10!" newStdGen main
import System.Random -- LOL randomNumber = 4 -- chosen by fair dice roll. -- guaranteed to be random. isValidNumber :: Int -> Bool isValidNumber n | n > 0 && n < 10 = True | otherwise = False testGuessedNumber :: Int -> Int -> Bool testGuessedNumber a b | a == b = True | otherwise = False getInt :: IO Int getInt = do num <- getLine return $ (read num :: Int) main :: IO () main = do putStr "Which number in the range from 1 to 10 am I thinking of? " number <- getInt if isValidNumber number then run randomNumber number else putStrLn "please select a number between 1 and 10." run :: Int -> Int -> IO() run r n | outcome == True = do putStrLn "You Win!" | outcome == False = do putStrLn "You guessed incorrectly, please try again." number <- getInt run r number where outcome = testGuessedNumber r n
I was impressed with a lot of what Haskell had to offer. Would I use it again? - No...
Code
By Josh Finnie | http://slides.com/joshfinnie/haskell | CC-MAIN-2020-05 | refinedweb | 366 | 64.91 |
] Unqualified name lookup
For an unqualified name, that.
int n = 1; // declaration of n int x = n + 1; // OK: lookup finds ::n int z = y - 1; // Error: lookup fails int y = 2; // declaration of y int main() {}
int n = 1; // declaration namespace N { int m = 2; namespace Y { int x = n; // OK, lookup finds ::n int y = m; // OK, lookup finds ::N::m int z = k; // Error: lookup fails } int k = 3; }
const int RED = 7; enum class color { RED, GREEN = RED+2, // RED finds color::RED, not ::RED, so GREEN = 2 BLUE = ::RED+4 // qualified lookup finds ::RED, BLUE = 11 };
struct X { static int x; static const int n = 1; // found 1st }; int n = 2; // found 2nd. int X::x = n; // finds X::n, sets X::x to 1, not 2
namespace X { extern int x; // declaration, not definition int n = 1; // found 1st }; int n = 2; // found 2nd. int X::x = n; // finds X::n, sets X::x to };
[edit] Qualified name lookup
] | http://en.cppreference.com/w/cpp/language/lookup | CC-MAIN-2014-52 | refinedweb | 165 | 65.93 |
0
I am trying to time the execution of a quicksort algorithm in C++ but for some reason it constantly returns 0 for me, which clearly can't be right!
I don't know where I am gooing wrong, so any help would be greatly appreciated!I have the code done for arrays of size 10,50,100,500 and 1000 but since the code is similart for them all I will just give the code for the arrays of size 10 and 50.
#include <iostream> #include <time.h> #include <cstdlib> using namespace std; void quickSort(int arr[],int left,int right) { /*This is the quickSort function that will sort all of the elements in an array in ascending order*/); } void time(int arr[],int left,int right){ clock_t stopwatch,t1,t2; /*These 3 lines are timing the exection of the quicksort to take place*/ t1=clock(); quickSort(arr,left,right); t2=clock(); /*Used to time the quicksort*/ cout<<"t1 = "<<t1<<endl; cout<<"t2 = "<<t2<<endl; stopwatch=t2-t1; /*How long it took to execute the quicksort*/ cout<< "Stopwatch ="<<stopwatch<<endl; /*Displaying how long it took to execute the code-i.e.how long the quickSort function took*/ } int main() { int arraya[10],arrayb[50],i; srand(time(NULL)); /*Seed for a random number generator*/ for(i=0;i<10;i++) arraya[i]=rand(); time(arraya,0,9); cout<<"The sorted array of 10 elements is :\n"; for(i=0;i<10;i++){ cout<<"arraya ["<<i<<"] = "<<arraya[i]<<"\n";} srand(time(NULL)); for(i=0;i<50;i++) arrayb[i]=rand(); time(arrayb,0,49); cout<<"The sorted array of 50 elements is :\n"; for(i=0;i<50;i++){ cout<<"arrayb ["<<i<<"] = "<<arrayb[i]<<"\n";} return 0; }
Thanks in advance.
Edited 5 Years Ago by WaltP: Added CODE Tags. Please use them. | https://www.daniweb.com/programming/software-development/threads/353753/timing-a-function-always-returns-0-for-me | CC-MAIN-2016-50 | refinedweb | 303 | 51.11 |
Test::CleanNamespaces - Check for uncleaned imports
use strict; use warnings; use Test::CleanNamespaces; all_namespaces_clean;
This module lets you check your module's namespaces for imported functions you might have forgotten to remove with namespace::autoclean or namespace::clean and are therefor available to be called as methods, which usually isn't want you want.
All functions are exported by default.
namespaces_clean('YourModule', 'AnotherModule');
Tests every specified namespace for uncleaned imports. If the module couldn't be loaded it will be skipped.
all_namespaces_clean;
Runs
namespaces_clean for all modules in your distribution.
The exported functions are constructed using the the following methods. This is what you want to override if you're subclassing this module..
my $coderef = Test::CleanNamespaces->build_namespaces_clean;
Returns a coderef that will be exported as
namespaces_clean.
my $coderef = Test::CleanNamespaces->build_namespaces_clean;
Returns a coderef that will be exported as
all_namespaces_clean. It will use the
find_modules method to get the list of modules to check.
my @modules = Test::CleanNamespaces->find_modules;
Returns a list of modules in the current distribution. It'll search in
blib/, if it exists.
lib/ will be searched otherwise.
my $builder = Test::CleanNamespaces->builder;
Returns the
Test::Builder used by the test functions.
Florian Ragwitz <rafl@debian.org>
This software is copyright (c) 2010 by Florian Ragwitz.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. | http://search.cpan.org/~flora/Test-CleanNamespaces-0.03/lib/Test/CleanNamespaces.pm | CC-MAIN-2014-23 | refinedweb | 234 | 50.33 |
Historically,.
FILE
A well-behaved application is one that meets all three of the following requirements:
This article explains in detail the runtime and programming solutions that were introduced under the extended FILE facility. The following discussion is relevant only in 32-bit applications, as 64-bit applications are immune to the limitation to 256 file descriptors.
A quick web search on the keywords Solaris stdio open file descriptors results in numerous references to stdio's limitation of 256 open file descriptors on the Solaris OS. A 1992 request for enhancement (RFE), explains the problem: "32-bit stdio routines should support file descriptors >255." The bug report links to a handful of other bugs related to stdio's limitation to 256 file descriptors.
stdio
The reason for this limitation on the Solaris OS is that an unsigned char is used to store the value of the file descriptor associated with a standard I/O stream. Have a look at the definition of the FILE structure that you will find in the header /usr/include/stdio_impl.h on any Solaris OS system that does not have the solutions that this article discusses:
unsigned char
/usr/include/stdio_impl.h
struct __FILE_TAG
{
#ifdef _STDIO_REVERSE
unsigned char *_ptr;
int _cnt;
#else
int _cnt;
unsigned char *_ptr;
#endif
unsigned char *_base;
unsigned char _flag;
unsigned char _file;
/* UNIX System file descriptor */
unsigned __orientation:2;
unsigned __ionolock:1;
unsigned __seekable:1;
unsigned __filler:4;
};
The name __FILE_TAG is just an alias for FILE. See /usr/include/stdio_tag.h.
__FILE_TAG
/usr/include/stdio_tag.h
The member field _file holds the file descriptor, which was declared as an unsigned char. An unsigned char occupies 8 bits in memory. Hence _file can hold a maximum value of 2^8 = 256. In other words, _file restricts the access to 256 file descriptors per 32-bit process. This limitation was clearly documented in the manual page of stdio(3C).
_file
stdio(3C)
Sun did not make changes from an 8-bit unsigned char to a 16-bit int to accommodate more file descriptors. Doing so would have broken the much-promised binary compatibility with earlier releases of the Solaris OS, because it changes the size of the FILE structure.
int.
As the title of this section suggests, a runtime solution does not require any source-code changes or recompilation of the objects to overcome the 256 file-descriptors limitation with the stdio(3C) C library functions. However, the default behavior of existing 32-bit applications will not change unless you explicitly enable the extended FILE facility. Applications that enable this feature will be able to associate any valid file descriptor with a standard I/O -- or stdio -- stream. Any value that lies within the range 3 and the value returned by ulimit -n from the shell used to launch the application is a valid file descriptor. The file descriptors 0, 1, and 2 are reserved for use as the default stdin, stdout, and stderr I/O streams.
ulimit -n
stdin
stdout
stderr
You can increase the per-process maximum number of file descriptors in a shell from the default 256 to any value that is less than or equal to the value returned by the command
echo 'rlim_fd_max/D' | mdb -k | awk '{ print $2 }'
To adjust the file-descriptor limit in a shell, run ulimit -n <max_file_descriptors> in sh/ksh/bash or limit descriptors <max_file_descriptors> in csh, where max_file_descriptors is the maximum number of file descriptors you desire.
ulimit -n <max_file_descriptors>
sh/ksh/bash
limit descriptors <max_file_descriptors>
csh
max_file_descriptors
The default hard limit for the number of files a process can have opened at any time is 65,536. You can tune this limit with the system-tunable parameter rlim_fd_max. Although a very large number of files can be opened by tuning the rlim_fd_max parameter, virtual memory space becomes the limit for 32-bit processes when hundreds of thousands of files are open. When the process reaches the limits of virtual memory, stdio calls fail with a Not enough space error.
rlim_fd_max
Not enough space
Before running the 32-bit application, enable the extended FILE facility by taking the following two actions:
/usr/lib/extendedFILE.so.1
Note that extendedFILE.so.1 is not a library but an enabler of the extended FILE facility.
extendedFILE.so.1
Here is how to enable the extended FILE facility from ksh:
ksh
% ulimit -n
256
% echo 'rlim_fd_max/D' | mdb -k | awk '{ print $2 }'
65536
% ulimit -n 65537
ksh: ulimit: exceeds allowable limit
% ulimit -n 65536
% ulimit -n
65536
% export LD_PRELOAD_32=/usr/lib/extendedFILE.so.1
% application [arg1 arg2 .. argn]
The following example shows the behavior of a simple 32-bit process with and without the extended FILE facility enabled. The test case, a simple C program, tries to open 65,536 files with the fopen() interface.
fopen()
% cat fopentestcase.c
#include <stdio.h>
#include <stdlib.h>
#define NoOfFILES 65536
int main()
{
char filename[10];
FILE *fds[NoOfFILES];
int i;
for (i = 0; i < NoOfFILES; ++i)
{
sprintf (filename, "/tmp/%d.log", i);
fds[i] = fopen(filename, "w");
if (fds[i] == NULL)
{
printf("\nNumber of open files = %d. " \
"fopen() failed with error: ", i);
perror("");
exit(1);
}
else
{
fprintf (fds[i], "some string");
}
}
return (0);
}
Reproduce the failure with the default maximum number of file descriptors in a shell:
% cc -o fopentestcase fopentestcase.c
% ulimit -a | grep descriptors
nofiles(descriptors) 256
% ./fopentestcase
Number of open files = 253. fopen() failed with error:
Too many open files
Raise the file-descriptor limit, enable the extended FILE facility, and run the test case again to see the runtime solution at work.
% ulimit -n 5000
% ulimit -a | grep descriptors
nofiles(descriptors) 5000
% export LD_PRELOAD_32=/usr/lib/extendedFILE.so.1
% ./fopentestcase
Number of open files = 4996. fopen() failed with error:
Too many open files
% ulimit -n 65536
% ulimit -a | grep descriptors
nofiles(descriptors) 65536
% ./fopentestcase
Number of open files = 65532. fopen() failed with error:
Too many open files
Observe the shortage of one file descriptor -- excluding 0, 1, and 2 for stdin, stdout, and stderr, respectively -- in the preceding examples. When the extended FILE facility is enabled, the file descriptor 196 will be made unallocatable by default to minimize silent data corruption. See the next section, Environment Variables, for more information.
Here is the pfiles output to confirm this proposition:
pfiles
% pfiles `pgrep fopentestcase` | egrep "log|:"
...
195: S_IFREG mode:0644 dev:102,7 ino:7380 uid:209044 ...
/tmp/192.log
197: S_IFREG mode:0644 dev:102,7 ino:7381 uid:209044 ...
/tmp/193.log
...
Two environment variables control the behavior of the extended FILE facility: _STDIO_BADFD and _STDIO_BADFD_SIGNAL.
_STDIO_BADFD
_STDIO_BADFD_SIGNAL
As you know, object code built on the Solaris OS in the era before the extended FILE facility existed will not be expecting any file descriptor that doesn't fit in an 8-bit unsigned char, and it will not understand how to handle extended FILE pointers. For these reasons, the range has been restricted from 3 through 255, so the code that retrieves the file-descriptor value by dereferencing the FILE -> _file rather than the fileno(3C) function will receive the unallocatable or bad file descriptor when the actual descriptor is indeed an extended file descriptor -- that is, any value greater than 255.
FILE -> _file
fileno(3C)
signal.h(3HEAD)
SIGABRT
Do not enable the extended FILE facility if the application does either of the following:
fileno()
fileno(FILE)
When this feature is enabled, file descriptors greater than 255 will be stored in an auxiliary location unknown to the application, and an unallocatable or bad file descriptor held by the environment variable _STDIO_BADFD will be stored in the FILE -> _file member field. Improper access by the application to the FILE -> _file member field will yield the unallocatable bad file descriptor when the actual underlying file descriptor is greater than 255, thus leading to silent data corruption.
Also, data corruption can occur if the process truncates the value returned by the fileno(FILE) function. For example, if the 16-bit or 32-bit int value returned by the fileno() function is stored in an 8-bit unsigned char variable, truncation occurs. Accessing the truncated file descriptor may then yield errors.
The following error message during runtime is a clear indication that the application is modifying the internal file-descriptor member field of the FILE structure from stdio.
Application violated extended FILE safety mechanism.
Please read the man page for extendedFILE.
Aborting
When you receive such an error message, stop using the extended FILE facility with the application. If possible, fix the source by replacing all references to FILE -> _file with calls to fileno(FILE). Ignoring this runtime error could lead to data corruption.
The following trivial example illustrates the usage of both environment variables, _STDIO_BADFD and _STDIO_BADFD_SIGNAL, and it shows the subsequent program crash when the code violates the extended FILE safety mechanism.
Compile the following code and build a library on any system running the Solaris OS without the extended FILE solutions. Note: Unpatched systems running Solaris 10 3/05 through Solaris 10 11/06 releases do not contain the extended FILE solutions. However, it is possible to install the extended FILE facility on those systems by applying the latest kernel and libc patches. See this article's Patches and Bugs section for instructions.
libc
% cat thirdpartysrc.c
#include <stdio.h>
void manipulatefd (FILE *fptr)
{
;
;
fprintf(stdout, "\n%s : manipulatefd(): " \
"underlying file descriptor = %d\n", \
__FILE__, fptr -> _file);
fptr -> _file = 123;
fprintf(fptr, "This call is gonna fail!\n");
;
;
}
% cc -G -o /tmp/libthirdparty.so thirdpartysrc.c
Compile the following code and build an executable by linking the object code with the library created in the preceding step, on any system running the Solaris OS with the extended FILE solutions:
% cat enableextfile.c
#include <stdio.h>
#include <stdlib.h>
#define NoOfFiles 500
void manipulatefd(FILE *);
int main ()
{
FILE *fptr;
int i;
for (i = 0; i < NoOfFiles; i++)
{
fptr = fopen("/tmp/enable_test.txt", "w");
if (fptr == NULL)
{
perror("fopen failed. ");
exit(1);
}
printf("\nfd = %d", fileno(fptr));
if (fileno(fptr) % 400 == 0)
{
manipulatefd(fptr);
}
}
return(0);
}
% export LD_LIBRARY_PATH=/tmp:$LD_LIBRARY_PATH
% cc -o enableextfile -lthirdparty enableextfile.c
Raise the limit of maximum file descriptors per process to any number greater than 255, set the environment variables _STDIO_BADFD and _STDIO_BADFD_SIGNAL, enable the extended FILE facility by preloading /usr/lib/extendedFILE.so.1, and finally run the executable:
% ulimit -n
256
% ulimit -n 500
% ulimit -n
500
% export _STDIO_BADFD=196
% export _STDIO_BADFD_SIGNAL=SIGABRT
% export LD_PRELOAD_32=/usr/lib/extendedFILE.so.1
% ./enableextfile
fd = 3
fd = 4
fd = 5
...
...
fd = 398
fd = 399
fd = 400
thirdpartysrc.c : manipulatefd():
underlying file descriptor = 196
Application violated extended FILE safety mechanism.
Please read the man page for extendedFILE.
Aborting
Abort(coredump)
% /usr/bin/pstack core
core 'core' of 10172: ./enableextfile
d1f28e65 _lwp_kill (1, 6) + 15
d1ee2102 raise (6) + 22
d1ec0dad abort (0, 80677e0, d1f60000, ...) + cd
d1f01d54 _file_get (80677e0) + b4
d1efeb21 _findbuf (80677e0) + 31
d1ef2f16 _ndoprnt (d1f70344, 80471d4, 80677e0, 0) + 46
d1ef669f fprintf (80677e0, d1f70344) + 9f
d1f702cb manipulatefd (80677e0) + 3b
0805097f main (1, 8047214, 804721c) + 9f
0805084a _start (1, 8047360, 0, 8047370, ... ) + 7a
If the application does not show any of the previously mentioned patterns, it can take advantage of this runtime solution regardless of its age -- that is, even applications built on the Solaris 7 OS or earlier versions may continue to work flawlessly.
See the manual page of extendedFILE(5) for more examples.
extendedFILE(5)
This section is intended for new applications and applications that the developer can easily modify.
Two programmatic interfaces will allow access to the larger than 256 file-descriptor FILE pool, provided the maximum file-descriptors resource limit has been raised. Note that the default limit on maximum file descriptors is still 256.
fopen(3C)
fdopen(3C)
popen(3C)
In order to reduce the effort in modifying the existing sources to take advantage of the extended FILE feature, the existing mode string of stdio open calls such as fopen(3C), fdopen(3C), and popen(3C) have been augmented with a new flag: F. For example:
F
FILE *fptr = fopen("dummy.txt", "rF");
int fd = creat("dummy2.txt", S_IWUSR);
FILE *stream = fdopen(fd, "wF");
FILE *ptr = popen("/usr/bin/ls *.txt", "rF");
If the last character of the mode string is an F, 32-bit processes will be allowed to associate a stream with a file accessed by a file descriptor with a value greater than 255. In the case of 64-bit applications, the application will silently ignore character F in the mode string. Except for this minor enhancement, the existing semantics of stdio open calls have not changed.
The F in the mode string of stdio open calls is intended only for code that does not do the following:
If the application exhibits any of the previously mentioned patterns, the character F must not be appended in the mode string to enable the extended FILE feature. Data corruption could occur if 32-bit applications directly use the member fields in the FILE structure when the last character of mode is F.
enable_extended_FILE_stdio(3C)
For a usage example, rebuild the test case after changing the line
fds[i] = fopen(filename, "w");
to this:
fds[i] = fopen(filename, "wF");
Now raise the file-descriptor limit from the shell, and run the test case again to see the results:
% cc -o fopentestcaseF fopentestcase.c
% ulimit -n 10000
% ulimit -a | grep descriptors
nofiles(descriptors) 10000
% ./fopentestcaseF
Number of open files = 9996. fopen() failed with error:
Too many open files
Note the absence of linking against any special libraries to make it work. All the stdio routines are still part of libc.
See the manual pages fopen(3C), fdopen(3C), and popen(3C) for more information.
If the FILE pointer is not confined within the context of a single function, you can use the new programming interface enable_extended_FILE_stdio(3C) to enable the extended FILE facility. This interface minimizes the data corruption by providing some protection mechanism to software with unknown behaviors, such as third-party libraries without source code. For instance, by using this interface, the user can choose any signal to be sent to the process during runtime when the application dereferences FILE -> _file inappropriately.
This new interface was defined in the /usr/include/stdio_ext.h header as follows:
/usr/include/stdio_ext.h
int enable_extended_FILE_stdio(int, int);
The first argument, an integer, specifies the file descriptor in the range of 3 through 255 that the application wants to be selected as the unallocatable file descriptor. Alternatively, setting it to -1 will request enable_extended_FILE_stdio(3C) to select a reasonable unallocatable file descriptor. This is the equivalent of setting the environment variable _STDIO_BADFD when enabling the runtime solution for extended FILEs.
The second argument, an integer, specifies the signal to be sent to the process when the unallocatable file descriptor is used as a file-descriptor argument to any system call except close(2) or closefrom(3C). Some applications may attempt to close file descriptors that they did not open. This exception prevents the application from crashing because of such harmless calls.
close(2)
closefrom(3C)
If -1 is passed, the default signal SIGABRT will be sent to the process. A value of 0 ignores any FILE -> _file dereferences by disabling the sending of a signal. Otherwise, the specified signal will be sent to the process. See the manual page of signal.h(3HEAD) for the complete list of signals on the Solaris OS. This is the equivalent of setting the environment variable _STDIO_BADFD_SIGNAL when enabling the runtime solution for extended FILEs.
The enable_extended_FILE_stdio(3C) function is available only in the 32-bit compilation environment.
For the extended FILE facility to be effective, raise the default maximum limit on file descriptors for the process from 256 to any number less than or equal to the hard limit for the number of files a process can have opened at any time. See the kernel tunable rlim_fd_max for more information. You can do this either from the shell with ulimit/limit commands or programmatically by using the getrlimit(2)/setrlimit(2) functions defined in the /usr/include/sys/resource.h header.
ulimit/limit
getrlimit(2)/setrlimit(2)
/usr/include/sys/resource.h
The trivial programming example that follows demonstrates three things:
Compile the following code and build an executable by linking the object code with the library libthirdparty.so, created in the Runtime Solution section of this article.
libthirdparty.so
% cat enableextfilestdio.c
#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <sys/resource.h>
#define NoOfFiles 500
void manipulatefd(FILE *);
int main ()
{
FILE *fptr;
struct rlimit rlp;
int i;
(void) getrlimit (RLIMIT_NOFILE, &rlp);
/* set the desired number of file descriptors */
rlp.rlim_cur = NoOfFiles;
if (setrlimit (RLIMIT_NOFILE, &rlp) == -1)
{
perror ("setrlimit(): ");
exit (1);
}
if (enable_extended_FILE_stdio (-1, -1) == -1)
{
perror ("enable_extended_FILE_stdio(3C): ");
exit (1);
}
for (i = 0; i < NoOfFiles; i++)
{
fptr = fopen ("/tmp/enable_test.txt", "w");
if (fptr == NULL)
{
perror("\nfopen failed. ");
exit (1);
}
printf ("\nfd = %d", fileno(fptr));
if (fileno (fptr) % 400 == 0)
{
manipulatefd (fptr);
}
}
return (0);
}
% export LD_LIBRARY_PATH=/tmp:$LD_LIBRARY_PATH
% cc -o enableextfilestdio -lthirdparty enableextfilestdio.c
% ./enableextfilestdio
fd = 3
fd = 4
fd = 5
...
...
fd = 398
fd = 399
fd = 400
thirdpartysrc.c : manipulatefd():
underlying file descriptor = 196
Application violated extended FILE safety mechanism.
Please read the man page for extendedFILE.
Aborting
Abort (core dumped)
See the manual page of enable_extended_FILE_stdio(3C) for more information.
_magic
In order to ensure safety in using the extended FILE mechanism, the member _file in FILE structure has been intentionally renamed to _magic in Solaris Express OS, a monthly snapshot of the next major customer release of the Solaris OS currently under development, and in the OpenSolaris source-code base after build 39. This change would break the compilation of source code containing any references to FILE -> _file. Note: This alert does not apply to Solaris 10 OS, including update releases.
The following diff output shows the changes introduced in the definition of the FILE structure to accommodate the extended FILE facility:
diff
- unsigned char _file; /* UNIX system file descriptor */
+ unsigned char _magic; /*Old home of the file descriptor*/
+ /* Only fileno(3C) can retrieve the value now */
- unsigned __filler:4;
+ unsigned __extendedfd:1; /* enable extended FILE */
+ unsigned __xf_nocheck:1; /*no extended FILE runtime check*/
+ unsigned __filler:10;
Hence, the compilation of code with references to FILE -> _file will fail with the following error message on systems running the Solaris Express OS or any OpenSolaris OS distribution after build 39, and on the successor to the Solaris 10 OS when it is available.
"filename.c", line xx: undefined struct/union member: _file
cc: acomp failed for filename.c
The value found in the field formerly known as _file might no longer contain the FILE's file descriptor. If the code is simply reading the value of _file, replace all such references with the more appropriate fileno(FILE) function. See the manual page for fileno(3C). You should no longer assign a new value to _file.
When the extended FILE facility is enabled, there is no performance impact when accessing file descriptors less than or equal to 255. But there will be a slight performance degradation in accessing file descriptors greater than or equal to 256, due to the storage and retrieval of the file descriptor in an auxiliary location.
If your system is running any existing version of the Solaris 10 OS -- that is, Solaris 10 3/05 through Solaris 10 11/06 -- you can install the extended FILE facility on the system with the following set of three patches (or later revisions) for your hardware platform:
SPARC platform:
libc nss ldap PAM zfs
x86/x64 platform:
If the application code links with STLport, the C++ standard library that was shipped with the Sun Studio software compiler suite, using the -library=stlport4 compiler option, make sure to patch Sun Studio 11 software with 121017-07 or later on the SPARC platform and with 121018-07 or later on x86/x64 platforms to take advantage of extended FILEs.
STLport
-library=stlport4
Report extended FILE bugs, if any, to the OpenSolaris OS bugs page and use the OpenSolaris OS discussion forums for any clarifications.
PSARC/2006/162: Extended FILE Space for 32-Bit Solaris Processes
Manual pages:
Giri Mandalika is a software engineer in the Sun Microsystems ISV-Engineering group, working with partners and ISVs to make Sun the preferred vendor of choice for running enterprise applications. Giri holds a master's degree in computer science from the University of Texas at Dallas. The author would like to thank Craig Mohrman, Peter Shoults, and Chien Yen of Sun Microsystems for their help. | http://developers.sun.com/solaris/articles/stdio_256.html | crawl-002 | refinedweb | 3,423 | 52.09 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
how to send an automatic email and a default message to a client telling him that his claim has been saved ?
Hi Familly!!
I'm developping a claim module and i want to know if is it possible to send an automatic email and a default message to a client telling him that his claim has been saved. how can i configure that!!
(sorry for my bad english)
Hi lewis
you can make a schedule for this from
settings-- > scheduler --- > scheduled Actions
create an template in
settings-- > emails --- > template
create a model (object) and create
function in that model (object), fuction should be like this
def my_function(self,cr,uid,context=None): # search your created template id here ex: your_tem_id # search your model ids here with your codition ex: my_ids self.pool.get('email.tempalte').send_mail(self, cr, uid, your_tem_id, my_ids, force_send=True) return True
note: in schedule actions you will have to give your model object in object field and
my_function in fucntion field and in parameter field
()
Thanks
Sandeep
how to send the multiple mail with send the template using schedular..?? which code is needed to put .py file for function in scheduler
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/how-to-send-an-automatic-email-and-a-default-message-to-a-client-telling-him-that-his-claim-has-been-saved-20612 | CC-MAIN-2017-39 | refinedweb | 250 | 56.49 |
Thanks to everyone who made a donation during our annual appeal! To see the list of donors, or make a donation, see the OEIS Foundation home page.
%I
%S 1,1,2,1,6,1,4,1,2,3,30,1,6,2,2,1,28,1,8,3,4,15,18,1,6,3,2,1,30,1,330,
%T 1,10,14,12,1,12,4,2,3,78,2,28,15,2,9,30,1,4,3,28,3,16,1,6,1,8,15,476,
%U 1,18,165,4,1,6,5,152,7,6,6,60,1,84,6,2,2,60,1
%N a(n) = least k such that k*n belongs to A120383.
%C a(2*k+1) is even for any k > 0.
%H Rémy Sigrist, <a href="/A285038/b285038.txt">Table of n, a(n) for n = 1..10000</a>
%e 5 = prime(3); as 5 is coprime to 3, a(5) must be a multiple of 3; 5*3 = prime(3)*prime(2) does not belong to A120383 as it is not divisible by 2; so a(5) must also be divisible by 2; 5*3*2 belongs to A120383, hence a(5) = 3*2 = 6.
%e 7 = prime(4); as 7 is coprime to 4, a(7) must be a multiple of 4; 7*4 belongs to A120383, hence a(7)=4.
%o (PARI) complete(n) = my (c=n); my (f=factor(n)); for (i=1, #f~, c = lcm(c, primepi(f[i,1]))); return (c)
%o a(n) = my (m=n); while (1, my (mm=complete(m)); if (m==mm, return (m/n), m=mm))
%Y Cf. A120383.
%K nonn
%O 1,3
%A _Rémy Sigrist_, Apr 08 2017 | http://oeis.org/A285038/internal | CC-MAIN-2020-05 | refinedweb | 292 | 87.86 |
Java Vector Methods
Summary: The most used DS is Vector. Developer is required thorough with all the Java Vector Methods. Be comfortable to go through the tutorial.
class Vector
Vector internally is a array-based data structure (linked list is node-based) and grows dynamically when more elements are .
Usage of Vector Constructors – Internal mechanism
Four constructors exist with Vector class.
- Vector vect1 = new Vector();
- Vector vect2 = new Vector(50);
- Vector vect3 = new Vector(50, 2);
- Vector vect4 = new Vector(vect3);
A vector comes with two properties – size and capacity. When a vector object is created, it comes with a default capacity that can store 10 elements. In the above code, vect1 capacity is 10. When 10 elements capacity is exhausted, it adds automatically another 10 and this process goes on. It is like StringBuffer where default capacity is 16 and grows by 16 when the buffer exhausted.
Vector stores the elements in the form of an array. Initially, the array size is 10 (it becomes the capacity to the vector). When more elements are added, it adds one more 10 capacity. How it adds? It searches for a new memory location sufficient to store 20 elements, copies the old location 10 elements into the new location and the old location is garbage collected. So, whenever the capacity gets exhausted, it is a big overhead to the OS. To have performance, we must give less memory management to the OS to execute the program. We have seen this in file copying using BufferedInputStream where performance increased few thousand times than using
FileInputStream alone.
To overcome this to some extent, the second vector object vect2 is created with a default capacity of 50. When 50 used out, it adds one more 50 (not 10 as in vect1). If 100 gets exhausted, it adds one more 100 and like on. This type of coding can be chosen when the programmer knows the capacity he requires when the vector object creation itself. But note, after creating initial capacity, for each addition of more elements than capacity, it is a overhead to the OS.
When the memory is very small, incrementing by double the existing capacity may not be bearable to the programmer. The third vector object vect3 takes 50 default capacity and increments by 2 only. That is, it becomes 52, 54 and 56 etc. This again kills the performance. This must be played only when the programmer stores very a few above 50.
The fourth vector object vect4 is created with the elements of vect3 added implicitly. Anyhow, as usual, vect4 can add extra elements one by one with add() method.
Note: A vector capacity cannot be below the size; it may equal.
Following is the class signature of Vector class
public class Vector extends AbstractList implements List, RandomAccess, Cloneable, Serializable
Observe, vector implements List. So Vector, a legacy class, can use the latest methods of List, one of the interfaces of collections framework, like iterator(), add() etc. Now the vector is a member of collections classes. Infact, a vector can be converted into a list or list can be converted into a vector because the super class of both is Collection interface. It is shown in Vector Play With.
Java Vector Methods
Following are some important methods
- void addElement(Object obj): Adds the element obj to the vector. It appends to the existing. The method does not return any value.
- boolean add(Object obj): Adds the element obj to the vector. Return true if added else false.
- void add(int ind, Object obj): Inserts the element obj at the specified index ind.
- boolean addAll(Collection col): Adds all the elements of Collection col to the existing elements in the vector. Adds at the end of the existing elements implicitly. Returns true if added successfully.
- boolean addAll(int ind, Collection col): Inserts all the elements of Collection col to the existing elements in the vector at the specified index ind. Returns true if added successfully.
- boolean remove(Object obj): Removes the element obj from the vector. Returns true if deleted successfully.
- Object remove(int ind): Deletes the element from the vector specified with index number ind. The element deleted is returned.
- void removeElementAt(int ind): Deletes the element at the specified index number ind. This method returns void. Earlier remove() returns the object deleted..
- boolean removeElement(Object obj): Deletes the element by its name obj (not by index number). If multiple elements exist on the same name, the first occurrence is deleted.
- void removeAllElements(): Deletes all the elements from the vector. Now, if size() is called, it prints 0. This method returns void.
- boolean removeAll(Collection col): Deletes all the elements present in the Collection col (vector). Returns true if the method call is successful.
- void removeRange(int start, int end): Removes elements from the vector starting from start and ending with end-1.
- void clear(): Removes all the elements. It is inherited from Collection interface. It is equivalent to removeAllElements().
- int size(): Returns an int value, the number of elements existing in the vector.
- int capacity(): Returns the storage capacity of the vector.
- void copyInto(Object[] ar1): Copies the elements of vector into the array ar1. See that the size of the array should accommodate all the elements of the vector. Else, it throws ArrayIndexOutOfBoundsException.
- void trimToSize(): Generally, this method is called by the programmer at the end of addition of all elements. This method removes extra capacity and keeps the capacity just to hold the elements. After this method call, the capacity and size will be the same.
- void ensureCapacity(int cap): It increases the capacity by cap.
- void setSize(int size1): It sets the size to size1. If the size1 is greater than the actual number of elements, the extra capacity is filled with null values. If the size1 is less than the number of elements, the extra elements beyond the size1 are deleted. This method is used by the programmer when he would like remove some elements.
- boolean isEmpty(): Checks whether elements exist or not. If no elements exist, it returns true and if exist, returns false.
- Enumeration elements(): Returns an Enumeration object used to iterate and print the elements.
- boolean contains(Object obj): Used to check the existence of an element, say obj. If the element obj exist, it returns true else false.
- int indexOf(Object obj): It works exactly same that of String. It returns the index number of the element obj. If a number of elements exist by the same name, it returns the first occurrence. If no element exist by name obj, it returns -1. Remember, the index numbers starts from zero.
- int indexOf(Object obj, int ind): Returns the index number of element obj. The search starts from index number ind but not from beginning. If no element exist by name obj, returns -1.
- int lastIndexOf(Object obj): Returns the index number of the last existence of the element obj. Returns -1 if not element exist.
- int lastIndexOf(Object obj, int ind): Returns index number of the last existence of the element obj. Search starts from the index number ind (and not from last element). Returns -1 if no element exist.
- Object elementAt(int ind): Returns the element existing at index number ind. Returns the element at the index number ind. If the ind is more than the size of the vector or negative number, it throws ArrayIndexOutOfBoundsException.
- Object firstElement(): Returns the first element (index zero). It is equivalent to elementAt(0). If no elements exist, it throws NoSuchElementException.
- Object lastElement(): Returns the last element. If no elements exist, it throws NoSuchElementException.
- Object set(int ind, Object obj): Replaces the original element present at index ind with the new element obj.
- void setElementAt(Object obj, int ind): Replaces the original element present at index ind with the new element obj. The difference with set() is sequence of parameters and return value.
- Object clone(): The vector object is cloned. The cloned object will have the same elements of original and at the same time maintains different locations thereby perfect encapsulation ismaintained.
- Object[] toArray(): Returns an array containing the same elements of vector.
- Object get(int ind): Returns the element present at the index number ind.
- boolean containsAll(Collection col): Returns true if the vector and collection col elements, passed as parameter, are same.
- void insertElementAt(Object obj, int ind): Inserts the element obj at the specified index ind. The original element is pushed by one.
- boolean retainAll(Collection col): Retains all the elements in the vector that also exist in Collection col. The other elements in vector are deleted.
- List subList(int start, int end): Returns the elements, as a List object, starting from start and ending with end-1 existing in the vector.
Hello sir, I think there is a mistake: the second vector object vect2 is created with a default capacity of 50. When 50 used out, it adds 50 more not 10!!!
and when 100 used out, it adds 100 more and then capacity becomes 200. i tried this.
Documentation says 10. Let me check out.
Yes, you are right. | https://way2java.com/collections/vector-methods/ | CC-MAIN-2017-39 | refinedweb | 1,519 | 59.3 |
A long time ago I wrote a VBScript parser. Most of one, at least. With this in hand, I figured it couldn't be too hard to take a parsed syntax tree and generate C# that performed the same work - VBScript is simple! It's just functions and classes, it doesn't have closures or inheritance to complicate things. It's somewhat relaxed in how it deals with type comparisons, but that's because it's somewhat relaxed about how it deals with types! It could be considered a dynamic language but that just means that a bit of reflection will be required at runtime in the emitted C#. HOW HARD COULD IT BE.
This was a long time ago. A slightly less long time ago, I actually made a proper stab at it. At the time, we had huge swathes of code at work relying upon so called "Classic" ASP. The performance of these sites is fine.. so long as there are plenty of servers to spread the load over. Today, much of this is being re-written but there is still a lot of code that relies upon Classic ASP / VBScript and its particular performance characteristics (read: not good). If the code that was not important enough to be rewritten could be made faster "for free" or if the code that was good enough but that wouldn't be rewritten yet could be made faster by magic, how good would that be! (Very good).
I'm willing to make certain compromises: Eval, Execute and ExecuteGlobal would result in already "dynamic" code potentially having to be re-analysed and rewritten at runtime. That sounds insanely complicated when considered in terms of a one-pass-conversion from VBScript to C# and I can live without them (I'm happier without them!) so they're out.
Also, VBScript has a deterministic garbage collector, which seems to be why people in the days of yore used to slap "Set x = Nothing" calls at the end of functions - I don't think they did it solely to drive me mad (if you don't know what I'm talking about then you are either lucky enough never to have dealt with it or you were one of the ones doing it and don't realise why it's a waste of typing.. help me out Eric: When are you required to set objects to Nothing). Trying to emulate this perfectly would also be incredibly difficult with .net's non-determinstic GC. Maybe some sort of reference counting alternate GC could be squeezed in, but this process is going to be difficult enough without going to such lengths. (I'll make sure that all resources are disposed of after any single script / request is processed, which should be good enough).
A final compromise is that this is not going to be comparable in performance to manually-written C# code - if the VBScript could be translated into C# by a real, thinking person then that would be much better! But so long as it's significantly quicker than the original VBScript, then that will be fine. Or maybe a parallel goal could be considered - if you have a Classic ASP site and the code is all translated into C# then you could host your site on Linux using Mono and not wory about Windows Server licenses!
Problem one: VBScript just sits around isolated in a script, waiting for a request to hit it. When this happens, it starts at the top and then only jumps around when it hits IF blocks, or FUNCTION calls or CLASS instantiations, or whatever. C# is not quite like this, C# wants a clear-cut explicit entry point.
Take the following:
For i = 1 To 5 Response.Write "Hello world " & i Next
And, instead, imagine it described by a C# class thus:"); for (env.i = (Int16)1; _.StrictLTE(env.i, 5); env.i = _.ADD(env.i, (Int16)1)) { _.CALL(env.response, "Write", _.ARGS.Val(_.CONCAT("Hello world ", env.i))); } } public class EnvironmentReferences { public object response { get; set; } public object i { get; set; } } } }
Then imagine that you have an entry point into a C# project (it could be a console application if the source VBScript was an admin script but for now let's assume it's an ASP.Net project). The work at this entry point could be something like:
var env = new TranslatedProgram.EnvironmentReferences { response = Response }; using (var compatLayer = CSharpSupport.DefaultRuntimeSupportClassFactory.Get()) { new TranslatedProgram.Runner(compatLayer).Go(env); }
This assumes that "Response" is a reference to an object that exposes the interface that the original script expected (which is only a "Write" method with a single property in the example above). If we're in an ASP.Net MVC Controller then we have just such a reference handily available. If we wanted to just write some test code then we could instead construct something like
public class ResponseMock { public void Write(object value) { Console.Write(value); } }
and then use that as the value for the TranslatedProgram.EnvironmentReferences "response" property.
Hurrah! We've just saved the stuck-in-VBScript world! Rejoice! Let's all use this magic translation process and leave VBScript behind.
What's that? This all sounds a bit hypothetical? Well.. take a look at the Bitbucket repo VBScriptTranslator.
Or, actually, don't yet. I want to take a brief foray into the madnesses of VBScript (we're not going to delve right into them, we may never emerge back out!). Then I'm going to make a confession. But don't skip all the excitement before hitting the bad news - it's just about to get good!
Imagine another example. One that is somewhat contrived, such that it serves no genuine purpose when executed, but that manages to capture a surpring number and range of WTFs in a small number of lines of code. Something like..
On Error Resume Next Dim o: Set o = new C1 Dim a: a = 1 o.F1(a) If o.F2(a) Then Response.Write "Hurrah! (a = " & a & ")<br/>" Else Response.Write "Ohhhh.. sad face (a = " & a & ")<br/>" End If Class C1 Function F1(b) Response.Write "b is " & b & " (a = " & a & ")<br/>" b = 2 Response.Write "b is " & b & " (a = " & a & ")<br/>" End Function Function F2(c) Response.Write "c is " & c & " (a = " & a & ")<br/>" c = 3 Response.Write "c is " & c & " (a = " & a & ")<br/>" Response.Write "Time to die: " & (1/0) End Function End Class
VBScript veterans pop quiz! (If anyone could bear to claim such an accolade today). What will the output of this be?
If you guessed the following, then you might want to seek medical guidance, you've internalised the VBScriptz too deep and you may never regain your sanity:
b is 1 (a = 1)
b is 2 (a = 1)
c is 1 (a = 1)
c is 3 (a = 3)
Hurrah! (a = 3)
To someone who didn't know VBScript, the first two lines may seem perfectly acceptable - it looks like a function F1 was called, an argument was passed, its value was changed within that function (where it is referred to as "b") but in the caller's scope the value was not affected (where it is referred to as "a"). I mean, languages tend to pass arguments "by-value", right, which is why the change to "b" did not affect "a"?
Wrong! Oh, no no no. VBScript passes "by-ref" by default, so since the "b" argument was not declared to be either "ByVal" or "ByRef" then VBScript prefers by-ref.
So why does it not change during the F1 call but it does during the F2 call? Well, when you're not interested in the return value of a function then you shouldn't wrap the arguments in brackets. In fact, when the VBScript interpreter looks at the line
o.F1(a)
It sees a function call where the set of arguments is not wrapped in brackets (because that's not allowed when the return value is not being considered) but where the single value "a" is wrapped in brackets. And VBScript takes this to mean pass this argument as by-value, even if the receiving function wants to take the argument by-ref.
This is different to the line
If o.F2(a) Then
since we do consider the return value, so the brackets do surround the function call's argument set and are not a special wrapper just around "a".
So that it's clear that there is no ambiguity, if F1 took two arguments then it would not be valid to call it and ignore the return value and try to wrap the arguments in brackets thusly:
o.F1(a, b)
This would result in a "compile error" (which is what happens when the interpreter refuses to even attempt to run the script) -
VBScript compilation error: Cannot use parenteses when calling a Sub
While we're thinking about how this variable "a" is and isn't being mistreated, did you notice that it's being accessed from within the functions F1 and F2 that are within the class C1? This would not be a very natural arrangement in a C# program since it means that any class instance (any instance of C1 or of any other class that a program may care to define) must be able to access references and function in the "outer most scope" (which is what I call the twilight zone of code in VBScript files that "just exists", unbound by any containing class). This sounds a bit like they are static variables and functions - but if this were the case then concurrent requests would manipulate this shared state at the same time. And if I'm going to switch to C# to see a boost in performance, I don't want to be in a place where only a single request can execute at a time and the state must be reset between!
At this point, there has been no explanation for the cheery execution of the "Hurrah" statement. There is an IF statement that guards access to the displaying of this message, and the evaluation of this IF condition involves calling the function F2, which clearly results in a division-by-zero error. Well before I shed any light on that, I want to bombard you with another crazy C# code sample -"); var _env = env; var _outer = new GlobalReferences(_, _env); var errOn = _.GETERRORTRAPPINGTOKEN(); _.STARTERRORTRAPPINGANDCLEARANYERROR(errOn); _.HANDLEERROR(errOn, () => { _outer.o = _.NEW(new c1(_, _env, _outer)); }); _.HANDLEERROR(errOn, () => { _outer.a = (Int16)1; }); _.HANDLEERROR(errOn, () => { _.CALL(_outer.o, "F1", _.ARGS.Val(_outer.a)); }); if (_.IF(() => _.CALL(_outer.o, "F2", _.ARGS.Ref(_outer.a, v2 => { _outer.a = v2; })), errOn)) { _.HANDLEERROR(errOn, () => { _.CALL( _env.response, "Write", _.ARGS.Val(_.CONCAT("Hurrah! (a = ", _outer.a, ")<br/>")) ); }); } else { _.HANDLEERROR(errOn, () => { _.CALL( _env.response, "Write", _.ARGS.Val(_.CONCAT("Ohhhh.. sad face (a = ", _outer.a, ")<br/>")) ); }); } _.RELEASEERRORTRAPPINGTOKEN(errOn); } public class GlobalReferences { private readonly IProvideVBScriptCompatFunctionalityToIndividualRequests _; private readonly GlobalReferences _outer; private readonly EnvironmentReferences _env; public GlobalReferences( IProvideVBScriptCompatFunctionalityToIndividualRequests compatLayer, EnvironmentReferences env) { if (compatLayer == null) throw new ArgumentNullException("compatLayer"); if (env == null) throw new ArgumentNullException("env"); _ = compatLayer; _env = env; _outer = this; o = null; a = null; } public object o { get; set; } public object a { get; set; } } public class EnvironmentReferences { public object response { get; set; } } [ComVisible(true)] [SourceClassName("C1")] public sealed class c1 { private readonly IProvideVBScriptCompatFunctionalityToIndividualRequests _; private readonly EnvironmentReferences _env; private readonly GlobalReferences _outer; public c1( IProvideVBScriptCompatFunctionalityToIndividualRequests compatLayer, EnvironmentReferences env, GlobalReferences outer) { if (compatLayer == null) throw new ArgumentNullException("compatLayer"); if (env == null) throw new ArgumentNullException("env"); if (outer == null) throw new ArgumentNullException("outer"); _ = compatLayer; _env = env; _outer = outer; } public object f1(ref object b) { object retVal = null; _.CALL( _env.response, "Write", _.ARGS.Val(_.CONCAT("b is ", b, " (a = ", _outer.a, ")<br/>")) ); b = (Int16)2; _.CALL( _env.response, "Write", _.ARGS.Val(_.CONCAT("b is ", b, " (a = ", _outer.a, ")<br/>")) ); return retVal; } public object f2(ref object c) { object retVal = null; _.CALL( _env.response, "Write", _.ARGS.Val(_.CONCAT("c is ", b, " (a = ", _outer.a, ")<br/>")) ); b = (Int16)3; _.CALL( _env.response, "Write", _.ARGS.Val(_.CONCAT("c is ", b, " (a = ", _outer.a, ")<br/>")) ); _.CALL( _env.response, "Write", _.ARGS.Val(_.CONCAT("Time to die: ", _.DIV((Int16)1, (Int16)0))) ); return retVal; } } } }
This is a C# representation of the spot-the-WTFs VBScript sample above. And there's a lot to take in!
In terms of scoping, it's interesting to note that all variables and functions that are in VBScript's "outer most scope" are wrapped in a GlobalReferences class in the C# version. This is like the EnvironmentReferences in the first example, but instead of being passed in to the Runner's Go method, it is instantiated and manipulated solely within the translated program.
The "Go" method sets the "o" and "a" properties of the GlobalReferences class right at the start with the lines:
_outer.o = _.NEW(new c1(_, _env, _outer)); _outer.a = (Int16)1;
Then a reference to this GlobalReferences class is passed around any other translated classes - the class "C1" has become a C# class whose constructor takes an argument for the "compatibility layer" (that handles a lot of the nitty gritty of behaving precisely like VBScript) along with arguments for both the EnvironmentReferences and GlobalReferences instances. This GlobalReferences class is how state is shared between the outer scope and any class instances.
The key difference between EnvironmentReferences and GlobalReferences, by the way, is that the former consists of undeclared variables - these might be external references (such as "Response"), which should be set by the calling code before executing "Go". Or they might just be variables that were never explicitly declared in the original source - why oh why was Option Explicit something to opt into?? (That's a rhetorical question, it's waaaaay too late to worry about it now). Meanwhile, GlobalReferences consists of variables and functions that were explicitly declared in the source - these are not exposed to the calling code, they are only used internally within the TranslatedProgram class' execution. So they both have a purpose and they may both be required by translated classes such as "C1" - you may conveniently note that both functions "F1" and "F2" refer to "_env.response" and "_outer.a" (properties from the EnvironmentReferences and GlobalReferences instances, respectively).
Now let's really go crazy. VBScript's error handling is.. unusual, particularly if you are used to C# or VB.Net or JavaScript (which are just the first examples which came immediately to mind).
In C#, the following
try { Console.WriteLine("Go"); Console.WriteLine("Go!"); throw new Exception("Don't go"); Console.WriteLine("GO!"); } catch { }
would display
Go
Go!
But when you tell VBScript not to stop for errors, it takes its task seriously! This code:
On Error Resume Next Response.Write "<p>Go</p>" Response.Write "<p>Go!</p>" Err.Raise vbObjectError, "Example", "Don't go!" Response.Write "<p>GO!</p>" On Error Goto 0
will display
Go
Go!
GO!
Unlike in C#, the error does not stop it in its path, it carries on over the error.
In fact, in the IF condition in the example above, when the expression that it's evaluating throws an error (division by zero), because On Error Resume Next is hanging around, it still pushes on - not content to abandon the IF construct entirely, the condition-evaluation-error spurs it on to charge into the truth branch of the conditional. Which explains why it happily renders the "Hurrah" message.
This is why every line in the C# version of the code individually gets checked for errors (through the "HANDLEERROR" compatibility method), if any of them fail then it will just march on to the next! Even the call to the "IF" function has some special handling to swallow errors and always return true if VBScript-style error handling is in play. This poses some interesting challenges - variables must not be declared in these lambdas used by HANDLEERROR, for example, since then they wouldn't be available outside of the lambda, which would be inconsistent with the VBScript source. There are more complications I could go into, but I think I'll leave them for another day.
Why are there no HANDLEERROR calls in the functions "f1" and "f2"? In VBScript, On Error Resume Next only affects the current scope, so enabling it in the "outer most scope" does not mean that it is enabled within functions that are then called. As soon as a line in one of these function fails, the function will terminate immediately. The On Error Resume Next in the outer most scope, however, means that this error will then be silently ignored. (If error-trapping / error-ignoring was required within the functions then distinct On Error Resume Next statements would be required within each function).
What's this "errOn" variable? In C#, a try..catch has a very clearly delineated sphere of influence. In VBScript, the points at which error-trapping are enabled and disabled can not be known at compile time and so the translator code has to consider anywhere that it might be enabled and wrap all the potentially-affected statements in a HANDLEERROR call. It then keeps track, using an "error token", of when errors really do need to be swallowed at runtime. The "STARTERRORTRAPPINGANDCLEARANYERROR" call corresponds to the On Error Resume Next statement. If there was an On Error Goto 0 (VBScript's "undo On Error Resume Next" command) then there would be a corresponding "STOPERRORTRAPPINGANDCLEARANYERROR" call. Every time HANDLEERROR is called, if the work it wraps throws an error then it checks the state of the error token - if the token says to swallow the error then it does, if the token says to let the error bloom into a beautiful ball of flames then it does.
What's up with funky method call syntax - the ".ARGS.Val" and ".ARGS.Ref" in particular?? Firstly, method calls could not be translated into really plain and simple C#, as you might have hoped. This is for multiple reasons. The biggie is that, in VBScript, if you call a function and give it the wrong number of arguments then you get a runtime error. Not a compile time error (where the interpreter will refuse to even attempt to run your code). Being a runtime error, this could be swallowed if an On Error Resume Next was sticking its big nose in. But in C#, if you have a method call with the wrong number of arguments then you get a compile error and you wouldn't be able to execute code that came from runnable VBScript.
So why not use "dynamic"? It seems like an obvious choice to make would be a liberal sprinkling of the "dynamic" keyword throughout the code. But that would have all sorts of problems. Imagine this code (contrived though it may be):
CallDoSomethingForValue new Incrementer, 1 CallDoSomethingForValue new LazyBoy, 1 Function CallDoSomethingForValue(o, value) o.DoSomething value End Function Class Incrementer Function DoSomething(ByRef value) value = value + 1 End Function End Class Class LazyBoy Function DoSomething(ByVal value) ' Lazy Boy doesn't actually do anything with the value End Function End Class
The line
o.DoSomething value
would have to become either
// This form is required when calling the LazyBoy's "DoSomething" method ((dynamic)o).DoSomething(ref value);
or
// This form is required when calling the LazyBoy's "Incrementer" method ((dynamic)o).DoSomething(value);
There is no way to write that line such that it will work with a "ByRef" value and a "ByVal" method argument; one of them will fail at runtime. The only way to deal with it is to do some runtime analysis, which is pretty much what I do. If I can be absolutely sure when translating that the argument will be passed by-val (like if it's a literal such as a number, string, boolean or builtin constant, or if it's the return value of a function, or if it's wrapped in magic make-me-ByVal brackets like I talked about earlier, etc..) then the C# looks something like
_.CALL(o, "DoSomething", _.ARGS.Val("abc"));
but if it may have to be passed by-ref, then it will look someting like
_.CALL(o, "DoSomething", _.ARGS.Ref(value, v => { value = v; }));
The "Ref" variation has to accept the input argument value and then provide a way for the "CALL" method to push a new value back on top of it. When it executes, the target function's method signature is inspected and some jiggery pokery done if it is a by-ref argument.
"Val" and "Ref" may be combined if there are multiple arguments with different characteristics - eg. if a method takes three arguments where the first and last are known to be by-val but the middle one might have to be by-ref then we get this:
_.CALL(o, "DoSomethingElse", _.ARGS.Val(1).Ref(value, v => { value = v; }).Val(2));
Runtime analysis? So it's really slow? Reflection is used to try to identify what function on a target reference should be called - and what arguments, if any, need the by-ref treatment. This is not something that is particularly quick to do in .net (or anywhere, really; reflection is hardly something associated with ultimate, extreme, mind-bending performance). However, it does then compile and cache LINQ expressions for the calls - so if you are running the same code over and over again (if, say, you were hosting a web site and basically hitting a lot of the same code paths while people browse your site) then you would not pay the "reflection toll" over and over again.
So it's really fast and you've done performance analysis and it's a tightly optimised product? No. It's not even a functionally-complete product yet. Stop getting so carried away.
Why are the class and function names lower-cased in the C# code? VBScript is a case-insensitive language. C# is not, C# cares about case. This means that, where direct named references exist, a consistency must be applied - for example, in the VBScript examples there was a class named "C1" which could be instantiated with
Set o1 = new C1 ' Upper case "C1"
or with
Set o1 = new c1 ' Lower case "c1"
.. in C# there will need to be consistency, so everything is lower-cased - this includes variable names, function names, property names, class names.
There is some magic involved with the "CALL" method, so the string arguments passed to "CALL" are not monkeyed about with - but it knows at runtime what sort of manipulation might have to be supported and makes it all work. This is why the functions "f1" and "f2" have lower-cased names where they are defined, but when mentioned as arguments passed to the CALL method they appear in their original form of "F1" and "F2".
This is important since the CALL target may not actually be code that the translator has wrangled - it might be a function on a COM component, for example. Which wouldn't be a problem if the only possible transformations related to casing of names but there are other things to account for, such as keywords that are legal in VBScript but not in C# - these also are renamed in the translated code. (If you have a VBScript function named "Params" then it must be tweaked somehow for C# since "params" is a C# reserved keyword - so the function would be renamed in the translated code but the string "Params" would still appear in calls to CALL, since CALL can perform the same name-mappings at runtime that the translator does at translation time).
Well... erm, no. Not quite. There's good news and bad news. The good news is that a lot of it does work. Everything described above works - you can take that VBScript example, pass it through the translator and then execute the code that it spits out. Good news part one.
Good news part two is that I've run thousands and thousands of lines of real, production VBScript code through the translator and I've so far only found a single form of statement that trips it up. But I've got a nice succinct reproduce case put aside that I intend to use to deal with the problem soon.
Slightly less good news is that I know of some edge cases to do with runtime error-handling that are misbehaving - resulting in the translator emitting C# that is not valid. There are similar issues to do with the propagation of by-ref function arguments; as shown above, when by-ref arguments are passed to the CALL method, they are referenced within a lambda (so that they may be overwritten, since they need to be treated as by-ref arguments). But if the variable being passed happens to be a "ref" argument of the containing function then there will be a "ref" variable referenced within a lambda, which is also not valid C#. I have a strategy to make this all work properly, though, that I've started implementing but not finished yet.
The other bad news is that the runtime "compability library" is.. patchy, shall we say. Woefully incomplete might be (much) more accurate. I think that all of the methods are present in the interface (though not always with the correct signatures), it's just that I need to flesh them out. So even if your real world script was translated perfectly into C#, when you tried to execute it it would probably fall over very quickly.
A big part of the problem is just how flexible VBScript decides to be. Re-implementing its built-in functions takes care, an eye for detail and a perverse fascination with trying to work out what was going through the minds of the original authors. Take the "ROUND" function, for example. Now, a grizzled VBScripter might immediately think "Banker's rounding"! But that's the easy bit. You might be wondering what else could be complicated about the rounding of a number.. and that would be the mistake! Who says it needs to be a number that gets passed in?! The ROUND function will take a string, if it can be parsed into a numeric value. It will accept "Empty", which is VBScript's idea of an undefined value - null in C# terms. It won't accept "Null", though. Oh, no no. "Null" in VBScript isn't actually an absence of a value, it's a particular value that historically people have misused to indicate an absence of a value - using it when they should have used "Empty" ("Null" is actually equivalent to "System.DBNull.Value" in .net and its purpose in VBScript really revolves around database access - say if you wanted to pass a value to an ADO command parameter to say that it must be a null value in the data, then you would use "Null".. of course, if you write old-school ever-popular-in-VBScript string-concatenation-based SQL queries then you would never have worried about values for command parameters; you'd be too busy being hacked through SQL injection attacks).
Sorry, I got a bit side-tracked there. But unfortunately, I'm not finished talking about ROUND yet. What happens if you pass it an instance of a class? Surely that would be invalid?? Well, if that class has a default parameter-less function or readable property then ROUND will even consider that (and try and parse it into a numeric value if it isn't already a number).
My point is: being as flexible as VBScript ain't easy.
Up until this point, it's been all "if this" and "you can" that and "it should" the other (unless you already cheated and followed the Bitbucket link I told you not to go to earlier!) so I guess I need to talk about actually running the translator.
Well here we go..
var scriptContent = "Response.Write \"I want to be C#!\""; var translatedStatements = CSharpWriter.DefaultTranslator.Translate( scriptContent, new[] { "Response" } ); Console.WriteLine( string.Join( Environment.NewLine, translatedStatements.Select(c => (new string(' ', c.IndentationDepth * 4)) + c.Content) ) );
The DefaultTranslator's "Translate" function takes in a string of VBScript and a list of references that are expected to be present at runtime*. It gives you back a set of TranslatedStatement instances that all have "Content" and "IndentationDepth" properties, allowing you to format your new lovely auto-generated C# code using tabs or spaces, based upon the indentation depth of the statement and your own personal formatting opinions (I've used spaces in the example above since tabs introduce too much whitespace when viewed in the console window - I am not getting into tabs vs spaces debate here! :)
The default is to create a new class called "Runner" in a new namespace called "TranslatedProgram" with an entry method called "Go". (If you look at "Translate" method's implementation then you'll be able to see how to tweak any of these values, but let's keep it simple for now).
* Note: The default configuration is for the translator to include C# comments at the top highlighting all of the undeclared variables, along with the lines on which they are accessed - to point out how naughty you've been by not using Option Explicit. You don't want these warnings for environment references that you would never explicitly declare (such as Request, Response, etc.. if you are running in an ASP context) so the translator accepts a set of reference names that may be expected to be defined, even though there is no "DIM" statement for them.
Now, as we already saw way up there somewhere, this code can be executed like so:
var env = new TranslatedProgram.EnvironmentReferences { response = new ResponseMock() }; using (var compatLayer = CSharpSupport.DefaultRuntimeSupportClassFactory.Get()) { new TranslatedProgram.Runner(compatLayer).Go(env); }
If you've reallllllllllly been paying attention, then you might have noticed that in the example above, the translated code to create a new instance of "C1" looks like this -
_outer.o = _.NEW(new c1(_, _env, _outer));
The new instance is returned via a "NEW" method, whose only job is to track object creation. When the Dispose method on the "compatLayer" instance is called, any objects that were created during that execution will also be disposed if they implement IDisposable. And any VBScript class with a "Class_Terminate" will be transformed into a C# class that implements IDisposable. So after every "script run", every applicable "Class_Terminate" is guaranteed to be run so that any releasing that they want to do may be done. Not the same as a deterministic garbage collector, but close enough for me!
One final note: the DefaultTranslator expects to operate only on "pure" VBScript content. Which, if you're considering some old-timey admin script, is fine. But if you're looking at ASP pages, with their static markup interspersed with script, then it's a different story. The good news on that front is that all that is required is a first pass at the ASP file to deal with flattening any server-side includes and to then take all of the static markup and force it into explicit Response.Write calls.
And to do some manipulations with script blocks such as
<% =GetName() %>
since they also need to be translated into explicit Response.Write calls. In this case:
Response.Write GetName()
I've got something in the pipeline that will do this work, then you'll be able to reduce the translation work to this:
var translatedStatements = DefaultASPTranslator.Translate(scriptContent);
It will even be able to default the assume-these-are-already-declared environment references to be the ASP Application, Response, Request, Session, and Server objects - meaning there's one less thing for you, the translation maestro, to have to specify. Hooray!
So there we are. I think that in both my professional and personal life, I've tackled some fairly challenging projects.. but this, undoutedly, ranks way up there with the toughest. I've got a lot of experience with C# and with VBScript and, while I didn't really think it would be easy, I was amazed at all the subtleties of VBScript's "flexibility" (I could think of some other adjectives) and I've really enjoyed the puzzle of trying to make it fit (at least fit enough) with C#.
Not to mention that the original code I started from was old. Really old. People talk about looking back at code that you wrote six months ago - trying looking back on code you wrote six years ago. Ouch. But it was a chance to refactor where necessary, to resist refactoring where I could get away with it and then to slowly add tests to try to illustrate new functionality and fixes and offer a comforting safety net against regressions. I will freely admit that a lot of the code still is far from pretty. And the test coverage could be higher. And a lot of the tests are really kinda integration tests rather than unit tests - there's no external dependencies like file or DB access, but a lot of them still don't have the tight laser focus that a true unit test should. But then this is my own project, I'll do it however I like! :D
It still has a long way to go but I'm getting real satisfaction out of the idea of completing something so "non-trivial". (If I'm being honest, this project is a bit of an exercise in bullheadness and wanting to see something all the way through!). Now, had I been able to do this ten years.. well it might be worth a little more to the world then just a curious insight into my mind - but better late than never, right??
Find the VBScriptTranslator on Bitbucket.
Posted at 08:45
Dan is a big geek who likes making stuff with computers! He can be quite outspoken so clearly needs a blog :)
In the last few minutes he seems to have taken to referring to himself in the third person. He's quite enjoying it. | http://www.productiverage.com/translating-vbscript-into-c-sharp | CC-MAIN-2017-13 | refinedweb | 5,731 | 61.77 |
SO! I am fairly new to Python and I have a large series of files that I need to replace certain lines with other lines.
I know this may be a little confusing, but let me explain.
So I have a directory full of files, let's so temp/.
I need to iterate through all the files in that directory, using Python and modify each file, replacing certain lines.
For this, I want to have one file called newStrings.txt
ReplaceWithThis
iLikeReplacingStuff
I hate this string
Please get rid of me
Code has been tailored per the poster's request.
import os folderLocation = "temp/" lookup = dict() with open("newString.txt","r") as values: with open("oldString.txt","r") as keys: keyLines = keys.readlines() valueLines = values.readlines() for i, line in enumerate(keyLines): lookup[line] = valueLines[i] for subdir, dirs, files in os.walk(folderLocation): for fileIn in files: os.rename(folderLocation + fileIn, folderLocation + "old_" + fileIn) with open (folderLocation + "old_" + fileIn, "r") as fi: with open(folderLocation + fileIn, "w") as fo: for line in fi: if line in lookup: fo.write(lookup[line]) else: fo.write(line) | https://codedump.io/share/32KRBhOtsYSa/1/how-to-replace-multiple-strings-in-multiple-text-files | CC-MAIN-2018-09 | refinedweb | 186 | 68.16 |
Parses a well-formed XAML fragment and creates a corresponding Silverlight object tree, and returns the root of the object tree.
Public Shared Function Load ( _
xaml As String _
) As Object
Dim xaml As String
Dim returnValue As Object
returnValue = XamlReader.Load(xaml)
public static Object Load(
string xaml
)
Usage for Load is documented thoroughly in the topic Using XamlReader.Load.
A "well-formed XAML fragment" must meet the following requirements:
The XAML content string must define a single root element.
The content string XAML must be well formed XML, as well as being parseable XAML.
The required root element must also specify a default XML namespace value. This is typically the Silverlight namespace, xmlns="". This XML namespace is required explicitly in Silverlight 2 and onward whereas it was implicitly assumed in Silverlight 1.0 and its CreateFromXaml JavaScript method.
Note that these conditions report parsing exceptions but the message in the exception will specifically note the cause indicating a general format failure rather than a specific parsing failure against the vocabulary identified by the XML namespace.
Beyond being "well-formed", Load will also report failures that occur when the XAML is submitted to the parser. See "XAMLReader.Load and Parsing Behavior" section of Using XamlReader.Load.
Any objects with a Name or x:Name value in the input XAML will be considered to be within a discrete XAML namescope, once the returned object tree is added to the main object tree. This can influence your ability to find the object in scope with FindName. For details, see "XAML Namescope Considerations" section of Using XamlReader.Load.
For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers. | http://msdn.microsoft.com/en-us/library/cc190359(VS.95).aspx | crawl-002 | refinedweb | 287 | 53.92 |
Dear javaprogrammingforums administrator and members,
Hello everyone, I hope everyone is fine upon reading this thread of mine. I'm currently reading "Java How to Program Third Edition by Deitel and Deitel" and exploring about Collections Framework. I tried to program one of their source codes about the Set interface implemented by HashSet. I edited it a little though. By the way, here's the code:
[FONT="Courier New"] import java.util.*; public class Sample{ public static void main(String [] args){ String colors[]={"green","red","blue","red","blue","white", "orange","black"}; List list = new ArrayList(Arrays.asList(colors)); System.out.println(list); HashSet ref = new HashSet(list); Iterator i = ref.iterator(); System.out.println("\n\nElements with no duplicates:"); while(i.hasNext()){ System.out.print( i.next()+ " "); //Line 11 } }//main }//class [/FONT]
The program works fine, but I just wonder why the ourput in Line 11 is in this order?
orange red blue green white black
I am really expecting this output:
green red blue white orange black
I hope someone would give more information about why this came to be. I hope this is not too much to ask.
Thank you and God bless everyone.
Respectfully Yours,
MarkSquall | http://www.javaprogrammingforums.com/collections-generics/534-getting-error-while-altering-source-code.html | CC-MAIN-2014-10 | refinedweb | 199 | 58.18 |
The numbers 1, 2, 3,…, n are known as natural numbers. This program takes the value of n (entered by user) and prints the sum of first n natural numbers.
For example: If user enters the value of n as 6 then this program would display the sum of first 6 natural numbers:
1+2+3+4+5+6 = 21
In this program we are using recursion to find the sum, we can also solve this problem using loops: C++ program to find the sum of n natural numbers using loop.
Example: Program to calculate and display the sum of n natural numbers using recursion
To understand this program, you should have the knowledge of C++ recursion, if-else statement and functions.
The logic we are using in this program is:
sum(5) = 5+sum(4) = 5+4+sum(3)=5+4+3+sum(2) = 5+4+3+2+sum(1) = 5+4+3+2+1+sum(0) = 15
So the recursive function should look like this: sum(n) = n+sum(n-1)
#include<iostream> using namespace std; /* This is function declaration, When you define function * after the main then you need to declare it like this. * If you define the function before main then no need to * declare function. */ int sum(int n); int main(){ int n; cout<<"Enter the value of n(should be positive integer): "; cin>>n; /* Here we are checking whether the entered value of n is * natural number or not. If user enters the zero or negative * value then display error message else prints the sum of n * natural numbers. */ if(n<=0){ cout<<"The entered value of n is invalid"; } else{ cout<<"Sum of n natural numbers is: "<<sum(n); } return 0; } int sum(int n){ /* We are calling sum function recursively until the value * of n is equal to 0. */ if(n!= 0) { return n + sum(n-1); } return 0; }
Output:
Enter the value of n(should be positive integer): 5 Sum of n natural numbers is: 15 | https://beginnersbook.com/2017/09/cpp-program-to-find-the-sum-of-n-natural-numbers-using-recursion/ | CC-MAIN-2021-04 | refinedweb | 335 | 50.7 |
In Java, Comparator interface is used to order(sort) the objects in the collection in your own way. It gives you the ability to decide how elements will be sorted and stored within collection and map.
Comparator Interface defines
compare() method. This method has two parameters. This method compares the two objects passed in the parameter. It returns 0 if two objects are equal. It returns a positive value if object1 is greater than object2. Otherwise a negative value is returned. The method can throw a ClassCastException if the type of object are not compatible for comparison.
Rules for using Comparator interface:
For Example:
If you want to sort the elements according to roll number, defined inside the class Student, then while implementing the Comparator interface, you need to mention it generically as follows:
class MyComparator implements Comparator<Student>{}
If you write only,
class MyComparator implements Comparator {}
Then it assumes, by default, data type of the compare() method's parameter to be Object, and hence you will not be able to compare the Student type(user-defined type) objects.
Student class:
class Student int roll; String name; Student(int r,String n) { roll = r; name = n; } public String toString() { return roll+" "+name; }
MyComparator class:
This class defines the comparison logic for Student class based on their roll. Student object will be sorted in ascending order of their roll.
class MyComparator implements Comparator<Student> { public int compare(Student s1,Student s2) { if(s1.roll == s2.roll) return 0; else if(s1.roll > s2.roll) return 1; else return -1; } }
Now let's create a Test class with
main() function,
public class Test { public static void main(String[] args) { TreeSet< Student> ts = new TreeSet< Student>(new MyComparator()); ts.add(new Student(45, "Rahul")); ts.add(new Student(11, "Adam")); ts.add(new Student(19, "Alex")); System.out.println(ts); } }
[ 11 Adam, 19 Alex, 45 Rahul ]
As you can see in the ouput Student object are stored in ascending order of their roll.
Note:
public class Test { public static void main(String[] args) { ArrayList< Student> ts = new ArrayList< Student>(); ts.add(new Student(45, "Rahul")); ts.add(new Student(11, "Adam")); ts.add(new Student(19, "Alex")); Collections.sort(ts,new MyComparator()); /*passing the name of the ArrayList and the object of the class that implements Comparator in a predefined sort() method in Collections class*/ System.out.println(ts); } } | https://www.studytonight.com/java/comparators-interface-in-java.php | CC-MAIN-2020-05 | refinedweb | 396 | 56.76 |
Linear least squares fitting with linear algebra
Posted February 18, 2013 at 09:00 AM | categories: data analysis, linear algebra | tags: | View Comments
Updated February 27, 2013 at 02:38 PM
The idea here is to formulate a set of linear equations that is easy to solve. We can express the equations in terms of our unknown fitting parameters \(p_i\) as:
x1^0*p0 + x1*p1 = y1 x2^0*p0 + x2*p1 = y2 x3^0*p0 + x3*p1 = y3 etc...
Which we write in matrix form as \(A p = y\) where \(A\) is a matrix of column vectors, e.g. [1, x_i]. \(A\) is not a square matrix, so we cannot solve it as written. Instead, we form \(A^T A p = A^T y\) and solve that set of equations.
import numpy as np x = np.array([0, 0.5, 1, 1.5, 2.0, 3.0, 4.0, 6.0, 10]) y = np.array([0, -0.157, -0.315, -0.472, -0.629, -0.942, -1.255, -1.884, -3.147]) A = np.column_stack([x**0, x]) M = np.dot(A.T, A) b = np.dot(A.T, y) i1, slope1 = np.dot(np.linalg.inv(M), b) i2, slope2 = np.linalg.solve(M, b) # an alternative approach. print i1, slope1 print i2, slope2 # plot data and fit import matplotlib.pyplot as plt plt.plot(x, y, 'bo') plt.plot(x, np.dot(A, [i1, slope1]), 'r--') plt.xlabel('x') plt.ylabel('y') plt.savefig('images/la-line-fit.png')
0.00062457337884 -0.3145221843 0.00062457337884 -0.3145221843
This method can be readily extended to fitting any polynomial model, or other linear model that is fit in a least squares sense. This method does not provide confidence intervals.
Copyright (C) 2013 by John Kitchin. See the License for information about copying. | http://kitchingroup.cheme.cmu.edu/blog/2013/02/18/Linear-least-squares-fitting-with-linear-algebra/ | CC-MAIN-2019-26 | refinedweb | 303 | 77.64 |
Sooner or later, all developers are required to interact with an API. The most difficult part is always related to reliably testing the code we write, and, as we want to make sure that everything works properly, we continuosly run code that queries the API itself. This process is slow and inefficient, as we can experience network issues and data inconsistencies (the API results may change). Let’s review how we can avoid all of this effort with Ruby.
Our Goal
"Flow is essential: write the tests, run them and see them fail, then write the minimal implementation code to make them pass. Once they all do, refactor if needed."
Our goal is simple: write a small wrapper around the Dribbble API to retrieve information about a user (called ‘player’ in the Dribbble world).
As we will be using Ruby, we will also follow a TDD approach: if you’re not familiar with this technique, Nettuts+ has a good primer on RSpec you can read. In a nutshell, we will write tests before writing our code implementation, making it easier to spot bugs and to achieve a high code quality. Flow is essential: write the tests, run them and see them fail, then write the minimal implementation code to make them pass. Once they all do, refactor if needed.
The API
The Dribbble API is fairly straightforward. At the time of this it supports only GET requests and doesn’t require authentication: an ideal candidate for our tutorial. Moreover, it offers a 60 calls per minute limit, a restriction that perfectly shows why working with APIs require a smart approach.
Key Concepts
This tutorial needs to assume that you have some familiarity with testing concepts: fixtures, mocks, expectations. Testing is an important topic (especially in the Ruby community) and even if you are not a Rubyist, I’d encourage you to dig deeper into the matter and to search for equivalent tools for your everyday language. You may want to read “The RSpec book” by David Chelimsky et al., an excellent primer on Behavior Driven Development.
To summarize here, here are three key concepts you must know:
- Mock: also called double, a mock is “an object that stands in for another object in an example”. This means that if we want to test the interaction between an object and another, we can mock the second one. In this tutorial, we will mock the Dribbble API, as to test our code we don’t need the API, itself, but something that behaves like it and exposes the same interface.
- Fixture: a dataset that recreates a specific state in the system. A fixture can be used to create the needed data to test a piece of logic.
- Expectation: a test example written the from the point of view of the result we want to achieve.
Our Tools
"As a general practice, run tests every time you update them."
WebMock is a Ruby mocking library that is used to mock (or stub) http requests. In other words, it allows you to simulate any HTTP request without actually making one. The primary advantage to this is being able to develop and test against any HTTP service without needing the service itself and without incurring in related issues (like API limits, IP restrictions and such).
VCR is a complementary tool that records any real http request and creates a fixture, a file that contains all the needed data to replicate that request without performing it again. We will configure it to use WebMock to do that. In other words, our tests will interact with the real Dribbble API just once: after that, WebMock will stub all the requests thanks to the data recorded by VCR. We will have a perfect replica of the Dribbble API responses recorded locally. In addition, WebMock will let us test edge cases (like the request timing out) easily and consistently. A wonderful consequence of our setup is that everything will be extremely fast.
As for unit testing, we will be using Minitest. It’s a fast and simple unit testing library that also supports expectations in the RSpec fashion. It offers a smaller feature set, but I find that this actually encourages and pushes you to separate your logic into small, testable methods. Minitest is part of Ruby 1.9, so if you’re using it (I hope so) you don’t need to install it. On Ruby 1.8, it’s only a matter of
gem install minitest.
I will be using Ruby 1.9.3: if you don’t, you will probably encounter some issues related to
require_relative, but I've included fallback code in a comment right below it. As a general practice, you should run tests every time you update them, even if I won’t be mentioning this step explicitly throughout the tutorial.
Setup
We will use the conventional
/lib and
/spec folder structure to organize our code. As for the name of our library, we’ll call it Dish, following the Dribbble convention of using basketball related terms.
The Gemfile will contain all our dependencies, albeit they’re quite small.
source :rubygems gem 'httparty' group :test do gem 'webmock' gem 'vcr' gem 'turn' gem 'rake' end
Httparty is an easy to use gem to handle HTTP requests; it will be the core of our library. In the test group, we will also add Turn to change the output of our tests to be more descriptive and to support color.
The
/lib and
/spec folders have a symmetrical structure: for every file contained in the
/lib/dish folder, there should be a file inside
/spec/dish with the same name and the ‘_spec’ suffix.
Let’s start by creating a
/lib/dish.rb file and add the following code:
require "httparty" Dir[File.dirname(__FILE__) + '/dish/*.rb'].each do |file| require file end
It doesn’t do much: it requires ‘httparty’ and then iterates over every
.rb file inside
/lib/dish to require it. With this file in place, we will be able to add any functionality inside separate files in
/lib/dish and have it automatically loaded just by requiring this single file.
Let’s move to the
/spec folder. Here’s the content of the
spec_helper.rb file.
#we need the actual library file require_relative '../lib/dish' # For Ruby < 1.9.3, use this instead of require_relative # require(File.expand_path('../../lib/dish', __FILE__)) #dependencies require 'minitest/autorun' require 'webmock/minitest' require 'vcr' require 'turn' Turn.config do |c| # :outline - turn's original case/test outline mode [default] c.format = :outline # turn on invoke/execute tracing, enable full backtrace c.trace = true # use humanized test names (works only with :outline format) c.natural = true end #VCR config VCR.config do |c| c.cassette_library_dir = 'spec/fixtures/dish_cassettes' c.stub_with :webmock end
There's quite a few things here worth noting, so let’s break it piece by piece:
- At first, we require the main lib file for our app, making the code we want to test available to the test suite. The
require_relativestatement is a Ruby 1.9.3 addition.
- We then require all the library dependencies:
minitest/autorunincludes all the expectations we will be using,
webmock/minitestadds the needed bindings between the two libraries, while
vcrand
turnare pretty self-explanatory.
- The Turn config block merely needs to tweak our test output. We will use the outline format, where we can see the description of our specs.
- The VCR config blocks tells VCR to store the requests into a fixture folder (note the relative path) and to use WebMock as a stubbing library (VCR supports some other ones).
Last, but not least, the
Rakefile that contains some support code:
require 'rake/testtask' Rake::TestTask.new do |t| t.test_files = FileList['spec/lib/dish/*_spec.rb'] t.verbose = true end task :default => :test
The
rake/testtask library includes a
TestTask class that is useful to set the location of our test files. From now on, to run our specs, we will only type
rake from the library root directory.
As a way to test our configuration, let’s add the following code to
/lib/dish/player.rb:
module Dish class Player end end
Then
/spec/lib/dish/player_spec.rb:
require_relative '../../spec_helper' # For Ruby < 1.9.3, use this instead of require_relative # require (File.expand_path('./../../../spec_helper', __FILE__)) describe Dish::Player do it "must work" do "Yay!".must_be_instance_of String end end
Running
rake should give you one test passing and no errors. This test is by no means useful for our project, yet it implicitly verifies that our library file structure is in place (the
describe block would throw an error if the
Dish::Player module was not loaded).
First Specs
To work properly, Dish requires the Httparty modules and the correct
base_uri, i.e. the base url of the Dribbble API. Let’s write the relevant tests for these requirements in
player_spec.rb:
... describe Dish::Player do describe "default attributes" do it "must include httparty methods" do Dish::Player.must_include HTTParty end it "must have the base url set to the Dribble API endpoint" do Dish::Player.base_uri.must_equal '' end end end
As you can see, Minitest expectations are self-explanatory, especially if you are an RSpec user: the biggest difference is wording, where Minitest prefers “must/wont” to “should/should_not”.
Running these tests will show one error and one failure. To have them pass, let’s add our first lines of implementation code to
player.rb:
module Dish class Player include HTTParty base_uri '' end end
Running
rake again should show the two specs passing. Now our
Player class has access to all Httparty class methods, like
get or
Recording our First Request
As we will be working on the
Player class, we will need to have API data for a player. The Dribbble API documentation page shows that the endpoint to get data about a specific player is
As in typical Rails fashion,
:id is either the id or the username of a specific player. We will be using
simplebits, the username of Dan Cederholm, one of the Dribbble founders.
To record the request with VCR, let’s update our
player_spec.rb file by adding the following
describe block to the spec, right after the first one:
... describe "GET profile" do before do VCR.insert_cassette 'player', :record => :new_episodes end after do VCR.eject_cassette end it "records the fixture" do Dish::Player.get('/players/simplebits') end end end
After running
rake, you can verify that the fixture has been created. From now on, all our tests will be completely network independent.
The
before block is used to execute a specific portion of code before every expectation: we use it to add the VCR macro used to record a fixture that we will call ‘player’. This will create a
player.yml file under
spec/fixtures/dish_cassettes. The
:record option is set to record all new requests once and replay them on every subsequent, identical request. As a proof of concept, we can add a spec whose only aim is to record a fixture for simplebits’s profile. The
after directive tells VCR to remove the cassette after the tests, making sure that everything is properly isolated. The
get method on the
Player class is made available, thanks to the inclusion of the
Httparty module.
After running
rake, you can verify that the fixture has been created. From now on, all our tests will be completely network independent.
Getting the Player Profile
Every Dribbble user has a profile that contains a pretty extensive amount of data. Let’s think about how we would like our library to be when actually used: this is a useful way to flesh out our DSL will work. Here’s what we want to achieve:
simplebits = Dish::Player.new('simplebits') simplebits.profile => #returns a hash with all the data from the API simplebits.username => 'simplebits' simplebits.id => 1 simplebits.shots_count => 157
Simple and effective: we want to instantiate a Player by using its username and then get access to its data by calling methods on the instance that map to the attributes returned by the API. We need to be consistent with the API itself.
Let’s tackle one thing at a time and write some tests related to getting the player data from the API. We can modify our
"GET profile" block to have:
describe "GET profile" do let(:player) { Dish::Player.new } before do VCR.insert_cassette 'player', :record => :new_episodes end after do VCR.eject_cassette end it "must have a profile method" do player.must_respond_to :profile end it "must parse the api response from JSON to Hash" do player.profile.must_be_instance_of Hash end it "must perform the request and get the data" do player.profile["username"].must_equal 'simplebits' end end
The
let directive at the top creates a
Dish::Player instance available in the expectations. Next, we want to make sure that our player has got a profile method whose value is a hash representing the data from the API. As a last step, we test a sample key (the username) to make sure that we actually perform the request.
Note that we’re not yet handling how to set the username, as this is a further step. The minimal implementation required is the following:
... class Player include HTTParty base_uri '' def profile self.class.get '/players/simplebits' end end ...
A very little amount of code: we’re just wrapping a get call in the
profile method. We then pass the hardcoded path to retrieve simplebits’s data, data that we had already stored thanks to VCR.
All our tests should be passing.
Setting the Username
Now that we have a working profile function, we can take care of the username. Here are the relevant specs:
describe "default instance attributes" do let(:player) { Dish::Player.new('simplebits') } it "must have an id attribute" do player.must_respond_to :username end it "must have the right id" do player.username.must_equal 'simplebits' end end describe "GET profile" do let(:player) { Dish::Player.new('simplebits') } before do VCR.insert_cassette 'base', :record => :new_episodes end after do VCR.eject_cassette end it "must have a profile method" do player.must_respond_to :profile end it "must parse the api response from JSON to Hash" do player.profile.must_be_instance_of Hash end it "must get the right profile" do player.profile["username"].must_equal "simplebits" end end
We’ve added a new describe block to check the username we’re going to add and simply amended the
player initialization in the
GET profile block to reflect the DSL we want to have. Running the specs now will reveal many errors, as our
Player class doesn’t accept arguments when initialized (for now).
Implementation is very straightforward:
... class Player attr_accessor :username include HTTParty base_uri '' def initialize(username) self.username = username end def profile self.class.get "/players/#{self.username}" end end ...
The initialize method gets a username that gets stored inside the class thanks to the
attr_accessor method added above. We then change the profile method to interpolate the username attribute.
We should get all our tests passing once again.
Dynamic Attributes
At a basic level, our lib is in pretty good shape. As profile is a Hash, we could stop here and already use it by passing the key of the attribute we want to get the value for. Our goal, however, is to create an easy to use DSL that has a method for each attribute.
Let’s think about what we need to achieve. Let’s assume we have a player instance and stub how it would work:
player.username => 'simplebits' player.shots_count => 157 player.foo_attribute => NoMethodError
Let’s translate this into specs and add them to the
GET profile block:
... describe "dynamic attributes" do before do player.profile end it "must return the attribute value if present in profile" do player.id.must_equal 1 end it "must raise method missing if attribute is not present" do lambda { player.foo_attribute }.must_raise NoMethodError end end ...
We already have a spec for username, so we don’t need to add another one. Note a few things:
- we explicitly call
player.profilein a before block, otherwise it will be nil when we try to get the attribute value.
- to test that
foo_attributeraises an exception, we need to wrap it in a lambda and check that it raises the expected error.
- we test that
idequals
1, as we know that that is the expected value (this is a purely data-dependent test).
Implementation-wise, we could define a series of methods to access the
profile hash, yet this would create a lot of duplicated logic. Moreover, the would rely on the API result to always have the same keys.
"We will rely on
method_missingto handle this cases and ‘generate’ all those methods on the fly."
Instead, we will rely on
method_missing to handle this cases and ‘generate’ all those methods on the fly. But what does this mean? Without going into too much metaprogramming, we can simply say that every time we call a method not present on the object, Ruby raises a
NoMethodError by using
method_missing. By redefining this very method inside a class, we can modify its behaviour.
In our case, we will intercept the
method_missing call, verify that the method name that has been called is a key in the profile hash and in case of positive result, return the hash value for that key. If not, we will call
super to raise a standard
NoMethodError: this is needed to make sure that our library behaves exactly the way any other library would do. In other words, we want to guarantee the least possible surprise.
Let’s add the following code to the
Player class:
def method_missing(name, *args, &block) if profile.has_key?(name.to_s) profile[name.to_s] else super end end
The code does exactly what described above. If you now run the specs, you should have them all pass. I’d encorage you to add some more to the spec files for some other attribute, like
shots_count.
This implementation, however, is not really idiomatic Ruby. It works, but it can be streamlined into a ternary operator, a condensed form of an if-else conditional. It can be rewritten as:
def method_missing(name, *args, &block) profile.has_key?(name.to_s) ? profile[name.to_s] : super end
It’s not just a matter of length, but also a matter of consistency and shared conventions between developers. Browsing source code of Ruby gems and libraries is a good way to get accustomed to these conventions.
Caching
As a final step, we want to make sure that our library is efficient. It should not make any more requests than needed and possibly cache data internally. Once again, let’s think about how we could use it:
player.profile => performs the request and returns a Hash player.profile => returns the same hash player.profile(true) => forces the reload of the http request and then returns the hash (with data changes if necessary)
How can we test this? We can by using WebMock to enable and disable network connections to the API endpoint. Even if we’re using VCR fixtures, WebMock can simulate a network Timeout or a different response to the server. In our case, we can test caching by getting the profile once and then disabling the network. By calling
player.profile again we should see the same data, while by calling
player.profile(true) we should get a
Timeout::Error, as the library would try to connect to the (disabled) API endpoint.
Let’s add another block to the
player_spec.rb file, right after
dynamic attribute generation:
describe "caching" do # we use Webmock to disable the network connection after # fetching the profile before do player.profile stub_request(:any, /api.dribbble.com/).to_timeout end it "must cache the profile" do player.profile.must_be_instance_of Hash end it "must refresh the profile if forced" do lambda { player.profile(true) }.must_raise Timeout::Error end end
The
stub_request method intercepts all calls to the API endpoint and simulates a timeout, raising the expected
Timeout::Error. As we did before, we test the presence of this error in a lambda.
Implementation can be tricky, so we’ll split it into two steps. Firstly, let’s move the actual http request to a private method:
... def profile get_profile end ... private def get_profile self.class.get("/players/#{self.username}") end ...
This will not get our specs passing, as we’re not caching the result of
get_profile. To do that, let’s change the
profile method:
... def profile @profile ||= get_profile end ...
We will store the result hash into an instance variable. Also note the
||= operator, whose presence makes sure that
get_profile is run only if @profile returns a falsy value (like
nil).
Next we can add the forced reload directive:
... def profile(force = false) force ? @profile = get_profile : @profile ||= get_profile end ...
We’re using a ternary again: if
force is false, we perform
get_profile and cache it, if not, we use the logic written in the previous version of this method (i.e. performing the request only if we don’t have already an hash).
Our specs should be green now and this is also the end of our tutorial.
Wrapping Up
Our purpose in this tutorial was to write a small and efficient library to interact with the Dribbble API; we’ve laid the foundation for this to happen. Most of the logic we’ve written can be abstracted and reused to access all the other endpoints. Minitest, WebMock and VCR have proven to be valuable tools to help us shape our code.
We do, however, need to be aware of a small caveat: VCR can become a double-edged sword, as our tests can become too much data-dependent. If, for any reason, the API we’re building against changes without any visible sign (like a version number), we may risk having our tests perfectly working with a dataset, which is no longer relevant. In that case, removing and recreating the fixture is the best way to make sure that our code still works as expected. | http://code.tutsplus.com/tutorials/writing-an-api-wrapper-in-ruby-with-tdd--net-23875 | CC-MAIN-2014-15 | refinedweb | 3,680 | 64.91 |
Unless you teach your bot new tricks its going to remain dum.
Hello everyone. In this tutorial we are going to teach our bot some new tricks
Training your chatbot
As i browsed the web i only found two way to train your chatbot:
- Using Listrainer class
- Using chatterbot corpus
Using ListTrainer class
Import libraries
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer
Create bot and start training
chatbot = ChatBot('Training Example') trainer = ListTrainer(chatbot) trainer.train([ "Hi there!", "Hello", ]) trainer.train([ "Greetings!", "Hello", ])
Its that simple
Using Chatterbot Corpus
According to the documentation:
Chatterbot corpus is a corpus of dialog data that is included in the chatterbot module.
Corpus data is user contributed, but it is also not difficult to create one if you are familiar with the language. This is because each corpus is just a sample of various input statements and their responses for the bot to train itself with.
Installing chatterbot-corpus module
pip install chatterbot-corpus
In most cases chatterbot-corpus is not installed by default so you have to install it.
Using the corpus
Forgive me i am thinking of the corpus callosum right now. I must be mad right?
from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer ''' This is an example showing how to create an export file from an existing chat bot that can then be used to train other bots. ''' chatbot = ChatBot('Export Example Bot') # First, lets train our bot with some data trainer = ChatterBotCorpusTrainer(chatbot) trainer.train('chatterbot.corpus.english')
All this stuff can be done from a separate file as long as you specify the correct bot name.
THE THIRD WAY
After some experimentation i discovered that the corpus is not that smart, you can get easily detected by someone who knows how you chat. We could use ListTrainer right?
You cant anticipate every conversation, it would take you days if not months or years to include every possible use case. So what should do we do? Curse fbchat and chatterbot authors?........Nope
What if we make chatbot take notes silently as we chart. We do the chitty chat chat and chatbot simply learns from the boss. One day when we are confident enough.......We unleash the beast
Until next time. See you next tutorial
Bye bye
Discussion | https://dev.to/takunda/facebook-unofficial-api-chatterbot-bot-part-4-bot-see-bot-do-138d | CC-MAIN-2020-50 | refinedweb | 381 | 56.05 |
Hopefully by now everyone has heard about the new app model in SharePoint 2013. There’s a lot of documentation out there about it so I won’t go into exactly what it is. What you should know is that it’s the preferred model for developing applications going forward. If you’ve done any development with the new app model so far though, one of the things that you may have noticed is that out of the box, we only ship a framework in Visual Studio 2012 for working with SharePoint sites that use Windows authentication. A frequent request I’ve heard already is how you can build apps that work with sites that use SAML or forms based authentication. In this post I’m going to walk through exactly how to do that.
The first thing to understand is that you need to distinguish between the authentication method used in SharePoint, and the authentication method used for your hosted application. To provide a very specific example, at RTM, SharePoint apps will not work for the scenario where SharePoint is using SAML authentication and the application itself is also hosted in SharePoint. However it WILL work if the SharePoint site is using SAML authentication and the application is hosted in Azure or provider-hosted (i.e. running on some non-SharePoint web server elsewhere in your organization). It’s this latter scenario that this post focuses on – your SharePoint site is using either SAML or FBA authentication, and you are using a SAML or FBA provider-hosted application.
For reasons I’ll explain a little later, there actually is a very loose coupling between the authentication method you use in your SharePoint site and the authentication you use in your provider-hosted application. What I mean by that is that I can have a SharePoint site that uses SAML authentication for example, but my provider-hosted application could be using FBA. I can still get those two to integrate and work because of how the OAuth authentication and authorization works between them. I’ll try and illustrate this point a little later in this post.
So let’s start with my original scenario – SAML secured SharePoint and provider-hosted application. As we walk through this you’ll see that everything works almost exactly the same for FBA, and then hopefully you’ll see how the two can interoperate irrespective of whether both SharePoint and the provider-hosted app use the same authentication model or not.
For this scenario then, I’ve created an SPTrustedIdentityTokenIssuer in SharePoint. The claims mappings for it include email, UPN, and SIP claims, and email is the identity claim. I’ve created a new web application in SharePoint that is using only that identity token issuer, and authentication happens in ADFS. For my provider-hosted application, I’ve just created a simple ASP.NET application that also uses SAML claims. I’ve also created a separate relying party for it in ADFS and that’s where users for the application authenticate. I also return the email, UPN and SIP claim for users that authentication to my ASP.NET application. I first test both the SharePoint and ASP.NET application separately to make sure that the SAML configuration is configured correctly and I’m getting the expected claim values in both applications. Once that’s squared away then I can move onto the next step.
The next thing I’m going to do is to create an SPAppPrincipal for my new application. I’m not going to go into great detail on this step because I’ve already discussed it in spots and there’s a fair amount of coverage on this topic on TechNet. If you aren’t sure about how to do this you can look at this post to get you started:. For simplicity’s sake, I created my applications as high trust apps, which means that I created a certificate that I will use to sign my OAuth tokens, and I’ve configured it SharePoint by created a new SPTrustedSecurityTokenIssuer. With that in place, I just need to run a little PowerShell to create my new SPAppPrincipal:
#*********************************************************************************
#TO CREATE A NEW APP
#1. Create a new GUID. Let's say it is 09E62669-0C55-47C0-B7FD-6645D13E1D1F.
#2. Paste it into the ClientId element in the AppManifest.xml file.
#3. Paste it into the ClientId element in the web.config file for your hosted app.
#4. Run the following PowerShell to create a new appPrincipal:
$clientId = "1b7e2733-9d25-485b-bf67-2479691374dc"
$spurl =""
$spweb = Get-SPWeb $spurl
$realm = Get-SPAuthenticationRealm -ServiceContext $spweb.Site
$fullAppIdentifier = $clientId + '@' + $realm
$appPrincipal = Register-SPAppPrincipal -NameIdentifier $fullAppIdentifier -Site $spweb -DisplayName "SAML App Model"
Now that my App Principal is created, I can create my application in Visual Studio 2012. In Visual Studio I open my project that has my ASP.NET SAML application and then I add a new application to it. I select App for SharePoint 2013, then I use the wizard and configure my app to be a Provider-hosted application. By the way, this is based on using the Office Developer RTM Preview tools; these tools get a necessary update with Preview 2, which I’ll explain a little later. When the wizard is complete it will add a new SharePoint app project as well as an ASP.NET project. In this case I’m not going to use the ASP.NET project it added because I already have my SAML site app that I’m going to use. You can delete the ASP.NET project it adds if you wish, but it doesn’t hurt anything to leave it there.
Now I need to configure the SharePoint app. To do that I right-click on the AppManifest.xml file and select View Code. There are two things I need to change here:
You can close the xml file now, but then double-click on it to open it in the designer. I do this so I can set the permissions I want to use for the application. In my demo case here I’m just going to pull back the title of the web using CSOM, but I’ve gone ahead and asked for Read rights to the Site Collection scope. Once I do that, the configuration of my SharePoint app is complete.
The next thing I need to do is work with my ASP.NET SAML application. The first thing I’m going to do is to add the web.config entries that I need to use the TokenHelper.cs class that is used to create the OAuth token for SharePoint. To begin with, here’s the entries that I’ve added to my web.config:
<appSettings>
<add key="ClientId" value="6a9fef7d-42d4-4fcd-8bef-ac852dfeb3dd"/>
<add key="ClientSecret" value="9LsXrzcHXn4QJl8lImyYTUOffI9CbxA1cpikqgCA2Ug="/>
<add key="ClientSigningCertificatePath" value="C:\HighTrustCert\spapps.pfx"/>
<add key="ClientSigningCertificatePassword" value="foobar"/>
<add key="IssuerId" value="e9134021-0180-4b05-9e7e-0a9e5a524965"/>
<add key="TrustedProviderName" value="ADFS"/>
<add key="MembershipProviderName" value="FbaMember"/>
… (other entries here that are used for SAML auth)
</appSettings>
Let’s talk about these entries. The ClientId and ClientSecret you should be familiar with – these are used by all SharePoint apps. The ClientSigningCertificatePath and ClientSigningCertificatePassword are used when you are using high trust apps. In my case I’ve created a certificate and SharePoint trusts it because I’ve created my SPTrustedSecurityTokenIssuer. In order to sign my OAuth tokens with that certificate, I need to let the TokenHelper class know where the PFX is and the password for it. The next three tags are ones that you probably have not seen before.
IssuerId is a value that is used starting with the Preview 2 bits version of the TokenHelper class. This value should be the ID of the SPTrustedSecurityTokenIssuer that you created. As noted in my other blogs, you MUST use the -IsTrustBroker flag when you create the SPTrustedSecurityTokenIssuer in order to use it with multiple applications like I am here. If you don’t remember what the ID is, you can just run the Get-SPTrustedSecurityTokenIssuer cmdlet. The confusing part of this is that you do NOT want the Id value that it displays! Instead you want just the first part of the RegisteredIssuerName property, up to but not including the ampersand. For example, my RegisteredIssuerName is e9134021-0180-4b05-9e7e-0a9e5a524965@72ddc737-72e5-4102-8e1e-91cecbc9884c, so my IssuerId as you see above is e9134021-0180-4b05-9e7e-0a9e5a524965.
The next two attributes – TrustedProviderName and MembershipProviderName – are properties that I’ve added to my TokenHelper helper class. The TrustedProviderName is used when you’re SharePoint site is using SAML authentication; in that case you need to put in the name of your SPTrustedIdentityTokenIssuer. The MembershipProviderName is used when your SharePoint site is using FBA. In that case you need to put the name of the “ASP.NET Membership provider name” you set up in the authentication providers dialog for your web application.
Once the web.config is configured, then I need to add the TokenHelper.cs file to my ASP.NET SAML web application. There’s three distinct steps here:
In short, what I’ve done here is I’ve added some additional functionality to support TokenHelper with FBA and SAML sites. To minimize the amount of changes to the TokenHelper.cs class, I created another partial class. ASP.NET is stupendously cool about taking partial classes and merging them all together to make one class at runtime. I did this so that when / if TokenHelper.cs changes in the future, you won’t have to try and sync code changes into it for FBA and SAML support. Instead you can just remove the namespace and change it to a partial class again, and you should be good to go. That takes care of getting all your helper classes into your ASP.NET SAML application.
Now that everything’s there, you can write some code. This fortunately is the really simple part I think. In this case we’re just going to add this code to the default.aspx code-behind:
try
{
TokenHelper.TrustAllCertificates();
var sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
var clientContext = TokenHelper.GetS2SClientContextWithClaimsIdentity(sharepointUrl,
HttpContext.Current.User, TokenHelper.IdentityClaimType.SMTP, TokenHelper.ClaimProviderType.SAML);
if (clientContext == null)
{
Debug.WriteLine("couldn't get a client context");
}
else
clientContext.Load(clientContext.Web);
clientContext.ExecuteQuery();
HelloLit.Text = "<h2>Web title retrieved using the managed client object model</h2>" +
"<p>" + clientContext.Web.Title + "</p>";
clientContext.Dispose();
}
catch (Exception ex)
HelloLit.Text = "There was an error: " + ex.Message;
A few things to note here. First, the code should be very much like other code on TechNet that describes how to use a high trust application. Second, the mystery magic here is in this line of code:
var clientContext = TokenHelper.GetS2SClientContextWithClaimsIdentity(sharepointUrl, HttpContext.Current.User, TokenHelper.IdentityClaimType.SMTP, TokenHelper.ClaimProviderType.SAML);
The GetS2SClientContextWithClaimsIdentity is one of the helper methods. The only two things that are going to vary in your code are the last two parameters. The IdentityClaimType.SMTP indicates to the helper that I want to use the SMTP claim to identify the user to SharePoint. The ClaimProviderType.SAML tells the helper class that my ASP.NET site is using SAML authentication; if it were using FBA then the parameter would be TokenHelper.ClaimProviderType.FBA. Again – this refers to the authentication being used in my provider-hosted site – NOT the SharePoint site.
Once I get the clientContext, then I can make my CSOM call into SharePoint. I have a Literal control in my default.aspx page called HelloLit and I just plugging in the data I get into that so that is what will be displayed on my app page. Pretty simple app obviously.
Now let’s talk a little bit more about the claims piece of this and how it all works. I mentioned above that in my call to get a clientContext I configured it to retrieve the SMTP claim to identify the user to SharePoint. What that means is that I’m going to get the SMTP address from the SMTP claim that I receive in my ASP.NET application – for example, darrins@contoso.com. I’m going to add that to my OAuth token that I send to SharePoint. When SharePoint gets the OAuth token it’s going to grab that SMTP value and it’s going to do a lookup in the user profile application for a user who has that SMTP address – darrins@contoso.com. Assuming it finds a match, it will then figure out all of the claims for that user as described here:. It will take all of the claims for that user and see if any grant access to the resource being requested – in this case the title of a particular web. If it does, and if the app itself also has rights to that resource, then SharePoint returns the data we requested in our CSOM call.
This process has some important implications. First, this is why I said earlier that the authentication of the provider-hosted application and the SharePoint application don’t have to match. Assume I’m still using SAML on my provider-hosted application and I use that to retrieve an email address. When I send that over to SharePoint it’s just going to look for the user who has that email address; it doesn’t really care how that user authenticates into a SharePoint site. So if the email address darrins@contoso.com maps to a profile for a Windows user called darrins, then it will retrieve the info for that user and present it to SharePoint. If the SharePoint site is using Windows authentication and darrins has rights to that site, then everything will work. (SIDE NOTE: There are some differences in one of claims your provider-hosted app needs to send to SharePoint to let it know whether you want to access a SAML, FBA or Windows site, that is beyond the scope of this post and not really relevant to the user info. For more information see the nii claim documentation here:. That being said – in this version of ClaimsTokenHelper it assumes that if you are asking for SAML info, the SharePoint site is using SAML; if you are asking for FBA info, the SharePoint site is using FBA. If you want to make different assumptions then you will need to modify ClaimsTokenHelper.cs.
Another implication is that means that these identifying properties – really SMTP, UPN and SIP – need to be unique in your entire user profile application. So you can’t have a Windows user and a SAML user that both have the same email address for example. They have to be universally unique or your call may fail. This is important to remember mostly for test environments, where you may have the same values for an SMTP user and a Windows user.
A third implication is that you need to understand how caching works. When you make an OAuth request, SharePoint will look in its cache first for a match. So if you’ve already sent over an OAuth token where SMTP address is darrins@contoso.com, it won’t go back and query the user profile application again; instead it will pull it out of its cache. The reason I bring this up is because if you want to test with different values to see what works and what doesn’t, you should NOT test that by just modifying values in the UPA. Once a profile is cached for a user we aren’t going to go back and re-retrieve it every time you change a value in the UPA. The key here is just to use multiple user identities when you’re testing, so you can play with different values in the SMTP and SIP fields to see what works and what doesn’t.
Another point worth pointing out is regarding the application pool account used by your provider-hosted application. When you’re using Windows authentication on a site I’ve found the default app pool for ASP.NET has no problems retrieving the token signing certificate for the SPTrustedSecurityTokenIssuer. However, when you switch to using SAML or FBA that no longer works. You need to do two things to remedy this. First, use a domain account for the application pool for your provider-trusted application. Second, create a new directory to store the token signing certificate and make sure you grant at least read rights to that directory for the app pool account you use. Otherwise you will errors in the constructor for TokenHelper.cs because the default app pool account doesn’t have rights to read in the token signing certificate.
There’s one last thing to point out here about the sample code supplied with this posting. The ClaimsTokenHelper class also works with FBA users, but how does it do this? In SAML it’s simpler because there are standard claim types that hold values for SMTP and SIP claims. FBA doesn’t have anything like that – it just has roles. Since there is no standard, I came up with my own way of passing this information in the roles collection. For each of my users I created three role claims: one has a value of SMTP:theUsersSmtpAddress, one is UPN:theUsersUpn, and the other is SIP:theUsersSipAddress. In my helper method to extract the SMTP or SIP address of an FBA user I just get the roles collection for that user and look for a role that starts with either SMTP:, UPN: or SIP: and then I do some string parsing to get the actual value. If you want to do it some other way then you will need to modify the ClaimsTokenHelper class accordingly.
That pretty much wraps it up. There should be enough information here to understand how OAuth works and how we can pass information about a user between a provider-hosted application and SharePoint for SharePoint to figure out who the user is and what he or she has access to. Really the only difference between using it when you’re using SAML versus FBA is the last parameter in the GetS2SClientContextWithClaimsIdentity method. I’ve added a lot of detail in this post to try and help you understand some of the moving parts and implications of that, but at the end of the day if you just want to write some code fairly quick and not worry about any of that, for the most part you should be able to do so.
Final note: the attached zip includes a Word version of this posting, along with the token helper class and my claims token helper class that I wrote for this posting. It also includes my provider-hosted FBA and SAML sites that I used in testing this.
UPDATE: I updated the attachment on 5/23/2013. There were two primary changes - 1) was to update the ClaimsTokenHelper.cs so to reflect a change of a constant name used in TokenHelper.cs that was modified for the Preview 2 release. 2) was to add an additional parameter to the main method in ClaimsTokenHelper so that you can configure it to use an App Only Token instead of App + User token. All the samples are updated to reflect these changes.?
Steve, thanks for this nice post. I will try it out in my local dev.
"SharePoint apps will not work for the scenario where SharePoint is using SAML authentication and the application itself is also hosted in SharePoint"
Was this for RTM or this still stands true?\username), please?
thanks ? | http://blogs.technet.com/b/speschka/archive/2012/12/07/using-sharepoint-apps-with-saml-and-fba-sites-in-sharepoint-2013.aspx | CC-MAIN-2015-22 | refinedweb | 3,270 | 62.88 |
Difference between revisions of "SMILA/FAQ"
Latest revision as of 03:07, 7 April 2015 Pipelets
- 5.2 OSGI-Services / Workers
- 5.3 General> ... SMILA.log ...
If you started SMILA from within the Eclipse IDE using the launcher, you can find the log file at the project SMILA.application in your workspace.
How can I see that SMILA started correctly?
1. Open your browser at, you should see a system state overview and links to different APIs.
2. You should see no stacktraces in the log ;) and it should end with an entry like the following if SMILA has just started:
... INFO ... internal.HttpServiceImpl - HTTP server started successfully on port 8080.
Building SMILA
I receive an Out of Memory error? What can I do?
While building with SMILA.
Build fails with 'java.net.MalformedURLException: no protocol: ${eclipseBaseURL}' message
The complete error looks like this:
... build.core: ... .
Launching SMILA
Linux
How to start/stop and manage SMILA as a background process on a Linux machine?
Since the default configuration (stored in SMILA.ini) of the OSGi runtime (in our case Equinox) launcher expects that you execute it in foreground and therefore have an OSGi console running in your shell and listening to the standard input, the first thing we have to do is to advise the launcher (and thereby Equinox) to listen on some TCP port instead. This is done by adding a new line with the port number just after the "-console" line.
For example, to set console to listen at TCP port 9999, SMILA.ini would look like this:
-console 9999 ...
Now, after SMILA has been started with “$ nohup ./SMILA &”, the console can be accessed from any computer simply by opening a telnet session:
$ telnet <smila_host_name> <console_port>
Bundles
new bundle was not started
After launching SMILA my new bundle doesn't seem to be started.
If you started SMILA.launch in eclipse to launch SMILA: The launcher didn't start your new bundle. Try this:
- Add your bundle by selecting "Run Configurations" in eclipse and choose your SMILA profile.
- Select your bundle in the list and set the checkmark.
- Set the start level to "4" and the autostart to "true".
If you started SMILA.EXE to launch SMILA: Your bundle isn`t defined in config.ini or the start level isn´t correct. Try this:
- Open the file
Implementing Pipelets / OSGi Services / Bundles
Pipelets
I want to use the
ConfigUtils class in my Pipelet to read the configuration, where do I have to put my configuration files?
Configuration files are searched for in the following order:
- <SMILA>/configuration/<bundle-name>/<config-file>
- <config-file> in the root path of the bundle jar-file
See Configuration Handler for more information.
I get classloading errors in invocations of my own Pipelet when running SMILA outside the IDE. In the IDE it works
The error could look like this:
2010-11-19 11:28:36,101 ERROR [ODEServerImpl-1 ] vpu.JacobVPU - Method "run" in class "org.apache.ode.bpel.rtrep.v2.EXTENSIONACTIVITY" threw an unexpected exception. java.lang.LinkageError: loader constraint violation: loader (instance of org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader) previously initiated loading for a different type with name "org/w3c/dom/Document"
We are not completely sure, why this happens, but a solution is to set this system property in the SMILA.ini file:
-Dosgi.java.profile.bootdelegation=override
Thanks to Bogdan Sacaleanu for the solution. See this thread in the smila-dev mailing list for additional details.
OSGI-Services / Workers
I implemented/deployed an OSGi Service but it seems that it isn't activated
Check your bundle, it should contain a file like that:
OSGI-INF/<myService>.xml
In this file your service has to be referenced. If you have copied the file from some other service, be sure to change the component name in the root element to something unique, because DS does not start multiple services with the same component name.
<component name="<myService>" immediate="true">
Also the file has to be referenced in the META-INF /, by adding it to the configuration/config.ini
... <bundle-id>@4:start, ...
If you are using <tt>SMILA.launch to launch SMILA in eclipse IDE, you have to open the run/debug configuration of SMILA, check the new bundle and set Auto-Start to "true".
If you checked all the things above and it still doesn't work:
- Implement an activate() method in your service - if not already there, and check if it's called at startup.
- If your service depends on other services, check if those are activated
- If your service uses other services, check the naming of the set/unset methods in the Java code vs. those specified in the <myService>.xml
- If your services uses 3rd-party-jars, make sure that they are specified in the Bundle-ClassPath section of your MANIFEST.MF (Do not reference the lib folder here, instead reference all jars, e.g. Bundle-ClassPath: ., <lib1.jar>, <lib2.jar>). Make also sure, that they are added to the binary build ("Build" page of the manifest editor).
- If your service has super-classes you may need to include Import-Package: declarations of the super-classes in your service implementation class even if there are no compile errors.
- Use the OSGi console, e.g. via: telnet <host> 9005
- ss <bundle-ID> - check if your bundle is in the list and ACTIVE (the bundle-ID is the "Bundle-SymbolicName" from the MANIFEST.MF)
- if it isn't in the list, the bundle is not correctly deployed
- if it isn't ACTIVE but only RESOLVED it's not started (-> see hints above)
- bundle <id> - check if your service is listed here in the "Registered Services" section (the "id" can be taken from the "ss" output)
- if it isn't there, your service is not correctly deployed (-> check all points above)
My activate() / deactivate() method isn't called
Check that your activate/deactivate method is protected or public.
If you use activate()/deactivate() methods without (ComponentContext) parameter, make sure that your service description xml file contains scr namespace:
<?xml version="1.0" encoding="UTF-8"?> <scr:component xmlns:scr="" ...
I implemented a worker, everything seems fine, but the worker processes no tasks during the job run
Make sure that your worker is actually running.
In the REST API, the worker description must be found via:
Check also if your worker is really started via debug API:
A warning is shown here, if your worker coudn't be found, e.g.:
... name: "myWorker", WARNING: "Worker is not registered in WorkerManager. Maybe worker OSGI service isn't started or worker's name setting is inconsistent." ...
If you get something like this, try to check FAQ for implementing an OSGI service above.. | http://wiki.eclipse.org/index.php?title=SMILA/FAQ&diff=cur&oldid=322385 | CC-MAIN-2015-40 | refinedweb | 1,120 | 54.73 |
The other day, I stumbled across Mark Nelson's blog post describing a fairly simple NPR word puzzle: "Take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two other U.S. States. What states are these?"
Mark Nelson is a programmer, so his first instinct of course was to write a small program to solve it. Mine too. I immediately stopped reading his post, opened a new emacs buffer and spent five minutes coming up with this:
Sure enough, it gave me the answer (and like Mark Nelson, seeing it made me realize that it probably would have been even more productive to just think about it for a minute instead of writing the code).
To me, that Python code is about as simple and direct as it gets. There's nothing clever going on there. Just loop over the cartesian product of states x states, skip a couple obvious cases and then normalize the names of the states by sorting the letters and put them into a dictionary. As soon as you hit a combination that's already in the dictionary, you have your answer.
That approach to me would qualify as a "naive" or "brute force" approach. I figured there might be a more optimized approach, but with only 50 states it wasn't really worth optimizing any more. Running it took all of 18 milliseconds.
When I went back and read the rest of the blog post, my jaw dropped. His first pass, in C++ involved a quadruply nested loop, STL libraries, and was taking upwards of an hour to run. Looking at his code, he really took the notion of a "brute force" approach to a level I hadn't even considered. His second and third passes improved the runtime and even simplified the code, but they still run on the order of a few seconds. That's for a compiled, low level language. My Python code written without any particular thoughts toward efficiency running in an interpreter (so the time of starting up the python process, parsing the code, and interpreting it directly, line by line without compiler optimizations are all included in the running time) was beating it by a couple orders of magnitude.
The key, of course, is the algorithm. Python, like Ruby, Perl, and other relatively high level languages, has supports a dictionary (or hashtable if you prefer) data type at the syntax level. As a result, anyone programming in one of those languages quickly learns how to make the most of them and becomes familiar with a number of idioms, including the one I used of testing for uniqueness by keeping a 'seen' dictionary, inserting keys one by one and looking for a collision. It's dead simple, commonly used in scripting languages, and extremely efficient since inserting into a hashtable is O(1) and tends to be one of the most finely tuned parts of a scripting language's interpreter/VM.
There's nothing Python specific about the algorithm. In fact, in the comments on the post, Vince Huston submits a C++ solution that's basically identical to my approach (and probably outperforms everyone else handily). If I were forced to solve the same problem in C++, I would probably have come up with something similar. I would not be at all surprised if Vince Huston has had some experience coding in scripting languages and Mark Nelson hasn't.
The point isn't that Mark Nelson is a bad programmer. Far from it. Looking around at the rest of his site, at articles like his explanation of the The Byzantine Generals Problem (which was how I ended up on his site in the first place), and at the books he's written, I'd guess that overall, he has more breadth and depth to his understanding of algorithms and programming than I do.
My point is really just to repeat the tired, broken record cry of advocates of higher level languages that 1) using a faster, more appropriate algorithm will usually go much further in optimization than low level optimizations (using a compiled language, static types, fretting over clock cycles in an inner loop, etc) and 2) learning different programming paradigms, languages, and idioms will improve your programming even if you end up going back to a lower level language. In this case, some familiarity with dictionary idioms common in scripting languages helps immensely in producing a fast, simple solution.
Another comment on his post goes even further. Tom Moertel submits a solution implemented in Haskell. From a performance standpoint, it's pretty much the same approach as mine, using a dictionary (in this case, Haskell's Data.Map library) to do the comparisons on normalized strings. What makes it a really nice solution though, is that he approaches it by starting with a "clusterBy" higher order function that takes a signature function and a list and returns a list of groups clustered by the signature (my explanation is bad; his examples make it much more clear). Essentially, instead of directly solving the problem, he creates a general purpose tool which can then trivially be applied to the specific problem at hand. clusterBy is the kind of function that I could see being useful to other problems. So not only does he end up with the solution to this problem, he also ends up with a useful tool to make future programming tasks simpler. Haskell's smooth support of higher order functions makes this a natural approach and it seems to be the way that proficient Haskell programmers end up taking on most problems.
Python had the good taste to steal a few items from Haskell's bag of tricks though, so I was inspired to try a Python version. Here's a rough equivalent of clusterBy:
def cluster_by(f,lst): transformed = [f(x) for x in lst] d = dict() for t,i in zip(transformed,lst): d.setdefault(t,[]).append(i) return d.values()
Not as pretty as the Haskell, but works essentially the same way.
Then, to solve the original problem, we need a normalize function:
def normalize(t): letters = list(t[0] + t[1]) letters.sort() return "".join(letters)
It takes the tuple of two state names, sorts all the letters in them and returns that as a string. The final piece is just to apply cluster_by with the normalize function to the cartesian product of states x states and find the resulting entries with multiple entries (and since I was going Haskell-style, I decided to use list comprehensions instead of for loops as well):
clustered = cluster_by(normalize,[(x,y) for x in states for y in states]) print [x for x in clustered if len(x) > 2]
It runs in 25 milliseconds on my machine, so slightly more overhead than the procedural approach, but close enough to not matter and, IMO, it's cleaner and would lend itself more to further reuse of the cluster_by or normalize functions.
So first knowing an idiom from a scripting language can produce better C++ code (see Vince Huston's solution), then taking a lesson from Haskell I'm able to come up with better Python code.
I'm waiting for a Prolog programmer to come along and smoke everyone next.
Andrew - Wed 31 Oct 2007 02:00:56
”(and like Mark Nelson, seeing it made me realize that it probably would have been even more productive to just think about it for a minute instead of writing the code).”
Seeing that and thinking for two seconds, I came up with:
North Carolina
South Dakota
converting to
South Carolina
North Dakota
Anonymous - Wed 31 Oct 2007 09:56:43
You can knock off a list traversal:
def cluster_by(f, lst):
d = dict()
for x in lst:
key = f(x)
d.setdefault(key,[]).append(x)
return d.values()
And use a generator instead of a list comprehension:
clustered = cluster_by(normalize,((x,y) for x in states for y in states))
Adam Atlas - Wed 31 Oct 2007 10:28:25
You can also do this one-liner which works without adding any new functions (though you need to import itertools):
Of course, that’s clearly crossing the line from “clever” into “obfuscated”, but oh well. It was fun to write. :)
anders pearson - Wed 31 Oct 2007 14:06:39
If you really enjoy this sort of thing, just get it over with and switch to Perl. Much better language for one-liners.
kat - Wed 31 Oct 2007 18:32:00
…and incomprehensibility.
;p
Peter - Wed 31 Oct 2007 10:53:58
Well, the problem of course is that at this point, JIT-compiled dynamic languages can blow away statically compiled languages in performance. A proper JIT can extrapolate most data types, and kill the overhead of having dynamic types, except when you actually use them. Ditto for most other high-level features. At that point, you’re at the same speed. In addition, there is a number of JIT-specific optimizations that, at this point, give you about a 10 percent boost over statically compiled. In addition, the GC can optimize the cache (in typical cases, cache-optimized code is 10x faster than unoptimized, although the GC will likely gain a bit less than the 10x from hand-optimizing memory layout).
In the long term, you can expect JITs to pick data types. I say “I want a list”, and the JIT picks whether I have an array, a linked list, or some kind of tree structure, based on statistics of past use.
Sadly, no one has yet written a good dynamic JIT.
brian bulkowski - Wed 31 Oct 2007 12:08:19
Certainly an interesting post, but, in my experience, your statement about scripting vs non-scripting languages is faulty.
At the company where I started programming, hash tables were the constant metaphor. We built routers. Small, home routers for AppleTalk and IP. AppleTalk requires the knowledge of all nets by all routers (non-scalable, and not widely used now), so the answer to any question was a hash table. You’d never use a btree, you’d never use a sorted list. My favorite from that chunk of code was a three-way indexed table, which was moderately innovative coding for the time.
Today’s common availability of hash tables is less about scripting languages and more about the wide availability of excellent support classes built into languages. I credit Java for starting the mad rush to excellence, and dun C++ for retarding innovation. The STL classes are poorly designed and don’t include some of the most useful structures, while Java entered with a strong collection framework and worked hard to fix design flaws (example: early versions forced synchronization when not needed, later versions created a synchronization wrapper class). I don’t count Java as a scripting language, but perhaps you do.
Thus, I agree with your premise, although I believe you are too quick to judge “low level languages” and too slow to judge the programmer. A programmer who doesn’t follow tools improvements, and improve themselves, is a poor programmer.
My professional programming has turned to Perl, Java, and C. If I want the complexity of objects, I want the structure of Java. I may, someday, migrate from Perl, as I’m still struggling with the syntax for references, and at some point you just try another language.
In any case, it’s a good time to be a programmer. A hash table used to be an annoying, scary construct, hand coded, now it’s something you simply new up, insert to, and go to town. Sweet.
anders pearson - Wed 31 Oct 2007 14:29:23
I really wasn’t judging the language. If I were writing the same program in C++ I would have come up with pretty much the same algorithm and probably code pretty close to what Vince Huston had. The point is that having experience in higher level languages or different programming paradigms can improve your skills even if you’re coding in a lower level language because it gives you new tools for thinking about the problem. The obvious algorithm to a C++ programmer involved a bunch of nested loops while the obvious algorithm for someone with scripting experience involves a hashtable and the obvious solution for a Haskell programmer involves reusable higher order functions.
Anyone reading this post and seeing anything controversial I think is reading too much into it. It pretty much boils down to “having a broad understanding of programming is good.”
I have nothing against C++ or Java programmers or anyone else unless they have the mindset of “well, I know $LANGUAGE and I can get work done in it so there’s no point in me learning any other language that might make my head hurt.” A Lisp programmer who thinks they would have nothing to learn from studying assembly programming I would consider equally foolish.
I still have plenty to learn, myself.
Peter - Wed 31 Oct 2007 13:04:40
Bryan,
Don’t dis it until you’ve tried it. Many BASIC programmers don’t see the point of pointers (or, for the politically correct, references) or real data structures. Indeed, if you explain the things you can do with a linked list, they’ll show you how to emulate one in BASIC. In fact, although both languages are Turing-complete, and so can do the same things as the other, both have different mindsets because they make different things easy. Similarly, many C/Java programmers (such as yourself) don’t see the point of closures, functional programming, and dynamic programming. It is a different way of programming, and a different way of thinking about programming. Coming from a background of C, Java, and a little bit of Perl, it is unlikely you’ll be able to grasp the power that comes from being able to fundamentally modify your programming language to the task at hand.
There’s a big difference between having a hash table class (Java), and being able to integrate a hash table into the syntax of your language (dynamic, functional programming languages).
I’ll add that while Perl has much of the functionality of modern scripting languages, it has a very different mindset.
30 second getting started guide if you decide to pursue this: If you’re interested in what you gain, the best book is SICP by Abelson and Sussman. If you’re interested in using it, the best language is Ruby, and a good demo of it is Rails.
Joel Parker Henderson - Wed 31 Oct 2007 17:08:52
Good article, thanks.
The concept is to pick all two-state combinatations,
and there is an easy, fast, accurate model for this.
It is called “combinations without repetitions”
and can be implemented like this in pseudocode:
while state1 = states.shift
for state2 in states
# your code here… no need to skip cases
end
end
Daniel Waite - Wed 31 Oct 2007 18:27:58
It took me a while to understand what the puzzle was asking me to solve. Is that a sign I’m a poor programmer? I mean, I had a suspicion which turned out to be correct, but it took me probably 15–20 minutes to confirm it (after rewriting the author’s script in Ruby).
I’m always curious how great programmers think and solve problems, and to be honest, it worries me that you were able to “immediately stop reading,” take five minutes and have it solved. In other words, I feel pretty slow sometimes.
Did anyone else take a moment to “gear up” to solve the puzzle?
kat - Wed 31 Oct 2007 18:37:42
i was just talking with someone about learning spoken languages, and how the things i appreciate most about it is the way it allows you to think in different ways, simply because you now have vocabulary (or language structures) you lacked before. it’s definitely true of programming languages, as well. the point isn’t to argue about whether high- or low- level languages are “better” (as it of course depends on what you’re trying to accomplish), but to add more tools—and more flexibility—to the toolkit in your head.
btw, i thought about it for a second and came up with the North/South thing, too. is there a valid answer aside from that obvious one, or did you over-complicate things? :)
nonsequitur - Wed 31 Oct 2007 19:25:06
states = [“alabama”, ..., “wyoming”]
module Enumerable
def unique_combinations
a = dup
result = []
length.times { el1 = a.shift; a.each { |el2| result << [el1, el2] } } result
end
def normalize_and_cluster
dict = {}
each { |el| (dict[yield(el)] ||= []) << el } dict
end
end
states.unique_combinations.normalize_and_cluster { |state1, state2| (state1 + state2).split(//).sort }.each { |k, v| puts ”#{v0.join(’ + ’)} = #{v1.join(’ + ’)}” if v.length > 1 }
# >> northcarolina + southdakota = northdakota + southcarolina
nonsequitur - Wed 31 Oct 2007 19:30:05
A better formatted version:
Anonymous - Wed 31 Oct 2007 23:24:50
Here’s another Haskell implementation. Like you, I didn’t bother to read ahead before I solved it, and I’m not a proficient Haskell programmer, so I did not think of making a clusterBy. Here goes anyway:
import Data.List;
states = [ ... ]
pairs l = [(x,y) | (x:r) <- tails l, y <- r] statePairs = map (\(x,y) -> (sort (x ++ y),(x,y))) $ pairs states
answer = filter (\((x,),(y,)) -> x == y) $ pairs statePairs
Anonymous - Wed 31 Oct 2007 23:31:29
Don’t know what happened before. Again, but with the missing new line:
pairs l = [(x,y) | (x:r) <- tails l, y <- r] statePairs = map (\(x,y) -> (sort (x ++ y),(x,y))) $ pairs states
answer = filter (\((x,),(y,)) -> x == y) $ pairs statePairs
Anonymous - Wed 31 Oct 2007 23:35:02
OK, it’s not me. Imagine there’s a newline between ”... ]” and “statePairs = ...”
Mina Naguib - Thu 01 Nov 2007 16:30:21
I’d like to contribute a ruby solution. While the logic of using a “seen” hash is re-used, this is fairly concise due to the ruby libraries’ tendency to allow cascading calls, and the flexibility of specifying the default not-found-key-handler of the Hash object:
Anonymous - Thu 01 Nov 2007 17:47:16
I’m not so sure about your assertion that Mark Nelson isn’t a bad programmer. If you put me in C and didn’t let me use my usual hashtable library, I still would have instinctually gone for an array sorted by keys. Since the list is short, a binary search isn’t going to take much longer than a hashtable lookup, and it doesn’t require implementing a hashtable from scratch. I probably would have done that on my first shot, and certainly if I’d thought about the problem long enough to optimize and write a blog post about it.
Maybe you could claim that my instinct there comes from knowledge of scripting languages, but I was doing that kind of thing in C before I’d ever worked full-time in a scripting language. And isn’t knowledge of your trade part of what makes you a good programmer?
Anonymous - Thu 01 Nov 2007 19:25:22
Eh, maybe he’s not so bad. His optimized solution works out to be the same as using a linear search through an unsorted list instead of a binary search through a sorted list, and it runs fast enough.
AnonymousJ - Sat 03 Nov 2007 12:41:55
Implementation in J
st=:>;:
|32 40|
|33 39|
32 40 { st
northcarolina
southdakota
30 39 { st
newmexico
southcarolina
Timed run
10(6!:2) ’((2=#&>)#])a (Ctrl+D exits)
notes
——-
j601 Release
Modified solution from a post at the following link
;: – sequential machine to read 50 states into 50 row x 13 char box array
> opens boxed array to table
i=.("1#])50 50#: i.*:50 - builds a 1225 x 2 array of numbers 0 1
0 2
.
.
46 47
46 48
46 49
47 48
47 49
48 49
array i has no double numbers – no double state names
i has no transposed copies of pairs (i.e. 47, 46) – no transposed state names
[ – yield left ~ a line continuation (reversed lines)
i{st – cartesian product between array i and array st
,“2 – rank 2 append across elements
(3d array => 2d array of doubleword states)
/:~“1 – rank 1 sort characters for each doubleword state
<"1 - rank 1 box for each char sorted doubleword a in array i applied to each collection of array i
having identical keys
> – open boxed array to table
2=#& – if 2 = tally bond (tally currying)
#] – yield the left argument tally
AnonymousJ - Sat 03 Nov 2007 12:46:56
Malformed post. There should be a less than symbol right after i=.(, in place of the <
((2=#&>)#])a
AnonymousJ - Sat 03 Nov 2007 12:54:45
One more time, quotes and double quotes needed retyping</.i[a=.<"1/:~"1,"2 i{st[i=.(</"1#])50 50#:i.*:50
Rob - Fri 14 Dec 2007 00:21:31
The code with cluster_by is not nearly as clear, IMHO. The initial procedural code is probably very close to what I’d write if I wanted to solve this problem.
Alexandre Vassalotti - Fri 14 Dec 2007 23:13:28
Great post!
I had heard about the `groupby’ function, but never about `clusterby’ (which seems much more useful). You r first solution that you posted look pretty much how I would had done it. Although, I have to admit that Tom Moertel’s solution is quite elegant.
Anyway, I improved slightly your translation of Moertel’s solution. I think you will appreciate the few tweaks I did:
P.S.: Your anti-spam challenge is ambiguous.
Anonymous - Tue 11 Mar 2008 06:56:50
- Tue 11 Mar 2008 07:02:41.
Jam - Mon 27 Oct 2008 19:08:54
Less complicated version of what you wrote would be: | http://thraxil.org/users/anders/posts/2007/10/30/A-Simple-Programming-Puzzle-Seen-Through-Three-Different-Lenses/ | crawl-002 | refinedweb | 3,662 | 66.57 |
29604/how-to-implement-queue-in-python
I am using Eclipse and getting this error:
q = queue.Queue(maxsize=0) NameError: global name 'queue' is not defined
I've checked the documentations and appears that is how its supposed to be placed. Am I missing something here? Thanks for all help.
from queue import *
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
def main():
q = queue.Queue(maxsize=0)
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done
main()
Using: Eclipse SDK and Python 3.x
You are missing this
from queue import *
This imports all the classes from the queue module already. Change that line to
q = Queue(maxsize=0)
Python dictionary is a built-in type that supports ...READ MORE
This is a simple example of a ...READ MORE
You can use Deque that works better than linked list ...READ MORE
Hi all,
As per the title, I am ...READ MORE
You missed a few login data forms, ...READ MORE
You want to avoid interfering with this ...READ MORE
raw_input() was renamed to input() so now input() returns the exact string ...READ MORE
class Stack:
def __init__(self):
...READ MORE
Firstly we will import pandas to read ...READ MORE
OR | https://www.edureka.co/community/29604/how-to-implement-queue-in-python?show=29605 | CC-MAIN-2019-35 | refinedweb | 225 | 79.36 |
The functionality to perform a rename can be done in one of two ways. You can simply return ENOSYS, which tells the client's rename() that you don't support renaming, or you can handle it. If you do return ENOSYS, an end user might not notice it right away, because the command-line utility mv deals with that and copies the file to the new location and then deletes the original. For a RAM disk, with small files, the time it takes to do the copy and unlink is imperceptible. However, simply changing the name of a directory that has lots of large files will take a long time, even though all you're doing is changing the name of the directory!
In order to properly implement rename functionality, there are two interesting issues:
The rename logic is further complicated by the fact that we are dealing with two paths instead of just one. In the c_link() case, one of the pathnames was implied by either an OCB (hard link) or actually given (symlink)—for the symlink we viewed the second "pathname" as a text string, without doing any particular checking on it.
You'll notice this "two path" impact when we look at the code:
int cfs_c_rename (resmgr_context_t *ctp, io_rename_t *msg, RESMGR_HANDLE_T *handle, io_rename_extra_t *extra) { // source and destination parents and targets des_t sparent, starget, dparent, dtarget; des_t components [_POSIX_PATH_MAX]; int ncomponents; int sts; char *p; int i; struct _client_info cinfo; // 1) check for "initial subset" (mv x x/a) case i = strlen (extra -> path); if (!strncmp (extra -> path, msg -> connect.path, i)) { // source could be a subset, check character after // end of subset in destination if (msg -> connect.path [i] == 0 || msg -> connect.path [i] == '/') { // source is identical to destination, or is a subset return (EINVAL); } } // get client info if (sts = iofunc_client_info (ctp, 0, &cinfo)) { return (sts); } // 2) do destination resolution first in case we need to // do a redirect or otherwise fail the request. if (connect_msg_to_attr (ctp, &msg -> connect, handle, &dparent, &dtarget, &sts, &cinfo)) { return (sts); } // 3) if the destination exists, kill it and continue. if (sts != ENOENT) { if (sts == EOK) { if ((sts = cfs_rmnod (&dparent, dtarget.name, dtarget.attr)) != EOK) { return (sts); } } else { return (sts); } } // 4) use our friend pathwalk() for source resolution. ncomponents = _POSIX_PATH_MAX; sts = pathwalk (ctp, extra -> path, handle, 0, components, &ncomponents, &cinfo); // 5) missing directory component if (sts == ENOTDIR) { return (sts); } // 6) missing non-final component if (components [ncomponents].name != NULL && sts == ENOENT) { return (sts); } // 7) an annoying bug if (ncomponents < 2) { // can't move the root directory of the filesystem return (EBUSY); } starget = components [ncomponents - 1]; sparent = components [ncomponents - 2]; p = strdup (dtarget.name); if (p == NULL) { return (ENOMEM); } // 8) create new... if (sts = add_new_dirent (dparent.attr, starget.attr, p)) { free (p); return (sts); } starget.attr -> attr.nlink++; // 9) delete old return (cfs_rmnod (&sparent, starget.name, starget.attr)); }
The walkthrough is as follows: | http://www.qnx.com/developers/docs/6.6.0_anm11_wf10/com.qnx.doc.neutrino.cookbook/topic/s2_ramdisk_c_rename.html | CC-MAIN-2018-43 | refinedweb | 480 | 50.36 |
.
Services have access to the full range of features of a Rio JSB, and as such can be good citizens of a J2EE or CORBA environment, or a JSP Web application..
Once connected to the COS, your application provides a handy
CosConnectable object with
create,
retrieve,
update,
delete, and other methods you can use to manage shared information..
Let's take a quick look at the actual
TaskTrackerEntry:
public class TaskTrackerEntry extends CosEntry implements Archivable:
TaskTrackerEntryto represent it..
Quite a bit of the universal information in our TaskTracker is contained in a lot of small lists, so we will use a
ListEntry to help us out a bit.
public class ListEntry extends CosEntry implements Archivable
Each list entry has two public properties:
/** the name of this list */ public String mListname; /** the list. **/ public Vector mList;
The list includes an
equals method to compare two lists, and methods to add items, remove items, and so forth. The
ListEntry is, in reality, a named shared vector and is ideal for small lists.
From this basic
ListEntry we make a
UserListEntry for short lists of the user's buddies, tasks they are working on, and tasks they've reported.
The client consists of a main application
ClientApp that extends COS'
AbstractClientApp and a bunch of Swing GUI JFrames for login, task lists, task editing, and so forth. Our client is 99% user interface.
The main
ClientApp uses property change events to notify the various JFrames of changes, and registers a
CosEventListener from the COS for changes to the global shared list of projects, the users's buddies, tasks, and so forth..
This involves the following train of logic:
In order to simplify our code we have written a small private utility method called
addItemToGlobalList. Happily, this method provides an excellent example of the patterns used for writing COS code..
By either registering your
ClientApp as a
CosEventListener, or by taking advantage of Rio's
Watchable interface, you can react to changes in watched data within the system. So, for example, when you add a category to the global list of categories, every client connected to the COS gets the updated category list via a remote event. These remote events cause changes to the client's local cache of categories, thus triggering a
PropertyChangeEvent that is heard by the local GUI elements.
Similarly, when you assign a task to one of your buddies, her task list will be updated by your client. That change will be transmitted to her client if she is connected to the COS. As these are RMI remote events, they cannot be relied upon to always succeed and are not used for mission-critical events; however, the damage done to a GUI by missing the occasional update here and there is not going to cause anyone to lose sleep. The client will get another event shortly, or will repoll the COS if it hasn't heard anything in a while. Either way, the changes get through eventually.
Ensemble systems are built upon the notion that all of their component parts will probably fail unexpectedly; this includes events. Your application is more than the sum of its parts, however; what is unreliable at the component level is seamless and reliable at the application level. When people criticize RMI events for their unreliability, they are making a classic "level error."
Jini-based ensemble applications are only really secure and simple on your local network right now, but Rio's JSP interface and Lincoln Tunnel, as well as Crudlet-style XML interfaces to COS, allow thin clients, Web pages, Flash movies, and so forth to connect to a COS system as if it were any other web service.
As Jini's Davis project (login required) matures, permitting secure, authenticated, ad-hoc, distributed networks, the patterns developed within the LAN become scalable to the global network.
You can download the TaskTracker Javadocs and a regular developer build of the TaskTracker from. The build includes full time-stamped source code, from which the above examples are taken, as well as JavaDocs and an Ant build script. You will not be able to build it without COS, however, as it relies on several COS-specific APIs.
The COS Javadocs are online at cosproject.sourceforge.net. The COS source code is being prepared for release soon. Current plans are to separate out the API code from the implemetation code, much in the manner of Jini, before the source is released.
Rio
Using Jini to Build a Catastrophe-Resistant System, Part 1
Dave Sag is a skilled Object Modeler and Software Designer, using Java as well as other programming environments.
Return to ONJava.com. | http://www.onjava.com/lpt/a/1689 | CC-MAIN-2015-14 | refinedweb | 776 | 57.3 |
- NAME
- SYNOPSIS
- Start using Devel::PPPort for XS projects
- DESCRIPTION
- FUNCTIONS
- COMPATIBILITY
- BUGS
- AUTHORS
- SEE ALSO
NAME
Devel::PPPort - Perl/Pollution/Portability
SYNOPSIS
Devel::PPPort::WriteFile(); # defaults to ./ppport.h Devel::PPPort::WriteFile('someheader.h'); # Same as above but retrieve contents rather than write file my $contents = Devel::PPPort::GetFileContents(); my $contents = Devel::PPPort::GetFileContents('someheader.h');
Start using Devel::PPPort for XS projects
$ cpan Devel::PPPort $ perl -MDevel::PPPort -e'Devel::PPPort::WriteFile' $ perl ppport.h --compat-version=5.6.1 --patch=diff.patch *.xs $ patch -p0 < diff.patch $ echo ppport.h >>MANIFEST
DESCRIPTION
Perl's API has changed over time, gaining new features, new functions, increasing its flexibility, and reducing the impact on the C namespace environment (reduced pollution). The header file written by this module, typically ppport.h, attempts to bring some of the newer Perl API features to older versions of Perl, so that you can worry less about keeping track of old releases, but users can still reap the benefit.
Devel::PPPort contains two functions,
WriteFile and
GetFileContents.
WriteFile's only purpose is to write the ppport.h C header file. This file contains a series of macros and, if explicitly requested, functions that allow XS modules to be built using older versions of Perl. Currently, Perl versions from __MIN_PERL__ to __MAX_PERL__ are supported.
GetFileContents can be used to retrieve the file contents rather than writing it out.
This module is used by
h2xs to write the file ppport.h.
Why use ppport.h?
You should use ppport.h in modern code so that your code will work with the widest range of Perl interpreters possible, without significant additional work.
You should attempt older code to fully use ppport.h, because the reduced pollution of newer Perl versions is an important thing. It's so important that the old polluting ways of original Perl modules will not be supported very far into the future, and your module will almost certainly break! By adapting to it now, you'll gain compatibility and a sense of having done the electronic ecology some good.
How to use ppport.h
Don't direct the users of your module to download
Devel::PPPort. They are most probably no XS writers. Also, don't make ppport.h optional. Rather, just take the most recent copy of ppport.h that you can find (e.g. by generating it with the latest
Devel::PPPort release from CPAN), copy it into your project, adjust your project to use it, and distribute the header along with your module.
Running ppport.h
But ppport.h is more than just a C header. It's also a Perl script that can check your source code. It will suggest hints and portability notes, and can even make suggestions on how to change your code. You can run it like any other Perl program:
perl ppport.h [options] [files]
It also has embedded documentation, so you can use
perldoc ppport.h
to find out more about how to use it.
FUNCTIONS
WriteFile
WriteFile takes one optional argument. When called with one argument, it expects to be passed a filename. When called with no arguments, it defaults to the filename ppport.h.
The function returns a true value if the file was written successfully. Otherwise it returns a false value.
GetFileContents
GetFileContents behaves like
WriteFile above, but returns the contents of the would-be file rather than writing it out.
COMPATIBILITY
ppport.h supports Perl versions from __MIN_PERL__ to __MAX_PERL__ in threaded and non-threaded configurations.
Provided Perl compatibility API
The header file written by this module, typically ppport.h, provides access to the following elements of the Perl API that is not available in older Perl releases:
__PROVIDED_API__
Perl API not supported by ppport.h
There is still a big part of the API not supported by ppport.h. Either because it doesn't make sense to back-port that part of the API, or simply because it hasn't been implemented yet. Patches welcome!
Here's a list of the currently unsupported API, and also the version of Perl below which it is unsupported:
__UNSUPPORTED_API__
BUGS
If you find any bugs,
Devel::PPPort doesn't seem to build on your system, or any of its tests fail, please send a bug report to perlbug@perl.org.
AUTHORS
Version 1.x of Devel::PPPort was written by Kenneth Albanowski.
Version 2.x was ported to the Perl core by Paul Marquess.
Version 3.x was ported back to CPAN by Marcus Holland-Moritz.
Versions >= 3.22 are maintained with support from Matthew Horsfall (alh).. | http://web-stage.metacpan.org/pod/Devel::PPPort | CC-MAIN-2019-39 | refinedweb | 765 | 58.28 |
Even if you've only dipped your toes into the world of iOS development, you almost certainly know about
UIAlertView. The
UIAlertView class has a simple interface and is used to present modal alerts.
Apple has deprecated
UIAlertView in iOS 8 though. As of iOS 8, it is recommended to use the
UIAlertController class to present action sheets and modal alerts. In this quick tip, I will show you how easy it is to transition from
UIAlertView to
UIAlertController.
1. Project Setup
Launch Xcode 6.3+ and create a new project based on the Single View Application template.
Name the project Alerts, set Language to Swift, and set Devices to iPhone. Tell Xcode where you'd like to store the project files and click Create.
Let's start by adding a button to trigger an alert view. Open Main.storyboard and add a button to the view controller's view. Set the button's title to Show Alert and add the necessary constraints to the button to keep it in place.
Open ViewController.swift and add an action to the class implementation. Leave the action's implementation empty for the time being. Revisit Main.storyboard and connect the view controller's
showAlert action with the button's Touch Up Inside event.
@IBAction func showAlert(sender: AnyObject) { }
2.
UIAlertView
Let's start by showing an alert view using the
UIAlertView class. As I mentioned, the interface of the
UIAlertView class is very simple. The operating system takes care of the nitty gritty details. This is what the updated implementation of the
showAlert action looks like.
@IBAction func showAlert(sender: AnyObject) { // Initialize Alert View let alertView = UIAlertView(title: "Alert", message: "Are you okay?", delegate: self, cancelButtonTitle: "Yes", otherButtonTitles: "No") // Configure Alert View alertView.tag = 1 // Show Alert View alertView.show() }
The initialization is straightforward. We provide a title and a message, pass in a delegate object, a title for the cancel button, and titles for any other buttons we'd like to include.
The delegate object needs to conform to the
UIAlertViewDelegate protocol. Because the view controller will act as the alert view's delegate, the
ViewController class needs to conform to the
UIAlertViewDelegate protocol.
import UIKit class ViewController: UIViewController, UIAlertViewDelegate { ... }
The methods of the
UIAlertViewDelegate protocol are defined as optional. The method you'll use most often is
alertView(_:clickedButtonAtIndex:). This method is invoked when the user taps one of the alert view's buttons. This is what the implementation of the
alertView(_:clickedButtonAtIndex:) method could look like.
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if alertView.tag == 1 { if buttonIndex == 0 { println("The user is okay.") } else { println("The user is not okay.") } } }
Build and run the application in the iOS Simulator to see if everything is working as expected.
3.
UIAlertController
The interface of
UIAlertController is very different from that of
UIAlertView, but Apple's motivation to transition to the
UIAlertController class makes sense once you've used it a few times. It's an elegant interface that will feel familiar.
The first benefit of using the
UIAlertController class is the absence of a delegate protocol to handle user interaction. This means that we only need to update the implementation of the
showAlert action. Take a look at the updated implementation below.
@IBAction func showAlert(sender: AnyObject) { // Initialize Alert Controller let alertController = UIAlertController(title: "Alert", message: "Are you okay?", preferredStyle: .Alert) // Initialize Actions let yesAction = UIAlertAction(title: "Yes", style: .Default) { (action) -> Void in println("The user is okay.") } let noAction = UIAlertAction(title: "No", style: .Default) { (action) -> Void in println("The user is not okay.") } // Add Actions alertController.addAction(yesAction) alertController.addAction(noAction) // Present Alert Controller self.presentViewController(alertController, animated: true, completion: nil) }
The initialization is pretty easy. We pass in a title, a message, and, most importantly, set the preferred style to
UIAlertControllerStyle.Alert or
.Alert for short. The preferred style tells the operating system if the alert controller needs to be presented as an action sheet,
.ActionSheet, or a modal alert,
.Alert.
Instead of providing titles for the buttons and handling user interaction through the
UIAlertViewDelegate protocol, we add actions to the alert controller. Every action is an instance of the
UIAlertAction class. Creating an
UIAlertAction is simple. The initializer accepts a title, a style, and a handler. The style argument is of type
UIAlertActionStyle. The handler is a closure, accepting the
UIAlertAction object as its only argument.
The use of handlers instead of a delegate protocol makes the implementation of a modal alert more elegant and easier to understand. There's no longer a need for tagging alert views if you're working with multiple modal alerts.
Before we present the alert controller to the user, we add the two actions by calling
addAction(_:) on the
alertController object. Note that the order of the buttons of the modal alert is determined by the order in which the actions are added to the alert controller.
Because the
UIAlertController class is a
UIViewController subclass, presenting the alert controller to the user is as simple as calling
presentViewController(_:animated:completion:), passing in the alert controller as the first argument.
4.
UIActionSheet
Unsurprisingly, Apple also deprecated the
UIActionSheet class and the
UIActionSheetDelegate protocol. As of iOS 8, it is recommended to use the
UIAlertController class to present an action sheet.
Presenting an action sheet is identical to presenting a modal alert. The only difference is the alert controller's
preferredStyle property, which needs to be set to
UIAlertControllerStyle.ActionSheet, or
.ActionSheet for short, for action sheets.
Conclusion
Even though
UIAlertView and
UIActionSheet are deprecated in iOS 8, you can continue using them for the foreseeable future. The interface of the
UIAlertController class, however, is a definite improvement. It adds simplicity and unifies the API for presenting modal alerts and action sheets. And because
UIAlertController is a
UIViewController subclass, the API will already feel familiar.
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.Update me weekly | https://code.tutsplus.com/tutorials/ios-fundamentals-uialertview-and-uialertcontroller--cms-24038?ec_unit=translation-info-language | CC-MAIN-2021-49 | refinedweb | 1,006 | 58.79 |
Jan 31, 2012 07:38 AM|BoEneD|LINK
Hey folks,
first of all, i'm total newbie to all this ASP.net stuff.
I got a DB where the employee from the it branch can write their duties into a table with different arrays like title, start time, end time etc. We decided do work with a MS Access DB, because it seems to be the easiest way to update by just opening the database and the gui for the tables and then add a new topics.
The idea is now, that I build a Intranet-Homepage, where other employees can inform themselves about current changes in f.e. our merchandise management system. Something like a news site...
My question is now: is there any possibility that I somehow connect the cshtml page in WebMatrix to the Access database. I just want to read the different arrays dynamicly, it is not neccessary to write into the database.
Thx in advance :)
greetings
Benedikt
All-Star
16526 Points
Jan 31, 2012 10:39 AM|stevenbey|LINK
Hi Benedikt
This video should help you.
Jan 31, 2012 10:47 AM|BoEneD|LINK
yeah it definitly gives me a better overview :) but my problem is: my collegues open a Access Database... update their content and close MS Access... is there a possibility to update the SDF-Database that I use in WebMatrix from the Access Database, or automatically sync it or the better option would be to directly use the Access Database.
All-Star
16526 Points
Jan 31, 2012 12:17 PM|stevenbey|LINK
You can connect to any kind of database, not just SQL Compact Edition. All you need to do is use the correct database connection/command and connection string. To connect to an Access database, you need to use the System.Data.OleDb namespace and ensure that you include the provider in the connection string. For example:
using(var conn = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = D:\\mydb.mdb")) using(var cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT * FROM [Table1]"; conn.Open(); using(var reader = cmd.ExecuteReader()) { ... } }
Jan 31, 2012 12:50 PM|BoEneD|LINK
oh okay.. but where do i put this code exactly? some websites told me to modify the _AppStart.cshtml, some said to directly in the specific file...
i tried it in the specific file, but it didn't even markup the syntax or recognized any code... ^^
sry I'n not experienced @ all with those kind of stuff.. :D cfml was way easier :D
Jan 31, 2012 11:13 PM|cbergman|LINK
This is something that I've been looking into for the past couple of days myself. They make it all nice and easy to open a connection to an SQL CE Database and access its data using C# Razor Syntax, but it would appear that if you want to open and access any other type of database (Microsoft Access DB for instance; .accdb or .mdb file extension) you need to use ADO.NET - at least for the time being until (hopefully) they add 'native' Razor Syntax for accessing other types of databases other than SQL CE DBs. It would probably be helpful to look into a book for an explantion of what ADO.NET is and how to use it, or at least research it a bit on the interwebs. I've just started looking deeper into my Beginning Visual C# 2008 by Wrox that's been explaining it pretty well and giving excellent examples on how to open different types of database connections and access their data. Here's the example they have for accessing an Access (.mdb) database with a console application.
using System; using System.Data; // Use ADO.NET namespace using System.Data.OleDb; // Use namespace for OLE DB .NET Provider using System.Collections.Generic; using System.Text; static void Main(string[] args) { // Create connection object for Microsoft Access OLE DB Provider; // note @ sign prefacing string literal so backslashes in path name; // work. OleDbConnection thisConnection = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Northwind\nwind.mdb"); // Open connection object thisConnection.Open(); // Create SQL command object on this connection OleDbCommand thisCommand = thisConnection.CreateCommand(); // Initialize SQL SELECT command to retrieve desired data thisCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers"; // Create a DataReader object based on previously defined command object OleDbDataReader thisReader = thisCommand.ExecuteReader(); while (thisReader.Read()) { Console.WriteLine("\t{0}\t{1}", thisReader["CustomerID"], thisReader["CompanyName"]); } thisReader.Close(); thisConnection.Close(); Console.Write("Program finished, press Enter/Return to continue:"); Console.ReadLine(); }
Taking this out of its Console Application context and adapting it to an ASP.NET application is fairly simple. You can place this code inside of a .cshtml file just like you would any C# code. So your basic .cshtml file:
@{ Layout = "~/_SiteLayout.cshtml"; Page.Title = "Some page title"; } @{ Place content here... }
Becomes something like:
@using System.Data @* My page worked just fine without this using statement, but I'll throw it in just in case.*@ @using System.Data.OleDb @* Be sure to include this using statement for the OLE DB .NET Data Provider namespace. *@ @{ Layout = "~/_SiteLayout.cshtml"; Page.Title = "Database Test Page"; } @{ // Create connection object for Microsoft Access OLE DB Provider. // Again, notice the @ sign prefacing the string literal so that the slashes // in the path name aren't interpreted as escape characters. var thisConnection = new OleDbConnection(@"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Documents and Settings\YOURUSERNAME\My Documents\My Web Sites\WebSite1\App_Data\database.mdb"); // Open Connection object thisConnection.Open(); // Create SQL command object on this connection var thisCommand = thisConnection.CreateCommand(); // Initialize SQL Select command to retrieve desired data thisCommand.CommandText = "SELECT * FROM tableName"; // Create a DataReader object based on previously defined command object OleDbDataReader thisReader = thisCommand.ExecuteReader(); <table> <tr><td>COLUMN1:</td><td>COLUMN2:</td><td>COLUMN3:</td></tr> @* Read() Advances the OleDbDataReader to the next record *@ @while(thisReader.Read()) { <tr> <td>@thisReader["COLUMN1"]</td> @* Print COLUMN1 field *@ <td>@thisReader["COLUMN2"]</td> @* Print COLUMN2 field *@
<td>@thisReader["COLUMN3"]</td> @* Print COLUMN3 field *@
@* And so on... *@
</tr> } </table> }
From that code, all you really need to change is the path to your own particular database inside of the ConnectionString (@"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=C:\Your\File\Path\Here\databaseFile.mdb), the table name in the SELECT statement, and which fields (columns) to print to the screen, and you should be good to go (at least for a basic select query). You can access every column in the result table from your query using the @thisReader["Name_of_Column_Goes_Here"] command. Again, it would probably be a good idea to research ADO.NET a bit to learn more about accessing/manipulating databases with it; learn its syntax and methods/commands.
Hope that helps!
P.S. I typed out all the code myself, so I appologize for any possible spelling errors.
Feb 01, 2012 06:09 AM|BoEneD|LINK
cbergman, you made my day! :D thx a lot :D just woke up and tried it right away.. worked PERFECTLY, i just had to change the
@"Provider = Microsoft.Jet.OLEDB.4.0;
to
@"Provider = Microsoft.ACE.OLEDB.12.0
thx a lot! :D now i just need to find out, why he puts a div tag around the content of a memo field ^^
Feb 01, 2012 03:51 PM|cbergman|LINK
Awesome! I'm glad it worked out for you ^_^ Ah, 12.0 must be for newer Office software. The database I'm accessing is an Office 2007 file so 4.0 did the trick. Now to get to work implementing it further into my own project
Member
2 Points
Feb 28, 2013 07:38 PM|mariammtariq|LINK
Hello, I am very new to asp.net. I am facing the very same problem: I wanna connect to an access database with web matrix.
I tried this piece of code you posted but it did not work. My question is, do i need to download something extra in order to make this piece of code work? I have Web Matrix 2, IIS Express 7, Microsoft Access 2007. Do i need to download something more in order for the code to work?
Please reply asap!
Thanks!
8 replies
Last post Feb 28, 2013 07:38 PM by mariammtariq | http://forums.asp.net/t/1764216.aspx?Connect+to+accdb+Database+with+WebMatrix | CC-MAIN-2014-15 | refinedweb | 1,373 | 59.09 |
jQuery is basically a toolkit with many DOM-related features while Mootools is more modular. They conflict because they have a few identically named functions and namespaces and as a result one or both scripts don't work, or at least don't work properly. In my experience it usually it is Mootools that loses out in this deal.
There are several workarounds available to make jQuery and Mootools work together. Some call for editing the core scripting of jQuery and others call for modifying your script, mostly just to avoid conflict with the "$" function that both rely on heavily. I tried several of these in the past, none worked that well and most just plain broke the script entirely. Maybe it was my fault for not implementing the changes properly, I dunno. I would post those here but it may confuse some who, like me, sometimes just skim pages looking for code snippets to fix what they already have.
After trying the hard way numerous times I found a very simple addition to jQuery scripts that makes it free up constants and variables so that other modules, like Mootools, can use them. In the simplest of terms you tell jQuery to not conflict.
Just add the following little line to the very top of your Jquery script(s), right after the script tag.
This method will usually make Jquery and Mootools play nice together with the least amount of headache. It has worked for me many times. | http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_3099-Using-Mootools-and-jQuery-on-the-same-page.html | crawl-003 | refinedweb | 248 | 77.77 |
Prev
C++ VC ATL STL Singleton Experts Index
Headers
Your browser does not support iframes.
Re: Singleton_pattern and Thread Safety
From:
James Kanze <james.kanze@gmail.com>
Newsgroups:
comp.lang.c++
Date:
Mon, 13 Dec 2010 02:44:43 -0800 (PST)
Message-ID:
<88ae426c-807e-438b-863e-ebe0a3f3e1ba@p11g2000vbn.googlegroups.com>
On Dec 11, 4:08 am, Leigh Johnston <le...@i42.co.uk> wrote:
On 11/12/2010 03:40, Joshua Maurice wrote:
On Dec 10, 7:17 pm, Leigh Johnston<le...@i42.co.uk> wrote:
On 11/12/2010 03:12, Joshua Maurice wrote:
Normally I instantiate all my singletons up front
(before threading) but I decided to quickly roll a new
singleton template class just for the fun of it
(thread-safe Meyers Singleton):
namespace lib
{
template <typename T>
class singleton
{
public:
static T& instance()
{
if (sInstancePtr != 0)
return static_cast<T&>(*sInstancePtr);
{ // locked scope
lib::lock lock1(sLock);
static T sInstance;
{ // locked scope
lib::lock lock2(sLock); // second lock should emit memory barrier here
sInstancePtr = &sInstance;
}
}
return static_cast<T&>(*sInstancePtr);
}
private:
static lib::lockable sLock;
static singleton* sInstancePtr;
};
template <typename T>
lib::lockable singleton<T>::sLock;
template <typename T>
singleton<T>* singleton<T>::sInstancePtr;
}
Even though a memory barrier is emitted for a specific
implementation of my lockable class it obviously still
relies on the C++ compiler not re-ordering stores across
a library I/O call (acquiring the lock) but it works fine
for me at least (VC++). I could mention volatile but
I better not as that would start a long argument. Roll
on C++0x.
If I'm reading your code right, on the fast path, you
don't have a barrier, a lock, or any other kind of
synchronization, right? If yes, you realize you've coded
the naive implementation of double checked? You realize
that it's broken, right? Have you even read
? To be clear, this has undefined behavior according to
the C++0x standard as well.
I am aware of double checked locking pattern yes and this
is not the double checked locking pattern (there is only
one check of the pointer if you look). If a pointer
read/write is atomic is should be fine (on the
implementation I use it is at least).
You've hidden the second check with the static keyword.
Example: Consider:
SomeType& foo()
{
static SomeType foo;
return foo;
}
For a C++03 implementation, it's likely implemented with something
like:
SomeType& foo()
{
static bool b = false; /*done before any runtime execution, stored
in the executable image */
static char alignedStorage[sizeof(SomeType)]; /*with some magic
for alignment */
if ( ! b)
new (alignedStorage) SomeType();
return * reinterpret_cast<SomeType*>(alignedStorage);
}
That's your double check.
For C++0x, it will not be implemented like that. Instead, it
will be implemented in a thread-safe way that makes your
example entirely redundant.
The problem with the traditional double checked locking
pattern is twofold:
1) The "checks" are straight pointer comparisons and for the second
check the pointer may not be re-read after the first check due to
compiler optimization.
That's not correct. Since there is a lock between the two
reads, the pointer must be reread.
One major problem with both the traditional double checked
locking and your example is that a branch which finds the
pointer not null will never execute any synchronization
primitives. Which means that there is no guarantee that it will
see a constructed object---in the absense of synchronization
primitives, the order of writes in another thread is not
preserved (and in practice will vary on most high end modern
processors).
You've added to the problem by not reading the pointer a second
time. This means that two threads may actually try to construct
the static object. Which doesn't work with most compilers today
(but will be guaranteed in C++0x, I think).
Finally, of course, if the instance function is called from the
constructor of a static object, there's a very good chance that
sLock won't have been constructed. (Unix supports static
construction of mutexes, but as far as I know, Windows doesn't.)
2) The initialization of the pointer may be re-ordered by the CPU to
happen before the initialization of the singleton object is complete.
I think you are confusing the checking issue. I am acquiring
a lock before this hidden check of which you speak is made and
this check is not the same as the initial fast pointer check
so issue 1 is not a problem.
I think you're missing the point that order is only preserved if
*both* threads synchronize correctly. You're lock guarantees
the order the writes are emitted in the writing thread, but does
nothing to ensure the order in which the writes become visible
in other threads.
As far as issue 2 is concerned my version (on VC++ at least) is solved
via my lock primitive which should emit a barrier on RAII construction
and destruction and cause VC++ *compiler* to not re-order stores across
a library I/O call (if I am wrong about this a liberal sprinkling of
volatile would solve it).
I should have stated in the original post that my solution is not
portable as-is but it is a solution for a particular implementation
(which doesn't preclude porting to other implementations). :)
There are definitly implementations on which it will work: any
single core machine, for example. And it's definitely not
portable: among the implementions where it will not work, today,
are Windows, Linux and Solaris, at least when running on high
end platforms.
--
James Kanze
Generated by PreciseInfo ™
Hymn to Lucifer
by Aleister Crowley 33? mason.
." | https://preciseinfo.org/Convert/Articles_CPP/Singleton_Experts/C++-VC-ATL-STL-Singleton-Experts-101213124443.html | CC-MAIN-2022-05 | refinedweb | 946 | 59.03 |
New Yorker: Don’t buy real estate in Miami…
“The Siege of Miami” is a New Yorker article about flooding in Miami. Here’s one point that seems worth discussing..
.”
What do readers think? I tend to be optimistic about technology for improving electric motors, batteries, windmills, and other items associated with cutting CO2 emissions. But flood control and pumps would seem to me to fall into the same category as building bridges, which Americans are getting worse over at over time (see “Longfellow Bridge repairs will now take about as long as the original construction” and “U.S. versus German infrastructure spending and results“).
Jack D
January 16, 2016 @ 12:50 pm
Half of the Netherlands would be permanently under water if it were not for flood control mechanisms. The mechanisms are well understood and have been for centuries. It’s not rocket science – you build a dike/levee/wall higher than the expected sea level around a city/area but by doing this you turn the city/area into a giant bathtub when it rains so now you need pumps to bail out the bathtub. As long as the levees and pumps do not fail, you stay dry.
New Orleans flooded not due to lack of technology but because of shoddy construction work and/or maintenance on the levees and floodwalls. And many of these were built when costs were lower – to build a new system of levees or floodgates around a major city that does not have them yet would costs billions and take forever because of the environmental studies, archaeological digs, etc., etc. – by the time they were completed the city that they were meant to protect would already be underwater. It’s clear from numerous examples that our society has lost the ability to do big things at a cost that anyone can afford.
Skeptical
January 16, 2016 @ 3:01 pm
The current rate of sea level rise is 7inches per century, same as its been since the 1800s with no acceleration coinciding with the extra CO2 emitted as we industrialized.
The scary sea level predictions have the same credibility as Al Gore saying 15 years ago that we only have 15 years until we reach a global warming point of no return (satellite+balloon data show no warming in the last 18 years), or the IPCC climate models from 15 years ago predicting 2-3C warming per century (last year they revised it down to 0.6-1.6C).
Jong
January 16, 2016 @ 3:20 pm
The Netherlands solution will not work in Florida. According to the article the land in Florida is porous, so the water comes up through the ground. They would have to do something to make the land not porous and then build dikes to block water coming in from the ocean.
Jackie
January 16, 2016 @ 3:54 pm
When they built the WTC they built something called “the bathtub” to keep out the water of the Hudson River using the “slurry wall” technique – they dug a deep narrow trench all around the site which they filled with mud (similar to drilling mud) as they dug to keep it from collapsing. They then pumped in “grout” (a liquidy form of concrete) that was heavier than the mud – this fell to the bottom of the trench and displaced the mud (which they would then recover for use on the next section). The grout hardened into concrete and formed a water proof barrier. For the WTC, they then dug out the inside of the bathtub, revealing the slurry walls but you don’t have to.
I’m sure that building a slurry wall around an entire city would not be cheap but it seems like it might be possible assuming that if you dig deep enough you will reach an impermeable layer. Or maybe you also have to create a slurry floor in addition to the slurry walls if the permeable layer is too deep to wall off.
Javier
January 16, 2016 @ 7:13 pm
Does Holland have to deal with the kind of storms and hurricanes that Florida gets?
M
January 16, 2016 @ 7:18 pm
I’m not sure I buy the argument… “30 years ago you wouldn’t have believed the possibility of an iPhone” – therefore, since we have the iPhone today, “you can believe that in 30 years we’ll have technology X,” where X = whatever technology the person is working on at the moment.
Why not jetpacks? A cancer cure? A secure, easy-to-use operating system? We’ll have all of these in 30 years, just as certainly as I hold this iPhone in my hand…
bobbybobbob
January 16, 2016 @ 9:11 pm
Dunno about the rising sea level stuff or the specifics of Miami, but there’s a reason most of the beach accessible eastern seaboard was cheap and small beach shacks as recently as 40 years ago. Areas near the beach get swept away (or sometimes grow dramatically). There are Jersey barrier islands where the block numbering starts at 12. It didn’t originally. Near the beach is just not suited for expensive buildings and federally subsidized flood insurance. Anything built near the beach on the east coast should be un-insurable. People very clearly used to build stuff right on the coast with the attitude that it’d be a write-off if a major hurricane and storm surge hit.
Unrelatedly, the New York Press can always be counted on to take a dump on wealth developing in the USA outside of New York. It’s hilarious. They were writing about the shale oil projects as full of drugs and rapists and toxic chemicals. They gloat about any other city falling on rough times. They do all kinds of underhanded stories on San Francisco and LA.
John V
January 18, 2016 @ 1:12 pm
Skeptical: I’m not sure where you get your data, but the article says “For the past several years, the daily high-water mark in the Miami area has been racing up at the rate of almost an inch a year, nearly ten times the rate of average global sea-level rise. ”
So they seem to think it is going up 1″ per year there, while global average is 1″ per decade.
Personally, I think this needs a trip to Florida to check things out first hand. Preferably this week, while it is 10 degrees outside here.
Phil: I read this article a few weeks back, after it was referenced on one of my Doomer websites. Yes, that paragraph did stick out as being somewhat unreasonably optimistic. | http://blogs.harvard.edu/philg/2016/01/16/new-yorker-dont-buy-real-estate-in-miami/ | CC-MAIN-2017-09 | refinedweb | 1,108 | 65.35 |
Migrating to ASP.NET Core 2.0
Before we get under way talking about migrating a simple ASP.NET Core 1.1 app to 2.0, we need to keep in mind that 1.1.2 is under LTS support, and that upgrading to 2.0 might not be for you. If you want more information on the current support levels of the various versions of .NET Core, you can find that here.
If you've decided to go ahead and want to migrate to 2.0, you'll also need the 2.0 SDK if you haven't already installed it. You can find that here.
Once installed, you can use the 2.0 SDK to code against 1.1 applications if you want, and I can confirm this because I've removed all previous versions of the SDK from my system and had a good play around with older projects.
Also, please note that I'll be using VS 2017 for this article. It uses the new csproj file and is upgraded to the latest version; this is required. If you're using a 1.1 application under VS 2015, you may still be using the old project.json. If this is the case, you can find assistance here…
Upgrading to 2.0
I'm going to walk through the upgrade using an empty 1.1 ASP.NET Core application, using the template provided by VS. And, the first thing we need to do is change our target framework. Edit the project's csproj file, and you can use Figure 1 as a reference. Right-click the project and click 'Edit *.csproj.'
Figure 1: Editing the csproj file
If you're new to VS 2017, you now are able to edit the csproj file while the project is open. There is no need to unload the project first. And, once we have this file open, we need to change this line:
<TargetFramework>netcoreapp1.1</TargetFramework>
to
<TargetFramework>netcoreapp2.0</TargetFramework>
Also, while we're in the csproj file, we can update our package references. For example, we can change this line:
<ItemGroup> <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" /> </ItemGroup>
to
<ItemGroup> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /> </ItemGroup>
Now, once you've done this, go ahead and upgrade any of your other packages as needed. However, keep in mind that, in some cases, it may be better to stick with the lowest version possible.
The next thing, while we're looking at the package references, is to upgrade any CLI tool references as needed. For example, you may be using Entity Framework Core while at the same time using the CLI to create migrations and update your database. This update would look something like this…
<DotNetCliToolReference Include "Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0"/>
Moving away from the csproj, let's turn our attention to the Program.cs. A 1.1 app would have code that looks something like this:
public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseApplicationInsights() .Build(); host.Run(); }
In 2.0, this has been simplified and now looks something like this…
public class Program { public static IWebHost BuildWebHost(string[] args) => WebHost .CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); public static void Main(string[] args) { BuildWebHost(args).Run(); } }
This new format is recommended and even required in some situations.
Finally, let's make a small change to your global.json to target the new SDK. If your project is missing one, as is the case with some templates for new projects, you can use Figure 2 as a reference and place it.
Figure 2: The global.json file
If you only have the 2.0 SDK installed, I find that leaving out the global.json is an option and it will, of course, default to the only available SDK on your system.
Now, the content of the global.json looks like this…
{ "sdk": { "version": "2.0.0" } }
At this point, you should be able to build the application, and run it. I've edited my final middleware component in the Statup.cs to look like this:
app.Run(async (context) => { await context.Response.WriteAsync("Hello World from Code Guru!"); });
Figure 3: The application running under ASP.NET Core 2.0
Conclusion
Given that we used only a simple application to demonstrate the migration project here, I've completed the steps shown here on much large projects without issue. However, as we said at the start, I would recommend taking the needed time to decide whether the upgrade is needed, but with all new projects I would heartily recommend starting with .NET Core 2.0.
If you have any questions about this article, you can always find me on Twitter @GLanata.
There are no comments yet. Be the first to comment! | https://www.codeguru.com/csharp/.net/net_asp/migrating-to-asp.net-core-2.0.html | CC-MAIN-2019-26 | refinedweb | 808 | 68.97 |
The Freescale Freedom platform is an ultra-low-cost development platform enabled by the Kinetis-L Series KL0x, KL1x and KL2x energy efficient microcontroller families built on ARM® Cortex™-M0+ processors.
Setting Up Your Board
For this example I used the popular mbed.org integration to program the Freedom board as it is quick and easy to set up plus it’s FREE.
You need to:
- Hold down the Reset Button between the two USB Connectors
- Plug one end of your USB cable into your computer and the other in to the USB port labelled SDA on the Board
- Once you have done this the KL25z will pop up as BOOTLOADER in your file system
- Copy this file from mbed.org to the root of this new drive
- Disconnect the USB cable from the board and plug it straight back in again and the drive will now pop up as MBED
- Open the drive and click on the MBED.HTM
- Login or Sign up and you now have access to all the tools your need to get started with the KL25z
Let’s start coding
Now for the fun part,
- Visit mbed.org/compiler and log in if you need to.
- Select New > Program and give your program a name e.g. KL25zHelloWorld
- The following “Hello World” Code will be placed into the main.cpp file
#include "mbed.h"
DigitalOut myled(LED1);
int main() {
while(1) {
myled = 1;
wait(0.2);
myled = 0;
wait(0.2);
}
}
4. Click Compile and Save the downloaded file (filename.bin) onto the MBED drive on the KL25z Board
5. Press the Reset Button and you will see the RGB LED Flashing.
I hope this helps you get started.
Don’t forget to share your projects | http://www.element14.com/community/community/code_exchange/blog/2013/03/25/freescale-freedom-kl25z-let-s-all-say-hello-world | CC-MAIN-2015-06 | refinedweb | 291 | 80.82 |
P15-6. Review the following 2012 balance sheet and income statement for T. F. Baker Cosmetics, Inc. The numerical values are in thousands of dollars.<?xml:namespace prefix = o
T.F. Baker Cosmetics, Inc.
Balance Sheet
Cash $ 5,000 Accounts payable $10,000
Accounts receivable 12,500 Short-term bank loan 15,000
Inventory 10,000 Long-term debt 10,000
Current assets $27,000 Common stock 15,000
Gross fixed assets $65,000 Retained earnings 12,500
Less: accum. depr. 30,000 Total liabilities and equity $62,500
Net fixed assets $35,000
Total assets $62,500
T.F. Baker Cosmetics, Inc.
Income Statement
Sales $150,000
Less: Cost of goods sold 120,000
Gross profit $ 30,000
Less: Operating expenses 15,000
Less: Depreciation 5,000
Less: Interest 2,000
Pretax profit $ 8,000
Less: Taxes (35%) 2,800
Net Income $ 5,200
At a recent board meeting, the firm set the following objectives for 2013:
1. The firm would increase liquidity. For competitive reasons, accounts receivable and inventory balances were expected to continue their historical relationships with sales and cost of goods sold, respectively, but the Board felt that the company should double its cash holdings.
2. The firm would accelerate payments to suppliers. This would have two effects. First, by paying more rapidly, the firm would be able to take advantage of early payment discounts, which would increase its gross margin from 20 percent to 22 percent. Second, by paying earlier, the firm’s accounts payable balance, which historically averaged about one twelfth of cost of goods sold, would decline to 4 percent of cost of goods sold.
3. The firm would expand its warehouse, which would require an investment in fixed assets of $10 million. This would increase projected depreciation expense from $5 million in 2012 to $7 million in 2013.
4. The firm would issue no new common stock during the year, and it would initiate a dividend payments in 2013 would total $1.2 million.
5. Operating expenses would remain at 10% of sales.
6. The firm did not expect to retire any long-term debt, and it was willing to borrow up to the limit of its current credit line with the bank, $20 million. The interest rate on its outstanding debts would average 8%.
7. The firm set a sales target for 2013 of $200 million.
Develop a set of pro forma financial statements to determine whether or not T.F. Baker Cosmetics can achieve all these goals simultaneously. | http://www.chegg.com/homework-help/questions-and-answers/p15-6-review-following-2012-balance-sheet-income-statement-t-f-baker-cosmetics-inc-numeric-q3878851 | CC-MAIN-2015-18 | refinedweb | 418 | 63.7 |
Thank you for the example. Took me a while to figure out a few quirks with the
q-selectprops.
for anyone looking for this … you can check @metalsadman provided sandbox above , he has done all the work . I want to add few comments for beginners like me .
$
quasar new c BaseSelect your custom extended component from quasar ( here is where we will customize the q-select in my case )
add index.js to export your component
import BaseSelect from './BaseSelect.vue' export { BaseSelect }
next mount it to your vue boot
$
quasar new b base-select
register the component in your new boot file
import * as BaseComponents from 'components' // leave the export, even if you don't use it export default async ({ app, router, Vue }) => { // Globally register the components Object.keys(BaseComponents).map(v => { Vue.component(v, BaseComponents[v]) }) }
final step is to go to your quasar.conf.js and add this boot file ( named in quasar new b xxx ) in the boot list array .
for q-select>> Few things i run into is to notice or take care ( not to mix
multiple prop , on a string data model for q-select) ,
This way is more expressive and saves lots of time if you need to use the same props over and over again . | https://forum.quasar-framework.org/user/amex | CC-MAIN-2019-35 | refinedweb | 213 | 60.04 |
Homework 5 and 6 (5+6 = 100 points)
Homework 5+6
You will be asked to deliver partial part of your projects, which must be uploaded to your moodle account. (online.cis.fiu.edu)
You already were asked to connect your mysql account at school and install (if possible) mysql in your computer. Remember your username for mysql is sum12_csusername and the password is your pantherID.
Since this homework will the based of your final project, it is recommended that you create a new web project in netbeans and add the files you need. Remember that in moodle you will find the shared files described in the book. You can also find them in the author’s web site.
Instructions:
Please follow the following steps for the first part of the homework.
- Modify the application so that it implements the Persistent Controller from Chapter 5 and 6. It should also implement the Post Controller and Required Validation. Review the steps in Tutorial 5.Controller (Part 2)
- Add all the necessary files to the
sharedpackage.
- Note that
HellperBaseCh6should be placed in the
sharedpackage.
- Add all the necessary JAR files to the Libraries folder.
- Modify your controller so that it can handle GET and POST request.
- Modify your controller so that it has the init method
- Bean
- Place the bean in the same package as the controller.
- Add annotations so that the bean can be saved to a database.
- Annotate the class so that it can be saved to its own table.
- Add a key field to the bean or extend it from
PersistentBase.
- Mark any properties that only have accessors so that they are not saved to the database.
- The bean should implement required validation.
- Validate that one of the numeric fields is in a specific range of numbers. Do not include 0 in the range. There are additional annotations that can be used with numeric properties.
- Remove any default validation for this field.
- @Min(value=100). Do not use the Hibernate annotation, use mine. Add the following files to the shared package:Min.java, MinValidator.java.
- @Max(value=200). Do not use the Hibernate annotation, use mine. Add the following files to the shared package:Max.java, MaxValidator.java.
- @Range(min=100,max=200). This is a built-in annotation for Hibernate: Built-in Annotations for Hibernate.
- Each of these needs an import statement:
import shared.Min;
import shared.Max;
import org.hibernate.validator.Range;
- Use the Pattern annotation to validate that one of the string properties only contains one of several words.
- Choose at least three words.
- The match should not be case sensitive.
- (PART 2) Use the mutator to store the string in lowercase. If the user enter Intel, store it as intel.
- (PART 2) Make sure the program does not crash if the property is null or empty string.
- For each field that is to be validated, display information in the web page that indicates the correct format of the data to be entered.
- (PART 2) Additional controls
- Add radio group and multiple selection list.
- Add checkbox group and single selection list.
- Validate this new controls.
- If the bean is numeric, then use min and max to validate the range of the value. (You can also use range)
- If the associated property in the bean is a string, the use a regular expression to validate it.
- All fields must have validation
- (PART 2) In addition to the annotations from Chapter 5, make sure you include the following :
- Mark any properties that return arrays so that they can be saved to the database in a separate table.
- Add Annotations to radio groups, checkbox groups, and select list so that they can be initialized easily in a JSP.
- Validate that at least two options from the checkbox group or multiple selection list have been choosen
- Look at the Hibernate validations. There is one there that can help you.
- Remember that these types of elements are nullable: if nothing is checked or selected, then there will be nothing in the query string. You will also need to validate that it is not null (size 0 is not the same as null).
- Controller Helper
- Use a unique name, other than “helper” and different than the one for Tutorial 5, to save the controller helper in the session.
- Change the name of the accessor for the bean to something other than
getData.
- Modify
jspLocationso that it returns the correct path for JSPs.
- Write the current record to the database when the process button is clicked.
- Do not retrieve records in this method.
- Write an information message to the log file containing the id of the record that is being written to the database.
- Add a button method for the view page (described below). Read the records from the database and make them available in the request for next JSP.
- Do not save to the database in this method.
- Write a debug message to the log file that contains the number of records that were retrieved from the database.
- Write a warning message to the log file if no records were retrieved from the database.
- Use a name other than “database” to store the database records in the request.
- When you are debugging your application, set the log level to debug. When you submit the assignment, change the log level to error.
- (PART 2) Also add the following (from chapter 6) to the controller helper:
- Write the current data to the database when the process button is clicked.
- Show all the records from the database in the view page. Use a name other than database when placing the list of beans into the request.
- Treat GET requests as the start of a new transaction.
- Always show the edit page when a GET request is made.
- Do not read the old data from the session when a GET request is made.
- Treat POST requests as the continuation of a transaction.
- Show the appropriate page based on the button that was clicked.
- Read the old data from the session and copy it into the bean.
- JSPs. ( Be sure there is a hypertext link in the
index.jsppage to the controller. Use a relative link. )
- (Part 2) Use the Apache style sheet for all your JSPs.
- Set the
hrefin the
linktag to
"cgsPantherID.css"
- For example, cgs1111.css
- If your style is in a different directory or has a different name, then modify the
hrefaccordingly.
- Make sure your style is not in a hidden directory.
- The
/in the
hrefalways means the root of the current server.
- If using apache (EXTRA CREDIT)
- For Apache the root is
docRoot, so
/equates to
docRoot.
- Your style sheet should be in
docRoot/styles/cgs4854.css
- From Apache, the URL
"/styles/cgs4854.css"equates to the physical path
docRoot/styles/cgs4854.c and the new name you used for the bean accessor. (Part 2)They should also use the new name that you used to redefine the accessor for the data.
- Modify
Edit.jsp
- When appropriate, display error messages next to each input element that implements required validation.
- (PART 2) Use a table to organize the input elements so that they appear in orderly columns.
- (PART 2) Be sure that your new input elements are initialized with the values from the bean. This means that radio groups and check box groups should be checked according to the values that are in the bean; the same is true for selection lists.
- (PART 2) Display error messages for all properties that are not valid. Place all error messages inside a dfn tag with the class set to alert. The errors should stand out on the page, based on your style sheet.
- (Part 2) Modify
Confirm.jsp.
- Use the dfn tag to display the values from the bean.
- Use nested ordered lists to display all the data in the bean. Those elements that return arrays will use the inner nested list to display all its values.
- Modify
Process.jsp.
- Only display the current record that was saved to the database. (PART 2) Use the dfn tag to display the values from the bean.
- Do not display all the records from the database in this page.
- If you do not have one, add a button that returns to the edit page so the user can change the values that were just saved. When the edit page appears, the current values should appear in the input elements in the page.
- If you do not have one, add a button that returns to the edit page to start a new request. When the edit page appears, the current values should NOT appear in the input elements. (This is not the same as the edit button. This will be a “Clear” or “New”)
- Add a button that sends the user to the view page.
- Add a new page named
View.jsp. (PART 2)
- Use a table to display all the data from the database.
- The first row in the database should use a
thtag for each column name.
- Use an unordered list to display those elements that have multiple values.
- There should be a button that allows the user to return to the edit page and enter new data into the database.
- Here is an example of how the pages might look: Example Pages.
- The webapp DOES NOT USE secure web.xml.
- Be sure to modify the project so that the .java files are placed in the WAR file: Configuring WAR File
- Make sure you compress the netbeans directory. Check in moodle to see what is required for you to upload.
- After the app is running in NetBeans, upload it and run it on ocelot: Uploading a WAR file
CSS FILE (PART 2)
- Create a file named
CGSPantherID.cssin the
stylesdirectory.
- Change the default style for the entire page.
- Change the color of the text.
- Change the color of the background.
- Change the font-family. Use at least three possible fonts; the last font in the list should be a generic font family. Do not include more than one generic font family in the list.
- Change the default style for the
dfntag.
- Use a relative size to make the size of the text larger.
- Use a different background color.
- Change the default style for the
inputand
selecttags.
- Use a
monospacefont.
- Use the
font-familytag.
- Choose at least one specific font.
- The last option in the list of fonts should be for the generic monospace font.
- Make the font twice as large as the default font. Use a relative measurement.
- Change the text color.
- Change the background color.
- Create a style named
alertthat can only be used with
dfntags.
- Use a relative size to make the size of the text larger.
- Underline the text.
- Make the text bold.
- Change the default ordering that is used for
oltags.
- Do not change the style for any
litags.
- Do not create a named style.
- Choose one of upper-roman, lower-roman, upper-alpha, lower-alpha.
- Change the default ordering for nested
oltags (
oltags inside
oltags).
- Do not change the style for any
litags.
- Do not create a named style.
- Choose one of upper-roman, lower-roman, upper-alpha, lower-alpha, decimal (different from the ol ordering).
- Create a style named
indentthat can only be used with paragraphs.
- Set the right margin. Use a relative measurement based on the height of the letter ‘M’.
- Set the left margin. Use a relative measurement baes on the height of the letter ‘x’.
- Change the default styles for
h1and
h2tags.
h1and
h2headings should use a different font than the body. Use the font-family attribute and specify a very specific font, a more common font and a generic font. All of these must be different from the default fonts for the page.
h1and
h2headings should have center alignment.
- Change
h1headings as:
- Make each letter upper case.
- Change the background image.
- Change the text color.
- Be sure the text color contrasts with the background image.
- Turn on italic.
- Change
h2headings as:
- Capitalized first letters for each word in the heading
- Turn off the default bold style.
- Turn on underline.
- Change the default style for unvisited hypertext links.
- Change the text color.
- Change the background-color.
- Turn off the underline.
- Make the font smaller than the body font. Use a relative measurement.
- Change the default style for visited hypertext links.
- Change the text color.
- Change the background-color.
- The other changes to the unvisited style will also cascade to this style.
- Use the style sheet in all pages that can be accessed from Apache, including all the files for your username web application on Tomcat (except the manager).
- Modify the
docRoot/index.htmlfile.
- Add some headings.
- Create one
h1heading at the top of the page.
- Use several
h2headings in the page. Place one before each of your paragraphs in the page. Make sure your paragraphs contain enough text so that the margin size can be observered.
- Do not use a heading for an entire paragraph.
- A heading should contain just a few words.
- Use several
dfntags throughout the page.
- Use the
indentstyle on one of the paragraphs | http://franciscoraulortega.com/teaching/cgs4854/cgs4854_homework-5and6/ | CC-MAIN-2018-17 | refinedweb | 2,179 | 76.93 |
I have a list of strings that may contain special characters. I'd like to loop through that list and remove any elements that have special characters.
import string
mylist = ['joe', 'dan', '#joe', 'd@n']
for name in mylist:
if any(c in string.punctuation for c in name):
mylist.remove(name)
>>>mylist
['joe', 'dan', 'd@n']
# so the 'for name in mylist' approach
# quits after finding #joe, leaving d@n
# let's try another approach....
mylist = ['joe', 'dan', '#joe', 'd@n']
>>> for i in range(len(mylist)):
if any(c in string.punctuation for c in mylist[i]):
mylist.remove(mylist[i])
Runtime error
Traceback (most recent call last):
File "<string>", line 2, in <module>
IndexError: list index out of range
>>> mylist
['joe', 'dan', 'd@n']
Okay, I get the out of range error since it has removed one element and len(mylist) is no longer 4; how do I plow through a list and remove all the bad-guys without stopping or tossing an error?
mylist = ['joe', 'dan', '#joe', 'd@n']
try:
for i in range(len(mylist)):
if any(c in string.punctuation for c in mylist[i]):
mylist.remove(mylist[i])
except IndexError:
pass
>>> mylist
['joe', 'dan', 'd@n']
Here, the error is suppressed, but I'm still left with that pesky d@n....
This might be the simplest thing to do:
I don't see how one can modify a list recursively: take the good-guys and leave the bad-guys behind.... | https://community.esri.com/thread/209123-removing-list-elements | CC-MAIN-2018-47 | refinedweb | 247 | 78.99 |
In my first post (link) I’ve explained what StyleCop is and how you can start with your own StyleCop rules. We will now dig a little bit deeper into the jungle of StyleCop….
StyleCop’s Code Model
After some reverse engineering of StyleCop’s Code Model, I thought it is not worth to try finding out what the meaning of all the classes is. I’ll just show you, how I exploratively found solutions for the things I wanted to check in the source code.
Just a few things: The Document is one file of C# code. If you walk through the Document using AnalyzeDocument and after that you use StyleCop’s WalkDocument callback mechanism for example to find out which Expression is a magic number, you will see some items twice. Maybe you’re confused now; just try out the source code mentioned at the end of this article.
Custom Rules Made Easy
It’s pretty annoying writing a whole SourceAnalyzer class every time you want to add a new rule. So I’ve created a generic mechanism where you just have to chose the type of item you want to inspect and the write the rule against it. You can try and write a dummy rule for each item to find out, what will be provided by each type of item.
The different items are
- Tokens
- Elements
- Expressions
Additionally you can decide which type of CsTokens (e.g. Attribute, Return, UsingDirective, …), Elements (e.g. Methods, Fields, Struct, …) or Expressions (e.g. Arithmetic, Lambda, Logical, Typeof, …) you like to inspect.
Test Driven Development TDD
It is one of my favorite to develop in TDD and I think it changed the whole thinking about development. To make that possible, you have to use StyleCop’s CodeProject class and the StyleCopConsole class and then some Code that violates your rules. The latter is easy, but the first one gave me some miracles until I solved it.
First of all, create a new CodeProject:
var configuration = new Configuration(new string[0]); CodeProject = new CodeProject(Guid.NewGuid().GetHashCode(), null, configuration);
Then you can add your violating source code to the CodeProject instance:
public void AddSourceCode(string fileName) { fileName = Path.GetFullPath(fileName); bool result = this.StyleCopConsole.Core.Environment.AddSourceCode(CodeProject, fileName, null); if (result == false) { throw new ArgumentException("Source file could not be loaded.", fileName); } }
To start the analysis use the following code:
public void StartAnalysis() { var projects = new[] { CodeProject }; bool result = this.StyleCopConsole.Start(projects, true); if (result == false) { throw new ArgumentException("StyleCopConsole.Start had a problem."); } }
I’ve put all the code above in an abstract base class and for the rules I’ve set up a new test class using Visual Studio’s integrated test runner:
namespace CleanCode.StyleCopCustomRules.UnitTests { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class CleanCodeTests : AbstractSourceAnalysisTest { [TestMethod] public void TooManyParameters() { AnalyzeCodeWithOneAssertion("TooManyParameters.cs"); } ... private void AnalyzeCodeWithOneAssertion(string codeFileName) { const int ExpectedViolations = 1; this.AnalyzeCodeWithAssertion(codeFileName, ExpectedViolations); } private void AnalyzeCodeWithAssertion(string codeFileName, int expectedViolations) { AddSourceCode(codeFileName); StartAnalysis(); WriteViolationsToConsole(); WriteOutputToConsole(); Assert.AreEqual(expectedViolations, StyleCopViolations.Count); } private void WriteOutputToConsole() { Console.WriteLine(string.Join(Environment.NewLine, StyleCopOutput.ToArray())); } private void WriteViolationsToConsole() { foreach (var violation in StyleCopViolations) { Console.WriteLine(violation.Message); } } } }
You would probably ask why I’ve used the Visual Studio test runner and not NUnit or xUnit. The reason is, that I haven’t found a way to copy the source code files that violates the rules to the directory where NUnit could find them. In VS.Net I could use the LocalTestRun.testrunconfig and say that the Resources folder should be deployed where the test is running. I’m curious if you find a solution with NUnit or xUnit.
Putting All Together
So far I’ve implemented some rules from the book “Clean Code” written by Robert C. “Uncle Bob” Martin which can be found here or at amazon. I was astonished and excited about the contents of the book. This was exactly what I was looking for years. Now I know what was wrong with our code walk-through’s and reviews. We had no idea what we were looking for!
The code is available on googlecode here. You should be able to use it after checking out from the subversion repository. Otherwise let me know…
Have fun
Thomas
Hi Thomas,
Recently I am investigating whether StyleCop can help us in our project. I’ve seen many articles but yours really appeals to me because of the generic mechanism you’ve created. And I very much like to unit-test the rules I’m about to make. However, when I run the unit tests from your source code (StyleCopContrib4.3.zip), some unit tests fail. This is because the StyleCopConsole never seems to generate a violation. The Output is always “No violations occurred”. Do you have any idea what I’m doing wrong? (VS2008, Win7 Pro 64bit)
Hi. I’m having problems running your code. The AddSourceCode method always fails when running the unit tests. More specifically the line in AbstractSourceAnalysisTest.cs always returns false:
this.StyleCopConsole.Core.Environment.AddSourceCode…
I’ve checked that the file exists in the expected location so I’ve no clue why this method returns false. Do you have any ideas?
Thanks
Phil
@Phil Hale
Hi Phil
The code in this post is very old (2009).
I’ll relay your comment to the original author of the post, maybe he can answer your question.
Sorry for not being much of help
Urs
@Phil Hale
What version of StyleCop are you using?I’m currently working on upgrading to 4.6 or 4.7…
Cheers Thomas
@Phil Hale
Hi Phil
I have updated the code on googlecode for StyleCop 4.7.8; just use the Branch StyleCop 4.7.
If you are running Windows 7, you might try to run VS2010 in Administrator mode.
Cheers
Thomas
Hi Thomas,
I created an example that works with ReSharper and xUnit as well as MSTest.
Cheers | https://www.planetgeek.ch/2009/09/21/custom-stylecop-rules-part-ii/ | CC-MAIN-2020-10 | refinedweb | 992 | 57.98 |
So, I was reading through comments to despam my old posts before archiving them, and came upon this old reply to this old post of mine which was a reply to this much older post.
I won’t reply to that post much, because it’s mostly… well, not useful to respond to. But people often talk about the wonders of Open Classes in Ruby. For Python people who aren’t familiar with what that means, you can do:
# Somehow acquire SomeClassThatAlreadyExists class SomeClassThatAlreadyExists def some_method(blahblahblah) stuff end end
And SomeClassThatAlreadyExists has a some_method added to it (or if that method already exists, then the method is replaced with the new implementation).
In Python when you do this, you’ve defined an entirely new class that just happens to have the name SomeClassThatAlreadyExists. It doesn’t actually effect the original class, and probably will leave you confused because of the two very different classes with the same name. In Ruby when you define a class that already exists, you are extending the class in-place.
You can change Python classes in-place, but there’s no special syntax for it, so people either think you can’t do it, or don’t realize that you are doing the same thing as in Ruby but without the syntactic help. I guess this will be easier with class decorators, but some time ago I also wrote a recipe using normal decorators that looks like this:
@magic_set(SomeClassThatAlreadyExists) def some_method(self, blahblahblah): stuff
The only thing that is even slightly magic about the setting is that I look at the first argument of the function to determine if you are adding an instance, class, or static method to an object, and let you add it to classes or instances. It’s really not that magic, even if it is called magicset.
I think with class decorators you could do this:
@extend(SomeClassThatAlreadyExists) class SomeClassThatAlreadyExists: def some_method(self, blahblahblah): stuff
Implemented like this:
def extend(class_to_extend): def decorator(extending_class): class_to_extend.__dict__.update(extending_class.__dict__) return class_to_extend return decorator | http://www.ianbicking.org/blog/2007/08/opening-python-classes.html | CC-MAIN-2019-43 | refinedweb | 345 | 52.63 |
Writing tests for an ASP.NET Web API service.
Web API testing can be broadly categorized into one of three groups:
- Unit testing a controller in isolation
- Submitting a request to an in-memory HttpServer and testing the response you get back
- Submitting a request to a running server over the network and testing the response you get back
Unit Testing Controllers
The first and simplest way of testing a Web API service is to unit test individual controllers. This means you'll first create an instance of the controller. And then call the Web API action you want to test with the parameters you want. Finally, you'll test that the action did what it was supposed to do, like updating a database for example and that it returned the expected value.
To illustrate the different ways of testing Web API services, let's use a simple example. Let's say you have an action that gets a movie by its ID. The action signature might look like this:
1: public class MoviesController : ApiController 2: { 3: public Movie GetMovie(int id); 4: }
Let's give this method the following contract. If the movie ID exists in our database, it should return the corresponding movie instance. But if there isn't a movie with a matching ID, it should return a response with a 404 Not Found status code. An example of a unit test for this action might look like this:
1: [Fact] 2: public void GetMovie_ThrowsNotFound_WhenMovieNotFound() 3: { 4: var emptyDatabase = new EmptyMoviesDbContext(); 5: var controller = new MoviesController(emptyDatabase); 6: HttpResponseException responseException = Assert.Throws<HttpResponseException>(() => controller.GetMovie(1)); 7: Assert.Equal(HttpStatusCode.NotFound, responseException.Response.StatusCode); 8: }
As a general principle, you should always try to test as little as possible and unit testing controllers is as simple as it gets.
Submitting requests against an in-memory HttpServer
Unit testing controllers is great, and you should be trying to do so whenever you can. But it does have its limitations. First off, Web API sets up state on the controller like the Request or the Configuration properties that may be needed for your action to function properly. It also sets properties on the request that are used by certain methods. Commonly used methods in the framework like Request.CreateResponse work fine in a normal Web API pipeline, but will not work when unit testing a controller unless you configure some additional properties.
Secondly, unit testing a controller doesn't cover everything else that might go wrong with your service. If you're using custom message handlers, routing, filters, parameter binders, or formatters, none of that is accounted for when unit testing. And even if you're using all the defaults, the request might never make it to your action or might result in your action being called with the wrong parameters. Unit testing doesn't help at all with this kind of issue.
And thirdly, unit testing doesn't always help you figure out what the HTTP response looks like. Maybe you really care about a certain HTTP header being set on the response or maybe you care about your response sending back the right status code to the client. If your action returns an HttpResponseMessage or throws an HttpResponseException like our example above, then you may be able to inspect and test the response. But otherwise, you won't get any insight into what response will actually be received by the client.
The recommended way to deal with all these issues is to set up an HttpServer, create a request you want to test, and submit it to the server. You can then test the response you get back and make sure it matches your expectations. One of the advantages of Web API's architecture is that you can do this without ever having to use the network. You can create an in-memory HttpServer and simply pass requests to it. It will simulate the processing of the request and return the same response you would have gotten if it were a live server.
Here's what the same unit test we wrote earlier would look like:
1: [Fact] 2: public void GetMovie_ReturnsNotFound_WhenMovieNotFound() 3: { 4: HttpConfiguration config = new HttpConfiguration(); 5: config.Routes.MapHttpRoute("Default", "{controller}/{id}"); 6: HttpServer server = new HttpServer(config); 7: using (HttpMessageInvoker client = new HttpMessageInvoker(server)) 8: { 9: using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "")) 10: using (HttpResponseMessage response = client.SendAsync(request, CancellationToken.None).Result) 11: { 12: Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); 13: } 14: }; 15: }
If you wanted to test the response body instead, you could use these lines:
1: ObjectContent content = Assert.IsType<ObjectContent>(response.Content); 2: Assert.Equal(expectedValue, content.Value); 3: Assert.Equal(expectedFormatter, content.Formatter);
Submitting requests against a running HttpServer
The last way to write a Web API test is to start a running server that's listening to a network port and send a request to that server. Usually, that involves starting up WebAPI's self-host server like this:
1: [Fact] 2: public void GetMovie_ReturnsNotFound_WhenMovieNotFound() 3: { 4: HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(""); 5: config.Routes.MapHttpRoute("Default", "{controller}/{id}"); 6: using (HttpSelfHostServer server = new HttpSelfHostServer(config)) 7: using (HttpClient client = new HttpClient()) 8: { 9: server.OpenAsync().Wait(); 10: using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "")) 11: using (HttpResponseMessage response = client.SendAsync(request).Result) 12: { 13: Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); 14: } 15: server.CloseAsync().Wait(); 16: }; 17: }
To test the response body instead, you could write:
1: Assert.Equal(expectedResponseBody, response.Content.ReadAsStringAsync().Result);
If at all possible, you should try avoiding writing these kinds of tests. Instead of just testing the service, you're testing a whole lot more - you're testing the client, you're testing the operating system's networking stack, and you're testing the host for your service. Whenever you test more than you have to, you expose yourself to potential issues at other layers that can make test maintenance and debugging a nightmare. For example, you might now have to run your tests with administrator privileges for the self host server to open successfully.
Now with all that said, there may be cases where this kind of test is the most appropriate. If you need to test that a client and a server can communicate, it's usually better to test the client and the server individually. You can test that the client is sending the request you expect it to send, and then you can test that the server returns the expected response given that request. But there may be cases where the hosting actually matters and you need to make sure that the client request actually makes it to the Web API server correctly. The best example that comes to mind is if you're using SSL/TLS and you want to make sure that the connection is working. You might then write one test against a running server to check that the connection is working, and write the rest of your tests as unit tests or against an in-memory server to check that the service is handling requests the way you'd expect it to. | https://docs.microsoft.com/en-us/archive/blogs/youssefm/writing-tests-for-an-asp-net-web-api-service | CC-MAIN-2020-16 | refinedweb | 1,188 | 52.29 |
Hello
I am using JFreeChart 1.1.11.
I would like include this java library into a web application (Servlet Bean and JSP)
Inside one bean, I would like write one getxxxx method, with the followed parameters
imput parameter: JFreeChart object
Output parameter: JPEG or PNG object
How can I.
Could you help me
Thank in advance
How to return one PNG object from a JFreeChart
A discussion forum for the Eastwood Chart Servlet.
Re: How to return one PNG object from a JFreeChart
Something like the following should do the trick:
Code: Select all
import org.jfree.chart.ChartUtilities; ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height) | https://www.jfree.org/forum/viewtopic.php?f=27&t=27628&p=76855&sid=1ce2816b18c2575dbcc4560e78f4973c | CC-MAIN-2021-39 | refinedweb | 107 | 59.84 |
Another feature of necko HTTP channels that maps badly to e10s is the fact that necko channels are also nsHashPropertyBags, i.e. hashtables that clients can stuff various things into and then pull out later.
I would really like to avoid sending IPC traffic around for get/sets of these hashtables. bz seems to think that in most cases, properties will only be retrieved by the same parent or child that set them, so we may not have to worry about this too much--just document that we don't support retrieval of properties set across a process boundary.
We have at least one known exception to this--we set a 'referer' property that may need to cross process boundaries. There may be others. So we should do a code or runtime audit of what gets set/retrieved to see what may need special handling.
Properties that need to be sent across the wire probably ought to be removed from the hashbag and instead put somewhere like nsIHttpChannelInternal.idl. Actually, if we could move *all* uses to nsIHttpChannelInternal and/or something sensible like a context "void *" member variable, I'd be much happier. Storing cruft in your objects in a big hashtable and doing lookups by name at runtime is the kind of programming that belongs in Javascript, not C++.
Biesi tells me we also stuff in a 64-bit Content-length field into our PropertyBags, too (as NS_CHANNEL_PROP_CONTENT_LENGTH). This is used by nsExternalHelperAppService and nsIncrementalDownload, at least, and possibly other things. This may also need to be propagated across process boundaries (though it also might not, assuming uriloader lives in the chrome process, and so do nsExternalHelperAppService/nsIncrementalDownload).
It's also possible that we'll need to propagate NS_CHANNEL_PROP_CONTENT_DISPOSITION, which is used by the JAR channel (which may have an Http channel target, i.e. jar:) and URILoader.
While I still think it's a splendid idea to refactor nsHashBag out of our channels, realistically I think we just need to keep the API for now and propagate the the handful of properties that need it.
We should feel free to change the API for necko to help get rid of these hashbag properties, particularly the ones that need to be propagated between child/chrome.
Bsmedberg suggests we change the APIs on mozilla-central first, and then propagate to the e10s branch.
I can take this. We should break this stuff sooner rather than later, if we're going to do it.
I have a patch that adds an nsIChannel2 with a contentLength64 property, and changes the dozen or so nsIChannel implementations in the tree to also implement nsIChannel2.
Frankly it's pretty gross, but we can do it if necessary. And that's just for that one property. There'll be other hashbag-related ones to come.
I'd rather wait to see if we're going to break binary compatibility on nsIChannel for other reasons. If so, the contentLength thing becomes much nicer.
We've decided that binary changes are OK now, right? (Is there a deadline for such changes? Last beta?)
The changes here will break script compat too, of course, but in a pretty visible way -- we'll throw when trying to QI to the property bag. Extensions should figure that out given enough beta time.
Getting this on blocker radar -- this needs to block b5 if we're going to do it. And we need to do something here, one way or the other. :)
Created attachment 467183 [details] [diff] [review]
part 1: make nsIChannel.contentLength 64-bit
This breaks the interface. Looking for r & sr here. FWIW it looks like there isn't any script in our tree that uses the "content-length" hash property, so no script changes required as a result of this.
Created attachment 467186 [details] [diff] [review]
part 2: implementors
Created attachment 467187 [details] [diff] [review]
part 3: consumers
After these three patches, there are no remaining references to the "content-length" hash property in the tree.
Comment on attachment 467183 [details] [diff] [review]
part 1: make nsIChannel.contentLength 64-bit
Actually, bz's on vacation, so I'll ping jst instead. ;)
Comment on attachment 467186 [details] [diff] [review]
part 2: implementors
+r with changes discuss on IRC.
Still makes me nervous to get rid of ENSURE_ARG macros, but dwitte makes good case we'll never get passed null.
I've built a list of all the in-tree uses of nsIPropertyBag/nsIWritablePropertyBag on channels.
Now the hard part: figuring out what to do with them. ;)
"docshell.previousURI":
"docshell.internalReferrer":
"docshell.newWindowTarget":
"docshell.previousFlags":
"baseURI":
"channel-policy":
"content-disposition":
My interpretations so far:
"content-disposition": not used in any meaningful way. says it's the way of the future, but reality disagrees.
"channel-policy": we could add an interface and put this property on it, and have nsHttpChannel implement it. bsterne and dveditz say that'd be fine; we only really need to support it for httpchannels. Redirects from http --> non-http can just ditch the CSP info and fail.
"docshell.internalReferrer": we might be able to get equivalent info by getting the principal directly from the channel (via the notification callbacks).
"docshell.previousFlags": used for tracking redirects for history purposes.
Comment on attachment 467187 [details] [diff] [review]
part 3: consumers
+r with fix to keep check for -1 in nsGnomeVFSInputStream::DoOpen.
We remove a lot of casts in this patch, which is great, unless we're adding compile-time warnings. We have some cases of assigning 64 bit ints to 32 bit ones, which will probably want casts to avoid warnings. Maybe grep make output before/after to compare warning count?
Otherwise looks great. Thanks! That was a a lot of code to chug through.
Oh, and we should definitely run these patches through tryserver.
> Redirects from http --> non-http can just ditch the CSP info and fail.
This doesn't mean all redirects from http to FTP would fail, does it? That doesn't sound good.
Death to channel PropertyBagHashes!
Should we split the Content-length patches into a separate bug and land once the tree is open for bizness?
Hmm, nevermind about "content-disposition", I missed a usage in nsURILoader. It was added in bug 474536.
It sounds like we could move that to a property on the channel.
I suppose the more useful thing to do at this point is figure out which of the properties in comment 13 only need to exist on either the parent or child but not both. Those can be left alone. The rest need to be dealt with.
(In reply to comment #17)
> This doesn't mean all redirects from http to FTP would fail, does it? That
> doesn't sound good.
Only if the httpchannel had a CSP, in which case we can't redirect to FTP because the CSP info would be lost, allowing it to redirect back.
(In reply to comment #18)
> Should we split the Content-length patches into a separate bug and land once
> the tree is open for bizness?
I'll just land these here, and leave the bug open for more stuff.
bsterne's content policy tests () pass in Fennec now that we have redirect stuff done, so changing "channel-policy" is definitely not a blocker.
Blocking beta5 on this. The primary reasoning here is to make this API change before the release instead of after to minimize the API changes we'll need to do. We've already changed nsIChannel, so one more change now is effectively free for us and others who depend on this.
Comment on attachment 467183 [details] [diff] [review]
part 1: make nsIChannel.contentLength 64-bit
Comment on attachment 467186 [details] [diff] [review]
part 2: implementors
Comment on attachment 467187 [details] [diff] [review]
part 3: consumers
Merged to m-c. I'll file separate bugs for the other bits as necessary.
Looks like we want to back this out?
bsmedberg wrote on dev.platform:
The IID of nsIChannel was changed between beta4 and beta5, for bugs 589292 and
536324. While I agree that these are virtuous changes, I don't think we should
be changing the IIDs of base interfaces so late in the beta cycle. It's going
to be very difficult to distinguish between crashes caused by third-party
extensions which were compiled against beta4, and crashes caused by issues
within our own code.
This change *might* be related to the topcrash bugs 591880 and 591678, but I
really can't tell.
Unless these changes were absolutely necessary for e10s (and it doesn't look to
me as if they were), I think these should be backed out and postponed until
after branching.
I'm not so sure we want to back this out. (The contentDisposition change isn't necessary, and we could back that out, but since we took the contentLength change we got that one for free.)
I don't have a complete understanding of what would break if we backed this out, but it worries me that people rely on the contentLength hash property and we have no easy way of remoting it. We could do a bunch of work inside nsHashPropertyBag itself, but that'd suck.
It might be that we get lucky and everything that depends on this lives in the child, but right now I'm not sure whether that's true or not.
We can rely on the contentLength hash property by implementing nsIHashPropertyBag and providing that key directly, can't we? That wouldn't involve interface changes.
Yep, I suppose we could specialcase it. Want me to roll that patch?
Yes please.
Being fixed in bug 591997?
Not blocking. -> Firefox 5
> "docshell.internalReferrer": we might be able to get equivalent info by getting
> the principal directly from the channel (via the notification callbacks).
No, you can't. The principal of the docshell is not immutable. So if you want the principal it had when the channel was opened, you need to grab it when the channel is opened.
Would this make sense as a property (on nsIChannel?), i.e. is it something we're cool exposing to script? (Or can we expose the same information in a different way?)
We're cool exposing it to chrome script (heck, it already is!).
The other option is to make .referrer on nsIHttpChannel be the always-set thing and just have an mInternalReferrer member for what goes on the wire. But then you might want people to know what goes on the wire...
If people want to know what goes on the wire, shouldn't they use getRequestHeader("referer")?
Hmm... Probably. But that won't do the right thing before on-modify-request, right?
HttpBaseChannel::SetReferrer looks to me like it should work anytime.
Er... it doesn't. It bails out in all sorts of cases, no?
Yes, in the ones where nothing goes out on the wire.
Reassigning to nobody. If anyone wants to work on this, feel free!
Did these happy patches simply never land?
These patches just need to be relanded, but I want us to hold off until I figure out how much they conflict with those from bug 589292 and/or 215450.
renaming, since this is now much narrower than getting rid of nsHashBag entirely.
This will change nsIChannel to a 64 bit content-length (only binary addons should be affected). See "Part 1" patch.
-> me on Jason's request.
Taking on Josh's request
Ok, no problem. But please ask next time, I just wanted to start with this today... If the status is ASSIGNED, then I intend to work on this and sometimes I even already do so. It is on my priority list too.
Created attachment 668560 [details] [diff] [review]
part 1: make nsIChannel.contentLength 64-bit
Un-bitrotted, carrying forward r+ and sr+ since it's the same bits, just updated for modern times.
Created attachment 668561 [details] [diff] [review]
part 2: implementors
Un-bitrotted part 2. Re-requesting review, as things have changed enough in the last year to warrant it.
Created attachment 668562 [details] [diff] [review]
part 3: consumers
Un-bitrotted part 3. Re-requesting review for the same reason as part 2.
The three patches are running through try right now,
We'll see just how much I broke :)
Comment on attachment 668561 [details] [diff] [review]
part 2: implementors
I'm delegating this review to Steve.
Created attachment 672064 [details] [diff] [review]
part 4: test
Now, with 100% more testing! r?sworkman since jduell already delegated the reviews for this bug to him.
Comment on attachment 668561 [details] [diff] [review]
part 2: implementors
Review of attachment 668561 [details] [diff] [review]:
-----------------------------------------------------------------
Looks good r=me.
Comment on attachment 668562 [details] [diff] [review]
part 3: consumers
Review of attachment 668562 [details] [diff] [review]:
-----------------------------------------------------------------
Looks good - just a couple of minor things to look at.
::: extensions/gnomevfs/nsGnomeVFSProtocolHandler.cpp
@@ -432,5 @@
> mBytesRemaining = info.size;
>
> // Update the content length attribute on the channel. We do this
> // synchronously without proxying. This hack is not as bad as it looks!
> - if (mBytesRemaining != UINT64_MAX) {
Discussed this with you in person: do you need to keep this UINT64_MAX check? And change NS_MAX(..., INT32_MAX) to NS_MAX(...,INT64_MAX)?
::: js/xpconnect/loader/mozJSSubScriptLoader.cpp
@@ +107,2 @@
> nsCString buf;
> rv = NS_ReadInputStreamToString(instream, buf, len);
Looks like len in NS_ReadInputStreamToString is uin32_t. Could your check above be '> UINT32_MAX' instead of '> INT32_MAX'?
::: netwerk/base/src/nsStreamLoader.cpp
@@ +72,5 @@
> chan->GetContentLength(&contentLength);
> if (contentLength >= 0) {
> + if (contentLength > UINT32_MAX) {
> + // Too big to fit into uint32, so let's bail.
> + // XXX we should really make mAllocated and mLength 64-bit instead.
Discussed this with you. I understand it's a bit of a rathole to fix mAllocated and mLength and out of the original scope of this bug. So, no worries.
::: netwerk/protocol/ftp/FTPChannelParent.cpp
@@ +170,1 @@
> chan->GetContentLength(&aContentLength);
Nitpick: Since you're already changing this line, can you rename aContentLength to contentLength to clarify that it's declared locally?
::: uriloader/exthandler/nsExternalHelperAppService.cpp
@@ +558,5 @@
> channel->GetURI(getter_AddRefs(uri));
>
> + int64_t contentLength = -1;
> + if (channel)
> + channel->GetContentLength(&contentLength);
Is it ok to aggregate these two 'if (channel)' statements?
::: uriloader/prefetch/nsPrefetchService.cpp
@@ +810,5 @@
> if (mChannel) {
> + int64_t size64;
> + nsresult rv = mChannel->GetContentLength(&size64);
> + NS_ENSURE_SUCCESS(rv, rv);
> + *aTotalSize = int32_t(size64); // XXX - loses precision
FYI: Looks like this truncates the bytes (I know we discussed it in person, but I had a little niggling thought, so I checked on my Mac and I'm getting truncated output, not smart casting). So, maybe you want to do something like the old nsBaseChannel::GetContentLength, and return (-1) if it's more than INT32_MAX. OR just truncate like HttpBaseChannel::GetContentLength. In any case, I'll let you decide how you want to proceed - leave it, or whatever :)
Comment on attachment 672064 [details] [diff] [review]
part 4: test
Review of attachment 672064 [details] [diff] [review]:
-----------------------------------------------------------------
::: netwerk/test/unit/test_bug536324_64bit_content_length.js
@@ +6,5 @@
> +const Cr = Components.results;
> +
> +Cu.import("resource://testing-common/httpd.js");
> +
> +const CONTENT_LENGTH = "1152921504606846975";
Can you add a comment to say what this is in reference to (U)INT32_MAX? :)
@@ +26,5 @@
> + httpServer.stop(do_test_finished);
> + }
> +};
> +
> +function hugeContentLength(metadata, response) {
'huge' should be in caps ;)
Created attachment 673909 [details] [diff] [review]
part 2: implementors (version for checkin)
Updated part 2 patch for checkin. Carry forward r+
Created attachment 673910 [details] [diff] [review]
part 3: consumers (version for checkin)
Updated part 3 for checkin. Carry forward r+
Created attachment 673911 [details] [diff] [review]
part 4: test (version for checkin)
Updated part 4 for checkin. Carry forward r+
Try looks good with the patch updates
Will land once the trees open.
Trees are open.
This broke Thunderbird:
/usr/bin/ccache /tools/gcc-4.5-0moz3/bin/g++ -o nsMsgQuickSearchDBView.o -c -I../../../mozilla/dist/stl_wrappers -I../../../mozilla/dist/system_wrappers -include /builds/slave/tb-c-cen-lnx/buildZLIB_INTERNAL -DMOZ_THUNDERBIRD=1 -DOSTYPE=\"Linux2.6.32-220.el6\" -DOSARCH=Linux -DHAVE_MOVEMAIL -I/builds/slave/tb-c-cen-lnx/build/mailnews/base/src -I. -I../../../mozilla/dist/include -I../../../mozilla/dist/include/nsprpub `/builds/slave/tb-c-cen-lnx/build/objdir-tb/mozilla/dist/sdk/bin/nspr-config --prefix=/builds/slave/tb-c-cen-lnx/build/objdir-tb/mozilla/dist --includedir=/builds/slave/tb-c-cen-lnx/build/objdir-tb/mozilla/dist/include/nspr --cflags` -I/builds/slave/tb-c-cen-lnx/build/objdir-tb/mozilla/dist/include/nss -fPIC -pedantic -Wall -Wpointer-arith -Woverloaded-virtual -Werror=return-type -Wtype-limits -Wempty-body -Werror=conversion-null -finline-limit=50 -fno-omit-frame-pointer -DMOZILLA_CLIENT -include ../../../comm-config.h -MD -MF .deps/nsMsgQuickSearchDBView.pp /builds/slave/tb-c-cen-lnx/build/mailnews/base/src/nsMsgQuickSearchDBView.cpp
nsMsgSearchDBView.cpp
../../../../mailnews/base/util/nsMsgProtocol.cpp:681:10: error: prototype for 'nsresult nsMsgProtocol::GetContentLength(int32_t*)' does not match any in class 'nsMsgProtocol'
../../../../mailnews/base/util/nsMsgProtocol.h:57:1350: error: candidate is: virtual nsresult nsMsgProtocol::GetContentLength(int64_t*)
../../../../mailnews/base/util/nsMsgProtocol.cpp:687:10: error: prototype for 'nsresult nsMsgProtocol::SetContentLength(int32_t)' does not match any in class 'nsMsgProtocol'
../../../../mailnews/base/util/nsMsgProtocol.h:57:1451: error: candidate is: virtual nsresult nsMsgProtocol::SetContentLength(int64_t)
make[7]: *** [nsMsgProtocol.o] Error 1
> This broke Thunderbird:
Standard8 pushed a bustage fix:
Added a note to and a call-out box to. | https://bugzilla.mozilla.org/show_bug.cgi?id=536324 | CC-MAIN-2016-44 | refinedweb | 2,868 | 56.96 |
We stayed at the Riu Santa Fe for 5 nights begining Dec. 10th. Just to give you some perspective, we are a gay couple from NY and are real "foodies," so this review definitely has a slant.
First of all, no need to pre-book a shuttle and worry about vouchers. They are all over the place right outside of baggage claim and the price is the same. Also, if you want to rent a car, it is about a 40 minute drive to the Riu, and there is free parking. Reserve in advance because the rental companies will gouge you if you just walk up to the counter. Transportation while there is limited to cabs or the bus if you have no car. Cabs to town are about $10, although you can easily walk to the center of town by walking down the beach, about 25-30 mins. If you want to rent a car the day before you check out and then drop off at the airport, there is a National at the Santa Fe, and there are Avis and Thrifty at adjacent resorts. You can do a little exploring and save the shuttle fee on the return (about $15 each).
Check-in was a breeze, and we experienced no problem communicating with the staff. The open-air lobby was quite attractive.
There is a lot of walking, but if you are fit, it's not overwhelming.
We had to change room 3 times until we realized that all of the rooms smell like mold. They looked clean, but there is such high humidity that mattresses, pillows and comforters get musty. This is a problem at many Mexican resorts, but to me, it was particularly bad at the Santa Fe, especially considering it is so new. Buy a can of Lysol at the WalMart across the street, it may come in handy. The rooms are very bland, no color at all. Television stations, especially in english, are limited. Also, I was unaware that they made 27" televisions with curved screens still, but Riu found them. Also, what's w/ not having key cards for the rooms?
The pools, except for the pool bar on the left at the beach, did not seem to be heated (note to Riu: Heat The Pools). The pools were attractive, there were plenty of loungers. We used the heated jacuzzi at the Spa without charge. It wasn't bad, but wished they has heated jacuzzis at the main pools. We were the only ones there, and they won't let you bring a drink in. We used the gym 3 times. It was adequately equipped, but I did want for a set of free weights.
The drinks were good, and plentiful. There are lots of bars. The premium liquor selection is limited. I am a gin drinker, and they have Beefeater on the menu, but many of the bars did not stock it. Also, the tonic they use is Canada Dry, but it tasted strange. Not sure why... The Sports Bar (also where the internet is) was somewhat weak. No American sports channels (c'mon Riu: 90% of your clientele is english speaking). Also, the prices for internet ($8 an hour) and a game of pool ($3) are a little steep. They always have "nachos" and snacks (sandwiches, hamburgers) in the Sports Bar. They are bad, avoid them.
The food, oh the food. Three words: mediocre at best. Everything is buffet, except the steakhouse. And, when you get your steak, you will wish it were a buffet. Hands down, the worst steak I have ever had. There is a lot of variety, but most everything tasted bland. The salad bar and the fresh fruit were the only things that were consistently acceptable. The desserts were inedible. I must admit that there were people there who liked the food. I am not sure what their story was, but all I can say is, if you enjoy excellent food, you are not going to enjoy eating at the Riu Santa Fe. I was actually craving cruise food by the time we left...and I generally detest cruise food! We actually ate several meals in town on this trip.
We generally avoided the entertainment. What we did see looked very amateurish and awkward, which can be entertaining in and of itself. We did not go to the disco. It would have been nice to have movie screenings. There were lots of employees out by the main pool during the day, trying to get people to play volleyball, dance, play ping pong, etc. However, most people were at the pool by the beach. The main pool is away from the beach. Once the resort gets toward capacity, there will be more people at the main pool by necessity, as the loungers by the beach pool will be full by 10 am. They do have 2 tennis courts, and they will loan you rackets and balls at the front desk.
They have representatives in the lobby daily from Orbitz, Travelocity, Cheap Carribean, etc. to sell excursions. We did an ATV tour which was fun. There are lots of options from which to choose.
About the Riu Palace next door, we did walk through it. It seemed slightly more upscale, and it is more beach oriented. They allow the people staying at the Palace to come and eat/drink at the Santa Fe, but not vice versa. My guess is that that is because the Palace is full and the Santa Fe is not. In order to make sure they don't lose the small crowd at the Santa Fe to the more bustling Palace, they have this policy for now. It will likely change when the Santa Fe has similar occupancy rates. Some people said that if you reversed the Santa Fe bracelt, it was the same color as the Palace one, so they were able to go over there and drink. Give that a try.
All in all, it was an acceptable trip. I would have been really bumbed though if we had paid more. We did get a great promotional rate. Good drink service, nice friendly service in general, nice location and pretty good pools are the strengths. Musty rooms, bad food, cold water in the pools and mediocre entertainment are weaknesses. If you are not getting a great rate, look around further. | http://www.tripadvisor.com/ShowUserReviews-g152515-d672603-r11679637-Riu_Santa_Fe_Hotel-Cabo_San_Lucas_Los_Cabos_Baja_California.html | crawl-002 | refinedweb | 1,067 | 83.25 |
> -----Original Message-----
> From: Paul Smith [mailto:paul.smith@lawlex.com.au]
> >?
> >
>
> public class MyClass {
> private static final Logger LOG = Logger.getLogger(MyClass.class);
> ....
> }
Which is of course the non-wrapped way to use the class. Thanks. I know given the rest of
your response, that you don't feel a wrapper is necessary. But, I believe since Ceki mentioned
it in his article, that there should be a proper way to write a wrapper, and that is still
the information I'm interested in. I appreciate your response and how quickly you provided
it, I also appreciate the advice your giving about keeping things simple and just using log4J,
but I'm not yet comfortable having everything I'm responsible for depend directly on Log4J.
>
> Then it's available all through your code, and is only
> initialised once.
>
>
> > Any pointers would be appreciated. (Note: I've googled,
> checked the short
> > manual, the FAQ, the JavaDocs, and the mailing list archives without
> > success.)
>
> My advice, don't wrap, it's just not worth the hassle, I've created in
> the past little Util classes that hide log4j from the rest of the app
> like I am sure so many other people have. Once you get to
> the point of
> really needing to know what is going on with a particular class, and
> can't deal with the volume of logging that tends to happen when an
> application grows you will thank yourself for having a separate Logger
> for each class.
Now, this has me thinking we may be on different topics, and perhaps I didn't make myself
clear. I don't have an issue with a logger for each class. I'm also pretty content with the
approach to logging which log4j has taken. So the paradigm is okay with me, besides Ceki has
demonstrated it's very close to jul. What I'm interested in is creating a single point of
package (or component) dependency such that all the source files I'm responsible for aren't
coupled to log4j (or any particular logger) directly. [Actually I would have been okay with
being coupled to a Java standard logger interface, but I feel the standard really should have
provided an api/spi interface to logging which would have allowed me to plug log4j in as a
service provider for my logging. Oh well.] Log4J has shown itself mature, stable and feature
rich enough that I'm willing to prefer it even to JDK 1.4 logging, but I'm not comfortable
enough that I want all sources from all projects importing it directly.
Anyway, all I'm really attempting at this point is a simple wrapper which will keep all the
projects' sources I'm responsible for dependent on one "company common" package which is in
turn is dependent on Log4J. I thought such a wrapper shouldn't be too difficult. I'm not
interested in commons-logging nor do I wish to try to re-implement it.
>
> Note, you can always do this:
>
> public class MyClass {
> private static final Logger CLASS_LOG =
> Logger.getLogger(MyClass.class);
>
> private static final Logger APP_LOG =
> Logger.getLogger("MyApp.LogicalSystem");
> ....
> }
>
> And then log low-level DEBUGS to the CLASS_LOG, and relevant
> Application
> logs to the other logger (logs that have more context with the other
> logs generated by companion/related components possibly from different
> packages etc). I am hoping the new 'Domains' concept will help make
> this a little easier to manage (coming in log4j 1.3).
>
> <aside>
> Once you begin to use Log4j you will realise how incredibly useful it
> is, you will really not care about the dependency. You can also later
> decide to use a pretty easy regexp search/replace to replace
> 'org.apache.log4j' with the JDK 1.4 Logger equiv (I don't
> remember what
> it is, as I've never used it) if you really have issues with the
> dependency later on.
I'm not interested in this for just one project. I have multiple products in many different
java environments (JMX, J2EE (web), Swing, J2SE, and J2EE (mail)). Since logging is architectually
significant in that it touches so many source files, I am currently more comfortable gating
logging through a common point of contact under company control. I feel if any problems arise
(or a requirement for a different logger), I will have one place to focus on and change implementation.
>
> This is of course 100% IMHO, and I am sure a lot of people
> starting out
> with log4j have the same feeling of the need to hide log4j as a
> component, but with experience I think you will find that having log4j
> as a friend for each of the classes you develop will pay off
> handsomely
> in the end.
> </aside>
I'm sure your right that a lot of people (just starting out) might what a similiar thing.
Maybe it would be reasonable idea then to provide a security blanket. A simple interface
which could be repackaged for a site's own use. Most of the code I've seen usually just uses
Logger.getLogger(MyClass.class) and the simple methods info(), debug(), etc. I could pretty
easily write an interface with a nested class to implement the factory method. It might be
a little ugly, but it would keep things to one line.
package com.mycompany.common.logging;
interface Logger {
void info(Object o);
void debug(Object o);
...
class Factory {
public Logger getLogger(Object s) {
return LogManager.getLogger(s);
}
}
}
Usage:
package com.mycompany.other;
import com.mycompany.common.logging.Logger;
class MyClass {
private static final Logger log = Logger.Factory.getLogger(MyClass.class);
...
log.debug("just like log4j, which is pretty much plug compatible with jul");
...
}
What I'm missing are the details for writing a wrapper to log4j. In this simplistic case I
could probably just subclass log4j.Logger and implement the com.mycompany.common.logging.Logger
interface. I'm just trying to get a handle on the issues with wrapping Log4J. I see it has
a method already documented for wrappers
public void log(String callerFQCN, Priority level, Object message, Throwable t);
I'm just looking for more info on writing a wrapper.
> cheers,
>
> Paul Smith
Thanks again,
Mike Rieser
---------------------------------------------------------------------
To unsubscribe, e-mail: log4j-user-unsubscribe@logging.apache.org
For additional commands, e-mail: log4j-user-help@logging.apache.org | http://mail-archives.apache.org/mod_mbox/logging-log4j-user/200403.mbox/%3C4AD55A877F263E4D9B5C3A09B9DA16055A81A8@scidalexcl1a.csg.stercomm.com%3E | CC-MAIN-2014-15 | refinedweb | 1,057 | 53.81 |
I have this one homework that has been bugging me for about week now, and I still can't figure it out. Its based on an earlier problem I did, but I just can't get it, I must be missing something. Well if you can help me figure this out I'd very much appreciate it.
Modify the Date class in the chapter before. The new version shoudl have the following overloaded operators:
++ Prefix and postfix increment operators. These operators should increment the object's day member.
-- Prefix and postfix decrement operators. These operators should decrement the object's day member.
- Subtraction operator. If one Date object is subtracted from another the operator should give the number of days between the two dates. For example, if April 10, 2000 is subtracted from April 18, 2000, the result will be 8.
<< cout's stream insertion operator. This operator should cause the date to be dsiplayed in the form: April 18, 2000
>> cin's extraction operator. This operator shoudl prompts the user for a date to be stored in the Date object.
The class should etect the following conditions and handle them accordingly:
when a date is et to the last day of the month and incremented, it should become the first day of the following month
when a date is set to December 31 and incremented, it should become January 1 of the following year
when a day is et to the first day of the month and decremented, it should become the last day of the previous month
when a date is set to January 1 and decremented, it should become December 31 of the previous year
I figured out the first part of this problem and here is the Date.h header file
And here is the Date.cpp file:And here is the Date.cpp file:Code:#ifndef DATE_H #define DATE_H #include <string> #include <cctype> using namespace std; class Date { private: int month; int day; int year; char date[9]; char name[10]; public: Date() // empty constructor { month = 1; day = 1; year = 1900; strcpy(date,""); strcpy(name, ""); } Date(int m, int d, int y) { setMonth(m); setYear(y); setDay(d); strcpy(date,""); strcpy(name, ""); } void setMonth (int m) //checks if m is a valid month { if (m>0 && m < 13) month = m; else month=1; } void setYear(int y) //checks if y is a valid year { if (y>=1900) year=y; else year=1900; } void setDay(int d) //checks if d is a valid day { if (d>0 && d<=31) switch(month) { case 1: day=d; break; case 3: day=d; break; case 5: day=d; break; case 7: day=d; break; case 8: day=d; break; case 10: day=d; break; case 12: day=d; break; case 4: if (d<=30) day=d; else { day=1; break; } case 6: if (d<=30) day=d; else { day=1; break; } case 9: if (d<=30) day=d; else { day=1; break; } case 11: if (d<=30) day=d; else { day=1; break; } case 2: if (year%100==0) { if (year%400==0) { if (d<=29) day=d; else day=1; } else { if (d<= 28) day=d; else day=1; } } else { if (year%4==0) { if (d<=29) day=d; else day=1; } else { if (d<= 28) day=d; else day=1; } break; } } } char * getShortDate() { char strDay[3] = { '\0' }; char strMon[3] = { '\0' }; char strYr[3] = { '\0' }; itoa(month, strMon, 10); strcpy(date, strMon); strcat(date, "/"); itoa(day, strDay, 10); strcat(date, strDay); strcat(date, "/"); itoa((year%100), strYr, 10); strcat(date, strYr); return date; } char * getMonthName(int m) { switch (m) { case 1: strcpy(name, "January"); break; case 2: strcpy(name, "February"); break; case 3: strcpy(name, "March"); break; case 4: strcpy(name, "April"); break; case 5: strcpy(name, "May"); break; case 6: strcpy(name, "June"); break; case 7: strcpy(name, "July"); break; case 8: strcpy(name, "August"); break; case 9: strcpy(name, "September"); break; case 10: strcpy(name, "October"); break; case 11: strcpy(name, "November"); break; case 12: strcpy(name, "December"); break; } return name; } }; #endif
Any help is very much appreciatedAny help is very much appreciatedCode:#include <iostream> #include "Date.h" using namespace std; int main() { Date date; int days, months, years; cout << "Which month would you like to display? " << endl; cin >> months; date.setMonth(months); cout << "Which year would you like to display? " << endl; cin >> years; date.setYear(years); cout << "Which day would you like to display? " << endl; cin >> days; date.setDay(days); cout << endl; cout << "Here is the information: " << endl; cout << endl; cout << date.getMonthName(months) << " " << days << ", " << years << endl; return 0; } | https://cboard.cprogramming.com/cplusplus-programming/52215-confused-class-problem.html | CC-MAIN-2017-22 | refinedweb | 765 | 61.5 |
I, for one, welcome our new snuffling, lowjacked underlords.
Elephant Agent and the Space Gentleman.
dnalounge update
I, for one, welcome our new supersized bug overlords.
These are amazing! I would like to have a fourteen inch snail as a pet. I think.
URGH!
dnalounge update
how much does Snow Leopard suck?
Normally I wouldn't give a shit about installing this OS upgrade, except that apparently Apple has fucked up ScreenSaverEngine, so in order to make the XScreenSaver distribion work on 10.6, I have to do a 64-bit build of all of the savers... and that's not possible on 10.5, because the 10.5 version of the ScreenSaver.framework bundle doesn't include the x86_64 architecture.
How angry am I going to be if I install 10.6 on my only computer?
Will it break Photoshop, Illustrator and Lightroom?
The nature of Apple's screen saver fuckup is that .saver bundles aren't separate programs (like they are in XScreenSaver under X11) but instead are dynamically loaded code into the ScreenSaverEngine app. And now they've changed ScreenSaverEngine to a 64-bit app which refuses to load 32-bit code -- meaning they broke every third party .saver bundle.
Dynamically loading the code this was always an idiotic idea. Even before Apple's current fuck-up, it had already meant that one screen saver could screw up the namespace of one that happens to run later (e.g., there are some savers that you can't run consecutively in System Preferences); and it means that a buggy screen saver that hangs can make you need to power-cycle the computer, since deactivation requires the cooperation of the 3rd party saver itself, instead of that being handled at a higher level. With X11 XScreenSaver, user activity guns down the saver whether it is responsive or not: a sandbox, basically, which is the only sensible way to do it.
I'd volunteer to rewrite ScreenSaverEngine from scratch, to make it less flaky and more compatible, if I thought there was any chance Apple would accept and ship my contribution.
Update: Progress is being made. I have questions.
OBSOLETE! OBSOLETE! OBSOLETE!
dnalounge update | https://www.jwz.org/blog/2009/08/ | CC-MAIN-2017-26 | refinedweb | 364 | 65.93 |
This Tutorial Explains Thread Synchronization in Java along with Related Concepts like Java Lock, Race Condition, Mutex, Java Volatile & Deadlock in Java:
In a multithreading environment where multiple threads are involved, there are bound to be clashes when more than one thread tries to get the same resource at the same time. These clashes result in “race condition” and thus the program produces unexpected results.
For example, a single file is being updated by two threads. If one thread T1 is in the process of updating this file say some variable. Now while this update by T1 is still in progress, let’s say the second thread T2 also updates the same variable. This way the variable will give wrong results.
=> Watch Out The Complete Java Training Series Here.
When multiple threads are involved, we should manage these threads in such a way that a resource can be accessed by a single thread at a time. In the above example, the file that is accessed by both the threads should be managed in such a way that T2 cannot access the file until T1 is done accessing it.
This is done in Java using “Thread Synchronization”.
What You Will Learn:
- Thread Synchronization In Java
- Multi-threading Without Synchronization
- Multi-threading With Synchronization
- Conclusion
Thread Synchronization In Java
As Java is a multi_threaded language, thread synchronization has a lot of importance in Java as multiple threads execute in parallel in an application.
We use keywords “synchronized” and “volatile” to achieve Synchronization in Java
We need synchronization when the shared object or resource is mutable. If the resource is immutable, then the threads will only read the resource either concurrently or individually.
In this case, we do not need to synchronize the resource. In this case, JVM ensures that Java synchronized code is executed by one thread at a time.
Most of the time, concurrent access to shared resources in Java may introduce errors like “Memory inconsistency” and “thread interference”. To avoid these errors we need to go for synchronization of shared resources so that the access to these resources is mutually exclusive.
We use a concept called Monitors to implement synchronization. A monitor can be accessed by only one thread at a time. When a thread gets the lock, then, we can say the thread has entered the monitor.
When a monitor is being accessed by a particular thread, the monitor is locked and all the other threads trying to enter the monitor are suspended until the accessing thread finishes and releases the lock.
Going forward, we will discuss synchronization in Java in detail in this tutorial. Now, let us discuss some basic concepts related to synchronization in Java.
Race Condition In Java
In a multithreaded environment, when more than one thread tries to access a shared resource for writing simultaneously, then multiple threads race each other to finish accessing the resource. This gives rise to ‘race condition’.
One thing to consider is that there is no problem if multiple threads are trying to access a shared resource only for reading. The problem arises when multiple threads access the same resource at the same time.
Race conditions occur due to a lack of proper synchronization of threads in the program. When we properly synchronize the threads such that at a time only one thread will access the resource, and the race condition ceases to exist.
So how do we detect the Race Condition?
The best way to detect race condition is by code review. As a programmer, we should review the code thoroughly to check for potential race conditions that might occur.
Locks/Monitors In Java
We have already mentioned that we use monitors or locks to implement synchronization. The monitor or lock is an internal entity and is associated with every object. So whenever a thread needs to access the object, it has to first acquire the lock or monitor of its object, work on the object and then release the lock.
Locks in Java will look as shown below:
public class Lock { private boolean isLocked = false; public synchronized void lock() throws InterruptedException { while(isLocked) { wait(); } isLocked = true; } public synchronized void unlock(){ isLocked = false; notify(); } }
As shown above, we have a lock () method that locks the instance. All the threads calling the lock () method will be blocked until the unblock () method sets are locked flag to false and notifies all the waiting threads.
Some pointers to remember about locks:
- In Java, each object has a lock or a monitor. This lock can be accessed by a thread.
- At a time only one thread can acquire this monitor or lock.
- Java programming language provides a keyword Synchronized’ that allows us to synchronize the threads by making a block or method as Synchronized.
- The shared resources that the threads need to access are kept under this Synchronized block/method.
Mutexes In Java
We already discussed that in a multithreaded environment, race conditions may occur when more than one thread tries to access the shared resources simultaneously and the race conditions result in unexpected output.
The part of the program that tries to access the shared resource is called the “Critical Section”. To avoid the occurrence of race conditions, there is a need to synchronize access to the critical section. By synchronizing this critical section, we make sure that only one thread can access the critical section at a time.
The simplest type of synchronizer is the “mutex”. Mutex ensures that at any given instance, only one thread can execute the critical section.
The mutex is similar to the concept of monitors or locks we discussed above. If a thread needs to access a critical section then it needs to acquire the mutex. Once mutex is acquired, the thread will access the critical section code, and when done, will release the mutex.
The other threads that are waiting to access the critical section will be blocked in the meantime. As soon as the thread holding mutex releases it, another thread will enter the critical section.
There are several ways in which we can implement a mutex in Java.
- Using Synchronized Keyword
- Using Semaphore
- Using ReentrantLock
In this tutorial, we will discuss the first approach i.e. Synchronization. The other two approaches – Semaphore and ReentrantLock will be discussed in the next tutorial wherein we will discuss the java concurrent package.
Synchronized Keyword
Java provides a keyword “Synchronized” that can be used in a program to mark a Critical section. The critical section can be a block of code or a complete method. Thus, only one thread can access the critical section marked by the Synchronized keyword.
We can write the concurrent parts (parts that execute concurrently) for an application using the Synchronized keyword. We also get rid of the race conditions by making a block of code or a method Synchronized.
When we mark a block or method synchronized, we protect the shared resources inside these entities from simultaneous access and thereby corruption.
Types of Synchronization
There are 2 types of synchronization as explained below:
#1) Process Synchronization
Process Synchronization involves multiple processes or threads executing simultaneously. They ultimately reach a state where these processes or threads commit to a specific sequence of actions.
#2) Thread Synchronization
In Thread Synchronization, more than one thread is trying to access a shared space. The threads are synchronized in such a manner that the shared space is accessed only by one thread at a time.
The Process Synchronization is out of the scope of this tutorial. Hence we will be discussing only Thread Synchronization here.
In Java, we can use the synchronized keyword with:
- A block of code
- A method
The above types are the mutually exclusive types of thread synchronization. Mutual exclusion keeps the threads accessing shared data from interfering with each other.
The other type of thread synchronization is “InterThread communication” that is based on cooperation between threads. Interthread communication is out of the scope of this tutorial.
Before we go ahead with the synchronization of blocks and methods, let’s implement a Java program to demonstrate the behavior of threads when there is no synchronization.
Multi-threading Without Synchronization
The following Java program has multiple threads that are not synchronized.
class PrintCount { //method to print the public void run() { two instances of thread class ThreadCounter T1 = new ThreadCounter( "ThreadCounter_1 ", PD ); ThreadCounter T2 = new ThreadCounter( "ThreadCounter_2 ", PD ); //start both the threads T1.start(); T2.start(); // wait for threads to end try { T1.join(); T2.join(); } catch ( Exception e) { System.out.println("Interrupted"); } } }
Output
From the output, we can see that as the threads are not synchronized the output is inconsistent. Both the threads start and then they display the counter one after the other. Both the threads exit at the end.
From the given program, the first thread should have exited after displaying the counter values, and then the second thread should have begun to display the counter values.
Now let’s go for synchronization and begin with code block synchronization.
Synchronized Code Block
A synchronized block is used to synchronize a block of code. This block usually consists of a few lines. A synchronized block is used when we do not want an entire method to be synchronized.
For example, we have a method with say 75 lines of code. Out of this only 10 lines of code are required to be executed by one thread at a time. In this case, if we make the entire method as synchronized, then it will be a burden on the system. In such situations, we go for synchronized blocks.
The scope of the synchronized method is always smaller than that of a synchronized method. A synchronized method locks an object of a shared resource that is to be used by multiple threads.
The general syntax of a synchronized block is as shown below:
synchronized (lock_object){ //synchronized code statements }
Here “lock_object” is an object reference expression on which the lock is to be obtained. So whenever a thread wants to access the synchronized statements inside the block for execution, then it has to acquire the lock on the ‘lock_object’ monitor.
As already discussed, the synchronized keyword ensures that only one thread can acquire a lock at a time and all the other threads have to wait till the thread holding the lock finishes and releases the lock.
Note
- A “NullPointerException” is thrown if the lock_object used is Null.
- If a thread sleeps while still holding the lock, then the lock is not released. The other threads will not be able to access the shared object during this sleep time.
Now we will present the above example that was already implemented with slight changes. In the earlier program, we did not synchronize the code. Now we will use the synchronized block and compare the output.
Multi-threading With Synchronization
In the Java program below, we use a synchronized block. In the run method, we synchronize the code of lines that print the counter for each thread.
class PrintCount { //print with synchronized block public void run() { synchronized(PD) { thread instances ThreadCounter T1 = new ThreadCounter( "Thread_1 ", PD ); ThreadCounter T2 = new ThreadCounter( "Thread_2 ", PD ); //start both the threads T1.start(); T2.start(); // wait for threads to end try { T1.join(); T2.join(); } catch ( Exception e) { System.out.println("Interrupted"); } } }
Output
Now the output of this program using synchronized block is quite consistent. As expected, both the threads start executing. The first thread finished displaying the counter values and exits. Then the second thread displays the counter values and exits.
Synchronized Method
Let’s discuss the synchronized method in this section. Earlier we have seen that we can declare a small block consisting of fewer code lines as a synchronized block. If we want the entire function to be synchronized, then we can declare a method as synchronized.
When a method is made synchronized, then only one thread will be able to make a method call at a time.
The general syntax for writing a synchronized method is:
<access_modifier> synchronized method_name (parameters){ //synchronized code }
Just like a synchronized block, in the case of a synchronized method, we need a lock_object that will be used by threads accessing the synchronized method.
For the synchronized method, the lock object may be one of the following:
- If the synchronized method is static, then the lock object is given by ‘.class’ object.
- For a non-static method, the lock object is given by the current object i.e. ‘this’ object.
A peculiar feature of the synchronized keyword is that it is re-entrant. This means a synchronized method can call another synchronized method with the same lock. So a thread holding the lock can access another synchronized method without having to acquire a different lock.
The Synchronized Method is demonstrated using the below example.
class NumberClass { //synchronized method to print squares of numbers synchronized void printSquares(int n) throws InterruptedException { //iterate from 1 to given number and print the squares at each iteration for (int i = 1; i <= n; i++) { System.out.println(Thread.currentThread().getName() + " :: "+ i*i); Thread.sleep(500); } } } public class Main { public static void main(String args[]) { final NumberClass number = new NumberClass(); //create thread Runnable thread = new Runnable() { public void run() { try { number.printSquares(3); } catch (InterruptedException e) { e.printStackTrace(); } } }; //start thread instance new Thread(thread, "Thread One").start(); new Thread(thread, "Thread Two").start(); } }
Output
In the above program, we have used a synchronized method to print the squares of a number. The upper limit of the number is passed to the method as an argument. Then starting from 1, the squares of each number are printed till the upper limit is reached.
In the main function, the thread instance is created. Each thread instance is passed a number to print squares.
As mentioned above, when a method to be synchronized is static, then the lock object is involved in the class and not the object. This means that we will lock on the class and not on the object. This is called static synchronization.
Another example is given below.
class Table{ //synchronized static method to print squares of numbers synchronized static void printTable(int n){ for(int i=1;i<=10;i++){ System.out.print(n*i + " "); try{ Thread.sleep(400); }catch(Exception e){} } System.out.println(); } } //thread class Thread_One class Thread_One extends Thread{ public void run(){ Table.printTable(2); } } //thread class Thread_Two class Thread_Two extends Thread{ public void run(){ Table.printTable(5); } } public class Main{ public static void main(String t[]){ //create instances of Thread_One and Thread_Two Thread_One t1=new Thread_One (); Thread_Two t2=new Thread_Two (); //start each thread instance t1.start(); t2.start(); } }
Output
In the above program, we print multiplication tables of numbers. Each number whose table is to be printed is a thread instance of different thread class. Thus we print multiplication tables of 2 & 5, so we have two classes’ thread_one and thread_two to print the tables 2 and 5 respectively.
To summarize, the Java synchronized keyword performs the following functions:
- The synchronized keyword in Java guarantees mutually exclusive access to shared resources by providing a locking mechanism. Locking also prevents race conditions.
- Using the synchronized keyword, we prevent concurrent programming errors in code.
- When a method or block is declared as synchronized, then a thread needs an exclusive lock to enter the synchronized method or block. After performing the necessary actions, the thread releases the lock and will flush the write operation. This way it will eliminate memory errors related to inconsistency.
Volatile In Java
A volatile keyword in Java is used to make classes thread-safe. We also use the volatile keyword to modify the variable value by different threads. A volatile keyword can be used to declare a variable with primitive types as well as objects.
In certain cases, a volatile keyword is used as an alternative for the synchronized keyword but note that it is not a substitute for the synchronized keyword.
When a variable is declared volatile, its value is never cached but is always read from the main memory. A volatile variable guarantees ordering and visibility. Although a variable can be declared as volatile, we cannot declare classes or methods as volatile.
Consider the following block of code:
class ABC{ static volatile int myvar =10; }
In the above code, the variable myvar is static and volatile. A static variable is shared among all the class objects. The volatile variable always resides in the main memory and is never cached.
Hence there will be only one copy of myvar in the main memory and all read/write actions will be done on this variable from the main memory. If myvar was not declared as volatile, then each thread object would have a different copy that would result in inconsistencies.
Some of the differences between Volatile and Synchronized keywords are listed below.
Deadlock In Java
We have seen that we can synchronize multiple threads using synchronized keyword and make programs thread-safe. By synchronizing the threads, we ensure that the multiple threads execute simultaneously in a multi-threaded environment.
However, sometimes a situation occurs in which threads can no longer function simultaneously. Instead, they wait endlessly. This occurs when one thread waits on a resource and that resource is blocked by the second thread.
The second thread, on the other hand, is waiting on the resource that is blocked by the first thread. Such a situation gives rise to “deadlock” in Java.
Deadlock in Java is depicted using the below image.
As we can see from the above diagram, thread A has locked the resource r1 and is waiting for resource r2. Thread B, on the other hand, has blocked resource r2 and is waiting on r1.
Thus none of the threads can finish their execution unless they get hold of the pending resources. This situation has resulted in the deadlock where both the threads are waiting endlessly for the resources.
Given below is an example of Deadlocks in Java.
public class Main { public static void main(String[] args) { //define shared resources final String shared_res1 = "Java tutorials"; final String shared_res2 = "Multithreading"; // thread_one => locks shared_res1 then shared_res2 Thread thread_one = new Thread() { public void run() { synchronized (shared_res1) { System.out.println("Thread one: locked shared resource 1"); try { Thread.sleep(100);} catch (Exception e) {} synchronized (shared_res2) { System.out.println("Thread one: locked shared resource 2"); } } } }; // thread_two=> locks shared_res2 then shared_res1 Thread thread_two = new Thread() { public void run() { synchronized (shared_res2) { System.out.println("Thread two: locked shared resource 2"); try { Thread.sleep(100);} catch (Exception e) {} synchronized (shared_res1) { System.out.println("Thread two: locked shared resource 1"); } } } }; //start both the threads thread_one.start(); thread_two.start(); } }
Output
In the above program, we have two shared resources and two threads. Both threads try to access the shared resources one by one. The output shows both the threads locking one resource each while waiting for the others. Thereby creating a deadlock situation.
Although we cannot stop deadlock situations from occurring completely, we can certainly avoid them by taking some steps.
Enlisted below are the means using which we can avoid deadlocks in Java.
#1) By avoiding nested locks
Having nested locks is the most important reason for having deadlocks. Nested locks are the locks that are given to multiple threads. Thus we should avoid giving locks to more than one thread.
#2) Use thread Join
We should use Thread.join with maximum time so that the threads can use the maximum time for execution. This will prevent deadlock that mostly occurs as one thread continuously waits for others.
#3) Avoid unnecessary lock
We should lock only the necessary code. Having unnecessary locks for the code can lead to deadlocks in the program. As deadlocks can break the code and hinder the flow of the program we should be inclined to avoid deadlocks in our programs.
Frequently Asked Questions
Q #1) What is Synchronization and why is it important?
Answer: Synchronization is the process of controlling the access of a shared resource to multiple threads. Without synchronization, multiple threads can update or change the shared resource at the same time resulting in inconsistencies.
Thus we should ensure that in a multi-threaded environment, the threads are synchronized so that the way in which they access the shared resources is mutually exclusive and consistent.
Q #2) What is Synchronization and Non – Synchronization in Java?
Answer: Synchronization means a construct is a thread-safe. This means multiple threads cannot access the construct (code block, method, etc.) at once.
Non-Synchronized constructs are not thread-safe. Multiple threads can access the non-synchronized methods or blocks at any time. A popular non- synchronized class in Java is StringBuilder.
Q #3) Why is Synchronization required?
Answer: When processes need to execute concurrently, we need synchronization. This is because we need resources that may be shared among many processes.
In order to avoid clashes between processes or threads for accessing shared resources, we need to synchronize these resources so that all the threads get access to resources and the application also runs smoothly.
Q #4) How do you get a Synchronized ArrayList?
Answer: We can use Collections.synchronized list method with ArrayList as an argument to convert ArrayList to a synchronized list.
Q #5) Is HashMap Synchronized?
Answer: No, HashMap is not synchronized but HashTable is synchronized.
Conclusion
In this tutorial, we have discussed the Synchronization of threads in detail. Along with it, we also learned about the volatile keyword and deadlocks in Java. Synchronization consists of Process and Thread synchronization.
In a multithreading environment, we are more concerned with thread synchronization. We have seen the synchronized keyword approach of thread synchronization here.
Deadlock is a situation wherein multiple threads endlessly wait for resources. We have seen the example of deadlocks in Java along with the methods to avoid deadlocks in Java.
=> Visit Here To Learn Java From Scratch. | https://www.softwaretestinghelp.com/what-is-thread-synchronization-in-java/ | CC-MAIN-2021-17 | refinedweb | 3,633 | 64 |
Scientific Graphing in Python
In my last few articles, I looked at several different Python modules that are useful for doing computations. But, what tools are available to help you analyze the results from those computations? Although you could do some statistical analysis, sometimes the best tool is a graphical representation of the results. The human mind is extremely good at spotting patterns and seeing trends in visual information. To this end, the standard Python module for this type of work is matplotlib. With matplotlib, you can create complex graphics of your data to help you discover relations.
You always can install matplotlib from source; however, it's easier to install it from your distribution's package manager. For example, in Debian-based distributions, you would install it with this:
sudo apt-get install python-matplotlib
The python-matplotlib-doc package also includes extra documentation for matplotlib.
Like other large Python modules, matplotlib is broken down into several sub-modules. Let's start with pyplot. This sub-module contains most of the functions you will want to use to graph your data. Because of the long names involved, you likely will want to import it as something shorter. In the following examples, I'm using:
import matplotlib.pyplot as plt
The underlying design of matplotlib is modeled on the graphics module for the R statistical software package. The graphical functions are broken down into two broad categories: high-level functions and low-level functions. These functions don't work directly with your screen. All of the graphic generation and manipulation happens via an abstract graphical display device. This means the functions behave the same way, and all of the display details are handled by the graphics device. These graphics devices may represent display screens, printers or even file storage formats. The general work flow is to do all of your drawing in memory on the abstract graphics device. You then push the final image out to the physical device in one go.
The simplest example is to plot a series of numbers stored as a list. The code looks like this:
plt.plot([1,2,3,4,3,2,1]) plt.show()
The first command plots the data stored in the given list in a regular
scatterplot. If you have a single list of values, they are assumed to be
the y-values, with the list index giving the x-values. Because you did not
set up a specific graphics device, matplotlib assumes a default device
mapped to whatever physical display you are using. After executing the
first line, you won't see anything on your display. To see
something, you need to execute the second
show() command. This
pushes the graphics data out to the physical display (Figure 1).
You should notice that there are several control buttons along the
bottom of the window, allowing you to do things like save the image
to a file. You also will notice that the graph you generated is
rather plain. You can add labels with these commands:
plt.xlabel('Index') plt.ylabel('Power Level')
Figure 1. A basic scatterplot window includes controls on the bottom of the pane.
You then get a graph with a bit more context (Figure 2). You
can add a title for your plot with the
title()
command, and the
plot command is even more versatile than that. You can change the plot
graphic being used, along with the color. For example, you can make green
triangles by adding
g^ or blue circles with
bo. If you want more than
one plot in a single window, you simply add them as extra options to
plot(). So, you could plot squares and cubes on the same plot with
something like this:
t = [1.0,2.0,3.0,4.0] plt.plot(t,[1.0,4.0,9.0,16.0],'bo',t,[1.0,8.0,27.0,64.0],'sr') plt.show()
Figure 2. You can add labels with the xlabel and ylabel functions.
Now you should see both sets of data in the new plot window (Figure 3). If you import the numpy module and use arrays, you can simplify the plot command to:
plt.plot(t,t**2,'bo',t,t**3,'sr')
Figure 3. You can draw multiple plots with a single command.
What if you want to add some more information to your plot, maybe a text
box? You can do that with the
text() command, and you can set the location
for your text box, along with its contents. For example, you could use:
plt.text(3,3,'This is my plot')
This will put a text area at x=3, y=3. A specialized form of text box is
an annotation. This is a text box linked to a specific point of data. You
can define the location of the text box with the
xytext parameter and
the location of the point of interest with the
xy parameter. You
even can set the details of the arrow connecting the two with the
arrowprops
parameter. An example may look like this:
plt.annotate('Max value', xy=(2, 1), xytext=(3, 1.5), ↪arrowprops=dict(facecolor='black', shrink=0.05),)
Several other high-level plotting commands are available.
The
bar() command lets you draw a barplot of your data. You can change
the width, height and colors with various input parameters. You even
can add in error bars with the
xerr and
yerr parameters. Similarly, you
can draw a horizontal bar plot with the
barh()
command. Or, you can draw box and whisker
plots with the
boxplot() command. You can create plain contour
plots with the
contour() command. If you want
filled-in contour plots,
use
contourf(). The
hist() command will draw a histogram,
with options to control items like the bin size. There is even a command
called
xkcd() that sets a number of parameters so all of the
subsequent drawings will be in the same style as the xkcd comics.
Sometimes, you may want to be able to interact with your
graphics. matplotlib needs to interact with several different toolkits,
like GTK or Qt. But, you don't want to have to write code for every
possible toolkit. The pyplot sub-module includes the ability to add event
handlers in a GUI-agnostic way. The FigureCanvasBase class contains
a function called
mpl_connect(), which you can use to connect some
callback function to an event. For example, say you have a function
called
onClick(). You can attach it to the button press event with
this command:
fig = plt.figure() ... cid = fig.canvas.mpl_connect('button_press_event', onClick)
Now when your plot gets a mouse click, it will fire your callback
function. It returns a connection ID, stored in the variable
cid in this
example, that you can use to work with this callback function. When you
are done with the interaction, disconnect the callback function with:
fig.canvas.mpl_disconnect(cid)
If you just need to do basic interaction, you can use the
ginput()
command. It will listen for a set amount of time and return a list of
all of the clicks that happen on your plot. You then can process those
clicks and do some kind of interactive work.
The last thing I want to cover here is animation. matplotlib includes a sub-module called animation that provides all the functionality that you need to generate MPEG videos of your data. These movies can be made up of frames of various file formats, including PNG, JPEG or TIFF. There is a base class, called Animation, that you can subclass and add extra functionality. If you aren't interested in doing too much work, there are included subclasses. One of them, FuncAnimation, can generate an animation by repeatedly applying a given function and generating the frames of your animation. Several other low-level functions are available to control creating, encoding and writing movie files. You should have all the control you require to generate any movie files you may need.
Now that you have matplotlib under your belt, you can generate some really stunning visuals for your latest paper. Also, you will be able to find new and interesting relationships by graphing them. So, go check your data and see what might be hidden there. | https://www.linuxjournal.com/content/scientific-graphing-python | CC-MAIN-2018-22 | refinedweb | 1,382 | 65.62 |
Hans Glitsch wrote: > Ok, I found that the bug was introduced into std_4rx_0tx.rbf at version > 4848. Version 4287 does not have the problem. The changes in changeset 4713 looked suspicious. "Refactored FPGA *.vh files. Moved common pieces to toplevel/include. " But I couldn't find any obvisous mistakes there. Then I generated a complete diff between r 4287 and 4848 the following way: $ cd usrp $ svn diff -r 4287:4848 But I didn't find any mistakes there even. It is also possible that something went wrong when generating std_4rx_0tx.rbf. Has anybody tried rebuilding it (with Quartus II) with the current trunk code (r 4848 or later) When looking further into the code for the RX_chain I did find a few (unrelated) bugs in usrp/fpga/sdr_lib/rx_chain.v When the NCO is turned off (RX_NCO_ON is not defined) then sample_strobe is assigned to 1 However sample_strobe is an input, so this will fail. The same mistake is made for decimator_strobe when the CIC is turned off. It can be solved by adding wires for sample_strobe_internal and decimator_strobe_internal and assigning to that in stead. This probably hasn't surfaced because at the moment NCO and CIC are always enabled. see lines 31,32, 64 and 74 below. usrp/fpga/sdr_lib/rx_chain.v 31 input sample_strobe, 32 input decimator_strobe, ... 51 `ifdef RX_NCO_ON 52 phase_acc #(FREQADDR,PHASEADDR,32) rx_phase_acc 53 (.clk(clock),.reset(reset),.enable(enable), 54 .serial_addr(serial_addr),.serial_data(serial_data),.serial_strobe(serial_strobe), 55 .strobe(sample_strobe),.phase(phase) ); 56 57 cordic rx_cordic 58 ( .clock(clock),.reset(reset),.enable(enable), 59 .xi(i_in),.yi(q_in),.zi(phase[31:16]), 60 .xo(bb_i),.yo(bb_q),.zo() ); 61 `else 62 assign bb_i = i_in; 63 assign bb_q = q_in; 64 assign sample_strobe = 1; 65 `endif // !`ifdef RX_NCO_ON 66 67 `ifdef RX_CIC_ON 68 cic_decim cic_decim_i_0 69 ( .clock(clock),.reset(reset),.enable(enable), 70 .rate(decim_rate),.strobe_in(sample_strobe),.strobe_out(decimator_strobe), 71 .signal_in(bb_i),.signal_out(hb_in_i) ); 72 `else 73 assign hb_in_i = bb_i; 74 assign decimator_strobe = sample_strobe; 75 `endif Greetings, Martin > > Hans > > > ----- Original Message ----- From: "Johnathan Corgan" > <address@hidden> > To: "Eric Blossom" <address@hidden> > Cc: "Hans Glitsch" <address@hidden>; <address@hidden> > Sent: Wednesday, October 24, 2007 10:57 AM > Subject: Re: [Discuss-gnuradio] found problem with std_4rx_0tx.rbf > > >> Eric Blossom wrote: >> >>> I can reproduce it. There's definitely something off with >>> std_4rx_0tx.rbf. >>> I've opened ticket:195 >>> >>> [This is all I'm going to do about this right now.] >> >> Since that RBF has only been re-synthesized a couple of times in the >> last year or so, it would be straightforward to manually replace the >> file with the versions from 3.0 series, and see where the problem >> started. I think there will be at most 4 versions to test. You >> wouldn't need to change the host code any, just get the proper RBF from >> the repository and manually install into $prefix/share/usrp/rev2 and 4. >> >> -- >> Johnathan Corgan >> Corgan Enterprises LLC >> >> >> -- >> This message has been scanned for viruses and >> dangerous content by MailScanner, and is >> believed to be clean. >> >> >> >> >> -- >> No virus found in this incoming message. >> Checked by AVG Free Edition. >> Version: 7.5.503 / Virus Database: 269.15.9/1090 - Release Date: >> 10/24/2007 8:48 AM >> >> > > > > > _______________________________________________ > Discuss-gnuradio mailing list > address@hidden > > | https://lists.gnu.org/archive/html/discuss-gnuradio/2007-10/msg00404.html | CC-MAIN-2015-27 | refinedweb | 540 | 57.16 |
How to add a graph with LWUIT?
import com.sun.lwuit.Component;
import javax.microedition.lcdui.Graphics;
public class ChartComponent extends Component {
public void paint(Graphics g) {
g.setColor(0x222222);
g.fillRect(20, 30, 200, 80);
g.setColor(0x456548);
g.drawLine(0, 0, 100, 200);
}
}<br />
protected boolean onGraphFormDraw() {
boolean val = super.onGraphFormDraw();
Form root = Display.getInstance().getCurrent();
root.addComponent(BorderLayout.CENTER, new ChartComponent());
return val;
}
The way you are adding 'ChartComponent' to the form is correct. The issue is in the paint(){...} of ChatComponent. Use my sample code to kickstart your work
class ChartComponent extends Component {
boolean isDirty;
ChartComponent () {
isDirty = true;
}
public void paint(Graphics g) {
if (isDirty) {
//isDirty = false;
int buffer = 20;
g.setClip(getX(), getY(), getWidth(), getHeight());
//BG
g.setColor(0xEDEDED);
g.fillRect(getX(), getY(), getWidth(), getHeight());
//Graph grids
g.setColor(0xFFFFFF);
int size = 6;
for (int i = 0, x = getX() + buffer, y = getY() + buffer,
w = getWidth() - (buffer * 2),
h = getHeight() - (buffer * 2),
dw = w / size,
dh = h / size;
i < size; i++) {
g.drawRect(x + ( i * dw), y, dw, h);
g.drawRect(x, y + ( i * dh), w, dh);
}
//Graph axis
g.setColor(0x333333);
g.drawLine(getX() + buffer, getY() + getHeight() - buffer,
getX() + getWidth() - buffer, getY() + getHeight() - buffer); //X-axis
g.drawLine(getX() + buffer, getY() + buffer,
getX() + buffer, getY() + getHeight() - buffer); //Y-axis
//Write code to render axis units
//Write code to render axis legends
//code to render graph
}
}
<br type="_moz" />
You also need to worry about the padding and margin of the component and considering that in your calcualtions.
A good starting pointing to understand the LWUIT rendering (paint(){...}) is Label component. Check the method
DefaultLookAndFeel.drawLabel(Graphics g, Label l) {...}<br type="_moz" />
and understand how the component x, y, width, height and its padding, margin is used to render the component.
If your target is the right top quater that contains the graph, the approach would be
Create a custom component, over-ride its paint(...) to manually render the axis, the background grids and the graphs. To render the axis and grids, use lcdui drawline(...). To render the axis units and axis legends which are strings use bitmap / system fonts and read the lwuit label text display paint logic. Now to render the graph idea is to scale the original graph co-ordinates to your target graph co-ordinates , by this i mean reuse the bezier (or any other) algorithm to trace the graph but convert each graph co-ordinate to the target graph co-ordinate using the following formula
NOTE: Assumption is the graph (0,0) graphics reference rendering start point in the source and the target systems is the same which is left-top. In case they are different you have to appropriately change the formula.
The above concept is same conversion of world to view transformation of the object with 2D axis.
The other 3 quaters in your image are pretty simply to implement using the different components and forms. | https://www.java.net/forum/topic/mobile-embedded/lwuit/how-add-graph-lwuit | CC-MAIN-2015-35 | refinedweb | 488 | 56.25 |
Well then. It's been some time. Well it certainly feels that
way. I have currently made a concerted attempt at fixing
ferite's namespace polution problems and defining a more
conrete policy regarding namespaces - along with better name
resolution. This is taxing my brain so I have decied to take
a week off from coding it, this finished on monday.
In the mean times I have been doing a few more social things with my life - finally caught up with some mates from school I haven't seen for ages (spoken to them - but they are the animated sort of people that can only truely be appreciated in the person) in the pub - this was excellent. I then spent friday in London for a friends 21st birthday party and caught up with my flat mates and close friends from uni - this was also excellent. (the reason why I have been lazy is because I have spent most of my awake time at work).
Speaking of work, I wrote a small netware client for some people to mount the netware shares at work with a similar interface to that of the window's client. The app can be found here. I then found out that we no longer needed linux. Arse. Well at least the last week has been better than all the others (basically playing with Linux-Mandrake - which is better than redhat but by no means debian =p, coding and playing with my favorite OS). Incidently I still plan on working on the netware client - 0.2 is slowly coming along nicely (planned features: automounting on login, multiple mount points and servers, indepentdant mounting/unmounting). I finally finish work and amble back to university on friday (well go back on sunday) which I am really looking forware to doing.
So there we have it. Fun. I have also made some changes to darkrock which make it more fun and actually provide more. And having had 47,500 hits, that aint bad for a homepage :) | http://www.advogato.org/person/bowis/diary.html?start=6 | CC-MAIN-2014-52 | refinedweb | 336 | 68.81 |
Red Hat Bugzilla – Bug 429464
wsdl2py fails to execute
Last modified: 2013-01-10 05:21:40 EST
Description of problem:
/usr/bin/wsdl2py fails during program execution. Error message points to a
missing PyXML, which is however installed on the system.
Version-Release number of selected component (if applicable):
python-ZSI-2.0-3.fc8
PyXML-0.8.4-7
How reproducible:
Always(?)
Steps to Reproduce:
1. run /usr/bin/wsdl2py
Actual results:
$ /usr/bin/wsdl2py
Traceback (most recent call last):
File "/usr/bin/wsdl2py", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 2561, in <module>
working_set.require(__requires__): PyXML>=0.8.3
Expected results:
A working wsdl2py, e.g.
$ /usr/bin/wsdl2py
Must specify either --file or --url option
Additional info:
PyXML-0.8.4-7 from the f8 repository is installed on the system. Removing "PyXML
>= 0.8.3" from
/usr/lib/python2.5/site-packages/ZSI-2.0-py2.5.egg-info/requires.txt results in
a working wsdl2py.
This seems to be caused by PyXML - its non-devel packages have egg-info, its
devel has. ZSI just looks for egg-info and it doesn't exist.
Would you submit a bug against PyXML with request to build its new release under
F-8 and F-7?
Thanks, I submitted a bug against PyXML with the request to build the new
version for f8 and f7 ().
Setting it as a dependency. | https://bugzilla.redhat.com/show_bug.cgi?id=429464 | CC-MAIN-2016-40 | refinedweb | 245 | 52.76 |
TDD in the real world
8 min read - 2019-11-04
- Started reading Growing Object Oriented Software, Guided by Tests. Amazing book, super real use case, you build a project through the book.
- Book helped understand the importance of TDD, how that could apply
- is not slower, the time you will not spend manually testing will make up for that
- helps in providing design hints
- works as a checklist
- shows you the way on what to do next
- helps you not to bikeshed
- yagni - you build only what is necessary
- started from the top (now we’re here :joy:)
- api first / user first (inside out)
- you focus on business requirements
- you don’t jump to the solution
- incremental
- it looks like I’m selling it, but pretty much all the stuff software design books is applied there
- you can sleep at night
- you don’t loose sight of where you at
ideas
- build a couple of screens with tdd
- build a todo list (shitty). Better to build a small app
- from reducer to view
- before tdd, after tdd?
- ask miguel/janos for their opinions
- Hi
- read a book
- who heard or tdd?
- how many do it?
- why? It never applies to our usecase:
2 things are needed to grow software
- check
- easy to change and update code. What does it need?
tests. Why aren’t there any?
- tests are boring to write
- developers don’t like writing tests
- in some companies testing is not even considered real work when compared to adding features
- isn’t it the same thing if I write the tests afterwards?
- how comes I’m testing a feature that I don’t know how it’s built?
- I don’t know where to start
- I don’t know how it will look like
- what is this feature?
And this is, for me, where it changed. When you test first, testing becomes a design activity. You start asking questions and thinking about the answers. You answer them completely unbiased. You don’t know how does the implementation looks like, and you don’t need to.
I recently finished reading Growing Object Oriented Software, Guided by Tests. The book is one the best I’ve read, it takes a real world approach to problems while teaching and helping solve some daily life concerns, while explaining (based on the authors experience) how using TDD and having that mindset helps make writing/growing software easier. As you can probably guess, it changed my mindset.
I’vr read quite a lot about TDD in the past, did some on those small and useless projects, when it came to use it in a ‘more real’ project I used that common misconception that the authors point out ‘this doesn’t apply to my usecase’. A couple of weeks after trying it, I can admit that I was completely wrong.
It was actually one of the author’s quotes that made me question this. Throughout the book authors build an application that participates in auctions and based on some criteria, bids for items (trying to win them). The interesting thing here is to see how the program grows, what changed, what should be refactored now and what should stay ‘as is’.
The book recurrently presents a checklist that was created on the first chapter. That checklist is created based on the requirements, the application use cases. Those represent the features that have to be working for the application to be ready to ship.
We all use checklists, but these have a special thing, it auto checks and unchecks itself while you’re doing the task, because every checklist item represents one test, and that’s the beauty of it.
I’ll try to explain you a bit how it influenced my workflow. The book examples are written in Java, I’ll use javascript, react and jest for this blog post.
What do we want to build?
A small app to keep track of wine orders and payments from friends. The high level requirements are the following:
- Add/remove a bottle of wine
- Show the list of bottles for the current order
- Keep track of orders
- Create bottle orders for people
- Declare orders as paid
Payments are made offline, this just keeps track of it.
Let’s start
We don’t know how we’re going to build this, we didn’t give it that much thought. But that’s ok, we know what we want, let’s start with that.
Following the book authors’ recommendation, let’s try to get the simplest meaningful test written.
If you wanna follow the code, here you have it
import App from './index' it('lists', () => { const wrapper = });
requirements
- add available wines
- show available wines
- order wine for people
- declare order as paid
get the simplest meaningful test to pass
food for thought
focus on writing the simplest/lighter test you can for whatever you wanna test (you don’t want to create an e2e test for something you could have unit tested)
write the simplest piece of software that satisfies your requirement. Remember the
red > green > refactor, we want to get to the green so we can refactor
building a feature
- create the simplest test to grant that the bare minimum works (can be integration or unit but most likely is integration)
- your small feature will be done when that test passes
example:
create a form to add wines to a table of wines (the big feature)
smaller features (tests to be written):
- wine X and Y should appear on the table with year and region
let’s write the test:
Integration test that visits the page and asserts that wine X and Y are there together with region and year
test will fail
we start writing the feature
- open the table page component (it has nothing)
- open the table page component test
TablePage - write the test (unit)
- test it renders, has a title and a table
you write the test, it’s failing. You go and implement the feature, done?
implement the feature
ok, now you want the wines to be shown, right?
- test that some wines should appear on the table, with name, year and region
implement the feature
isn’t it ugly to not have a message when the table is empty? reflect that on tests
- test that by going to the page, an empty table message should appear
implement the feature
isn’t your code a little bit messy? (messi image :joy:). It is, we got to the green, lets refactor.
One of the big advantages the authors talk about in the book, TDD will let you use your developers instincts to detect where refactor is needed, it will take care of the it’s working? part.
Lets refactor our table to a
WinesTable that does logic we don’t wanna see here too often.
- create the folder > file
- let’s then write your logic… kidding, we apply the same principle, write the test first
test steps
- ok, import our component, it should render
- sending wines in, it should render as much tr as there’s wines
- wines years, names and region should be presented
- every test is failing, amazing!
let’s do an interesting thing: if what we have to do is the simplest implementation that works, let’s do it the simplistic way. We’re copying the hardcoded version of the table in.
- what happened? some of our tests are passing? we did a great job, let’s keep those on green while we implement the rest of the feature
- implement the logic to list wines with
.mapand etc (are the test still green? cool)
- all green! does it work? amazing!
note: without looking at your browser you’ve implemented a table that you’re confident enough that it works, aren’t you? How many refreshes did it take? How many clicks? Exactly.
Remember our tests for the
TablePage
implement the feature
passing? amazing
- test that by clicking on the
Addbutton it should redirect to the
/addpage
implement the feature
- test that by filling up the fields and clicking on submit, a callback should be called
implement the feature
- test that after the wine creation is successful, it should redirect to the table
Are you confident that your page is working? Are you confident that is has what it needs to? Let’s look at our checklist.
Subscribe to my newsletter to get updates on my newest articles!
No worries, I will not send more than 1 email per month , nor sell your email to third parties. | https://alexandrempsantos.com/growing-react-software-guided-by-tests/ | CC-MAIN-2020-29 | refinedweb | 1,425 | 66.98 |
Setting bluetooth characteristic in new firmware
Hello!
I'm trying to use Wipy as a BLE sensor. The following code is working on firmware 1.18.2.r7. I'm using the nRF Connect and with notifications enabled, characteristic changes are updated.
But with newer firmware it crashes on chr1.value(i) with "OSError: Erorr while sending BLE indication/notification".
from network import Bluetooth import time bt = Bluetooth() bt.set_advertisement(name='test-sensor', service_uuid=b'1234567890123456') bt.advertise(True) srv1 = bt.service(uuid=0x3000, isprimary=True, nbr_chars=1) chr1 = srv1.characteristic(uuid=0x3001, properties=Bluetooth.PROP_READ | Bluetooth.PROP_NOTIFY, value=0) i = 1 while i < 10: chr1.value(i) print('characteristic value = '+str(i)) time.sleep(5) i+=1
@wituwitu According to the answer from @lmo, you can only set the characteristic once you actually have a client connected. You'll get an error if you try to set it when there's no client.
I also have this problem... I tried with another similar code, but the same error "OSError: Erorr while sending BLE indication/notification" is displayed on chr1.value(val).
Anyone got a fix?
- nowakowski912 Banned last edited by
This post is deleted!
Thanks @jcaron, that was it. It would be nice if the characteristic could be set even if no client is connected, but I can probably work around that.
@lmo not sure I ever played with the BLE stuff on the Pycom modules, but shouldn’t you need to wait for a connection before sending updates? Though it would seem legitimate for it to just cache the value and don’t send anything if there’s no connection.
Does it throw on the first call, or after a few updates? | https://forum.pycom.io/topic/5725/setting-bluetooth-characteristic-in-new-firmware | CC-MAIN-2021-43 | refinedweb | 284 | 60.82 |
Cant connect Sipy to Sigfox Backend[Argentina][RCZ4]
Hello. I have now been trying to connect to Sigfox Backend for over a week without any success. I successfully went through the whole setup project, following the web page tutorial and this one:
On every step, i changed RCZ1 to RCZ4 given that is my sigfox zone.
At the end, this is what i get in my device data on the sigfox backend:
This is what i see on the back end:
I am now trying to post something to sigfox public network from the device telnet commandline using the following code:
import socket
from network import Sigfox
sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ4)
s = socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW)
s.setblocking(True)
s.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False)
s.send(bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]))
12
I tried downgrading the firmware from 1.15 to 1.12, also without success.
Please help! Thanks a lot!
This post is deleted!
- egimbernat last edited by
Hello both,
To receive help is preferable to you share your current location (Country, city) to find out if Sigfox is available, pycom device (They are 3 devices that can use Sigfox) and current framework you are using.
First verify the coverage for your location
Please verify:
1- THE ANTENNA IS CONNECTED TO THE DEVICE
2- Try sending a message outside of building
3- Try to send short message
4- Follow this tutorial for disengage sequence number
@pepo hola
tengo el mismo problema, lograste conectarte?
podrias darme una mano, muchas gracias por responder | https://forum.pycom.io/topic/3361/cant-connect-sipy-to-sigfox-backend-argentina-rcz4 | CC-MAIN-2018-51 | refinedweb | 268 | 53.61 |
Abstract
Contents
- Abstract
- Rationale
- Use Cases
- Code transformer API
- Changes
- Examples
- Other Python implementations
- Discussion
- Prior Art
Propose an API to register bytecode and AST transformers. Add also -o OPTIM_TAG command line option to change .pyc filenames, -o noopt disables the peephole optimizer. Raise an ImportError exception on import if the .pyc file is missing and the code transformers required to transform the code are missing. code transformers are not needed code transformed ahead of time (loaded from .pyc files).
Rationale
Python does not provide a standard way to transform the code. Projects transforming the code use various hooks. The MacroPy project uses an import hook: it adds its own module finder in sys.meta_path to hook its AST transformer. Another option is to monkey-patch the builtin compile() function. There are even more options to hook a code transformer.
Python 3.4 added a compile_source() method to importlib.abc.SourceLoader. But code transformation is wider than just importing modules, see described use cases below.
Writing an optimizer or a preprocessor is out of the scope of this PEP.
Usage 1: AST optimizer
Transforming an Abstract Syntax Tree (AST) is a convenient way to implement an optimizer. It's easier to work on the AST than working on the bytecode, AST contains more information and is more high level.
Since the optimization can done ahead of time, complex but slow optimizations can be implemented.
Example of optimizations which can be implemented with an AST optimizer:
- Copy propagation: replace x=1; y=x with x=1; y=1
- Constant folding: replace 1+1 with 2
- Dead code elimination
Using guards (see the PEP 510), it is possible to implement a much wider choice of optimizations. Examples:
- Simplify iterable: replace range(3) with (0, 1, 2) when used as iterable
- Loop unrolling
- Call pure builtins: replace len("abc") with 3
- Copy used builtin symbols to constants
- See also optimizations implemented in fatoptimizer, a static optimizer for Python 3.6.
The following issues can be implemented with an AST optimizer:
-
Usage 2: Preprocessor
A preprocessor can be easily implemented with an AST transformer. A preprocessor has various and different usages.
Some examples:
- Remove debug code like assertions and logs to make the code faster to run it for production.
- Tail-call Optimization
- Add profiling code
- Lazy evaluation: see lazy_python (bytecode transformer) and lazy macro of MacroPy (AST transformer)
- Change dictionary literals into collection.OrderedDict instances
- Declare constants: see @asconstants of codetransformer
- Domain Specific Language (DSL) like SQL queries. The Python language itself doesn't need to be modified. Previous attempts to implement DSL for SQL like PEP 335 - Overloadable Boolean Operators was rejected.
- Pattern Matching of functional languages
- String Interpolation, but PEP 498 -- Literal String Interpolation was merged into Python 3.6.
MacroPy has a long list of examples and use cases.
This PEP does not add any new code transformer. Using a code transformer will require an external module and to register it manually.
See also PyXfuscator: Python obfuscator, deobfuscator, and user-assisted decompiler.
Usage 3: Disable all optimization
Ned Batchelder asked to add an option to disable the peephole optimizer because it makes code coverage more difficult to implement. See the discussion on the python-ideas mailing list: Disable all peephole optimizations.
This PEP adds a new -o noopt command line option to disable the peephole optimizer. In Python, it's as easy as:
sys.set_code_transformers([])
It will fix the Issue #2506: Add mechanism to disable optimizations.
Usage 4: Write new bytecode optimizers in Python
Python 3.6 optimizes the code using a peephole optimizer. By definition, a peephole optimizer has a narrow view of the code and so can only implement basic optimizations. The optimizer rewrites the bytecode. It is difficult to enhance it, because it written in C.
With this PEP, it becomes possible to implement a new bytecode optimizer in pure Python and experiment new optimizations.
Some optimizations are easier to implement on the AST like constant folding, but optimizations on the bytecode are still useful. For example, when the AST is compiled to bytecode, useless jumps can be emitted because the compiler is naive and does not try to optimize anything.
Use Cases
This section give examples of use cases explaining when and how code transformers will be used.
Interactive interpreter
It will be possible to use code transformers with the interactive interpreter which is popular in Python and commonly used to demonstrate Python.
The code is transformed at runtime and so the interpreter can be slower when expensive code transformers are used.
Build a transformed package
It will be possible to build a package of the transformed code.
A transformer can have a configuration. The configuration is not stored in the package.
All .pyc files of the package must be transformed with the same code transformers and the same transformers configuration.
It is possible to build different .pyc files using different optimizer tags. Example: fat for the default configuration and fat_inline for a different configuration with function inlining enabled.
A package can contain .pyc files with different optimizer tags.
Install a package containing transformed .pyc files
It will be possible to install a package which contains transformed .pyc files.
All .pyc files with any optimizer tag contained in the package are installed, not only for the current optimizer tag.
Build .pyc files when installing a package
If a package does not contain any .pyc files of the current optimizer tag (or some .pyc files are missing), the .pyc are created during the installation.
Code transformers of the optimizer tag are required. Otherwise, the installation fails with an error.
Execute transformed code
It will be possible to execute transformed code.
Raise an ImportError exception on import if the .pyc file of the current optimizer tag is missing and the code transformers required to transform the code are missing.
The interesting point here is that code transformers are not needed to execute the transformed code if all required .pyc files are already available.
Code transformer API
A code transformer is a class with ast_transformer() and/or code_transformer() methods (API described below) and a name attribute.
For efficiency, do not define a code_transformer() or ast_transformer() method if it does nothing.
The name attribute (str) must be a short string used to identify an optimizer. It is used to build a .pyc filename. The name must not contain dots ('.'), dashes ('-') or directory separators: dots are used to separated fields in a .pyc filename and dashes areused to join code transformer names to build the optimizer tag.
Note
It would be nice to pass the fully qualified name of a module in the context when an AST transformer is used to transform a module on import, but it looks like the information is not available in PyParser_ASTFromStringObject().
code_transformer() method
Prototype:
def code_transformer(self, code, context): ... new_code = ... ... return new_code
Parameters:
- code: code object
- context: an object with an optimize attribute (int), the optimization level (0, 1 or 2). The value of the optimize attribute comes from the optimize parameter of the compile() function, it is equal to sys.flags.optimize by default.
Each implementation of Python can add extra attributes to context. For example, on CPython, context will also have the following attribute:
- interactive (bool): true if in interactive mode
XXX add more flags?
XXX replace flags int with a sub-namespace, or with specific attributes?
The method must return a code object.
The code transformer is run after the compilation to bytecode
ast_transformer() method
Prototype:
def ast_transformer(self, tree, context): ... return tree
Parameters:
- tree: an AST tree
- context: an object with a filename attribute (str)
It must return an AST tree. It can modify the AST tree in place, or create a new AST tree.
The AST transformer is called after the creation of the AST by the parser and before the compilation to bytecode. New attributes may be added to context in the future.
Changes
In short, add:
- -o OPTIM_TAG command line option
- sys.implementation.optim_tag
- sys.get_code_transformers()
- sys.set_code_transformers(transformers)
- ast.PyCF_TRANSFORMED_AST
API to get/set code transformers
Add new functions to register code transformers:
- sys.set_code_transformers(transformers): set the list of code transformers and update sys.implementation.optim_tag
- sys.get_code_transformers(): get the list of code transformers.
The order of code transformers matter. Running transformer A and then transformer B can give a different output than running transformer B an then transformer A.
Example to prepend a new code transformer:
transformers = sys.get_code_transformers() transformers.insert(0, new_cool_transformer) sys.set_code_transformers(transformers)
All AST transformers are run sequentially (ex: the second transformer gets the input of the first transformer), and then all bytecode transformers are run sequentially.
Optimizer tag
Changes:
- Add sys.implementation.optim_tag (str): optimization tag. The default optimization tag is 'opt'.
- Add a new -o OPTIM_TAG command line option to set sys.implementation.optim_tag.
Changes on importlib:
- importlib uses sys.implementation.optim_tag to build the .pyc filename to importing modules, instead of always using opt. Remove also the special case for the optimizer level 0 with the default optimizer tag 'opt' to simplify the code.
- When loading a module, if the .pyc file is missing but the .py is available, the .py is only used if code optimizers have the same optimizer tag than the current tag, otherwise an ImportError exception is raised.
Pseudo-code of a use_py() function to decide if a .py file can be compiled to import a module:
def transformers_tag(): transformers = sys.get_code_transformers() if not transformers: return 'noopt' return '-'.join(transformer.name for transformer in transformers) def use_py(): return (transformers_tag() == sys.implementation.optim_tag)
The order of sys.get_code_transformers() matter. For example, the fat transformer followed by the pythran transformer gives the optimizer tag fat-pythran.
The behaviour of the importlib module is unchanged with the default optimizer tag ('opt').
Peephole optimizer
By default, sys.implementation.optim_tag is opt and sys.get_code_transformers() returns a list of one code transformer: the peephole optimizer (optimize the bytecode).
Use -o noopt to disable the peephole optimizer. In this case, the optimizer tag is noopt and no code transformer is registered.
Using the -o opt option has not effect.
AST enhancements
Enhancements to simplify the implementation of AST transformers:
- Add a new compiler flag PyCF_TRANSFORMED_AST to get the transformed AST. PyCF_ONLY_AST returns the AST before the transformers.
Examples
.pyc filenames
Example of .pyc filenames of the os module.
With the default optimizer tag 'opt':
With the 'fat' optimizer tag:
Bytecode transformer
Scary bytecode transformer replacing all strings with "Ni! Ni! Ni!":
import sys import types class BytecodeTransformer: name = "knights_who_say_ni" def code_transformer(self, code, context): consts = ['Ni! Ni! Ni!' if isinstance(const, str) else const for const in code.co_consts] return types.CodeType(code.co_argcount, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, tuple(consts), code.co_names, code.co_varnames, code.co_filename, code.co_name, code.co_firstlineno, code.co_lnotab, code.co_freevars, code.co_cellvars) # replace existing code transformers with the new bytecode transformer sys.set_code_transformers([BytecodeTransformer()]) # execute code which will be transformed by code_transformer() exec("print('Hello World!')")
Output:
Ni! Ni! Ni!
AST transformer
Similary to the bytecode transformer example, the AST transformer also replaces all strings with "Ni! Ni! Ni!":
import ast import sys class KnightsWhoSayNi(ast.NodeTransformer): def visit_Str(self, node): node.s = 'Ni! Ni! Ni!' return node class ASTTransformer: name = "knights_who_say_ni" def __init__(self): self.transformer = KnightsWhoSayNi() def ast_transformer(self, tree, context): self.transformer.visit(tree) return tree # replace existing code transformers with the new AST transformer sys.set_code_transformers([ASTTransformer()]) # execute code which will be transformed by ast_transformer() exec("print('Hello World!')")
Output:
Ni! Ni! Ni!
Other Python implementations
The PEP 511 should be implemented by all Python implementation, but the bytecode and the AST are not standardized.
By the way, even between minor version of CPython, there are changes on the AST API. There are differences, but only minor differences. It is quite easy to write an AST transformer which works on Python 2.7 and Python 3.5 for example..
In 2015, Victor Stinner wrote the fatoptimizer project, an AST optimizer specializing functions using guards.
In 2014, Kevin Conway created the PyCC optimizer.
In 2012, Victor Stinner wrote the astoptimizer project, an AST optimizer implementing various optimizations. Most interesting optimizations break the Python semantics since no guard is used to disable optimization if something changes.
In 2011, Eugene Toder proposed to rewrite some peephole optimizations in a new AST optimizer: issue #11549, Build-out an AST optimizer, moving some functionality out of the peephole optimizer. The patch adds ast.Lit (it was proposed to rename it to ast.Literal).
Python Preprocessors
- MacroPy: MacroPy is an implementation of Syntactic Macros in the Python Programming Language. MacroPy provides a mechanism for user-defined functions (macros) to perform transformations on the abstract syntax tree (AST) of a Python program at import time.
- pypreprocessor: C-style preprocessor directives in Python, like #define and #ifdef
Bytecode transformers
- codetransformer: Bytecode transformers for CPython inspired by the ast module’s NodeTransformer.
- byteplay: Byteplay lets you convert Python code objects into equivalent objects which are easy to play with, and lets you convert those objects back into living Python code objects. It's useful for applying crazy transformations on Python functions, and is also useful in learning Python byte code intricacies. See byteplay documentation.
See also: | http://docs.activestate.com/activepython/3.5/peps/pep-0511.html | CC-MAIN-2018-34 | refinedweb | 2,201 | 50.02 |
P
Thanks for your feedback.
10/16/2006 Update: I updated the link to the correct site
Was it funded by Microsoft project ?
The Power Collections project is interesting but I would never use this library due to its bizarre "Shared Source License".
So any effort you put into PowerXxx projects is wasted from my perspective, unless you change to something sane like the MIT license.
Unless you do that, I would prefer you put the effort into improving the .NET Framework and other official libraries.
The PowerCollections library has a noxious licensing clause, IIRC, about being impossible to use with open source / free software. Even though I don’t write open source software, I can’t limit my options for the future, so such a library is out of the question.
Barrkel and Chris — thanks for your feedback on the license… this is helpful.
TAG — yes, we put some money into it as well as time from folks like Anders Hejlsberg and other product team members.
I’m perfectly happy to see PowerCollections folded into the Framework. Same with a PowerIO and a PowerMath class.
One of the great successes of Python was in having a very rich Framework out of the box. I think PowerFoo can serve that end for .NET, but to greatest effect only if packaged with the main framework for both visibility and standardization.
Having to go through and download yet-another-implementation-of-the-wheel is one of the pains I’ve encountered in dealing with Java projects. I’d rather not have to do that.
Wishlist re Math: Physical constants library and some sort of dimension-safe-at-compile-time units framework. That way I could say that not only is some value a double, but that it’s a Length, or that it’s a Mass, and that this funtion takes Speed, which is the same as Length over Time, etc. One could do this at runtime (I’ve written as much), but true compile time safety of this nature would require some work on the compiler and CLR to add value parameterization.
struct Unit<T><NLength, NTime, NMass, NCharge, …>
struct Speed<T> : Unit<T><1, -1, 0, 0, …>
struct Unit<T><int NLength, int NTime, int NMass, int NCharge, …>
{
Unit<T><NLength – nLength, NTime – nTime, NMass – nMass, NCharge – nCharge, ….>
operator/(Unit<T><nLength, nTime, nMass, nCharge, …> divisor) { }
}
var Meter = new Unit<double><1, 0, 0, 0, …>(1);
var Second = new Unit<double><0, 1, 0, 0, …>(1);
var SpeedOfLight = 300000 * Meter / Second;
This also leads to compile-time safety for fixed-size matrices, also a math goodness.
Hi Brad,
I didn’t know Microsoft went as far as paying for some of this stuff. While you were at it, why wasn’t the effort done internally? BCL is sorely lacking in the department Power Collections are covering and if it weren’t for Power Collection I’d probably have to roll some of my own, which is insane in 2005 (all of the collections and algorithms were present in C++/Java for quite some time).
I like that at least something is available and appreciate the effort guys from Wintellect put into it. The library seems well designed (we’ll see how well it is implemented once I start using it more seriously).
That said, you should know that many, many developers will simply not use it because it’s not "official" Microsoft stuff (is not part of BCL) while many would probably use it if they knew it existed (thus it is good you’re writing this, some might discover the lib through this post).
Personally, I think that Microsoft should have done the Power Collections and have richer containter classes/algorithms in BCL. However, if this is the only way we can hope to get some stuff out of the door due to buirocracy in Microsoft, then by all means "outsource" other pieces of BCL. I’d still prefer Microsoft doing the work, not because I fear the quality of work of external companies, but because of the issues above – discoverability and "officialness".
Aside for the licence, which I have already complain to in Peter Golde’s blog, I think Power Collections are awesome. I’ve been using it for the last 6 months or so and now I can’t stop using it, if feels like part of the BCL itself and that’s great. I really apreciate you guys putting effort on this project and I’m really loking forward for more power stuff (specially Power Threading… any news on this project??)
I’d have to agree with some of the other comments: why doesn’t this come directly from Microsoft?
I’d be *MUCH* more likely to take it seriously if it was in a Microsoft.<something> namespace and available as a MSDN download.
Either that…or get the guys a boost.org to take it over 🙂
I would really like to use this, but it looks like clause B (the anti-GPL clause) is still hanging around the license. I’d rather just roll my own classes as I need them than limit what other people can do with my (research-oriented) code once I make it freely available.
Yes I would like PowerMath and PowerIO. Math should get BigInteger so don’t have to rip it out of Mono. This would kinda look like a "Fedora" deal where community adds function and eventually MS picks the best stuff and adds to BCL.
I’m not sure i understand the other comments.
Why is Power* any different from Boost* libraries? A good library is a good library, and is all about not rebuilding a wheel (especially one done better).
For the licensing, is GPL the only concern? Many licenses aren’t GPL-compatible. Not even the whole BCL is GPL-compatible, though Rotor and Mono show that a subset can be replicated. If you don’t like the terms of the license, do as Mono does and copy the API surface.
Is it that those interested are in more of an academic environment? I genuinely don’t understand the antipathy.
Not being one of those who cares about OSS licensing (I’m wistful for the simple "public domain" days), all I can comment on is the desire to see Power Collections assume a more prominent position as a proper member of the BCL.
It makes the BCL richer, helps promote standardization (the roll-your-own instinct leads to disasterous balkanization), and removes any excuses people have for not knowing what it is or where to get it. Any, that is, except for "Haven’t tried that part of the namespace .. yet!".
I’m already using PowerCollections in some of our projects. Coming from a strong C++/STL background, I can see huge utility in these PowerCollections.
Having it as part of the "official" class libraries would be most welcome – and any additional PowerX libraries would be equally welcome!
I agree with lot of people here that there shouldnt be any added licesning restrictions in using this code. It should be avialble as .NET BCL
to me, the license doesn’t seem too bad…(of course, this is all subjective)… It would be great if it was MIT or in the BCL, but between a take it or leave it, I’ll take it.
Adding more to my thoughts concerngin the license, it seems that it wants to restrict you from combining or having its license overridden by another’s license, in the case of combining…
…why does it have to be combined? why can’t it be a library that is uesd? There may be an issue I’m not thinking of.
PowerCollections are great. Too bad that there is such a bizarre licence that prevent any free/open source distribution. It’s preventing me to actually use such good tool.
I do not understand how does it make sense for MS? Why having a more restrictive licence for the PowerCollections than for the .Net framework?
Power Collections look very good, I think I might use them for my next application, but,..
I’d also be scared of the non-standardization issue. I’m a freelancer in a certain company. Sometimes I take the whole projects, and sometimes I only take that certain part. So, I need something that won’t confuse other developers when they look at it. SAme for the out/in the box issue.
A great example on that all would be MS Enterprise Library. It’s done by MS and as a community project; It’s standard enough to work with and recommend, and, when the next version of the framework ships, I know it’ll include most of the current Ent. Lib. features. This already happened with En. Lib. and .NET 1.x and 2.0. I think this is the best model ever! | https://blogs.msdn.microsoft.com/brada/2005/11/14/powercollections-for-v2-0-rtm/ | CC-MAIN-2017-09 | refinedweb | 1,484 | 70.73 |
lseek — reposition read/write file offset
#include <sys/types.h> #include <unistd.h>
l:
Upon successful completion,
lseek() returns the resulting offset
location as measured in bytes from the beginning of the file.
On error, the value (off_t)
−1 is returned and
errno is set to indicate the error.
fd is not an
open file descriptor.
whence is
not valid. Or: the resulting file offset would be
negative, or beyond the end of a seekable device.
whence is
SEEK_DATA or
SEEK_HOLE, and the file offset is
beyond the end of the file.
The resulting file offset cannot be represented in an off_t..
dup(2), fallocate(2), fork(2), open(2), fseek(3), lseek64(3), posix_fallocate(3) | https://manpages.net/htmlman2/lseek.2.html | CC-MAIN-2022-21 | refinedweb | 116 | 60.82 |
i want to make a program that has a player take on the computer in a game of Rock Paper Scissors. The GUI should have an appropriate lable at the top. it should allow the player to select his or her weapon of choice. program should have a fight button that when clicked has the computer select either rock, paper or scissors at random and displays the results of the battle
here is my code could ya'll show we what to do
import random Name = raw_input ("Enter Name here: ") print "Hello " + Name + "! I am a python script specialy designed for a game called rock paper scissors!" answer = raw_input ("Do you want to play? : ") if answer == ("yes"): print "Okay! Lets play!" PC = raw_input ("Choose rock, paper, or scissors: ") rand = random.randint(1, 3) #1 means rock, 2 means paper, 3 means scissors if PC == ("rock"): if rand == (1): print "Tie game!" elif rand == 2: print "Game lost!" elif rand == 3: print "Game Win!" if PC == ("paper"): if rand == 2: print "Tie game!" elif rand == 3: print "Game lost!" elif rand == 1: print "Game Win!" if PC == ("scissors"): if rand == 3: print "Tie game!" elif rand == 1: print "Game lost!" elif rand == 2: print "Game Win!" else : print "aww!" | https://www.daniweb.com/programming/software-development/threads/328529/rock-paper-scissors-gui | CC-MAIN-2017-22 | refinedweb | 208 | 93.74 |
From Documentation
Python With ZK.
Below we show you a possible way of keeping Python code separate from your ZUL files and even do a little bit of MVC and "design by convention" to make things easier.
First a Simple ZUL - testhello.zul
<zk> <zscript src="PythonForwardComposer.py" language="python"></zscript> <zscript src="BobController.py" language="python"></zscript> <window title="Test Hello Window" border="normal" height="200px" apply="${BobController}" width="200px" closable="true" sizable="true"> Hello World Message: <label id="lMessage"/> <textbox id="txMessage"/> <button id="okButton" label="OK"/> </window> </zk>
The important things to notice are the includes for PythonForwardCompose.py and BobController.py and the
apply="${BobController}" parameter. Both includes are python files. Let us ignore PythonForwardComposer for now and start with BobController :-
A simple controller - BobController.py
class BobController(PythonForwardComposer): def onClick_okButton(self, event): message = txMessage.getValue() lMessage.setValue(lMessage.getValue() + message)
The
apply="${BobController}" on the ZUL tells ZK that instead of the GenericForwardComposer we will use BobController to compose the page. BobController simply extends PythonForwardComposer but overides the onClick event for the okButton. Notice how there is an underscore between onClick and okButton. In the many java examples you will see a "$" sign used but that is a reserved character in python, therefore we use an underscore.
At the risk of stating the obvious, just as with using GenericForwardComposer in Java (ZK Developer's Reference: MVC) it is important that the name of the button in the ZUL (id="okButton") matches exactly (including case) the method defined in BobController. Welcome to "design by convention".
You will also see how in BobController we can use txMessage and lMessage (defined in the ZUL with exactly those names) directly and get and set them as required
Ok, we have seen how a simple python can automatically get at ZUL variables and how a ZUL component will invoke a method in BobController.
Now for the magic :-
Python composer - PythonForwardComposer.py
from org.zkoss.zk.ui.util import GenericForwardComposer; method.count('_') == 1:)
This bit of magic extends the standard ZK GenericForwardComposer. Importantly it changes the separator from being a dollar to an underscore. It then wires in all of the "events" and on receiving one of those events it fires off the appropriate method in (in this case) BobController.
That's it.
You should not need to change PythonForwardComposer, just simply include it at the start of your ZUL files. Of course you still have to write your own version of BobController and your own ZUL but now you have a template to follow.
Put the 3 files above (testhello.zul, BobConroller.py and PythonForwardComposer.py) into the WebContent folder of a ZK project and try it. You should get a screen with the words "Hello World Message" with an input box under it. Enter something in the input box, click OK and the Hello World Message" will change.
Thanks must go to my colleague Jon Ady for help with this (specifically PythonForwardComposer) and to Michele Mazzei who wrote a Java version of the helloworld ZK that this version is based on.
See Also | http://books.zkoss.org/wiki/Small%20Talks/2010/February/Python%20With%20ZK | CC-MAIN-2014-15 | refinedweb | 515 | 56.55 |
Introduction on CardLayout in Java
The following article CardLayout in Java provides an outline for the different methods of CardLayouts in java. As we are aware of the concept of Layout in Java and how the different Layout Manager helps in managing so many components in a single container without affecting the positioning of each other. The card layout is one of them. Unlike other layouts, which display the components of a container one at a time, Card Layout as the name indicates, works like a deck of playing cards with only one card, i.e. the topmost card visible at a single time. It treats every component in a container as a Card and the container acting as a Stack of cards. The ordering of the cards in a container is defined internally. When the container is displayed for the first time, it is the first component present in the container that is visible at that time.
Constructors of CardLayout in Java
CardLayout is a class of Java and it has some constructors. Below given are some of the Constructors of CardLayout in Java:
CardLayout()
This constructor of Java class CardLayout is used to create a new CardLayout with the gaps of size zero (0) between the different components.
CardLayout(int hgap, int vgap)
This constructor of Java is used to create a new CardLayout with the horizontal and vertical gap between the components as mentioned in the arguments. Hgap denotes the horizontal gap whereas vgap represents the vertical gap between the components.
Methods of CardLayout class in Java
Below given is the list of the methods of CardLayout class:
Example for CardLayout in Java
// importing all the necessary packages
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.*;
// Class Cardlayout is extending the JFrame and implementing the interface of ActionListener
public class Cardlayout extends JFrame implements ActionListener {
// Declaring the objects of the above mentioned Cardlayout class.
CardLayout cd;
// Declaring the objects of JButton class which we want in our JFrame
JButton jb1, jb2, jb3;
// Declaring the object of the Container class with the name ‘con’.
Container con;
// Using the constructor of the class CardLayout in order to initialise the above objects
Cardlayout()
{
// using the method in order to get the content
con = getContentPane();
// Initializing the object "cd” of CardLayout class with horizontal and vertical spaces as 70 and 50 respectively
cd = new CardLayout(70, 50);
// setting of the layout using the setLayout method
con.setLayout(cd);
// Initialising the object "jb1" of the above JButton class.
jb1 = new JButton("Hello");
// Initialising the object "jb2" of the above JButton class.
jb2 = new JButton("Hey");
// Initialising the object "jb3" of the above JButton class.
jb3 = new JButton("Hii");
// Using this Keyword in order to refers to the current object.
// Adding of Jbutton "jb1" on JFrame using the methods of ActionListener
jb1.addActionListener(this);
// Adding of Jbutton "jb2" on JFrame.
jb2.addActionListener(this);
// Adding of Jbutton "jb3" on JFrame.
jb3.addActionListener(this);
// Adding of the above buttons to the container one by one
// Adding the JButton "jb1" using add method
con.add("a", jb1);
// Adding the JButton "jb2" similar to the above
con.add("b", jb2);
// Adding the JButton "jb3" in the container
con.add("c", jb3);
}
public void actionPerformed(ActionEvent e)
{
// using next method to call the next card
cd.next(con);
}
// Main Method of Java class from where the execution starts
public static void main(String[] args)
{
// Creating Object of CardLayout class.
Cardlayout cl1 = new Cardlayout();
// Setting the title of JFrame
cl1. setTitle("Checking how Card Layout works");
// Setting the size of JFrame.
cl1.setSize(800, 800);
// Setting the resizable value of JFrame.
cl1.setResizable(false);
// Setting the visibility of JFrame.
cl1.setVisible(true);
// Function to set default operation of JFrame.
cl1.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
In the above example, Cardlayout is the class name which is inheriting the JFrame and implementing the ActionListener interface. We are trying to arrange the various JLabel components in a JFrame. We are creating 3 jButtons with the name jb1, jb2, jb3 and adding them to the JFrame. The buttons are added to the jFrame using the add () method. In the main function, various methods are used like setVisible() in order to set the visibility of frame, setResizable in order to set the resizability, setTitle and setSize for setting the title and size of the frame.Explanation
Output:
So as given below, output would be a jFrame with the first button with the name “Hello” displayed first, clicking on it second button “Hey” is displayed and then clicking on it button “Hii” is displayed to the user.
Conclusion
There are various types of layouts in Java and every layout has its own way of arranging the components. To work efficiently on GUI applications, deep and practical understanding of every layout is very important for a programmer. Graphics Programming also uses Layout Managers in its development which is trending in IT industry.
Recommended Articles
This is a guide to CardLayout in Java. Here we discuss the Introduction, Constructors, and Methods of Cardlayout in Java along with some Examples. You may also look at the following articles to learn more– | https://www.educba.com/cardlayout-in-java/ | CC-MAIN-2020-24 | refinedweb | 857 | 53.41 |
You may link to this document using short form: or its real address: or view this file with any Markdown viewer.
This library is poorly documented at the moment and expects of the user to be acquainted with C/C++.
ImGui::ShowDemoWindow()function. The demo covers most features of Dear ImGui, so you can read the code and see its output.
ImGui::ShowMetricsWindow()function exposes lots of internal information and tools. Although it is primary designed as a debugging tool, having access to that information tends to help understands concepts.
This library is called Dear ImGui. Please refer to it as Dear ImGui (not ImGui, not IMGUI).
(The library misleadingly started its life in 2014 as “ImGui” due to the fact that I didn't give it a proper name when the ambiguity without affecting existing code bases, I have decided in December 2015 a fully qualified name “Dear ImGui” for this library.
I occasionally tag Releases but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported.
You may use the docking branch which includes:
Many projects are using this branch and it is kept in sync with master regularly.
You may merge in the tables branch which includes:
Read
PROGRAMMER GUIDE section of imgui.cpp. Read examples/README.txt.
You can read the
io.WantCaptureMouse,
io.WantCaptureKeyboard and
io.WantTextInput flags from the ImGuiIO structure.
e.g.
if (ImGui::GetIO().WantCaptureMouse) { ... }
io.WantCaptureMouseis set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application.
io.WantCaptureKeyboardis set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application.
io.WantTextInputis set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
Note: You should always pass your mouse/keyboard inputs to Dear ImGui, even when the io.WantCaptureXXX flag are set false. This is because imgui needs to detect that you clicked in the void to unfocus its own windows.
Note: The
io.WantCaptureMouse is more correct that any manual attempt to “check if the mouse is hovering a window” (don't do that!). It handle mouse dragging correctly (both dragging that started over your application or over a Dear ImGui window) and handle e.g. popup and modal windows blocking inputs.
Note: Those flags are updated by
ImGui::NewFrame(). However it is generally more correct and easier that you poll flags from the previous frame, then submit your inputs, then call
NewFrame(). If you attempt to do the opposite (which is generally harder) you are likely going to submit your inputs after
NewFrame(), and therefore too late.
Note: If you are using a touch device, you may find use for an early call to
UpdateHoveredWindowAndCaptureFlags() to correctly dispatch your initial touch. We will work on better out-of-the-box touch support in the future.
Note: Text input widget releases focus on the “KeyDown” event of the Return key, so the subsequent “KeyUp” event that your application receive will typically have
io.WantCaptureKeyboard == false. Depending on your application logic it may or not be inconvenient to receive that KeyUp event. You might want to track which key-downs were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboardto enable.
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepadto enable (with a supporting back-end).
USING GAMEPAD/KEYBOARD NAVIGATION CONTROLSsection of imgui.cpp for more details.
style.TouchPaddingsetting) to accommodate for the lack of precision of touch inputs, but it is recommended you use a mouse or gamepad to allow optimizing for screen real-estate and precision.
This usually means that: your font texture wasn‘t uploaded into GPU, or your shader or other rendering state are not reading from the right texture (e.g. texture wasn’t bound). If this happens using the standard back-ends it is probably that the texture failed to upload, which could happens if for some reason your texture is too big. Also see docs/FONTS.md.
You are probably mishandling the clipping rectangles in your render function. Each draw command needs the triangle rendered using the clipping rectangle provided in the ImDrawCmd structure (
ImDrawCmd->CllipRect). Rectangles provided by Dear ImGui are defined as
(x1=left,y1=top,x2=right,y2=bottom) and NOT as
(x1,y1,width,height) Refer to rendering back-ends in the examples/ folder for references of how to handle the
ClipRect field.
A primer on labels and the ID Stack...
Dear ImGui internally need to uniquely identify UI elements. Elements that are typically not clickable (such as calls to the Text functions) don't need an ID. Interactive widgets (such as calls to Button buttons) need a unique ID. Unique ID are used internally to track active widgets and occasionally associate state to widgets. Unique ID are implicitly built from the hash of multiple elements that identify the “path” to the UI element.
Begin("MyWindow"); Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK") Button("Cancel"); // Label = "Cancel", ID = hash of ("MyWindow", "Cancel") End();
Begin("MyWindow"); if (TreeNode("MyTreeNode")) { Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "MyTreeNode", "OK") TreePop(); } End();
Begin("MyFirstWindow"); Button("OK"); // Label = "OK", ID = hash of ("MyFirstWindow", "OK") End(); Begin("MyOtherWindow"); Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK") End();
We used “...” above to signify whatever was already pushed to the ID stack previously:
Button("OK"); Button("OK"); // ID collision! Interacting with either button will trigger the first one.
Fear not! this is easy to solve and there are many ways to solve it!
Begin("MyWindow"); Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play") Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above End();
Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox!
Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID") Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even if the label looks different sprintf(buf, "My game (%f FPS)###MyGame", fps); Begin(buf); // Variable title, ID = hash of "MyGame"
Begin("Window"); for (int i = 0; i < 100; i++) { PushID(i); // Push i to the id tack Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click") PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj); Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click") PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj->Name); Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click") PopID(); } End();
Button("Click"); // Label = "Click", ID = hash of (..., "Click") PushID("node"); Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") PushID(my_ptr); Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click") PopID(); PopID();
Button("Click"); // Label = "Click", ID = hash of (..., "Click") if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag) { Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") TreePop(); }
When working with trees, ID are used to preserve the open/close state of each tree node. Depending on your use cases you may want to use strings, indices or pointers as ID.
Short explanation:
ImGui::Image(),
ImGui::ImageButton()or lower-level
ImDrawList::AddImage()to emit draw calls that will use your own textures.
Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward.
Long explanation:
OpenGL: - ImTextureID = GLuint - See ImGui_ImplOpenGL3_RenderDrawData() function in imgui_impl_opengl3.cpp
DirectX9: - ImTextureID = LPDIRECT3DTEXTURE9 - See ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp
DirectX11: - ImTextureID = ID3D11ShaderResourceView* - See ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp
DirectX12: - ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE - See ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp
For example, in the OpenGL example binding we store raw OpenGL texture identifier (GLuint) inside ImTextureID. Whereas in the DirectX11 example binding we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure tying together both the texture and information about its format and how to read it.
User code may do:
// Cast our texture type to ImTextureID / void* MyTexture* texture = g_CoffeeTableTexture; ImGui::Image((void*)texture, ImVec2(texture->Width, texture->Height));
The renderer function called after ImGui::Render() will receive that same value that the user code passed:
// Cast ImTextureID / void* stored in the draw command as our texture type MyTexture* texture = (MyTexture*)pcmd->TextureId; MyEngineBindTexture2D(texture);
Once you understand this design you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui. This is by design and is actually a good thing, because it means your code has full control over your data types and how you display them. If you want to display an image file (e.g. PNG file) into the screen, please refer to documentation and tutorials for the graphics API you are using.
Refer to Image Loading and Displaying Examples on the Wiki to find simplified examples for loading textures with OpenGL, DirectX9 and DirectX11.
C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTextureID / void*, and vice-versa. Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTextureID / void*. Examples:
GLuint my_tex = XXX; void* my_void_ptr; my_void_ptr = (void*)(intptr_t)my_tex; // cast a GLuint into a void* (we don't take its address! we literally store the value inside the pointer) my_tex = (GLuint)(intptr_t)my_void_ptr; // cast a void* into a GLuint ID3D11ShaderResourceView* my_dx11_srv = XXX; void* my_void_ptr; my_void_ptr = (void*)my_dx11_srv; // cast a ID3D11ShaderResourceView* into an opaque void* my_dx11_srv = (ID3D11ShaderResourceView*)my_void_ptr; // cast a void* into a ID3D11ShaderResourceView*
Finally, you may call
ImGui::ShowMetricsWindow() to explore/visualize/understand how the ImDrawList are generated.
You can edit imconfig.h and setup the
IM_VEC2_CLASS_EXTRA/
IM_VEC4_CLASS_EXTRA macros to add implicit type conversions. This way you'll be able to use your own types everywhere, e.g. passing
MyVector2 or
glm::vec2 to ImGui functions instead of
ImVec2.
std::vectoror any other data structure: the
BeginCombo()/EndCombo()API lets you iterate and submit items yourself, so does the
ListBoxHeader()/ListBoxFooter()API. Prefer using them over the old and awkward
Combo()/ListBox()api.
std::stringon applications with large amount of UI may incur unsatisfactory performances. Modern implementations of
std::stringoften include small-string optimization (which is often a local buffer) but those are not configurable and not the same across implementations.
ImDrawListapi to render shapes within a window.
ImGui::Begin("My shapes"); ImDrawList* draw_list = ImGui::GetWindowDrawList(); // Get the current ImGui cursor position ImVec2 p = ImGui::GetCursorScreenPos(); // Draw a red circle draw_list->AddCircleFilled(ImVec2(p.x + 50, p.y + 50), 30.0f, IM_COL32(255, 0, 0, 255), 16); // Draw a 3 pixel thick yellow line draw_list->AddLine(ImVec2(p.x, p.y), ImVec2(p.x + 100.0f, p.y + 100.0f), IM_COL32(255, 255, 0, 255), 3.0f); // Advance the ImGui cursor to claim space in the window (otherwise the window will appears small and needs to be resized) ImGui::Dummy(ImVec2(200, 200)); ImGui::End();
ShowExampleAppCustomRendering()in
imgui_demo.cppfrom more examples.
IM_COL32(255,255,255,255)to generate them at compile time, or use
ImGui::GetColorU32(IM_COL32(255,255,255,255))or
ImGui::GetColorU32(ImVec4(1.0f,1.0f,1.0f,1.0f))to generate a color that is multiplied by the current value of
style.Alpha.
IM_VEC2_CLASS_EXTRAin
imconfig.hto bind your own math types, you can use your own math types and their natural operators instead of ImVec2. ImVec2 by default doesn't export any math operators in the public API. You may use
#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui_internal.h"to use the internally defined math operators, but instead prefer using your own math library and set it up in
imconfig.h.
ImGui::GetBackgroundDrawList()or
ImGui::GetForegroundDrawList()to access draw lists which will be displayed behind and over every other dear imgui windows (one bg/fg drawlist per viewport). This is very convenient if you need to quickly display something on the screen that is not associated to a dear imgui window.
ImGuiWindowFlags_NoDecorationflag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse). Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
ImGui::GetDrawListSharedData(), or create your own instancing ImDrawListSharedData, and then call your renderer function with your own ImDrawList or ImDrawData data.
The short answer is: obtain the desired DPI scale, load a suitable font resized with that scale (always round down font size to nearest integer), and scale your Style structure accordingly using
style.ScaleAllSizes().
Your application may want to detect DPI change and reload the font and reset style being frames.
Your ui code should avoid using hardcoded constants for size and positioning. Prefer to express values as multiple of reference values such as
ImGui::GetFontSize() or
ImGui::GetFrameHeight(). So e.g. instead of seeing a hardcoded height of 500 for a given item/window, you may want to use
30*ImGui::GetFontSize() instead.
Down the line Dear ImGui will provide a variety of standardized reference values to facilitate using this.
Applications in the
examples/ folder are not DPI aware partly because they are unable to load a custom font from the file-system (may change that in the future).
The reason DPI is not auto-magically solved in stock examples is that we don't yet have a satisfying solution for the “multi-dpi” problem (using the
docking branch: when multiple viewport windows are over multiple monitors using different DPI scale). The current way to handle this on the application side is:
platform_io.Monitors[]before
NewFrame()).
platform_io.OnChangedViewport()to detect when a
Begin()call makes a Dear ImGui window change monitor (and therefore DPI).
This approach is relatively easy and functional but come with two issues:
Begin()without knowing on which monitor it’ll land.
Begin()call crossing monitor boundaries. You may need to do some custom scaling mumbo-jumbo if you want your
OnChangedViewport()handler to preserve style overrides.
Please note that if you are not using multi-viewports with multi-monitors using different DPI scale, you can ignore all of this and use the simpler technique recommended at the top.
Use the font atlas to load the TTF/OTF file you want:
ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear imgui's source code.
(Tip: monospace fonts are convenient because they allow to facilitate horizontal alignment directly at the string level.)
(Read the docs/FONTS.md file for more details about font loading.)
New programmers: remember that in C/C++ and most programming languages if you want to use a backslash \ within a string literal, you need to write it double backslash “\”:
io.Fonts->AddFontFromFileTTF("MyFolder\MyFont.ttf", size); // WRONG (you are escaping the M here!) io.Fonts->AddFontFromFileTTF("MyFolder\\MyFont.ttf", size; // CORRECT io.Fonts->AddFontFromFileTTF("MyFolder/MyFont.ttf", size); // ALSO CORRECT
The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your strings. You may want to see
ImFontConfig::GlyphMinAdvanceX to make your icon look monospace to facilitate alignment. (Read the docs/FONTS.md file for more details about icons font loading.) With some extra effort, you may use colorful icon by registering custom rectangle space inside the font atlas, and copying your own graphics data into it. See docs/FONTS.md about using the AddCustomRectFontGlyph API.
Use the font atlas to pack them into a single texture: (Read the docs/FONTS.md file and the code in ImFontAtlas for more details.)
ImGuiIO& io = ImGui::GetIO(); ImFont* font0 = io.Fonts->AddFontDefault(); ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() // the first loaded font gets used by default // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime // Options ImFontConfig config; config.OversampleH = 2; config.OversampleV = 1; config.GlyphOffset.y -= 1.0f; // Move everything by 1 pixels up config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config); // Combine multiple fonts into one (e.g. for icon fonts) static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; ImFontConfig config; config.MergeMode = true; io.Fonts->AddFontDefault(); io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
When loading a font, pass custom Unicode ranges to specify the glyphs to load.
// Add default Japanese ranges io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need) ImVector<ImWchar> ranges; ImFontGlyphRangesBuilder builder; builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) builder.AddChar(0x7262); // Add a specific character builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) io.Fonts->AddFontFromFileTTF("myfontfile.ttf", 16.0f, NULL, ranges.Data);
All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 by using the u8“hello” syntax. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work! Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
Text input: it is up to your application to pass the right character code by calling
io.AddInputCharacter(). The applications in examples/ are doing that. Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode). You may also use MultiByteToWideChar() or ToUnicode() to retrieve Unicode codepoints from MultiByte characters or keyboard state. Windows: if your language is relying on an Input Method Editor (IME), you copy the HWND of your window to io.ImeWindowHandle in order for the default implementation of io.ImeSetInputScreenPosFn() to set your Microsoft IME position correctly.
You may take a look at:
Yes. People have written game editors,)..
Dear ImGui is built to be efficient and scalable toward the needs for AAA-quality applications running all day. The IMGUI paradigm offers different opportunities for optimization that the more typical RMGUI paradigm.
Somehow.. Dear ImGui is NOT designed to create user interface for games, although with ingenious use of the low-level API you can do it.
A reasonably skinned application may look like (screenshot from #2529)
Dear ImGui takes advantage of a few C++ languages features for convenience but nothing anywhere Boost insanity/quagmire. Dear ImGui does NOT require C++11 so it can be used with most old C++ compilers. Dear.
contact AT dearimgui.orgif you work in a place using Dear ImGui! We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts. This is among the most useful thing you can do for Dear ImGui. With increased funding we can hire more people working on this project. | https://skia.googlesource.com/external/github.com/ocornut/imgui/+/041ef01b33f5aa2e40fb466682eb9c5df0d8512d/docs/FAQ.md | CC-MAIN-2021-04 | refinedweb | 3,245 | 56.35 |
The QMimeSource class is an abstraction of objects which provide formatted data of a certain MIME type. More...
#include <qmime.h>
Inherited by QDragObject and QDropEvent.
List of all member functions.
Drag-and-drop and clipboard use this abstraction.
See also IANA list of MIME media types, Drag And Drop Classes, Input/Output and Networking, and Miscellaneous Classes.
See also serialNumber().
Returns the encoded data of this object in the specified MIME format.
Subclasses must reimplement this function.
Reimplemented in QStoredDrag, QDropEvent, and QIconDrag.
Returns the i-th supported MIME format, or 0.
Example: fileiconview/qfileiconview.cpp..
Returns the mime source's globally unique serial number.
This file is part of the Qt toolkit. Copyright © 1995-2003 Trolltech. All Rights Reserved. | http://doc.trolltech.com/3.2/qmimesource.html | crawl-002 | refinedweb | 121 | 54.9 |
ctermid (3) - Linux Man Pages
ctermid: get controlling terminal name
NAME
ctermid - get controlling terminal name
SYNOPSIS
#include <stdio.h> char *ctermid(char *s);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
ctermid(): _POSIX_C.
ATTRIBUTESFor an explanation of the terms used in this section, see attributes(7).
CONFORMING TOPOSIX.1-2001, POSIX.1-2008, Svr4.
BUGSThe returned pathname may not uniquely identify the controlling terminal; it may, for example, be /dev/tty.
It is not assured that the program can open the terminal.
COLOPHONThis page is part of release 5.05 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. | https://www.systutorials.com/docs/linux/man/docs/linux/man/3-ctermid/ | CC-MAIN-2020-45 | refinedweb | 118 | 57.87 |
Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!.
JavaFAQ Home » Java Notes by Fred Swartz
Following the optional package declaration, you can have import
statements, which allow you to specify classes that can be referenced without
qualifying them with their package.
Packages are directories / folders that contain the Java classes, and
are a way of grouping related classes together. For small programs it's common
to omit a package specification (Java creates what it calls a default
package in this case).
NetBeans 4.0 uses packages in several ways.
The package-path is a dot-separated series of nested packages, eg,
java.awt or java.awt.event. You can import (make visible) either a
single class or all classes in package with the "*" wildcard character.
Suggestion: Use only the first wildcard case below. It is by far the most
common usage.
import package-path.*; // Makes all classes in package visible.
import package-path.class; // Makes only class visible.
import static package-path.*; // Makes all static variables in all classes in package visible.
import static package-path.class; // Makes all static variables in class visible.
The JOptionPane class is in the swing package, which is located
in the javax package.
import javax.swing.*; // Make all classes visible altho only one is used.
class ImportTest {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hi");
System.exit(0);
}
}
There are 166 packages containing 3279 classes and interfaces in Java 5.
However, there are only a few packages that are used in most programming. GUI
programs often use the first three imports.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.text.*;
import java.util.regex.*;
import javax.swing.JOptionPane; // Make a single class visible.
class ImportTest {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hi");
System.exit(0);
}
}
There is no need to use import when names are fully qualified. You
will see some programs in this style, but it isn't as common because it makes
source programs more congested and harder to read.
class ImportTest {
public static void main(String[] args) {
javax.swing.JOptionPane.showMessageDialog(null, "Hi");
System.exit(0);
}
}
A: No, import only tells the compiler where to look for symbols.
A: No. The search for names is very efficient so there is no effective
difference.
A: This shows good intentions, but ...
A: The wildcard "*" only makes the classes in this package visible, not
any of the subpackages.
A: All classes in the java.lang package are visible without an
import.
A: No. Group them for readability. it!
RSS feed Java FAQ News | http://www.javafaq.nu/java-article890.html | CC-MAIN-2016-18 | refinedweb | 459 | 61.22 |
#include <OMX_Video.h>
Data structure used to define a video path. The number of Video paths for input and output will vary by type of the Video video path. If additional vendor specific data is required, it should be transmitted to the component using the CustomCommand function. Compliant components will prepopulate this structure with optimal values during the GetDefaultInitParams command.
STRUCT MEMBERS: cMIMEType : MIME type of data for the port pNativeRender : Platform specific reference for a display if a sync, otherwise this field is 0 nFrameWidth : Width of frame to be used on channel if uncompressed format is used. Use 0 for unknown, don't care or variable nFrameHeight : Height of frame to be used on channel nBitrate : Bit rate of frame to be used on channel if compressed format is used. Use 0 for unknown, don't care or variable xFramerate : Frame rate to be used on channel if uncompressed format is used. Use 0 for unknown, don't care or variable. Units are Q16 frames per second. bFlagErrorConcealment : Turns on error concealment if it is supported by the OMX component eCompressionFormat : Compression format used in this instance of the component. When OMX_VIDEO_CodingUnused is specified, eColorFormat is used eColorFormat : Decompressed format used by this component pNativeWindow : Platform specific reference for a window object if a display sink , otherwise this field is 0x0. | http://limoa.sourceforge.net/docs/1.0/structOMX__VIDEO__PORTDEFINITIONTYPE.html | CC-MAIN-2017-17 | refinedweb | 223 | 51.28 |
Hi,We've got a very simple CF interface on our eval board, sitting onlocalbus with a couple of gpios for control. mem and i/o port rangesare mapped to two mmio ranges, i.e. 0xf0000000 and 0xf1000000 in our case.I've got a pcmcia driver for the slot to handle all the probing, etc. It ioremaps boththe mem and io ranges, and provides that with the registered device: cf->mem_base = ioremap(mem->start, mem->end - mem->start); cf->io_base = ioremap(io->start, io->end - io->start);[...] /* pcmcia layer only remaps "real" memory not iospace */ cf->socket.io_offset = (unsigned long)cf->io_base; /* reserve chip-select regions */ if (!request_mem_region(mem->start, mem->end + 1 - mem->start,[...] if (!request_mem_region(io->start, io->end + 1 - io->start, driver_name))[...] cf->socket.dev.parent = &ofdev->dev; cf->socket.ops = &electra_cf_ops; cf->socket.resource_ops = &pccard_static_ops; cf->socket.features = SS_CAP_PCCARD | SS_CAP_STATIC_MAP | SS_CAP_MEM_ALIGN;[...](I'll post the full driver separately, but wanted to bring this up first).Bottom line is that io_offset points to the ioremap()ed memory, i.e a64-bit kernel address.The problems show up further up the stack, in this case in thepata_pcmcia driver, where pcmcia_request_io() is used to handle theaddress allocation. That in turn calls alloc_io_space(), which takes anioaddr_t * as argument and does math on it.ioaddr_t is 32-bit, causing obvious problems since io_offset is64-bit. There's a compatible kio_addr_t available, but I'm guessing it'salready not used because of ABI requiremenets given the big warning atthe definition of ioaddr_t.Since ppc64 never has had pcmcia before (We're the first platform withit), changing the type under ifdef like mips/arm shouldn't be a problem,at least it won't lead to regressions -- there's no previous user appsto regress.However, that's not enough in this case: Next thing that will fail isioport_map() in ppc-specific code, called from devm_ioport_map(). Itcurrently assumes to be passed the bus-local port number and addingit to the ioremap base of the (normally only) bus with I/O ports,i.e. ISA/LPC. Since we already use that for other devices (UARTS, etc),we now have more than one base register.I see two ways to solve this:1. Create infrastructure to track the various io-port ranges, registerthem and let the infrastructure take care of the ioremap, pick the rightioport_map(), etc. I.e. create virtual io port ranges.2. Make ioport_map() detect already mapped arguments (i.e.:+ if (port >= IMALLOC_BASE && (port+len) < IMALLOC_END)+ return (void __iomem *)port;(1) would be appealing if it was the only change needed, and if thatmeant that I didn't have to change ioaddr_t. It doesn't though, sincethe pcmcia code still stores the ioport_map():ed value in an ioaddr_t,so it really just adds complexity without that much benefit.I'm tempted to go with (2) + type change but if someone has a thirdoption I'm all ears.-Olof-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2007/5/9/528 | CC-MAIN-2013-20 | refinedweb | 513 | 58.48 |
I have two domains (example names used):
domain1.com.au - unix samba domain - 202.20.75.x ip range
domain2.com.au - Win2003 AD domain - 10.1.2.x ip range
We're doing a migration from domain1 to domain2. I want to copy the user's profile usin File And Settings Transfer wizard then change the pc from domain1 to domain2. I've done this a few times and some machines were done over a year ago and work fine.
However the IP address is still 202.20.75.x on the pc's as they can talk to each other and there's no communication issues. domain1's DNS server talks to domain2's so the only issue is when you need to connect to a pc that's on domain2 you need to add .domain2.com.au at the end of the hostname
Now one of our network admins says the pc's need to be using the 10.1.2.x range as you can't have pc's from one domain in another domain's namespace...
It this required? I don't think i've enough free ports on our switches to change them all over and I was hoping to get them all done this weekend. Eventually a new AD domain will be created with a whole new IP addressing scheme so this will probably only continue for about 6 months.
Do I have to cancel my whole changeover process or can it go ahead and he's just worrying?
7 Replies
Jan 7, 2010 at 4:45 UTC
IP Address has no effect on AD at all, just so long as the PC's can communicate with the server. You can most definitely have two domains on a single IP range (this is different then namespace).
Jan 8, 2010 at 4:53 UTC
There is no problem sharing IP's across domains.
Could the network admin be trying to set up DHCP? I think that will complain if there's another DHCP server already serving the same range. You would need to allocate half the addresses to each (or whatever proportion suits)
You can't however control which DHCP server will serve which PC, so if that's required you would need to look at VLANS
Jan 8, 2010 at 6:22 UTC
You could have DHCP set up on 1 server. On that server create 2 DHCP Scopes then use reservations to allocate the correct scope to the correct pc.
I have not done this before but just google a couple of things and it appears this is possible.
Another thing to remember is you can bind more than one ip address to a single nic by going into the NIC properties, TCP IP Properties, advanced and add another IP there. This has helped me in a few migrations in the past.
Jan 8, 2010 at 8:19 UTC
Whilst I haven't done any migrations I can tell you that half our domain is on 192.168.111.x and the other is on 10.x.x.x (not sure why some artard set it up that way but nevermind)
No offence but the guy complaining is prolly just being anal about the numbers :P
Jan 8, 2010 at 12:02 UTC
Now one of our network admins says the pc's need to be using the 10.1.2.x range as you can't have pc's from one domain in another domain's namespace.
Personally I think the other guy is blowing smoke. IP addresses have nothing to do with namespace. Even reverse DNS is just a translation and doesn’t care if 2 IPs on the same subnet are from 2 different AD domains.
Jan 10, 2010 at 8:15 UTC
Just to give some more feedback into this. After all the comments on here, and thanks to all those who said something, I went and had a further discussion about this..
He tried giving me various other solutions but in the end the route I went down was:
Doing the migration from one domain to the other and doing the profile migrations
Get everyone logging in with their new usernames and making sure all panic attacks are handled by those employees that could be considered "sensative"
Migrating the pc's over to the other range as much as possible with the remaining ones using the other IP range until the new IP ranges are developed.
The issue with doing it this way was we had a lot of casuals who moved around a lot and I wanted to avoid givign them another username and password and them having to log in to one pc with one and another pc with the other. Better to just change over to one I thought.
Changeover of pc's to domain is done now, will now work on migration to other IP range... that in itself is a pain as the comms panels are a mass of cables with many ports patched in when they don't need to be. It'll take time but hopefully at the end I'll end up with a free more free ports on the switches...
Jan 11, 2010 at 3:30 UTC.
I don't think this is an actual problem.
To expand on what I said earlier, our main office has a Windows SBS 2003 server running the entire domain. It gives out DHCP addresses for 192.168.111.x and looks after its DNS.
Our second office has a regular Windows Server 2003 which is a secondary domain controller for the same domain as our main office, gives out DHCP addresses for 10.x.x.x and looks after its DNS. The two offices share a domain across a VPN.
I do not recall having to make one DNS server authoritative whilst setting it all up (but SBS may have done that on its own).
So to sum up: one domain, two IP address schemes, one DNS server for each scheme, no fiddling around done on either DNS server and no problems either *touch wood* | https://community.spiceworks.com/topic/85503-change-domain-but-keep-ip-from-old-domain | CC-MAIN-2017-22 | refinedweb | 1,024 | 77.87 |
When we first started to add catalogs capability to Cocoon
as proof-of-concept we used the Abortext code (i did not
know of the existence of any other code). Dims then added
the actual capability using the Sun package. I gather that
the Sun code is the evolution of the Arbortext package
(both are written by Norm Walsh). So there are many code
improvements and that would be the base for the future.
If the license of the new package is not suitable, then it may
be appropriate to approach Norm about changing it. I am
sure that the intent is to get entity resolution capability into
as wide usage as possible.
See documentation URLs below.
regards, David Crossley
Jeff Turner wrote:
> Peter Donald wrote:
> > Hi,
> >
> > I just had a look at Cocoons Catalog manager code and noticed it used
Suns
> > code. Considering the original code is in the public domain and Suns is
under
> > a less than desirable license I was wondering what advantage Suns code
had?
> > Would there be any advantage of using arbortexts PDed code directly? I
was
> > thinking of adding it into Excalibur CVS and integrating it with some of
our
> > stuff. Anyone care to enlighten me why this may be a bad idea? ;)
>
> I found a few minor bugs with the arbortext code (eg debug flags not getting
> propagated), and one major bug (DOCTYPE doesn't work), which I mailed Norm
> Walsh about. He said DOCTYPE would never work under XML due to namespace
> issues, and mentioned that the Sun version had been "substantially
modified",
> whatever that means.
>
> Anyway, I think it would be excellent to get *some* version of that catalog
> code in under Jakarta, because it's darn useful stuff, and it doesn't have a
> home. People all over the world are poking around in that code, discovering
the
> same bugs and limitations, and fixing them individually.
>
> I've put an Ant-buildable version of the arbortext code at:
>
>
>
> --Jeff
>
> Btw, for those who are wondering what the fuss is about, read:
>
Also read the Cocoon 2 xdocs/catalog.xml and its associated
demonstration sample. The Sun resolver code also includes
an evolved version of that Arbortext Think Tank article.
> > --
> > Cheers,
> >
> > Pete
---------------------------------------------------------------------
To unsubscribe, e-mail: avalon-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: avalon-dev-help@jakarta.apache.org | http://mail-archives.apache.org/mod_mbox/avalon-dev/200109.mbox/%3C01092409340901.01052@localhost.localdomain%3E | CC-MAIN-2018-05 | refinedweb | 392 | 61.97 |
cygwin_conv_path_t what;
const void * from;
void * to;
size_t size;
Use this function to convert POSIX paths in
from to Win32 paths in
to
or, vice versa, Win32 paths in
from to POSIX paths
in
to.
what
defines the direction of this conversion and can be any of the below
values.
CCP_POSIX_TO_WIN_A /* from is char *posix, to is char *win32 */ CCP_POSIX_TO_WIN_W, /* from is char *posix, to is wchar_t *win32 */ CCP_WIN_A_TO_POSIX, /* from is char *win32, to is char *posix */ CCP_WIN_W_TO_POSIX, /* from is wchar_t *win32, to is char *posix */
You can additionally or the following values to
what, to define whether you want the resulting
path in
to to be absolute or if you want to keep
relative paths in relative notation. Creating absolute paths is the
default.
CCP_ABSOLUTE = 0, /* Request absolute path (default). */ CCP_RELATIVE = 0x100 /* Request to keep path relative. */
size is the size of the buffer pointed to
by
to in bytes. If
size
is 0,
cygwin_conv_path just returns the required
buffer size in bytes. Otherwise, it returns 0 on success, or -1 on
error and errno is set to one of the below values.
EINVAL what has an invalid value or from is NULL. EFAULT from or to point into nirvana. ENAMETOOLONG the resulting path is longer than 32K, or, in case of what == CCP_POSIX_TO_WIN_A, longer than MAX_PATH. ENOSPC size is less than required for the conversion.
Example 2.1. Example use of cygwin_conv_path
#include <sys/cygwin.h> /* Conversion from incoming Win32 path given as wchar_t *win32 to POSIX path. If incoming path is a relative path, stick to it. First ask how big the output buffer has to be and allocate space dynamically. */ ssize_t size; char *posix; size = cygwin_conv_path (CCP_WIN_W_TO_POSIX | CCP_RELATIVE, win32, NULL, 0); if (size < 0) perror ("cygwin_conv_path"); else { posix = (char *) malloc (size); if (cygwin_conv_path (CCP_WIN_W_TO_POSIX | CCP_RELATIVE, win32, posix, size)) perror ("cygwin_conv_path"); } | http://www.sourceware.org/cygwin/cygwin-api/func-cygwin-conv-path.html | CC-MAIN-2014-10 | refinedweb | 304 | 62.98 |
Quick guide to using QHTM
I'll using that you are using Visual C++. The basic method is the same for pretty much any programming language.
These are the basic steps:
- Include the QHTM header file
- Link the library to your application
- Initialise the library
- Add the control to your dialog
- Give QHTM some HTML
Include the QHTM header
This is the easiest bit:
#include "QHTM.h"
Link the library
Note: With the latest build you don't need to do this as QHTM will emit a command to the link to add QHTM.LIB into your project providing you have set an addition library path.
All we need to do is tell Visual C++ where to find the QHTM functions. We bring up the project settings (ALT+F7), choose the correct project, select the appropriate project, choose All Configurations and select the Link tab. We then add in the appropriate library name. For the Free version of QHTM the library name is QHTMLight.lib, for the paid for version it's QHTM.lib.
Initialise the library
We need to add a single call to
QHTM_Initialize somewhere in our application startup. Traditionally this would be in
WinMain, or in MFC this would be in the
InitInstance member of your
CWinApp desrive class.
// Plain Win32 API would look like this QHTM_Initialize( hInstance ); // MFC might look like this QHTM_Initialize( AfxGetInstanceHandle() )
Add the control to your dialog
Once the library is initialised we are free to use it anywhere a normal Win32 window can be used. This includes adding it to a dialog box or using CreateWindow APIs to create it. For this example we'll add it to a dialog.
We first add a custom control to the dialog. Select the custom control icon from the control palette, see the image on the right.
We set the caption1 to be the HTML we want displayed and set the class2 to be the QHTM window class, which is
QHTM_Window_Class_001.
Give QHTM some HTML
Because we have added the control to a dialog and at the same time set the caption to be our HTML we don't need to write any more code. So, in one single line of code (QHTM_Initialize) we have added a HTML control to our dialog.
There is one 'gotcha' though. Resources are restricted to the amount of text that a caption can have. Whilst this is mostly okay for plain text HTML places much higher demands. Sometimes the text you want in the control is too big and needs to be sent to the control manually.
Luckily this is easy to achieve. QHTM will use whatever text you send it. This means you can use the
SetDlgItemText or
SetWindowText API functions to send QHTM some HTML.
SetDlgItemText( hwndDlg, IDC_QHTM, "Some <b>HTML in bold</b>" ); | https://gipsysoft.com/qhtm/doc/howto_simple.shtml | CC-MAIN-2022-40 | refinedweb | 467 | 71.85 |
It looks like you're new here. If you want to get involved, click one of these buttons!
void test();
and a file named "test.cpp" which contains the
following:
#include "test.h"
#include
#include
void test()
{
printf("This is a test");
}
I can simply compile test.cpp, thus creating an obj file
in a particular directory, and then have yet another
file, "testi.cpp" including only the test.h file and
still be able to call the function test(), as long as
it is linked to the obj file and outputs to the same
directory, can't I? Unfortunately, I get the linker
error "Undefined symbol test() in module testi.cpp."
Am I doing something wrong? Thanks for your help.
mat
It is also often helpful to #include the header in the source for the function itself so that the prototype and the definition don't get out of synch. So put a #include at the top of your source file with the call to the routine as well as the top of the source file with the called routine.
If you're using Borland with the GUI project environment, you shouldn't have to link in the obj separately. Just include both .cpp files in the project. It will do the appropriate linking. | http://programmersheaven.com/discussion/1497/linking-obj-files | CC-MAIN-2017-43 | refinedweb | 215 | 76.32 |
score:3
You can return your index page and browserHistory of React will handle anything else.
Route::pattern('path', '[a-zA-Z0-9-/]+'); Route::any( '{path}', function( $page ){ return view('index'); });
score:10
EDIT in Feb 2022: I posted this solution when the latest Laravel was V5 and react-router was V4. There could be a better solution now, because both Laravel and react-router evolved a lot since then
==================================================
How about using
<HashRouter>?
E.g.
import React from 'react'; import { HashRouter, Route, Link }from 'react-router-dom'; import Profile from './Profile'; export default class App extends React.Component { constructor(props) { super(props); } render() { return ( <HashRouter> <Link to="/profile" replace>Profile</Link> <Route path="/profile" component={Profile}/> </HashRouter> ); } }
In Laravel's router...
Route::get('/', function(){ return view('index'); //This view is supposed to have the react app above });
With
HashRouter, your client side routing is done with
# (Fragment Identifier), which is not read by Laravel's routing (i.e. server side routing)
Upon arriving this page, the URL is
/.
Clicking the link will make the URL
/#/profile and the component will appear.
After that, if you refresh the page, you wont' see the
Route not exist error. This is because, from Laravel's perspective, the URL is still
/. (The component
Profile still remains there.)
Hope my explanation is clear.
score:14
This seems works for me
For any react routes
Route::get('{reactRoutes}', function () { return view('welcome'); // your start view })->where('reactRoutes', '^((?!api).)*$'); // except 'api' word
For laravel routes
Route::get('api/whatever/1', function() { return [ 'one' => 'two', 'first' => 'second' ]; }); Route::get('api/something/2', function() { return [ 'hello' => 'good bye', 'dog' => 'cat' ]; });
score:18
Based on Jake Taylor answer (which is correct, by the way) : it has a little mistake, is missing a quotation mark after
'/{path?}' , just the last one.
Also, if you don't need to use a Controller and just redirect back to your view, you can use it like this:
Route::get( '/{path?}', function(){ return view( 'view' ); } )->where('path', '.*');
Note: Just make sure to add this Route at the end of all of your routes in the routes file ( web.php for Laravel 5.4 ), so every existing valid route you have may be catched before reaching this last one.
score:45
Create a route that maps everything to one controller, like so:
Route::get('/{path?}', [ 'uses' => 'ReactController@show', 'as' => 'react', 'where' => ['path' => '.*'] ]);
Then in your controller, just show the HTML page that contains the react root document:
class ReactController extends Controller { public function show () { return view('react'); } }
Then do everything as normal with react router. Seems to work well for me.
Update for Laravel 5.5 If your controller only returns a view (like in the example above), you can replace all of the above code with this in your routes file:
Route::view('/{path?}', 'path.to.view') ->where('path', '.*') ->name('react'); Laravel routes alongside with React SPA single route in Laravel 8
- how to use params in meteor mongo query with react router
- How to use Typescript with React Router and match
- How to use React Router <Link > with an id from antd table column
- How to use Laravel routes over react router
- How to use matchPatch with dynamic links on React Router v6
- How to use react router with Algolia search hits?
- How to use React Routes with laravel and Admin Lte?
- to use laravel echo with react js?
-
More Query from same tag
- All child elements inheriting onclick event from parent div on React
- How to access pure js value outside of a react class
- cannot use import statement outside a module with Next.js
- How to Show two components for a url in react js
- Display result contained in let declaration Typescript
- TypeError: Cannot read property 'handleClick' of undefined
- Redux + Typescript + typesafe-actions:
- How to set data in react typescript array of object from axios response
- BrowserRouter redirect not rendering component
- How to Validate multiple forms in the parent?
- Delay suggestion time in MUI Autocomplete
- Why handlesubmit is not working on this react-hook-form implementation?
- Antd clear form after submit in reactjs
- Redux form with compose not working throwing error
- Set a default ref value on React?
- How to use this.props in React Styled Components
- Add a loader while an if else statement is being evaluated
- React - filtering items from an array in any order
- How to conditionally fetch user data based on logged-in state with SWR?
- How can I pass props from a Parent to Child with this.props.children?
- How can I check a click on a child component using jest, if the callback isn't passed as prop?
- Redux: Accessing current state - best practice?
- AWS AppSync, how to send an email after a mutation?
- Grunt browserify transform ReactJS then bundle
- Best practice for handling intervals for multiple clients on socket server
- React map object and embedded object from JSON and convert to single array for state
- React.js generate dynamic routes for the same component with different data
- React MapBox GL geocoder input outside the map is that possible?
- Operating response status code in react application
- How to display the text with "anchor tag", coming from json response in react? | https://www.appsloveworld.com/reactjs/100/5/how-to-use-react-router-with-laravel | CC-MAIN-2022-40 | refinedweb | 865 | 61.16 |
Spring Framework 3.1.0 M2 Released
PLUS, IcedTea-Web 1.1, and Seam Reports 3.0.0.Alpha1 released.
Spring Framework 3.1.0 M2
The second milestone of Spring 3.1.0 is out now. This release adds support for injection against non-standard JavaBeans setters, Servlet 3 code-based configuration of Servlet container and Servlet 3 MultipartResolver. Validation For @RequestBody Method Arguments has been added, and bean references in mvc:interceptor namespace elements is now allowed. The cache abstraction has been revised to focus on minimal atomic access operations. More information is available at the Chanelog, and New Features and Enhancements in Spring 3.1.
IcedTea-Web 1.1 Released
Version 1.1 of the IcedTea-Web project has been released. IcedTea-Web provides a web browser plugin for running applets written in Java and an implementation of Java Web Start, originally based on NetX. Version 1.1 replaces binary launchers with shell scripts, and can be installed to a FHS-compliant location. Proxy Auto Config files are now usable and IcedTea-Web 1.1 supports applications using jnlp.versionEnabled and jnlp.packEnabled. There is also a list of bug fixes for issues including Mercurial revision detection, and Applets and JNLP apps, which previously used SSL/TLS functioning incorrectly.
Seam Reports 3.0.0.Alpha1 with JasperReports and Penatho Support
Seam Reports 3.0.0.Alpha1 has been announced with initial support for the JasperReports Java reporting library, and the Pentaho Reporting Engine embeddable Java reporting library.
Seam Reports is portable between Java EE 6 and Servlet environments enhanced with CDI, and can also be used with CDI in J2SE. It abstracts the usage of commonly used reporting engine frameworks, and acts as a bridge between CDI and supported engine frameworks. Seam Reports can be downloaded now from github.
Proposed JCP Changes in JCP.next JSR 1
The list of proposed changes in JCP.next JSR 1, the first of the two JSRs put forward to update the Java Community Process, has been published online. These changes include the issue of transparency, which was recently raised in the Java SE 7 Public Review Ballot.
Security Fixes for IcedTea
The IcedTea project has announced three new security releases: versions 1.8.8, 1.9.8 and 1.10.2. These updates address vulnerabilities in deserialisation and SAAJ, and a heap overflow vulnerability in FileDialog.show(). The releases also fix a crash that could occur during Java 2D transforming an image with scale close to zero. For lists of the fixes included in each release, please see the release announcement.
Apache Nutch 1.3 With Lucene and SolrJ Upgrades
Version 1.3 of the Apache Nutch open source web-search software, has been released. With this release, the Nutch team have updated to SolrJ version 3.1, Lucene to 2.9.1, Xerces to 2.91 and Tika to version 0.9. NutchConfiguration and the list of suffix domains have been improved. | https://jaxenter.com/spring-framework-3-1-0-m2-released-103319.html | CC-MAIN-2016-22 | refinedweb | 493 | 60.51 |
I'm a little lost here. I'm trying to read from a file named source.txt located in the same area as my program. If i could figure this out i could continue with the rest of the program. I'm just getting a blank screen so i know i'm way off heres the code if anyone could push me in the right direction it would help greatly thanks
#include <iostream> #include <iomanip> #include <cstdlib> #include <fstream> #include <istream> using namespace std; float readStoreCount(float numbers[]); float printNumbers(float numbers[]); int main () { float numbers[100]; numbers [100] = readStoreCount(numbers); printNumbers(numbers); system ("pause"); return 0; } //main float readStoreCount(float numbers[]) { int i = 0; ifstream source; source.open ("source.txt"); if (!source) { cerr << "\aError 100 opening source.txt" << endl; exit (100);//opening failure test } for (i = 0; i < 100; i++) cin >> numbers [i]; cout << "numbers are going in" << endl; source.close (); if (source.fail()) { cerr << "\aERROR 102 closing source.txt" << endl; exit (102);//closing failure test } } float printNumbers(float numbers[]) { int i; float numbersIn[100]; for (i = 100; i > numbers [i]; i--) cout << numbers [i]; } | https://www.daniweb.com/programming/software-development/threads/14973/reading-from-file-into-array | CC-MAIN-2018-43 | refinedweb | 186 | 71.65 |
Entity Framework Code First Migrations
So you've created your entities and had Entity Framework create your database for you. Now, you want to change your entities and of course also change the database schema. How do you go about doing that?
Can I Just Delete the Database?
You can, and I've done this lots of times. You know that Entity Framework can create the database for you if there is no database yet. So when you change your entities, you can delete the existing database, and when you run your application again, you would get a new database with a schema that corresponds to the updated entities.
While this works well during development, you can imagine that deleting and recreating the database is not very suitable for production!
Can I Update the Database Schema Manually?
Entity Framework uses a set of rules that determine the appropriate database schema that corresponds with your entities. If you know these rules, you would be able to manually update the database to mimic what Entity Framework would have done.
You can also imagine that this is not the best solution because just one mistake can cause errors. In addition, Entity Framework can already do this for you, so there's no need for you to do this manually.
Use Migrations
Today we will be using migrations to update the database schema. Specifically, we will be using Code First Migrations.
Here is a summary of the code first migration workflow:
- You create your classes and let Entity Framework (EF) create the database for you.
- You tell EF that you would like to use its Migrations feature.
- EF records the initial state of your classes.
- You update your classes. Changes warrant a database schema change.
- You tell EF about the current state of your classes. EF records this new state.
- You tell EF to update the database.
- Database schema update complete!
Let's see these steps in action.
1. You create your classes and let Entity Framework (EF) create the database for you.
Let's create a console application, import the Entity Framework package, create an entity, create a context, and then insert an entity.
Here is a sample User entity:
public class User { public int Id { get; set; } public string Name{ get; set; } }
Here is the context:
public class MyContext : DbContext { public DbSet<User> Users { get; set; } }
Here is Program.cs:
public class Program { static void Main() { try { using (var db = new MyContext()) { db.Users.Add(new User { Name = "Cowman" }); db.SaveChanges(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
Here is a snapshot of the Solution Explorer window which shows the classes:
When you run the program, the database gets created and a User gets inserted, as expected.
2. You tell EF that you would like to use its Migrations feature.
To do this, type Enable-Migrations into the Package Manager Console and press enter, like so:
Note: The Default project should be the project where your context class is in.
Note 2: If you have multiple contexts, you need to specify on which context you would like to enable Migrations, using the following command:
Enable-Migrations -ContextTypeName [FullyQualifiedNameOfYourContextClass]
3. EF records the initial state of your classes.
You may have noticed that after enabling migrations, a couple of new classes and a folder appeared in the project:
You can ignore the Configuration class for now. What's interesting is the "InitialCreate" class - it serves as a snapshot of the state of your classes the first time Migrations was enabled.
4. You update your classes. Changes warrant a database schema change.
Now add an Address field to the User entity:
public class User { public int Id { get; set; } public string Name{ get; set; } public string Address { get; set; } }
You will get an exception: "The model backing the 'MyContext' context has changed since the database was created. Consider using..." This is because there is a mismatch between the shape of your classes and the database schema. To move on, you need to do the next steps:
5. You tell EF about the current state of your classes. EF records this new state.
You can do this by executing the Add-Migration -Name [MigrationName] command in the Package Manager Console. [MigrationName] is an identifying name of this migration (eg AddAddressToUser):
Notice that another class was added to the Migrations folder:
6. You tell EF to update the database.
At this point, Entity Framework has information about the initial state of the system and the new, target state of the system. Entity Framework can use this information to update the database schema accordingly. You can trigger this update manually by using the Update-Database command, again in the Package Manager Console:
Once the command finishes, the database schema would have been updated. Now, the shape of your classes and the database schema are in sync again, and you will no longer get any exceptions when you try to run the application. | http://www.ojdevelops.com/2014/09/entity-framework-code-based-migrations.html | CC-MAIN-2020-05 | refinedweb | 825 | 64.2 |
Basic Usage: This document describes the basic usage of the pyecharts library.
Install pyecharts
Compatibility
pyecharts supports Python2.7+ and Ptyhon3.5+. If you are using Python 2.7, please declare the character encoding at the top of the code, otherwise there will be Chinese garbled problems.
#coding=utf-8 from __future__ import unicode_literals
pyecharts
pip install
$ pip install pyecharts
source code install
$ git clone $ cd pyecharts $ pip install -r requirements.txt $ python setup.py install
Map plugin
Since v0.3.2, in order to reduce the size of the project itself and maintain the lightweight operation of the pyecharts project, pyecharts will no longer have its own map js file. Developers who want to use the map must manually install the map plugin. Detailed reference Map Customization.
Quick start
Now, you are ready to make your first chart!
from pyecharts import Bar bar = Bar("My first bar chart", "For our fashion shop client") bar.add("Clothes", ["T-shirt", "Sweater", "Georgette", "Trousers", "High-heels", "Socks"], [5, 20, 36, 10, 75, 90]) # bar.print_echarts_options() # This line is only for printing configuration items, which is convenient for debugging. bar.render() # generate a local HTML file
add()main method,add the data and set up various options of the chart
print_echarts_config()print and output all options of the chart
render()creat a file named
render.htmlin the root directory defaultly, which supports path parameter and set the location the file save in, for instance render(r"e:\my_first_chart.html"), open file with your browser.
Note: Click the image download button on the right hand side of the chart. If you need more buttons, please insert
is_more_utils=True when calling add()
from pyecharts import Bar bar = Bar("My first bar chart", "For our fashion shop client") bar.add("Clothes", ["T-shirt", "Sweater", "Georgette", "Trousers", "High-heels", "Socks"], [5, 20, 36, 10, 75, 90], is_more_utils=True) bar.render()
Use theme
Since 0.5.2+, pyecharts has supported the replacement of the theme color. Here's an example of changing to 'dark':
from pyecharts import Bar bar = Bar("My first bar chart", "For our fashion shop client") bar.use_theme('dark') bar.add("Clothes", ["T-shirt", "Sweater", "Georgette", "Trousers", "High-heels", "Socks"], [5, 20, 36, 10, 75, 90]) bar.render()
pyecharts supports extra 5 body colors, Please move to the theme color for more configuration information.
Rendering as image using pyecharts-snapshot
To get png, pdf, gif files instead of
render.html, pyecharts-snapshot is required。What's more, node.js is also required and can be downloaded from.
- Install phantomjs
npm install -g phantomjs-prebuilt
- install pyecharts-snapshot
pip install pyecharts-snapshot
- Call
rendermethod
bar.render(path='snapshot.png')
The file suffix can be svg/jpeg/png/pdf/gif. Note that the svg file requires you to set
renderer='svg'in the chart's constructor.
For more details, please refer to pyecharts-snapshot
Chart drawing process
A chart class provides the following apis for building and rendering. Here are the generic steps to draw your own chart:
From v0.5.9, the methods involved above support method-chaining. For example:
from pyecharts import Bar CLOTHES = ["T-shirt", "Sweater", "Georgette", "Trousers", "High-heels", "Socks"] clothes_v1 = [5, 20, 36, 10, 75, 90] clothes_v2 = [10, 25, 8, 60, 20, 80] (Bar("My second bar chart") .add("H&M", CLOTHES, clothes_v1, is_stack=True) .add("Zara", CLOTHES, clothes_v2, is_stack=True) .render())
Render Charts Many Times
From v0.4.0+, pyecharts reconstructed the internal logic of rendering to improve efficiency. It is recommended to display multiple charts in the following ways.
You can call
chart.render many times to show some charts in a script.
from pyecharts import Bar, Line.render(path='bar.html')]) line.render(path='line.html')
In v0.4.0+, pyecharts refactors the internal logic and make render faster.The following code is recommended.
from pyecharts import Bar, Line from pyecharts.engine import create_default_environment]) env = create_default_environment() # Create a default configuration environment for rendering # create_default_environment(filet_ype) # file_type: 'html', 'svg', 'png', 'jpeg', 'gif' or 'pdf' env.render_chart_to_file(bar, path='bar.html') env.render_chart_to_file(line, path='line.html')
This example uses the only one engine object to render multiple charts.
Pandas & Numpy examples
In the context of Numpy and/or Pandas,
pdcast(pddata) and
npcast(npdata) methods, provided in 0.19.2 are no log required. Please see the advanced example in README.
Note: When using Pandas&Numpy, ensure that the integer type is int instead of numpy.int32
Of course you can use the cooler way, use Jupyter Notebook to show the chart. What matplotlib have,so do pyecharts
Note: From v0.1.9.2, the
render_notebook() method has been deprecated and is now more pythonic. It is ok to call the instance itself directly.
like this
and this
more Jupyter notebook examples, please refer to notebook-use-cases. You could download and run it on your notebook.
Use Jupyter Notebook to display charts, just call your own instance and be compatible with Python2 and Python3's Jupyter Notebook environment. All charts can be displayed normally, and the interactive experience is consistent with the browser. It is even no need PPT with this method to display report! !
Offline installation instructions for pyecharts
Please visit faq section for more details | https://pyecharts.readthedocs.io/projects/pyecharts-en/zh/latest/en-us/prepare/ | CC-MAIN-2022-40 | refinedweb | 868 | 59.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.