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 |
|---|---|---|---|---|---|
How to check or find the angular version in my project?
Dung Do Tien Nov 05 2020 290
I just study angular. I created a project by using the command
ng new my-first-app. Now I want to check the angular version of this project and where is stored it?
Have 1 answer(s) found.
- 0
You have some way to check your project version in Angular
1. Using
ng version
Open CMD and select the root folder containing your project and type
ng version. You can see the result as below:
_ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | | / ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | | /_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___| |___/ Angular CLI: 9.1.12 Node: 12.18.3 OS: win32 x64 Angular: 9.1.12 ... animations, cli, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... router Ivy Workspace: Yes Package Version ----------------------------------------------------------- @angular-devkit/architect 0.901.12 @angular-devkit/build-angular 0.901.12 @angular-devkit/build-optimizer 0.901.12 @angular-devkit/build-webpack 0.901.12 @angular-devkit/core 9.1.12 @angular-devkit/schematics 9.1.12 @ngtools/webpack 9.1.12 @schematics/angular 9.1.12 @schematics/update 0.901.12 rxjs 6.6.3 typescript 3.7.5 webpack 4.42.0
2. See the angular project version from package.json file.
At the root of your project, you will see the
package.jsonfile, open this file and find
@angular/cliand some other packages such as forms, common, animations....
"@angular/animations": "^9.1.1", "@angular/common": "^9.1.1", "@angular/compiler": "^9.1.1", "@angular/core": "^9.1.1", "@angular/forms": "^9.1.1", "@angular/cli": "^9.1.12"
3. Using code to log version of the project.
import { VERSION } from '@angular/core'; console.log(VERSION.full);Marry Christ Nov 08 2020
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others. | https://quizdeveloper.com/faq/how-to-check-or-find-the-angular-version-in-my-project-aid89 | CC-MAIN-2021-10 | refinedweb | 351 | 55.91 |
A threadlocalvariable isn't a thread, but a local variable of thread, and it may be named more easily.
When a variable is used to maintain a variable, the ds0 provides a separate copy of the variable for each thread using that variable, so each thread can change the
From a thread 's point of view, the target variable is the local variable of the thread, which is the meaning of"local"in the class name.
Threadlocal interface method
A class interface is simple, with only 4 methods, and we're going to know:
void set(Object value)
To set the value of the thread local variable for the current thread.
public Object get()
This method retur & the thread local variable corresponding to the current thread.
public void remove()
Deletes the value of the current thread local variable, and aims to reduce memory footprint, which is a new method for jdk 5.0. It's important to note that when the thread ends, the local variable that should be thread is automatically reclaimed, so explicitly calling the method to clear the local local variable isn't the necessary action, but it speeds up the memory recovery speed.
protected Object initialValue()
Returns the initial value of the local variable, which is a protected method, obviously designed to allow subclasses to override. This method is a delayed invocation method that executes when the thread 1 calls get ( ) or set ( object ), and executes only 1 times. The default implementation in the directly returns a null.
Note that in jdk5. 0, has already supported generics, and the class name of the class has been changed. Api methods are also adjusted, and the new version of the api method is void set ( t value ), t get ( ), and t _ initialvalue ( ).
Ds0 maintenance variables
How does the turtle maintain a copy of the variable for each thread. In fact, the idea is simple: There's a map in the ds0 class to store a copy of each thread 's variable, and the key of the element in the map is a thread object, and a copy of the We can provide a simple version of the implementation:
public class SimpleThreadLocal { private Map valueMap = Collections.synchronizedMap(new HashMap()); public void set(Object newValue) { valueMap.put(Thread.currentThread(), newValue);//①键为线程对象,值为本线程的变量副本 } public Object get() { Thread currentThread = Thread.currentThread(); Object o = valueMap.get(currentThread);//②返回本线程对应的变量 if (o == null &&!valueMap.containsKey(currentThread)) { //③如果在Map中不存在,放到Map中保存起来。 o = initialValue(); valueMap.put(currentThread, o); } return o; } public void remove() { valueMap.remove(Thread.currentThread()); } public Object initialValue() { return null; } }
Although the version of the above code is relatively straightforward, it's similar to that provided by the jdk in the implementation idea.
A theadlocal I & tance
Below, we know how to use a concrete example with a specific example.
public class SequenceNumber { //①通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值 private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){ public Integer initialValue(){ return 0; } }; //②获取下一个序列值 public int getNextNum(){ seqNum.set(seqNum.get()+1); return seqNum.get(); } public static void main(String[] args) { SequenceNumber sn = new SequenceNumber(); //③ 3个线程共享sn,各自产生序列号 TestClient t1 = new TestClient(sn); TestClient t2 = new TestClient(sn); TestClient t3 = new TestClient(sn); t1.start(); t2.start(); t3.start(); } private static class TestClient extends Thread { private SequenceNumber sn; public TestClient(SequenceNumber sn) { this.sn = sn; } public void run() { for (int i = 0; i <3; i++) {//④每个线程打出3个序列值 System.out.println("thread["+Thread.currentThread().getName()+ "] sn["+sn.getNextNum()+"]"); } } }
Typically, we define the subclasses of the ds0 by means of an anonymous inner class, providing the initial variable value, as shown in the example. A testclient thread generates a set of serial numbe & where we generate 3 testclient, which share the same sequencenumber I & tance. Run the above code to output the following results on the co & ole:
thread[Thread-2] sn[1] thread[Thread-0] sn[1] thread[Thread-1] sn[1] thread[Thread-2] sn[2] thread[Thread-0] sn[2] thread[Thread-1] sn[2] thread[Thread-2] sn[3] thread[Thread-0] sn[3] thread[Thread-1] sn[3]
Look at the results of the output, we found that each thread generated the sequence number, but they didn't interfere with each other, but they generated a separate serial number, because we provided a separate copy of each thread by the mat, because we provided a separate copy for each thread.
The role of the threadlocal.
Threadlocal isn't used to solve access problems for shared objects, typically by the object that's used by the threadlocal ( ) to the thread in the thread, and other threads aren't required to access it and are accessed by other threads. There are different objects in each thread to ask. ( note that this is just a"general situation". If the object in a threadlocal is shared with the same object in the thread, the access to the same shared object is the same shared object.
1. Provides methods for saving objects: Each thread has its own ThreadLocalMap class object, which allows you to keep its own objects in one of them, each of which can be properly accessed by the thread.
2. The convenient object access method to avoid paramete &: A common threadlocal I tance as key, saving references to different objects to ThreadLocalMap of different threads, and then executing that object at the end of the thread through the get ( ) method of the, avoids the trouble of passing this object as a parameter, avoiding the trouble of passing this object as a parameter.
Unde & tanding the copy of the variables mentioned in the ds0
"when a variable is used to maintain a variable, -- provides a separate copy of the variable for each thread that uses that variable,"isn't implemented through the mixin. Set ( ), but each thread uses the"new object"( or copy ) action to create a copy of the object, so each thread is taken out of its own map, so that the is used as the key for the map ( which is used as the key for map ). (.
If the object in the get. Set ( ) is the same object that's shared by multithreaded, then. ( ) gets or that the shared object itself is --, or there's a concurrent access problem.
/* * 如果ThreadLocal.set()进去的是一个多线程共享对象,那么Thread.get()获取的还是这个共享对象本身-----并不是该共享对象的副本。 * 假如:其中其中一个线程对这个共享对象内容作了修改,那么将会反映到其它线程获取的共享对象中----所以说 ThreadLocal还是有并发访问问题的! */ public class Test implements Runnable { private ThreadLocal<Person> threadLocal = new ThreadLocal<Person>(); private Person person; public Test(Person person) { this.person = person; } public static void main(String[] args) throws InterruptedException { //多线程共享的对象 Person sharePerson = new Person(110,"Sone"); Test test = new Test(sharePerson); System.out.println("sharePerson原始内容:"+sharePerson); Thread th = new Thread(test); th.start(); th.join(); //通过ThreadLocal获取对象 Person localPerson = test.getPerson(); System.out.println("判断localPerson与sharePerson的引用是否一致:"+(localPerson==localPerson)); System.out.println("sharePerson被改动之后的内容:"+sharePerson); } @Override public void run() { String threadName = Thread.currentThread().getName(); System.out.println(threadName+":Get a copy of the variable and change!!!"); Person p = getPerson(); p.setId(741741); p.setName("Boy"); } public Person getPerson(){ Person p = (Person)threadLocal.get(); if (p==null) { p= this.person; //set():进去的是多线程共享的对象 threadLocal.set(p); } return p; }
General steps used by
1, in classes, such as the ThreadDemo class, create a ds0 object threadxxx that holds the object that requires isolation between threads.
2, in the ThreadDemo class, create a method getXXX ( ) that gets the data to be isolated. ( ) is determined in the method, and if the mixin object is null, the new ( ) an object that isolated the access type should be used and cast to the type to apply.
3, in the run ( ) method of the ThreadDemo class, get the data to operate through the getXXX ( ) method, which guarantees that each thread corresponds to a data object.
/** * 学生 */ public class Student { private int age = 0; //年龄 public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } } /** * 多线程下测试程序 */ public class ThreadLocalDemo implements Runnable { //创建线程局部变量studentLocal,在后面你会发现用来保存Student对象 private final static ThreadLocal studentLocal = new ThreadLocal(); public static void main(String[] agrs) { ThreadLocalDemo td = new ThreadLocalDemo(); Thread t1 = new Thread(td, "a"); Thread t2 = new Thread(td, "b"); t1.start(); t2.start(); } public void run() { accessStudent(); } /** * 示例业务方法,用来测试 */ public void accessStudent() { //获取当前线程的名字 String currentThreadName = Thread.currentThread().getName(); System.out.println(currentThreadName + " is running!"); //产生一个随机数并打印 Random random = new Random(); int age = random.nextInt(100); System.out.println("thread" + currentThreadName + " set age to:" + age); //获取一个Student对象,并将随机数年龄插入到对象属性中 Student student = getStudent(); student.setAge(age); System.out.println("thread" + currentThreadName + " first read age is:" + student.getAge()); try { Thread.sleep(500); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("thread" + currentThreadName + " second read age is:" + student.getAge()); } protected Student getStudent() { //获取本地线程变量并强制转换为Student类型 Student student = (Student) studentLocal.get(); //线程首次执行此方法的时候,studentLocal.get()肯定为null if (student == null) { //创建一个Student对象,并保存到本地线程变量studentLocal中 student = new Student(); studentLocal.set(student); } return student; } }
Run results:
a is running! thread a set age to:76 b is running! thread b set age to:27 thread a first read age is:76 thread b first read age is:27 thread a second read age is:76 thread b second read age is:27
You can see a, b, two thread age is identical at different times at different times. This program can't only realize concurrent concurrency, but also keep the data security.
Here's an example of the following: Simulate a game, randomly set an integer for [ 1, 10 ], then each player to guess the number, each player knows the result of another player, and see who.
This game is really boring, but it's just possible to take each player as a thread, and then use ds0 to record the history of the player 's guess so that it's easy to unde.
Judge: used to set the target numbers and judge the results.
Player: per player as a thread, multiple player parallel to try guess, thread termination when guessing.
Class attempt: classes with mixin fields and guessing action static methods that are used to save a guessing number.
Record: save history data structure with a list field.
In order to be compatible with various types of data, the actual content is an object that passes through set and get, as shown in attempt 's getrecord ( ).
At run time, each player thread is to call the attemp. Guess ( ) method, and then work with the same mixin variable history, but can save each thread 's own data, which is the role of the cla.
public class ThreadLocalTest { public static void main(String[] args) { Judge.prepare(); new Player(1).start(); new Player(2).start(); new Player(3).start(); } } class Judge { public static int MAX_VALUE = 10; private static int targetValue; public static void prepare() { Random random = new Random(); targetValue = random.nextInt(MAX_VALUE) + 1; } public static boolean judge(int value) { return value == targetValue; } } class Player extends Thread { private int playerId; public Player(int playerId) { this.playerId = playerId; } @Override public void run() { boolean success = false; while(!success) { int value = Attempt.guess(Judge.MAX_VALUE); success = Judge.judge(value); System.out.println(String.format("Plyaer %s Attempts %s and %s", playerId, value, success? " Success" : "Failed")); } Attempt.review(String.format("[IFNO] Plyaer %s Completed by", playerId)); } } class Attempt { private static ThreadLocal<Record> history = new ThreadLocal<Record>(); public static int guess(int maxValue) { Record record = getRecord(); Random random = new Random(); int value = 0; do { value = random.nextInt(maxValue) + 1; } while (record.contains(value)); record.save(value); return value; } public static void review(String info) { System.out.println(info + getRecord()); } private static Record getRecord() { Record record = history.get(); if(record == null) { record = new Record(); history.set(record); } return record; } } class Record { private List<Integer> attemptList = new ArrayList<Integer>();; public void save(int value) { attemptList.add(value); } public boolean contains(int value) { return attemptList.contains(value); } @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(attemptList.size() + " Times:"); int count = 1; for(Integer attempt : attemptList) { buffer.append(attempt); if(count <attemptList.size()) { buffer.append(","); count++; } } return buffer.toString(); } }
Run results
Plyaer 2 Attempts 8 and Failed Plyaer 3 Attempts 6 and Failed Plyaer 1 Attempts 5 and Failed Plyaer 2 Attempts 7 and Success Plyaer 3 Attempts 9 and Failed Plyaer 1 Attempts 9 and Failed Plyaer 3 Attempts 2 and Failed Plyaer 1 Attempts 2 and Failed [IFNO] Plyaer 2 Completed by 2 Times: 8, 7 Plyaer 3 Attempts 4 and Failed Plyaer 1 Attempts 1 and Failed Plyaer 3 Attempts 5 and Failed Plyaer 1 Attempts 3 and Failed Plyaer 3 Attempts 1 and Failed Plyaer 1 Attempts 10 and Failed Plyaer 3 Attempts 8 and Failed Plyaer 1 Attempts 6 and Failed Plyaer 3 Attempts 7 and Success Plyaer 1 Attempts 4 and Failed [IFNO] Plyaer 3 Completed by 8 Times: 6, 9, 2, 4, 5, 1, 8, 7 Plyaer 1 Attempts 7 and Success [IFNO] Plyaer 1 Completed by 9 Times: 5, 9, 2, 1, 3, 10, 6, 4, 7
Hreadlocal get ( )
For the principle of ds0, it can be seen from its get ( ) method.
public class ThreadLocal<T> { ... public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map!= null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e!= null) return (T)e.value; } return setInitialValue(); } ThreadLocalMap getMap(Thread t) { return t.threadLocals; } ... }
Execute get ( ) first, get the current thread, get the ThreadLocalMap - t, threadlocals in thread, and take the actual value as its own key. As you can see, the variable 's variable actually remains in thread, and the container is a map, which is used by thread, and how many entry. | https://www.dowemo.com/article/46353/threadlocal | CC-MAIN-2018-26 | refinedweb | 2,212 | 54.22 |
No More Transformers: High-Performance Effects in Scalaz 8
No More Transformers: High-Performance Effects in Scalaz 8
For performant programs, you've probably shied away from monad transformers. Fortunately, Scalaz 8 offers an alternative approach.
Join the DZone community and get the full member experience.Join For Free
Get the Edge with a Professional Java IDE. 30-day free trial.
Monad transformers just aren’t practical in Scala.
They impose tremendous performance overhead that rapidly leads to CPU-bound, memory-hogging applications that give functional programming in Scala a reputation for being impractical.
Fortunately, all hope is not lost! In this article, I’ll describe the alternative approach that is being championed by Scalaz 8, which offers many of the benefits of MTL, but without the high costs.
The Trouble With Transformers
Monad transformers rely on vertical composition to layer new effects onto other effects. For example, the
EitherT monad transformer adds the effect of error management to some base effect
F[_].
In the following snippet, I have defined an
OptionT transformer that adds the effect of optionality to some base effect
F[_]:
case class OptionT[F[_], A](run: F[Option[A]]) { def map[B](f: A => B)(implicit F: Functor[F]): OptionT[F, B] = OptionT(run.map(_.map(f))) def flatMap[B](f: A => OptionT[F, B])(implicit F: Monad[F]): OptionT[F, B] = OptionT(run.flatMap( _.fold(Option.empty[B].point[F])( f andThen ((fa: OptionT[F, B]) => fa.run)))) } object OptionT { def point[F[_]: Applicative, A](a: A): OptionT[F, A] = OptionT(a.point[Option].point[F]) }
If you’ve ever written high-performance code on the JVM, even a quick glance at this definition of
OptionT should concern you. The transformer imposes additional indirection and heap usage for every usage of
point,
map, and
flatMap operation in your application.
While runtimes for languages like Haskell are reasonably efficient at executing this type of code, the JVM is not. We can see this very clearly by performing a line-by-line analysis of the transformer.
The definition of the class introduces a wrapper
OptionT:
case class OptionT[F[_], A](run: F[Option[A]]) {
Compared to the original effect
F[_], use of this wrapper will involve two additional allocations: an allocation for
Option, and an allocation for
OptionT. In the worst case (for a simple
F[_]), this wrapper might triple memory consumption of your application!
The
map function is defined as follows:
def map[B](f: A => B)(implicit F: Functor[F]): OptionT[F, B] = OptionT(run.map(_.map(f)))
In the
map of the original
F[_], there is a minimum of one method call. While no allocations are required, it is likely the function passed to
map will be a lambda that closes over some local state, which means there will often be another allocation.
In the
map function of the
OptionT transformer, there are an additional 3 method calls (
OptionT.apply,
run,
map), and an additional two allocations (
OptionT,
_), one for the
OptionT wrapper and one for the anonymous function.
If the type class syntax is not free, like in the Cats library, then there will be even more allocations and method calls.
This looks bad, but the actual situation is far worse than it appears.
Monad transformers can be stacked on top of any monad. This means they need to require monadic constraints on
F[_], here represented by
implicit F: Functor[F] on the
map function (for this operation, we don’t need to assume
Monad, because all we need is
Functor).
We are interacting with the base monad through a JVM interface, which has many, many implementations across our code base. Most likely, the JVM will not be able to determine which concrete class we are interacting with, and if so, the method calls will become megamorphic, which prevents many types of optimizations that can occur when calling methods on concrete classes.
The story for
flatMap is similar:
def flatMap[B](f: A => OptionT[F, B])(implicit F: Monad[F]): OptionT[F, B] = OptionT(run.flatMap( _.fold(Option.empty[B].point[F])( f andThen ((fa: OptionT[F, B]) => fa.run))))
This definition of
flatMap could be optimized, but even if completely optimized, there is even more overhead than
map.
Recently some benchmarks have compared the performance of Scalaz 8 IO (which has a bifunctor design for modeling errors) to its equivalent in
typelevel/cats, which is roughly
EitherT[cats.effect.IO, E, A] (modulo the additional failure case embedded into
IO).
The difference in performance is staggering: Scalaz 8 IO is nearly five times faster than
EitherT[cats.effect.IO, E, A].
Actual use in production could be faster or slower than these figures suggest, depending on the overhead of the base monad and how well the JRE optimizes the code. However, most applications that use monad transformers use many layers (not just a single
EitherT transformer), so the takeaway is clear: applications that use monad transformers will be tremendously slower and generate far more heap churn than applications that do not.
Monad transformers just aren’t practical in Scala, a fact that Scalaz 8 is uniquely prepared to embrace.
The Good Part of MTL
Monad transformers aren’t all bad. In Haskell, the
mtl library introduced type classes for abstracting over data types that support the same effect.
For example,
MonadState abstracts over all data types that are capable of supporting getting and setting state (including, of course, the
StateT monad transformer).
In fact, these days MTL-style does not refer to the use of monad transformers, per se, but to the use of the type classes that allow abstracting over the effects modeled by data structures.
In Scala, this style has become known as finally tagless for historical reasons. Most programmers doing functional programming in Scala recommend and use finally tagless-style, because it offers additional flexibility (for example, mocking out services for testing).
It is not widely known in the Scala programming community that finally tagless does not require monad transformers. In fact, there is absolutely no connection between finally tagless and monad transformers!
In the next section, I will show how you can use MTL-style, without specializing to concrete monad transformers.
M-L Without the T
Let’s say our application has some state type
AppState. Rather than use
StateT[F, S, A], which is a monad transformer that adds state management to some base monad
F[_], we will instead use the
MonadState type class:
trait MonadState[F[_], S] extends Monad[F] { self => def get: F[S] def put(s: S): F[Unit] }
We can then use
MonadState in our application like so:
def runApp[F[_]](implicit F: MonadState[F, AppState]): F[Unit] = for { state <- F.get ... _ <- F.put(state.copy(...)) ... } yield ()
Notice how this type class says absolutely nothing about the data types
F[_] that can support state management.
While we can use our function
updateState with a
StateT monad transformer, there is no requirement that we do so.
The high-performance, industrial-strength approach embraced by Scalaz 8 involves defining instances for a newtype wrapper around the
IO effect monad.
I’ll show you how to do this in the next section.
The first step in the Scalaz 8 approach involves defining a newtype wrapper for
IO. The point of this wrapper is to create a unique type, which will allow us to define instances of type classes like
MonadState that are specific to the needs of our application.
Although there are more reliable ways, one simple way to define a newtype is to declare a class that extends
AnyVal and stores a single value:
class MyIO[A](val run: IO[MyError, A]) extends AnyVal
Once we have define this newtype, then we need to create instances for all the type classes used by our application.
There are several ways to create an instance of
MonadState for
MyIO. Since instances are first-class values in Scala, I prefer the following way, which uses an
IORef to manage the state:
def createMonadState[E, S](initial: S): IO[E, MonadState[MyIO, S]] = for { ref <- IORef(initial) } yield new MonadState[MyIO, S] { def get: MyIO[S] = MyIO(ref.read) def put(s: S): MyIO[Unit] = MyIO(ref.write(s)) }
We can now use this function as follows inside our main function:
def main(args: IList[String]) = for { monadState <- createMonadState(AppState(...)) _ <- runApp(monadState) } yield ()
Because
MyIO is nothing more than a newtype for
IO, there are no additional heap allocations or method calls associated with use of the data type. This means that you get as close to the raw performance of
IO as is possible in the finally tagless style.
This approach works smoothly and efficiently for most common type classes, including
MonadReader,
MonadWriter, and many others.
Now you can have your cake and eat it, too: use type classes to precisely capture the minimal set of effects required by different parts of your application, and use instances of these type classes for your own newtype around
IO, giving you both abstraction and (relatively) high-performance.
Stack Safety
In Scala, many obvious monad transformers are stack unsafe. For example, the classic definition of
StateT is not stack safe. It can be modified to become stack safe, but the performance of an already slow data type becomes even slower, with many more method calls and allocations.
The problem is not limited to transformers, either. It is common to use stack-safe monad transformers to implement base monads (
State,
Writer,
Reader, and so on). For example, one can define a stack-safe base
State monad by using the type alias
type State[S, A] = StateT[F, S, A], for some stack-safe
StateT and trampolined monad
F.
While this approach (seen in the Cats library) creates stack safety for the base monad (by piggybacking on the safety of the transformer and the trampolined base monad), the resulting
State monad, which is powered by a slow
StateT transformer (made slower by stack safety!), becomes even slower due to trampolining.
The technique presented in this post lets you eliminate base monads like
State, bypassing the massive performance overhead entailed by older approaches to stack safety.
Going Forward
A decade of functional programming in Scala has taught us that while the abstraction afforded by MTL is extremely powerful and useful, transformers themselves just don’t work well in Scala—not today, and maybe not ever.
Fortunately, we can take advantage of MTL-style without sacrificing performance, merely by defining instances for cost-free wrappers around
IO.
As outlined in this post, there is a small amount of ceremony associated with this style, especially if you want to use localized effects. In addition, the
AnyVal approach to creating newtypes is fraught with problems and doesn’t have the guarantees we need.
In Scalaz 8, we should be able to address these issues in a way that makes it simple for users to use the right approach.
Watch this space for more coverage of how recent innovations are making functional programming in Scala practical—suitable for mainstream use even for demanding technical requirements. }} | https://dzone.com/articles/no-more-transformers-high-performance-effects-in-s | CC-MAIN-2018-39 | refinedweb | 1,867 | 50.67 |
Tutorial: HTTP Session handling using Servlet Filters
- By Viral Patel on February 12, 2009
Following small piece of code comes handy whenever you are working for a J2EE web application in JSP/Servlet/Struts/JSF or any Servlet oriented web framework.
A lot of time we have to handle session errors in such applications and redirect user to particular error page. Generally user is redirected to the login page where she can giver her credential and log in the application again.
In my previous post, I wrote about handling session errors and other server errors at client side using AJAX. But for doing this still we have to handle the session errors first at server side.
Let us see how we can track user session using Servlet Filter and redirect her to login page if session is already invalidated. We will induce session tracking facility to our web project (for this tutorial, I am using normal JSP web application in Eclipse).
Step 1: Create Servlet Filter to track Session
Create a package to place our session filter (in this case net.viralpatel.servlet.filter) and create a Java class SessionFilter.
Copy following code in the Java file.
package net.viralpatel.servlet.filter; import java.io.IOException; import java.util.ArrayList; SessionFilter implements Filter { private ArrayList<String> urlList; allowedRequest = false; if(urlList.contains(url)) { allowedRequest = true; } if (!allowedRequest) { HttpSession session = request.getSession(false); if (null == session) { response.sendRedirect("index.jsp"); } } chain.doFilter(req, res); } public void init(FilterConfig config) throws ServletException { String urls = config.getInitParameter("avoid-urls"); StringTokenizer token = new StringTokenizer(urls, ","); urlList = new ArrayList<String>(); while (token.hasMoreTokens()) { urlList.add(token.nextToken()); } } }
The init() method will get called by the servlet container and will get FilterConfig object as arguement. From this config object, we read the init parameters. We will see shortly what parameters do we passed in filter.
The doFilter() method will be called for each request of our application. Hence we can check the session in this method and see if it is valid. From init() method, we had generated a list of pages (urls) that were having access although the session is null. Index pages, error pages and other pages that you think user can access without logging in should be specified in this list.
In doFilter() method, you will notice one response.sendRedirect. I have redirected my user to index.jsp page if session is not valid. You can give any landing URL that you want your user to go when session is not valid. Alternatively you may want to create a JSON response and send it to client if you think the request was originated from AJAX.
Step 2: Specify filter entry in Web.xml deployment descriptor
Copy following entry in your application’s Web.xml file.
<filter> <filter-name>SessionFilter</filter-name> <filter-class> net.viralpatel.servlet.filter.SessionFilter </filter-class> <init-param> <param-name>avoid-urls</param-name> <param-value>index.jsp</param-value> </init-param> </filter> <filter-mapping> <filter-name>SessionFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
We have specified the filter in web.xml file which will get called for url /*. You can configure the URL mapping like normal filters URL mapping. Also note that we have specified a parameter avoid-url in init-parameters of filter. The value of this parameter will be a comma separated paths that we do not want to apply session validations on. I have specified index.jsp, you can give more urls separated by comma.
e.g.
index.jsp, someAction.do, Request.jsp, Message.jsf
Get our Articles via Email. Enter your email address.
Wouldn\’t you want a \"break\" statement after line 35?
With the current implementation it’s a meaningless optimization, but if there were a number of non-session oriented pages you wouldn’t want to continually do String compares when it doesn’t change the result.
Thanks Corey.
I have updated the post and added the break statement. Certainly a break will be needed in order to skip unnecessary comparisons.
Based on J2EE javadoc, HttpServletRequest.getSession() will always return a session object. (If the session dose not already exists, it will create a new one). I think in line 41 you need to have HttpSession session = request.getSession(false);
Thanks Shahram for pointing out the error. I have modified the code and added HttpSession session = request.getSession(false); instead of HttpSession session = request.getSession();
Thanks again :)
it doesn,t works.
I have this exception :
java.lang.IllegalStateException: Cannot forward after response has been committed
Hi Dod,
Can you please paste your Filter code? The above code seems to be working for me.
The error you are getting comes when you try to do response.sendRedirect( ) after printing something in response. You may have some out.print () statements before the redirect.
Still I am not sure about the problem.
that’s my code:
Ok, so the code seems to be working();
String contextPath = request.getContextPath();
boolean allowedRequest = false;
for(int i=0; i<totalURLS; i++) {
if(url.contains(urlList.get(i))) {
allowedRequest = true;
break;
}
}
if (!allowedRequest) {
HttpSession session = request.getSession();
if (null == session) {
response.sendRedirect(contextPath+”/jsp/loginError.jsp”);
}else{
String logged = (String) session.getAttribute(“logged-in”);
if (logged == null){
response.sendRedirect(contextPath+”/jsp/loginError.jsp”);
}else{
chain.doFilter(request, response);
}
}
} else{
chain.doFilter(request, response);
}
}
Nice to see that your error got resolved :-)
I think the code HttpSession session = request.getSession(); needs to be replaced with HttpSession session = request.getSession(false); otherwise everytime a new session will get created.
Hi dod,
you’ve got an error in line 34, please remove the semicolon.
Additionally i get the “Cannot create a session after the response has been committed”-message, too, although i don’t put anything in out?!
Any idea?
————–
public class SessionFilter implements Filter {
private ArrayList urlList;
private int totalURLS; noSessionNeeded = false;
for(int i=0; i<totalURLS; i++) {
String pattern=urlList.get(i);
if(url.contains(pattern)) {
noSessionNeeded = true;
break;
}
}
if (!noSessionNeeded) {
HttpSession session = request.getSession(false);
boolean exists=(session!=null);
boolean isNew=session.isNew();
if(!exists) response.sendRedirect("index.jsp");
if(isNew) response.sendRedirect("index.jsp");
}
chain.doFilter(req, res);
}
public void init(FilterConfig config) throws ServletException {
String urls = config.getInitParameter("noSessionNeeded");
StringTokenizer token = new StringTokenizer(urls, ",");
urlList = new ArrayList();
while (token.hasMoreTokens()) {
urlList.add(token.nextToken());
}
totalURLS = urlList.size();
}
}
Add a return after the forward/redirect statement, this will remove the illegalArgumentException
I had the problem with “Cannot create a session after the response has been committed” when using filter and JSF.
The solution was to do a requestDispatcher.forward instead of response.sendRedirect.
Look here:
Hi daniel, Thanks for sharing useful link.
When my session expires it’s not making it to the filter? Any idea of what I might be missing that is causing this to happen?
Hello Viral,
Thank you for this tutorial it’s been very useful. Is there a way to send the user to the page they’ve selected when the session expired?
What I have done is to store the selected link as an attribute and tried to alter the response by setting it as the string of the response.sendRedirect but this isn’t working for me. Do you have any advice as to how I might be able to achieve this?
Thanks.
I have a problem
After the session expires. the user is asked to relogin. When he relogins
he must be redirected to the page the where the session expired. I please to send me your
reply to mail id. I am waiting for your reply
thanks in advance
Hi Viral,
Can we do the same thing..i.e when user copy paste the URL in new window, he must be redirected to Login page using JSPs. I am using Struts 2.0 framework. I am not using servlets. Filters are available for servlets only or for JSPs also?
TIA
@Chandra: The above example will work for you in any case. i.e. it will work for JSPs, Servlets or Struts2 as well. Filters are available for both servlets and JSPs because we have mapped /* url with filter SessionFilter.
Hi I am getting StringTokenizer null pointer error, i Tried but same thing is comming.
if you have any solution plz send me
String urls = filterConfig.getInitParameter(“avoid-urls”);
StringTokenizer token = new StringTokenizer(urls, “,”);
urlList = new ArrayList();
while (token.hasMoreElements()) {
urlList.add(token.nextToken());
}
totalURLS = urlList.size();
Hi,
how can use this for ajax applications. per say, i have extjs spring applications. need to handle session time out or if session is not their, redirect to different page..
wrt a prg html page(login.html) which accept username and password.Authenticaticate them using filters and then to helloworld servlet if the user is a valid .(if username is “genesis” print response as “hello” ,otherwise print response as “invaliduser” )……………
answer give me
Thank you very much for this article.
But I improved the example in the following way:
This code prevent a java.lang.IllegalStateException: Cannot forward after response has been committed
Hi I keep on getting The page isn’t redirecting properly error, any ideas?
thanks
Hi, I’m developing a web application using JSP. In my application, after user login, if he clicks back button of the browser, he should not go to the index page of my website. can u help me with this?
I’m basically getting the same error as “learner”. I didn’t use this code but rather wrote my own. I have discovered that if I call getSession()/getSession(true), I always geta brand new session. If I call getSession(false) I always get null. I’ve been tearing my hair out over this the past few days. If I set session attributes in the filter and check them in the page where the filter redirects me to, I can read the values. But if I set attributes in the page, the filter never sees them because, as I said, getSession either returns null or a brand new session.
I’m using Tomcat 7.0.2. I’ve been using basic JSPs for years but this is the first time I create a servlet filter. I thought it was so brilliant until I hit this wall.
Hope you can help me. I would post the code but don’t have access to it right now.
@Gisli I am getting the same problem. But when i use tomcat v6 i don’t get the problem.
My problem is that the values i place in the session are lost.
If you find the solution please update me.
Hello,
nice tutorial, but i have a problem with me web.xml. I copied it like you have but still doesnt work for me. what changes do i have to make on both of them?
do i have to do something else to the other jsp files ?
thanks
hello Sir thank you very much for ur nice tutorial
But I am getting following error…
“The page isn’t redirecting properly”
Any suggestion will be herately appreciated …….
here is my web.xml code
SessionFilter
SessionFilter
avoid-urls
index.jsp
SessionFilter
/*
LoginServlet
LoginServlet
SuccessPage
SuccessPage
Failure
Failure
SessionFilter
SessionFilter
LoginServlet
/LoginServlet
SuccessPage
/SuccessPage
Failure
/Failure
1
hello Sir,
Thank you very much for such nice article but in my case its not working
Error is ““The page isn’t redirecting properly””.plz sir help me to resolve the problem
As I am in need of it badly in my current App
Plz sir reply soon plz sir
Hi sir,
How can i handle session when it is expired.
Actually i want to save the expired time in to database….when i click.
plz replay me soon….
u can check is session invalid or not in inside filter class
Hello Mr Patel
Its really an awesome article.
I have been searching for an example code where i can get some idea about session filter to implement.Your code did this for me and its working well.
except two things 1. should have a return after redirect and 2.request dispatcher.
otherwise it was throwing error like “…..after the response has been committed”
After reading all responses these issues are resolved.
Thanks a lot.
HttpSession session = request.getSession(false);
if(session == null){
//code
}
For the first request i am getting session null but on second request it returns org.apache.catalina.session.StandardSessionFacade
so what could be the problem?
Dear Yogesh,
same problem facing, one of my workmate, I’ll ask him. ;)
you just saved our lives and our jobs, love you you are the best, we have been dealing with this months ago………….
Is there any way to set the time out time?
hello.. i m observing in my maven proj web app code while using filters that when we write HttpSession session=request.getSession(true) in servlet, a new session is created. Now acc. to my code, before calling this servlet, filter should be called. In filter, request.getSession().getAttribute and likely instructions create new session. My question is , is it like when you call filter before servlet, a new session would be created with above lines? Because, in my servlet i have invalidated current session and i am trying to call servlet through address bar to check if session is actually expired or not. However because of request.getAttribute() creates a new session instead of null.
This filter should chain to other filters (row 43). If you redirect to index.jsp (row 39), the remaining filter will activate and you’ll get a “Response already committed” error . To avoid this behaviour you have to break the filters chain putting a
after row 39.
Good Content. Thanks Virat. This tutorial helped me a lot.
replace this line:
with this:
as below line of code return servlet path with prefix “/” :
Hi Viral,
Can you please provide some tutorial on how to remove JSessionId from URLs in Spring MVC application (at programming side and as well server side).
Thanks,
Sachin | http://viralpatel.net/blogs/http-session-handling-tutorial-using-servlet-filters-session-error-filter-servlet-filter/ | CC-MAIN-2014-52 | refinedweb | 2,330 | 59.8 |
After.
My thinking was that this could be used in a SIEM-like way to make sense of the huge amounts of data spat out by cyber security solutions. To test it out, though, I decided to fight back against those writing Chelsea off after a bit of a rocky period by comparing their Premier League performance this year to the beginning of the title-winning 2016/17 season.
Setting everything up
As with most Python projects, we have to begin with a little bit of setup. Plotly’s quite simple in this regard, though, and can be imported with a single line – or two words, to be exact.
import plotly
Giving Plotly our data
Next up, we need to prepare our data for Plotly. This involves setting up variables for the X and Y axes for each series – in this case, the 2016/17 and 2017/18 Premier League seasons.
#2016/17 data
lastseason_x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
lastseason_y = [3, 6, 9, 10, 10, 10, 13, 16, 19, 22, 25, 28, 31]
#2017/18 data
thisseason_x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
thisseason_y = [0, 3, 6, 9, 10, 13, 13, 13, 16, 19, 22, 25, 26]
The X axis values are matchdays and the Y axis values represent Chelsea’s point count. If I was using Plotly to generate a graph for a more dynamic data set – figures fetched using an API, for example – this would be a bit more complex.
Plotting our data on the graph
Now we need to tell Plotly how exactly we want this data to appear on the graph. I’ll define two lines to be plotted – one representing last season and one for this season.
#Create lines
lastseason_line = plotly.graph_objs.Scatter(
x = lastseason_x,
y = lastseason_y,
mode = ‘lines+markers’,
name = ‘2016/17’
)
thisseason_line = plotly.graph_objs.Scatter(
x = thisseason_x,
y = thisseason_y,
mode = ‘lines+markers’,
name = ‘2017/18’
)
As you can see, I’ve assigned the X and Y axis values I’ve just entered to their corresponding lines, and given the series names. The mode “lines+markers” displays the data as a line with a node at each data point – great for comparing the two seasons.
Formatting and exporting the graph
Now to bring everything together and make it look pretty. As you can see, I’ve created a variable for my data series and a layout variable, which contains a bunch of formatting options that pretty much do what they say (“dtick” represents the interval between the axis labels). Handily, Plotly accepts RGB or HTML hex colour codes for the colour settings.
#Create graph
data = [lastseason_line, thisseason_line]
layout = dict(title = ‘Chelsea Premier League performance – 2016/17 vs. 2017/18’,
xaxis = dict(title = ‘Matchday’,
gridcolor=’#555′,
dtick = 1),
yaxis = dict(title = ‘Points’,
gridcolor=’#555′),
font = dict(family = ‘Arial’,
color = ‘ddd’),
paper_bgcolor=’#333′,
plot_bgcolor=’#333′
)
fig = dict(data=data, layout=layout)
plotly.offline.plot(fig, filename=’cfc_points’)
I then import all of these into a variable called fig, which I feed into Plotly’s offline graph generation function, telling it to output the results to a file that will be called cfc_points.htm.
Output
As you can see, the end result is a neat interactive graph that looks much flashier than anything anybody ever produced in Microsoft Excel. And you can also see that Chelsea’s point tally is only marginally lower than it was at this stage in the last Premier League season – not bad considering we’re also in the Champions League this year!
This was a fairly simple, trivial example, but at some point I’d love to try to grab some live data from somewhere and use Plotly to generate near-live graphs that make it easier to make sense of. Perhaps I’ll have a chance over my Christmas @cfcunofficial (Chelsea Debs) (CC BY-SA 2.0). Cropped. | https://mattcasmith.net/2017/11/30/creating-beautiful-graphs-in-python-with-plotly/ | CC-MAIN-2019-35 | refinedweb | 653 | 54.36 |
- NAME
- SYNOPSIS
- DESCRIPTION
- OPTIONS
- NOTES
- EXAMPLES
- SEE ALSO
- BUGS
- CREDITS
- COPYING
NAME
Object::Import - import methods of an object as functions to a package
SYNOPSIS
use Object::Import $object; foo(@bar); # now means $object->foo(@bar);
DESCRIPTION
This module lets you call methods of a certain object more easily by exporting them as functions to a package. The exported functions are not called as methods and do not receive an object argument, but instead the object is fixed at the time you import them with this module.
You use the module with the following syntax:
use Object::Import $object, %options;
Here,
$object is the object from which you want to import the methods. This can be a perl object (blessed reference), or the name of a package that has class methods.
As usual, a
use statement is executed in compile time, so you should take care not to use values that you compute only in run-time, eg.
my $object = Foo::Bar->new(); use Object::Import $object; # WRONG: $object is not yet initialized
Instead, you have to create the object before you import, such as
use Object::Import Foo::Bar->new();
You can also call import in run-time, eg.
use Object::Import (); my $object = Foo::Bar->new(); import Object::Import $object;
but in that case, you can't call the imported functions without parenthesis.
If you don't give an explicit list of methods to export, Object::Import tries to find out what callable methods the object has and import all of them. Some methods are excluded from exporting in this case, namely any methods where exporting would overwrite a function existing in the target package or would override a builtin function, also any methods with names that are special to perl, such as
DESTROY, and any methods whose name starts with an underscore. This automatic search for methods is quite fragile because of the way perl OO works, so it can find subroutines that shouldn't actually be called as methods, or not find methods that can actually be called. In particular, even if you import an object from a purely object oriented module, it can find non-method subs imported from other (non-OO) modules.
If you do give a list of methods to export, Object::Import trusts you know what you mean, so it exports all those subs even if it has to replace existing subs or break something else.
OPTIONS
The following import options can be passed to the module.
list =>$arrayref
Sets the list of methods to export, instead of the module deciding automatically. $arrayref must be a reference to an array containing method names. Eg.
use Object::Import LWP::UserAgent->new, list => [qw"get post head mirror request simple_request"];
target =>$package_name
Export the sub names to the given namespace. Default is the package from where you call import.
deref => 1
Signals that the first import argument, instead of being the object itself, is a reference to a scalar that contains the object.
The content of this scalar may later be changed, and the imported functions will be called on the new contents. (The scalar may even be filled with undef, as long as you don't call the functions at that time.) If you don't pass the list of methods explicitly, the content of the scalar at the time of the import is used for determining the methods as a template to determine the methods. If, however, you give the list of methods, the content of the scalar is not examined at the time of the import.
prefix =>$string
Prepends a string to the names of functions imported. This is useful if some of the method names are the same as existing subs or builtins. Eg.
use Object::Import $object, prefix => "foo"; foo_bar(); # calls $object->bar();
suffix =>$string
Like the prefix option, only the string is appended.
underscore => 1
Consider a method for automatic inclusion even if its name starts with an underscore. Such methods are normally excluded, because they are usually used as private subs.
exclude_methods =>$hashref
Sets a list of additional methods that are not automatically imported. The argument must be a reference to a hash whose keys are potential method names. Ignored if you use the
listoption.
exclude_imports =>$hashref
Sets a list of additional sub names which the module must never use as names of imported subs. These names are thus compared not with the original method names, but the names possibly transformed by adding prefixes and suffixes. This applies even if you give an explicit
listof methods to import.
savenames =>$hashref
Save the (unqualified) names of the functions exported by adding them as a key to a hash (the value is incremented with the ++ operator). This could be useful if you wanted to reexport them with Exporter. $arrayref must be a real reference to a hash, not an undef.
nowarn_redefine => 1
Do not warn when an existing sub is redefined. That is currently only possible if you give the list of methods to be exported explicitly with the
listoption, because if the module chooses automatically then it will not redefine subs.
nowarn_nomethod => 1
Suppress the warning when you try to import methods from an object you might have passed in by mistake. Namely the object could be the name of a nonexistent package, a string that is not a valid package name, an unblessed object, or undef. Such values either don't currently have any methods, or calling methods on them is impossible. That warning often indicates that you passed the wrong value to Object::Import or forgot to require a package.
debug => 1
Print debugging messages about what the module exports.
NOTES
Importing from IO handles
It is possible to use an IO handle as the object to export methods from. If you do this, you should require IO::Handle first so that the handle actually has methods. You should probably also use the prefix or suffix option in such a case, because many methods of handles have the same name as a builtin function.
The handle must not be a symbolic reference, whether qualified or unqualified, eg.
open FOO, "<", "somefile" or die; use Object::Import "FOO"; # WRONG
You can pass a handle as a glob, reference to glob, or an IO::Handle object, so any of these would work as the object after the above open statement:
*FOO,
\*FOO,
*FOO{IO}. Another way to pass an IO::Handle object would be like this:
use IO::File; use Object::Import IO::File->new("somefile", "<");
Changing the object
The
deref option deserves special mention. This option adds a level of indirection to the imported functions: instead of them calling methods on an object passed to import, the methods are called on the object currently contained by a scalar to which a reference is passed in to import. This can be useful for various reasons: operating on multiple objects throughout the course of the program, being able to import the functions at compile time before you create the object, or being able to destroy the object. The first of this use is straightforward, but you may need to know the following for the other two uses.
The list of methods imported is decided at the time you call import, and will not be changed later, no matter how the object is changed or methods the object supports are changed. You thus have to do extra loops if you want to call import before the object is available. The simplest solution is to pass the list of methods you want explicitly using the list option. If for some reason you don't want to do this, you need to fill the scalar with a suitable prototype object that has all the methods of the actual object you want to use. In many cases, the package name the object will be blessed to is a suitable prototype, but note that if you do not control the module implementing the object, then that module may not guarantee what package the object will actually be blessed to: the package may depend on some run-time parameters and the details about this could change in future versions of the module. This is, of course, not specific to the deref option, but true to a lesser extent to any case when you're using Object::Import without an explicit list of methods: a future version of the module could create the methods of the class in runtime or AUTOLOAD them without declaring them, or it could add new private methods that will clash with function names you're using. Nevertheless, using the classname as a prototype can be a useful trick in quick and dirty programs, or if you are in control of the implementation of the object.
Now let's hear about destroying an object that may hold resources you want to free. Object::Import guarantees that if you use the deref option, it does not hold references to the object other than through the one scalar, so if undef the contents of that scalar, the object will be freed unless there are references from somewhere else.
Finally, there's one thing you don't want to know but I must document it for completeness: if a method called through Object::Import changes its invocant (zeroth argument), that will also change the object the imported functions refer to, whether you use the deref option or not, and will change the contents of the scalar if you use the deref option.
EXAMPLES
Our examples assume the following declarations:
use feature "say";
Basic usage
First a simple example of importing class methods.
use Math::BigInt; use Object::Import Math::BigInt::; say new("0x100");
This prints 256, because Math::BigInt->new("0x100") creates a big integer equal to 256.
Now let's see a simple example of importing object methods.
use Math::BigInt; use Object::Import Math::BigInt->new("100"); say bmul(2); say as_hex();
This prints 200 (2 multiplied by 100), then 0xc8 (100 as hexadecimal).
Multiple imports
Now let's see a more complicated example. This prints the leading news from the English Wikinews website.
use warnings; use strict; use LWP::UserAgent; use XML::Twig; use Object::Import LWP::UserAgent->new; my $response = get "?". "pages=Template:Lead_article_1&limit=1"; import Object::Import $response; if (is_success()) { use Object::Import XML::Twig->new; parse content(); for my $parmname (qw"title summary") { first_elt("text")->text =~ /\|\s*$parmname\s*=([^\|\}]+)/ or die; print $1; } } else { die message(); }
For example, as I am writing this (2010-09-05), this outputs
Magnitude 7.0 earthquake hits New Zealand
An earthquake with magnitude 7.0 occurred near South Island, New Zealand at Saturday 04:35:44 AM local time (16:35:44 UTC). The earthquake occurred at a depth of 16.1 kilometers (10.0 miles). The earthquake was reported to have caused widespread damage and power outages. Several aftershocks were also reported.
In this,
get refers to the useragent object;
is_success,
content and
message refers to the response object (and these must be called with a parenthesis); while
parse and
first_elt refer to the twig object. This is not a good example to follow: it's quite fragile, and not only because of the simple regex used to parse out the right parts, but because if a new sub is added to a future version of the LWP::UserAgent or HTTP::Response classes, they might suddenly get imported and would shadow the methods we're supposed to import later.
Suffix
Now let's see an example of using a suffix.
use File::Temp; use Object::Import scalar(File::Temp->new()), suffix => "temp"; printtemp "hello, world\nhidden"; seektemp 0, 0; print getlinetemp; say filenametemp;
Here we need the suffix because print and seek are names of builtin functions.
Creating the object later
Let's see how we can import methods before we create an object.
use Math::BigInt; our $number; use Object::Import \$number, deref => 1, list => ["bmul"]; sub double { bmul 2 } $number = Math::BigInt->new("100"); say double;
This will output 200. Notice how here we're using the bmul function without parenthesis, so we must import it compile time for the code to parse correctly, but the object is not created till later.
Prototype object
This code is the same as above, except that instead of supplying a list of methods, we use a prototype object, namely the Math::BigInt package. At least one of the two is needed, for otherwise Object::Import would have no way to know what methods to import.
use Math::BigInt; our $number; use Object::Import \($number = Math::BigInt::), deref => 1; sub double { bmul 2 } $number = Math::BigInt->new("100"); say double;
Exporting to other package
This example shows how to export to a different namespace. This is useful if you want to write your own sugar module that provides a procedural syntax:
package My::Object::DSL; use Object::Import; use My::Object; sub import { my ($class, %options); if (@_ == 2) { ($class, $options{ name }) = @_; } else { ($class, %options) = @_; }; my $target = delete $options{ target } || caller; my $name = delete $options{ name } || '$obj'; my $obj = My::Object->new(%options); $name =~ s/^[\$]// or croak 'Variable name must start with $'; { no strict 'refs'; *{"$target\::$name"} = \$obj; # Now install in $target:: import Object::Import \${"$target\::$name"}, deref => 1, target => $target; } }
You can use the module
My::Object::DSL as follows:
use My::Object::DSL '$obj';
If you want to pass more options, you can use
use My::Object::DSL name => '$obj', foo => 'bar';
Implementing a small
::DSL module instead of using
Object::Import directly has the advantage that you can add defaults in
DSL.pm.
SEE ALSO
Class::Exporter, Scope::With, Sub::Exporter, Acme::Nooo
BUGS
Please report bugs using the CPAN bug tracker (under the distribution name Object-Import), or, failing that, to
corion@cpan.org.
CREDITS
The primary author and maintainer of this module is Zsban Ambrus
ambrus@math.bme.hu. Some of the code was written by Max Maischein, who also gave the motivation to turn a prototype to the full module you see. Thanks to exussum0 for the original inspiration.
The module is maintained by Max Maischein since 2018.
COPYING
This program is free software: you can redistribute it and/or modify it under the terms of either the GNU General Public License version 3, as published by the Free Software Foundation; or the "Artistic License" which comes with perl. source tree of this module under the name "GPL", or else see "". A copy of the Artistic License can be found in the source tree under the name "ARTISTIC", or else see "". | https://metacpan.org/pod/Object::Import | CC-MAIN-2019-13 | refinedweb | 2,435 | 55.58 |
Lightning Guide to XML
Generating XML
Parsing XML
Transforming XML with XSLT
Web Services
XML, the
Extensible Markup
Language, is a standardized data format. It looks a little like HTML,
with tags
(<example>like
this</example>) and entities
(&). Unlike HTML, however, XML is designed
to be easy to parse, and there are rules for what you can and cannot
do in an XML document. XML is now the standard data format in fields
as diverse as publishing, engineering, and medicine.
It's used for remote procedure calls, databases,
purchase orders, and much more.
There are many scenarios where you might want to use XML. Because it
is a common format for data transfer, other programs can emit XML
files for you to either extract information from (parse) or display
in HTML (transform). This chapter shows how to use the XML parser
bundled with PHP, as well as how to use the optional XSLT extension
to transform XML. We also briefly cover generating XML.
Recently, XML has been used in remote procedure calls. A client
encodes a function name and parameter values in XML and sends them
via HTTP to a server. The server decodes the function name and
values, decides what to do, and returns a response value encoded in
XML. XML-RPC has proved a useful way to integrate application
components written in different languages. In this chapter,
we'll show you how to write XML-RPC servers and
clients.
Most
XML consists of elements (like HTML tags), entities, and regular
data. For example:
<book isbn="1-56592-610-2">
<title>Programming PHP</title>
<authors>
<author>Rasmus Lerdorf</author>
<author>Kevin Tatroe</author>
</authors>
</book>
In HTML, you often have an open tag
without a close tag. The most common example of this is:
<br>
In XML, that is illegal. XML requires that every open tag be closed.
For tags that don't enclose anything, such as the
line break <br>, XML adds this syntax:
<br />
can be nested but cannot overlap. For example, this is valid:
<book><title>Programming PHP</title></book>
but this is not valid, because the book and
title tags overlap:
<book><title>Programming PHP</book></title>
XML also requires that the
document begin with a processing instruction that identifies the
version of XML being used (and possibly other things, such as the
text encoding used). For example:
<?xml version="1.0" ?>
The final requirement of a well-formed XML document is that there be
only one element at the top level of the file. For example, this is
well formed:
<?xml version="1.0" ?>
<library>
<title>Programming PHP</title>
<title>Programming Perl</title>
<title>Programming C#</title>
</library>
but this is not well formed, as there are three elements at the top
level of the file:
<?xml version="1.0" ?>
<title>Programming PHP</title>
<title>Programming Perl</title>
<title>Programming C#</title>
XML documents generally are not completely ad hoc. The specific tags,
attributes, and entities in an XML document, and the rules governing
how they nest, comprise the structure of the document. There are two
ways to write down this structure: the
Document Type Definition (DTD)
and the Schema. DTDs and Schemas are used to validate documents; that
is, to ensure that they follow the rules for their type of document.
Most XML documents don't include a DTD. Many
identify the DTD as an external with a line that gives the name and
location (file or URL) of the DTD:
<!DOCTYPE rss PUBLIC 'My DTD Identifier' ''>
Sometimes it's
convenient to encapsulate one XML document in another. For example,
an XML document representing a mail message might have an
attachment element that surrounds an attached
file. If the attached file is XML, it's a nested XML
document. What if the mail message document has a
body element (the subject of the message), and the
attached file is an XML representation of a dissection that also has
a body element, but this element has completely
different DTD rules? How can you possibly validate or make sense of
the document if the meaning of body changes
partway through?
This problem is solved with the use of namespaces. Namespaces let you
qualify the XML tag—for example, email:body
and human:body.
There's a lot more to XML than we have time to go
into here. For a gentle introduction to XML, read Learning
XML, by Erik Ray (O'Reilly). For a
complete reference to XML syntax and standards, see XML in
a Nutshell, by Elliotte Rusty Harold and W. Scott Means
(O'Reilly). | https://docstore.mik.ua/orelly/weblinux2/php/ch11_01.htm | CC-MAIN-2019-39 | refinedweb | 761 | 61.97 |
Synopsis_06 - Subroutines
Damian Conway <damian@conway.org> and Allison Randal <al@shadowed.net>
Maintainer: Larry Wall <larry@wall.org> Date: 21 Mar 2003 Last Modified: 24 Feb 2006 Number: 6 Version: anonymous subroutines is:
sub ( PARAMS ) TRAITS {...}
But one can also use a scope modifier to introduce the return type first:
my RETTYPE sub ( PARAMS ) TRAITS {...} our RETTYPE sub ( PARAMS ) TRAITS {...} # means the same as "my" here }
Only the name is installed into the
GLOBAL package by
*. To define subs completely within the scope of the
GLOBAL namespace you should use "
package GLOBAL {...}" around the declaration. => sub ($self) { return lastval(); }, STORE => sub ($self, hash subscript (but evaluated at compile time). So any of these indicate A6, not escaped, so
PKG::circumfix:{'<','>'} is canonicalized to
PKG::{'circumfix:<< >>'}, and decanonicalizing always involves stripping the outer angles and splitting on space, if any. This works because a hash key knows how long it is, so there's no ambiguity about where the final angle is. And space works because operators are not allowed to contain spaces.
Operator names can be any sequence of non-whitespace characters including Unicode characters. For example:
sub infix:<(c)> ($text, $owner) { return $text but Copyright($owner) } method prefix:<±> (Num $x);
Ordinary hash notation will just pass the value of the hash entry as a positional argument regardless of whether it is a pair or not. To pass both key and value out of hash as a positional pair, use
:p.
doit %hash<a>:p,1,2,3; doit %hash{'b'}:p,1,2,3;
instead.. (The
:p stands for "pairs", not "positional"--the
:p adverb may be placed on any hash reference to make it mean "pairs" instead of "values".).Arg an undefined value if they have no default. (A supplied argument that is undefined is not considered to be missing, and hence does not trigger the default. Use
//= within the body for that.)
(Conjectural: Within the body you may also use
exists on the parameter name to determine whether it was passed. Maybe this will have to be restricted to the
? form, unless we're willing to admit that a parameter could be simultaneously defined and non-exist),.
Slurpy parameters are treated lazily -- the list is only flattened into an array when individual elements are actually accessed:
@fromtwo = tail(1..Inf); # @fromtwo contains a lazy [2..Inf].
0... ==> @;foo; 'a'... ==> @;foo; pidigits() ==> @;foo; for zip(@;foo) { say } [0,'a',3] [1,'b',1] [2,'c',4] [3,'d',1] [4,'e',5] [5,'f',9] ...
Here
@;foo is an array of three iterators, so
zip(@;foo)
is equivalent to
zip(@;foo[0]; @;foo[1]; @;foo[2])
A semicolon inside brackets is equivalent to.map { say }
and then you just get 0,'a',1,'b',2,'c'. This is good for
for @;tmp.map -> ...).map: -> $x, $i { ...}
Also note that these come out to identical for ordinary arrays:
@foo.map @foo.cat
Parameters declared with the
& sigil take blocks, closures, or subroutines as their arguments. Closure parameters can be required, optional, named, or slurpy., instead captures the actual "kind" of object and also declares a package/type name by which you can refer to that kind later in the signature or body. For instance, if you wanted to match any two Dogs as long as they were of the same kind, you can say:
sub matchedset (Dog ::T $fido, T $spot) {...}
(Note that
::T is not required to contain
Dog, only a type that is compatible with
Dog.)
The
:: sigil is short for "subset" in much the same way that
& is short for "sub". Just as
& can be used to name any kind of code, so too
:: can be used to name any kind of type. Both of them insert a bare identifier into the paren would try to match literally.
If a submethod's parameter is declared with a
. or
! after the sigil (like an attribute):
submethod initialize($.name, $!age) {}
then the argument is assigned directly to the object's attribute of the same name. This avoids the frequent need to write code like:
submethod initialize($name, $age) { $.name = $name; $!age = $age; } either as
$age or
$!age.:
-> };:
our Egg sub lay {...} our sub lay returns Egg {...} my Rabbit sub hat {...} my sub hat returns Rabbit {...}
If a subroutine is not explicitly scoped, it belongs to the current namespace (module, class, grammar, or package), as if it's scoped with the
our scope modifier. Any return type must go after the name:
sub lay returns Egg {...}
On an anonymous subroutine, any return type can only go after the
sub keyword:
$lay = sub returns Egg {...};
but you can use a scope modifier to introduce a return type:
$lay = my Egg sub {...}; $hat = my Rabbit sub {...};
Because they are anonymous, you can change the
my modifier to
our without affecting the meaning.; }
Properties are predeclared as roles and implemented as mixins--see S12.
These traits may be declared on the subroutine as a whole (individual parameters take other traits).. ref
Specifies that the parameter is passed by reference. Unlike
is rw, the corresponding argument must already be a suitable lvalue. No attempt at coercion or autovivification is made, so unsuitable values throw an exception when you try to modify them.
is copy
Specifies that the parameter receives a distinct, read-writ)) {...}'
wantfunction
Hypothetical variables use the same mechanism, except that the restoring closure is called only on failure.
Note that "env" variables may be a better solution than temporized globals in the face of multithreading.) } );");
This form should generally be restricted to named parameters.
To curry a particular multimethod it may be necessary to specify the type of one or more of its invocants:
.
In aid of returning syntax tree, Perl provides a "quasiquoting" mechanism using the quote
q:code, followed by a block intended to represent an AST:
return q:code { say "foo" };
Modifiers to the
:code adverb () { q:code { $COMPILING::x } } moose(); # macro-call-time error my $x; moose(); # resolves to 'my $x'
If you want to mention symbols from the scope of the macro call, use the import syntax as modifiers to
:code:
:= and
require forms, not
::= a "unquoted" expression of either type within a quasiquote, use the quasiquote delimiter tripled, typically a bracketing quote of some sort:
return q:code { say $a + {{{ $ast }}} } return q:code [ say $a + [[[ $ast ]]] ] return q:code < say $a + <<< $ast >>> > return q:code ( rule is parameterized to know that
}}} or whatever is its closing delimiter.)
The delimiters don't have to be bracketing quotes, but the following is probably to be construed as Bad Style:
return q:code / say $a + /// $ast /// /
De variable. .)
A quasiquote is not a block (even if the delimiters are curlies), so any declaration of a variable is taken to be part of the block surrounding the macro call location. Add your own {...} if you want a block to surround your declarations.
{...}.). | http://search.cpan.org/~autrijus/Perl6-Bible/lib/Perl6/Bible/S06.pod | CC-MAIN-2016-30 | refinedweb | 1,145 | 64.41 |
8.17: Moving by Holding Down the Key
- Page ID
- 14593
# handle moving the piece because of user input if (movingLeft or movingRight) and time.time() - lastMoveSidewaysTime > MOVESIDEWAYSFREQ: if movingLeft and isValidPosition(board, fallingPiece, adjX=-1): fallingPiece['x'] -= 1 elif movingRight and isValidPosition(board, fallingPiece, adjX=1): fallingPiece['x'] += 1 lastMoveSidewaysTime = time.time() if movingDown and time.time() - lastMoveDownTime > MOVEDOWNFREQ and isValidPosition(board, fallingPiece, adjY=1): fallingPiece['y'] += 1 lastMoveDownTime = time.time()
Remember that on line 227 the
movingLeft variable was set to
True if the player pressed down on the left arrow key? (The same for line 233 where
movingRight was set to
True if the player pressed down on the right arrow key.) The moving variables were set back to
False if the user let up on these keys also (see line 217 and 219).
What also happened when the player pressed down on the left or right arrow key was that the
lastMoveSidewaysTime variable was set to the current time (which was the return value of
time.time()). If the player continued to hold down the arrow key without letting up on it, then the
movingLeft or
movingRight variable would still be set to
True.
If the user held down on the key for longer than 0.15 seconds (the value stored in
MOVESIDEWAYSFREQ is the float
0.15) then the expression
time.time() - lastMoveSidewaysTime > MOVESIDEWAYSFREQ would evaluate to
True. Line 2's [265] condition is
True if the user has both held down the arrow key and 0.15 seconds has passed, and in that case we should move the falling piece to the left or right even though the user hasn’t pressed the arrow key again.
This is very useful because it would become tiresome for the player to repeatedly hit the arrow keys to get the falling piece to move over multiple spaces on the board. Instead, they can just hold down an arrow key and the piece will keep moving over until they let up on the key. When that happens, the code on lines 216 to 221 will set the moving variable to
False and the condition on line 2 [265] will be
False. That is what stops the falling piece from sliding over more.
To demonstrate why the
time.time() - lastMoveSidewaysTime > MOVESIDEWAYSFREQ returns
True after the number of seconds in
MOVESIDEWAYSFREQ has passed, run this short program:
import time WAITTIME = 4 begin = time.time() while True: now = time.time() message = '%s, %s, %s' % (begin, now, (now - begin)) if now - begin > WAITTIME: print(message + ' PASSED WAIT TIME!') else: print(message + ' Not yet...') time.sleep(0.2)
This program has an infinite loop, so in order to terminate it, press Ctrl-C. The output of this program will look something like this:
1322106392.2, 1322106392.2, 0.0 Not yet... 1322106392.2, 1322106392.42, 0.219000101089 Not yet... 1322106392.2, 1322106392.65, 0.449000120163 Not yet... 1322106392.2, 1322106392.88, 0.680999994278 Not yet... 1322106392.2, 1322106393.11, 0.910000085831 Not yet... 1322106392.2, 1322106393.34, 1.1400001049 Not yet... 1322106392.2, 1322106393.57, 1.3710000515 Not yet... 1322106392.2, 1322106393.83, 1.6360001564 Not yet... 1322106392.2, 1322106394.05, 1.85199999809 Not yet... 1322106392.2, 1322106394.28, 2.08000016212 Not yet... 1322106392.2, 1322106394.51, 2.30900001526 Not yet... 1322106392.2, 1322106394.74, 2.54100012779 Not yet... 1322106392.2, 1322106394.97, 2.76999998093 Not yet... 1322106392.2, 1322106395.2, 2.99800014496 Not yet... 1322106392.2, 1322106395.42, 3.22699999809 Not yet... 1322106392.2, 1322106395.65, 3.45600008965 Not yet... 1322106392.2, 1322106395.89, 3.69200015068 Not yet... 1322106392.2, 1322106396.12, 3.92100000381 Not yet... 1322106392.2, 1322106396.35, 4.14899992943 PASSED WAIT TIME! 1322106392.2, 1322106396.58, 4.3789999485 PASSED WAIT TIME! 1322106392.2, 1322106396.81, 4.60700011253 PASSED WAIT TIME! 1322106392.2, 1322106397.04, 4.83700013161 PASSED WAIT TIME! 1322106392.2, 1322106397.26, 5.06500005722 PASSED WAIT TIME! Traceback (most recent call last): File "C:\timetest.py", line 13, in <module> time.sleep(0.2) KeyboardInterrupt
The first number on each line of output is the return value of
time.time() when the program first started (and this value never changes). The second number is the latest return value from
time.time() (this value keeps getting updated on each iteration of the loop). And the third number is the current time minus the start time. This third number is the number of seconds that have elapsed since the
begin = time.time() line of code was executed.
If this number is greater than 4, the code will start printing "PASSED WAIT TIME!" instead of "Not yet...". This is how our game program can know if a certain amount of time has passed since a line of code was run.
In our Tetromino program, the
time.time() – lastMoveSidewaysTime expression will evaluate to the number of seconds that has elapsed since the last time
lastMoveSidewaysTime was set to the current time. If this value is greater than the value in
MOVESIDEWAYSFREQ, we know it is time for the code to move the falling piece over one more space.
Don’t forget to update
lastMoveSidewaysTime to the current time again! This is what we do on line 7 [270].
Lines 9 [272] to 11 [274] do almost the same thing as lines 2 [265] to 7 [270] do except for moving the falling piece down. This has a separate move variable (
movingDown) and "last time" variable (
lastMoveDownTime) as well as a different "move frequency" variable (
MOVEDOWNFREQ). | https://eng.libretexts.org/Bookshelves/Computer_Science/Book%3A_Making_Games_with_Python_and_Pygame_(Sweigart)/08%3A_Tetromino/8.17%3A_Moving_by_Holding_Down_the_Key | CC-MAIN-2021-10 | refinedweb | 913 | 84.88 |
I will explore useful information I received from Karin – Principal Software Architect at Infor Product Development and technology evangelist at the Smart Office blog – in response to my ask for help with continuous integration of Mashups. Refer to my posts #1 and #2 for the backstory.
Disclaimer
I will be exploring web services and APIs that are internal to Smart Office, and not supposed to be used by anyone other than Infor Product Development. Also, they may change at any time in a future version. So use are your own risk.
No command line 😦
Karin confirmed “unfortunately there is no command-line support in LifeCycle Manager (LCM)”, at least not publicly available. And regarding the Velocity scripts, she said they “are only for applications so via LCM it is not possible to use command line.”
Bummer!
Use MangoServer, not LCM 🙂
She added “In the latest version of 10.2.1. you can consider using REST/Servlet upload to automatically upload Mashups. But that means that you will be managing them from outside of LCM from that time on which kind of leaves the installation you will be working on in a limbo since it will have old entries in LCM that you should never care about again. But it might still be worth the effort to remove all the mashups in LCM and manage them in the Management pages for the Mango Server. [The service] is internal as we use it from the Management pages it is not a real WS/REST service but grid internal.”
Waaaa? We can deploy directly to MangoServer and short-circuit LCM?
Web Services
I think Karin is referring to the /mangows Web Service used by the Mashup File Administration tool as identified with .NET Reflector and Fiddler:
I explored the various WSDL and found that InstallationPointManager has the method DeployMashup:
The method takes two input parameters: Name takes the Mashup’s filename+extension (e.g. Thibaud.mashup), and MashupFile takes the Base64-encoding of the Mashup’s binary contents; I use the bash command $ base64 -w 0 Thibaud.mashup or whatever Base64 encoding tool, and make sure to copy/paste the result as a single line:
The web service adds the Mashup to the MangoServer database:
Finally, we restart Smart Office, and we can now use the Mashup:
FANTASTIC! I can easily write a command line that calls the web service.
Note 1: We can keep calling the web service to deploy new versions of the Mashup, and it will override the old version with the new versions; good.
Note 2: I could not find a web service to un-deploy a Mashup. So if we need to remove a Mashup, I guess we have to change the access to None in the Mashup File Administration tool; to be tested.
Note 3: The web service will always return the same response regardless of if it succeeded or not. I had to turn on the DEBUG and TRACE log levels of the MangoServer application and of other Grid applications to get the details I needed:
Note 4: I think you have to be in the MangoServer/Administrator role:
To LCM, or not to LCM?
As Karin said, from now on that Mashup cannot be administered in LCM, it doesn’t even show in LCM:
We can still continue to use LCM to administer legacy Mashups and to upload new Mashups, as long as they don’t have the same name as the Mashups we deploy via the MangoServer web service. That’s mixed administration. Now we have the choice of how to administer Mashups: either we administer them all in LCM as before, either we administer them all in MangoServer with the web service, in which case it’s probably best to un-register the legacy Mashups from LCM to avoid confusion, either we administer them mixedly, in which case it will probably be confusing.
UPDATE 2016-06-06: Karin said it is very important to remove Mashups from LCM and only manage them via Smart Office if that is what we decide to do.
MangoAdmin
Karin adds: “[You can] use the MangoAdmin tool to import mashups files. But since they require a metadata file with table entries it’s a bit too much work to do them manually. But it is an alternative if you create one zip and then import against different environments. But it needs to be in the UI to be able to upload the file. There is a command line version but it requires the zip to already be uploaded to the server in the MangoData/Import folder. With the Mango Admin tool I mean the stand alone tool (exe) that is found in the download zip. It has one UI version and one command line exe version.”
I could not find said MangoAdmin tool. I found some tools in the Smart Office SDK but they do not take Mashups as input nor output: InforApplicationBuilder.exe:
UPDATE 2016-06-06: The Mango Admin Tool is explained at,
Instead, I decompiled the Mashup Designer again, and replicated how it generates the Mashup file:
It calls the method Mashup.Designer.DeploymentHelper.SaveMashupFile which calls the private method ValidateManifest and the public method CreatePackageFromManifest:
Here is the source code to do the same:
import System.IO; import System.Reflection; import Mango.UI.Services.Mashup; import Mango.UI.Services.Mashup.Internal; import Mashup.Designer; package MForms.JScript { class Test { public function Init(element: Object, args: Object, controller : Object, debug : Object) { var manifest: ManifestDesigner = new ManifestDesigner(new FileInfo("C:\\Mashups\\ThibaudMashup.manifest")); DeploymentHelper.InvokeMember("ValidateManifest", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static, null, null, [manifest]); var defaultFileName: String = manifest.File.Directory + "\\" + manifest.DeploymentName + Defines.ExtensionMashup; var packageFile: FileInfo = new FileInfo(defaultFileName); Mango.UI.Services.Mashup.Internal.PackageHelper.CreatePackageFromManifest(manifest, manifest.File, packageFile, PackageHelper.DeployTarget_LSO); var message: String = "Please note that this Mashup contains a profile section and should be deployed using Life Cycle Manager. Warning - Using the Mashup File Administration tool will not result in a merge of profile information into the profile."; if (manifest.GetProfileNode() != null) { debug.WriteLine(message); } } } }
FeatureServlet
Karin said of the latest Smart Office: “I looked around to see what we had to upload a .lawsonapp and we just added it to the HF that will be released now. Anyway we have added a upload servlet that needs to get a single file using: “A file upload request comprises an ordered list of items that are encoded according to RFC 1867, “Form-based File Upload in HTML”. FileUpload can parse such a request and provide your application with a list of the individual uploaded items.” You post a file to /FeatureServlet and then it will be uploaded. You need to be a Smart Office administrator to do this. This servlet is completely new so if you browse to /mango/FeatureServlet and get HTTP 404 you don’t have it. No documentation available.”
My server does not have that hotfix so that’s future work.
Future work
Next time I will:
- Call the MangoServer web service from a command line
- Transform the script into a command line
- Explore the Mango Admin tool
- Explore the FeatureServlet of the latest Smart Office hotfix
Conclusion
I now have a solution to deploy Mashups via a web service. It short-circuits LifeCycle Manager and deploys directly to the MangoServer, so we have to decide how to administer Mashups from that point forward. Also, I have a solution to generate the Mashup files from the manifest, with validation and metadata. That’s all I need for my goal of a command line. Next time I will do the command line.
That’s it!
Please leave a comment below, slap a Like, follow this blog, share with your colleagues, and come write something.
Thank you Karin!!
Related posts
- Continuous integration of Mashups #1 – HELP WANTED!!
- Continuous integration of Mashups #2 – Reverse engineering
- Continuous integration of Mashups #3 – HELP GOTTEN!!
- Continuous integration of Mashups #4 – Command line
7 thoughts on “Continuous integration of Mashups #3 – HELP GOTTEN!!”
Note: To un-deploy a Mashup, maybe we can use Mango.Core.ApplicationInstallerService.Uninstall(string name); to be tested
UPDATE: I moved the disclaimer to the top, and I added Karin’s update about the importance of removing Mashups from LCM if we decide to administer them in Smart Office.
UPDATE: I added the link to the Mango Admin Tool; for future work | https://m3ideas.org/2016/06/02/continuous-integration-of-mashups-3-help-gotten/?shared=email&msg=fail | CC-MAIN-2021-43 | refinedweb | 1,400 | 52.7 |
From: Reggie Seagraves (reggie_at_[hidden])
Date: 2000-01-18 18:24:24
Ladies and Germs,
The following doesn't seem to work with the latest
MW Codewarrior tools.....
Is this a known problem, unknown problem, or, am I smokin' crack?
#include <boost/array.hpp>
static void test_boost() {
static int r[] = { 5, 4, 3, 2, 1, 0 } ;
cout << *(boost::begin(r)) << flush;
}
Error : function call 'begin(int *)' does not match
'boost::begin(T0 &)'
'boost::begin(T0[{targ_expr}] &)' // seems to me it should
match this!!!
CoreTest.cp line 419 cout << *(boost::begin(r)) << flush;
My theory, (ahem), is this.....
MW Codewarrior compiler is losing the 'arrayness' of 'r' as SOON as
you pass it as a function parameter (without matching the function
template parameters first).
Thanks ahead of time,
Reggie.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2000/01/1859.php | CC-MAIN-2020-05 | refinedweb | 150 | 67.25 |
Sergey Matveychuk <address@hidden> writes: > Here is a third version. Great! After reading your patch I found some other problems, sorry for not looking good enough the first time. Most problems I found are minor nitpicks. If it is ok for Okuji I can make the changes I proposed (and have a quick look at the changelog entry) and commit the patch. > -- > Sem. > diff -ruNp grub2/ChangeLog grub2.test/ChangeLog > --- grub2/ChangeLog Fri Mar 19 23:55:21 2004 > +++ grub2.test/ChangeLog Sat Mar 20 01:38:47 2004 > @@ -1,3 +1,19 @@ > +2004-03-15 Sergey Matveychuk <address@hidden> > + > + * util/i386/pc/biosdisk.c: Added headers for BSD. Please say exactly what header files you are including. > + (pupa_util_biosdisk_get_pupa_dev): Do not call Please end a sentence with a ".". > + make_device_name(drive,-1-1) if not a block device. > + * util/i386/pc/getroot.c: Update copyright. No need to notice the copyright update when changing years. It is only required when changing the copyright holders (Correct me if I am wrong). > + (find_root_device): Do not check for a block device. > + * util/misc.c: Include malloc.h only if it's needed. > + (pupa_memalign): Change memalign() with malloc() where unavailable. > + * util/pupa-emu.c: Include malloc.h only if it's needed. > + (main): Move pupa_util_biosdisk_init() above pupa_guess_root_device(). I do not see the configure.ac changes in the changelog entry. Same for including config.h in misc.c. This is only what I noticed at first. Please make sure the changelog entries are complete. > -/* Define it to \"addr32\" or \"addr32;\" to make GAS happy */ > +/* Define it to "addr32" or "addr32;" to make GAS happy */ Why are you doing this? I assume this is what the autotools generated? > -/* Define it to \"data32\" or \"data32;\" to make GAS happy */ > +/* Define it to "data32" or "data32;" to make GAS happy */ Same here. > +AC_CHECK_HEADER(malloc.h) > +AC_CHECK_FUNC(memalign) This is what I meant, great! > +#if !defined(__FreeBSD__) > if (! S_ISBLK (st.st_mode)) > return make_device_name (drive, -1, -1); > +#endif make_device_name does not have to be called at all? > -#elif defined(__GNU__) > - /* GNU uses "/dev/[hs]d[0-9]+(s[0-9]+[a-z]?)?". */ > +#elif defined(__GNU__) || defined(__FreeBSD__) || defined(__NetBSD__) || > defined(__OpenBSD__) > + /* GNU uses "/dev/[ahsw]d[0-9]+(s[0-9]+[a-z]?)?". */ Is this comment correct? It says something about GNU, now you changed the regexp. so it matches *BSD as well. Thanks, Marco | http://lists.gnu.org/archive/html/grub-devel/2004-03/msg00039.html | CC-MAIN-2015-06 | refinedweb | 394 | 71 |
does not execute action listener
Splash › Forums › PrettyFaces Users › does not execute action listener
This topic contains 22 replies, has 4 voices, and was last updated by
Christian Kaltepoth 5 years, 6 months ago.
- AuthorPosts
I have started with prettyfaces yesterday.
And today I have very stupid problems.
I have big register form and this button at the bottom
<h:commandButton
Everything was working very well before. But yesterday I embedded pretty-confg.xml and it stopped working
registerBacking.create is not called at all !!!. This method should persist new user and navigate him to secured
page causing FORM based authentication to redirect him to login.xhtml. There can’t be validation or conversion error.
Method registerBacking.create is not called because the first line is print statement which never appears in server.log
The second problem is that when unauthrised user accesses any secured page user is not redirected
to login.xhtml by container security mechanism but is sent directly to that secured page.
ALL this was working very well before I embedded prettyfaces.
Please tell me what to do?
Hi. Could you please tell us which version of PrettyFaces you are using and post you
pretty-config.xmland
web.xml. Thanks.
Hello!
Thank you for reply!
In pom.xml I have:
<dependency>
<groupId>com.ocpsoft</groupId>
<artifactId>prettyfaces-jsf2</artifactId>
<version>3.3.3</version>
</dependency>
I have resolved security issues by specifying url-pattern in security-constraint to be the same as ‘pattern’ processed by
PrettyFilter.!
My pretty-config.xml looks as follows:
<?xml version="1.0" encoding="UTF-8"?>
<pretty-config xmlns=""
xmlns:xsi=""
xsi:
<url-mapping
<pattern value="/" />
<view-id
<action>#{user.notifyUserOfActivation}</action>
</url-mapping>
<url-mapping
<pattern value="/login" />
<view-id
<action>#{user.redirectLoggedInUser}</action>
</url-mapping>
<url-mapping
<pattern value="/guest" />
<view-id
<action>#{user.logout}</action>
</url-mapping>
<url-mapping
<pattern value="/register" />
<view-id
</url-mapping>
<url-mapping
<pattern value="/myProfile" />
<view-id
</url-mapping>
<url-mapping
<pattern value="/forums" />
<view-id
</url-mapping>
<rewrite match="/forum.xhtml" substitute="/prettyurl" redirect="301" />
<url-mapping
<pattern value="/#{forumId}">
<!--<validate index="0" validatorIds="shortConverter" onError="pretty: home" />-->
</pattern>
<view-id
</url-mapping>
<url-mapping
<pattern value="/newTopic">
</pattern>
<view-id
</url-mapping>
</pretty-config>
I recollected that also this line causes my page not to be rendered:
<validate index="0" validatorIds="shortConverter" onError="pretty: home" />
I type /forums/2 and instead to receive page that displays topics in forum with id=2 I have pretty: home.
By shortConverter is really simple :
@FacesConverter(value = "shortConverter",forClass=Short.class)
public class ShortConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null) {
return value;
}
Short shortValue;
try {
shortValue = Short.valueOf(value);
} catch (NumberFormatException e) {
System.out.println("ShortConverter.getasobject=" + e);
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleBean.getString("age_notvalid"), JavaHelpConstants.HIDE_MESSAGE.toString()));
}
if (value.length() > 2) { //this should not happen
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, LocaleBean.getString("age_toolong"), JavaHelpConstants.HIDE_MESSAGE.toString()));
}
return shortValue;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return null;
}
if (value instanceof Short) {
return value.toString();
}
Logger.getLogger("shortconverter").info("GETASSTRING exception in shortconvertern");
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Internal error! Converted value is not of type Short", JavaHelpConstants.HIDE_MESSAGE.toString()));
}
}
Without this validator everything works as expected.
Lincoln Baxter IIIKeymaster
If you debug the validator, what is causing it to fail validation?
About shortConverter
[#|2012-12-06T21:30:58.359+0200|SEVERE|glassfish3.1.2|javax.enterprise.resource.webcontainer.jsf.application|_ThreadID=117;_ThreadName=Thread-9;|JSF1005: Cannot instantiate validator of type shortConverter|#]
BUT now my main problem is!
I have made sure that action method is not invoked solely because of this mapping in pretty-config.xml
<url-mapping id=”register” onPostback=”false”>
<pattern value=”/register” />
<view-id value=”/register.xhtml” />
</url-mapping>
After I commented out this mapping my register form is submitting data as expected. The problem is just in this mapping.
What can I do here?
I don’t see any reason why postbacks shouldn’t work any more when using a pretty URL. I never had this kind of problem.
The typical root cause for action methods not being invoked any more is that some parent component of the button is
rendered="false"when the postback is processed. Mostly this happens because request scoped beans lost their values. But you wrote that you are using view scope, right? You could (just for a test) set the scopes of all beans used by the page to
sessionand try it again. If it works with this change, it is usually a scoping issue.
A strategy that I sometimes use to debug theses problems is to add a special PhaseListener implementation to my application that logs the start and end of each JSF phase. By looking at the logs one can then easily see, if the request processes the INVOKE_APPLICATION phase at all. If not, it is usually some kind of problem in the validation phase.
I hope this helps a bit.
Perhaps it is possible for you to trim down you app or create a minimal application that reproduces this issue? In this case I could have a look at your code.
Hello!
I set up phase listener which is simplest. It is registered in faces-config.xml and the path is correct !!!
This listener is not invoked on any phase. Logger does not log anything.
How can it be?
Next, WITHOUT that register mapping in pretty-config.xml action method is invoked and I am redirected to correct page and data is persisted( it is exactly) regardless of browser notification.
BUT there is one thing to note. After I click that register button I have (but not always) notification from browser:
httpError: Http Transport returns a 0 transport code. This is usually the result of mixing ajax and full requests. This is usually undesired both for performance and data integrity reasons!
As I understand some error occurred. I don’t know what else to check but this error still occurs.
I set up try catch where something bad can happen. Nothing is logged about any error!
How can I catch the error because of which that notification appeares?
Please, help poor beginner!
There is something weird going on in your app.
Are you using the correct logger in your phase listener? It’s really very strange, that your phase listener isn’t working at all. You could test it by replacing your log statements with something like System.out.println().
Regarding the error you are getting. I never saw this message before. You should try to find out what this message really means. There seem to be many posts on the net regarding this, like:
PrettyFaces is good and good!
That notification from browser was because my whole form is cramped up with ajax calls.
But submit button sends the full form through full request not partial( <f:ajax>).
This caused two rquests to be mixed. I found solution at
After I changed my command button to
<h:commandButton id=”registerButton” class=”registerButton” value=”Register” type=”submit” action=”#{registerBacking.create}”>
<f:ajax render=”@form” />
</h:commandButton>
everything is working well. New user is persisted and I am redirected finally to needed page after register form.
When I commented away my register mapping in pretty-config.xml I still had that notification but application was working
well !!!
Why did phase listener log nothing I don’t want to say!
Can I ask you one more question?
How to allow mapping in pretty-config.xml to be used only within my site but not from path typed in browser
If user clicks link on my site this mapping is called, but this mapping is not called if user types path that matches pattern of the same mapping !!!
Thank you!
Nice to hear you fixed you first problem.
But I’m not sure I understand your second question correctly. Do you want that a certain URL doesn’t work when it is manually entered into the browser bar but it should work when a link within your application is clicked?
There is not way for PrettyFaces to distinguish between the two kind requests. I doubt that something like this makes sense. The only way to implement something like this would be to manually check the “Referer” header.
It makes sense!
I have this command link that should assign forumBacking.forumName property with needed forum’s name
<h:commandLink
<f:setPropertyActionListener
</h:commandLink>
When I click this link I have correct forum name assigned to forumBacking.forumName . But I want to move to next page clicking this link without passing any parameters. I have mapping in pretty-config
<url-mapping
<pattern value="/" />
<view-id
</url-mapping>
This mapping is bad because it matches parent_mapping(forums) + “/”. It means that user types in browser bar what matches and receives nothing because forumBacking.forumName is null .
I dont’ want to pass forum.name as a parameter because moderator on javaranch told me:
<qoute>Passing parameters on the View is something that should be avoided. So is using an object locator.
In JSF, the preferred way to pass objects around is to keep them in Managed Beans and inject them as Managed Properties into the beans that use them. It makes for less network traffic (objects don’t have to be serialized out and back), more security (nothing exposed to the client side where it can be hacked), and simpler coding. </qoute>
- AuthorPosts
You must be logged in to reply to this topic. | https://www.ocpsoft.org/support/topic/does-not-execute-action-listener/ | CC-MAIN-2018-39 | refinedweb | 1,595 | 50.73 |
This section documents all changes and bug fixes applied since the release of 5.2.19.
Functionality Added or Changed and can be changed to
UNIQUE or other types.
Although the artificial
FOREIGN index type
has been removed, MySQL Workbench still automatically creates and
maintains indexes for each foreign key by naming them after the
keyname and keeping the names (FK to IDX) synchronized.
(Bug #48728)
Bugs Fixed)
In the Snippets tab of the SQL Editor, there appeared to be a third column, with no heading or data, in the snippets list. MySQL Workbench now expands the second column to fill the available space. (Bug #52559))
In the SQL Editor, field data of type
VARBINARY viewed using the context-sensitive menu item was
displayed only up to the first null byte (\0).
(Bug #52954) Variables tab of the Administrator, variables with long descriptions were not displayed correctly. They appeared wrapped to a new line, and clipped by the height of the Description row. (Bug #53025)
Each time an Admin tab was started an
instance of
cscript.exe was executed.
However, when the Admin tab was closed the
corresponding
cscript.exe process was not
terminated. This resulted in ever increasing numbers of
cscript.exe processes, which consumed
resources unnecessarily, and constituted a resource leak.
(Bug #51601)
In the Export to Disk tab of the Administrator's Data Dump facility, selecting multiple schemata for export to a self-contained file resulted in this exception:
unhandled exception: local variable 'tables' referenced before assignment.
(Bug #52981)
If an SQL statement was selected in the SQL Statements area of the SQL Editor, and copied to the snippets list using thetoolbar button, then the statement was only partially saved, the beginning of the statement being missing.. (Bug #51474)
If a snippet was deleted from the Snippets tab in the SQL Editor, after MySQL Workbench was restarted the deleted snippet would reappear as if it had never been deleted. (Bug #51335, Bug #52558)
SQL Editor syntax highlighting did not correctly recognize
escaping of the single quote character ('). Queries such as
SELECT '\'' FROM DUAL; were therefore not
highlighted correctly.
(Bug #50324)
If multiple SQL Editor tabs were opened, closing the last one caused MySQL Workbench to crash. (Bug #53061)
Selecting multiple tables at the same time in the Overview tab of the SQL Editor caused MySQL Workbench to crash. (Bug #52922)
On Windows, if SQL Editor was using a named pipe connection, and the SQL Editor tab was closed, MySQL Workbench stopped responding to user input and had to be killed using the Task Manager. (Bug #53021)
When switching between Model Overview Page, and EER Diagram View, MySQL Workbench incorrectly rendered the EER Diagram View inside the Table Editor panel. (Bug #52778). (Bug #52433). (Bug #51495)
When using the Forward Engineer SQL Script wizard, if an existing script file was selected to be overwritten, the wizard would not continue, the file had to be deleted first. (Bug #46920)
If a schema was opened and an object editor, such as the Table Editor was opened, MySQL Workbench crashed if the schema was closed and immediately reopened. (Bug #53027)
When an EER Diagram was displayed, the Properties tab was empty. Also, if a table in the EER Diagram was selected, the Properties tab remained empty. (Bug #52971)
The MySQL Workbench make targets, with the exception of
make all, were broken by the file
ext/ctemplate/Makefile.
(Bug #51024)
The MySQL Workbench
configure.in configure
script contained a construct incompatible with NetBSD. The
script used
test == instead of
test
=.
(Bug #53175) Reverse Engineer Database wizard, on the Connection Options page, if the first empty connection was selected from the Stored Connection list, and then the Connection Method changed, the fields on the Parameters tab did not change accordingly. (Bug #51742)). (Bug #51141, Bug #52965)
MySQL Workbench crashed when the
root user,
located in the Server Access Management tab
of the Accounts facility in the Administrator, was clicked.
(Bug #50703)
MySQL Workbench failed to compile from source due to a missing
#include <stdarg.h> statement in the
file
library/sql-parser/include/myx_sql_tree_item.h.
(Bug #52919)
In the EER Diagram view, layer objects did not respond to edit commands (either double-clicking or using thecontext-sensitive menu option). (Bug #52822, Bug #52823)
In the Columns tab of the Table Editor, if a column was right-clicked on, and then selected, the column ordering was not updated within the Columns tab, until the area was clicked again. (Bug #51139)
When MySQL Workbench was sized to 1280 x 800, the Export to Disk tab of the Data Dump facility. (Bug #52932)button was not visible in the
When building MySQL Workbench, the build process failed if the
--no-copy-dt-needed-entries linker option was
specified (this happens by default when building on Fedora 13).
(Bug #52918)
The HUD blocked access to other applications that were running. This was particularly a problem when Administrator or SQL Editor were launched from the Home screen, and took a long time to load. (Bug #53006)
The MySQL Workbench dependency on
libmysqlclient
has changed to use version 16 of the library rather than 15.
(Bug #52682) | http://docs.oracle.com/cd/E17952_01/workbench-relnotes-en/wb-news-5-2-20.html | CC-MAIN-2014-10 | refinedweb | 858 | 59.84 |
If the sensor input changes (e.g. from FTFF to FTTF) I want to change which image the pi displays. This works. But if the sensor input doesn't change in the time it takes to loop through my function, i just want it to keep the existing image displayed. They way it is working right now, it will close out the image and reopen it. I can't figure out where the issue is exactly. But I've tracked the issue down to the fact that it seems like each loop it seems to think that it didn't get a serial input (initially), so it enters the "close image" else clause before getting the serial input. I think this is related to having/not having a buffer for serial set up correctly, but I don't understand the serial read well enough. Any help would be much appreciated. Code below, let me know if I left any important details out. Thanks!
Code: Select all
def touchPic (sensor1, sensor2, sensor3, sensor4, sensorCase, picPath): import os import time import serial #check sensor values if sensor1 and sensor2 and sensor3 and sensor4: if sensorCase != 1: #only enter the image open function if status is different than previous status os.system("sudo pkill fbi") os.system("sudo fbi -a -T 2" + picPath + "testpic" + "all" + ".png") sensorCase = 1 elif sensor1 and sensor2 and sensor3 and not sensor4: if sensorCase != 2: os.system("sudo pkill fbi") os.system("sudo fbi -a -T 2" + picPath + "testpic" + "123" + ".png") sensorCase = 2 elif sensor1 and sensor2 and sensor4 and not sensor3: if sensorCase != 3: os.system("sudo pkill fbi") os.system("sudo fbi -a -T 2" + picPath + "testpic" + "124" + ".png") sensorCase = 3 #... continue for all cases... time.sleep(.3) picPath = " /home/pi/Pictures/" ser = serial.Serial('/dev/ttyUSB0', 9600) if (ser.in_waiting > 0): #read the serial data from arduino. Set cases based on T/F inputs line = str(ser.readline().strip()) sensor1status = line[0] sensor2status = line[1] sensor3status = line[2] sensor4status = line[3] if sensor1status == "T": sensor1 = True elif sensor1status == "F": sensor1 = False if sensor2status == "T": sensor2 = True elif sensor2status == "F": sensor2 = False if sensor3status == "T": sensor3 = True elif sensor3status == "F": sensor3 = False if sensor4status == "T": sensor4 = True elif sensor4status == "F": sensor4 = False if sensor1 or sensor2 or sensor3 or sensor4: (sensor1, sensor2, sensor3, sensor4) = escapeFunctions.touchPic(sensor1, sensor2, sensor3, sensor4, sensorCase,picPath) else: #if no serial data to read, then close out of the image, set all values to false, and exit function #code seems to run this every loop even though serial data should be coming in constantly... os.system("sudo pkill fbi") time.sleep(5) sensorCase = 0 sensor1 = False sensor2 = False sensor3 = False sensor4 = False return (sensor1, sensor2, sensor3, sensor4) #time.sleep(1) #os.system("sudo pkill fbi") | https://www.raspberrypi.org/forums/viewtopic.php?f=32&t=241245&p=1475048 | CC-MAIN-2019-47 | refinedweb | 464 | 57.37 |
This is my little piece of code. I'm a little rusty, so I don't remember
how to do this 100%. But basically, the below example will allow to
enter a string up to 100 chars, output it and just for kicks, turn it into
a string class object.
It works, but it can be improved on.
Now, my question is this, would there be a way that would liberate me
from the C character array?
I tried this example (all the way at the bottom) in my VC++ 2010 andI tried this example (all the way at the bottom) in my VC++ 2010 andCode:#include <iostream>#include <ios> #include <limits> using namespace std; int main(int argc, char * argv[]) { char testString[100]; std::cout << "Please enter a string: "; std::cin.getline(testString, 100); cout << "This is the string that you entered: " << testString << std::endl << std::endl; std::string simpleString(testString); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin.get(); return 0; }
when I typed in getline, my IDE told me the following:
:-/:-/Error: no instance of 'getline' matches the argument list | http://cboard.cprogramming.com/cplusplus-programming/154691-there-better-way-do-string-input-cplusplus-via-standard-input.html | CC-MAIN-2016-07 | refinedweb | 186 | 70.02 |
Python alternatives for PHP functions
>>>class MyClass:
i = 3
>>> print MyClass.i
3
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
class C:
@staticmethod
def f(arg1, arg2, ...): ...
Declaring class members or methods as static makes them accessible
without needing an instantiation of the class. A member declared as
static can not be accessed with an instantiated class object (though
a static method can).
For compatibility with PHP 4, if no visibility
declaration is used, then the member member example
<?phpclassprint Bar::$my_static . "\n";$bar = new Bar();print $bar->fooStatic() . "\n";?>
Example #2 Static method example
<?phpclass Foo { public static function aStaticMethod() { // ... }}Foo::aStaticMethod();$classname = 'Foo';$classname::aStaticMethod(); // As of PHP 5.3.0?> | http://www.php2python.com/wiki/language.oop5.static/ | CC-MAIN-2018-22 | refinedweb | 117 | 53.58 |
#include <wx/protocol/>
wxFTP can be used to establish a connection to an FTP server and perform all the usual operations.
Please consult the RFC 959 () for more details about the FTP protocol.
wxFTP can thus be used to create a (basic) FTP client.
To use a command which doesn't involve file transfer (i.e. directory oriented commands) you just need to call a corresponding member function or use the generic wxFTP::SendCommand() method. However to actually transfer files you just get or give a stream to or from this class and the actual data are read or written using the usual stream methods.
Example of using wxFTP for file downloading:
To upload a file you would do (assuming the connection to the server was opened successfully):
Default constructor.
Destructor will close the connection if connected.
Aborts the download currently in process, returns true if ok, false if an error occurred.
Implements wxProtocol.
Change the current FTP working directory.
Returns true if successful.
Send the specified command to the FTP server.
ret specifies the expected result.
Gracefully closes the connection with the server.
Reimplemented from wxSocketBase.
Connect to the FTP server to default port (21) of the specified host.
Connect to the FTP server to any port of the specified host.
By default (port = 0), connection is made to default FTP port (21) of the specified host.
Returns true if the given remote file exists, false otherwise.
But on Windows system, it will look like this:
winamp~1 exe 520196 02-25-1999 19:28 winamp204.exe 1 file(s) 520 196 bytes.
This function returns the computer-parsable list of the files in the current directory (optionally only of the files matching the wildcard, all files by default).
This list always has the same format and contains one full (including the directory path) file name per line.
Creates a new input stream on the specified path.
You can use all but the seek functionality of wxStreamBase. wxStreamBase::Seek() isn't available on all streams. For example, HTTP or FTP streams do not deal with it. Other functions like wxStreamBase::Tell() are not available for this sort of stream, at present.
You will be notified when the EOF is reached by an error.
Implements wxProtocol.
Returns the last command result, i.e.
the full server reply for the last command.
Initializes an output stream to the specified file.
The returned stream has all but the seek functionality of wxStreams. When the user finishes writing data, he has to delete the stream to close it.
Create the specified directory in the current FTP working directory.
Returns true if successful.
Returns the current FTP working directory.
Rename the specified src element to dst.
Returns true if successful.
Remove the specified directory from the current FTP working directory.
Returns true if successful.
Delete the file specified by path.
Returns true if successful.
Send the specified command to the FTP server and return the first character of the return code.
Sets the transfer mode to ASCII.
It will be used for the next transfer.
Sets the transfer mode to binary.
It will be used for the next transfer.
If pasv is true, passive connection to the FTP server is used.
This is the default as it works with practically all firewalls. If the server doesn't support passive mode, you may call this function with false as argument to use an active connection.
Sets the password to be sent to the FTP server to be allowed to log in.
Reimplemented from wxProtocol.
Sets the transfer mode to the specified one.
It will be used for the next transfer.
If this function is never called, binary transfer mode is used by default.
Sets the user name to be sent to the FTP server to be allowed to log in.
Reimplemented from wxProtocol. | http://docs.wxwidgets.org/3.0.3/classwx_f_t_p.html | CC-MAIN-2017-51 | refinedweb | 638 | 69.07 |
Introduction
In this tutorial, the third installment of the SpriteKit From Scratch series, we take a detailed look into the physics simulation functionality of SpriteKit and how this can be utilized in your 2D SpriteKit games.
This tutorial requires that you are running Xcode 7.3 or higher, which includes Swift 2.2 and the iOS 9.3, tvOS 9.2, and OS X 10.11.4 SDKs.
To follow along, you can either use the project you created in theprevious tutorial or download a fresh copy from GitHub .
The graphics used for the game in this series can be found on GraphicRiver . GraphicRiver is a great source for finding artwork and graphics for your games.
1. Physics Worlds
The first part of any physics simulation in SpriteKit is the
physicsWorld property of the current scene. This property is an
SKPhysicsWorld object that defines properties such as your scene’s gravity, speed of physics simulation, and contact delegate. Physics worlds can also define joints between objects to effectively pin multiple nodes together at specific points.
Gravity
For the top view style game we are creating in this series, we want to change the default gravity value provided by SpriteKit. The default gravity is intended for a front view game with a value of (0, -9.8) which simulates Earth’s gravity, that is, 0 horizontal acceleration and a downwards acceleration of 9.8m/s² . For our game, we need 0 vertical gravity so that the car doesn’t start accelerating downwards once we set its physics properties.
Open MainScene.sks and click the grey background to select the scene. Next, open the Attributes Inspector and change Gravity so that both the X and Y components are set to 0 .
It is important to note that gravity is the only physics world property that can be changed using Xcode’s scene editor. Any other properties need to be changed programmatically.
Contact Delegate
In order for the game to detect collisions between objects, we need to set the scene’s physics world’s
contactDelegate property. This delegate can be any object that conforms to the
SKPhysicsContactDelegate protocol. This protocol defines two methods,
didBeginContact(_:) and
didEndContact(_:) . You can use these methods to perform actions based on the objects that are colliding in the scene.
To keep our code together, we are going to make the
MainScene instance its own contact delegate. Open MainScene.swift and edit the
MainScene class definition to conform to the
SKPhysicsContactDelegate protocol.
import UIKit import SpriteKit class MainScene: SKScene, SKPhysicsContactDelegate { ... }
In
didMoveToView(_:) , we set the
MainScene instance as the contact delegate of the
physicsWorld property.
override func didMoveToView(view: SKView) { ... physicsWorld.contactDelegate = self }
We will implement the methods of the
SKPhysicsContactDelegate protocol later. We first need to set up the physics properties of the nodes in the scene.
2. Physics Bodies
Any node in SpriteKit that you want to simulate physics on in some way must be assigned a unique
SKPhysicsBody object. Physics bodies contain several properties including:
- mass
- density
- area
- friction
- velocity
In your games, you can also define up to 32 unique categories and a physics body can be assigned to any number of these categories. Categories are very useful for determining which nodes in your scene can interact with each other in terms of collisions.
On physics bodies, these categories are represented by the
categoryBitMask and
collisionBitMask properties, which are both given the 0xFFFFFFFF value by default. This means that all nodes belong to all categories. It is important to note that in this value, each hexadecimal digit F is a shorthand form and represents the number 15 in binary digits ( 1111 ) each of which correspond to one of the 32 categories you can use.
When two nodes collide, a logical
AND operation is performed on the
collisionBitMask and the
categoryBitMask of the first and second body respectively. If the result is a non-zero value, then SpriteKit performs its simulation on the two nodes the bodies belong to.
Note that this
AND calculation is performed twice with the two bodies swapped around. For example:
- Calculation 1:
bodyA.collisionBitMask & bodyB.categoryBitMask
- Calculation 2:
bodyB.collisionBitMask & bodyA.categoryBitMask
If you don’t know how an
AND operator works, then here is a very simple example written in Swift:
let mask1 = 0x000000FF let mask2 = 0x000000F0 let result = mask1 & mask2 // result = 0x000000F0
The
AND operator determines which parts of the bit masks are the same and returns a new bit mask value containing the matching parts..
In order for these methods to be executed, you must specify a
contactTestBitMask for each body, which produces a non-zero value when an
AND operator acts on them. For all physics bodies, this bit mask has a default value of 0x00000000 meaning that you will not be notified of any collisions that the physics body takes part in.
Physics bodies, including their various bit masks, can be set up in the Xcode scene editor. Open MainScene.sks , select the car, and open the Attributes Inspector on the right. Scroll down to the Physics Definition section.
Because Body Type is set to None , none of the properties related to physics are visible. To change this, we need to set Body Type to a value other than None . Three body types are available:
- bounding rectangle
- bounding circle
- alpha mask
These three physics body types are the most common in SpriteKit. Bounding rectangle and Bounding circle work by creating a barrier around the sprite to be used in physics simulations. This means that the sprite collides with another node whenever its bounding shape hits another node’s physics body.
The edge of a bounding rectangle is exactly the same as the node’s size shown in the scene editor. If you select Bounding circle , however, you see a thin light blue circle representing the shape of the bounding circle.
Alpha maskworks.
For our game, since we are only using one car sprite and our scene is not particularly complex, we are going to use the Alpha mask body type. It is not recommended to use this body type for all sprites in your scene even though it is the most accurate. When you select this option from the drop down menu, you should see a light blue line appear around the edge of the car.
It is important to note that other types of physics bodies can be created programmatically, such as bodies from
CGPath objects as well as circles and rectangles of custom sizes.
Still in the Attributes Inspector , you should now see more options available to you in the Physics Definition section. The only property we need to change is the Contact Mask . Change this to a value of 1 .
With the car’s physics body set up, we can start putting some obstacles into the game to collide with the car.
3. Detecting Collisions
Before we implement the methods of the
SKPhysicsContactDelegate protocol, we need to add some obstacles for the car to avoid. To do this, we are going to spawn a new obstacle every three seconds in front of the car and position the obstacle in a random lane.
Open MainScene.swift and add an import statement for the GameplayKit framework so we can use the random number generators provided by GameplayKit.
import GameplayKit
Next, add the following method to the
MainScene class:) }
This method is invoked every three seconds. Let’s break it down to see what is going on. If the current player node is hidden, which is true when the car hits an obstacle, then we invalidate the timer and stop spawning obstacles.
We obtain a random number between 1 and 2 , and use this to create a sprite node with one of the two obstacle sprites available in the project. We then change the obstacle’s scale so that they are small enough for the car to manoeuvre around.
Next, we create a physics body for this new obstacle with a circle with a radius of 15 and a contact mask of 0x00000001 . We set
pinned to
true and
allowsRotation to
false so that the obstacle stays in place and doesn’t move. The physics body is then assigned to the obstacle.
We generate another random number between 1 and 3 to determine which lane the obstacle should be placed in and give the obstacle its calculated position, adding it to the scene.
Note that the horizontal difference, 85 , used in
spawnObstacle(_:) is different from the one used when moving the car, 70 . We do this to allow for a bit more space for the car to move between obstacles.
With the obstacle spawning logic in place, we can add the following code to the end of the
didMoveToView(_:) method. }
We create a timer to execute
spawnObstacle(_:) every three seconds and add it to the main run loop. We also create an
SKCameraNode to act as the camera for the scene and assign it to the
camera property of the scene. This causes the scene to be rendered from this camera node’s point of view. Note that the camera is centered horizontally and slightly above the car..
The last part for collision detection is implementing either one of the
SKPhysicsContactDelegate protocol methods. In our case, we are going to implement the
didBeginContact(_:) method as we want to be notified as soon as the car hits an obstacle. Add the following method to the
MainScene class.
func didBeginContact(contact: SKPhysicsContact) { if contact.bodyA.node == player || contact.bodyB.node == player { player.hidden = true player.removeAllActions() camera?.removeAllActions() } }
You can see that this method has one
SKPhysicsContact parameter passed to it. This object contains key information about the collision, including its direction, impulse, and the objects involved.
In this code, we are only concerned about which nodes are involved in the collision. We check to see whether either of them was the car and, if true, hide the car in the scene and end the movement of the car and camera.
Build and run your app and play your game. You will see that, when you run into an obstacle, the car disappears and the scene stops moving.
Conclusion.
In the next tutorial of SpriteKit From Scratch , we are going to look at the more advanced visual functionality in SpriteKit, including particle systems, lights, and filters.
As always, be sure to leave your comments and feedback » SpriteKit From Scratch: Physics and Collisions
评论 抢沙发 | http://www.shellsec.com/news/17110.html | CC-MAIN-2017-22 | refinedweb | 1,743 | 62.17 |
Created on 2018-06-30 06:58 by ncoghlan, last changed 2018-07-24 13:39 by ncoghlan. This issue is now closed.
In the current documentation, Py_Main is listed as a regular C API function:
We also didn't add Py_Main() to when we did the review for "Functions which are safe to call before Py_Initialize()".
If it truly is a regular C API function, then this suggests that Py_Main() should be called *after* Py_Initialize().
However, Py_Main() has historically called Py_Initialize() *itself*, and generally assumes it has total control over management of the current process - it doesn't expect to be sharing the current process with an embedding application.
In Python 3.7, Py_Main() was changed to call _Py_InitializeCore() and _Py_InitializeMainInterpreter() as separate steps, allowing it to detect cases where an embedding application had already called Py_Initialize(), meaning that Py_Main()'s config setting changes wouldn't be applied.
In effect, we've converted a silent failure (settings not read and applied as expected) into a noisy one (attempting to call Py_Main() in an already initialised interpreter).
(The test suite is silent on the matter, since the idea of an embedding application calling Py_Initialize() before calling Py_Main() never even occurred to us)
So the question is, what should we do about this for Python 3.7:
1. Treat it as a regression, try to replicate the old behaviour of partially (but not completely) ignoring the config settings read by Py_Main()
2. Treat it as a regression, but don't try to replicate the old config-settings-are-partially-applied behaviour - just ignore the settings read by Py_Main() completely
3. Treat it as a long standing documentation error, update the docs to make it clear that Py_Main() expects to handle calling Py_Initialize() itself, and update the Python 3.7 porting guide accordingly
This hits fontforge. See
An example of how it should be handled there if 3) is selected would be greatly appreciated. Thanks
Even if it's ugly, calling Py_Main() after Py_Initialize() works in Python
3.6 by ignoring the new config of Py_Main(). I suggest to do nothing (just
return) when Py_Initialize() is called again by Py_Main() in Python 3.7. It
would fix the fontforge *regression*.
I suggest to only enhance the code (really apply the new Py_Main() config)
in the master branch. From what I saw, apply the new config is not trivial.
It will take time to decide what to do for *each* option.
Yeah, I've asked Miro to try essentially that in
My concern is that Py_Main used to keep a *lot* of state on the local C stack that we've now moved into the main interpreter config.
So my suspicion is that even that change I've asked Miro to try may not do the right thing, but it really depends on *why* fontforge is calling Py_Main, and what they're passing in argc and argv.
Given that the embedded Py_Initialize is a no-op, they may be better off just copying out the parts they actually need from the code execution aspects of it, and skipping the Py_Main call entirely.
At the very least, I think this calls for a documentation change, such that we make it clear that:
1. The expected calling pattern is to call Py_Main() *instead of* Py_Initialize(), since Py_Main() calls Py_Initialize().
2. If you do call Py_Initialize() first, then exactly which settings that Py_Main() will read from the environment and apply is version dependent.
So I'll put together a docs patch that's valid for 3.6+, and then we can decide where to take 3.7 and 3.8 from an implementation perspective after that.
Currently, I'm thinking that for 3.7, our goal should specifically be "fake the 3.6 behaviour well enough to get fontforge working again" (so it will mostly be Fedora that drives what that 3.7.1 change looks like), while for 3.8 we should aim to deprecate that code path, and instead offer a better building block API for folks that want to implement their own Py_Main() variant.
Removing 3.6 from the affected versions, since we re-arranged these docs a bit for 3.7 to make it clearer which functions could be called prior to initialization, as well as adding more tests for the actual pre-init functionality.
Since 3.6 isn't going to change, and we'll be aiming to get back to something a bit closer to the 3.6 behaviour for 3.7.1, it seems simpler to just focus on 3.7 and 3.8.
My PR 8043 fix the Python 3.7 regression: allow again to call Py_Main() after Py_Initialize().
Nick: if you want to raise an error on that case, I would prefer to see a deprecation warning emitted in version N before raising an error in version N+1.
Technically, it seems possible to allow calling Py_Main() after Py_Initialize(). It's "just" a matter of fixing Py_Main() to apply properly the new configuration.
Aye, and I think from Miro's comments on your PR, making it apply some of the same configuration settings that 3.6 and earlier applied is going to be required to get fontforge working again for 3.7.
At the very least, the call to set sys.argv is needed.
Thinking about this some more, I'm inclined to go the same way we did with issue 33932: classify it as an outright regression, work out the desired requirements for a missing embedding test case, and then fix the implementation to pass the new test case.
My suggestion for test commands would be:
../Lib/site.py
-m site
-c 'import sys; print(sys.argv)' some test data here
Once those work properly, we'd consider the regression relative to Python 3.6 fixed.
Those could either be 3 different test cases, or else we could run them all within a single test case, with a Py_Initialize() call before each one (since Py_Main() calls Py_Finalize() internally).
I tested fontforge. It became clear to me that the fontforge must be able to call Py_Initialize() and only later call Py_Main(). fontforge calls Py_Initialize() and then uses the Python API:
/* This is called to start up the embedded python interpreter */
void FontForge_InitializeEmbeddedPython(void) {
// static int python_initialized is declared above.
if ( python_initialized )
return;
SetPythonProgramName("fontforge");
RegisterAllPyModules();
Py_Initialize();
python_initialized = 1;
/* The embedded python interpreter is now functionally
* "running". We can modify it to our needs.
*/
CreateAllPyModules();
InitializePythonMainNamespace();
}
Py_Main() is called after FontForge_InitializeEmbeddedPython().
To be clear, Py_Main() must be fixed in Python 3.7 to apply properly the new configuration, or *at least* define sys.argv.
> This hits fontforge. See
Copy of my comment 20:
I looked one more time to the issue:
* fontforge code is fine: it calls Py_Initialize() before using the Python C API to initialize its Python namespace (modules, functions, types, etc.), and later it calls Py_Main().
* Python 3.7.0 is wrong: it fails with a fatal erro when Py_Main() is called if Py_Initialize() has been called previously. It is a regression since it worked fine in Python 3.6.
* My PR works again the simplest test: "fontforge -script hello.py" where hello.py is just "print('Hello World!')"
* This PR is not enough according to Miro, since fontforge requires sys.argv to be set, whereas sys.argv is no longer set when Py_Main() is after Py_Initialize():
I looked one more time at Python 3.6, code before my huge Py_Main()/Py_Initialize() refactoring, before _PyCoreConfig/_PyMainInterpreterConfig have been added. In short, calling Py_Main() after Py_Initialize() "works" in Python 3.6 but only sys.argv is set: almost all other options are lost/ignored. For example, if you call Py_Initialize() you get a sys.path from the current environment, but if Py_Main() gets a new module search path: sys.path is not updated.
I modified PR 8043 to write the minimum patch just to fix fontforge. When Py_Main() is called Py_Initialize(): just set sys.argv, that's all.
If someone wants to fix this use case, apply properly the new Py_Main() configuration carefully, I would suggest to only work in the master branch: that's out of the scope of this specific regression.
IMHO it would be nice to enhance this use case. For example, it would be "nice" to update at least "sys.path" (and other related variables) in such case.
+1 from me for the idea of fixing Python 3.7 to correctly set sys.argv in this case (and leaving everything else unmodified).
As far as further enhancement in Python 3.8 goes, perhaps that can be seen as part of PEP 432, such that embedding applications have to explicitly opt-in to any new behaviour by calling the new APIs?
I created bpo-34170: "Py_Initialize(): computing path configuration must not have side effect (PEP 432)" as a follow-up of this issue.
New changeset fb47bca9ee2d07ce96df94b4e4abafd11826eb01 by Victor Stinner in branch 'master':
bpo-34008: Allow to call Py_Main() after Py_Initialize() (GH-8043)
New changeset 03ec4df67d6b4ce93a2da21db7c84dff8259953f by Victor Stinner (Miss Islington (bot)) in branch '3.7':
bpo-34008: Allow to call Py_Main() after Py_Initialize() (GH-8043) (GH-8352)
Ok, I fixed the fontforge bug in 3.7 and master branches. Sorry for the regression, but I really didn't expect that anyone would call Py_Main() after Py_Initialize() :-) I guess we should be prepared for such hiccup when reworking the Python initialization :-)
Nick: Can I close the issue, or do you want to keep it open to change the documentation?
Since we decided the correct resolution here was to restore the Python 3.6 behaviour, I've filed as a separate docs clarification issue (I'll amend my PR accordingly) | https://bugs.python.org/issue34008 | CC-MAIN-2021-49 | refinedweb | 1,614 | 64.81 |
Need help adding to collision detection algorithmOk thanks. I'll just come up with my own algorithm. :)
Need help adding to collision detection algorithmHello,
I'm using SFML, and I found this code for collision detection in SFML:...
C++ Programmer looking for teamI sent you an email from chuckleluck@gmail.com.
I'm a somewhat new programmer (started about 2-3 yea...
2-Dimensional Array not working?Thank you. I assumed that all variables started at 0.
2-Dimensional Array not working?I have this code:
[code]#include <iostream>
#include <conio.h>
using namespace std;
int main()...
This user does not accept Private Messages | http://www.cplusplus.com/user/Chuckleluck/ | CC-MAIN-2013-48 | refinedweb | 104 | 62.95 |
Using Windows Communication Foundation with Windows Workflow Foundation – Part 2
by Maurice de Beijer
August 2008
Both Windows Communications Foundation (WCF) and Windows Workflow Foundation (WF) were released at the same time as part of the .NET 3.0 release. But even though they were released together, they didn’t really work together. Fortunately, this shortcoming was rectified with the 3.5 release of the .NET Framework. In Part 1 of these articles I covered the SendActivity, which enables us to send requests from a workflow to a WCF-compatible service. In this second article, I will be taking a closer look at its companion, the ReceiveActivity.
Exposing workflows as Windows Communication Foundation services
As its name suggests, the ReceiveActivity is all about receiving requests into a workflow and thereby exposing the workflow as a service. Just like the SendActivity, it is completely built on top of the WCF stack, allowing it to be used with a variety of communication protocols.
Again, the best way to explain how to use this activity is by starting with a simple sample. Just like in the previous article, I am using Visual Studio 2008 and the .NET Framework 3.5. The first step is to create a new project (see Figure 1). This time, however, we are going to select the WCF project types instead of the Workflow project types, and choose the Sequential Workflow Service Library project type to create a new project called SimpleReceive. This may seem a little odd at first, as we are going to create a workflow project and not a WCF project; we are just exposing our workflow through WCF. Figure 2 shows the workflow designer with the workflow that was automatically created for us.
Figure 1. The New Project dialog box to create the workflow service
Figure 2. The designer showing the newly created workflow
Let’s take a look at what the project template provided for us before continuing. If we open the Solution Explorer, we will find a project containing an App.config file, an IWorkflow1.vb file, and finally a Workflow1.vb file. The Workflow1.vb file is the default workflow, as shown in Figure 2. This workflow already contains a ReceiveActivity. This ReceiveActivity already implements the GetData() function of the IWorkflow1 interface, something that can be seen in the property sheet by examining the ServiceOperationInfo property. This IWorkflow1 service interface is defined in the IWorkflow1.vb file and looks just like any other WCF interface with its ServiceContract and OperationContract attributes decorating the interface and the GetData() function. The App.config file contains the required WCF address, binding, and contract settings so we can expose our workflow as a service.
If you have not done any WCF development using Visual Studio 2008, you might be surprised to learn that you can press F5 and run the project just as it is. Two utilities, delivered as part of Visual Studio 2008, make this possible. The first is the WCF Service Host. This is a small lightweight host application that will launch and start exposing your service for use on your local machine, very much like the ASP.NET Development web server you can use when developing web applications from Visual Studio. Figure 3 shows this WCF Service Host in action. This WCF Service Host will automatically start as soon as a solution containing a WCF service project is started and makes life much easier, as you no longer have to write an application hosting your service first.
Figure 3. The WCF Service Host hosting our workflow.
The second utility is the WCF Test Client, shown in Figure 4. This test client enables us to make service calls to the workflow that we just published using the WCF Service Host. This test client is somewhat limited in what we can do with it, as it can only work with simple parameters and creates a new proxy for every request; but it’s still a nice way to get started quickly.
Figure 4. The WCF Test Client after calling the GetData() function.
Adding a second operation to the IWorkflow1service
Let’s take a look at what we need to do now that we have a running workflow exposed as a service. The first step in adding a service operation is opening the service contract, located in IWorkflow1.vb, and adding a new operation. In this case we are going to add a second operation named SayHello and decorate it with the OperationContract attribute. The IWorkflow1.vb file should now look like Listing 1.
Listing 1. The IWorkflow1 interface with a second operation
Next, we need to implement the service operation in our workflow. To do so, we need to drag a ReceiveActivity from the toolbox (see Figure 5) onto the Workflow1 and place it just below the receiveActivity1 that implements the GetData operation. Once the second ReceiveActivity is on the workflow, it shows a red exclamation mark at the right top with an error message “Activity 'receiveActivity2' does not have a service operation specified.” Click the error message to select the ServiceOperationInfo property. Clicking the button with the ellipses will bring up the Choose Operation dialog box (see Figure 6), enabling you to bind the ReceiveActivity to a service operation. This dialog box will show us all the service contracts already used on the workflow and all operations available. In this case we need to select the SayHello operation by selecting it and clicking OK.
Figure 5. Selecting the ReceiveActivity from the Toolbox
Figure 6. Choosing the SayHello operation to bind to the ReceiveActivity
The Choose Operation dialog box can be a little confusing at first. When we open it, a green checkmark is displayed before the GetData operation. This checkmark only indicates that this operation is currently implemented somewhere in the workflow, not that this is the GetData operation. Instead, the current operation is the one with the selection bar over it; in this case, SayHello. This problem is worse when we open the dialog box again after selecting the SayHello operation, as now both operations show a green checkmark. In this case it is very easy to change the operation selection without noticing. The best solution is always to double-check by looking at the operation name, and its parameters, at the bottom half of the screen.
After selecting the SayHello operation, we should see two new properties appear in the property sheet. These work just like they did with the SendActivity and enable us to bind the parameters and return value to workflow properties. In this case, we are going to add two new properties to the workflow, SayHelloName and SayHelloReturnValue, both of type string, and bind to them by double-clicking the yellow icon in the property sheet. The result should look like Figure 7. Please refer to Part 1 for a more in-depth explanation of property bindings.
Figure 7. The input and output parameters bound to workflow properties.
Pressing F5 to run our application should result in the WCF Test Client opening up again. The only difference is that this time, there should be two operations under the IWorkflow1 node: the first should be GetData and the second should be SayHello.
Now that we have the basic structure of our workflow hosted as a WCF service, we still need to implement the two service operations. The simplest way to do so now is to add two CodeActivities to the workflow, one in the GetData and the second inside of the SayHello operation. Let’s name the first GetDataImplementation and the second SayHelloImplementation. Now add the two event handlers shown in Listing 2 and bind the ExecuteCode handlers to these functions.
Private Sub GetDataImplementation_ExecuteCode( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) ReturnValue = String.Format("The input value was {0}", InputValue) End Sub Private Sub SayHelloImplementation_ExecuteCode( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) SayHelloReturnValue = String.Format("Hello there '{0}'", SayHelloName) End Sub
Listing 2. The two CodeActivity ExecuteCode event handlers
If we now press F5 to debug our workflow, we are going to run into a problem. First we need to select the GetData operation and, after entering a value for the input parameter, click Invoke. The operation will execute and, after a brief pause, the result will appear just as it is supposed to. However, when we select the SayHello operation, enter a name and press Invoke, we receive an error. The error message is:
“Failed to invoke the service. The service may be offline or inaccessible. Refer to the stack trace for details.”
The details start with the following message:
“There is no context attached to incoming message for the service and the current operation is not marked with "CanCreateInstance = true". In order to communicate with this service check whether the incoming binding supports the context protocol and has a valid context initialized.”
Part of the details are about the CanCreateInstance property not being set to true. In this case that is correct, as this is the second ReceiveActivity in the workflow and setting this property to true means the workflow runtime creates a new workflow to handle the request, something we don’t want in this case. The error message also mentions that there is context attached to the incoming message. In fact, this is the real problem, because the WCF test Client creates a new proxy for every request, so it has lost all knowledge of the first request. Let’s take a look at what happens when we call the workflow ourselves using a different client.
Add a new ConsoleApplication project to the solution and call it SimpleReceiveClient. Once this project is created, add a service reference to workflow by right-clicking the project and choosing “Add Service Reference”. When the dialog box appears, choose the Discover button. Doing so will show the workflow service in the Services pane. Change the namespace to SimpleReceive and click OK to add the reference. Figure 8 shows the results in the Solution Explorer.
Figure 8. The solution with a console client
Once the service reference has been added, we can update the Sub Main located in Module1.vb. We need to add the code shown in Listing 3. Before we run the solution again, we need to make sure the SimpleReceiveClient is the startup project by right-clicking the project and choosing “Set as StartUp Project”.
Listing 3. The Sub Main of our test client
When we run the application, we should notice a few different things. First of all, the WCF Test Client no longer appears, as the console application is now the startup project. The WCF Service Host still starts to host your workflow and the related service. And finally, the client is able to make both calls to the service without any errors. The reason the console client is able to do both service calls whereas the WCF Test Client could not is that the console client uses the same proxy object for both requests, while the WCF Test Client creates a new proxy for each call. However, workflows are often long-running, and keeping the proxy alive is probably not a viable solution, so let’s investigate this further.
Invoking multiple operations on long-running workflows
In order to test invoking multiple operations on the same instance of a long-running workflow, we should split the two calls on the client. To do so, we need to change the code in Module1.vb to the code in Listing 4.
Sub Main() CallGetData() CallSayHello() Console.ReadLine() End Sub Sub CallGetData() Using proxy As New SimpleReceive.Workflow1Client() Console.WriteLine(proxy.GetData(5)) End Using End Sub Sub CallSayHello() Using proxy As New SimpleReceive.Workflow1Client() Console.WriteLine(proxy.SayHello("Maurice")) End Using End Sub
Listing 4. Using multiple proxy objects to call a workflow, take 1
The code in Listing 4 mimics what a real client would do, and what the WCF Test Client does, when calling a long running workflow by creating a new proxy object before each call. In this case, we get the same error as we did when using the WCF Test Client. In order to understand why this is the case, we need to understand that a number of specific bindings were added to WCF to support routing multiple calls to the same workflow instance. These are the so called context bindings, and we are using one, the wsHttpContextBinding, in this case. These context bindings make sure the context, or the required information to route multiple requests to the same workflow, is passed along with each request. In the case of the first client, using the same proxy for both requests, everything worked because the context was returned by the first request and automatically added to the second request. In the second test we used multiple proxy objects, and while the first did receive the context information, the second proxy was unaware of it, so could not send it with the second request. To solve this problem, we need to save the context from the first request and add it to the second proxy before we make the second request. Listing 5 shows how to do this by retrieving the IContextManager from the proxy innerChannel and setting it on the second proxy object. Before we can do so, however, we need to add a reference to System.WorkflowServices, part of the .NET Framework 3.5, as this assembly contains the required interface.
Sub Main() CallGetData() CallSayHello() Console.ReadLine() End Sub Private _context As Dictionary(Of String, String) Sub CallGetData() Using proxy As New SimpleReceive.Workflow1Client() Console.WriteLine(proxy.GetData(5)) Dim contextManager As IContextManager contextManager = proxy.InnerChannel.GetProperty(Of IContextManager)() _context = contextManager.GetContext() End Using End Sub Sub CallSayHello() Using proxy As New SimpleReceive.Workflow1Client() Dim contextManager As IContextManager contextManager = proxy.InnerChannel.GetProperty(Of IContextManager)() contextManager.SetContext(_context) Console.WriteLine(proxy.SayHello("Maurice")) End Using End Sub
Listing 5. Saving and adding the WCF request context
The context that is passed along is an IDictionary with, in this case, a single key/value pair named instanceId identifying the workflow instance. In some cases, where correlation between multiple ReceiveActivities is required, a second value will be present, the conversationId, used for routing the message to the correct ReceiveActivity.
The Service Host
Normally, a WCF service is hosted by a ServiceHost object. In the case of a workflow being hosted, this is a little different, as a WorkflowServiceHost is used instead. This WorkflowServiceHost not only takes care of exposing the required end points, but also creates a WorkflowRuntime object so it can run the workflows. The most important thing the WorkflowServiceHost does is add the WorkflowRuntimeBehavior to the behaviors collection. This WorkflowRuntimeBehavior is the behavior that creates the WorkflowRuntime and configures it as needed. You can specify your own configuration for the workflow runtime using the application configuration file as shown in Listing 6.
<behaviors> <serviceBehaviors> <behavior name="SimpleReceive.Workflow1Behavior" > <!-- Details omitted --> <workflowRuntime> <services> <add type="System.Workflow.Runtime.Hosting.SqlWorkflowPersistenceService, System.Workflow.Runtime, Version=3.0.00000.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 </services> </workflowRuntime> </behavior> </serviceBehaviors> </behaviors>
Listing 6: Adding the SqlWorkflowPersistenceService service to the runtime
Of course you can host the workflow yourself using the WorkflowServiceHost if you prefer. This is not very different from hosting a regular WCF service, with the exception that you use the WorkflowServiceHost instead of the default ServiceHost. Listing 7 shows how to do so and add the same SqlWorkflowPersistenceService to the WorkflowRuntime.
' Create the service host Dim host As New WorkflowServiceHost(GetType(Workflow1)) ' Retreive the WF behavior Dim workflowRuntimeBehaviour As WorkflowRuntimeBehavior = _ host.Description.Behaviors.Find(Of WorkflowRuntimeBehavior)() ' Retreive the WF runtime Dim workflowRuntime As WorkflowRuntime = workflowRuntimeBehaviour.WorkflowRuntime ' Create and add the SqlWorkflowPersistenceService Dim connectionString As String = "Data Source=localhost\sqlexpress;" + _ "Initial Catalog=WorkflowPersistence;Integrated Security=True;Pooling=False" Dim persistenceService As New SqlWorkflowPersistenceService(connectionString) workflowRuntime.AddService(persistenceService) ' Start listening host.Open()
Listing 7: Self-hosting the workflow service
Adding a second workflow to our service
So far we have been working with the workflow that was automatically created and configured when we created our workflow service. However, in all likelihood we will want to publish more than a single workflow from the same service, and we need to add all required configuration.
To add a new workflow, right-click the SimpleReceive project and choose Add, and then choose Sequential Workflow…. This will open the Add New Item dialog box with the Sequential Workflow selected. Name the workflow TheSecondWorkflow and click Add. This gives us an empty second workflow. Because we also want to start this workflow using a WCF request, we first need to add a ReceiveActivity to the workflow. Go ahead and drag one from the toolbox onto the workflow. The ReceiveActivity we just added shows a red exclamation mark indicating it is not valid yet; selecting it will reveal the message “Activity ‘receiveActivity1’does not have a service operation specified.”. Clicking it will take us to the ServiceOperationInfo property in the property sheet. Clicking the button brings up the “Choose Operation” dialog box, but unlike the previous times there are no operations listed. There are two possible ways to add a service contract to a workflow. The first, and this is what we did in the first workflow, is to define an interface in Visual Basic code and use that. This is done by clicking the “Import…” button that opens the type browser enabling us to select an existing interface. The second option is to define the service contract in the workflow itselfl this is done by using the Add Contract button. This last option means there is no actual Visual Basic source file with the service interface; everything is contained inside of the workflow. Let’s use the Add Contract option, as we have already used the Import in the first workflow.
Clicking the Add Contract button adds a new service contract with name Contract1 and a single service operation named Operation1. Let’s rename the service operation to StartWorkflow and the contract to MySecondContract. Changing the return value or adding parameters can be done in the Parameters tab at the bottom of the window when the operation is selected. Change the return value to type String and add one parameter, name, also of type String. Click OK to confirm the new operation.
Figure 9: Adding a new service operation
We also want this operation to start a new workflow, so we must set the CanCreateInstance property of the ReceiveActivity to True. If this is set to False, the context binding will not create a new workflow, but return a fault when the workflow context is not passed along with the WCF request. Before we can use our workflow through the WCF ServiceHost, we still need to add this service to the configuration file. To do so, we need to add a second service in the App.Config file and name it “SimpleReceive.TheSecondWorkflow”. As we don’t need a different behavior from our first workflow, we can reuse the same behaviorConfiguration. Next we need to specify a base address and add an endpoint with MySecondContract as the contract and one of the context bindings, wsHttpContextBinding in this case, as the binding. Listing 8 shows the new section in the App.Config file.
<system.serviceModel> <services> <service name="SimpleReceive.TheSecondWorkflow" behaviorConfiguration="SimpleReceive.Workflow1Behavior"> <host> <baseAddresses> <add baseAddress="" /> </baseAddresses> </host> <endpoint address="" binding="wsHttpContextBinding" contract="MySecondContract" > <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> <!-- Remainder omitted. -->
Listing 8: The new service definition in our configuration file
With the service all set up, the next thing we need to do is get the client to call the second workflow. The second workflow will not show up using the existing service reference because the second workflow is a completely new service, so we need to add a second service reference. Right-click the Service References node in the SimpleReceiveClient project and choose Add Service Reference…. This will open the Add Service Reference dialog box again, but this time, after we click the Discover button, there should be two services listed. Select the service pointing to SimpleReceive/TheSecondWorkflow/mex and change the Namespace to TheSecondWorkflow before clicking OK. This will generate the proxy classes required to work with the second workflow. Listing 9 shows how to call the second workflow. Note that it will not actually print anything, as we didn’t add any functionality to the workflow itself.
Listing 9: Calling the second workflow
Conclusion
Using a ReceiveActivity it is not hard to expose a workflow as a WCF service. The WCF Service Host makes life easy by providing us with a host application to use when developing. The WorkflowServiceHost creates the WorkflowRuntime and exposes the configured endpoints for us. It also configures the workflow runtime with the specified configuration if needed. Combine the ReceiveActicity with the SendActivity described in the previous article and you get the combined power of WCF and WF.
About Development Network, the largest Dutch .NET user group. Maurice can be reached through his websites, either or, or by emailing him at Maurice@TheProblemSolver.nl. | https://msdn.microsoft.com/en-us/library/cc904193.aspx | CC-MAIN-2015-11 | refinedweb | 3,530 | 54.12 |
All you need to do is this:: Make back-ups of all your data first then >>
1. Boot the PC into MS DOS Mode
2. At the C:/format C:/ hit return (note the space between the T of format and C)
3. Type Y for yes to proceed
Once its formated insert the Floppy or set your BIOS to 1st boot from CD Rom have the windows CD in your rom and it will start to install..
If you use the Boot Floppy use CD Rom support then once its finished type in at the A:/ or C:/ prompt your CD drive letter per say D:/ hit return. Now if it is D:/(type) setup.. You should be ok from this point forward.. | http://www.pcadvisor.co.uk/forum/helproom-1/format-win98se-85077/ | CC-MAIN-2016-50 | refinedweb | 124 | 87.76 |
With the new Sense Hat, you no longer need extra parts, all sensors are included! Simply attach the Sense Hat atop your Raspberry Pi 3 and you are all set!
- Gyroscope - Temperature
- Accelerometer - Barometric Pressure
- Magnetometer - Humidity
Follow along with this simple tutorial and discover the weather around you.
We will be using the Temperature, Humidity and Pressure sensors for this project.
Step 1: Gather Components
The following components are used for this project:
Sense Hat case New! See-through enclosure protects your LED screen without obstructing visibility.
HDMI Cable
Monitor
Keyboard
Mouse
Looking for a great introduction to Raspberry Pi? Try the Zagros Raspberry Pi 3 Starter Kit which has everything you need to begin discovering Raspberry Pi.
Step 2: Update and Upgrade
Make sure your system is updated and upgraded with the latest version by running the following commands in the Terminal. (Terminal is the computer icon on the Raspberry Pi menu bar)
1.) Type this command and press enter.
sudo apt-get update
2.) Type this command and press enter.
sudo apt-get dist-upgrade
Step 3: Open Python Editor.
1.) Press Menu button.
2.) Navigate to Programming >> Python-3 (IDLE).
You have now opened the Python Shell.
3.) Click File.
4.) Click New File.
Step 4: Import Modules for Your Project.
Type or copy into editor:
from sense_hat import SenseHat
import time
Step 5: Set Variables.
Pi was created in England, so the temperature output is in Celsius. The conversion to Fahrenheit is included below.
Type or copy into editor:
sense = SenseHat()
temp = round(sense.get_temperature()*1.8 +32)
humidity = round(sense.get_humidity())
pressure = round(sense.get_pressure())
message = 'Temperature is %d F Humidity is %d percent Pressure is %d mbars' %(temp,humidity,pressure)
Step 6: Display Weather on Sense Hat!
The show_message() command displays your message like a banner across the LED screen. Scroll_speed allows you to control how fast the message rolls across. I've set the text_colour to pink and the back_colour to blue. Find your favorite contrast and change your colors.
Type or copy into editor:
sense.show_message(message, scroll_speed=(0.08),text_colour=[200,0,200], back_colour= [0,0,200])
To clear the screen after the message is complete. Type:
sense.clear()
To run your program, press F5.
(The Python file for the project is attached)
Step 7: Keep a Weather Log.
Great! You created a weather banner!
Now you can amend your program to save your weather data in a text file.
At the very top of the file add this module:
from time import asctime
Step 8: Create Text File.
At the very bottom of the file add a while statement:
while True:
log = open("weather.txt", "a")
The second argument indicates how the file is to be opened "a"= append and "w" will write over anything that was was already in the file.
now = str(asctime())
Asctime() outputs a time-stamp in an easy to read form.
log.write(now + " " + message + "\n")
print(message)
log.close()
sleep(30)
Waits 30 seconds before continuing with the loop.
You can adjust this time however you like. If you have a portable battery pack you can take samples of weather in different rooms, the basement, garage, inside your car, and outside!
To run your program press F5 while the cursor is in your program file.
Step 9: Alternate Loop.
Your program will continue to run without end unless you kill it in the Shell by typing Ctrl + C.
You can set the amount of times it will run by using a for loop to set the range:
for i in range(10):
log = open("weather.txt", "a")
now = str(asctime())
log.write(now + " " + message + "\n")
print(message)
sleep(30)
log.close()
Step 10: Weather.txt Sample.
Open the weather.txt file and it should look something like this.
With the current setting, each time you run the program the new data will be appended after the last line.
Step 11: ## Commenting Tip.
As a note, the message will display completely before the weather is logged to the text file.
If you would like to skip the message displaying on your Sense Hat, make it a comment:
1.) Highlight text.
2.) Click Format.
3.) Click Comment Out Region.
or
1.) Highlight text.
2.) Alt + 3.
3 Discussions
1 year ago
Hello, Can you tell me how to loop the data from the Sense hat back to the LED matrix? Thanks
2 years ago
Hi Matt,
It's no bother at all. Thank you for your question. If you would like to run an infinite loop just replace the for i in range(10): line withwhile True:
Check out step 8 for the code of the while True: statement.
Thanks!
2 years ago
Super sorry to bother you but how would I go about having the display loop non-stop?
Thank you very much, this is my first project. | https://www.instructables.com/id/Weather-Display-With-Sense-Hat/ | CC-MAIN-2019-26 | refinedweb | 814 | 76.32 |
Nicola Pero <address@hidden> wrote: > > > > #import is deprecated - on technical grounds - by any gcc compiler hacker > > > we had the chance of talking to, both GNU and Apple folks - they have > > > strong views on that point and they keep the warning turned on in the > > > compiler by default. > > > > As a complete ObjC newbie - > > *why* is it deprecated? Does #import work anything like the Java import, > > I'm not much inside this, but I think it's because the languages are very > different - > > in Java it's very easy to implement import. import imports a *class*. > when the compiler reaches an import, it checks if it has already imported > that class or not. That's it. > > in C/ObjC, #import instead imports a file - which makes it not really > clearly defined because different physical files on disk might contain the > same code - but you don't want the same code to be loaded more than once > (that's the whole purpose of #import) so the compiler has to guess ... it > could check that the files are the same ? but what if they are different > versions of the same header ... they are different physically on the disk, > but should never be included twice ... all this which looks silly but then > might turn into very complex stuff for the compiler writer and might > actually cause some real mess with complicated system libraries when you > have multiple versions installed and a serious risk on including different > versions twice. I'm sure I read somewhere on the net a very definite > tricky example of a real-world case which was fooling gcc's #import into > loading the same file (with different versions perhaps) twice and crashing > compilation. Unfortunately I can't seem to find it any longer. > > Anyway my explanation is probably incomplete and confused, but should give > you an idea of why the problem arises.. The #import CPP directive is defined as including a given file once ever in a compilation run, and that's enough to be an improvement to #include. It's a higher level construct than #include because it imposes a more structured handling of the files than #include, one that is more usefull in big project than the ability to include a given "header" several times, be it with the same macro environment or not, because it help programmers avoid small errors in writting the pattern #include+#ifndef+#define, and because it's more meaningfull when we program objects with one class per couple of interface / implementation files. > Defining a preprocessor tag inside the header file itself seems to be the > only real way of fixing this problem in C. The only thing I can think of > to make this prettier but still reliable would be to extend C (or ObjC) > adding a > > #declare GNUSTEP_H_APPKIT > > directive (or whatever the name), which would only be allowed as the first > command in a file, and would cause the compiler to behave as if > > #ifndef GNUSTEP_H_APPKIT > #define GNUSTEP_H_APPKIT > > where at the beginning and #endif at the end of file. The #declare would > declare a programmer-level tag marking the file, with the convention that > no two files with the same tag should be loaded ever. > > Then, you could use #include in the same way as you use #import. You > would only have to add #declare GNUSTEP_H_APPKIT at the beginning of each > header file. This might make pascal happy I suppose :-) as a single > #declare per file is pretty high-levelish IMO and the compiler people as > well, because it would be well defined, reliable and efficient. > > Anyway, in general #ifdef/#define looks like a minor annoyance after all. > It's a C thing, difficult to loose. -- _------ | http://lists.gnu.org/archive/html/discuss-gnustep/2001-12/msg00205.html | CC-MAIN-2015-35 | refinedweb | 613 | 53.85 |
There change this to avoid printing a newline at the end.
There are many options for this choice. We could use a space to print space-separated strings.
a = "Hello" b = "from AskPython" print(a, end=' ') print(b)
This would print strings
a and
b, separated by a single space, instead of a newline.
Output
Hello from AskPython
We could also print them consecutively, without any gap, by using an empty string.
a = "Hello" b = "from AskPython" print(a, end='') print(b)
Output
Hellofrom AskPython
2. Printing list elements without a Newline
Sometimes, when iterating through a list, we may need to print all its elements on the same line. To do that, we can again use the same logic as before, using the
end keyword argument.
a = ["Hello", "how", "are", "you?"] for i in a: print(i, end=" ")
Output
Hello how are you?
3. Using the sys module
We can also use the
sys module to print without a newline.
More specifically, the
sys.stdout.write() function enables us to write to the console without a newline.
import sys sys.stdout.write("Hello from AskPython.") sys.stdout.write("This is printed on the same line too!")
Output
Hello from AskPython.This is printed on the same line too!
4. Creating our own C style printf() function
We can also create our custom
printf() function in Python! Yes, this is possible using the module
functools, which allows us to define new functions from existing ones via
functools.partial()!
Let’s use the same logic on the
end keyword argument on
print() and use it to create our
printf() function!
import functools # Create our printf function using # print() invoked using the end="" # keyword argument printf = functools.partial(print, end="") # Notice the semicolon too! This is very familiar for a # lot of you! printf("Hello!"); printf("This is also on the same line!");
Output
Hello!This is also on the same line!
We can also combine the semicolon to this (Python compiler will not complain) to bring back our C
printf() function as it was!
References
- JournalDev Article on printing without a newline
- StackOverflow Question on the same topic
Great info, thank you! I also found this article on printing without a newline in python 2 and 3 –. | https://www.askpython.com/python/examples/python-print-without-newline | CC-MAIN-2020-16 | refinedweb | 376 | 76.01 |
Running on Read the Docs¶
Read the Docs is an excellent site for hosting project documentation. It provides hooks into common project hosting sites like Github & Bitbucket and can rebuild your documentation automatically whenever you push new code.
The site is designed for documentation written with Sphinx and supports Sphinx
extensions via a correctly configured
setup.py file.
As Breathe is a Sphinx extension you can use it on Read the Docs. However, as Breathe requires doxygen XML files, some additional configuration is required.
Doxygen Support¶
Read the Docs do not explicitly support doxygen however they have had requests for it to be supported and it is currently installed on their build servers.
Generating Doxygen XML Files¶
We assume that you are not checking your doxygen XML files into your source control system and so you will need to generate them on the Read the Docs server before Sphinx starts processing your documentation.
One simple way of achieving this is to add the following code to your
conf.py file:
import subprocess, os read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True' if read_the_docs_build: subprocess.call('cd ../doxygen; doxygen', shell=True)
The first line uses the
READTHEDOCS environment variable to determine
whether or not we are building on the Read the Docs servers. Read the Docs
set this environment variable specifically for this purpose.
Then, if we are in a Read the Docs build, execute a simple shell command to build the doxygen xml for your project. This is a very simple example; the command will be determined by your project set up but something like this works for the Breathe documentation.
As this is then executed right at the start of the
sphinx-build process then
all your doxygen XML files will be in place for the build.
A More Involved Setup¶
If you’d rather do something more involved then you can run
doxygen as part
of a
builder-inited event hook which you can install from your
conf.py
file by adding a
setup function as shown below.
This is an approximation of the code that Breathe has in its
conf.py in
order to run
doxygen on the Read the Docs server.
import subprocess, sys def run_doxygen(folder): """Run the doxygen make command in the designated folder""" try: retcode = subprocess.call("cd %s; make" % folder, shell=True) if retcode < 0: sys.stderr.write("doxygen terminated by signal %s" % (-retcode)) except OSError as e: sys.stderr.write("doxygen execution failed: %s" % e) def generate_doxygen_xml(app): """Run the doxygen make commands if we're on the ReadTheDocs server""" read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True' if read_the_docs_build: run_doxygen("../../examples/doxygen") run_doxygen("../../examples/specific") run_doxygen("../../examples/tinyxml") def setup(app): # Add hook for building doxygen xml when needed app.connect("builder-inited", generate_doxygen_xml) | http://breathe.readthedocs.io/en/latest/readthedocs.html | CC-MAIN-2017-26 | refinedweb | 462 | 54.22 |
The CD-ROM Media Device Path is used to define a system partition that exists on a CD-ROM. More...
#include <DevicePath.h>
The CD-ROM Media Device Path is used to define a system partition that exists on a CD-ROM.
Definition at line 1011 of file DevicePath.h.
Definition at line 1012 of file DevicePath.h.
Boot Entry number from the Boot Catalog.
The Initial/Default entry is defined as zero.
Definition at line 1016 of file DevicePath.h.
Starting RBA of the partition on the medium.
CD-ROMs use Relative logical Block Addressing.
Definition at line 1020 of file DevicePath.h.
Size of the partition in units of Blocks, also called Sectors.
Definition at line 1024 of file DevicePath.h. | http://dox.ipxe.org/structCDROM__DEVICE__PATH.html | CC-MAIN-2019-47 | refinedweb | 123 | 62.04 |
You can use the os.walk() method to get the list of all children of path you want to display the tree of. Then you can join the paths and get the absolute path of each file.
import os def tree_printer(root): for root, dirs, files in os.walk(root): for d in dirs: print os.path.join(root, d) for f in files: print os.path.join(root, f) tree_printer('.')
This will print a list of all the directories in your tree first and the print the paths of all the files in the directory recursively.
C:\hello\my_folder C:\hello\another_folder C:\hello\my_folder\abc.txt C:\hello\my_folder\xyz.txt C:\hello\another_folder\new.txt ... | https://www.tutorialspoint.com/How-to-list-directory-tree-structure-in-python | CC-MAIN-2021-43 | refinedweb | 118 | 69.58 |
RIAA Says It Doesn't Have Enough Evidence 208
NewYorkCountryLawyer writes "In Elektra v. Wilke, the Chicago RIAA case in which defendant Paul Wilke has moved for summary judgment, the RIAA has responded to the summary judgment motion by filing a motion for 'expedited discovery', alleging that it needs expedited pretrial discovery because it does not have sufficient evidence to withstand Mr. Wilke's motion. The RIAA's lawyer said: 'Plaintiffs cannot at this time, without an opportunity for full discovery present by affidavit facts essential to justify their opposition to Defendant's motion.' The motion and supporting affidavit are available online."
Makes sense (Score:5, Insightful)
ah-ha (Score:3, Insightful)
Evidence (Score:5, Insightful)
They have enough evidence to start proceedings, but not enough to prove guilt. So they ask for more with the discovery. This is also seen in other types of cases, so its not unheard of.
The discovery might even entail impounding his entire home, and all his assets for 'review'. A good 'threat' to cause him to settle out of court like everyone else has. Does he have the balls for it? The RIAA has nothing to lose by a war of attrition. He does. ( we all do )
While not unheard of (Score:5, Insightful)
It's a smelly, scummy sort of ambulance chaser that doesn't have his/her ducks in a row before they baste some poor person in oil and fry them before the bench.
This bodes badly for whatever hacks the RIAA has employed to enforce their ex-foreclosure bar-bells. I doubt they're embarrassed, as it is impossible to embarrass sociopaths.
Now mod me down for troll-- or be enlightened and understand that the poster actually got some most interesting and relevant information: the RIAA's enforcers are starting to sputter.
Re:While not unheard of (Score:5, Funny)
I bet no-one's ever uttered that exact sentence ever before.
Re: (Score:2)
Which is to say "none".
You know that line you see in legal filings "On information and belief..." It means they have no evidence.
You're not supposed to start proceedings if you have no evidence, but there's nothing stopping you if you really don't.
Just look at the SCOX vs IBM lawsuit.
IANAL (Score:2)
Summary judgement is appropriate where any disagreement about the nature of the facts in a case is insufficient to overrule the legal standing. In short, summary judgement is like saying "Your honor, even if everything they say is true, the law is still on my side."
I suppose it is too much to hope that a Real Lawyer(TM) will explain this to us....)
Hopefully, Paul (or Paule) does not have any evidence of those songs on his computer (and more importantly, does not have evidence that they may have been erased, there was a precedent where someone got the book thrown at them after using a drive wiper, hopefully that gets thrown back on appeal). Sadly, even if he is innocent, if they (the tools) can convince a judge that the data has been tampered with (wiped hard drive, another computer, whatever) they could still reak (pun intended) havoc.
This is an opportunity to raise the bar by requiring much more specific proof of infringement before violating a person's right to privacy and disrupting their lives, but don't expect that to come out of Chicago. Next best thing is that if Paul can withstand the expedited discovery (and many dirty tricks will probably be used) then he wins and precedent is set. This will limit and force the hand of the tools in future cases and encourage others to resist the suit (specifically if Paul can get attorney fees).
Re: )
Defendant: I'm tired of this bullshit. Show me what you really have so we can get this over and done with.
RIAA: Uhhh... shit. We don't have a thing. Your honour could we please search everything the defendant owns in order to find something?
Re: )
See?
I know you were being funny, but put together a cohesive argument for my grandmother/mother/brother why they should all of the sudden switch to metric. My father and I are engineers and hate working with English units, so we are not your target. Even then, we usually only have to deal with English units at the beginning and the end of the design phase, or when using older equipment. 300 million people using a system of measure is all by itself a good reason not to change. From their point of view, it)
No, actually - though Monty Python is pretty damn funny. I've never seen Dr. Who or Red Dwarf. I think I've seen one episode from each continent of the Office.
That said, if you think it matters whether someone has a sense of humour or a sense of humor, then you've pretty much failed at life. Loser.
Re:Since submitter is a lawyer ... (Score:4, Insightful)
From the RIAA's point of view, that's not as dumb as it sounds.
1) They get the publicity (another mile on the piracy lawsuit odometer). Whether this one is guilty or not, it counts just as well in their scare tactics.
2) The mere fact that there *is* a lawsuit leads to out-of-court settlements more often than to court sessions, because the defendants (plain citizens) believe they'll save on legal expenses that way.
In this case they had the bad luck to "hit" a 50+ year old guy who stands up for himself, but suppose it'd been someone with a 14-year old kid using the family's internet connection. You know how kids are, and they wouldn't file a complaint if they had nothing to back it, would they? So you'd probably believe it, and try to move it into history as fast and as cheap as you can.
Re: )
The RIAA claim they got attacked by Paul Wilke in 2001 when Paul allegedly flew his ftp client into a Warez carrier. Of course this was before Hilary Rosen's "resignation" as the RIAA's chief anti-piracy lead, which I'll come back to. Now the RIAA are claiming that Paul can copy an MP3 within 45 minutes, which is contentious because they can't really tell the judge _which_ MP3s Paul can copy so fast. But given the nature and extreme urgency of the threat, they're asking the Judge for the right to go into Paul's house _right now_ and change the OS on his PC. Apparently, once they've liberated his hard disk, it'll be trivial to find tons of hidden MP3s.
Naturally, Paul isn't too happy about this, and he's been talking with his French lawyer about vetoing the proposal, which is what this letter is about. Right now, we're all wondering if the judge is going to make a resolution, and if the RIAA will go it alone anyway if it doesn't look like it'll work out for them.
Re:Since submitter is a lawyer ... (Score:5, Informative)
Discovery is a process where each side submits lists of documents and other evidence (worded as broadly as they can get away with) and the court will force the other side to supply what's listed, if it's arguably relevant to proving or disproving a claim (or counterclaim, bla bla).
Courts generally supposed to frown on "fishing expeditions". Theoretically you have to have some evidentiary basis for a suit in the first place, before you can use the suit to compel discovery. Who knows what the RIAA can get away with, though.
(not a lawyer, did the jd, but this is not legal advice, yada yada)
Re: )
Standing is different from having enough evidence to make a case. Standing, in this type of case, means that the plaintiff is alleging harm to itself by the defendant. I, for instance, would lack standing trying to sue Joe for hitting Jane with his car. But, if someone hit my car, and I think it was Joe, but I don't know for sure - I have standing, but perhaps no case.
In this case, the defendant has filed a motion saying that the plaintiffs (RIAA) do not have any evidence against him, and no reasonable judge or jury would find in the plaintiffs' favor. Unlike standing, RIAA could clear this hurdle merely by finding more facts that would implicate the defendant. The question is whether the plaintiff can use the discovery process to build a case if they have no evidence in the first place.
A defendant can be compelled to turn over any documents and records to the opposition that the opposition specifically asks for. However, RIAA needs to show that it has some basis for filing the suit, and that it isn't simply harassing the defendant. RIAA does not need to show it has enough evidence to proceed to trial. I'm not sure where they are on this case.
Re: )
You might be talking about these cases: Priority Records v. Candy Chan [riaalawsuits.us]( Chan I ) and Priority Records v. Brittany Chan [riaalawsuits.us] (Chan II ), in Michigan; Capitol v. Foster [riaalawsuits.us], in Oklahoma; Warner v. Stubbs [riaalawsuits.us], also in Oklahoma; and Virgin Records v. Tammie Marson [riaalawsuits.us], in California. All cases resulted in RIAA dropping the case.
All of the RIAA's cases are based on the same slender evidence: (a) a screenshot; (b) a half dozen or so song files their investigator was able to download; and (c) tracing the dynamic IP address of t
Re:So in English . . (Score:5, Informative)
In which case the answer is no. The RIAA should have a good faith basis for suing, but part of the legal process is that once the suit is initiated, there is a phase called "discovery" where both sides attempt to obtain evidence that supports their position, exchanges that evidence, requests access to certain things (e.g. the defendant's harddrive), and essentially tries to collect everything necessary to put on a case. Then there's the opportunity to file a Motion for Summary Judgment, if the evidence appears to show that the facts are undisputed (or fails to show anything of relevance). Then there's the trial. Obviously this is a highly simplified explanation, which leaves out other potential steps (or mis-steps) that are not currently relevant to my short summary as it pertains to this case, but that's the gist of it.
Re: (Score:2)
Re: (Score:2)
RIAA and good faith?
hello, hell? how is the weather down there? i was hoping to get som skiing done.
Re:So in English . . (Score:4, Interesting)
This particular phenomenon is the biggest argument for tort reform in recent memory. The American legal system is set up in such a way that, if you are sued, you are financially penalized win or lose. In other jurisdictions (I'm thinking of the UK in particular) the plaintiff is obligated to pay for the defendant's legal fees if the plaintiff loses the suit. This has the effect of curtailing suits that are filed simply to harass defendants, or to promote failing business models as the only choice available to the consumer, lest they be bankrupted in court.
Re: )
RIAA: Hey yr honor, this dude stole my stuf, i know 'cause a guy i pay to hang on the net told me so!
DUDE: Nope, i didn't.
RIAA: Sure, they all claim the same, and actually by now i've got no evidence, but if you let me go his home and
put everything upside-down i bet my "experts" will find something!
Well, i hope this is not the way the USA justice works.
And if i were Defendant i'd ask RIAA in return (and before giving anything to them) to let me do forensics on computer their investigators used to identify my IP and computers they used to exchange mails and every other piece of equipement i could think off (like routers of their ISP). And it'd
take me 10 years or so, and of course at the expense or RIAA (i mean, forensics is a hard work, i intend to get payd for it) if i figure that they made a mistake.
Re: (Score:2)
Hope and a buck will get you a cup of coffee -- maybe you'll wake up and understand the lie that is the US legal (not justice) system.
-l
Re: (Score:2)
Re: (Score:2)
Re: (Score:2, Interesting)
I was actually thinking of a situation where I could be in the USA working as a consultant (as I have before), and the RIAA decide they want me after I login to the Internet using the laptop I use back here at home. Or to look about more widely, at a situation like Dmitri Skylarov faced when in the USA with a perfectly valid visa.
Besides, your jails are not so nice. We know that your prisoners at Guantanamo Bay arn't treated "cush
Re: (Score:2)
Re: (Score:2)
Grok Some Law (Score:4, Funny)
This is the way the system works (Score:5, Interesting)
Re: (Score:2)
Re: (Score:2)
In cases like you mention, there is at lest a set of plausible events that show a logical 'possibility' that a defendant did as charged. As per your example, your kid gets cancer, there's something funny with your water, this big company is upstream from your water supply and there are no other big companies up there...There is a trail that leads somewhere.
This is being used by the RIAA as a complete wild goose chase. He did it! Nope, we've got)
So, now the RIAA wants permission to search for the evidence the clearly never had in the first place. Alright, my question is, can this guy go back to the judge with "Given that I was summoned to appear here on the pretext of compelling evidence that we now know the RIAA does not posses, and given that I am not prepared to waive my right to a speedy trial while they are given additional time to find this evidence, can we just dismiss this and all go home?"
Also, can I counter-sue for lost time, lost wages, added stress, etc.?
but, of course, IANAL (besides being ANAL, I'm not a lawyer either
During the search (Score:2)
Who is 100% clean in this world, we ALL have something we can be nailed for if one searches hard and long enough. And the RIAA/MPAA/BSA/HSD/whatever has the time and money to grind you into the ground finding that one shred of evidence that can put you away. Unless of course you give up along the way, like most of the common folk have to do
Re: (Score:2)
Re:So...to continue the train of thought we all ha (Score:2)
Also, can I counter-sue for lost time, lost wages, added stress, etc.?
Probably not. First, you aren't going to lose any wages unless you have to take time off from your job. There's no reason you would have to do that unless it actually went to trial.
Stress, distress, etcetera are awardable in situations where your leg gets cut off or you watch your kid get run over by a car. But they are not awardable s
Re:So...to continue the train of thought we all ha (Score:2)
That's not a right that is relevant here. The U.S. Constitution codifies a right to a speedy trial for criminal cases, not civil matters. This right exists to prevent the government from accusing you of a crime, putting you behind bars, and then delaying the proceedings until you've served 15 years (thereby circumventing your right to be tried for your crime). A civil case, on the other hand, can go on as long as either party is willing to fight.
Re: (Score:2)
Not a criminal trial, thus no right to a speedy trial.
As if (Score:2)
As if they ever did, ever have, or ever will.
I suppose they want exclusive access to his hard drive so they can find an MP3 file somewhere.
"He only had a few of the songs from exhibit B [the screenshot] on his computer, and those were from legally purchased CD's owned by Mr. Wilke"
Good god - screenshots (which are very hard to fake your honor). This circus of a crusade gets increasingly stupid with each instance of accusation.
--
Ooo look your honor - MP3'
Since there seem to be some questions (Score:5, Informative)
Having filed, they're entitled to gather evidence more easily, by getting testimony, physical evidence, etc. They generally have a right to gather it for the suit, rather than merely asking for it. Federal civil trials in the US are big on discovery. The idea is that there should be no surprises in court; both sides will have ample opportunity to determine precisely what happened. Hopefully, there won't even be a dispute over the facts, making the trial go faster, and ideally it'll get the parties to settle or the case to get dropped, since court time is a valuable commodity.
In any event, what has happened here is that the defendant has filed for summary judgment to dismiss the case. In a trial, there are questions of fact (e.g. did A stab B?) and questions of law (e.g. is it against the law for A to stab B?). In a summary judgment motion, the moving party is saying that there are no questions of fact which will have any bearing on the case, or some portion thereof. Therefore, the case (or the portion of the case for which summary judgment is sought) can be decided by the judge immediately, based purely on the law and the facts for which there is no question. (e.g. A and B agree that A stabbed B, so accepting that, the only issue is whether it was against the law, not whether it happened)
However, often both sides will dispute whether there are material factual questions remaining or not, that is, whether there are disputed facts where a reasonable jury could go either way, and which are important to the case. For instance, if A says that the knife was a toy knife, and B disagrees, this is likely material. But a dispute over the color of the knife likely is not.
Here, defendant is asking for summary judgment because he says RIAA sued the wrong person, and anyway, he didn't infringe. RIAA is saying that they need to gather more evidence so that they can show it to the judge, show that there are material questions of fact which are in dispute, and that they should go to a jury. In order to do this, they need to engage in discovery to find out some of these facts, since they weren't required to have them prior to filing the suit. N.b. that all RIAA has to do is show that there are still issues that need to go to a jury -- they do not need to show that the jury would find in their favor, or that they'd win the eventual case. Even highly disreputable and unbelievable evidence is sufficient to defeat the motion if a reasonable jury might believe it. In summary judgment matters, the court will look at all the facts in the light most favorable to the non-moving party, who is in this case, RIAA. This is because it's the moving party that wants no trial, and so should be required to prove it. The moving party isn't allowed to use summary judgment as a railroad to get the case dismissed before crucial evidence can be gathered, as that would run contrary to the rules allowing for discovery and setting the low threshold for filing.
Honestly, this is all fairly ordinary stuff. I don't think it's really news.)
If a plaintiff believes it has been wronged but the information necessary to sufficiently prove their case is somehow privileged, there is no way for them to possess that information as evidence without discovery. That's why it's called "discovery". Plaintiffs frequently believe that internal documents or sworn testimony of the defendant will prove their case, but without discovery, they will never be able to read those documents or obtain that testimony.
In this case, the RIAA needs access to defendant's computer to prove its case. It has no such access without a subpoena, which it cannot obtain without a lawsuit. Plaintiff has filed that lawsuit and is now asking the court for permission to obtain the evidence needed to prove it.
I would be very surprised if the court denied their motion.)
They mean "Plaintiffs cannot at this time, without an opportunity for full discovery, present by affidavit facts essential to justify their opposition to Defendant's motion."
Without that extra comma, the "present" they wrote has the accent on the first syllable, meaning "now", rendering their statement grammatically incorrect and nonsense. | https://slashdot.org/story/06/09/10/0643210/riaa-says-it-doesnt-have-enough-evidence?sdsrc=nextbtmprev | CC-MAIN-2017-04 | refinedweb | 3,567 | 67.79 |
Mango you hit a dead end somewhere. There were also some nice opportunities for small, specialised attack scripts, which I particularly enjoyed!
When we start out by scanning the box, we get the following report:
# nmap -sS -sC -oN mango.nmap 10.10.10.162 Starting Nmap 7.80 ( ) at 2019-12-08 13:30 GMT Nmap scan report for 10.10.10.162 Host is up (0.13s latency). Not shown: 997 closed ports PORT STATE SERVICE 22/tcp open ssh | |_ 403 Forbidden 443/tcp open |_ done: 1 IP address (1 host up) scanned in 10.49 seconds
When you know what to look for, it’s trivial, but it took me more time than I’m willing to admit here to see the leaking domain name in the SSL certificate. Its subject points to
staging-order.mango.htb. Port 80 is not that interesting at is just yields a permission error. Heading to the site on port 443, are are greeted with a search page:
Exploring the site manually, we find an analytics frontend:
On the first look, this seems to provide some interesting attack surface. Checking the source code, we only find hardcoded JSON data and file inclusions from flexmonster.com – all sample data, apparently. So we skip it as there is nothing interesting on here that is in scope.
Moving on, with the
mango.htb added to our hosts file, we can access the SSL-protected part of the site, which we got from the certificate’s common name. There, we are greeted with a login panel:
Logging the network requests on the page when trying some easy default candidates does not yield any success. However, thinking about the box’ name, I thought that it might be a hint for MongoDB as a backend service. And the all-time classic here is attempting NoSQL injection. So I crafted a little Python script that uses form field regular expressions to enumerate the database’s usernames:
import requests import string import sys username = "" u = " def escape(c): return "\\" + c if c in string.punctuation else c while True: sanitized = username.replace("\\", "") found = False for c in string.ascii_letters + string.digits + string.punctuation: esc = escape(c) sys.stdout.write("\r{}{}".format(sanitized, c)) sys.stdout.flush() # print("Sending", "{}{}.*".format(username, esc)) params = { "password[$ne]": "foo", "username[$regex]": "{}{}.*".format(username, esc), "login": "login" } r = requests.post( u, data=params, verify=False, allow_redirects=False ) if r.status_code == 302: username += esc found = True break if not found: print("\rFound username: '{}'".format(sanitized)) break
Et voilà, the usernames
mango and
admin show up. Armed with that knowledge, we can exploit the same vulnerability to extract the user’s passwords from the database with a little variation of the above script:
import requests import string import sys username = "admin" password = "" u = " def escape(c): return "\\" + c if c in string.punctuation else c while True: sanitized = password.replace("\\", "") found = False for c in string.ascii_letters + string.digits + string.punctuation: esc = escape(c) sys.stdout.write("\r{}{}".format(sanitized, c)) sys.stdout.flush() # print("Sending", "{}{}.*".format(password, esc)) params = { "password[$regex]": "^{}{}.*".format(password, esc), "username": username, "login": "login" } r = requests.post( u, data=params, verify=False, allow_redirects=False ) if r.status_code == 302: password += esc found = True break if not found: print("\rFound password for {}: '{}'".format(username, sanitized)) break
And we get the following output:
mango: h3mXK8RhU~f{]f5H admin: t9KcS3>!0B#2
Logging in as either just brings us to a dead end:
So we circle back to our recon results and see where we can apply this new information to make progress. Trying to log in through SSH shows that the
mango user also exists on the server, and they have reused their password. We manage to get a shell, but no user flag. Sad. 😦
But maybe the admin user exists on the machine too and just didn’t enable the password on their SSH login. Running
su admin and entering the password leads to great success and we have now secured the user flag.
As admin, doing the usual enumeration game…
$ cd /tmp $ wget 10.10.14.13/LinEnum.sh --2019-12-09 11:34:28-- Connecting to 10.10.14.13:80... connected. HTTP request sent, awaiting response... 200 OK Length: 46476 (45K) [text/x-sh] Saving to: ‘LinEnum.sh’ LinEnum.sh 100%[=================================>] 45.39K 138KB/s in 0.3s 2019-12-09 11:34:28 (138 KB/s) - ‘LinEnum.sh’ saved [46476/46476] $ chmod +x LinEnum.sh $ ./LinEnum.sh > totallynotareport.txt
… we find an interesting line in the report:
[+] Possibly interesting SUID files: -rwsr-sr-- 1 root admin 10352 Jul 18 18:21 /usr/lib/jvm/java-11-openjdk-amd64/bin/jjs
Indeed, interesting. Because
jjs is a super easy point for privilege escalation when run with elevated privileges. And this one has an SUID flag! Reading up a bit on GTFOBins (because no one can remember that stuff, seriousy), we craft the following payload:
echo 'var BufferedReader = Java.type("java.io.BufferedReader"); > var FileReader = Java.type("java.io.FileReader"); > var br = new BufferedReader(new FileReader("/root/root.txt")); > while ((line = br.readLine()) != null) { print(line); }' | jjs Warning: The jjs tool is planned to be removed from a future JDK release jjs> var BufferedReader = Java.type("java.io.BufferedReader"); jjs> var FileReader = Java.type("java.io.FileReader"); jjs> var br = new BufferedReader(new FileReader("/root/root.txt")); jjs> while ((line = br.readLine()) != null) { print(line); } 8a8ef79a7a2fbb01ea81688424e9ab15
And that gives us the root flag. Awesome! | https://dmuhs.blog/2020/08/08/hackthebox-mango-write-up/ | CC-MAIN-2022-21 | refinedweb | 915 | 59.4 |
Docs |
Forums |
Lists |
Bugs |
Planet |
Store |
GMN |
Get Gentoo!
Not eligible to see or edit group visibility for this bug.
View Bug Activity
|
Format For Printing
|
XML
|
Clone This Bug
gentoolkit/gentoolkit-0.2.4_rc3 depends on >=dev-lang/python-2.0, but
glsa-check uses email.mime.text, which was introduced in python-2.5, hence it
should depend on that.
Reproducible: Always
Steps to Reproduce:
1. glsa-check -m affected
2.
3.
Actual Results:
# glsa-check -m affected
Traceback (most recent call last):
File "/usr/bin/glsa-check", line 311, in ?
from email.mime.text import MIMEText
ImportError: No module named mime.text
Expected Results:
only mailed output.
Created an attachment (id=144868) [edit]
glsa-check-import-MIMEText.patch
Python-2.5 changes the location of the import, but it's still there in earlier
versions.
Please test this patch.
Result after patch:
# glsa-check -m affected
Traceback (most recent call last):
File "/usr/bin/glsa-check", line 349, in ?
myattachments.append(MIMEText(str(myfd.getvalue()), _charset="utf8"))
TypeError: 'module' object is not callable
Created an attachment (id=146444) [edit]
MIMEText patch
Patch should be from email.MIMEText import MIMEText
Leave open until fix is included in a release.
$ svn commit -m "Fix imports so mail functionality in glsa-check works with
python versions less than 2.5 (Bug 211706)"
Sending ChangeLog
Sending src/glsa-check/glsa-check
Transmitting file data ..
Committed revision 485.
Patch tested with python-2.5.1 and python-2.4.4
Released in gentoolkit-0.2.4_rc4 | http://bugs.gentoo.org/211706 | crawl-002 | refinedweb | 254 | 54.59 |
#include <wx/html/htmlcell.h>
Internal data structure.
It represents fragments of parsed HTML page, the so-called cell - a word, picture, table, horizontal line and so on. It is used by wxHtmlWindow and wxHtmlWinParser to represent HTML page in memory.
You can divide cells into two groups : visible cells with non-zero width and height and helper cells (usually with zero width and height) that perform special actions such as color or font change.
Constructor.
This method is called.
Converts the cell into text representation.
If sel != NULL then only part of the cell inside the selection is converted.
Renders the cell.
This method is called instead of Draw() when the cell is certainly out of the screen (and thus invisible).
This is not nonsense - some tags (like wxHtmlColourCell or font setter) must be drawn even if they are invisible!
Returns pointer to itself if this cell matches condition (or if any of the cells following in the list matches), NULL otherwise.
(In other words if you call top-level container's Find() it will return pointer to the first cell that matches the condition)
It is recommended way how to obtain pointer to particular cell or to cell of some type (e.g. wxHtmlAnchorCell reacts on wxHTML_COND_ISANCHOR condition).].
Returns descent value of the cell (m_Descent member).
See explanation:
Returns height of the cell (m_Height member).
Returns unique cell identifier if there is any, the empty string otherwise.
Returns hypertext link if associated with this cell or NULL otherwise.
See wxHtmlLinkInfo. (Note: this makes sense only for visible tags).
Returns cursor to show when mouse pointer is over the cell.
Returns cursor to show when mouse pointer is over the specified point.
This function should be overridden instead of GetMouseCursorAt() if the cursor should depend on the exact position of the mouse in the window.
Returns pointer to the next cell in list (see htmlcell.h if you're interested in details).
Returns pointer to parent container.
Returns width of the cell (m_Width member).
Layouts the cell.
This method performs two actions:
It must be called before displaying cells structure because m_PosX and m_PosY are undefined (or invalid) before calling Layout().
This function is simple event handler.
Each time the user clicks mouse button over a cell within wxHtmlWindow this method of that cell is called. Default behaviour is to call wxHtmlWindow::LoadPage.
Sets unique cell identifier.
Default value is no identifier, i.e. empty string.
Sets the hypertext link associated with this cell.
(Default value is wxHtmlLinkInfo("", "") (no link))
Sets the next cell in the list.
This shouldn't be called by user - it is to be used only by wxHtmlContainerCell::InsertCell.
Sets parent container of this cell.
This is called from wxHtmlContainerCell::InsertCell.
Sets the cell's position within parent container. | https://docs.wxwidgets.org/trunk/classwx_html_cell.html | CC-MAIN-2021-17 | refinedweb | 464 | 59.5 |
10-17-2012 12:32 AM - edited 10-17-2012 07:51 AM
Hi everyone
I want to add focusable Images in my app and want the images to fit a specific part of all blackberry screens, I heard about a DPI formula, anyone know anything about this?
Thank you
Solved! Go to Solution.
10-17-2012 05:10 AM
10-17-2012 07:28 AM
seeing as no one is replying. is there a function that I can use in order to make the images in my app more or less the same size?
10-17-2012 07:49 AM
10-17-2012 07:52 AM
Thank you Simon I will keep that in mind for the future reference
10-27-2012 01:37 PM
I am responding to this:
"
Just for clarification resolution is the desnity of the pixles on the screen. A lot of people mix this up with screen size, so they say their screen resoltuion is 320 * 240, which of course is actually the screen size.
In your code, h and v are already resolutions - they are pixels in a meter. Both are the same because BB screens all have the same resolution vertically and horizontally. If you wanted to convert this to dpi (dots/pixels per inch) you would divide by 39.3700787.
So
double inchesInAMeter = 39.3700787;
double hvi= ((double) Display.getHorizontalResolution()) / inchesInAMeter;
should give you what you want.
10-29-2012 01:08 AM - edited 10-29-2012 01:18 AM
Theank you for replying Peter, I have one more question. I used the formula that you gve me and I got the following:
8520 - 162dpi.
9780 - 246dpi.
I did research before hand to get all the DPI's for the cellphones that are in my country and the research stated:
8520 - 164dpi.
9780 - 184dpi.
Do you think the DPI information I got online is inacurate? because I compare my answer from the coded formula to the actual DPI's in the chart I created (Based on research online) to make sure My info is acurate in my code.
I am assuming that if the screen resollutions are the same the DPI will be the same, I just checked out another lin which says that 480 x 360 = 246 DPI (the article is on the 9360) so I am assuming that the DPI applies to the 9780 as well?
Thank you
10-29-2012 05:36 AM
I would trust the calculation, not the documentation.
Here is some different documentation for the 9780.....
"I am assuming that if the screen resollutions are the same the DPI will be the same"
As noted previously, a lot of people use screen resolution to mean the number of pixels on the screen, rather than the density of the pixels. Since I'm not sure what meaning you are using here I can't answer the question.
But when the terms are used correctly, resolution and dpi are technically the same thing, just they might be measured with different units.
BTW, I recommend that you do this calculation in your startup, and have your application size everything appropriately. I suggest this is a lot easier, because you only need one build. I suspect you are doing the calculation on the Simulator and then having a build for each resolution.
10-29-2012 05:38 AM
Thanks Peter
10-29-2012 03:17 PM
Here's a class to convert DPI to the Android format:
public abstract class DisplayUtils { public static final float density = DisplayUtils.getDensity(); private static float getDensity() { float dpi = (Display.getHorizontalResolution() * 0.0254f);
if (dpi <= 135.0f) { return 0.75f; // LDPI } else if (dpi <= 175.0f) { return 1.0f; // MDPI } else if (dpi <= 250.0f) { return 1.5f; // HDPI } else { return 2.0f; // XHDPI } } public int convertPxToDp( int px ) { return (int) ( px * DisplayUtils.density + 0.5f ); } } | http://supportforums.blackberry.com/t5/Java-Development/DPI-formula/td-p/1952915 | CC-MAIN-2014-10 | refinedweb | 642 | 72.36 |
Assignment:Assignment:
Write a program, which will act as a simple four-function calculator. That is it will read a number, read an operator, read another number, then do the operation. The calculator works with integers and uses four functions: +, -, *, and /. After the first operation is completed, the program will read another operator and uses the result of the previous operation as the first value for the next operation. If the user enters a C the result is cleared and then the user starts entering a new number. If the user enters an X, the calculator is turned off. The various input values (i.e. numbers, operators, commands) will be followed by the ENTER key. Your program should prompt the user on what the user is to do. The commands C and X may be entered in place of an operator
This is what I did. I am not sure whether it is right or not. Can anyone help me with this?
Thanks
#include <iostream>
using namespace std;
#include <stdlib.h>
void main()
{
bool InvalidOp;
int Number1;
int Number2;
char op;
cout << "Please enter a number and press enter: ";
cin >> Number1;
cout << "Please enter another number and press enter: ";
cin >> Number2;
cout << "Please enter a a valid operator, 'c' to clear, or 'x' to turn off and press ENTER : ";
cin >> op;
do {
cout << "Enter an operator [+-*/ccXx]: ";
cin >> Op;
InvalidOp = false;
switch (op)
{
case '+':
cout << "The result is: " << Number1 + Number2 << endl;
break;
case '-':
cout << "The result is: " << Number1 - Number2 << endl;
break;
case '*':
cout << "The result is: " << Number1 * Number2 << endl;
break;
case '/':
cout << "The result is: " << Number1 / Number2 << endl;
break;
case 'C':
case 'c':
break;
case 'X':
case 'x':
cout << "Bye" << endl;
exit (0);
default:
cout << "Invalid operator" << endl;
InvalidOp = true;
}
} while (InvalidOp);
} | http://www.codingforums.com/computer-programming/273956-calculator-problem.html?s=1ddf4a09b05563b67d5b7af418164d6c | CC-MAIN-2016-22 | refinedweb | 292 | 59.03 |
Before we begin, it’s worth noting that this article is a sequel, so it presumes sound knowledge of the things we learned in the prior part. That part of the series was also published here, so should you have any doubts, please refer back to it.
There are three kinds of variable types to which threads have access. The first type is local variables, but these are private, meaning that the threads cannot access each other’s variables; plus, if more threads are running the same snippet, then each thread has its own copies of the local variables. Then we have object attributes and static attributes. The latter are reachable by all threads. Object attributes can be shared (explicitly), if necessary.
Since we can work with multiple threads, it makes sense that Java allows more than one thread to be grouped. When we are working with a huge number of threads, this actually simplifies our job, since we can manage threads by their group. Say we’re juggling five threads, and they’re all part of a ThreadGroup. It’s so much easier to stop them by calling the method via the group, rather than doing so independently.
Moreover, we can hierarchically add groups of threads into one thread group. This is how the entire concept turns into a tree-like hierarchy. It should be noted that threads can only access information from their own ThreadGroup, but not their parent’s or other’s. We can work with Threads just like we would with arrays or sets.
Let’s see the following example:
class MyThread extends Thread{
public MyThread (String name){
super(name);
}
public void run(){
try{
for(int i = 0; i < 10; ++i)
sleep(1000);
}
catch(InterruptedException e){}
}
}
class MyThreadGroup{
public static void main (String args[]){
MyThread t[] = new MyThread[10];
for (int i = 0; i < 10; ++i)
t[i] = new MyThread("Thread no: " + i);
for (int i = 0; i < 10; i+=2)
t[i].start();
ThreadGroup grp = Thread.currentThread().getThreadGroup();
int instanceCount = grp.activeCount();
Thread th[] = new Thread[instanceCount];
int activeCount = grp.enumerate(th);
System.out.println("Thread Group Name: " + grp.getName());
System.out.println("Count of Threads: " + instanceCount);
System.out.println("Count of Active Threads: " + activeCount);
System.out.println("List of Active Threads: ");
for (int i = 0; i < activeCount; ++i)
System.out.println(th[i].getName());
grp.interrupt();
}
}
And guess what, the above code snippet has the following output:
Thread Group name: main
Count of Threads: 6
Count of Active Threads: 6
List of Active Threads:
main
Thread no: 0
Thread no: 2
Thread no: 4
Thread no: 6
Thread no: 8
Now it’s time for us to continue with some advanced ideas.
{mospagebreak title=Stopping and Synchronization}
We covered earlier that threads must be started with the start() method. Failing to do so and then running them via run() results in a sequential execution and not what we want, which is multi-threading: simultaneous execution of multiple threads. All right but one might also ask, how do we stop a thread that is running?
There’s a method called stop() that does that—however, its use isn’t advised. That is because there’s a chance it might hog the execution, dragging the system into a stale mate or dead point. The stop() method does not free up allocated system resources. Fortunately, there is a simple and effective workaround. We’re going to introduce a boolean variable (attribute) that always refers to the state of the thread.
Let’s call it isRunning. We declare this as an attribute of the class with the following modifiers: private volatile. At first, surely, this variable starts out as true. However, we will write a method that sets this to false, such as the stopping() thread. Right after that, we can easily modify the run() method so that it runs while isRunning is true.
class MyThread extends Thread{
private volatile boolean isRunning = true;
public void stopping(){
isRunning = false;
}
public void run(){
while (isRunning){
// action goes here
try{
sleep(10);
}
catch (InterruptedException e){}
}
}
Based on the above source code, threads can be stopped by calling the stopping() method instead of the inherited stop(), which might cause problems. This is much safer.
And finally, the time has come for us to talk about synchronization. It is one of the most important concepts when working with multiple threads within an application. In order to fully grasp the concept of synchronized execution, we’re required to also talk about unsynchronized (asynchronous) execution.
If we don’t explicitly “synchronize” the execution of threads, then by all norms they’re executed asynchronously. This kind of multi-threading isn’t reliable because it does not give consistent results. A so-called “race condition” appears, which means the threads are “racing each other” because some operations can be completed faster than others, the processor might have faster access to some data (registers), and so forth.
Moreover, this also means that executing the same application another time does not yield the same results with a 100% guarantee. By definition, a thread becomes synchronized if you become the owner of its object monitor. This is somewhat similar to locking the object. And you can do this in two possible ways.
Each time the program enters a synchronized method, it becomes owner of that object’s monitor (or class monitor in the case of static methods). In a nutshell, this locks the thread’s access to the synchronized method if another thread is already executing it. And this blockage applies until the lock is released by exiting the method or invoking the wait() method. The latter wait() temporarily releases the monitor.
You can make a method synchronized by adding the “synchronized” keyword prior to its declaration. This is the first solution. Another way to make a thread become owner of its object monitor is by using the “synchronized” statement on a common object. The latter is safer because it always releases the lock once the execution is done.
Consider the following example for the synchronized method path.
synchronized void func(…){
…
}
And now let’s see another example for the synchronized common object solution.
void func(…){
// …
synchronized(obj){
// …
}
}
On the next page we’ll tackle inter-thread communication and present an example of the popular producer-consumer model. That problem pops up very frequently as an approach used by professors to explain how inter-thread communication is applied.
{mospagebreak title=Inter-Thread Synchronization and Communication}
Inter-thread communication is all about making synchronized threads communicate with each other. Sometimes one might want to pause (or delay) the execution of a thread until some condition is met. And this condition only occurs if another thread does such and such. To implement these, inter-thread communication is necessary.
Java offers three possible solutions. The following three methods are inherited from the Object class: public final void wait(), public final void notify(), public final void notifyAll(). The first method forces a thread to wait until some other thread calls either notify() or notifyAll() methods. The second notify() method wakes up the thread that invoked the wait() method on the same object. And the third method, notifyAll(), wakes up all of the threads that called the wait() method on the same object.
As mentioned earlier, wait() is defined in the Object class, and it can only be called from a synchronized thread. It may throw an InterruptedException. In short, it releases the lock it is holding on an object’s monitor, thereby allowing other threads to run. The notify() method wakes up any of the threads that are waiting to release the object’s monitor lock. This choice is arbitrary and at the discretion of the JVM.
The awakened threads will resume execution right from where they were paused. The same applies to notifyAll(). Now let’s explain the producer-consumer model. Imagine the shelf of a bookstore, for example. The producer places books on the shelf, while the consumer grabs them. There are two conditions necessary. First, there should be books on the shelf for the consumer to grab. And second, if there are too many books on the shelf, then there isn’t any space left for more books.
The producer and consumer model consists basically of two synchronized threads that should communicate with each other. It’s not that hard at all, but if it is neglected, the results can be disastrous. So this problem is going to implement two of the major concepts we have learned in this article: thread synchronization and inter-thread communication. All right, so let’s begin writing the code!
public class Books{
private int count;
private boolean isReady = false;
public synchronized int grab(){
while (isReady == false){
try{
wait();
}
catch (InterruptedException e){}
}
isReady = false;
notifyAll();
return count;
}
public synchronized void place(int newCount){
while (isReady == true){
try{
wait();
}
catch (InterruptedException e){}
count = newCount;
isReady = true;
notifyAll();
}
}
}
And now the implementation of the Producer class:
public class Producer extends Thread{
private Books myShelf;
private int number;
public Producer(Books b, int number){
myShelf = b;
this.number = number;
}
public void run(){
for (int i = 0; i < 5; ++i){
myShelf.place(i);
System.out.println("Prod No#: " + this.number + " places " +i);
try{
sleep(10);
}
catch (InterruptedException e){}
}
}
}
Finally, here comes the Consumer class as well. Check it out below.
public class Consumer extends Thread{
private Books myShelf;
private int number;
public Consumer(Books b, int number){
myShelf = b;
this.number = number;
}
public void run(){
int val = 0;
for (int i = 0; i < 5; ++i){
val = myShelf.grab();
System.out.println("Cons No#: " + this.number + " grabs " +val);
}
}
}
All that is left is creating a class with public static void main, so that we can launch this application. The last snippet is below.
public class MyClass{
public static void main (String args[]){
Books b = new Books();
Producer p = new Producer (b, 1);
Consumer c = new Consumer (b, 1);
p.start();
c.start();
}
}
And finally, here’s the attached output. Check it out. And we’re done for now!
Prod No#: 1 places 0
Cons No#: 1 grabs 0
Prod No#: 1 places 1
Cons No#: 1 grabs 1
Prod No#: 1 places 2
Cons No#: 1 grabs 2
Prod No#: 1 places 3
Cons No#: 1 grabs 3
Prod No#: 1 places 4
Cons No#: 1 grabs 4
{mospagebreak title=Taking a Break}
As you can see, we have arrived at the end of this sequel article. By now you should know how to work with multiple threads, create them, make them share data and variables between each other, synchronize attributes, manage their states, and make them communicate between each other.
Before we finish, there are two more interesting types of classes regarding threads that we should mention. These are the Timer Class and the TimerTask Class. With the help of these we can schedule some parts of our program. Basically, the scheduled task will be run as a separate thread (like a background thread) when its appropriate time arrives. As a rule of thumb, these timer tasks should be quick, otherwise they might hog and/or speed up (since the task was delayed) the application execution.
Here’s a really quick example; please complete the snippet with the required parts.
class Scheduler{
Timer timer;
public Scheduler(int seconds){
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask{
public void run(){
System.out.println(" Boo! "); // this is the actual task
timer.cancel();
}
}
Thanks for following this series; hopefully, you’ve found it educational. We welcome and appreciate all kinds of feedback in the blog comment section below; thus, feel free to write your opinion, ask questions, and we’ll clarify your dilemmas.
In closing, I’d like to invite you to join our experienced community of technology professionals on all areas of IT&C starting from software and hardware up to consumer electronics at Dev Hardware Forums. Also, be sure to check out the community of our sister site at Dev Shed Forums. We are friendly and we’ll do our best to help you. | http://www.devshed.com/c/a/Java/More-About-Multithreading-in-Java/ | CC-MAIN-2016-30 | refinedweb | 2,008 | 63.49 |
On Sat, Nov 05, 2005 at 01:31:10PM -0500, Randall A. Jones wrote: > I extended an LV to 12.28TB and ran xfs_growfs on the mount point, lv0. > This appeared to work fine except that after this, the filesystem didn't > appear any larger. I looked into this problem awhile back now. I believe what you're seeing here is an inconsistency in the kernels block layer - at least, when I last looked at this, this was the problem - the size increase was indeed done inside the driver, and /sys/block/xxx/size confirmed that, but the interfaces which use /dev/xxx to get the device size do not see the increase (i.e. lseek(SEEK_END) or a BLKGETSIZE64 ioctl). I wrote the attached program to show the issue, and sent mail to LKML to let folks know of the issue, I guess noone has got around to trying to address the problem yet though. The core of the problem was that the /dev/xxx inode size (i_size) had not been updated to reflect the change in device size, IIRC. Hmm, actually, I just went and read through fs/block_dev.c again, and perhaps this is a device mapper bug after all - there is an interface for increasing the inode size (bd_set_size) but it doesn't seem to be called from anywhere in drivers/md/dm*...? Theres one call to the i_size_write interface on the bdev inode, but I can't tell whether it will be called on the resize - perhaps a device mapper guru can tell us? It looks like MD might do the resize correctly though, its got a call in what looks like a device-size-increasing code path. Give this program a try though, just to see if you are seeing the same problem that I was. cheers. -- Nathan
#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/mount.h> #ifndef BLKGETSIZE64 # define BLKGETSIZE64 _IOR(0x12,114,size_t) #endif int main(int argc, char **argv) { __uint64_t size; long long sz = -1; int error, fd; if (argc != 2) { fputs("insufficient arguments\n", stderr); return 1; } fd = open(argv[1], O_RDONLY); if (!fd) { perror(argv[1]); return 1; } error = ioctl(fd, BLKGETSIZE64, &size); if (error >= 0) { /* BLKGETSIZE64 returns size in bytes not 512-byte blocks */ sz = (long long)(size >> 9); printf("%lld 512 byte blocks (BLKGETSIZE64)\n", sz); } else { /* If BLKGETSIZE64 fails, try BLKGETSIZE */ unsigned long tmpsize; error = ioctl(fd, BLKGETSIZE, &tmpsize); if (error < 0) { fprintf(stderr, "can't determine device size"); return 1; } sz = (long long)tmpsize; printf("%lld 512 byte blocks (BLKGETSIZE)\n", sz); } return 0; } | https://www.redhat.com/archives/linux-lvm/2005-November/msg00027.html | CC-MAIN-2014-10 | refinedweb | 437 | 70.43 |
The winnow class uses a heap for finding the best few out of several items. At this it is quicker and shorter than python 2.3's heapq module, which is aimed at queuing rather than sifting. OTOH, it is unlikely to have any advantage over 2.4's heapq, which (I hear) has expanded functionality and is implemented in C.
Discussion
When there are many more candidates than available positions, the time taken usually approaches a linear relationship to the number of candidates, because most new candidates will be rejected at the first comparison. Put another way, it is O(n log k), where n is the number of candidates and k is the size of the elite. Performance is worst when each candidate is better than its predecessors -- the inner loop of winnow.test is exercised for every one.
The simplest way to achieve the same effect would be to sort and slice:
def simpleWinnow(k, p): p.sort() #p.reverse() #depending on which end you want. return p[:k]
This will be best for small, static populations, due to the speed of the builtin sort. But it won't scale well, nor elegantly cope with data that dribbles in slowly.
The operator function can return either true or false for equal values, with different but correct results in either case. The example below shows two case-insensitive winnows seeking the 3 lowest letters.
>>> le = winnow(3, lambda a,b: a.lower() <= b.lower(), 'z', ' ') >>> lt = winnow(3, lambda a,b: a.lower() < b.lower(), 'z', ' ') >>> for z in "abcCdcBA": ... print '%2s %20s %20s' % (z, lt(z), le(z)) ... a ['a'] ['a'] b ['a', 'b'] ['b', 'a'] c ['c', 'a', 'b'] ['c', 'b', 'a'] C ['c', 'a', 'b'] ['C', 'b', 'a'] d ['c', 'a', 'b'] ['C', 'b', 'a'] c ['c', 'a', 'b'] ['c', 'b', 'a'] B ['B', 'a', 'b'] ['b', 'B', 'a'] A ['b', 'a', 'A'] ['B', 'A', 'a']
The first column is the candidate letter, the second column is a winnow using a less-than function, and the third uses less-than-or-equal. Once both are filled up, in the 4th row, they meet a candidate equal to their worst. The lt winnow ignores it, while le absorbs it. Then again in row 6, le swaps two equal values. In row 7, both take in the B, as they should, but le propagates it down to the bottom of the heap, while lt leaves it at the top. Thus both comparisons work, but le does unnecessary work.
The target argument is of dubious benefit. All it does is save a bounds check in winnow.test. Without it, every inner cycle of the test method would need to check a boundary which is rarely exceeded. You would need this:
if child + 1 < self.length and \ self.op(self.heap[child], self.heap[child + 1]): child += 1
instead of
if self.op(self.heap[child], self.heap[child + 1]): child += 1
or, to be overly concise
child += self.op(self.heap[child], self.heap[child + 1])
abject is there to ease the creation of a fixed length heap in the absense of real values. It can also be used to set a threshold, outside of which values will be rejected out of hand. For instance
winnow(10, operator.gt, 7, 1e999)
will select the 10 highest numbers greater than 7. Which might be of use. | http://code.activestate.com/recipes/299058/ | crawl-002 | refinedweb | 567 | 74.19 |
tableiw — Change the contents of existing function tables.
This opcode operates on existing function tables, changing their contents. tableiw is used when all inputs are init time variables or constants and you only want to run it at the initialization of the instrument. The valid combinations of variable types are shown by the first letter of the variable names.
isig -- Input value to write to the table.
indx -- Index into table, either a positive number range matching the table length (ixmode = 0) or a 0 to 1 range (ixmode not equal to 0)
ifn -- Table number. Must be >= 1. Floats are rounded down to an integer. If a table number does not point to a valid table, or the table has not yet been loaded (GEN01) then an error will result and the instrument will be de-activated.
ixmode (optional, default=0) -- index mode.
0 = indx and ixoff ranges match the length of the table.
not equal to 0 = indx and ixoff have a 0 to 1 range.
ixoff (optional, default=0) -- index offset.
0 = Total index is controlled directly by indx, i.e. the indexing starts from the start of the table.
Not equal to 0 = Start indexing from somewhere else in the table. Value must be positive and less than the table length (ixmode = 0) or less than 1 (ixmode not equal to 0).
iwgmode (optional, default=0) -- Wrap and guard point mode.
0 = Limit mode.
1 = Wrap mode.
2 = Guardpoint mode.
Limit the total index (indx + either one less than (iw.
Here is an example of the tableiw opcode. It uses the file tableiw.csd.
Example 904. Example of the table tableiw.wav -W ;;; for file output any platform </CsOptions> <CsInstruments> sr = 44100 ksmps = 32 nchnls = 2 0dbfs = 1 seed 0 ;generate new values every time the instr is played instr 1 ifn = p4 isize = p5 ithresh = 0.5 itemp ftgen ifn, 0, isize, 21, 2 iwrite_value = 0 i_index = 0 loop_start: iread_value tablei i_index, ifn if iread_value > ithresh then iwrite_value = 1 else iwrite_value = -1 endif tableiw iwrite_value, i_index, ifn loop_lt i_index, 1, isize, loop_start turnoff endin instr 2 ifn = p4 isize = ftlen(ifn) prints "Index\tValue\n" i_index = 0 loop_start: ivalue tablei i_index, ifn prints "%d:\t%f\n", i_index, ivalue loop_lt i_index, 1, isize, loop_start ;read table 1 with our index aout oscili .5, 100, ifn ;use table to play the polypulse outs aout, aout endin </CsInstruments> <CsScore> i 1 0 1 100 16 i 2 0 2 100 e </CsScore> </CsoundSynthesizer>
More information on this opcode: , written by Jacob Joaquin | http://www.csounds.com/manual/html/tableiw.html | CC-MAIN-2016-30 | refinedweb | 425 | 73.47 |
I.
Code Generation with Perl
Next, I wrote a Perl script to load the information in the YAML file and generate the packages. You can see the full source for package-generator.pl as well. This script is pretty ugly. I do all the work of generating the information in Perl with embedded here-documents. A much better way to do this would be to use a templating tool like Andy Wardley's Template Toolkit, which is what I'd ultimately like to do.
Basically, this program iterates over all the entries loaded from the YAML file and generates a package for each class. It creates a Perl package name from the Java package name and a Perl package file at the appropriate location in the distribution.
For example,
javax.jcr.nodetype.ItemDefinition gets a Perl package name of
Java::JCR::Nodetype::ItemDefinition and a file location of lib/Java/JCR/Nodetype/ItemDefinition.pm.
The code injects a stock header and footer into the package file. All the real magic happens in between these.
Handling Static Fields
The code adds static fields by modifying the symbol table so that the wrappers point to the automatically generated stubs. For example,
Java::JCR::PropertyType gets several entries like:
*STRING = *Java::JCR::javax::jcr::PropertyType::STRING; *BINARY = *Java::JCR::javax::jcr::PropertyType::BINARY; *LONG = *Java::JCR::javax::jcr::PropertyType::LONG;
For those who may not know, the first line makes the name
Java::JCR::PropertyType::STRING exactly identical to using the longer name,
Java::JCR::javax::jcr::Property::STRING by modifying the symbol table directly.
OK, looking at that, you probably want to know why all the
Inline::Java stubs now have
Java::JCR on the front of them. The reason is that in the generated code, I use the
study_classes() routine to import the Java code and specify that the base package for the import should be
Java::JCR:
study_classes(['javax.jcr.PropertyType'], 'Java::JCR');
Why? It's really not that critical, but I figured that because the name of the package I was putting on CPAN was
Java::JCR, I really didn't want to drop packages into an external namespace while I was at it. Because the wrappers hide all the long names, the actual length of the internal names doesn't matter anyway.
Dealing with Constructors and Methods
After fields, the code checks whether the Java class provides a constructor (that is, if it's a class rather than an interface). As it turns out, I never actually use the code for dealing with constructors for two reasons:
- Exceptions. For reasons I'll explain later, I don't generate the exception classes. Therefore, these constructors go unused.
SimpleCredentials. The only remaining class that has a constructor is
java.jcr.SimpleCredentials, which is the special case I've already mentioned. Therefore, I only need to cope with constructors as a special case. I'll cover the special cases later as well.
After the constructor, the program runs through each method and generates both the static and instance method wrappers. Here's a typical method wrapper from
Java::JCR::Repository:
sub login { my $self = shift; my @args = Java::JCR::Base::_process_args(@_); my $result = eval { $self->{obj}->login(@args) }; if ($@) { my $e = Java::JCR::Exception->new($@); croak $e } return Java::JCR::Base::_process_return($result, "javax.jcr.Session", "Java::JCR::Session"); }
Camel Case
This particular example doesn't show it, but I also changed the camel-case Java names of every method to all lowercase with underscores, which is a much more common way of naming methods in Perl. I may add aliases using the Java names in the future, but I don't care for Java-style naming conventions in Perl code. The most interesting part of this process was handing names that include all-caps abbreviations. That required two lines of Perl:
my $perl_method_name = $method_name; $perl_method_name =~ s/(p{IsLu}+)/_L$1E/g;
The
/(\p{IsLu}+)/ matches any uppercase letter or string of uppercase letters. The replacement applies the
\L modifier to the regular expression to convert the matched snippet to all lowercase. I prepend an underscore to complete the conversion. Thus, the method named
getDescriptor becomes
get_descriptor and the method named
getNodeByUUID becomes
get_node_by_uuid. This won't work very well, by the way, if there are any names that have abbreviations before the end (for example, if there had been a
getUUIDNode, which would become
get_uuidnode) Fortunately, this case never shows up in the JCR API.
Method Wrappers
Java::JCR::Base::_process_arg() processes the arguments passed to each method. This function looks for any of the generated wrapper objects (anything that
isa
Java::JCR::Base) in the list of arguments and unwraps the generated stub by pulling the
obj key out of the blessed hash.
sub _process_args { my @args; for my $arg (@_) { if (UNIVERSAL::isa($arg, 'Java::JCR::Base')) { push @args, $arg->{obj}; } else { push @args, $arg; } } return @args; }
The wrapper then executes the wrapped method on the generated stub by passing it the unwrapped arguments (as if the wrappers weren't there).
I make sure to wrap every call in an
eval because
Inline::Java passes Java exceptions as Perl exception objects. If an exception is thrown, I wrap it in a custom class named
Java::JCR::Exception, which I wrote by hand.
Finally, the code returns the result. If the return type has a wrapper, as is the case in
login()), I use
Java::JCR::Base::_process_return() to cast the class and wrap it.
sub _process_return { my $result = shift; my $java_package = shift; my $perl_package = shift; # Null is null if (!defined $result) { return $result; } # Process array results elsif ($java_package =~ /^Array:(.*)$/) { my $real_package = $1; return [ map { bless { obj => cast($real_package, $_) }, $perl_package } @{ $result } ]; } # Process scalar results else { return bless { obj => cast($java_package, $result), }, $perl_package; } }
This brings up two considerations: Why the custom exception class? Why do I need to cast the object? In both cases, I do this to handle minor issues in
Inline::Java.
In the case of exceptions, the generated exception objects don't handle Perl stringification very well. Because a lot of exception handlers assume that exceptions are strings or properly stringified, this can be (and has been for me) a problem. My exception class makes sure stringification works the right way.
As for the cast,
Inline::Java works on the assumption that you want to use the class in its most specific form, but if it hasn't studied that form, you get a generic object on which you cannot call any methods. Rather than engage the potentially costly
AUTOSTUDY option to make sure
Inline::Java studies everything and then smarten up the wrappers more, I've chosen to cast the objects into the expected return type. This does limit some of the flexibility.
Other than the custom pieces, I needed some additional helpers to get the job done. I didn't want to write out a lot of
use statements to use this library. As a JAPH, I like to keep things simple. Therefore, if I need to use the JCR and Jackrabbit, I just want to say:
use Java::JCR; use Java::JCR::Jackrabbit;
I included a package loader in the main package, Java::JCR, that will take care of these details and then created a package for each of the subpackages in the JCR. The loader looks like:
sub import_my_packages { my ($package_name, $package_file) = caller; my %excludes = map { $_ => 1 } @_; my $package_dir = $package_file; $package_dir =~ s/.pm$//; my $package_glob = File::Spec->catfile($package_dir, '*.pm'); for my $package (glob $package_glob) { $package =~ s/^$package_dir///; $package =~ s/.pm$//; $package =~ s///::/g; next if $excludes{$package}; eval "use ${package_name}::$package;"; if ($@) { carp "Error loading $package: $@" } } }
I make sure to call that method once the package has finished loading and pass in exclusions to keep it from loading all the subpackages. This needs further enhancement to allow for future extensions under the
Java::JCR namespace, so as not to load them automatically, but this is a good starting point. I built one class for each subpackage, then, that inherits from Java::JCR and then calls this method to load each of those classes.
Connecting to Jackrabbit
Obviously, the next step was to create the code to connect to Jackrabbit. This was done in Java::JCR::Jackrabbit. The initial implementation is very simple:
use base qw( Java::JCR::Base Java::JCR::Repository ); use Inline ( Java => 'STUDY', STUDY => [], ); use Inline::Java qw( study_classes ); study_classes(['org.apache.jackrabbit.core.TransientRepository'], 'Java::JCR'); sub new { my $class = shift; return bless { obj => Java::JCR::org::apache::jackrabbit::core::TransientRepository ->new(@_), }, $class; }
I extended Java::JCR::Repository to add a constructor that calls the Jackrabbit constructor. Done.
Handling Special Cases
With all that work, I still couldn't make the second hop because I still hadn't resolved the whole problem of passing an array of characters. However, with the infrastructure I had in place, this was now solvable.
I created an additional YAML configuration file named specials.yml. This file contains hand-coded alternatives to use where appropriate. I then wrote an alternative for the new constructor:
javax.jcr.SimpleCredentials: new: |- sub new { my $class = shift; my $user = shift; my $password = shift; my $charArray = Java::JCR::PerlUtils->charArray($password); return bless { obj => Java::JCR::javax::jcr::SimpleCredentials->new($user, $charArray), }, $class; }
Then, I reran the generator script. Fortunately, I had already improved it to use any implemented method or constructor rather than generating one automatically.
To perform the conversion, I also needed to embed a little extra Java code. I wrote a very small Java class called
PerlUtils for handling the conversion:
use Inline ( Java => <<'END_OF_JAVA', class PerlUtils { public static char[] charArray(String str) { return str.toCharArray(); } } END_OF_JAVA );
Given a string, it returns an array of characters to pass back into the
SimpleCredentials constructor. No other work is necessary. I could now perform the JCR second hop in Perl. That script attaches to a Jackrabbit repository, logs in as "username" with password "password" and then creates a node.
Using Handles as InputStreams
The third (and final) hop of the Jackrabbit tutorial demonstrates node import using an XML file. However, in order to perform the import shown, you must pass an
InputStream off to the
importXML() method. While
Inline::Java provides the ability to use Java
InputStreams as Perl file handles, it doesn't provide the mapping in the opposite direction. Thus I needed another special handler and an additional set of helper methods.
The special code configuration looks like:
javax.jcr.Session: import_xml: |- sub import_xml { my $self = shift; my $path = shift; my $handle = shift; my $behavior = shift; my $input_stream = Java::JCR::JavaUtils::input_stream($handle); $self->{obj}->importXML($path, $input_stream, $behavior); }
This calls the
input_stream() method, which is a Perl subroutine.
sub input_stream { my $glob = shift; my $glob_val = $$glob; $glob_val =~ s/^\*//; my $glob_caller = Java::JCR::GlobCaller->new($glob_val); return Java::JCR::GlobInputStream->new($glob_caller); }
As you can see, this subroutine uses two separate Java classes to provide the interface from a Perl file handle to Java
InputStream. The first class,
Java::JCR::GlobCaller, performs most of the real work using the callback features provided by
Inline::Java. It gets passed to the
Java::JCR::GlobInputStream, which calls
read() whenever the JCR reads from the stream:
public int read() throws InlineJavaException, InlineJavaPerlException { String ch = (String) CallPerlSub( "Java::JCR::JavaUtils::read_one_byte", new Object[] { this.glob }); return ch != null ? ch.charAt(0) : -1; }
The
read_one_byte() function is a very basic wrapper for the Perl built-in
getc.
sub read_one_byte { my $glob = shift; my $c = getc $glob; return $c; }
With this in place, you can now perform the third JCR hop in Perl. By executing this script, you will connect to a repository, log in, and then create nodes and properties from an XML file.
Getting Ready to Distribute
The implementation is now, more or less, complete. You can use
Java::JCR to connect to a Jackrabbit repository, log in, create nodes and properties, and import data from XML. There's a lot left untested, but the essentials are now present. With this done, I was ready to begin getting ready for the distribution. However, because some Java libraries are requirements to use the library, the library has some special needs to build and install easily. You should be able to install it by just running:
% cpan Java::JCR
I needed a way to build this library. My preferred build tool is Ken Williams' Module::Build. It's in common use, compatible with the CPAN installer, and cooperates well with g-cpan.pl, which is a packaging tool for my favorite Linux distribution, Gentoo. Finally, it's easy to extend.
When customizing
Module::Build, I prefer to create a custom build module rather than by placing the extension directly inline with the Build.PL file. In this case, I've called the module Java::JCR::Build. I placed it inside a directory named inc/ with the rest of the tools I built for generating the package.
After creating the basic module that extends
Module::Build, I added a custom action to fetch the JAR files called
get_jars. I also added the code to execute this action on build by extending the
code ACTION:
sub ACTION_get_jars { my $self = shift; eval "require LWP::UserAgent" or die "Failed to load LWP::UserAgent: $@"; my $mirror_dir = File::Spec->catdir($self->blib, 'lib', 'Java', 'JCR'); mkpath( $mirror_dir, 1); my $ua = LWP::UserAgent->new; print "Checking for needed jar files...n"; while (my ($file, $url) = each %jars) { my $path = File::Spec->catfile($mirror_dir, $file); $self->add_to_cleanup($path); next if -f $path; my $response = $ua->mirror($url, $path); if ($response->is_success) { print "Mirroring $url to $file.n"; } elsif ($response->is_error) { die "An error occurred fetching $url to $file: ", $response->status_line, "n"; } } } sub ACTION_code { my $self = shift; $self->ACTION_get_jars; $self->SUPER::ACTION_code; }
I use Gisle Aas's LWP::UserAgent to fetch the JAR files from the public Maven repositories and drop them into the build library folder, blib.
Module::Build will take care of the rest by copying those JAR files to the appropriate location during the install process.
I also needed some code in
Java::JCR to set the
CLASSPATH correctly ahead of time:
my $classpath; BEGIN { my @classpath; my $this_path = $INC{'Java/JCR.pm'}; $this_path =~ s/.pm$//; my $jar_glob = File::Spec->catfile($this_path, "*.jar"); for my $jar_file (glob $jar_glob) { push @classpath, $jar_file; } $classpath = join ':', @classpath, ($ENV{'CLASSPATH'} || ''); $ENV{'CLASSPATH'} = $classpath; }
This bit of code asks Perl for the path to the location of this library, which I assume is the installed location of the JAR files. Then, I find each file ending with .jar in that directory and put them into the
CLASSPATH. Unfortunately, my code assumes a Unix environment when it uses the colon as the path separator. A future revision could make sure that this works on other systems as well, but because I use only Unix-based operating systems, my motivation is lacking.
With all that, you can now deploy this by downloading the tarball and running:
% perl Build.PL % ./Build % ./Build test % ./Build install
It works!
Testing
I haven't mentioned this yet, but during the whole process of building this library, I also built a series of test cases. You can find these in the t/ directory of the distribution. The first few tests are actually just variations on the Jackrabbit tutorial, as well as a test to make sure the POD documentation contains no errors (every module author should use this test; you can just copy and paste it into any project).
Final Thoughts
I love Perl. This port from Java to Perl was easier than I would have thought possible. I wanted to share my success in the hopes of spurring on others. Kudos go to Ken Williams and Patrick LeBoutillier and the others that have assisted them to build the tools that made this possible.
Cheers. | http://www.perl.com/pub/java/ | CC-MAIN-2016-07 | refinedweb | 2,640 | 52.9 |
How to extract all functions and API calls used in a Python source code?
Let us consider the following Python source code;
def package_data(pkg, roots): data = [] for root in roots: for dirname, _, files in os.walk(os.path.join(pkg, root)): for fname in files: data.append(os.path.relpath(os.path.join(dirname, fname), pkg)) return {pkg: data}
From this source code, I want to extract all the functions and API calls. I found a similar question and solution. I ran the solution given here and it generates the output
[os.walk, data.append]. But I am looking for the following output
[os.walk, os.path.join, data.append, os.path.relpath, os.path.join].
What I understood after analyzing the following solution code, this can visit the every node before the first bracket and drop rest of the things.
import ast class CallCollector(ast.NodeVisitor): def __init__(self): self.calls = [] self.current = None def visit_Call(self, node): # new call, trace the function expression self.current = '' self.visit(node.func) self.calls.append(self.current) self.current = None def generic_visit(self, node): if self.current is not None: print("warning: {} node in function expression not supported".format( node.__class__.__name__)) super(CallCollector, self).generic_visit(node) # record the func expression def visit_Name(self, node): if self.current is None: return self.current += node.id def visit_Attribute(self, node): if self.current is None: self.generic_visit(node) self.visit(node.value) self.current += '.' + node.attr tree = ast.parse(yoursource) cc = CallCollector() cc.visit(tree) print(cc.calls)
Can anyone please help me to modified this code so that this code can traverse the API calls inside the bracket?
N.B: This can be done using regex in python. But it requires a lot of manual labors to find out the appropriate API calls. So, I am looking something with help of Abstract Syntax Tree.
1 answer
- answered 2018-07-20 21:25 MSeifert
Not sure if this is the best or simplest solution but at least it does work as intended for your case:
import ast class CallCollector(ast.NodeVisitor): def __init__(self): self.calls = [] self._current = [] self._in_call = False def visit_Call(self, node): self._current = [] self._in_call = True self.generic_visit(node) def visit_Attribute(self, node): if self._in_call: self._current.append(node.attr) self.generic_visit(node) def visit_Name(self, node): if self._in_call: self._current.append(node.id) self.calls.append('.'.join(self._current[::-1])) # Reset the state self._current = [] self._in_call = False self.generic_visit(node)
Gives for your example:
['os.walk', 'os.path.join', 'data.append', 'os.path.relpath', 'os.path.join']
The problem is that you have to do a
generic_visitin all
visits to ensure you walk the tree properly. I also used a list as
currentto join the (reversed) afterwards.
One case I found that doesn't work with this approach is on chained operations, for example:
d.setdefault(10, []).append(10).
Just in case you're interested in how I arrived at that solution:
Assume a very simple implementation of a node-visitor:
import ast class CallCollector(ast.NodeVisitor): def generic_visit(self, node): try: print(node, node.id) except AttributeError: try: print(node, node.attr) except AttributeError: print(node) return super().generic_visit(node)
This will print a lot of stuff, however if you look at the result you'll see some patterns, like:
... <_ast.Call object at 0x000001AAEE8FFA58> <_ast.Attribute object at 0x000001AAEE8FFBE0> walk <_ast.Name object at 0x000001AAEE8FF518> os ...
and
... <_ast.Call object at 0x000001AAEE8FF160> <_ast.Attribute object at 0x000001AAEE8FF588> join <_ast.Attribute object at 0x000001AAEE8FFC50> path <_ast.Name object at 0x000001AAEE8FF5C0> os ...
So first the call-node is visited, then the attributes (if any) and then finally the name. So you have to reset the state when you visit a call-node, append all attributes to it and stop if you hit a name node.
One could do it within the
generic_visitbut it's probably better to do it in the methods
visit_Call, ... and then just call
generic_visitfrom these.
A word of caution is probably in order: This works great for simple cases but as soon as it becomes non-trivial this will not work reliably. For example what if you import a subpackage? What if you bind the function to a local variable? What if you call the result of a
getattrresult? Listing the functions that are called by static analysis in Python is probably impossible, because beside the ordinary problems there's also frame-hacking and dynamic assignments (for example if some import or called function re-assigned the name
osin your module). | http://quabr.com/51449914/how-to-extract-all-functions-and-api-calls-used-in-a-python-source-code | CC-MAIN-2019-13 | refinedweb | 763 | 52.05 |
Python Programming, news on the Voidspace Python Projects and all things techie.
Happy Birthday Resolver
Resolver the company, and the fledgling application, is now one year old [1].
Around this time in 2005 Giles & William started work on the functional test suite so that they could build Resolver.
Originally they decided to write Resolver as a .NET application using C#. .NET is a great framework for writing professional programs. They started to search for a scripting language to embed into Resolver. The choices were between Ruby [2] and Python, and IronPython was further advanced than the Ruby alternatives.
Neither of them had used Python before, but after playing with it for a bit they realised that it could be a lot easier to write Resolver in IronPython.
In early 2006 Andrzej joined (ironically a Ruby programmer) and I joined in around April or so. More recently Christian and Jonathan have joined the team.
Resolver today is around 15 000 lines of production code (98% Python code and the rest C#) and 45 000 lines of test code [3]. We have completed over eighty user stories.
There are only two 'showstopper' missing features before we could theoretically put Resolver into the hands of (friendly) customers. These are printing and charting. We've spiked [4] these this week and could have 'first-cut' implementations in place pretty quickly.
We have just started to show Resolver to a few potential customers. We're not yet ready for beta, but we're getting some very good feedback. We're hoping to be able to do a limited beta around spring next year.
Resolver processes 'business data', and yes that tells you next to nothing. It has Python integrated into it in a very interesting way.
The good news is that the board are considering the possibility of a 'community edition', free for non-commercial use. This isn't definite, and there is no timescale, but you guys could do some amazing stuff with Resolver.
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-12-07 22:06:38 | |
Categories: Work, IronPython
Basic Hints for Windows Command Line Programming or the Shell environment.
This article is a tutorial on setting up a basic command line environment. It contains a few tips and tricks specific to Python, but should be useful to anyone who wants to set-up the console.
The article covers topics like:
- Running and using the cmd console
- Configuring the console including QuickEdit mode
- Setting up the PATH and PATHEXT environment variables
Please point out any errors, or things I've missed, by posting a comment.
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-12-05 21:03:56 | |
Categories: Python, General Programming, Computers, Tools
IronPython, Old Style Classes and Performance
Today my boss and I were running a build chasing a checkin. We'd made various minor changes, but nothing serious. Surprisingly our performance test failed. It tests that processing a moderate sized dataset takes no more than a second. On my machine it normally takes around 0.75 seconds, suddenly it was consistently taking 2.1 seconds.
We backed out our changes until we isolated the cause. One of our classes had been an old style class, and we'd made it a new style class purely out of habit.
The class is used in our 'processing pipeline', so it gets instantiated and then called quite a few times; but only in one stage of the whole operation. Changing the class to inherit from object slowed our performance test down three times.
I've reduced it to a simple test case for both Python and IronPython; to see if it's reproducible. It accesses a few instance attributes to be slightly closer to our code.
The test code for Python is :
def timeItOldStyle():
class Example:
def __init__(self):
self.x = None
self.y = None
self.z = None
def __call__(self):
x = self.x
y = self.y
z = self.z
start = time.time()
for i in range(100000):
Example()()
return time.time() - start
def timeItNewStyle():
class Example(object):
def __init__(self):
self.x = None
self.y = None
self.z = None
def __call__(self):
x = self.x
y = self.y
z = self.z
start = time.time()
for i in range(100000):
Example()()
return time.time() - start
print 'Old Style:', timeItOldStyle()
print 'New Style:', timeItNewStyle()
For IronPython I replaced the timing code with the following (because time.time() has a resolution of 0.1 seconds and I was getting weird results with time.clock()) :
start = System.DateTime.Now
...
total = (System.DateTime.Now - start).TotalMilliseconds / 1000
The results :
>python PythonPerformance.py Old Stle: 0.233999967575 New Stle: 0.25 >ipy IronPythonPerformance.py Old Stle: 0.1875 New Stle: 0.625
Under CPython old style and new style are very similar.
For IronPython, the old style classes are slightly faster than CPython. The new style classes are dramatically slower. Hmm... worth bearing in mind.
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-12-04 22:19:29 | |
Categories: Python, IronPython, Hacking
Python and its Basic Datatypes
You can blame this entry on Ryanair and a six hour wait for a delayed plane. Ok, so most of the wait was spent playing Super Mario Kart [1], but whilst my laptop battery lasted I made a start on the tutorial I've been intending to write for ages.
It is a brief introduction to Python and its basic data-types. It covers syntax for strings, numbers, lists, dictionaries, sets and tuples. It doesn't cover the methods, just basic usage.
In the process of writing this I realised how many syntax variations there are for strings. That made it a tad longer than it could have been.
At some point I may write that tutorial, but in the meantime...
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-12-03 19:08:43 | |
Categories: Python, Writing
Motherboards, Processors and Power Supplies: Oh My!
Ok, so back to my dead computer.
I've confirmed that the power supply is dead, and the motherboard doesn't draw power from a working power supply. The standby LED does come on though.
So the power supply is definitely dead and the motherboard is probably dead... or is it the processor.
Unfortunately the only way to find out is to get a new motherboard and try it. The old motherboard is an ASUS A7N8X, which is a socket A motherboard for the Athlon XP 3000+ processor it lovingly cradles.
The A7N8X must have been a popular motherboard. You can buy a new motherboard for 20 pounds, but you can pay 40 pounds or more for a secondhand A7N8X on ebay.
So I need a new socket A motherboard, except new motherboards seem to come in a variety of delicious flavours like socket 939, 754, AM2 and in fact anything except socket A. sigh
Hopefully the lazy web will come to my rescue...
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-12-03 16:07:36 | |
PyCon Talk Presentation Tools (and stuff)
It's time to start preparing for the PyCon talk. We need to decide on how to prepare the slides.
I am a big fan of ReStructured Text, so S5 is looking good (and it makes good looking presentations to boot).
Bruce also looks interesting.
Note
Bruce is really very good. Unfortunately getting it to produce an interactive demonstration with IronPython is probably out of reach for me before the conference.
S5 / Docutils produces a more immediately web friendly presentation.
Crunchy Frog is fantastic (run the demo). I wonder if it could be made to work with IronPython ? It is more aimed at creating tutorials than presentations though.
Anyone got any recommendations or comments ?
Personally I rarely find slideshows from a talk I've not been to that useful. I hope to prepare more information to go alongside the slides. Perhaps a link from each slide for those reading online.
Some of the talks look great.
With such a great lineup it is inevitable that there will be some clash of talks I'd love to go to. From the draft conference schedule :
On Friday, the Python-Dev Panel clashes with Towards and Beyond PyPy 1.0 and Writing Parsers and Compilers with PLY clashes with both the Web Frameworks Panel and IronPython: Present and futures [1].
On Saturday, Distributing your project with Python Eggs clashes with The Absolute Minimum an Open Source Developer Must Know About Intellectual Property [2].
The testing track on Sunday looks great. If the schedule doesn't change I'll only have to miss the first one, which is the least interesting from my point of view.
Whilst we're on the subject of PyPy (which we were at least vaguely...), there is an interesting note on the Psyco Homepage (See 6th August 2005).!
From the PyPy Duesseldorf Sprint Report :.
Now that's why I want to go to the PyPy talk. sigh
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-12-03 14:55:37 | |
Categories: Tools, Python
Google, Mondrian, Python and Guido
Wow. Hot news..
News from Niall Kennedy's Weblog.
So Guido is earning his pay-check at google building a web-based code review system with Python... Cool. It is backended with Perforce. Niall Kennedy's blog entry suggests that google could open source it once they have provided Subversion and SQLite backends.
From my point of view pair programming and collective code ownership beats code review, but maybe they're not mutually exclusive.
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-12-02 21:41:00 | |
Nested Lambda Fun
At work we did a partial implementation of the Python grammar using PLY (for reasons which will become obvious at some point in the future if you continue to read this blog).
Because of this I knew it was possible to nest lambdas, I'd just never tried it.
Muharem Hrnjadovic has just posted about his problems with functools.partial and operator.lt. Because operator.lt is a built-in function, it doesn't take keyword arguments, so he can't use partial to fill in the second argument.
Whilst this doesn't invalidate his general point, you can achieve his specific aim with a nested lambda. Shown is a function (lessthansomething) which takes an argument (something). It returns a function which takes an argument and returns True if the argument is less than something. All in a oneliner
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> lessthansomething = lambda something : lambda x : x < something >>> lessthansomething <function <lambda> at 0x00B43270> >>> lessthan3 = lessthansomething(3) >>> lessthan3 <function <lambda> at 0x009E9AB0> >>> lessthan3(2) True >>> lessthansomething(6)(7) False >>>
Don't do this at home [1], but it's still fun.
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-12-02 21:09:19 | |
Categories: Python, Hacking
Earliest Known Pythoneers and the Real Meaning of Pythonic
It has just been discovered that there have avid Pythoneers around for about 70 000 years.
Additionally, according to Webster's Revised Unabridged Dictionary 1913 edition, "Pythonic" means "Prophetic":
Py*thon"ic (?), a. [L. pythonicus, Gr. . See Pythian.] Prophetic;oracular; pretending to foretell events.
(Which apparently comes from Greek mythology and the oracle at Delphi.)
All taken (with a large pinch of salt) from the folks at Python-Dev.
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-12-02 20:23:55 | |
Archives
This work is licensed under a Creative Commons Attribution-Share Alike 2.0 License.
Counter... | http://www.voidspace.org.uk/python/weblog/arch_d7_2006_12_02.shtml | crawl-002 | refinedweb | 2,095 | 77.03 |
BOTANICAL SOCIETY OF AMERICA
OPERATIONAL PROCEDURES
AND ACCOUNTING MANUAL
Revised May, 2011
I. OVERVIEW OF ORGANIZATION
BOTANICAL SOCIETY
OF AMERICA (BSA)
AMERICAN JOURNAL
OF BOTANY (AJB)
II.QUICKBOOKS ONLINE ACCOUNTING
CHART OF ACCOUNTS
& CLASSES
DUES PROCESSING
INSTITUTIONAL SUBSCRIPTIONS
PAYROLL
ACCOUNTS PAYABLE
PETTY CASH
BANK ACCOUNTS
BANK
RECONCILIATIONS
INSURANCE
POLICIES
ENDOWMENT
FUND & SALOMON SMITH BARNEY ACCOUNTING
ACCOUNTANT
RESPONSIBILITIES
ANNUAL BUDGETS
MONTHLY / ANNUAL CLOSE OF
BOOKS
DONATIONS TO THE
BSA
QUID PRO DONATIONS
TO THE BSA
RECORD RETENTION
MONTHLY / ANNUAL CHECKLIST
III. WEB SITE & DATABASE MANAGEMENT
WEBSITE MANAGEMENT
ONLINE
DUES PROCESSING
DATABASE
MANAGEMENT
IV. INTERNAL CONTROL
OPENING MAIL
& CASH RECEIPTS
BANK
RECONCILIATIONS
V. GRANT MANAGEMENT & ADMINISTRATION
VI. ANNUAL MEETING
VI. SECTION & SPECIAL FUNDS ACCOUNTS
SECTIONS
Allotment
Allocation
Use
of Allotments
SPECIAL ACCOUNTS
BSA
Unrestricted Funds
BSA
Endowment Fund
BSA
Educational Fund
BSA
Botanical Friends Fund
BSA
PlantingScience Fund
Vernon
I Cheadle Fund
Michael
Cichan Fund
Conant
Travel Fund
Isabel
Cookson Fund
Leasure
K. Darbaker Fund
Katherine
Esau Fund
Donald Kaplan Fund
John
S. Karling Fund
Margaret
Menzel Fund
Maynard
Moseley Fund
Winfried
and Reneta Remy Fund
James M. and Esther N. Schopf Fund
A. J. Sharp
Thorhaug Fund
Grady L. Webster Fund
Wilson Fund
Supporting Documents - BSA Bylaws, BSA Policies
The Botanical Society of America (BSA) is a "not-for-profit"
membership society that exists to promote botany, the field of
basic science dealing with the study and inquiry into the form,
function, diversity, reproduction, evolution, and uses of plants
and their interactions within the biosphere.
For tax purposes, they are a 501©(3) organization that was
originally incorporated in Connecticut – TAX ID# 62-0671591.
Member Kent Holsinger is our agent for service in the state of
Connecticut and files the incorporation renewal with the CT Secretary
of State every 2 years. The administrative offices of the BSA
are located in St. Louis, Missouri adjacent to the Missouri Botanical
Gardens (MOBOT) and MOBOT provides the site and support services
to the BSA.
Sales tax – the BSA has no obligation to charge sales tax
for internet sales. All internet sales across state lines are
not subject to sales tax (as of now…).
As the BSA operates as a non-profit in Missouri, they have applied
for and received an exemption so they don’t have to charge
sales tax (which would normally apply to merchandise sales to
Missouri residents). Their Tax Exempt# 18473598.
The BSA is registered as a non-profit organization with the Missouri
Secretary of State.
The BSA has a fiscal year of October 1st to September 30th. Prior
to 1999, the organization had a June fiscal year end but it was
changed to encompass the Annual Meeting activity in July/August.
Missouri does not require a corporate or non-profit return filing
so the Association only files an annual federal non-profit tax
return, form 990. This form is available online at a national
non-profit website located at:. As a non-profit
, the Association is required to provide a current copy of their
tax return to any person or organization that requests it (and
the BSA can charge them a copy or mailing fee).
The BSA formerly had their administrative offices in Columbus,
Ohio and they still have one employee who works from her home
and administers the Annual Meeting for the BSA.
The Botanical Society of America publishes a magazine called
the American Journal of Botany; an online subscription is included
in each annual membership fee. Apart from members, institutional
subscribers (clients) also purchase the magazine.
The editorial office in New York (onsite at Cornell University)
handles the editing & publishing of the AJB magazine on a
monthly basis; Karl Niklas is the current editor.
Allen Press handles the publication of the monthly AJB and, as
part of their processing, creates the electronic files that are
then forwarded to Stanford High Wire Press who publishes the journal
electronically via the web site.
The Editorial office is provided gratis by Cornell University
and the BSA has an immaterial amount of money invested in equipment
there. The BSA does carry liability and workers compensation insurance
on the NY office with Traveler’s Insurance Co. $1,500 is
paid each quarter to Cornell to cover the out-of-pocket costs
of the magazine incurred by Cornell – office supplies, postage,
etc.
The Plant Science Bulletin is another publication of the BSA printed
quarterly & published by a volunteer committee who prepares
the info on MS Pagemaker and directly submits to Allen Press.
The BSA’s accounting records are kept online with Quickbooks.
That site is located at. Quickbooks/Intuit
is responsible for the daily backup of this information at an
off-site server.
Separate sign-ins are available for Wanda (St. Louis office),
Johanne (working from home in Ohio), and Mary (off-site accountant).
All financial reporting is done through the online Quickbooks
program.
See the attached appendix for the full chart of accounts
As part of the accounting, each Income and Expense transaction
is also posted to a specific department, called Class, within
Quickbooks. This allows the reporting of BSA results by the following
classes:
1 – St. Louis
2 – AJB (American Journal of Botany)
3 – EC (Executive Committee)
4 – Annual Meeting Activity
5 – Sections and Special Interest Accounts
6 – Awards
7 – Investment activity
8 – PSB (Plant Science Bulletin)
Income is generated from these different areas:
In addition to individual members, the AJB magazine is also available
by subscription to businesses and institutions (academic and non-academic)
in either a print or online version.
These are based on a different pricing system than the individual
member subscription and are recorded separately in the accounting.
The majority of the institutional subscriptions are handled by
agents (Ebsco, Swets Information Services) who do the actual invoicing
to the institution. They then send a lump sum check to the BSA
with the various client payments attached.
Other than one agent, Swets/Blackford, these have not been converted
to an electronic system for easy download into the database. The
Administrative Coordinator inputs them manually into the database.
There are two employees of the BSA in the St. Louis, MO office:
Bill Dahl, the Executive Director, and Wanda Lovan, the Administrative
Coordinator.
They are ‘officially’ employed by the Missouri Botanic
Garden (MOBOT) and fall under the MOBOT umbrella for fringe benefits,
including retirement, workers compensation coverage, and sick
and vacation time. The BSA reimburses MOBOT for their out-of-pocket
costs on these employees.
The BSA has a personnel committee which oversees the performance
and employee reviews for both of these employees.
All operational and section cash disbursements are made from
the BSA’s primary bank account at Commerce Bank.
Within Quickbooks, checks are written through the menu option
Banking, Write Checks. The bank account is #1025, Commerce Bank.
Choose a payee from the vendor list (drop down arrow to the right
of Payee field), input the amount & memo, and then post to
a specific Account (drop down arrow to the right of the Account
field), and add a Class.
Leave the ‘to be printed’ box checked so the system
can automatically assign check numbers when printing checks.
Then go to Banking, Print Checks, change the bank account to
#1025 and add the starting check number. Put the computer checks
in the printer & then print. Align as needed to fit the check
form.
When a check is first written to fund the petty cash drawer, that
payment is posted to Account# 1020 – Petty Cash Missouri.
As cash is used up, the receipts are collected so that they may
be entered into the accounting system as expenses.
To re-fund the cash drawer, a check is written to cash for the
new amount to replenish the drawer. Simultaneously, a journal
entry is recorded in Quickbooks to record how the previous cash
was spent.
A sample journal entry is recorded as:
Debit: Office Expense (for receipts on hand) $35.
Debit: Meals Expense (for receipts on hand) $50
Credit: Petty Cash/MO $85.
As with any payment, a class designation needs to be input for
each expense entry.
At any time, the balance for Petty Cash in the financial statements
should match the combination of the cash on hand plus the receipts
in the drawer.
Example:
Starting cash to fund drawer $100
Receipts on hand ($85)
Net cash on hand $ 15
Add: new check to replenish funds $100
Equals: cash on hand in drawer $115
Commerce Bank, Missouri (2) – there are two accounts, a
general checking and a sweep (savings) account. Both are administered
by the St. Louis administrative office. Online access is available
for both accounts. Authorized signatures on the account are: __________
Bank One, Ohio – this is the Meeting account used solely
by Johanne Stogran to collect income and pay expenses for the
Annual Meeting. Authorized signatures on the account are: Johanne
Stogran and Joe Armstrong, Treasurer and Bill Dahl ??
Salomon Smith Barney accounts (3) – these three accounts
are overseen by the Finance Committee and include the BSA endowment
and long-term savings of the Association. The bank statements
are directly sent to the Treasurer, Joe Armstrong, and the CPA,
Mary Widiner, who reconciles the statements online. The St. Louis
business office has online access to these accounts.
Huntington Bank, Ohio – pending closure; this is the old
account used by the old administrative offices in Columbus, Ohio
Santa Barbara Bank & Trust (2) – pending closure; these
are two accounts, checking and savings, used by the Treasurer,
Joe Armstrong. All future expenses will be paid through the main
administrative account in St. Louis
American Century, Ohio – pending closure; this is a savings
account used by the old administrative offices in Columbus, Ohio.
These are prepared monthly for all open bank accounts. Use Quickbooks
help for additional instruction.
When the bank reconciliation is complete, print a copy of that
month’s check register and save it with the bank reconciliation
summary/detail report.
The BSA keeps the following policies:
Traveler’s – Commercial, Liability and Worker’s
Comp for the NY Editorial Office
Traveler’s - $3 million Commercial Umbrella coverage for
the Annual Meeting
Insurance for the St. Louis, Missouri administrative offices
is paid for by the MOBOT (who owns the offices).
Worker’s compensation insurance is provided for by Ohio
State (for Johanne/Meeting Coordinator) and by MOBOT for the St.
Louis employees.
Old Republic - there is a fidelity bond for $100,000 that renews
every 3 years in August. The last premium paid was $814 for the
policy period 8/8/2001 thru 8/8/2004 – Premium# FLA0367382,
Agency 92-2857. HRH is the agent for renewal – phone# 352-378-2511.
In 1993, the BSA created an endowment fund with the purpose of
increasing the monetary assets of the Society to provide income
for funding major initiatives, travel grants, scholarships, and
other activities within its Mission. The Financial Advisory Committee
(FAC) has been given the authority to manage this fund.
There are currently 3 accounts held at Salomon Smith Barney that
hold these endowment funds, and which are invested in a mixture
of stocks, corporate bonds, and cash. Each account is ‘actively
managed’ and incurs a quarterly investment fee.
Contributions are made to the endowment fund by a direct contribution
made through the business office or through the annual online
membership renewal process. Direct contributions to the BSA Endowment
fund, increased or decreased by investment performance, amount
to approximately $200,000 (as of May, 2004).
There was an increase to the endowment fund made by long-time
members of the BSA, Richard and Deana Klein, in 2001 and that
has been accounted for separately including an increase or decrease
due to the portfolio performance. This donation was unrestricted,
with the funds to be used for “___________________”.
(Mary to research further…)
Although the BSA Board of Directors refers to the entirety of
funds held in Salomon Smith Barney as the ‘Endowment Fund’,
for accounting and tax purposes, only specific donations made
to the Endowment Fund are separated on the financial statements.
Since the BSA has a specific plan (as approved in their bylaws)
for how Endowment funds are to be presented, and since they have
solicited for funds on this basis, the BSA must account for those
donations separately than other operational funds that have accumulated
in the course of time.
The FAC has voted that the BSA Endowment fund will be allocated
their pro-rata share of any investment increases or decreases
that occur during the year, including both realized and unrealized
gains.
The Treasurer has a three year term of office within the BSA.
Each Treasurer chooses the accountant that they want to work with
(normally in their local area) who is responsible for the following:
? Preparation of the annual tax return (form 990)
? Preparation of quarterly financial statements
? Preparation of the NY payroll & the related payroll tax
returns & year end W-2’s
? Preparation of forms 1099 at year end (for non-employee compensation
exceeding $600)
? Accounting support for the Business Office as needed, including
assistance with the annual budget preparation
The Executive Director, Bill Dahl, handles the drafting of the
annual budget which the Treasurer presents to the Board for approval
at the annual meeting in July/August.
The Quickbooks online accounting software does not require a
monthly or annual closing of the books. At the fiscal year end,
Quickbooks automatically reclassifies net income to Retained Earnings
as of October 1st. The accountant then creates a journal entry
to reclassify the Retained Earnings to the various BSA fund accounts.
When donations are made to the BSA (including through the web
site), the donation is classified as either “unrestricted”
or “restricted”. Unrestricted donations are made with
‘no strings attached’ and can be spent freely by the
BSA on anything they choose. Restricted donations are made to
be spent for a ‘specific purpose’ or item and need
to be tracked separately in the financially statements and internally
so that our record keeping can support that we actually spent
the item how we were supposed to. We need to save all correspondence
that comes in with these ‘restricted’ donations for
tax support.
QUID PRO QUO DONATIONS TO THE BSA
Even though the BSA is a non-profit organization, donations to
the BSA to pay membership dues are not a tax deductible charitable
donation UNLESS a specific donation is made to the BSA endowment
or one of the special funds, and in that case, only the donation
part of the cost is tax-deductible.
Membership dues are not considered a ‘charitable donation’
as you receive something back in return (in the form of member
services, including the AJB subscription).
For businesses, the BSA membership cost is a business deduction
(fully deductible) and for individuals, it is a personal non-deductible
cost. On an individual return, it might be considered a ‘Union
& Professional Dues’ cost deductible as an itemized
deduction on Schedule A.
This explanation covers regular dues as well as section dues
paid in.
All membership, check disbursement and banking records should
be maintained for a minimum of 7 years.
The exception to that is any records pertaining to assets that
are still held by the BSA, including the Salamon Smith Barney
accounts and all correspondence related to the Endowment account.
See the appendix for a calendar of key dates
The BSA maintains a web site called
The AJB magazine maintains a web site called the
Both web sites and database support are maintained by Lanspeed,
a computer support company in Santa Barbara, California.
The majority of the BSA membership renewals are now processed
online via the web site.
These are reviewed by the Administrative Coordinator before importing
them into the member database.
Lanspeed created the current Access database being used and incorporated
a prior database being kept by the Columbus, Ohio office. The
current database runs off of the BSA web site at
and is maintained by both the Executive Director, Bill Dahl, and
the Administrative Coordinator, Wanda Lovan.
The database contains all current individual membership information
for 2004, including section alliances, donations made to the BSA,
papers written, and _________________. Prior membership information
is available but no supplemental information on donations, etc.
is available for past years.
To keep the database current, all outside deposit info (for Special
interest accounts too) will be manually input into the Database
so that those reports can be used as the Master control of all
financial deposits to the BSA. For the Special interest accounts,
this includes the Remy & Remy royalty payments, Karling &
Darbacker accounts, etc. What is not input into the database are
miscellaneous receipts non-specific to a member, such as advertising
revenue, editorial charges, etc.
The goal of the BSA is to have the majority of their individual
memberships apply and renew their annual subscription online.
Lanspeed has created the form for this on the web
site and this has been available for the 2004 membership year
(beginning with October, 2003, the first month of our fiscal year).
COMMERCE BANK - Wanda opens mail, makes deposits, reconciles
bank statement; Bill has online access and reviews frequently,
makes cash transfers and reviews financial statements frequently.
MEETING ACCOUNT: Johanne makes all deposits and writes all checks;
bank statements and cancelled checks are sent to Wanda who reviews
the cancelled checks and reconciles the account.
ONLINE DUES PAYMENT – cash is directly deposited into Commerce
Bank account.
The Botanical Society of America will comply with all grant requirements, in specific we note the following for Fedral Funding Agencies:
As part of the BSA operations, they host and put on an annual
botanical conference which is where the bulk of the awards sponsored
by the BSA are given out. This conference is at a new site each
year.
Johanne Stogran, a BSA employee in Ohio, is our dedicated meeting
administrator and coordinates the meeting activities year round.
The conference is held in July/August of each year and the BSA
collects income from registration fees, sponsorships, advertising,
and exhibitor booth rentals. Expenses include site selection expenses,
registration & housing costs, promotion, field trip costs,
honoraria, administration, etc.
There is a separate bank account that Johanne maintains at Bank
One for all the Annual meeting collection of income and expense
payments. Johanne maintains all the accounting activity in the
master company online Quicbkooks file. The monthly bank statement
and all bank correspondence are mailed directly to the BSA main
office in St. Louis and the bank statement and cancelled checks
are reviewed and reconciled there.
An additional $3 million of liability insurance was taken out
with Traveller’s to cover this event. This will be paid
annually along with our existing liability policy, but the cost
is directly allocated to this event.
As part of being a general member of the BSA, there are special
interest groups (i.e. ecology, paleobotany, etc) that each member
can join (called Sections); some of these Sections require an
additional fee be paid up front and these monies are allocated
towards a specific cash fund for that section (although no separate
bank accounts are kept). These funds are discretionary & to
be used by the Sections as their bylaws allow – for association
dues, awards and Annual Meeting related expenses.
In addition to monies they raise through dues, the sections are
also allocated an annual sum (called an Allotment) that they can
also spend in accordance with their bylaws.
Each section has both a Cash account (from dues raised and specific
donations to that fund) and an Allotment account. Expenses for
the sections are first paid out of the Allotment accounts and
then out of the Cash account. Since no Sections are allowed to
end the fiscal year in the red, any over spending of the Allotment
account is covered by a transfer from the Cash account of each
specific section.
To continue placing an emphasis on the annual meeting and to
provide active Sections with more resources to support their activities,
the Executive Council instilled a new method of allocation. The
Allotment amounts used to be a fixed $700 per year per section
but have been restructured to be in increments of $1,150 and $400,
with each amount determined based on the Section’s activity
at the last annual meeting.
$1,150 is allocated to disciplinary Sections organizing one or
more full contributed paper sessions (approx 10-12 presentations).
The remaining disciplinary and regional Sections shall be allocated
$400. Since the activity of some Sections at the annual meeting
is variable and dependent upon the presence of a co-convening
society, the allocation may vary from year to year. In an effort
to keep funding and participation synchronous, in those years
when a co-convening society (e.g. but not limited to, Association
for Tropical Biology, American Bryological and Lichenological
Society, Phycological Society of America) meets with the BSA the
allocation for the affiliated Section will be $1,150 for that
fiscal year. If the co-convening society does not meet with the
BSA in the following year, the allocation to the appropriate affiliated
Section will return to the lower level. The Treasurer will notify
sections of the their allocational status and available funds.
Based on BSA board discretion, the Allotment funds may either
be carried over to use in future years or any unused funds are
then taken back.
If an allotment is unused for two years, the funds will revert
to the BSA, and the annual allocation will cease until the Section
petitions the BSA Treasurer for an allocation by presenting a
proposed activity and budget (invited speaker, social, symposium,
etc.) for fund use. Allocational funds will not be transferred
to any other sectional accounts or societies.
These funds are administered by the BSA Treasurer in accordance
with policies established by the BSA Council and Executive Committee.
Direct payments of awards and honoraria are made to the recipients.
Officers of the Section or chairs of the award committees must
provide the name of the award recipients, name and address of
the awardee to the Treasurer prior to the 5pm on the day of the
BSA banquet for the awardee to receive their award at that time.
Expenses may be billed directly to the Treasurer with prior notification
by a Section officer. All other expenditures are handled as reimbursements
supported by receipts. All payments to non-society members should
be submitted by a sectional officer.
For accounting purposes, these monies are never given directly
to the Sections. Dues and donations are accounted for as part
of the normal dues collection process and reported in the financial
statements. Section expenses are submitted to the BSA office and
paid from the general operating account.
Separate accounting is done outside of the online Quickbooks
accounting for the BSA; a separate (not online) Quickbooks file
is maintained to track the running balances of the various Section
and Special Fundraising funds. Reporting is done to the Sections
on a quarterly or as requested basis.
Special fundraising & award accounts – there are specific
fundraising & award funds that have been setup through the
years and they provide scholarships, awards and other benefits
to both members and non-members (see attached list). Most of these
awards are given out at the Annual Meeting in August.
The FAC has voted that both the Section and Special accounts (excluding
Allotment accounts) that have a minimum average balance of $1,000
or greater during the year will be allocated their pro-rata share
of any investment increases or decreases that occur during the
year, including both realized and unrealized gains.
See the attached information from the web site with descriptions
of each Special Interest Fund.
The following Special funds have specific directed donations
that need tracking each year:
a) They receive a dedicated donation each year from Mellon Bank
a) Check the budget to see if any of the awards given were directed
to come specifically from the Karling fund.
b) The Karling fund sells T-shirts & merchandise at the Annual
Meeting. Historically, both the costs (from AJL Merchandising)
& the proceeds are posted to the Karling fund. This changed
in Yr 2003 as the BSA office sells the remaining t-shirts and
sales were poor, so evaluate annually before affecting the Karling
accounts.
a) Pat Gensel, BSA Past President, has allocated the full royalty
proceeds from her book, “Plants Invade the Land” to
the Remy & Remy fund. Various royalty payments are received
during the year from Columbia University | http://www.botany.org/governance/procedures.php | CC-MAIN-2016-26 | refinedweb | 4,052 | 50.57 |
Quickstart: Integrate an Azure Storage account with Azure CDN
In this quickstart, you enable Azure Content Delivery Network (CDN) to cache content from Azure Storage. Azure CDN offers developers a global solution for delivering high-bandwidth content. It can cache blobs and static content of compute instances at physical nodes in the United States, Europe, Asia, Australia, and South America.
Prerequisites
- An Azure account with an active subscription. Create an account for free.
Create a storage account
A storage account gives access to Azure Storage services. The storage account represents the highest level of the namespace for accessing each of the Azure Storage service components: Azure Blob, Queue, and Table storage. For more information, see Introduction to Microsoft Azure Storage.
To create a storage account, you must be either the service administrator or a coadministrator for the associated subscription.
In the Azure portal, select Create a resource on the upper left. The New pane appears.
Search for Storage account and select Storage account - blob, file, table, queue from the drop-down list. Then select Create:
In the Create storage account pane, enter the following details:
Leave all other details set to the defaults, then select Review + create.
Creating the storage account might take several minutes to complete. Once creation is complete, select Go to resource to open the storage account's page for the next step.
Enable Azure CDN for the storage account
On the page for your storage account, select Blob service > Azure CDN from the left menu. The Azure CDN page appears.
In the New endpoint section, enter the following information:
Select Create. After the endpoint is created, it appears in the endpoint list.
Tip
If you want to specify advanced configuration settings for your CDN endpoint, such as large file download optimization, you can instead use the Azure CDN extension to create a CDN profile and endpoint.
Enable additional CDN features
From the storage account Azure CDN page, select the CDN endpoint from the list to open the CDN endpoint configuration page.
From this page, you can enable additional CDN features for your delivery, such as compression, query string caching, and geo filtering.
Enable SAS. For more information, see Using Azure CDN with SAS.
Access CDN content
To access cached content on the CDN, use the CDN URL provided in the portal. The address for a cached blob has the following format:
http://<endpoint-name>.azureedge.net/<myPublicContainer>/<BlobName>
Note
After you enable Azure CDN access to a storage account, all publicly available objects are eligible for CDN POP caching. If you modify an object that's currently cached in the CDN, the new content will not be available via Azure CDN until Azure CDN refreshes its content after the time-to-live period for the cached content expires. CDNQuickstart-rg*.
On the Resource group page, select Delete resource group, enter CDNQuickstart-rg in the text box, then select Delete.
This action will delete the resource group, profile, and endpoint that you created in this quickstart.
To delete your storage account, select it from the dashboard, then select Delete from the top menu. | https://docs.microsoft.com/en-us/azure/cdn/cdn-create-a-storage-account-with-cdn?WT.mc_id=partlycloudy-blog-masoucou | CC-MAIN-2020-34 | refinedweb | 516 | 54.52 |
Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
The SimpleCV framework includes tools to draw several basic shapes such as lines, bezier curves, circles, ellipses, squares, and polygons. To demonstrate the true power of the drawing engine, Figure 7-6 is a rendering of a lollipop (there is a reason we did not go to art school):
from SimpleCV import Image, Color img = Image((300,300))
img.dl().circle((150, 75), 50, Color.RED, filled = True)img.dl().circle((150, 75), 50, Color.RED, filled = True)
img.dl().line((150, 125), (150, 275), Color.WHITE, width = 5)img.dl().line((150, 125), (150, 275), Color.WHITE, width = 5)
img.show()img.show()
This creates a blank 300×300 image.
Fetches the drawing layer and draws a filled red circle on it.
Fetches the drawing layer and draws a white line on it that is 5 pixels wide. | http://my.safaribooksonline.com/9781449337865/id2753816 | CC-MAIN-2013-48 | refinedweb | 156 | 70.5 |
System: ubuntu 12.04
The version from 12th december 2012 installed fine with cmake.
File downloaded on 20th december 2012 prints following error
CMake Error at CMakeLists.txt:75 (message):
Can't link to the standard math library. Please report to the Eigen
developers, telling them about your platform.
-- Configuring incomplete, errors occurred!
best regards, andreas
Are you sure this happened recently? I don't see any relevant changes in that period. Did you change anything on your platform? Can you compile/link this simple program:
#include <cmath>
int main(){std::sin(1.0); std::log(1.0f);}
-- GitLab Migration Automatic Message --
This bug has been migrated to gitlab.com's GitLab instance and has been closed from further activity.
You can subscribe and participate further through the new bug through this link to our GitLab instance:. | https://eigen.tuxfamily.org/bz/show_bug.cgi?id=538 | CC-MAIN-2020-16 | refinedweb | 137 | 61.93 |
Create a Line Graph with Hovering to Render a Dual Line Highlight using VX and D3
We'll be using VX to abstract away a little bit of the tedious work that D3 makes us do.
We're going to be building a graph that displays prices, in our cases mock data of apple stock prices.
A user can move their mouse over the graph and a line will appear, as well as appear to split the line right in half.
This will highlight the area that the user is potentially interested in seeing. This may not be an entirely useful feature but it's going to demonstrate some simple techniques.
Setup
We're going to kick this off with the graph bit already setup but I'll walk us through the code.
Lets look at our imports
import React, { Component } from "react";
import { LinePath, Line, Bar } from "@vx/shape";
import { appleStock } from "@vx/mock-data";
import { scaleTime, scaleLinear } from "@vx/scale";
import { localPoint } from "@vx/event";
import { extent, max, bisector } from "d3-array";
We import a few shapes from
@vx/shape which just proxy some calls to D3 and make dealing with rendering the underlying SVG a breeze.
Then we import mock data to use, and also
scaleTime and
scaleLinear. These also proxy a few calls to
d3-scale so we don't have to chain, instead we just provide an object.
The
localPoint from
@vx/event will allow us to get coordinate positions relative to the SVG. Otherwise our coordinates would be for the screen and we wouldn't be able to detect our drags correctly.
Finally we grab a few bits from
d3-array to help us out.
const stock = appleStock.slice(800); const xSelector = d => new Date(d.date);
const ySelector = d => d.close;
const bisectDate = bisector(xSelector).left;
We grab our
stock data, and setup to functions that are just selectors for data. When given a value from stock it will select and create the appropriate x/y values that our system expects.
Finally our
bisectDate uses bisector, we'll get into this later but it'll help us determine the exact index that the user is mousing over
Then in our render we need to setup a few scales to deal with our data. The
width and
height are purely arbitrary it's just some values that I picked
render() { const width = 500; const height = 300; const xScale = scaleTime({ range: [0, width], domain: extent(stock, xSelector), }); const yMax = max(stock, ySelector); const yScale = scaleLinear({ range: [height, 0], domain: [0, yMax + (yMax / 4)], });
}
Lets dissect each of these scales. The first is
scaleTime.
We provide it a
range, this is the range of the pixels. We want to map out data values and scale them to fit into the range of
[0, 500].
Our domain is our data. We use the
extent method and pass it our
xSelector. It will loop over each of our data points and eventually return an array.
That array will be
[earliestDate, latestDate]. So our earliest date will map to position
0 on screen and our latest date will map to pixel
500.
const xScale = scaleTime({ range: [0, width], domain: extent(stock, xSelector),
});
Then our yScale we construct the scale ourself rather than using
extent. The reason we do this is so we can add a bit of padding.
If we don't add some padding via the
yMax / 4 then our maximum data point will be positioned right at the top of the screen.
Which brings me to our
range you can see it's swapped form our
xScale. The
height comes first and then the
0. That's because the
0 point which when you look at a graph visually is technically on top, and the bottom of the graph is at the full height of the graph.
So when our stock has a
0 value it will map to render at the
height of the SVG and thus be at the bottom.
const yMax = max(stock, ySelector); const yScale = scaleLinear({ range: [height, 0], domain: [0, yMax + yMax / 4],
});
Finally we render it all, you can see here we have a
rect that is just a color and covers the whole
width/height of the SVG. Then we also add in a
LinePath from
@vx/shape. This takes our data, our scales, and then how it should go about selecting our data so we give it our
xSelector and
ySelector.
class App extends Component { state = { position: null, }; render() { const width = 500; const height = 300; const xScale = scaleTime({ range: [0, width], domain: extent(stock, xSelector), }); const yMax = max(stock, ySelector); const yScale = scaleLinear({ range: [height, 0], domain: [0, yMax + yMax / 4], }); return ( <svg width={width} height={height}> <rect x={0} y={0} width={width} height={height} fill="#32deaa" rx={14} /> <LinePath data={stock} xScale={xScale} yScale={yScale} x={xSelector} y={ySelector} strokeWidth={2} /> </svg> ); } } export default App;
Add Mouse Movements
Now the next thing we need to do is add mouse movements. This will require 2 things. One a thing to attach the movements too, and then a function to handle the dragging.
This might look like a lot but it's just creating a
rect in the background. You can see we created a
rect right up above. This is partly unnecessary to use
Bar from VX. The reason we could is how it handles any touch/mouse event it will inject the data into it. You may have some abstractions that don't give you access to the data that the
Bar actually has access to. So it can help when building out abstractions.
Also because you have created the scales in our render function we need to pass them along, otherwise we won't be able to figure out the necessary stuff.
<Bar x={0} y={0} width={width} height={height} fill="transparent" rx={14} data={stock} onTouchStart={data => event => this.handleDrag({ event, data, xSelector, xScale, yScale, })} onTouchMove={data => event => this.handleDrag({ event, data, xSelector, xScale, yScale, })} onMouseMove={data => event => this.handleDrag({ event, data, xSelector, xScale, yScale, })} onTouchEnd={data => event => this.setState({ position: null })} onMouseLeave={data => event => this.setState({ position: null })} />
We'll keep it as a bar but you could just as easily say. You'll notice we need to pass in
stock as data, and remove the 2 arrow functions to just the one.
<rect x={0} y={0} width={width} height={height} fill="transparent" rx={14} onTouchStart={event => this.handleDrag({ event, data: stock, xSelector, xScale, yScale, }) } onTouchMove={event => this.handleDrag({ event, data: stock, xSelector, xScale, yScale, }) } onMouseMove={event => this.handleDrag({ event, data: stock, xSelector, xScale, yScale, }) } onTouchEnd={event => this.setState({ position: null })} onMouseLeave={event => this.setState({ position: null })} />
Here is the tough par to understand but is key. We take our
event and pass it through
localPoint to get a point that is transformed relative to the
x/y of the SVG rather than the whole screen.
const { x } = localPoint(event);
Our
xScale not only can convert a data point to a screen renderable pixel but also do the reverse. So we call
xScale.invert with our coordinate from the event. This will return an approximate date based on the range.
const x0 = xScale.invert(x);
Now we need to figure out from our date what exact index we are possibly at.
bisectors make this easier to deal with.
We pass our data, our approximate date from our
invert, and then a minimum returned index of 1.
let index = bisectDate(data, x0, 1);
With our index we can determine our 2 pieces of data. Either the current index or the previous index. We don't want to go below
0 index so that's why our
bisectDate was set at a minimum of
1.
Now we need to figure out which point we're closest to. In our case we take our position, then use our
xSelector on each point. This will return a
Date.
When dates are used in math they get converted to their unix timestamp integer form.
We can now determine which data point we are at, and also importantly what index we are at.
const d0 = data[index - 1];
const d1 = data[index];
let d = d0;
if (d1 && d1.date) { if (x0 - xSelector(d0) > xSelector(d1) - x0) { d = d1; } else { d = d0; index = index - 1; }
}
Armed with our
index and our data point we're closest to we'll do a
setState.
We need to pass our data point into our
xSelector and
xScale which will give us an
x position to render our line so the user can see what's going on.
Converting to a point to render can technically be put in the render function and we could just do a
setState with the
index but I'm doing it this way slightly arbitrarily.
this.setState({ position: { index, x: xScale(xSelector(d)), },
});
All of it put together.
handleDrag = ({ event, data, xSelector, xScale, yScale }) => { const { x } = localPoint(event); const x0 = xScale.invert(x); let index = bisectDate(data, x0, 1); const d0 = data[index - 1]; const d1 = data[index]; let d = d0; if (d1 && d1.date) { if (x0 - xSelector(d0) > xSelector(d1) - x0) { d = d1; } else { d = d0; index = index - 1; } } this.setState({ position: { index, x: xScale(xSelector(d)), }, }); };
Render a Line
Now we've got our position we need to render a
Line. We check if our
position exists as it's undefined when we aren't hovering.
Then pass our
from and
to objects. These define 2 points to render a line between. We're rendering a straight line up and down at a certain X coordinate.
So our
x will be the same in both from and to, then our
y will be the top/bottom of our SVG.
{ position && ( <Line from={{ x: position.x, y: 0 }} to={{ x: position.x, y: height }} strokeWidth={1} /> );
}
Render another LinePath
Now comes the point where we need to render another line to highlight the part of the line the user cares about. Your first instinct might be to create new scales (mine was), but what we actually want to do is just
slice our data.
The scales we created are already configured to render our data. In normal cases we just pass all the data to render the full line. But we don't have to start from rendering at
0 we can render any data. As long as it matches the
domain we setup it'll map to our
range correctly.
So we pass in our
data but we do a
slice. This will cut the data from that index to the end of the array. So we'll start our rendering of our line right at the index. We'll now be rendering a line with
.5 opacity right over the other
LinePath that's our full data.
{ position && ( <LinePath data={stock.slice(position.index)} xScale={xScale} yScale={yScale} x={xSelector} y={ySelector} strokeWidth={2} ); }
Split the Lines
Now that we're rendering one line on top of the other lets see what it's like to "split" the line. We don't actually split anything we just render 2 lines.
We split the data from
0 to the
index that the user has their mouse at.
<LinePath data={position ? stock.slice(0, position.index) : stock} xScale={xScale} yScale={yScale} x={xSelector} y={ySelector} strokeWidth={2}
/>
Then when we aren't hovering we render the full line.
Ending
There you have it, you can now hover over the SVG and cause 2 lines to be drawn and split it. You could use this to set 2 posts and render 3 lines, and show statistics about the data the user has constrained. The key parts are understanding that scales will respond to data correctly, so manipulate the data and not the scales and rendering what you want becomes easier.
| http://brianyang.com/create-a-line-graph-with-hovering-to-render-a-dual-line-highlight-using-vx-and-d3/ | CC-MAIN-2018-22 | refinedweb | 1,973 | 63.7 |
Note: <ol type=1>.
This function is the same as length().
This can be used to iterate over the map. Note that the nodes in the map are ordered arbitrarily.
If the named node map does not contain such a node, a null node is returned. A node's name is the name returned by QDomNode::nodeName().
See also setNamedItem() and namedItemNS().
If the map does not contain such a node, a null node is returned.
See also setNamedItemNS() and namedItem().
The function returns the removed node or a null node if the map did not contain a node called name.
See also setNamedItem(), namedItem(), and removeNamedItemNS().
The function returns the removed node or a null node if the map did not contain a node with the local name localName and the namespace URI nsURI.
See also setNamedItemNS(), namedItemNS(), and removeNamedItem().
If the new node replaces an existing node, i.e. the map contains a node with the same name, the replaced node is returned.
See also namedItem(), removeNamedItem(), and setNamedItemNS().
See also namedItemNS(), removeNamedItemNS(), and setNamedItem(). | http://man.linuxmanpages.com/man3/QDomNamedNodeMap.3qt.php | crawl-003 | refinedweb | 177 | 86.5 |
38072/how-check-input-string-valid-regular-expression-not-python
HI all. Pretty simple question!
Basically, in Java, I was able to use the following piece of code to check if my input string was a valid or an invalid regular expression.
boolean isRegex;
try {
Pattern.compile(input);
isRegex = true;
} catch (PatternSyntaxException e) {
isRegex = false;
}
Now my question is that I want to know what the Python equivalent is of Pattern.compile() and PatternSyntaxException?
I am sure it exists in Python and that I am unaware of it. Using this in a project of mine.
All help appreciated!
Hi. Good question! Well, just like what we have in Java, for Python we have re.error exception just for this very purpose. Check out the code below to understand it better:
import re
try:
re.compile('[')
is_valid = True
except re.error:
is_valid = False
What is re.error exception, you ask?
Here is the formal definition I got from the official documentation:
"Exception raised when a string passed to one of the functions here is not a valid regular expression or when some other error occurs during compilation or matching. "
Hope this helped!
$ to match the end of the ...READ MORE
Hey @Vedant, that's pretty simple and straightforward:
if ...READ MORE
As per the documentation, an identifer can ...READ MORE
Try using in like this:
>>>>> y ...READ MORE
You can also use the random library's ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
can you give an example using a ...READ MORE
You can simply the built-in function in ...READ MORE
For Python 3, try doing this:
import urllib.request, ...READ MORE
Hi, good question. I have a solution ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/38072/how-check-input-string-valid-regular-expression-not-python | CC-MAIN-2021-04 | refinedweb | 293 | 70.7 |
fi
Site: Basically, I have a working affixed side menu (seen on screens with a width larger than px)... I would like to change the color (and active color of the text in this 'affix'ed menu), when the menu passes over t
I'm trying to edit a wordpress plugin which targets the background image of the body which makes it scroll with the page. The code from the plugin is quoted below. I want the same effect to target the background images of other divs but I can't get i
Guys I am beginner in AngularJs and javascript. In my project, I am using this plugin but I am facing error and I am not able to find the root cause even after spending too much time. H
I'm creating simple 2D platformer and I want that my background image update with my player1 y coordinate. Here's my Background class public class Background{ private Sprite sprite, sprite2; public static int x = 50, y = 0; public Background(){ sprit
I have a webpage where I want a featured image that background scrolls with the speed of browser scroll. Here is my jsfiddle $(window).scroll(function () { $("#featured-image").css("background-position", "50%" + ($(this).scro
I'm currently working on a bilingual website, with a horizontal layout to support an English Left-to-Right and an Arabic Right-to-Left layout. So far the layout is working very fine, according to: <body dir="ltr"> or <body dir="rtl
I've created my index.html and I want the navigation bar to be on the bottom of the screen. When the page loaded is has a lot of content i want to be able to scroll where the content is loaded, but have the navbar at the bottom of the page always sta have a fixed header function like below. I would like to change dynamically "100" value while window resizing. I was trying to wrap everything in sth like "if (screen.width >= 1200)" or "jQuery(window).on('resize', function ()" but this kind of
Discovered the header effect found below. I know that it's using jQuery Waypoints, but I can't figure how it's swapping headers. I'd like to duplicate the effect for a presentation. If anyone has a link to the effect being
So I have this code which allows me to scroll between divs with the previous and next buttons, the script works well although I was trying to find a way to solve a little issue which is when I scroll normally with the mouse wheel or the scrollbar and
I would like to disable scrolling on the HTML body completely. I have tried the following options: overflow: hidden; (not working, did not disable scrolling, it just hid the scrollbar) position: fixed; (this worked, but it scrolled completely to the
I'm developing a mobile web app using framework7 and phonegap build and i'm testing on android device. I'm using framework7's inline pages layout and i can't manage to get scroll inertia or momentum (the feature that make a long page scrolling even a
I have an image in a scrolling div: <div style=" width:600px;height:400px; overflow:scroll; position:relative; top:0;left:0; -webkit-overflow-scrolling: touch;"> <img src=image.jpg width=2000 height=2000> </div> It works everywhere
i'm currently working on a website in wich i integrated a couple of open source jquery script, but i can't really get it to work as it should... this is the complete demo of the website: here is the list
I've created a web view recently & everything seems to be working fine except the window.scroll event. I'm loading content in my mobile website once user reaches the end of the screen, unfortunately that doesn't work in Android Webview. I've enab
I want to implement a Layout which supports zooming and 2d scrolling like in chrome app or Firefox app both of them got 2d scrolling and zooming. I havent seen one example in the internet of how to do so, and I've searched a lot believe me. By the wa
I'm having a weird bug with Angular. Here's the context: The page loads with everything fitting in the window. The user clicks on something and a bunch more content loads. An ng-repeat pushes the document height below the fold, the vertical scrollbar | http://www.pcaskme.com/tag/scroll/ | CC-MAIN-2019-04 | refinedweb | 745 | 65.96 |
706/hyperledger-network-roles-assigned-to-peer-nodes
Hyperledger assigns network roles based on node type and transaction execution is separated from transaction ordering and commitment. I read somewhere that 'Executing transactions prior to ordering them enables each peer node to process multiple transactions simultaneously'
I want to understand how how one can execute a transaction prior to ordering one?
In a hyperledger fabric network transactions are initiated with client applications sending transaction proposals to endorsing peers.
Each endorsing peer simulates the proposed transaction, without updating the ledger. The endorsing peers will capture the set of Read and Written data which are called R-W Sets.
The application then submits the endorsed transaction and the R-W sets to the ordering service.
The ordering service takes the endorsed transactions and RW sets, orders this information into a block, and delivers the block to all peer nodes.
The committing peers validate the transaction by checking to make sure that the R-W sets still match the current world state.
Committing peers are responsible for adding transaction blocks to the shared ledger and updating the world state.
The peers communicate among them through the ...READ MORE
There are two ways you can do ...READ MORE
When you start with Geth you need ...READ MORE
Hyperledger has evolved a lot. The updated ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
IBM Bluemix Blockchain service Hyperledger Fabric v0.6 will ...READ MORE
I know it is a bit late ...READ MORE
In Hyperledger Composer, you have all the ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/706/hyperledger-network-roles-assigned-to-peer-nodes | CC-MAIN-2020-40 | refinedweb | 282 | 57.98 |
You can add the contents of a standard header to a source file by inserting an #include directive, which must be placed outside all functions. You can include the standard headers as many times as you want, and in any order. However, before the #include directive for any header, your program must not define any macro with the same name as an identifier in that header. To make sure that your programs respect this condition, always include the required standard headers at the beginning of your source files, before any header files of your own.
C programs run in one of two execution environments
: hosted or freestanding. Most common programs run in a hosted environment; that is, under the control and with the support of an operating system. In a hosted environment
, the full capabilities of the standard library are available. Furthermore, programs compiled for a hosted environment must define a function named main( ), which is the first function invoked on program start.
A program designed for a freestanding environment runs without the support of an operating system. In a freestanding environment
, the name and type of the first function invoked when a program starts is determined by the given implementation. Programs for a freestanding environment cannot use complex floating-point types, and may be limited to the following headers:
float.h
iso646.h
limits.h
stdarg.h
stdbool.h
stddef.h
stdint.h
Specific implementations may also provide additional standard library resources.
All standard library functions
have external linkage. You may use standard library functions without including the corresponding header by declaring them in your own code. However, if a standard function requires a type defined in the header, then you must include the header.
The standard library functions are not guaranteed to be reentrantthat is, two calls to a standard library function may not safely be in execution concurrently in one process. One reason for this rule is that several of the functions use and modify static variables, for example. As a result, you can't generally call standard library functions in signal handling routines. Signals are asynchronous, which means that a program may receive a signal at any time, even while it's executing a standard library function. If that happens, and the handler for that signal calls the same standard function, then the function must be reentrant. It is up to individual implementations to determine which functions are reentrant, or whether to provide a reentrant version of the whole standard library.
As the programmer, you are responsible for calling
functions and function-like macros with valid arguments. Wrong arguments can cause severe runtime errors. Typical mistakes to avoid include the following:
Argument values outside the domain of the function, as in the following call:
double x = -1.0, y = sqrt(x);
Pointer arguments that do not point to an object or a function, as in this function call with an uninitialized pointer argument:
char *msg; strcpy( msg, "error" );
Arguments whose type does not match that expected by a function with a variable number of arguments. In the following example, the conversion specifier %f calls for a float pointer argument, but &x is a pointer to double:
double x; scanf( "%f", &x );
Array address arguments that point to an array that isn't large enough to accommodate data written by the function. Example:
char name[ ] = "Hi "; strcat( name, "Alice" );
Macros in the standard library make full use of parentheses, so that you can use them in expressions in the same way as individual identifiers. Furthermore, each function-like macro in the standard library uses its arguments only once.[*] This means that you can call these macros in the same way as ordinary functions, even using expressions with side effects as arguments. Here is an example:
[*] The C99 standard contradicts itself on this point. In describing the use of library functions it says, "Any invocation of a library function that is implemented as a macro shall expand to code that evaluates each of its arguments exactly once, fully protected by parentheses where necessary, so it is generally safe to use arbitrary expressions as arguments," but in its descriptions of the functions putc( ), putwc( ), getc( ), and getwc( ), the standard contains warnings like this one: "The putc function is equivalent to fputc, except that if it is implemented as a macro, it may evaluate stream more than once, so that argument should never be an expression with side effects." It is fair to hope that the warnings are obsolete, but perhaps safer just to avoid using arguments with side effectsor to use fputc( ) rather than putc( ), and so on.
int c = 'A';
while ( c <= 'Z' ) putchar( c++ ); // Output: 'ABC ... XYZ'
The functions in the standard library may be implemented both as macros and as functions. In such cases, the same header file contains both a function prototype and a macro definition for a given function name. As a result, each use of the function name after you include the header file invokes the macro. The following example calls the macro or function toupper( ) to convert a lowercase letter to uppercase:
#include <ctype.h>
/* ... */
c = toupper(c); // Invokes the macro toupper( ), if there is one.
However, if you specifically want to call a function and not a macro with the same name, you can use the #undef directive to cancel the macro definition:
#include <ctype.h>
#undef toupper // Remove any macro definition with this name.
/* ... */
c = toupper(c) // Calls the function toupper( ).
You can also call a function rather than a macro with the same name by setting the name in parentheses:
#include <ctype.h>
/* ... */
c = (toupper)(c) // Calls the function toupper( ).
Finally, you can omit the header containing the macro definition, and declare the function explicitly in your source file:
extern int toupper(int);
/* ... */
c = toupper(c) // Calls the function toupper( ).
When choosing identifiers to use in your programs, you must be aware that certain identifiers are reserved
for the standard library. Reserved identifiers include the following:
All identifiers that begin with an underscore, followed by a second underscore or an uppercase letter, are always reserved. Thus you cannot use identifiers such as _ _x or _Max, even for local variables or labels.
All other identifiers that begin with an underscore are reserved as identifiers with file scope. Thus you cannot use an identifier such as _a_ as the name of a function or a global variable, although you can use it for a parameter, a local variable, or a label. The identifiers of structure or union members can also begin with an underscore, as long as the second character is not another underscore or an uppercase letter.
Identifiers declared with external linkage in the standard headers are reserved as identifiers with external linkage. Such identifiers include function names, as well as the names of global variables such as errno. Although you cannot declare these identifiers with external linkage as names for your own functions or objects, you may use them for other purposes. For example, in a source file that does not include string.h, you may define a static function named strcpy( ).
The identifiers of all macros defined in any header you include are reserved.
Identifiers declared with file scope in the standard headers are reserved within their respective name spaces. Once you include a header in a source file, you cannot use any identifier that is declared with file scope in that header for another purpose in the same name space (see "Identifier Name Spaces" in Chapter 1) or as a macro name.
Although some of the conditions listed here have "loopholes" that allow you to reuse identifiers in a certain name space or with static linkage, overloading identifiers can cause confusion, and it's generally safest to avoid the identifiers declared in the standard headers completely. In the following sections, we also list identifiers that have been reserved for future extensions of the C standard. The last three rules in the previous list apply to such reserved identifiers
as well. | http://books.gigatux.nl/mirror/cinanutshell/0596006977/cinanut-CHP-15-SECT-1.html | CC-MAIN-2018-43 | refinedweb | 1,334 | 58.52 |
Why readable, documented code is especially important for scientists (and a three-step plan for getting there)
During my most recent teaching engagement I spent some time talking specifically about code readability and documentation. As often happens, presenting these ideas to a roomful of novice programmers helped to crystallize my thoughts on the topic, and made me realize that I'd never written about it – plus I thought that it would be an ideal topic for first post of the new year, since documentation is something that many programmers constantly resolve to do better at!
There's no shortage of articles and book chapters explaining the general importance of documenting your code – if you learned to program from a book or an online tutorial then it will almost certainly have been mentioned. The arguments in favour of documentation are well-rehearsed: it makes it easier for you to work on your own code over a long period of time, it makes it easier for others to contribute fixes and features, it forces you to think about the purpose of each section, etc. In this post, I want to talk about why documentation is particularly important for you – somebody who is using programming for carrying out scientific work. The basis of my argument is that for us as scientists, code serves two important features over and above simply being executed: it acts as both the ultimate supplementary methods, and it's the way in which you express your original ideas.
Code as supplementary methods
It's probably fair to say that most users of most programs don't care about how they actually work, as long as they do what they're supposed to. When you fire up an image editing program to brighten up a dull digital photo or rotate one where the horizon isn't straight, you probably aren't interested in exactly what transformation is being applied to the RGB values, or what trigonometry is being used to straighten the image – you're only interested in the end result.
Scientific software is different: the end-users are often extremely interested in how the program works internally, since understanding that is a part of understanding the results. And the ultimate way to resolve questions or disagreements about what a program is doing is to examine the source code. This is a great advantage we have when working in bioinformatics. For wetlab work, there is only so much information you can give in the pages of a journal about how an experiment was carried out. Using supplementary information can help, but even then you're limited to what the authors thought important enough to write down. For a bioinformatics experiment, however, one can always see exactly where the data came from and what happened to it, providing one has access to the source code. You can read about a piece of bioinformatics software in a journal, listen to a talk on it, discuss it with the authors, but at the end of the day if you still have questions about how it works, you can always go back to the source code.
The vast majority of programmers don't have to worry about their users wanting to read the source, but we do – so we should make readability and documentation a priority to make sure that it's as useful as possible.
Code as a way of expressing original ideas
The vast majority of software projects don't implement any ideas that are particularly original. This isn't a problem, it's just a reflection of the fact that many pieces of software do very similar things to other pieces of software, and do them in similar ways. There are fairly standard ways of writing a blog engine, a stock management program, an image manipulation program etc. We could make an argument, therefore, that for those categories of software it's not super-important that the code is really well documented, since it's unlikely to be doing anything surprising, and a reader can probably work out what's going on in each section by referring to other software that carries out the same task.
Scientific software is different. Yes, we tend to write scripts to carry out tedious everyday tasks like tweaking file formats and correcting sequence headers, but we also use it for implementing entirely new ideas about how to assemble genomes, or how to correct frameshift mutations, or how to pick species for phylogenetic analysis. We're far more likely than other programmers to write code that does something entirely new. As such our programs (at least the ones that do something interesting) are going to be harder to understand than yet another text editor or chat program.
As programmers, we're very lucky in that the language we use to implement our original ideas – code – is also an excellent way to communicate them to other researchers. But the usefulness of that language depends on whether we write it in a readable way and document it well.
Three steps to readable, documented code
Documentation is a skill that is learned over the course of a career, but here's an exercise that I often have my students do. Using a framework like this can make documenting your code less daunting if you've no idea where to start.
Step one: make sure your variable and function names are meaningful
Programmers are fond of talking about self-documenting code – i.e. code that doesn't require external documentation to be understood. A large part of this is using meaningful variable names. Examples of bad variable and function/method names include:
- Single-letter names e.g.
a,
b,
f(with the exception of variable names that follow common conventions such as
xand
yfor co-ordinates or
ifor an index)
- Names that describe the type of data rather than the contents e.g.
my_list,
dict
- Names that are extremely generic e.g.
process_file(),
do_stuff(),
my_data
- Names that come in multiples e.g.
file1,
file2
- Names that are excessively shortened e.g.
gen_ref_seq_uc
- Multiple names that are only distinguished by case or punctuation e.g.
input_fileand
inputfile,
DNA_seqand
dna_seq
- Names that are misspelled – the computer does not care about spelling but your readers might
Go through your code and look for any instances of the above, and replace them with good names. Good variable names tell us the job of the variable or function. This is also a good opportunity to replace so-called magic numbers – constants that appear in the code with no explanation – with meaningful variable names e.g. 64 might be replaced by
number_of_codons.
Example: we want to define two variables which hold the DNA sequence for a contig and a frame, then pass them to a method which will carry out protein translation and store the result. Here's how not to do it, even though the code is perfectly valid Python:
a = 2 b = 'ATGCGATTGGA' c = do_stuff(a, b)
This is much better:
frame = 2 contig_dna_seq = 'ATGCGATTGGA' contig_protein_seq = translate(frame, contig_dna_seq)
Step two: write brief comments explaining the reasoning behind particularly important or complex statements
For most programs, it's probably true to say that the complexity lies in a very small proportion of the code. There tends to be a lot of straightforward code concerned with parsing command-line options, opening files, getting user input, etc. The same applies to functions and methods: there are likely many statements that do things like unpacking tuples, iterating over lists, and concatenating strings. These lines of code, if you've followed step one above, are self-documenting – they don't require any additional commentary to understand, so there's no need to write comments for them.
This allows you to concentrate your documentation efforts on the few lines of code that are harder to understand – those whose purpose is not clear, or which are inherently difficult to understand. Here's one such example – this is the start of a function for processing a DNA sequence codon-by-codon (e.g. for producing a protein translation):
for codon_start in range(0, len(dna)-2, 3): codon_stop = codon_start+3 codon = dna[codon_start:codon_stop] ...
The first line is not trivial to understand, so we want to write a comment explaining it. Here's an example of how not to do it:
# iterate over numbers from zero to the length of # the dna sequence minus two in steps of three for codon_start in range(0, len(dna)-2, 3): ...
The reason that this is a bad comment is that it simply restates what the code does – it doesn't tell us why. Reading the comment leaves us no better off in knowing why the last start position is the length of the DNA sequence minus two. This is much better:
# get the start position for each codon # the final codon starts two bases before the end of the sequence # so we don't get an incomplete codon if the length isn't a multiple of three for codon_start in range(0, len(dna)-2, 3): ...
Now we can see from reading the comment that the reason for the -2 is to ensure that we don't end up processing a codon which is only one or two bases long in the event that there are incomplete codons at the end of the DNA sequence.
Go through your code and look for lines whose function isn't obvious just from reading them, and add explanations
Step three: add docstrings to your functions/methods/classes/modules
Functions and methods are the way that we break up our code into discrete, logical units, so it makes sense that we should also document them as discrete, logical units. Everything in this section also applies to methods, classes and modules, but it keep things readable I'll just refer to functions below.
Python has a very straightforward convention for documenting functions: we add a triple-quoted string at the start of the function which holds the documentation e.g.
def get_at_content(dna): """return the AT content of a DNA string. The string must be in upper case. The AT content is returned as a float""" length = len(dna) a_count = dna.count('A') t_count = dna.count('T') at_content = float(a_count + t_count) / length return at_content
This triple-quoted line is called a docstring. The advantage of including function documentation in this way as opposed to in a comment is that, because it uses a standard format, the docstring can be extracted automatically. This allows us to do useful things like automatically generate API documentation from docstrings, or provide interactive help when running the Python interpreter in a shell.
There are various different conventions for writing docstrings. As a rule, useful docstrings need to describe the order and types of the function arguments and the description and type of the return value. It's also helpful to mention any restrictions on the argument (for instance, as above, that the DNA string must be in upper case). The example above is written in a very unstructured way, but because triple-quoted strings can span multiple lines, we could also adopt a more structured approach:
def get_at_content(dna): """return the AT content of a DNA string. Arguments: a string containing a DNA sequence. The string must be in upper case. Returns: the AT content as a float""" ...
If you think it's helpful, you can also give examples of how to use the function in the docstring. Notice that we're not saying anything in the docstring about how the function works. The whole point of encapsulating code into functions is that we can change the implementation without worrying about how it will affect the calling code!
Summary
These three steps represent the minimum amount of work that you should do on any code that you plan on keeping around for more than a few weeks, or that you plan on showing to anybody else. | https://pythonforbiologists.com/3-steps-to-readable-code/ | CC-MAIN-2018-26 | refinedweb | 1,993 | 54.56 |
If I make the following module hello.py available via the publisher
handler:
""" Publisher example """
import os
def say(req, what="NOTHING"):
return "I am saying %s" % what
Then a browser request which looks like this:
/hello/os/renames?old=/tmp/blah&new=/tmp/blah1
will actually work (as the apache user). I am fairly sure that this
is not desirable...
If someone knows which modules you are importing in your code, they
will be able to call any non-builtin function anywhere in the
namespace.
Maybe the publisher handler should only allow objects to be published
if they have some sort of special attribute, __publish__ for example.
- Dave
-- | https://modpython.org/pipermail/mod_python/2001-January/011618.html | CC-MAIN-2022-05 | refinedweb | 109 | 63.49 |
Many machine learning algorithms work best when numerical data for each of the features (the characteristics such as petal length and sepal length in the iris data set) are on approximately the same scale. The conversion to a similar scale is called data normalisation or data scaling. We perform this as part of out data pre-processing before training an algorithm.
Two common methods of scaling data are 1) to scale all data between 0 and 1 when 0 and 1 are the minimum and maximum values for each feature, and 2) scale the date so that the all features have a mean value of zero and a standard deviation of 1. We will perform this latter normalisation. Scikit learn will perform this for us, but the principle is simple: to normalise in this way, subtract the feature mean from all values, and then divide by the feature standard deviation.
The normalisation parameters are established using the training data set. These parameters are then applied also to the test data set.
Let’s first import our packages including StandardScaler from sklearn.preprocessing:
import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler
To improve readability of the results, we’ll set up a function to format NumPy output, controlling the width and decimal places.
def set_numpy_decimal_places(places, width=0): set_np = '{0:' + str(width) + '.' + str(places) + 'f}' np.set_printoptions(formatter={'float': lambda x: set_np.format(x)}) set_numpy_decimal_places(3,6)
We’ll load up our iris data:
# Load iris data iris = datasets.load_iris() X=iris.data y=iris.target # Create training and test data sets X_train,X_test,y_train,y_test=train_test_split( X,y,test_size=0.3,random_state=0)
We’ll now apply our scalar, training it on the training data set, and applying it to both the training and test data set.
# Initialise a new scaling object sc=StandardScaler() # Set up the scaler just on the training set sc.fit(X_train) # Apply the scaler to the training and test sets X_train_std=sc.transform(X_train) X_test_std=sc.transform(X_test)
Let’s see what it has done to our data sets. Our training data set appears not to be perfectly normalised, but it is on exactly the same scale as the training data set, which is what our machine learning algorithms will need.
print ('Original training set data:') print ('Mean: ', X_train.mean(axis=0)) print ('StDev:', X_train.std(axis=0)) print ('\nScaled training set data:') print ('Mean: ', X_train_std.mean(axis=0)) print ('StDev:', X_train_std.std(axis=0)) print ('\nOriginal test set data:') print ('Mean: ', X_test.mean(axis=0)) print ('StDev:', X_test.std(axis=0)) print ('\nScaled test set data:') print ('Mean: ', X_test_std.mean(axis=0)) print ('StDev:', X_test_std.std(axis=0)) OUT: Original training set data: Mean: [ 5.893 3.045 3.829 1.227] StDev: [ 0.873 0.439 1.796 0.778] Scaled training set data: Mean: [ 0.000 -0.000 -0.000 -0.000] StDev: [ 1.000 1.000 1.000 1.000] Original test set data: Mean: [ 5.727 3.076 3.596 1.133] StDev: [ 0.688 0.414 1.656 0.715] Scaled test set data: Mean: [-0.191 0.070 -0.130 -0.120] StDev: [ 0.789 0.943 0.922 0.919]
One thought on “65. Machine learning: Feature Scaling” | https://pythonhealthcare.org/2018/04/15/65-machine-learning-feature-scaling/ | CC-MAIN-2020-29 | refinedweb | 551 | 60.01 |
Hi Kevin,
all depends of how things evolve but I must say that my propossal (and my
contribution if someday get materialized in code) about Haxe is base the
API in current Flex 4.x as a starting point (a draft), but modeling and
changing it as project evolve. This project is for fun, at least in its
conception, and taking into account that it will be done in spare time, I
would not try even to plan any migration or compatibility with old Flex
applications to that FlexHaxe thing. We should copy the right things and
rethink the old or bad ones. For people that wants to continue the current
path (Flex 4.x) always will be maintenance a new features/patches in that
"Flex line". Apache Flex count we members involved in such different ways,
what's very cool to get both things done. A new Flex framework should be
new and free from any ties from the pass.
2012/11/20 Kevin Newman <CaptainN@unfocus.com>
> HaXe really is more similar to AS3 than many here seem to think (it's more
> of a superset than a subset - though there are some missing features like
> namespace). Would Flex really need to start from scratch when porting to
> HaXe? Could some level of automation be utilized (there's an unfinished
> tool that could be picked up and worked on for doing just that)?
>
> The biggest problem with a change in platform has more to do legacy
> support.
>
> What do you do with all that AS3 code? If Flex is written in HaXe, and you
> still target Flash/AIR platform, you can still rely on the old AS3 compiler
> to leverage all that legacy SWC and AS3 code. HaXe in this migration path
> doesn't require dumping legacy code at all. Win/win. Flex migration could
> even be modularized, because of this. I wonder if a small proof of concept
> could be attempted - convert some core Flex components to HaXe, compile to
> SWC, and leave the rest in AS3, and see how that goes.
>
> A benefit of the switch, of course, is HaXe allows movement to many
> platforms other than ABC/Flash/AIR - including open stacks such as NME,
> Neko and HTML5.
>
> In short HaXe nets Flex a lot. Legacy code base support through Flash/AIR,
> support for completely open stack(s) for apps, and HTML5 support. This is
> the power of open source.
>
> HaXe Foundation:
>
>
> Kevin N.
>
>
> On 11/16/12 3:58 PM, Gordon Smith wrote:
>
>> The silliest of the bunch in my opinion is porting to HaXe or starting
>> from scratch.
>>
>
>
--
Carlos Rovira
Director de Tecnología
M: +34 607 22 60 05
F: +34 912 35 57 77 | http://mail-archives.apache.org/mod_mbox/incubator-flex-dev/201211.mbox/%3CCAMFKFRif6DZBzKXSiWKiO2-RWvNrErUdzEbUChfr9bAoZBsUAA@mail.gmail.com%3E | CC-MAIN-2015-48 | refinedweb | 452 | 79.3 |
You can subscribe to this list here.
Showing
20
results of 20
> The error is triggered on this line:
> LOG.debug("Context: " + contextSequence.getLength());
> If that line is removed, the function works.
Oh, I committed this by mistake. I inserted the LOG statement while
debugging the normalize-space issue we recently discussed on this
list. Just remove it, please.
I used the 1.0 version for debugging, so 1.1 will work without change.
Wolfgang
I was using the latest version from SVN, in cocoon 2.1.8.
Regards
Hans
On 7/31/06, Michael Beddow <mbexlist-2@...> wrote:
> Jonas Lundberg wrote:
>
>
> > Exist output:
> > java.lang.NullPointerException
>
> What version are you using? This works fine on 1.1 newcore.
>
> Michael Beddow
>
>
>
> -------------------------------------------------------------------------
> Take Surveys. Earn Cash. Influence the Future of IT
> Join SourceForge.net's Techsay panel and you'll get the chance to share your
> opinions on IT & business topics through brief surveys -- and earn cash
>
> _______________________________________________
> Exist-open mailing list
> Exist-open@...
>
>
Hi Sjur,
> NOTE: the proper solution would probably be to always ensure proper
> unescaping of escaped URIs, leaving the above escaping as is.
Yes, I think we have to unescape the fragment part of the URI before
passing it to the query engine. I changed the code after line 217 as
follows:
if(xpointer!=null) {
try {
xpointer = XMLUtil.decodeAttrMarkup(URLDecoder.decode(xpointer, "UTF-8"));
} catch (UnsupportedEncodingException e) {
}
}
The fix is in SVN trunk. Thanks for tracking this issue.
Wolfgang
Jonas Lundberg wrote:
> Exist output:
> java.lang.NullPointerException
What version are you using? This works fine on 1.1 newcore.
Michael Beddow
Query:
xquery version "1.0";
<xml>
{ normalize-space("bollar")}
</xml>
Saxon output:
<xml>bollar</xml>
Exist output:
java.lang.NullPointerException
at org.exist.xquery.functions.FunNormalizeSpace.eval(FunNormalizeSpace.java:82)
at org.exist.xquery.InternalFunctionCall.eval(InternalFunctionCall.java:49)
at org.exist.xquery.AbstractExpression.eval(AbstractExpression.java:56)
at org.exist.xquery.PathExpr.eval(PathExpr.java:210)
.
The error is triggered on this line:
LOG.debug("Context: " + contextSequence.getLength());
If that line is removed, the function works.
Maybe this is some kind of Cocoon / Exist configuration error?.
Regards
Hans
My bad, the way I was reading xupdate.xml was wrong, I was using
StringBuffer to read instead of a StringWritter to store xupdate.xml
in memory !! Very bad :)
Thank you guys
cheeeers
chinmaya
On 7/31/06, Pierrick Brihaye <pierrick.brihaye@...> wrote:
> Hin
>
> chinmayareddy@... a =E9crit :
>
> > Attaching contents of both files :)
>
> That looks perfect (just tested them). So, the problem is probably
> related to way xupdate.xml is stored and/or retrieved.
>
> Cheers,
>
> p.b.
>
--=20
thanks
chinmaya
Hin
chinmayareddy@... a =E9crit :
> Attaching contents of both files :)
That looks perfect (just tested them). So, the problem is probably=20
related to way xupdate.xml is stored and/or retrieved.
Cheers,
p.b.
I'm trying to do an exact phrase search in an xquery, and I need both
correct phrase highlighting (words in the phrase should not be
highlighted by themselves) and correct counts for phrase matches.=20
When I searched the mailing list archives I found out about the
phrase() function that does what I need-- however, when I replace
near() with phrase() in my xquery, the response time goes from under a
second to anywhere from 35 to 52 seconds, depending on the size of the
document (and some of them are quite large).
Is there anything I can do to optimize the query for using the phrase
search, or are there any indexing options that would improve this
response time? And, if there isn't anything I can do right now, does
anyone know if there are any plans to improve the phrase function at
some point?
I can correct the highlighting & probably the counts in xslt if
necessary, but it would be far preferable if there's any way to get
eXist do to it for me.
Thanks in advance for your help.
--=20
Rebecca Sutton Koeser
rebecca.s.koeser@...
Digital Programs Team - Woodruff Library, Emory University, Atlanta GA
> I have just updated to 1.0rc from snapshot 20060316. Now I have problems
> importing a module. I execute a XQuery stored in file system (in
> D:\devlp\webapp\retrieval\search) that imports a module stored in eXist. The
> import declaration is:
>
> import module namespace mymodule=""; at
> "xmldb:exist:///db/system/modules/mymodule.xq";;
I just fixed this. The corresponding lines in XQueryContext should be
changed as follows:
XmldbURI locationUri = XmldbURI.xmldbUriFor(location);
if (moduleLoadPath.startsWith(XmldbURI.XMLDB_URI_PREFIX)) {
XmldbURI moduleLoadPathUri = XmldbURI.xmldbUriFor(moduleLoadPath);
locationUri = moduleLoadPathUri.resolveCollectionPath(locationUri);
}
moduleLoadPath should only be used if it is an xmldb URI, not if it
points to the file system.
Wolfgang
Attaching contents of both files :)
thanks
chinmaya
================= xupdate xml ===============
<?xml version="1.0" encoding="UTF-8"?>
<xu:modifications
<!-- remove an address -->
<xu:remove
</xu:modifications>
================== address.xml =================
<?xml version="1.0" encoding="UTF-8"?>
<addressbook>
<address>
<fname>John</fname>
<lname>Jekyll</lname>
<company>Johnny's Car Wash</company>
<city>Bloomington</city>
</address>
<address>
<fname>Andrew</fname>
<lname>Hyde</lname>
<company>Null-Devices</company>
<city>Washington</city>
</address>
</addressbook>
Hi,
> we tried to use the new eXist 1.1rc version today and run into some obscure
> problems and finally found that the exist.jar at least is compiled with JDK 1.5.
Unfortunately, some dependencies on Java 5 made it into the release.
This was a mistake and not intended. The current SVN versions will
again compile with 1.4 and we will make sure the next releases remain
backwards compatible.
Wolfgang
Hi,
we tried to use the new eXist 1.1rc version today and run into some obscure
problems and finally found that the exist.jar at least is compiled with JDK 1.5.
We are due to many other dependencies still on 1.4.2 and CANNOT switch to 1.5 yet.
I know that there might be some nifty features in 1.5 but the load of all people
out here is still on 1.4 and this is not an easy move! So please would it be
possible to still compile with 1.4.2 and support this?
I will try to compile it from source with 1.4.2, is this still possible?
Thanks, Peter
I just added a few Ant scripts to better test eXist's web integration
and HTTP-based interfaces. While the core database functions and the
XQuery language are well-covered by automated tests, we still lack a
dedicated test suite to ensure that all the application-level
interfaces and especially the XQuery-Web integration work as expected.
I have thus experimented with Canoo's WebTest
() yesterday, which is basically just a set of
Ant tasks to simulate a web client and test the behaviour of a web
application. Writing tests is quite easy once you have a general
skeleton, so I decided to integrate this into eXist. For example, the
following code snip invokes test-modules1.xql and checks if the
returned HTML response body contains <h1>PASS</h1>:
<webtest name="testModuleImports2">
<config host="localhost" port="8080" protocol="http"
basepath="exist/rest/db/webtest"
summary="true" resultpath="${test.results}"/>
<steps>
<invoke description="REST: import module from database"
url="test-modules2.xql"/>
<verifyElementText type="H1" text="PASS"/>
</steps>
</webtest>
To run the test suite, call Ant from within the root directory of your
eXist installation:
./build.sh -f tools/webtest/build.xml
The first time you run it, the script will try to download and install
the required WebTest Ant tasks from the Canoo web site. It then starts
a Jetty webserver and processes the tests. The queries for the tests
are contained in directory webapp/webtest. After the test suite has
completed, you will find a test report in
test/webtest/html/results.html.
Right now, the test suite contains just 6 simple tests like this to
check module imports for the XQueryServlet/XQueryGenerator/REST. I'd
like to encourage other developers to add more tests here.
Wolfgang
Artem Y. Pervin wrote:
> Could you, please, point out what else requirements my XML DBMS
> should meet to work within OGSA-DAI?
I'm not sure why you think anyone here, eXist developer or not, could answer
this question and the ones preceding it, at least not from the angle you put
them.
If the OGSA-DAI architecture doesn't work with a NXD system like eXist that
implements a very large subset of the current XQuery spec ( XMLDB:API is now
moribund) then that's a problem for the guys in Edinburgh and Manchester, so
why not ask them?
You might also ask them why their FAQ gives a page not found error. We can't
help with that one, either.
Michael Beddow
Hello, all!
Could anyone from the eXist developers team share the experience of
implementing functionality required by OGSA-DAI architecture?
I`m currently working with an XML DBMS which is not listed among DBMSs
supported by OGSA-DAI. Unfortunately I`m forced to use it. As far as I
understood from OGSA-DAI documentation my XML DBMS have to support
XMLDB:API (by the way, is that true that Core Level 1 of XMLDB:API is
required by OGSA-DAI?).
Probably there is some extra functionality required?
Could you, please, point out what else requirements my XML DBMS
should meet to work within OGSA-DAI?
--
Best regards,
Artem Y. Pervin
mailto:ArtemPervin@...
Still replying to myself:-)
Den 31. jul. 2006 kl. 10.47 skrev Sjur N=F8rsteb=F8 Moshagen:
> Replying to myself:
> ...
> I'll have a look at the current trunk, and see if that one behaves
> any better (but beware that I'm no Java guy, I'm just copying and
> pasting, trying and failing:-)
No luck - I don't understand what's going on. The present trunk =20
(r3921) gives exactly the same behaviour as the 1.0rc code base:
31 jul 2006 14:05:07,871 [P1-9] DEBUG (XIncludeFilter.java =20
[startElement]:169) - processing include ...
31 jul 2006 14:05:07,880 [P1-9] DEBUG (XIncludeFilter.java =20
[processXInclude]:213) - found href=3D"terms-sme.xml#xpointer(//entry=20
[@id=3D'=E1iti\S'])"
31 jul 2006 14:05:07,900 [P1-9] DEBUG (XQuery.java [compile]:154) - =20
Query diagnostics:
[root-node]/descendant-or-self::entry[attribute::id =3D "%C3%A1iti%5CS"]
31 jul 2006 14:05:07,902 [P1-9] DEBUG (XQuery.java [compile]:156) - =20
Compilation took 8
31 jul 2006 14:05:07,904 [P1-9] INFO (XIncludeFilter.java =20
[processXInclude]:305) - xpointer query: [root-node]/descendant-or-=20
self::entry[attribute::id =3D "%C3%A1iti%5CS"]
I'll have to leave this one to those with Real Knowledge.
Best regards,
Sjur
Hello,
Thank you very much for information.
Now I could confirm that my range indexes are created and used.
However, I also found a problem in the Java Interactive Client. In "Query Dialog", the "Context" dropdown seems to be non-functional. I have two collections containting the same set of XML data. No matter what context I choose, it seems like the query always search both collections. Since one collection has a range index and the other does not, eXist doesn't use index to find answer. After I modified the query to explicity choose the collection by collection(""), the query performed as expected and range index is used when it is available.
Maybe this is related to your range index proiblem?
Thank you,
Joe
Boris Verhaegen <boris.verhaegen@...> wrote: Hello
On 7/30/06, Jingjoe Ja wrote:
> Hello,
>
> I'm new to eXist and I have a few questions about range index:
>
> 1. How can I check what indexes are available and active for a collection?
> (without looking at the .xconf file) Right now, I'm curious whether my index
> definition is used by eXist or not.
use the index-keys() function like that :
declare namespace f="";;
declare function f:term-callback($term as xs:string, $data as xs:int+)
as element() {
{$term}
};
util:index-keys(collection("/db/db1kRI"), xs:integer(0),
util:function("f:term-callback", 2), 1000)
this query returns all integers keys >=0 for the collection /db/db1kRI
if your keys are string or doubles, change xs:integer(0) with
xs:string("") or xs:double(0.0)
if you want know if range-index is used by eXist for a given query,
you must use the profiler with i.e.
declare option exist:profiling "enabled=yes verbosity=5";
and see the log file (EXIST_HOME/webapp/WEB-INF/logs/profile.log
you can also tune the log file (size, ...) in EXIST_HOME/log4j.xml
the line to search in log are (from Pierrick, thanks to him)
OPTIMIZATION Using value index to find key 'xs:xxx(yyy)'";
*without*
OPTIMIZATION FALLBACK nodeSetCompare [27,2]
However, it seems there is a problem presently with range-index (see
my discussion with Pierrick in a previous post in this ML "Problem
with range-index").
good evening,
Boris
Send instant messages to your online friends
Perhaps, to explain my reticence on this occasion, I may be allowed to
self-quote from a posting over 3 years ago now...
====================================================
All this insistence on nodesets isn't mere pedantry. It's an issue that
leads to a lot of grief and misunderstanding in the XPath world. Just one
final example of what I mean.
Let's truncate your example file to:
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<test>
<div id="7"></div>
</test>
Now consider the Xpath //div[nr = nr] applied to this file. Not very useful
but perfectly legal. But what's the value of the expression in the
predicate? Deep breath: the value is false. How come? Because where the
operands on both sides of an XPath equality expression are node sets, the
expression is true if, and only if, there is at least one node in each set
that has the same string value as at least one node in the other set. So, if
either or both of the node-sets are empty, the result is false. And while
people are spluttering about that, how about, applied to the same data,
//div[nr != nr] ? That one is false as well: an XPath expression with
operator != and node sets as both operands evaluates to true if and only if
there is at least one node in one set that has a different string value from
at least one node in the other set. So again, if either set is empty, the
expression evaluates to false (and there are a lot of cases in which != and
= between two non-empty nodesets both return the same Boolean
result, since the conditions for the truth of both = and != can hold good
simultaneously).
There are more somewhat counter-intuitive things to be said about operations
on XPath nodesets, but I've probably taken up too much time and bandwidth
already. If it's any consolation, readers of this list can now safely join
me at the any conference bar without running the risk of me winning a beer
off them with this little conundrum. Though I do have one or two others in
reserve...
(full context and thread via )
====================================================
I can't help thinking that we wouldn't have this sort of problem (the
difference between NULL and zero in the database world is a close cousin) if
so many of us weren't shaped by European cultures which didn't absorb the
full impact of ancient Indian mathematics. Ask a Filipino fruitseller in a
Tagalog-speaking region whether she has a particular sort of banana, and if
she is out of stock the reply will be "Wala". Ask the same question of an
ironmonger, and the answer will always be "Hindi". Both have to be
translated as "No" in English, but they represent logically fundamentally
different concepts, a fact that is very plain in some Asian languages but
obscured in most European ones.
Michael Beddow
Hi,
Michael Beddow a =E9crit :
> As ever, if you think eXist is wrong, try Saxon. If Saxon says the same
> thing, as here, either re-ponder the specs or ask on xquery-talk. If yo=
u do,
> Michael Kay will probably give you an answer himself.
I'd add just two things to this excellent answer :
In a general comparison, an empty sequence is never equal to anything=20
else, even an empty sequence.
In a general comparison, an empty sequence is always different from=20
anything else, even an empty sequence.
I can't provide a link to the specs right now, but it should be easy to=20
find the relevant paragraph.
Cheers,
p.b.
Replying to myself:
Den 28. jul. 2006 kl. 21.28 skrev Sjur N=F8rsteb=F8 Moshagen:
> ... and the following item in the changelog
> caught our attention:
>
> - Added important safeguard in XmldbURI to ensure that non-ASCII
> chars are always encoded
It relates to this change:
Index: XmldbURI.java
mldbURI.java (revision 3308)
+++ XmldbURI.java (revision 3309)
@@ -34,6 +34,7 @@
import org.exist.storage.DBBroker;
import org.exist.xquery.Constants;
import org.exist.xquery.util.URIUtils;
+import org.exist.xquery.value.AnyURIValue;
/** A utility class for xmldb URis.
* Since, java.net.URI is <strong>final</strong> this class acts as =20=
a wrapper.
@@ -87,7 +88,7 @@
}
public static XmldbURI xmldbUriFor(String xmldbURI) throws =20
URISyntaxException {
- URI uri =3D new URI(xmldbURI);
+ URI uri =3D new URI(AnyURIValue.escape(xmldbURI));
if(isCollectionPathOnly(uri)) {
return new XmldbURI(uri);
}
Reverting this change in the 1.0rc code base isn't enough - a Cocoon =20
error is thrown instead, indicating that the XIncludes were left =20
untouched by eXist, causing Cocoon to try to resolve references that =20
are internal to the eXist db, which of course fails. The error =20
reported by Cocoon is ironically about the URI containing illegal =20
characters:-)
I'll have a look at the current trunk, and see if that one behaves =20
any better (but beware that I'm no Java guy, I'm just copying and =20
pasting, trying and failing:-)
NOTE: the proper solution would probably be to always ensure proper =20
unescaping of escaped URIs, leaving the above escaping as is.
Best regards,
Sjur | http://sourceforge.net/p/exist/mailman/exist-open/?viewmonth=200607&viewday=31 | CC-MAIN-2014-23 | refinedweb | 3,025 | 66.03 |
Just in case if you didn't notice, there is glm::slerp in the newer versions. The older versions of glm probably used mix as slerp.
Thanks, I did notice that there is glm::slerp, I just hadn't really tried it as there was a problem having to do with there being two versions of glm::slerp having the same arguments, one defined in quaternion.hpp and another in compatibility.hpp. I fixed it by making a small hack to compatibility.hpp. (added an additional namespace inside of glm). After getting that out of the way, the program compiled and everything worked. Thanks for your help, I appreciate it. | http://www.gamedev.net/user/126662-chris528/?tab=posts | CC-MAIN-2016-18 | refinedweb | 110 | 66.94 |
October 27, 2021
Bioconductors:
We are pleased to announce Bioconductor 3.14, consisting of 2083 software packages, 408 experiment data packages, 904 annotation packages, 29 workflows and 8 books.
There are 89 new software packages, 13 new data experiment packages, 10 new annotation packages, 1 new workflow, no new books, and many updates and improvements to existing packages; Bioconductor 3.14 is compatible with R 4.1.1, and is supported on Linux, 32- and.
Bioconductor used Microsoft Azure VMs during our 3.14 release process for a critical part of our branching process for software packages. These VMs are available to Bioconductor through our collaboration with the Microsoft Genomics team.
To update to or install Bioconductor 3.14:
Install R 4.1.1. Bioconductor 3.14 has been designed expressly for this version of R.
Follow the instructions at Installing Bioconductor.
There are 89 new software packages in this release of Bioconductor.
atena.
benchdamic.
BindingSiteFinder.
biodbChebi The biodbChebi library provides access to the ChEBI Database, using biodb package framework. It allows to retrieve entries by their accession number. Web services can be accessed for searching the database by name, mass or other fields.
biodbHmdb.
biodbKegg.
biodbLipidmaps The biodbLipidmaps library provides access to the Lipidmaps Structure Database, using biodb package framework. It allows to retrieve entries by their accession number, and run web the services lmsdSearch and lmsdRecord.
biodbUniprot The biodbUniprot library is an extension of the biodb framework package. It provides access to the UniProt database. It allows to retrieve entries by their accession number, and run web service queries for searching for entries.
BioPlex.
bugsigdbr The bugsigdbr package implements convenient access to bugsigdb.org from within R/Bioconductor. The goal of the package is to facilitate import of BugSigDB data into R/Bioconductor, provide utilities for extracting microbe signatures, and enable export of the extracted signatures to plain text files in standard file formats such as GMT.
BUSseq.
cageminer This package aims to integrate GWAS-derived SNPs and coexpression networks to mine candidate genes associated with a particular phenotype. For that, users must define a set of guide genes, which are known genes involved in the studied phenotype. Additionally, the mined candidates can be given a score that favor candidates that are hubs and/or transcription factors. The scores can then be used to rank and select the top n most promising genes for downstream experiments.
CellBarcode.
Cepo.
cfDNAPro.
cliProfiler An easy and fast way to visualize and profile the high-throughput IP data. This package generates the meta gene profile and other profiles. These profiles could provide valuable information for understanding the IP experiment results.
Cogito.
csdR.
CyTOFpower.
cytoKernel.
deconvR.
DelayedTensor.
Dino.
dStruct.
easier.
enhancerHomologSearch Get ENCODE data of enhancer region via H3K4me1 peaks and search homolog regions for given sequences. The candidates of enhancer homolog regions can be filtered by distance to target TSS. The top candidates from human and mouse will be aligned to each other and then exported as multiple alignments with given enhancer.
epistack The epistack package main objective is the visualizations of stacks of genomic tracks (such as, but not restricted to, ChIP-seq, ATAC-seq, DNA methyation or genomic conservation data) centered at genomic regions of interest.
FindIT2.
FLAMES Semi-supervised isoform detection and annotation from both bulk and single-cell long read RNA-seq data. Flames provides automated pipelines for analysing isoforms, as well as intermediate functions for manual execution.
genomicInstability.
GeoDiff A series of statistical models using count generating distributions for background modelling, feature and sample QC, normalization and differential expression analysis on GeoMx RNA data. The application of these methods are demonstrated by example data analysis vignette.
GEOexplorer: //).
ggmsa A visual exploration tool for multiple sequence alignment and associated data. Supports MSA of DNA, RNA, and protein sequences using ‘ggplot2’. Multiple sequence alignment can easily be combined with other ‘ggplot2’ plots, such as phylogenetic tree Visualized by ‘ggtree’, boxplot, genome map and so on. More features: visualization of sequence logos, sequence bundles, RNA secondary structures and detection of sequence recombinations.
ggspavis Visualization functions for spatially resolved transcriptomics datasets stored in SpatialExperiment format. Includes functions to create several types of plots for data from from spot-based (e.g. 10x Genomics Visium) and molecule-based (e.g. seqFISH) technological platforms.
HPiP.
imcRtools.
iPath.
m6Aboost This package can help user to run the m6Aboost model on their own miCLIP2 data. The package includes functions to assign the read counts and get the features to run the m6Aboost model. The miCLIP2 data should be stored in a GRanges object. More details can be found in the vignette.
MAI.
metapone.
methylclock.
miaSim Microbiome time series simulation with generalized Lotka-Volterra model, Self-Organized Instability (SOI), and other models. Hubbell’s Neutral model is used to determine the abundance matrix. The resulting abundance matrix is applied to SummarizedExperiment or TreeSummarizedExperiment objects.
microbiomeMarker.
MicrobiomeProfiler This is an R/shiny package to perform functional enrichment analysis for microbiome data. This package was based on clusterProfiler. Moreover, MicrobiomeProfiler support KEGG enrichment analysis, COG enrichment analysis, Microbe-Disease association enrichment analysis, Metabo-Pathway analysis.
mitoClone2.
monaLisa.
mosbi This package is a implementation of biclustering ensemble method MoSBi (Molecular signature Identification from Biclustering). MoSBi provides standardized interfaces for biclustering results and can combine their results with a multi-algorithm ensemble approach to compute robust ensemble biclusters on molecular omics data. This is done by computing similarity networks of biclusters and filtering for overlaps using a custom error model. After that, the louvain modularity it used to extract bicluster communities from the similarity network, which can then be converted to ensemble biclusters. Additionally, MoSBi includes several network visualization methods to give an intuitive and scalable overview of the results. MoSBi comes with several biclustering algorithms, but can be easily extended to new biclustering algorithms.
MsBackendRawFileReader implements a MsBackend for the Spectra package using Thermo Fisher Scientific’s NewRawFileReader .Net libraries. The package is generalizing the functionality introduced by the rawrr package (Kockmann T. et al. (2020) <doi:10.1101/2020.10.30.362533>) Methods defined in this package are supposed to extend the Spectra Bioconductor package.
MSstatsLiP Tools for LiP peptide and protein significance analysis. Provides functions for summarization, estimation of LiP peptide abundance, and detection of changes across conditions. Utilizes functionality across the MSstats family of packages.
NanoTube.
netOmics.
NeuCA.
nullranges.
NxtIRFcore.
ODER.
orthogene.
pairkat.
pengls Combine generalised least squares methodology from the nlme package for dealing with autocorrelation with penalised least squares methods from the glmnet package to deal with high dimensionality. This pengls packages glues them together through an iterative loop. The resulting method is applicable to high dimensional datasets that exhibit autocorrelation, such as spatial or temporal data.
plotgardener.
ProteoDisco ProteoDisco is an R package to facilitate proteogenomics studies. It houses functions to create customized (mutant) protein databases based on user-submitted genomic variants, splice-junctions, fusion genes and manual transcript sequences. The flexible workflow can be adopted to suit a myriad of research and experimental settings.
rGenomeTracks.
RiboCrypt R Package for interactive visualization and browsing NGS data. It contains a browser for both transcript and genomic coordinate view. In addition a QC and general metaplots are included, among others differential translation plots and gene expression plots. The package is still under development.
RLSeq RLSeq is a toolkit for analyzing and
evaluating R-loop mapping datasets. RLSeq serves two primary
purposes:
(1) to facilitate the evaluation of dataset quality
rmspc.
scanMiR A set of tools for working with miRNA affinity models (KdModels), efficiently scanning for miRNA binding sites, and predicting target repression. It supports scanning using miRNA seeds, full miRNA sequences (enabling 3’ alignment) and KdModels, and includes the prediction of slicing and TDMD sites. Finally, it includes utility and plotting functions (e.g. for the visual representation of miRNA-target alignment).
scanMiR.
scAnnotatR.
scatterHatch The objective of this package is to efficiently create scatterplots where groups can be distinguished by color and texture. Visualizations in computational biology tend to have many groups making it difficult to distinguish between groups solely on color. Thus, this package is useful for increasing the accessibility of scatterplot visualizations to those with visual impairments such as color blindness.
scReClassify.
scShapes We present a novel statistical framework for identifying differential distributions in single-cell RNA-sequencing (scRNA-seq) data between treatment conditions by modeling gene expression read counts using generalized linear models (GLMs). We model each gene independently under each treatment condition using error distributions Poisson (P), Negative Binomial (NB), Zero-inflated Poisson (ZIP) and Zero-inflated Negative Binomial (ZINB) with log link function and model based normalization for differences in sequencing depth. Since all four distributions considered in our framework belong to the same family of distributions, we first perform a Kolmogorov-Smirnov (KS) test to select genes belonging to the family of ZINB distributions. Genes passing the KS test will be then modeled using GLMs. Model selection is done by calculating the Bayesian Information Criterion (BIC) and likelihood ratio test (LRT) statistic.
scTreeViz.
segmenter.
sparrow.
spatialDE SpatialDE is a method to find spatially variable genes (SVG) from spatial transcriptomics data. This package provides wrappers to use the Python SpatialDE library in R, using reticulate and basilisk.
spatzie Identifies motifs that are significantly co-enriched from enhancer-promoter interaction data. While enhancer-promoter annotation is commonly used to define groups of interaction anchors, spatzie also supports co-enrichment analysis between preprocessed interaction anchors. Supports BEDPE interaction data derived from genome-wide assays such as HiC, ChIA-PET, and HiChIP. Can also be used to look for differentially enriched motif pairs between two interaction experiments.
spiky.
surfaltr.
svaNUMT.
svaRetro svaRetro contains functions for detecting retrotransposed transcripts (RTs) from structural variant calls. It takes structural variant calls in GRanges of breakend notation and identifies RTs by exon-exon junctions and insertion sites. The candidate RTs are reported by events and annotated with information of the inserted transcripts.
synapsis Synapsis is a Bioconductor software package for automated (unbiased and reproducible) analysis of meiotic immunofluorescence datasets. The primary functions of the software can i) identify cells in meiotic prophase that are labelled by a synaptonemal complex axis or central element protein, ii) isolate individual synaptonemal complexes and measure their physical length, iii) quantify foci and co-localise them with synaptonemal complexes, iv) measure interference between synaptonemal complex-associated foci. The software has applications that extend to multiple species and to the analysis of other proteins that label meiotic prophase chromosomes. The software converts meiotic immunofluorescence images into R data frames that are compatible with machine learning methods. Given a set of microscopy images of meiotic spread slides, synapsis crops images around individual single cells, counts colocalising foci on strands on a per cell basis, and measures the distance between foci on any given strand.
tanggle Offers functions for plotting split (or implicit) networks (unrooted, undirected) and explicit networks (rooted, directed) with reticulations extending. ‘ggtree’ and using functions from ‘ape’ and ‘phangorn’. It extends the ‘ggtree’ package [@Yu2017] to allow the visualization of phylogenetic networks using the ‘ggplot2’ syntax. It offers an alternative to the plot functions already available in ‘ape’ Paradis and Schliep (2019) <doi:10.1093/bioinformatics/bty633> and ‘phangorn’ Schliep (2011) <doi:10.1093/bioinformatics/btq706>.
TargetDecoy A first step in the data analysis of Mass Spectrometry (MS) based proteomics data is to identify peptides and proteins. With this respect the huge number of experimental mass spectra typically have to be assigned to theoretical peptides derived from a sequence database. Search engines are used for this purpose. These tools compare each of the observed spectra to all candidate theoretical spectra derived from the sequence data base and calculate a score for each comparison. The observed spectrum is then assigned to the theoretical peptide with the best score, which is also referred to as the peptide to spectrum match (PSM). It is of course crucial for the downstream analysis to evaluate the quality of these matches. Therefore False Discovery Rate (FDR) control is used to return a reliable list PSMs. The FDR, however, requires a good characterisation of the score distribution of PSMs that are matched to the wrong peptide (bad target hits). In proteomics, the target decoy approach (TDA) is typically used for this purpose. The TDA method matches the spectra to a database of real (targets) and nonsense peptides (decoys). A popular approach to generate these decoys is to reverse the target database. Hence, all the PSMs that match to a decoy are known to be bad hits and the distribution of their scores are used to estimate the distribution of the bad scoring target PSMs. A crucial assumption of the TDA is that the decoy PSM hits have similar properties as bad target hits so that the decoy PSM scores are a good simulation of the target PSM scores. Users, however, typically do not evaluate these assumptions. To this end we developed TargetDecoy to generate diagnostic plots to evaluate the quality of the target decoy method.
transformGamPoi Variance-stabilizing transformations help with the analysis of heteroskedastic data (i.e., data where the variance is not constant, like count data). This package provide two types of variance stabilizing transformations: (1) methods based on the delta method (e.g., ‘acosh’, ‘log(x+1)’), (2) model residual based (Pearson and randomized quantile residuals).
traviz.
TRESS This package is devoted to analyzing MeRIP-seq data. Current functionality is for detection of transcriptome-wide m6A methylation regions. The method is based on hierarchical negative binomial models.
tripr.
txcutr.
VAExprs A fundamental problem in biomedical research is the low number of observations, mostly due to a lack of available biosamples, prohibitive costs, or ethical reasons. By augmenting a few real observations with artificially generated samples, their analysis could lead to more robust and higher reproducible. One possible solution to the problem is the use of generative models, which are statistical models of data that attempt to capture the entire probability distribution from the observations. Using the variational autoencoder (VAE), a well-known deep generative model, this package is aimed to generate samples with gene expression data, especially for single-cell RNA-seq data. Furthermore, the VAE can use conditioning to produce specific cell types or subpopulations. The conditional VAE (CVAE) allows us to create targeted samples rather than completely random ones.
veloviz.
There are 13 new data experiment packages in this release of Bioconductor.
curatedTBData The curatedTBData is an R package that provides standardized, curated tuberculosis(TB) transcriptomic studies. The initial release of the package contains 49 studies. The curatedTBData package allows users to access tuberculosis trancriptomic efficiently and to make efficient comparison for different TB gene signatures across multiple datasets.
easierData Access to internal data required
for the functional performance of easier package and exemplary
bladder cancer dataset with both processed RNA-seq data and
information on response to ICB therapy generated by Mariathasan et
al. “TGF-B attenuates tumour response to PD-L1 blockade by
contributing to exclusion of T cells”, published in Nature, 2018
doi:10.1038/nature25501. The
data is made available via
IMvigor210CoreBiologies
package under the CC-BY license.
GSE103322.
GSE159526.
nullrangesData.
NxtIRFdata NxtIRFdata is a companion package for NxtIRF, which is an IRFinder- based R package for Intron Retention and Alternative Splicing quantitation for RNA-seq BAM files. NxtIRFdata contains Mappability files required for the generation of human and mouse references. NxtIRFdata also contains a synthetic genome reference and example BAM files used to test NxtIRF. BAM files are based on 6 samples from the Leucegene dataset provided by NCBI Gene Expression Omnibus under accession number GSE67039.
plotgardenerData This is a supplemental data package for the plotgardener package. Includes example datasets used in plotgardener vignettes and example raw data files. For details on how to use these datasets, see the plotgardener package vignettes.
RLHub | RLHub provides a convenient interface to the processed data provided within RLSuite, a tool-chain for analyzing R-loop-mapping data sets. The primary purpose of RLHub is to serve the processed data sets required by the RLSeq R package and the RLBase web service. Additionally, RLHub provides a stand-alone R interface to these data, benefiting users who are addressing questions related to R-loop regions (RL-Regions), R-loop-binding proteins (RLBPs), R-loop co-localizing factors, and the differences between R-loop-mapping methods. The full data-generating protocol is found here:.
scanMiRData This package contains
companion data to the scanMiR package. It contains
KdModel (miRNA
12-mer binding affinity models) collections corresponding to all
human, mouse and rat mirbase miRNAs. See the scanMiR package for
details.
scATAC.Explorer This package provides a tool to search and download a collection of publicly available single cell ATAC-seq datasets and their metadata. scATAC-Explorer aims to act as a single point of entry for users looking to study single cell ATAC-seq data. Users can quickly search available datasets using the metadata table and download datasets of interest for immediate analysis within R.
spatialDmelxsim Spatial allelic expression counts from Combs & Fraser (2018), compiled into a SummarizedExperiment object. This package contains data of allelic expression counts of spatial slices of a fly embryo, a Drosophila melanogaster x Drosophila simulans cross. See the CITATION file for the data source, and the associated script for how the object was constructed from publicly available data.
TabulaMurisSenisData This package provides access to RNA-seq data generated by the Tabula Muris Senis project via the Bioconductor project. The data is made available without restrictions by the Chan Zuckerberg Biohub. It is provided here without further processing, collected in the form of SingleCellExperiment objects.
tuberculosis The tuberculosis R/Bioconductor package features tuberculosis gene expression data for machine learning. All human samples from GEO that did not come from cell lines, were not taken postmortem, and did not feature recombination have been included. The package has more than 10,000 samples from both microarray and sequencing studies that have been processed from raw data through a hyper-standardized, reproducible pipeline.
There are 10 new annotation packages in this release of Bioconductor.
chromhmmData Annotation files of the formatted genomic annotation for ChromHMM. Three types of text files are included the chromosome sizes, region coordinates and anchors specifying the transcription start and end sites. The package includes data for two versions of the genome of humans and mice.
CTCF.
excluderanges Genomic coordinates of problematic genomic regions that should be avoided when working with genomic data. GRanges of exclusion regions (formerly known as blacklisted), centromeres, telomeres, known heterochromatin regions, etc. (UCSC ‘gap’ table data). Primarily for human and mouse genomes, hg19/hg38 and mm9/mm10 genome assemblies.
GeneSummary This package provides long description of genes collected from the RefSeq database. The text in “COMMENT” section started with “Summary” is extracted as the description of the gene. The long text descriptions can be used for analysis such as text mining.
ontoProcData This package manages rda files of multiple ontologies that are used in the ontoProc package. These ontologies were originally downloaded as owl or obo files and converted into Rda files. The files were downloaded at various times but most of them were downloaded on June 22 2021.
rGenomeTracksData rGenomeTracksData is a collection of data from pyGenomeTracks project. The purpose of this data is testing and demonstration of rGenomeTracks. This package include 14 sample file from different genomic and epigenomic file format.
scAnnotatR.models Pretrained models for scAnnotatR package. These models can be used to automatically classify several (immune) cell types in human scRNA-seq data.
synaptome.data The package provides access to the copy of the Synaptic proteome database. It was designed as an accompaniment for Synaptome.DB package. Database provides information for specific genes and allows building the protein-protein interaction graph for gene sets, synaptic compartments, and brain regions.
synaptome.db The package contains local copy of the Synaptic proteome database. On top of this it provide a set of utility R functions to query and analyse its content. It allows extraction of information for specific genes and building the protein-protein interaction graph for gene sets, synaptic compartments, and brain regions.
TxDb.Athaliana.BioMart.plantsmart51 Exposes an annotation databases generated from BioMart by exposing these as TxDb objects. This package is for Arabidopsis thaliana (taxID: 3702). The BioMart plantsmart release number is 51.
There is 1 new workflow package in this release of Bioconductor.
There are no new online books.
Changes in version 1.41.1
Changes in version 1.65.3 (2021-09-22)
SOFTWARE QUALITY
Making sure all pathnames are of length 100 or shorter.
Changes in version 1.65.2 (2021-09-22)
SOFTWARE QUALITY
Now properly registering native routines.
Changes in version 1.65.1 (2021-09-09)
BUG FIXES
Changes in version 3.3.4 (2021-09-16)
Changes in version 1.3.2 (2021-08-05)
Add rmarkdown to the suggests field
Changes in version 1.3.1 (2021-08-05)
Add warnings for small sample size.
Changes in version 3.1.0
MAJOR UPDATES
USER-VISIBLE MODIFICATIONS
(3.1.1) If there is a duplicate entry in the hub cache for a resource, hub code will no longer produce an ERROR. If the duplicate resource was not requested the duplicate is ignored. If the duplicate resource is requested, produce a warning for corrupt cache and continue with first found entry.
(3.1.3) Fix typo in message display
(3.1.5) Deprecate the
display,Hub-method
BUG CORRECTION
Changes in version 1.6.0
NEW FEATURES
(v. 1.5.5) add repository() to return the binary repository location, if available.
(v. 1.5.7) drs_stat() and drs_cp() support signed URLs
USER VISIBLE CHANGES
(v. 1.5.2) drs_stat() uses multiple cores (on non-Windows) to enhance performance
(v. 1.5.6) install() delegates to BiocManager::install(), providing more flexibility (e.g., installing from GitHub) and robustness.
(v. 1.5.7) drs_stat() returns fields more selectively.
Changes in version 1.4.0
New Features
Changes in version 1.7.3 (2021-08-01)
Fixed the typo in vignettes.
Changes in version 1.7.2 (2021-07-31)
Fixed the issues of using 3’most bam file (generate using ThreeMostPairBam) in PASEXP_IPA.
Changes in version 1.7.1 (2021-07-09)
Fixed the missing SS column issues in PAS2GEF.
Changes in version 3.23.1 (2021-08-19)
DOCUMENTATION
Changes in version 1.10.2 (2021-07-13)
Bug fix affecting {artmsAnalysisQuantifications()}
Allow {artmsAnalysisQuantifications()} to process previous versions of artMS
Change Extension of {artms_sessionInfo_quantification} file from {.txt} to {.log}
Change default parameters of the configuration files: less verbose
Changes in version 1.10.1 (2021-06-30)
External packages used exclusively by the {artmsAnalysisQuantifications} function are not required. Those packages will have to be installed before running this function.
{artmsAvgIntensityRT}: argument {species} is not longer required
Changes in version 2.3.1
BUG FIXES
Changes in version 1.17.1
Changes in version 0.99.36 (2021-08-01)
USER VISIBLE CHANGES
Changes in version 2.5.7 (2021-10-05)
Fix tests for BiocParallel behaviour.
Changes in version 2.5.6 (2021-10-05)
Revert 2.5.5 changes; add expectation to empty tests.
Changes in version 2.5.5 (2021-08-24)
Bugfix tests with change in BiocParallel behaviour
Changes in version 2.5.4 (2021-08-24)
Ensure ordering of genes in chains is consistent with input data when using divide and conquer
Changes in version 2.5.3 (2021-08-11)
Add GeneExponent and CellExponent settings for divide and conquer.
Changes in version 2.5.2 (2021-08-11)
Add better spacing around EFDR message.
Fix ggplot2
guide=FALSE warnings
Remove an errant browser() call
Changes in version 2.5.1 (2021-05-19)
Add error condition for unnamed cells.
Changes in version 1.3.1
Minor improvements and fixes
Update documentation for getRDS(), mcmcChain(), and spatialEnhance().
Changes in version 1.3.0
Minor improvements and fixes
Changes in version 0.99.4 (2021-10-15)
Changed stats::coef to stats4::coef
Changes in version 0.99.3 (2021-10-15)
Added the plotIt = FALSE option for plotRMSE function
Added some more explanations into the “Goodness of Fit” chapter
fitNB, fitZINB, fitHURDLE, fitZIG, and fitDM functions now work with both phyloseq object or count matrices
Changes in version 0.99.2 (2021-10-11)
Changed dependency from R 4.0.0 to 4.1.0
Added example for iterative_ordering() function
Removed the usage of @ to access object’s slot in the vignette
Removed a suppressMessages() and a suppressWarnings() from createTIEC()
Added verbosity to createTIEC() function
Added NEWS file
Changes in version 0.99.1 (2021-10-04)
Removed unnecessary files
Changes in version 0.99.0 (2021-09-29)
Bumped version for submission to Bioconductor
Added README.md file
Changes in version 2.18.1
Possibility to retrieve single cell full length RNA-Seq from Bgee 15.0 and after
Possibility to filter data based on sex and strain for Bgee 15.0 and after
Possibility to filter on cellTypeId for single cell full length RNA-Seq for Bgee 15.0 and after
Added pValue in the download files
Changes in version 0.99.10
coverageOverRanges() now supports mean and sum as combination method. Dpending on the returnOption, mean/ sum are computed over ranges or replicates.
Changes in version 0.99.9
BSFDataSet() and BSFDataSetFromBigWig() now check the path to the bigwig files in the meta data for potential duplicates
coverageOverRanges() now supports also ranges with different width,
if
returnOption =
merge_positions_keep_replicates
Fix bug in makeBindingSites(); The minWidth parameter is now implemented as true lower boundary (>= instead of >). The default has changed from 2 to 3.
Fix description in makeBindingSites(); The minCrosslinks parameter describes the number of positions covered by crosslink events, instead of the total number of crosslinks.
Updated color scheme in rangeCoveragePlot(); and changed position of indicator box
Updated visual of reproducibiliyCutoffPlot() function
Changes in version 0.99.8
Updated coverageOverRange(), Function now does support different output formats, summarizing the coverage differently over range, replicates and condition
Changes in version 0.99.1
Fix bugs for Bioconductor submission
Changes in version 0.99.0 (2021-05-15)
Submitted to Bioconductor
Changes in version 1.29
NEW FEATURES
(1.29.10) Check for
Sys.setenv and
suppressWarnings/
suppressMessages
(1.29.8) Check for
sessionInfo /
session_info in vignette code.
(1.29.5) Check for installation calls in vignette code.
(1.29.1) Check for
install() function calls in R code.
BUG FIXES
(1.29.14) Various internal improvements to the codebase.
(1.29.12) Checks on class membership code now include
is() ==
grammar.
(1.29.6) Use appropriate input (
pkgdir) to internal checking
functions.
(1.29.3) Add unit tests for legacy function searches.
(1.29.2) rename internal function from checkIsPackageAlreadyInRepo to checkIsPackageNameAlreadyInUse
Changes in version 2.1
MAJOR UPDATES
Changes in version 1.28
USER VISIBLE CHANGES
(v 1.27.3) Setting
progressbar = TRUE for SnowParam() or
MulticoreParam() changes the default value of
tasks from 0 to
.Machine$integer.max, so that progress on each element of
X is
reported.
(v 1.27.3)
tasks greater than
length(X) are set to
length(X). Thus
.Machine$integer.max, for instance, assures
that each element of
X is a separate task.
(v 1.27.5) Use of random numbers is robust to the distribution of jobs across tasks for SerialParam(), SnowParam(), and MulticoreParam(), for both bplapply() and bpiterate(), using the RNGseed= argument to each *Param(). The change is NOT backward compatible – users wishing to exactly reproduce earlier results should use a previous version of the package.
(v 1.27.8) Standardize SerialParam() construct to enable setting additional fields. Standardize coercion of other BiocParallelParam types (e.g., SnowParam(), MulticoreParam()) to SerialParam() with as(., “SerialParam”).
(v. 1.27.9) By defualt, do not only run garbage collection after every call to FUN(), except under MulticoreParam(). R’s garbage collection algorithm only fails to do well when forked processes (i.e., MulticoreParam) assume that they are the only consumers of process memory.
(v 1.27.11) Developer-oriented functions bploop.*() arguments changed.
(v 1.27.12) Ignore set.seed() and never increment the global random number stream. This reverts a side-effect of behavior introduced in v. 1.27.5 to behavior more consistent with version 1.26.
(v 1.27.16) Better BPREDO support for previously started BPPARAM, and ‘transient’ BPPARAM without RNGseed.
BUG FIXES
Changes in version 1.12.0
NEW FEATURES
biocRevDepEmail sends an email to several downstream maintainers to
notify them of a deprecated package.
biocBuildEmail allows deprecation notices using the template in the
inst folder. Use
templatePath() to see available templates by
their
location.
PackageStatus indicates whether a package is slated for
‘Deprecation’ by checking the
meat-index.dcf file.
pkgDownloadStats provides the download statistics table for a
particular package.
BUG FIXES
biocDownloadStats includes all types of Bioconductor packages
biocBuildReport improved to work on old-rel, release, and devel
Bioconductor versions
Changes in version 2.22.0
USER-VISIBLE CHANGES
BUG FIXES AND IMPROVEMENTS TO HTML STYLE
Improved navigation for screen readers by adding role=’link’ and tabindex=’0’ to elements in the table of contents. TOC navigation can also be followed by pressing “Enter” when selected in addition to clicking with the cursor.
Addressed further styling issues for code blocks, introduced by changes in rmarkdown. This time re-introducing padding around <pre> tags.
Changes in version 1.3.8
SIGNIFICANT USER-VISIBLE CHANGES
use_bioc_github_action() has been updated to match as much as possible the changes in r-lib/actions up to the latest commit.
Changes in version 1.3.4
NEW FEATURES
use_bioc_github_action() is now more robust in preventing tcltk errors thanks to this pull request by Ben Laufer.
Changes in version 1.3.2
NEW FEATURES
Changes in version 1.61.0
ENHANCEMENT
Changes in version 1.1.16 (2021-10-19)
Update documentation.
Add ORCID for Alexis.
Changes in version 1.1.15 (2021-10-18)
Correct getUrlContent() to handle binary files.
Changes in version 1.1.14 (2021-10-17)
Factorize RCurl calls into global functions.
Disable warnings in calls to readLines() when using base::url().
Catch errors when trying to set locale.
Correct some tests.
Changes in version 1.1.13 (2021-10-12)
Make custom persistent the cache the default, following slowness with BiocFileCache in biodbHmdb.
Remove useless bib refs in vignettes/references.bib.
Add session info in vignettes.
Add ORCID, URL and BugReports.
Add an install section in main vignette.
Changes in version 1.1.12 (2021-10-09)
Switch back to custom implementation of persistent cache, following errors with BiocFileCache on Windows and also slowness with HMDB.
Changes in version 1.1.11 (2021-10-07)
Decompose test test.collapseRows() because of error on Bioconductor not reproduced on local computer.
Changes in version 1.1.10 (2021-09-30)
Disable UniProt request test: it fails (result is NA) for reason unknown only on Bioconductor Linux server during “R CMD check”. Works fine on local computer.
Changes in version 1.1.9 (2021-09-28)
Correct handling of wrong URL with base::url().
Changes in version 1.1.8 (2021-09-28)
Correct bug of UniProt request on Windows.
Changes in version 1.1.7 (2021-09-23)
Ignore build folder when building package.
Update documentation.
Correct setting of R_ENVIRON_USER when building.
Changes in version 1.1.6 (2021-09-14)
Update documentation.
Changes in version 1.1.5 (2021-09-13)
Correct bug in return type of BiodbRequestScheduler::sendRequest().
Correct encoding of test reference filenames.
Changes in version 1.1.4 (2021-09-12)
Allow to set the test reference folder directly into runGenericTests(). This is now necessary for running generic tests in extension packages.
Changes in version 1.1.3 (2021-09-12)
Set package name when calling runGenericTests() in order to find test ref files the correct way, by calling system.file().
Changes in version 1.1.2 (2021-09-09)
Use BiocFileCache for the persistent cache system.
Switch to R6.
Define do…() private methods to be redefined in subclasses, instead of redefining public methods defined inside super class.
Use now local entry files for testing parsing of entry fields.
Changes in version 1.1.1 (2021-06-10)
Allow skipping of some fields when testing searchForEntries().
Move test reference entries folder from tests/testthat/res to inst/testref.
Move long tests folder from tests/long to longtests and enable Bioconductor long tests.
Changes in version 1.0.4 (2021-06-09)
Bug fix: correct call to logger in BiodbPersitentCache class.
Changes in version 1.0.3 (2021-05-26)
Bug fix: correct generic test of searchForEntries(), allowing testing with NA value.
Changes in version 1.0.2 (2021-05-23)
Bug fix: correct return type of searchForEntries(), which now returns always a character vector and never NULL.
Changes in version 1.0.1 (2021-05-20)
Bug fix: correct some calls to logging functions that raised a warning.
Changes in version 0.99.6 (2021-10-12)
Rename vignette.
Add session info and install section in vignette.
Use importFrom.
Changes in version 0.99.5 (2021-10-07)
Write description on multiple lines.
Put comment banners to indicate public and private sections in R6 class.
Changes in version 0.99.4 (2021-09-28)
Correct list index in vignette.
Changes in version 0.99.3 (2021-09-28)
Complete all chapters in README.
Remove ‘foo’ names in vignette.
Changes in version 0.99.2 (2021-09-23)
Define R_BUILD_TAR in makefile to build on UNIX.
Changes in version 0.99.1 (2021-09-23)
Upgrade maintenance files.
Ignore build folder.
Changes in version 0.99.0 (2021-09-16)
Submitted to Bioconductor
Changes in version 0.99.4 (2021-10-18)
When reading the zipped database, take the only XML file available, ignoring other files.
Changes in version 0.99.2 (2021-10-12)
Add ORCID, URL and BugReports.
Add session info and install sections in vignette.
Corrected indentations in vignette.
Changes in version 0.99.1 (2021-09-29)
Slight corrections for Bioconductor submission.
Changes in version 0.99.0 (2021-07-16)
Submitted to Bioconductor
Changes in version 0.99.4 (2021-10-13)
Merge both vignettes into a single one.
Remove messages from magick package.
Changes in version 0.99.3 (2021-10-12)
Add install section in vignette.
Use importFrom.
Add ORCID, URL and BugReports.
Changes in version 0.99.2 (2021-10-12)
Rename main vignette file.
Add reference.
Add session info in vignettes.
Changes in version 0.99.1 (2021-09-28)
Made some corrections for submitting to Bioconductor.
Changes in version 0.99.0 (2021-09-16)
Submitted to Bioconductor
Changes in version 0.99.3 (2021-10-18)
Remove deprecated slow frequency of request send.
Changes in version 0.99.2 (2021-10-12)
Add ORCID, URL and BugReports.
Add citation into vignette.
Add install and session info sections to vignette.
Changes in version 0.99.1 (2021-09-29)
Complete README.
Slight corrections for Bioconductor submission.
Add generated documentation files.
Changes in version 0.99.0 (2021-09-16)
Submitted to Bioconductor.
Changes in version 0.99.4 (2021-10-12)
Add session info and install section in vignette.
Rename vignette.
Use importFrom.
Add ORCID, URL and BugReports.
Changes in version 0.99.3 (2021-10-11)
Show progress when filtering results in geneSymbolToUniprotIds().
Changes in version 0.99.2 (2021-10-03)
Use biodb 1.1.10.
Changes in version 0.99.1 (2021-09-23)
Ignore build folder when building package.
Add documentation.
Changes in version 0.99.0 (2021-09-16)
Submitted to Bioconductor
Changes in version 2.50.0
MINOR CHANGES
BUG FIXES
Address issue where checking the list of Ensembl Archives would stop all queries from working if the main site was unavailable.
Fix bug introduced in getSequence() where asking for flanking sequences resulted in an invalid query.
The argument ‘host’ is no longer ignored in useEnsembl() (Thanks to forum user “A” -)
Changes in version 1.0.0
Changes in version 1.17.0
futureand
doFuturefor simplification of parallelization. All control of parallel computation now done through
BiocParallel.
Changes in version 0.99.0
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 0.99.18 (2020-06-01)
Importing “assay<-“ in the NAMESPACE
Changes in version 0.99.17 (2020-06-01)
Correcting the import of dependencies
Changes in version 0.99.16 (2020-06-01)
Avoiding the overlapping when loading dependencies
Changes in version 0.99.15 (2020-06-01)
Removing the redundant print and summary function
Changes in version 0.99.14 (2020-06-01)
Modifying the output of BUSseq_MCMC as a SingleCellExperiment object and allowing the input as that object as well
Changes in version 0.99.13 (2020-05-15)
Modifying the running example
Changes in version 0.99.12 (2020-05-15)
Revising the random number generator for MacOS
Changes in version 0.99.11 (2020-05-15)
Debugging for MacOS
Changes in version 0.99.10 (2020-05-15)
Continuing to debug for MacOS
Changes in version 0.99.9 (2020-05-15)
Modifying the warnings when building on MacOS
Changes in version 0.99.8 (2020-05-15)
Correcting the usage of OS macro
Changes in version 0.99.7 (2020-05-14)
Updating th source code for MacOS
Changes in version 0.99.6 (2020-05-13)
Downsizing the example dataset to avoid reaching the time limit of check
Changes in version 0.99.5 (2020-05-12)
Adding the macro for Mac in the source code
Shortening the vignettes
Adding Watched Tags BUSseq to my profile
Changes in version 0.99.4 (2020-05-12)
Correct R version dependency
Solve the warnings by missing parenthesees
Changes in version 0.99.3 (2020-05-08)
Set LazyData as TRUE for building vignette
Changes in version 0.99.2 (2020-05-08)
Correctly pushing by Git
Changes in version 0.99.1 (2020-05-07)
Revised the warnings by R CMD check, including adding parentheses in src and R dependency in DESCRIPTION
Changes in version 0.99.0 (2020-05-04)
Submitted to Bioconductor
Changes in version 0.99.0
NEW FEATURES
Changes in version 2.0.0
BACKWARDS-INCOMPATIBLE CHANGES
The
CAGEset class is removed.
Accessors using plain
data.frame formats are removed.
Modifier functions return the object instead of silently modifying it
in the global environment. Thus, you can use R pipes (
|>).
Removed export function that unconditionally wrote files to the
working directory, such as
exportCTSStoBedGraph. As a replacement
a
new converter is provided,
exportToBrowserTrack, that produces
UCSCData objects that the user can then wite to files using the
rtracklayer package.
Removed the
extractExpressionClass function, as the information is
easily accessible from within the
CTSS or
ConsensusClusters
objects.
NEW FEATURES
CTSSnormalizedTpmGR and
CTSStagCountGR now accept
"all" as a
special
sample name to return them all in a
GRangesList object.
Plot interquantile width and expression clusters with ggplot2.
BUG FIXES
Corrected the
getExpressionProfiles function to accept CAGEexp
objects.
Updated the
exampleCAGEexp object to contain expression classes.
Restore paraclu support for CAGEexp objects.
Corrected a bug in
aggregateTagClusters that was causing
mislabelling
of tag clusters (PR#42).
Prevent
plotReverseCumulatives from crashing when values are not in
range. (PR#43).
Changes in version 2.11.3
BUG FIXES
Fix strange behavior from random number generation in R >= 4.1.1
Changes in version 2.11.2
BUG FIXES
Fix reference naming scheme for binning and alignment methods
Changes in version 2.11.1
BUG FIXES
Use as(x, ‘DFrame’) instead of as(x, ‘DataFrame’)
Fix logical length > 1 error in ‘segmentationTest()’
Changes in version 1.16.0 (2021-10-14)
New Features
Changes in version 2.6.0
New features
Changes in version 1.9.3 (2021-10-04)
Speed up final step in decontX when creating final decontaminated matrix
Changes in version 1.9.2 (2021-07-19)
Changes in version 0.0.1
Changes in version 1.5.4
Update CITATION
Changes in version 1.4.3
Fix netConditionsPlot function bug related to factors in data.frame
Changes in version 0.99.1
Documentation improvements.
Changes in version 0.99.0
Changes in version 3.27.7
Fix the error “!anyNA(m32) is not TRUE” in seqlevelsStyle is not handled.
Changes in version 3.27.6
Fix the error “pvalue” undefined columns selected in enrichmentPlot
Changes in version 3.27.5
update documentation of pipeline.rmd
Changes in version 3.27.4
use formatSeqnames function to handle the error from seqlevelsStyle: “cannot switch some of GRCm38’s seqlevels from NCBI to UCSC style”
Changes in version 3.27.3
use formatSeqnames function to handle the error from seqlevelsStyle: “!anyNA(m31) is not TRUE “
Changes in version 3.27.2
add keepExonsInGenesOnly for genomicElementDistribution
add upstream and downstream for assignChromosomeRegion function when define promoter and downstream regions.
Changes in version 3.27.1
Add the possibility of find overlaps by percentage covered of interval for function findOverlapsOfPeaks
Changes in version 1.29.2
extend functions for plotting peak profiles to support other types of bioregions (2021-10-15, Fri, @MingLi-292, #156, #160, #162, #163)
Changes in version 1.29.1
add example for seq2gene function (2021-05-21, Fri)
Changes in version 1.1.3
Overview:
New functionalities:
Fixed and improved input in CAPRIpop dataset format
Changes in version 1.1.1
Overview:
New functionalities:
Fixed bugs related with byrow options when reading CAPRI formatted datasets
Improved VisNetwork output to include information about samples inside nodes
Changes in version 2.14.0
Changes in version 0.99.0 (2021-01-22)
Changes in version 1.7.0
Changes in version 1.32.0
DEPRECATION NOTICE
Changes in version 4.1.4
import yulab.utils (2021-08-20, Fri)
Changes in version 4.1.3
Remove Human Gut Microbiome dataset as the functionalities are provided in (2021-08-15, Sun)
Changes in version 4.1.2
update kegg_species.rda and allow online download using KEGG api (2021-08-14, Sat)
Changes in version 4.1.1
Changes in version 1.5.2 (2021-10-04)
clustify_lists() support for output of overlapping genes
(
details_out = TRUE)
Added truncated mean and trimean modes to
average_clusters()
Changes in version 1.5.1 (2021-08-04)
clustify_lists() support for uneven number of markers
Deprecated SeuratV2 support
Changes in version 1.7.4
MINOR
Minor fix: removed ` from Vignette
Changes in version 1.7.3
SIGNIFICANT USER-VISIBLE CHANGES
CNVfilteR specfically supports VCFs produced by Torrent Variant Caller
Changes in version 1.7.2
BUG FIXES
MINOR
Minor bug fixed: stop message was not completely shown on loadSNPsFromVCF()
Changes in version 1.7.1
MINOR 2.9.4
fixed a bug of missing right annotation legends for vertically concatenated heatmaps.
Legend(): support
border to be set to
asis.
Rasterization: the default maximal size for temporary image is set to 30000 px (both for width and height).
add a new argument
beside in
anno_barplot() to position bars
beside each other.
add
plot() method for
Heatmap and
HeatmapList classes.
add
anno_customize().
Changes in version 2.9.3
pheatmap()/
heatmap()/
heatmap.2(): set default of run_draw to
FALSE.
throw error when the heatmaps (list) are already initialized by draw() when adding them.
set
wrap = TRUE in
grid.grabExpr() when capturing the legend
objects.
make_comb_mat(): support
GRangesList object as input.
legends: fixed a bug of the grid heights were not correctedly calculated.
discrete annotations: neighbour grids are merged into one single grid if they have the same values.
anno_barplot(): allows to add numbers on top of bars.
UpSet(): axis labels are automatically formated for genomic
coordinates.
AnnotationFunction(): add a new argument
cell_fun.
When the dendrogram height is zero, the corresponding viewport has scale (0, 1).
Changes in version 2.9.2
fixed a bug of
bg_col for transposed matrix in
UpSet().
print warnings if names of annotations have different orders from the matrix row/column names.
Changes in version 2.9.1
fixed a bug of editing gTree object where the list element “just” has been changed to “justification” in recent R versions.
Changes in version 1.1.002 (2021-08-31)
Made the following significant changes
Added an internal function .retrieveClustersNumberK to suggest the clusters number to use in lusterCellsInternal().
Added suggestedClustersNumber slot in scRNAseq class to retrieve this suggested clusters number.
Added accessors getSuggestedClustersNumber and setSuggestedClustersNumber.
Updated all the objects used in examples and tests to have this slot.
Changes in version 1.5.7
CoreSets can now be made with treatment combination experiments via the TreatmentResponseExperiment class!
Changes in version 1.5.6
Fix bug in LongTable -> data.table coerce method that was causing rows of some assays to be dropped (closes issue #)
Changes in version 1.5.5
Overhauled LongTable coerce methods to use the LongTableDataMapper class instead of the deprecated ‘LongTable.config’ attribute
Changes in version 1.5.4
Fix bug in .sanitize input caused by length > 1 coercing to logical vector
Changes in version 1.5.3
Fix bug in connectivityScore caused by length > 1 coercing to logical vector; this should fix errors in RadioGx and PharmacoGx vignettes that were caused by failed R CMD build
Changes in version 1.5.2
Added a CoreSet-utils documentation section to document subset, intersect, combine and other set operations for a CoreSet object.
Changes in version 1.5.1
Fix bug in .rebuildProfiles where the function fails if replicate_id is assigned as a rowID column in the LongTable in @sensitivity
Changes in version 1.5.0
Changes in version 0.99.6
Calculation of column ranks now uses matrixStats::colRanks instead of an apply statement with base::rank.
Changes in version 0.99.0
Changes in version 1.12.0
Web server support (optimised to run in ShinyProxy)
Bug fixes and minor improvements
Changes in version 0.99.0
Changes in version 1.5.4 (2021-09-17)
It is not required anymore to specify exactly the right colours
Changes in version 1.5.3 (2021-09-16)
Added option to read in .h5 files
Changes in version 1.5.2 (2021-09-15)
Added description on how to handle images with couplet/patchwork
Changes in version 1.5.1 (2021-05-19)
Bugfix: erroneous dimension setting when legend=NULL
Changes in version 3.11
API Changes
Fixes/internal changes
Add CytoML XSD to installation
Changes in version 3.10
API Changes
Change handling of quad gates according to RGLab/cytolib#16
Renaming of methods:
compare.counts -> gs_compare_cytobank_counts
Renaming of classes:
flowJoWorkspace -> flowjo_workspace
Fixes/internal changes
Changes in version 2.6.0
Major: We fixed a bug in DaMiR.ModelSelect. Now optimal models are correctly selected;
Major: Now users can plot specific graphs in DaMiR.Allplot and we added new plots;
Minor: We modified the color scale in corrplot
Changes in version 1.3.2
NEW FEATURES
Changes in version 1.5.1 (2021-09-01)
Changes in version 2.0.0
Changes
Some method’s names have been changed to make them easier to identify:
scira now is called Univariate Linear Model (ulm).
The column name for tf in the output tibbles has been changed to source.
Updated documentation for all methods.
Updated vignette and README.
decouple function now accepts order mismatch between the list of methods and the list of methods’s arguments.
New features
New methods added:
Multivariate Linear Model (mlm).
New decoupleR manuscript repository:
New consensus score based on RobustRankAggreg::aggregateRanks() added when running decouple with multiple methods.
New statistic corr_wmean inside wmean.
Methods based on permutations or statistical tests now return also a p-value for the obtained score (fgsea, mlm, ora, ulm, viper, wmean and wsum).
New error added when network edges are duplicated.
New error added when the input matrix contains NAs or Infs.
Changes in version 1.1.0
New features
All new features allow for tidy selection. Making it easier to evaluate different types of data for the same method. For instance, you can specify the columns to use as strings, integer position, symbol or expression.
Methods
New decouple() integrates the various member functions of the decoupleR statistics for centralized evaluation.
New family decoupleR statists for shared documentation is made up of:
Converters().3.1
Changes in version 0.20.0
BUG FIXES
Changes in version 1.0.0
Changes in version 1.9.1 (2021-10-16)
Changes in version 1.1.2
Changes in version 2.1.4
Using non-linear fit to constrain similarity matrix.
Recalculate intensity for given peaks.
Direct alignment to root is added.
Multiple strategies for getting distance matrix and tree-agglomeration is added.
Remove peaks if not aligned.
Changes in version 2.1.0
Added support for IPF based Post-translation Modification alignment.
Added Minimum Spanning Tree based alignment for reference-free approach.
Reintegrate area under the peak for low-confidence peaks.
Supporting Savitzky-Golay smoothing while calculating area.
Added input to select peptides which to align.
Speed improvement in progressive alignment by storing new featues in lists instead of data frames.
Changes in version 3.3.4
Fix bFlip issues
Fix bug where mode not passed to summarizeOverlaps
Add $inter.feature config parameter
Changes in version 3.3.2
Re-compute FDR when fold change other than 0 is specified
Remove most gc() calls for performance
Roll in bugfixes
Changes in version 0.99.5
Data reformatting
Changes in version 0.99.4
Bug fix
Changes in version 0.99.3
Reduce size of tutorial data
Changes in version 0.99.1
Updated default number of cores to 2
Changes in version 0.99.0
Changes in version 1.4.1
fixed bug in log2_FC.R;
added rmarkdown as
Suggests in DESCRIPTION.
Changes in version 1.6
Bug Fixes:
Changes in version 3.19.4
upate error message of enricher_internal (2021-9-3, Fri)
Changes in version 3.19.3
upate DisGeNET and NCG data (2021-8-16, Mon)
Changes in version 3.19.2
bug fixed, change ‘is.na(path2name)’ to ‘all(is.na(path2name))’ (2021-06-21, Mon)
Changes in version 3.19.1
Changes in version 0.99.3 (2021-05-23)
Ensured that all global variables are well-defined in the namespace.
Changes in version 0.99.2 (2021-05-22)
Revised to address comments by the Bioconductor reviewer.
dStruct now uses the IRanges object from Bioconductor.
All function names follow camel case.
More descriptions of functions.
Added a test to check validity of code when running dStruct in the proximity_assisted mode.
Changes in version 0.99.1 (2021-04-11)
Fixed errors and warnings from checks by bioc-issue-bot.
Changes in version 0.99.0 (2021-04-07)
Submitted to Bioconductor
Changes in version 0.9.0
Changes in version 1.5.2
Changes in version 1.12
Changes in version 1.13.2
cnetplot now works with a named list (2021-08-23, Mon; clusterProfiler#362)
Changes in version 1.13.1
Changes in version 2.17.4
Fix issue with extracting 5’ or 3’ UTRs for transcript without UTRs.
Changes in version 2.17.3
Make parameter
port optional in the script to create EnsDb
databases.
Changes in version 2.17.2
Disable ideogram plotting in vignettes.
Changes in version 2.17.1
Fix error when importing uncompressed GTF files.
Changes in version 1.1.9 (2021-09-19)
min.baseq to reduce the effect of sequencing errors
very fast Fisher Exact from HTSlib
old code removed
Changes in version 1.1.0 (2021-05-21)
Changes in version 1.0.8
Minor bug fix in maxStepProb documentations
Changes in version 1.0.7
Exporting maxStepProb, which compute the MLE of initial and transition probabilities of a K-state HMM, as well as simulateMarkovChain, which simulates a Markov chain of length ‘n’ given a matrix of transition probabilities
Changes in version 1.0.6
Minor bug fix in controlEM documentation
Changes in version 1.0.5
Minor bug fix in callPatterns and info function (explict import of S4Vectors::mcols and utils::tail).
Exporting expStep function, which implements the E-step of EM algorithm (forward-backward & Viterbi algorithm) for a K-state HMM.
Changes in version 1.0.4
Adding function callPatterns to exp[ort] combinatorial patterns (or posterior probabilities) associated with a given set of genomic regions.
Adding function info to print summary statistics from epigraHMM output. This function will print the model’s BIC, log-likelihood, and combinatorial patterns associated with mixture model components.
Adding new example dataset helas3 with ENCODE ChIP-seq data from broad epigenomic marks H3K27me3, H3K36me3, and EZH2.
Adding option to prune combinatorial patterns associated with rare states. See vignette for details.
In differential peak calling, epigraHMM now exports combinatorial pattern table. See vignette for details.
Improvement of the vignette to clarify epigraHMM’s use of blacklisted regions and gap tracks.
Changes in version 1.0.3
Minor updates in the NEWS file as well as the README page.
Changes in version 1.0.2
epigraHMM now exports a function called segmentGenome that segments a given genome (e.g. ‘mm10’) into non-overlapping genomic windows while considering gap tracks and blacklisted regions.
Changes in version 1.0.1
Minor fix in the package DESCRIPTION file and version numbers
Changes in version 1.3.1
Aligning versions to the current bioconductor release
Added DietSeurat() call in vignette to prevent issues
Changes in version 1.19.1
default for typePlot: fix issue length > 1 in coercion to logical
fix for ggplot2 >= 3.3.4: replace guides(fill = FALSE) by guides(fill = ‘none’)
fix few notes check SummarizedExperiment + ggvis
Changes in version 2.1.0
MAJOR UPDATES
Changes in version 1.21.2
Allow writing of HaploPainter input files without a HaploPainter installation.
Changes in version 1.21.1
Add information on kinship-based relatedness to kinship sum test results.
Keep memory consumption constant. This allows arbitrary long simulation runs without running out of memory. Fixes issue #22. Due to the solution of that problem, histograms and densities reported by the simulation functions may slightly deviate from comparable former runs on the same data.
Changes in version 1.3.1 (2021-10-13)
Fix tests
Changes in version 1.3.0 (2020-11-27)
Rshiny modifications for figure in paper
Changes in version 1.19.7
Changes in version 1.19.4
plotGseaTable now accepts units vector for column widths
Changes in version 1.19.2
Fixed fora() failing to run on a single pathway
Fixed problems random gene set generation for large k (issue #94)
Changed default eps to 1e-50
Changes in version 0.99.13 (2021-08-11)
convert geom_density into geom_hist in plot_annoDistance function
Changes in version 0.99.11 (2021-07-16)
rename findIT_enrichInAll to findIT_enrichFisher
Changes in version 0.99.10 (2021-07-15)
move all shiny function in FindIT2 into InteractiveFindIT2
Changes in version 0.99.0 (2021-06-27)
Changes in version 2.0.0
New loadFry() function, written by Dongze He with contributions from Steve Lianoglou and Wes Wilson. loadFry() helps users to import and process alevin-fry quantification results. Can process spliced, unspliced and ambiguous counts separately and flexibly. Has specific output formats designed for downstream use with scVelo or velocity analysis. See ?loadFry for more details.(). For gene-level summarization, importAllelicCounts() can create an appropriate tx2gene table with the necessary a1 and a2 suffices, and it will automatically set txOut=FALSE, see ?importAllelicCounts for more details.
Added a ‘q’ argument to plotInfReps to change the intervals when making point and line plots.
Switched the legend of plotInfReps so that reference levels will now be on the bottom, and non-reference (e.g. treatment) on top.
Changes in version 1.99.18
Added helper functionality to importAllelicCounts, so it will create an appropriate tx2gene table with the necessary a1 and a2 suffices, and it will automatically set txOut=FALSE.
Added a ‘q’ argument to plotInfReps to change the intervals when making point and line plots.
Switched the legend of plotInfReps so that reference levels will now be on the bottom, and non-reference (e.g. treatment) on top.
Added loadFry() to process alevin-fry quantification result. Can process spliced, unspliced and ambiguous counts separately and flexibly.
Changes in version 1.99.15().
Changes in version 1.9.6
Specifying ties.method in matrixStats::rowRanks.
Changes in version 1.9.1
Added importAllelicCounts() with options for importing Salmon quantification on diploid transcriptomes.
Changes in version 0.99.0 (2021-04-15)
Changes in version 2.1.24
Added UpdateMetaclusters function, removed RelabelMetaclusters, ReassignMetaclusters and Reordermetaclusters functions.
Updated CheatSheet
Added code from UpdateDerivedValues for metaclustersMFIs to UpdateFlowSOM
Changes in version 2.1.23
Added checkNames = FALSE in MetaclusterMFIs
Changes in version 2.1.22
Reordered code in UpdateDerivedValues, RelabelMetaclusters, ReorderMetaclusters and ReassignMetaclusters.
Changes in version 2.1.21
Added ReorderMetaclusters, to reorder the metacluster levels.
Changes in version 2.1.20
Updated PlotManualBars, Plot2DScatters and FlowSOMmary so that it works with relabeled metaclusters.
Changes in version 2.1.19
AggregateFlowFrames accepts channels and markers
AggregateFlowFrames now gives a warning when files do not contain the same number of channels
AggregateFlowFrames now gives warnings when files do not contain the same markers
Bugfix in AggregateFlowFrames now works when one channel is given
Bugfix in PlotFileScatters now works when one channel is given
Added silent parameter in PlotFileScatters to stop messages
PlotFileScatters supports channels and markers now
Add info to FlowSOM object: date when flowSOM object is made, FlowSOM verion and arguments given to FlowSOM call
Fixed bug in PlotManualBars
Added silent parameter in NewData. GetFeatures’ silent parameter now also surpresses message from NewData (more concrete: ReadInput)
Changes in version 2.1.17
Added ReassignMetaclusters, to rename or split metaclusters
Fixed issue where a lot of warnings were printed in FlowSOMmary
PlotFilescatters now makes filenames unique if they are not and the function now works with output of AggregateFlowFrames 1.1.9
fobitools 1.0.0
Changes in version 2.0.0
MAJOR UPDATE Adding the Following Functionality:
Format, Library, and Testing Improvements
o Enable processing of libraries with 1:many reagent:target assignments
o Standardization and clarification of Annotation objects and symbol/identifier relationships
o Implementation of factored quantile normalization for timecourse screens
o Introduction of the simpleResult format and integration with associated functions
o Conditional testing framework for quantifying and visualizing signal agreement between contrasts
Transition to gene set enrichment testing via Sparrow
o Implement wrappers and provide recommendations fopr geneset enrichment testing in pooled screens
o Implementation of GREAT-style pathway mapping for libraries with heterogenous target:gene mappings
o Summarization tools for comparing enrichment signals across screens
New Visualization and Interpretation Tools
o Signal Summary Barchart (Single or Multiple Contrasts)
o Waterfall reagent/target/pathway visualization (Single Contrast)
o Contrast comparison plots:
Concordance at the Top (CAT)
Probability Space scatter plots
UpSet plots with conditional overlap framework
Changes in version 2.23.9
Subset covariance matrix to specified samples when sample.id argument is passed to fitNullModel when called with an AnnotatedDataFrame
Changes in version 2.23.8
Added option for recessive and dominant coding to assocTestSingle.
Changes in version 2.23.7
Implement MatrixGenotypeReader method for pcair by writing a temporary GDS file.
Changes in version 2.23.5
assocTestSingle, assocTestAggregate, admixMap, and pcrelate use the BiocParallel package for parallel execution on blocks of variants.
Changes in version 2.23.4
For assocTestAggregate, the total number of genotypes in a single iterator element (NxM where N=number of samples and M=number of variants) may be >2^31.
Changes in version 1.6.0
New features
Other notes
Changes in version 1.30.0
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
UCSC hg38 genome is now based on GRCh38.p13 instead of GRCh38.p12
UCSC mm10 genome is now based on GRCm38.p6 instead of GRCm38
seqlevelsStyle() setter now issues a warning when some seqlevels cannot be switched.
Changes in version 1.30.0
Changes in version 1.46.0
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.46.0
Changes in version 1.2.0
nargument of
annotatePCwas hard-coded. Now it can return different number of enriched pathways.
absargument of
annotatePCwas fixed.
plotAnnotatedPCAfunction.
drawWordcloudhas a new argument
droplist.
plotAnnotatedPCAis changed from
PCsto
PCnum.
studyTitlefor
findStudiesInClusterfunction.
Changes in version 0.99.5
Revisions
fix platform build/check errors
Changes in version 0.99.4
Revisions
address reviewer’s comments
Changes in version 0.99.3
Revisions
remove seed
Changes in version 0.99.2
Revisions
change the maintainer
Changes in version 0.99.1
Revisions
modify the vignette for Bioc submission
Changes in version 0.99.0
NEW FEATURES
Changes in version 2021-09-22
0.99.5 make the consensus_views compatible ggtreeExtra and add package description. (2021-10-21, Thu)
Changes in version 0.0.10
update default color schemes in lower part of the SeqDiff plot (2021-08-20, Fri)
Changes in version 0.0.9
import R4RNA to fix R check (2021-08-03, Tue)
Changes in version 0.0.8
The migration of sequence recombination functionality from seqcombo package. (2021-07-20, Tue)
Changes in version 0.0.7
added ggSeqBundle() to plot Sequence Bundles for MSAs based ggolot2 (2021-03-18, Thu)
Changes in version 0.0.6
supports customize colors custom_color. (2020-12-28, Mon)
Changes in version 0.0.5
added new colors LETTER and CN6 provided by ShixiangWang.issues#8
Changes in version 0.0.4
added a Monospaced Font DroidSansMono (2020-3-23, Mon)
Changes in version 0.0.3
used a proportional scaling algorithm (2020-01-08, Wed)
Changes in version 0.0.2
tidy_msa for converting msa file/object to tidy data frame (2019-12-09, Mon)
Changes in version 0.0.1
Changes in version 0.99.0 (2021-08-08)
Changes in version 3.1.6
work with negative edge lengths (hclust may generate negative tree heights) (2021-09-29, Wed; @xiangpin, #441, #445)
Changes in version 3.1.5
bug fixed of nudge_x parameter in geom_segment2 (2021-09-03, Fri; @xiangpin, #433)
Changes in version 3.1.4
allow using options(layout.radial.linetype) to set linetype of radial layout (either ‘strainght’ or ‘curved’) (2021-08-13, Fri; @xiangpin, #427)
Changes in version 3.1.3
geom_tiplab supports fontface aesthetic (2021-07-06, Tue; @xiangpin)
Changes in version 3.1.2
geom_range supports aes mapping (2021-06-04, Fri)
Changes in version 3.1.1
Changes in version 1.3.6
fix the issue of gridlines when some data is removed. (2021-08-25, Wed)
Changes in version 1.3.5
update citation of ggtreeExtra (2021-08-25, Wed).
Changes in version 1.3.4
The ggplot2 (>=3.3.4) introduced computed_mapping.
Changes in version 1.3.3
c(TRUE, TRUE) && c(TRUE, TRUE) is not allowed in devel environment of bioconductor
Changes in version 1.3.1
Changes in version 1.3.0
Changes in version 1.5
Choose a more reasonable scale for global overdispersion estimate
Make code more robust accidental internal NA’s
Add fallback mechanism in case the Fisher scoring fails to converge. Instead of returing NA, try again using the BFGS algorithm.
Better error message if the design contains NA’s
Changes in version 1.13.1
USER-LEVEL CHANGES
Changes in version 2.19.1
TCSS method (@qibaiqi, #35; 2021-08-02, Mon)
GOSemSim 2.18.0
Bioconductor 3.13 release
Changes in version 1.8.0
Improved parallelization implementation for a faster analysis performance.
resolved knitr error June 2021
Changes in version 1.56
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.50
BUG FIXES
Changes in version 1.22.0
Changes in version 1.27.1 (2021-07-28)
Updated CITATION FILE.
Added rmarkdown to Suggests.
Changes in version 1.1.3 (2021-07-06)
Modify the plotting functions.
Changes in version 1.1.2 (2021-06-14)
Add APIs for Seurat pipeline and igraph pipeline.
Changes in version 1.1.1 (2021-05-27)
Modify the package manual.
Changes in version 1.1.0 (2021-05-20)
The development version 1.1.0 is available in Bioconductor.
Changes in version 1.27.1
Changes in version 1.30.0
Changes in version 1.7.6 (2020-10-13)
Trigger bioc build
Changes in version 1.7.5 (2020-10-08)
Update R version dependency from 3.6 to 4.1
Changes in version 1.7.4 (2020-10-08)
Fix a typo
Add citation file
Changes in version 1.7.3 (2020-10-07)
Prepare for release
Changes in version 1.7.2 (2020-10-07)
Fix warnings in unit tests
Changes in version 1.7.1 (2020-10-07)
Update the man files
Changes in version 1.29.1
Changes in version 1.35
Changes in version 1.35.1
Changes in version 1.35.0
Changes in version 1.2.1
Caught an error where not having
Not detected column breaks the
function
Included ‘rmarkdown’ package in Suggests
Changes in version 0.99.17 (2021-09-16)
Changed the get_positivePPI() function
Changes in version 0.99.16 (2021-09-15)
Changes in version 1.9.1
msigdb_download() filters by distinct gene symbols within genesets (relevant to msigdb >=7.4.1)
Changes in version 1.9.0
Version bump for bioconductor
Changes in version 1.18.0
Bug fixes
Other notes
Changes in version 1.7.24 (2021-10-14)
Changes in version 0.99.9 (2021-10-22)
Removed certain unit tests for 64-bit windows
Changes in version 0.99.8 (2021-10-11)
Added patch detection method
Changes in version 0.99.7 (2021-10-10)
Added all unit tests
Fixed read_steinbock x/y axis defaults
Changes in version 0.99.0 (2021-09-14)
Bioconductor submission
Changes in version 0.3.12 (2021-09-01)
clean up for Bioconductor submission
Changes in version 0.3.11 (2021-08-19)
Added flip_x, flip_y argument for plotSpatial function
readSCEfromTXT does not require spot names anymore
knn graph construction can be pruned by distance
added
Changes in version 0.3.10 (2021-08-18)
Added countInteractions function
Added testInteractions function
Changes in version 0.3.9 (2021-07-29)
Added buildSpatialGraph function
Added plotSpatial function
Added aggregateNeighbors function
Changes in version 0.3.8 (2021-06-30)
Adjusted default parameters for read_steinbock function
Added updated test data
Changes in version 0.3.7 (2021-06-14)
added read_cpout function, docs and tests
Changes in version 0.3.6 (2021-06-04)
added read_steinbock function, docs and tests
Changes in version 0.3.5 (2021-05-20)
unit tests and docs for filterPixels
Changes in version 0.3.4 (2021-05-18)
added readImagefromTXT function and tests
Changes in version 0.3.3 (2021-05-17)
unit tests for binAcrossPixels
Changes in version 0.3.2 (2021-05-16)
adjusted plotSpotHeatmap function and unit test
Changes in version 0.3.1 (2021-05-15)
readSCEfromTXT accepts list and path
Changes in version 0.3.0 (2021-05-07)
Added helper functions for spillover correction
Removed redundant functions
Changes in version 0.2.0 (2019-11-28)
The functions calculateSummary, plotCellCounts, and plotDist have been added
Changes in version 0.1.0 (2019-09-17)
initial commit
Changes in version 1.25.2
bugfix immunoMeta contructor from single immunoClust-object
Changes in version 1.25.1
Changes in version 1.1.1 (2021-08-09)
Changes in version 1.8.1 (2020-08-16)
Fix name generation error for step 15.
Handle annotation names as strings even if they look like numbers.
Changes in version 1.1.4
For the three div blocks of heatmap widgets, now
display:table-cell
is used so that
the positions of divs won’t change when changing the size of the
browser window.
Add a new vignette “Share interactive heatmaps to collaborators”.
Changes in version 1.1.3
fontawesome is directly from the fontawesome package.
also inherit row_names_gp and column_names_gp from the complete heatmap
content of js and css for specific heatmap is directly add to html instead of containing as files
Changes in version 1.1.2
Add
save argument in
htShiny().
Changes in version 1.1.1
add new argument
sub_heatmap_cell_fun and
sub_heatmap_layer_fun
to only set cell_fun
or layer_fun for sub-heatmaps.
Changes in version 2.0.0 (2021-10-20)
Changes in version 0.99
NEW FEATURES
Initial review.
Changes in version 0.99.0
Revise required files and format the code style.
Changes in version 2.28.0
SIGNIFICANT USER-VISIBLE CHANGES
DEPRECATED AND DEFUNCT
Changes in version 1.3.9 (2021-10-25)
FIXES
Fixed issues with function that make use of BiocParallel that sometimes failed on Windows platform
Changes in version 1.3.7 (2021-10-20)
NEW
FIXES
Fixed minor issues in data files refGenes_mm9 and function compute_near_integrations()
Changes in version 1.3.6 (2021-10-05)
NEW
FIXES
Fixed small issue in printing information in reports
Changes in version 1.3.5 (2021-09-21)
MAJOR CHANGES
NEW
New function for plotting sharing as venn/euler diagrams sharing_venn()
Changes in version 1.3.4
FIXES/MINOR UPDATES
Slightly modified included data set for better examples
Changes in version 1.3.3 (2021-07-30)
MAJOR CHANGES
MINOR CHANGES
NEW FUNCTIONALITY
FIXES
DEPRECATIONS
OTHER
Reworked documentation
Changes in version 1.3.2 (2021-06-28)
FIXES
Corrected issues in man pages
Changes in version 1.3.1 (2021-06-24)
NEW FUNCTIONALITY
MINOR UPDATES
Changes in version 2.5.3
Replace icons with fontawesome 5 versions
Changes in version 2.5.2
Bugfix for heatmap crashing if columns were ordered by a selection that was not shown
Changes in version 2.5.1
Changes in version 1.5.2
Fix bug in retrieving a feature set
Changes in version 1.5.1
Changes in version 1.15.02 (2021-09-14)
Update type: minor.
Various error message updates
Changes in version 1.15.1
FIX
rmarkdown dependcies
fix bug that will create difference with older versions (#19)
Changes in version 1.27.2
fix in evaluatePrediction() (avoid length>1 logical condition)
Changes in version 1.27.1
fix to avoid warnings arising from compiled code
fix in kebabsDemo() to avoid build warnings; executing this function now does not have any side effects anymore (previously, data objects were loaded into the global workspace)
Changes in version 1.27.0
new branch for Bioconductor 3.14 devel
Changes in version 3.50.0
Improve help pages for fry() and barcodeplot().
Revise Section 18.1.10 of User’s Guide so that coloring of X and Y genes is consistent between plots.
Fix bug in the MDS class method of plotMDS() (introduced in the
previous release) when new
dim.plot values are set.
Fix bug in read.idat() when
annotation contains NA values.
Changes in version 1.19.2
Eliminated some duplication resulting from relict “trimmed_databases” directory
Changes in version 1.18.1
Updated authors and maintainers
Formalized support for new lipid classes including bile salts, wax esters, quinones, etc.
Changes in version 1.10.1
NEW FEATURES
BUG FIXES
Changes in version 2.4.0
LRBase.XXX.eg.db-type annotation packages for organisms were deprecated.
The distribution of each SQLite file has been changed to the AnnotationHub-style.
By using LRBaseDbi, we can convert SQLite files acquired by the AnnotationHub’s query function into LRBase objects, which can then be used for analysis using LRBase.XXX.eg.db as before.
makeLRBasePackage function was deprecated.
.loadLRBaseDbiPkg was deprecated.
Changes in version 0.99.0 (2021-05-27)
Changes in version 1.7.1
Update tutorial data files
Update knitr dependency for bioconductor tests
Changes in version 3.14
NEW FUNCTIONS
BUG FIXES
ENHANCEMENTS
Changes in version 3.13
added feature-label output on May 10, 2021
Changes in version 3.12
added feature-label output on April 27, 2021
added cutoff value on March 06, 2021
Changes in version 1.5.4
Sync API with matrixStats v0.60.1.
Changes in version 1.5.2
Sync API with matrixStats v0.60.0.
Changes in version 1.5.1
Fix problem with function environment of fallback mechanism (<URL:> and <URL:>). Make sure that packages can use MatrixGenerics with the :: notation to call functions from sparseMatrixStats and DelayedMatrixStats.
Changes in version 1.1.2 (2021-09-06)
take sample IDs for shinyQC from colnames(se)
take feature IDs for shinyQC from rownames(se)
fix error in report.Rmd (change input for create_boxplot to se)
Changes in version 1.1.1 (2021-08-27)
fix bug in biocrates and maxQuant function
Changes in version 1.19.1 (2021-10-20)
BUG FIXES
Changes in version 1.3.3
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.1.3
fixed a bug in runTomTom where setting norc = TRUE failed on data import
Changes in version 1.1.1
runFimo now returns NULL and prints a message when text = FALSE and FIMO detects no matches instead of throwing a cryptic error message
Changes in version 1.30.0
MeSH-related packages (MeSH.XXX.eg.db, MeSH.db, MeSH.AOR.db, and MeSH.PCR.db) were deprecated.
The distribution of each SQLite file has been changed to the AnnotationHub-style.
By using MeSHDbi, we can convert SQLite files acquired by the AnnotationHub’s query function into MeSH objects, which can then be used for analysis using MeSH-related packages as before.
makeGeneMeSHPackage was deprecated.
.loadMeSHDbiPkg was deprecated.
Changes in version 1.19.3
cache mesh db and table (2021-09-01, Wed)
Changes in version 1.19.2
import yulab.utils (2021-8-19, Thu)
Changes in version 1.19.1
remove MeSH.db package and use AnnotationHub to get MeSHDb databases (2021-8-13, Fri)
Changes in version 2.0.0
Specification changed as “AnnotationHub-style”
Dependencies of MeSH.db, MeSH.AOR.db, MeSH.PCR.db, MeSH.Hsa.eg.db, MeSH.Aca.eg.db, MeSH.Bsu.168.eg.db, MeSH.Syn.eg.db were removed
Vignette changed for the specification change
All datasets removed
Changes in version 1.3.2
Changes to labelRows
new resolveConflicts + rtOrder argument added for automated resolution of conflicting feature pair alignment fows in combinedTable, with embedded C function (resolveRows.c)
new argument rtOrder paired with resolveConflicts determines if RT order consistency is expected when resolving alignment conflicts
duplicate column names for {labels, subgroup, alt} removed and no longer allowed in resulting combinedTable
Changes to metabCombiner
new check for metabCombiner object inputs: labelRows must be called before aligning a metabCombiner object with a new dataset
resolveConflicts method applied to metabCombiner object to eliminate conflicting alignments/ attain 1-1 matches for all features
new rtOrder argument controlling resolveConflicts similar to above
Changes in version 1.3.1
Changes to fit_gam()/ fit_loess
Changes to metabCombiner() & combinedTable / featdata slots
Changes to calcScores() / evaluateParams() / labelRows
Changes to write2file
Changes in version 1.1
MetaboCoreUtils 1.1.1
Changes in version 1.5.1 (2021-06-14)
NEW FEATURES
BUG FIXES
Fix in annotation backwards compatibility.
Fix bigGenePred gene annotation track generation.
Changes in version 0.99.27
Changes in version 1.11.5 (2021-10-12)
add assays in structural based on columns in transformations that are defined by the var argument in structural, adjacency matrices of type will be stored in the AdjacencyMatrix object defined in the columns of transformation
implement structural that it can also calculate mass differences of 0 for undirected networks
Changes in version 1.11.4 (2021-09-09)
shift calculation of as.data.frame(am) in mz_summary
several fixes of typos in the comments and vignette
fix rtCorrection function
Changes in version 1.11.3 (2021-08-30)
change calculation of mass differences, use the differences between (M_2+ppm)-(M_1-ppm) and (M_2-ppm)-(M_1+ppm) instead of (M_1-ppm)-(M_1) and (M_2+ppm)-(M_1) for querying against the list of transformations
Changes in version 1.11.2 (2021-08-30)
change error message in test_combine
Changes in version 1.1 (2021-06-04)
split transformCounts into transformSamples and transformFeatures
added log_modulo_skewness as a diversity index
added functions for summarizing dominant taxa information
added wrapper for adding dominant taxa information to colData
added specialized subsetting function for subsetting by prevalence (subsetByPrevalentTaxa/subsetByRareTaxa)
added mapTaxonomy
added estimateDivergence
bugfix: makePhyloseqFromTreeSummarizedExperiment checks now for rowTree be compatible
bugfix: meltAssay supports Matrix types
bugfix: meltAssay is able to include rowData also when there are duplicated rownames
added subsampleCounts for Subsampling/Rarefying data
Changes in version 0.99.0 (2021-09-29)
Three simulation models and three functions are added
Submitted to Bioconductor
Changes in version 1.1
Changes in version 2.1.2 (2020-07-01)
Core heatmap labeling improved
aggregate_top_taxa deprecated
bimodality and potential_analysis functions fixed
Changes in version 2.1.1 (2020-04-06)
Added overlap function
Changes in version 1.14.1 (2021-09-29)
Removed categorical method from associate function
Changes in version 0.99.0 (2021-09-01)
Changes in version 0.99.0
Changes in version 1.5.9
update mp_plot_ord to suppress the message of the third depend package. (2021-10-08, Fri)
Changes in version 1.5.8
add mp_aggregate function. (2021-09-26, Sun)
Changes in version 1.5.7
update the mp_plot_ord. (2021-09-13, Mon)
Changes in version 1.5.6
introduce include.lowest parameter in mp_filter_taxa. (2021-09-07, Tue)
Changes in version 1.5.5
fix the issue when the rowname or colnames of SummarizedExperiment is NULL for as.MPSE. (2021-08-26, Thu)
Changes in version 1.5.4
add mp_stat_taxa to count the number and total number taxa for each sample at different taxonomy levels (Kingdom, Phylum, Class, Order, Family, Genus, Species, OTU). (2021-08-03, Tue)
Changes in version 1.5.3
optimize the print for MPSE. (2021-07-22, Thu)
Changes in version 1.5.2
add mp_mantel and mp_mrpp for MPSE or tbl_mpse object. (2021-07-19, Mon)
add mp_envfit and update mp_cal_dist to support the distance calculation with continuous environment factors and rename mp_cal_adonis to mp_adonis, mp_cal_anosim to mp_anosim. (2021-07-17, Sat)
add mp_cal_rda, mp_cal_cca, mp_cal_adonis and mp_cal_anosim for MPSE or tbl_mpse object. (2021-07-16, Fri)
add mp_cal_dca, mp_cal_nmds and mp_extract_internal_attr. (2021-07-15, Thu)
add mp_cal_pca, mp_cal_pcoa and mp_extract_abundance. (2021-07-14, Wed)
add mp_cal_clust to perform the hierarchical cluster analysis of samples and mp_extract_dist to extract the dist object from MPSE object or tbl_mpse object. (2021-07-13, Thu)
add mp_cal_dist to calculate the distance between samples with MPSE or tbl_mpse object. (2021-07-12, Mon)
add mp_extract_sample, mp_extract_taxonomy, mp_extract_feature to extract the sample, taxonomy and feature (OTU) information and return tbl_df or data.frame. (2021-07-09, Fri)
add mp_cal_venn to build the input for venn plot (2021-07-09, Fri)
mp_cal_rarecurve add action argument to control whether the result will be added to MPSE and tbl_mpse or return directly. (2021-07-08, Thu)
add mp_cal_upset to get the input of ggupset. (2021-07-08, Thu)
add mp_extract_tree to extract the otutree or taxatree from MPSE or tbl_mpse object. (2021-07-07, Wed)
add pull and slice to support the MPSE object. (2021-07-06, Tue)
add mp_cal_rarecurve to calculate the rarecurve of each sample with MPSE or tbl_mpse. (2021-07-06, Tue)
add mp_cal_abundance to calculate the relative abundance of each taxonomy class with MPSE or tbl_mpse. (2021-07-05, Mon)
add mp_decostand provided several standardization methods for MPSE, tbl_mpse and grouped_df_mpse. (2021-07-04, Sun)
add mp_import_qiime to parse the output of qiime old version. (2021-07-03, Sat)
add taxatree slot to MPSE. (2021-06-30, Wed)
add mp_cal_alpha function for MPSE or mpse object. (2021-07-01, Thu)
add rownames<- to support renaming the names of feature. (2021-07-01, Thu)
add mp_import_qiime2 and mp_import_dada2 to parse the output of dada2 or qiime2 and return MPSE object. (2021-07-02, Fri)
update print information for MPSE, tbl_mpse and grouped_df_mpse. (2021-06-29, Tue)
add [ to the accessors of MPSE. (2021-06-29, Tue)
use MPSE object. (2021-06-28, Mon)
Formatted output.
update as.MPSE and as.treedata for grouped_df_mpse object.
(2021-06-29, Tue) - This feature is useful to explore the
microbiome data in taxa tree. This feature has been replaced by
the taxatree slot
Changes in version 1.5.1
Changes in version 1.1.0
Bioconductor release!
Changes in version 1.0.13
adds new HLA-KIR interaction A03_A11_KIR3DL2 defined as (A03 | A11) & KIR3DL2.
Changes in version 1.0.12
fixes bug causing MiDAS subsetting to break omnibus testing.
Changes in version 1.0.11
runMiDAS inheritance_model argument is no longer by defaut ‘additive’. Now it is required to specify desired inheritance model, when appplicable.
Changes in version 1.0.10
fix bug causing Bw6 groups to be counted twice in hla_NK_lingads experiment.
Changes in version 1.0.9
fix bug causing runMiDAS errors when statistical model evaluated with a warrning.
Changes in version 1.0.8
fixed bug causing filterByVariables and filterByFrequency to strip omnibus groups from target experiment.
Changes in version 1.0.7
fixed bug causing HWETest filtration to strip omnibus groups from target experiment
Changes in version 1.0.6
removed unused expression dictionaries
Changes in version 1.0.4
In frequency calculations the “NA”s were counted as non-carriers, this has been changed such that “NA” samples are now omitted.
Changes in version 1.0.3
warnings and errors occuring upon model evaluation are now summarized into more readable form
Changes in version 1.0.2
fixed problem vignettes index entry values, preventing vignettes from being build
Changes in version 1.0.1
Changes in version 1.1.0 (2021-10-12)
Changes in version 1.39
v1.39.1 Initial support for the Allergy and Asthma array.
v1.39.2 More support for the Allergy and Asthma array.
v1.39.3 Bug fix that prevented R CMD build from working.
Changes in version 1.1.5 (2021-08-24)
Updated citation
Changes in version 1.1.3 (2021-05-27)
Added new option for model_type, one_dimensional
Added new filtering parameters, keep_all_below_boundary and enforce_left_cutoff
Added demonstrations of new models and parameters to vignette
Changes in version 1.1.3 (2021-08-22)
Changes made in the vignette
Changes in version 1.1.2 (2021-08-22)
Link example data on zenodo in vignette
Changes in version 1.1.1 (2021-06-03)
Addition to miRanda Files
Changes in version 1.2.0
Release version for Bioconductor 3.14. See changes for 1.1.x.
Changes in version 1.1
IMPORTANT: R2 is now reported in percentages for intra, multi and gain. Collecting results from running mistyR < 1.1.11 will lead to miscalcuation of gain.R2. Update the performance.txt files by multiplying the values in columns intra.R2 and multi.R2 by 100.
Changes in version 1.0.3
Vignette output switched from BiocStyle to rmarkdown for pdfs due to BiocStyle issue.
Changes in version 1.0.2
Avoid calls to os-dependent file.info in tests.
Changes in version 1.0.1
Changes in version 6.18.0
new features / enhancements / changes
bug fixes
Changes in version 0.99.5
Updated R/monaLisa-package.R file
Changes in version 0.99.4
Suppressed warnings from matchPWM (due to presence of Ns) in regression vignette
Changes in version 0.99.3
Updated README.md file
Changes in version 0.99.2
Addressed failing test in calcBinnedKmerEnr
Changes in version 0.99.1
Added legend position and size arguments to plotSelectionProb()
Changes in version 0.99.0
Preparation for Bioconductor submission
Changes in version 0.2.0
Changes in version 1.0.0
Major changes
Changes in version 1.37.5
Change the style of motifPile.
Fix the bug of the ylab grid.
Changes in version 1.37.4
Fix the bug that the rownames were not checked for alignment.
Changes in version 1.37.3
Fix the bug method argument of matAlign is ignored.
Changes in version 1.37.2
Improve importMatrix to read the tags from file.
Changes in version 1.37.1
handle the error “failed to load cairo DLL”
Changes in version 1.1.8
Fixed test that was resulting in error duet to version 1.1.6 updated way to read the files.
Changes in version 1.1.7
Removed parentheses from the news that was causing issues in Bioconductor.
Changes in version 1.1.6
Bug fixed: If a table was missing, the report was not generated.
Changes in version 1.1.5
The plot generated by PlotPTM() will now indicate (in the legend title) whether the Post-Translational modifications have been aggregated or not as a result of the parameter aggregate_PTMs.
The function PlotPeptidesIdentified() and PlotProteinsIdentified() now return a plot containing Missing Values, Frequency of Identified by Match Between Runs and Frequency of identified by MS/MS. With this, the funciton PlotIdentificationType() becomes obsolete.
The function PlotProteinCoverage() now can take as input multiple UniprotID in a vector format.
The function PlotPTMAcrossSamples() now can take as input multiple PTM_of_Interest in a vector format.
Change in the function make_MQCombined() to read faster the tables and reducing the overall time required to generate a report.
Changes in version 1.1.4
The function PlotProteinCoverage() now reports the coverage individually in each plot rather than the total protein coverage.
MQmetrics now is adapted to MaxQuant v.2.x, since the column names are different than in MaxQuant v.1.x. MQmetrics will detect the MaxQuant version used and read the columns accordingly.
Enhanced error message in PlotiRT() and PlotiRTScore() when irt peptides are note found. Enhanced error message for PlotProteinCoverage() when the UniprotID is not found.
Changes in version 1.1.3
In the function PlotPTM() a parameter combine_same_residue_ptms has been added. It combines multiple PTMs happening in the same residue such as: Dimethyl (KR), Trimethyl (KR).
Changes in version 1.1.2
Improved aesthethics in the plots from PlotCombinedDynamicRange() and PlotAllDynamicRange().
Changes in version 1.1.1
Changes in version 1.25.3
further changes to get rid of compiler warnings
Changes in version 1.25.2
removed build/ directory from repo to avoid installation problems
Changes in version 1.25.1
update of gc
minor changes to get rid of compiler warnings
Changes in version 1.25.0
new branch for Bioconductor 3.14 devel
Changes in version 1.1
Changes in 1.1.4
Changes in 1.1.3
Changes in 1.1.2
Changes in 1.1.1
Changes in version 1.1
Changes in 1.1.3
Changes in 1.1.2
Changes in 1.1.1
Changes in version 1.0.0
Changes in version 1.3.0
Users can now specify the rank of the model to fit by msImpute
Added mspip for identification transfer between runs using Maxquant results (Beta phase only)
Added evidenceToMatrix which creates limma compatible objects from MaxQuant evidence table
Changes in version 2.19
Changes in 2.19.2
Changes in 2.19.1
Changes in version 1.19.2
XCMS 3 compatability update (M-R-JONES)
Changes in version 1.19.1
Bug fix for flagRemove (full width was not calculated as expected)
Changes in version 1.1.1
Changes in version 1.2.1
Changes in version 2.2.3 (2021-10-06)
Minor change: fix the bug when df.prior is infinite
Changes in version 2.2.2 (2021-09-21)
Major change: extend groupComparisonTMT() function to cover repeated measures design
Allow flexible order of condition in dataProcessPlotsTMT.
Fix bug in Condition label in dataProcessPlotsTMT.
Improve MSstatsTestSingleProteinTMT() by directly reading lmerTest output. This may make statistics slightly different due to different numeric accuracy
fix bug when condition name contains ‘group’
change the x-axis order in profile plot
Changes in version 2.0.1 (2021-06-14)
update comments of PD converter function
fix bug in proteinSummarization() function when MBimpute = F
Changes in version 1.20.0
Bug fixes and minor improvements 1.1.27
Bug fixes
New Features
read_header and read_sumstats now both work with .bgz files.
Changes in version 1.1.26
New Features
Extra mappings for FRQ column, see data(“sumstatsColHeaders”) for details
Changes in version 1.1.23
New Features
format_sumstats(frq_is_maf) check added to infer if FRQ column values are minor/effect allele frequencies or not. frq_is_maf allows users to rename the FRQ column as MAJOR_ALLELE_FRQ if some values appear to be major allele frequencies
Changes in version 1.1.19
New Features
format_sumstats(convert_ref_genome) now implemented which can perform liftover to GRCh38 from GRCh37 and vice-versa enabling better cohesion between different study’s summary statistics.
Changes in version 1.1.11
Bug fixes
New Features
Input summary statistics with A0/A1 corresponding to ref/alt can now be handled by the mappign file as well as A1/A2 corresponding to ref/alt.
Changes in version 1.1.2
New Features
Bug fixes
check_n_num now accounts for situations where N is a character vector and converts to numeric.
Changes in version 1.1.1
Bug fixes
Changes in version 1.7.2
Changes in version 1.3.1 (2021-10-10)
Updated version number to match Bioconductor
Changes in version 1.2.1 (2021-08-08)
Changes in version 2.27.1
Add missing atomic_count_sync.hpp BH file (see PR #248 by vjcitn)
Changes in version 2.27.0
New Bioc devel version
Changes in version 2.0.0
Changes in version 1.1.2 (2020-09-28)
Update license
Changes in version 1.1.1 (2020-08-13)
Documentation updates
Handle new parameters from ggiraph update
Changes in version 1.1.0 (2020-05-19)
Initial Bioconductor devel 3.14 version
Changes in version 0.99.0
Changes in version 1.3.3
Changes
update description to accommodate changes in knitr/rmarkdown packages
update dummy data files to new format so vignette can run
Changes in version 1.3.1
Changes
include ability to iteratively acquire and visualize Bkg std error
new arguments to choose whether to calculate Bkg std error
accomodate StereoGene version 2.22, esp. seeding of analysis
better run analysis on track files outside local directory
Changes in version 1.5.3
Moved RCy3, scater, clusterExperiment and netSmooth to “Suggests” to reduce dependency burden
Sped up vignettes by limiting all to binary classification and limiting number of layers
Removed TL;DR from vignettes as usefulness in question but maintainance high. Developers notes:
Added Dockerfile and Github Actions for automated testing
GHA auto-generates a Docker image with netDx which gets pushed to shraddhapai/netdx_devenv
Changes in version 1.5.2
Added wrapper functions for ease-of-use. Includes:
getResults() to plot results of running the predictor
getPSN() for creating and visualizing integrated PSN
confusionMatrix() to visualize confusion matrix
tSNEPlotter() to visualize tSNE of integrated PSN (doesn’t require Cytoscape)
Added CITATION file with citations to netDx methods and software paper
Changes in version 1.5.1
Adding support for Java 16.
Disabling CNV-based vignette to allow other three vignettes to run without causing build timeout on devel system
Changes in version 1.53.2 (2021-07-28)
Changes in version 1.9.3
Bug fixes for importing macs2 logs
Changes in version 1.9.2
Bug fixes for later versions of ggplot2
Changes in version 1.8.1
Bug fix in .makeSidebar
Changes in version 1.18.2
Changed deprecated ‘GenomeInfoDb::fetchExtendedChromInfoFromUCSC’ to ‘GenomeInfoDb::getChromInfoFromUCSC’ in R/methods.R
Changes in version 1.18.1
Fixing R 4.1.0 _R_CHECK_LENGTH_1_LOGIC2 error in tests/testthat/utils.R:applyMap by using inherits() instead of class() to account for hadleyverse
Changes in version 1.0.0
Changes in version 0.99.12 (2021-10-26)
Fixed bug in MakeSE() and CoordToGR()
Changes in version 0.99.10 (2021-10-20)
Accounts for when NxtIRFdata cannot fetch data from ExperimentHub
Changes in version 0.99.9 (2021-10-20)
Added GetCoverageBins()
Add warning in IRFinder if coordinate sorted BAM file takes too long to run.
Fixed missing coverage data at both ends of plot track.
Changes in version 0.99.8 (2021-10-13)
Fixed memory leak when writing COV files
Changes in version 0.99.6 (2021-10-12)
Added GetCoverageRegions() which calculates the mean coverage of each region in a given GRanges object
Added BAM2COV() which calculates and creates COV files from BAM files
Changes in version 0.99.2 (2021-10-07)
Fixed bug in Find_FASTQ
Changes in version 0.99.0 (2021-09-29)
Bioconductor Release
Changes in version 0.99.0
NEW FEATURES
Changes in version 3.2.0
Changes in version 3.1.2 (2021-10-06)
Better test of poset transformation
Changes in version 3.1.1 (2021-10-06)
XOR, AND, OR dependencies: plots of DAGs honor all possible values.
Few miscell minor changes.
Changes in version 3.11
Enhancements
Bug Fixes
Added a fix to the density estimate used by gate_tautstring
Changes in version 3.10
API Changes
Simple renaming
Classes and methods no longer exported
Bug Fixes
Changes in version 2.11.1
Changes in version 1.13.7
SIGNIFICANT USER-VISIBLE CHANGES
Massive improvement in speed of coveragePerTiling
Improved p-shifting analysis (also added verbose output)
Added possible optimization for annotation
Rewritten vignettes
Changes in version 0.99.9
New Features
Fixes
Adjusted vignette yamls to make resulting htmls smaller.
Changes in version 0.99.8
New Features
create_background now uses all_genes when all 3 species are the same.
Changes in version 0.99.7
New Features
Fixes
report_orthologs no longer throws error due to not finding tar_genes.
Changes in version 0.99.6
Fixes
Allow all messages to be suppressed in report_orthologs.
Changes in version 0.99.3
New Features
New method “babelgene” added to convert_orthologs.
Changes in version 0.99.2
Fixes
GenomeInfoDbData now required.
Changes in version 0.1.0
New Features
Changes in version 1.3 (2021-10-14)
Changes in version 0.99.0 (2021-09-21)
Changes in version 2.20.0
Other notes
Changes in version 2.6.0
Changes in version 1.7.1 (2021-06-21)
Error due to change in behavior for default axis label in ggplot2 histogram
GGplot2 ‘guide’ depreciation warning
Changes in version 0.1.0
Changes in version 2.5.3
The original constructor and all accessors remain in the package for full backwards compatibility
Changes in version 2.5.2
Fix: remove ‘fdr’ item from geneDrugSensitivity return vector
Changes in version 2.5.1
Fix: reverted GDSCsmall.rda and CCLEsmall.rda to original data format; they were accidentally pushed with MultiAssayExperiments in @molecularProfiles
Changes in version 2.5.0
Changes in version 1.19.1
USER-VISIBLE CHANGES
Added support for TreeSummarizedExperiment class
Added support for phyloseq class
Updated vignette
Changed main argument name from df to x
INTERNAL
Changes in version 1.1.1 (2021-08-05)
Changes in version 1.2.1
Changes in version 1.7.8
only mainInput is required in config file
Changes in version 1.7.7
use config file for input files, refspec selection and othes settings
Changes in version 1.6.6
turn off auto sizing for large number of taxa or genes (>= 10.000)
Changes in version 1.6.5
fixed filter for “species relation”
added midpoint colors
Changes in version 1.6.2
increase default font size for profile and domain plot
make links to DBs: ncbi taxonomy, ncbi protein, uniprot, pfam, smart
Changes in version 1.6.1
modified taxonomy ranks (ropensci#875)
improved rank indexing function (ropensci#874)
improved x-axis label (#116)
Changes in version 1.19.50 (2021-10-14)
New functions
Neda added the identify.modules(), make.filter(), and apply.filter() functions, but not exported them yet.
Changes in version 1.19.30 (2021-09-08)
Bug Fixes
The averaged.network() function does not have the nodes argument in bnlearn Version >=4.7, and thus this argument was removed.
Changes in version 1.19.24 (2021-08-06)
New functions
Bug Fixes
A bug fix in the gene.mapping() function that used to occur when we had multiple output databases.
Changes in version 1.19.10 (2021-06-25)
Changes in existing functions
The message.if() function can now write the message in a text file.
Changes in version 1.19.8 (2021-05-25)
Bug Fixes
Changes in version 1.65.1
new feature:
–allow parameter
Prefix' in run.plgem’ to be passed down to
plgem.fit' when writeFiles=TRUE’
bug fix:
–only check existence of
fittingEvalFileName' when both
fittingEval’ and
plot.file' are TRUE in plgem.fit’
new feature:
–added parameter
Prefix' to run.plgem’ to be passed down to
plgem.write.summary' when writeFiles=TRUE’
bug fix:
–fixed error occurring when running
run.plgem' with plotFile=TRUE’
Changes in version 0.99.11
BUG FIXES
o
: added back to readHic for
strawr region parsing.
o
plotHicSquare subsetting fixed for off diagonal regions.
NEW FEATURES
o All Hi-C functions now allow input of remote Hi-C files.
Changes in version 0.99.9
This package was previously called BentoBox.
Changes in version 0.99.0
NEW FEATURES
o Version bump to 0.99.0 for Bioconductor package submission.
o
bb_mapColors function for users to map a vector to a palette
of colors.
o
linecolor parameter in
bb_plotPairs,
bb_plotPairsArches,
and
bb_plotRanges now accepts a single value, a vector of colors,
a
colorby object, or the value “fill”.
Changes in version 0.0.0.14
BUG FIXES
o R version requirement changed to (R >= 4.1.0) for proper plot placement.
NEW FEATURES
o
colorby object now has a
scalePerRegion parameter to scale
numerical
colorby data to the range of data in a plotted genomic region.
Changes in version 0.0.0.13
SIGNIFICANT USER-VISIBLE CHANGES
o
bb_plotManhattan
fill paramete now accepts a single value,
a vector of colors, or a
colorby object.
Changes in version 0.0.0.12
SIGNIFICANT USER-VISIBLE CHANGES
o
colorby constructor now includes optional palette specification.
o
bb_plotPairs,
bb_plotPairsArches, and
bb_plotRanges
fill
parameter
now accepts a single value, a vector of colors, or a
colorby
object.
BUG FIXES
o
GInteractions assembly match checking moved before dataframe
conversion.
Changes in version 0.0.0.11
SIGNIFICANT USER-VISIBLE CHANGES
o Data moved to
plotgardenerData package.
o Default genome assembly updated to “hg38”.
BUG FIXES
o Streamlined parameter parsing and data reading logic.
Changes in version 0.0.0.10
NEW FEATURES
o Added unit tests with
testthat.
o
bb_annoDomains function addition.
o
bb_plotSignal vertical orientation.
Changes in version 0.0.0.9
NEW FEATURES
o Added a
NEWS file to track changes to the package.
BUG FIXES
o Updated viewport parsing for package
grid version 4.1.0.
Changes in version 1.1.1 (2021-06-09)
Changes in version 1.25.1
adjusted NAMESPACE to account for changes in BiocGenerics package
Changes in version 1.25.0
new branch for Bioconductor 3.3.3 (2021-09-28)
The default for MinPts DBSCAN parameter has been changed to 100
Changes in version 1.3.2 (2021-09-21)
Vignette edits
Changes in version 1.3.1 (2021-07-19)
Change y of x.y.z version number to comply with the release
Add MD as a maintainer
Changes in version 1.3.3
plotPromoters is deprecated
Implemented three new functions
Changes in version 2.21.1 1.33
Changes in version 1.0
Changes in version 1.25.1
add bin, compareChromatograms and compareSpectra
Changes in version 1.25.0
Bioc devel (3.14) version bump
Changes in version 1.20.0
Improve species and genome selection
Changes in version 1.18.6
ShinyProxy support
Bug fixes
Orange region (the reference exon) is now on top of blue region
Changes in version 1.18.5
Fix loading twice when selecting a new event (visual interface)
Changes in version 1.18.4
Remove warning related with TCGA data when MD5 checks fail
Changes in version 1.18.3
Fix Bioconductor build report’s timeout when creating vignettes on Windows
Changes in version 1.18.2
Fix issues with unit tests in Bioconductor
Changes in version 1.18.1
Changes in version 1.1.4 (2021-09-23)
removal of the loaded prtset data to avoid any local path problems
Changes in version 1.1.1 (2021-09-13)
Added graphical interface
Changes in version 2.0.0
NEW FEATURES
Report median absolute pairwise difference (MAPD) of tumor vs normal log2 ratios in runAbsoluteCN
Improved mapping bias estimates: variants with insufficient information for position-specific fits (default 3-6 heterozygous variants) are clustered and assigned to the most similar fit
Make Cosmic.CNT INFO field name customizable
SIGNIFICANT USER-VISIBLE CHANGES
Cleanup of naming of command line arguments (will throw lots of deprecated warnings, but was long overdue)
More robust alignment of on- and off-target tumor vs normal log2 ratios. Ratios are shifted so that median difference of neighboring on/off-target pairs is 0. This should fix spurious segments consisting of only on- or off-target regions in high quality samples where those minor off-sets sometimes exceeded the noise.
Added min.variants argument to runAbsoluteCN
Added PureCN version to runAbsoluteCN results object (ret$version)
Added pairwise sample distances to normalDB output object helpful for finding noisy samples or batches in normal databases
Do not error out readCurationFile when CSV is missing and directory is not writable when re-generating it (#196)
Add segmentation parameters as attributes to segmentation data.frame
Added min.betafit.rho and max.betafit.rho to calculateMappingBias*
Made –normal_panel in PureCN.R defunct
BUGFIXES
Fix for crash when –normal_panel in NormalDB.R contained no variants (#180).
Fix for crash when rtracklayer failed to parse –infile in FilterCallableLoci.R (#182)
More robust parsing of VCF with missing GT field (#184)
Fix for bug and crash when mapping bias RDS file contains variants with multiple alt alleles (#184)
Added missing dependency ‘markdown’
Fix for crash when only a small number of off-target intervals pass filters (#190)
Fix for crash when PSCBS segmentation was selected without VCF file (#190)
Fix for crash when Hclust segmentation was selected without segmentation file (#190)
Fix for crashes when not many variant pass filters (#192, #195)
Fix for crash when provided segmentation does not have chromosomes in common with VCF (#192) or does not provide all chromosomes present in the coverage file (#192)
Changes in version 1.31
qcmetrics 1.31.1
Changes in version 1.29.6 (2021-10-23)
BUG FIXES
segmentBins() would report the sample names as “NA” in output messages if the sample name contained hyphens, or other symbols automatically replaced by data.frame(…, check.names = TRUE). This was a harmless bug.
Changes in version 1.29.5 (2021-10-20)
PERFORMANCE
MISCELLANEOUS
Moved ‘future’ from Imports to Suggests.
Changes in version 1.29.4 (2021-10-16)
DOCUMENTATION
DEPRECATION AND DEFUNCT
Argument ‘seeds’ of segmentBins() is defunct. It has been deprecated and ignored since QDNAseq 1.21.3 (September 2019).
Changes in version 1.29.3 (2021-10-04)
NEW FEATURES
Now argument ‘logTransform’ of exportBins() is ignored if ‘type’ = “calls”.
Now exportBins() returns the pathname to the files written.
SOFTWARE QUALITY
Test code coverage was increased from 42% to 52%.
Add package test for exportBins().
BUG FIXES
exportBins(fit, format = “seg”, …) and format = “vcf” would merge segments with equal copy-number calls if they were interweaved with copy-neutral segments.
exportBins(fit, format = “seg”, …) and format = “vcf” produced an obscure error with messages “Error in dimnames(x) <- dn : length of ‘dimnames’ 2 not equal to array extent” for samples with no copy-number abberations.
exportBins(fit, format = “seg”, file = …) and format = “vcf” did not respect argument ‘file’ but instead wrote files of its own names to the current working directory.
exportBins() would corrupt option ‘scipen’. Now it is left unchanged.
KNOWN ISSUES
callBins() produces warnings on “Recycling array of length 1 in vector- array arithmetic is deprecated. Use c() or as.vector() instead.” in R (>= 3.4.0). This is a problem in the package ‘CGHcall’ dependency and is something that needs to be fixed there. For further details, please see.
Changes in version 1.29.2 (2021-09-22)
SOFTWARE QUALITY
Test code coverage was increased from 32% to 39%.
Added package tests for binReadCounts().
BUG FIXES
binReadCounts() would fail when specifying argument ‘chunkSize’. The fix was to require ‘future’ package version 1.22.1 or newer.
Changes in version 1.29.1 (2021-08-26)
SOFTWARE QUALITY
Changes in version 1.3.0
QFeatures 1.3.6
QFeatures 1.3.5
QFeatures 1.3.4
QFeatures 1.3.3
QFeatures 1.3.2
QFeatures 1.3.1
QFeatures 1.3.0
Changes in version 1.9.2 (2021-09-01)
Added Hmisc to Imports
Changes in version 1.9.1 (2021-06-24)
Added qsmoothGC function (Contributed from Koen Van den Berge)
Changes in version 1.34.0
USER-VISIBLE CHANGES
removed automatic downloading and installation of BSgenome references
added option to parallelize qExportWig
Changes in version 1.18.0
New features
Bug fixes and minor improvements
Changes in version 1.1.2 (2021-05-28)
reviewers’ suggestions were implemented, docs updated, typos fixed
new methods for simulation of AMR and test data sets
NULL as a default for data.samples (to use all)
doRNG is used to ensure reproducibility during parallel computing
a couple of new defaults for previously required parameters for easy usage
Changes in version 1.1.0 (2021-05-21)
released at bioconductor
Changes in version 1.1 (2021-05-31)
Improved error handling of system2 call in .rawrrSystem2Source by logging stdout and stderr and make them available from the R console.
Added helper function .checkReaderFunctions.
Changes in version 2.14.0
Cleaned up dependencies, dramatically reducing RCy3 package installation time
Changes in version 1.7.5 (2021-09-28)
Fixed documentation of “plot_heatmap”
Changes in version 1.7.4 (2021-09-24)
Added new plotting function “plot_heatmap”
Changes in version 1.7.3 (2021-09-14)
Updated vignette to introduce the “open_reactome” command
Changes in version 1.7.2 (2021-09-09)
Fixed timeout issue during large requests in perform_reactome_analysis
Changes in version 1.7.1 (2021-06-09)
Fixed bug in scRNA-seq vignette.
Changes in version 1.19.2
BUG FIXES
Changes in version 1.3.9
BUG FIXES
Resolved.
Changes in version 1.3.7
NEW FEATURES
Added the create_hub() function for creating UCSC track hub configuration files for using the UCSC Genome Browser to explore the recount3 BigWig base-pair coverage files.
Changes in version 1.3.2
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES
Changes in version 1.3.1
Changes in version 1.5.3 (2021-08-04)
Changes in version 1.12.2
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
DEPRECATED AND DEFUNCT
BUG FIXES
changed implementation show_all_metadata() for better preformance
Changes in version 1.12.1
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
removed is_GMQL from read_gmql function The entire dataset must have the right folder structure in order to works correctly <dataset_name> —> <files>
Swap order of arguments ‘dir_out’ and ‘name’ of the collect() function so now the latter comes before the former.
DEPRECATED AND DEFUNCT
BUG FIXES
Changes in version 2.38.0
NEW FEATURES
Added support for reading attributes where the datatype is either a 64-bit or unsigned 32-bit integer.
Added many functions for working with file creation property lists. (Thanks to @ilia-kats for the contribution,)
Added support for variable length and UTF-8 encoded string datasets. (Thanks to Aaron Lun @LTLA for the contribution,)
CHANGES
BUG FIXES
Changes in version 1.16
Bug fixes
AR and RANLIB programs used to compile R are now also used to compile the HDF5 library. This resolves issue when the default versions found on a system are incompatible with options used to build R. (thanks to @miesav,)
Fixed issue in Windows installation introduced by upstream changes to libcurl distributed by rwinlibs. ()
Changes in version 0.99.11
Package
Status
Pre-release. This version is prior to the first official release (v1.0.0), anticipated in Oct. 2021.
Changes in version 0.99.0
Changes in version 1.7.1 (2021-07-27)
Changes in version 2.21
CHANGES IN VERSION 2.21.1
CHANGES IN VERSION 2.21.0
Changes in version 1.99.01
Changes in version 1.49.1 (2021-07-28)
Changes in version 2.1
rpx 2.1.12
rpx 2.1.11
rpx 2.1.10
rpx 2.1.9
rpx 2.1.8
New PXDataset2 class with richer interface and more stable data downloading functions. PXDataset and PXDataset2 work transparently and PXDataset2 is now default.
Add deprecation notice in PXDataset() constructor.
rpx 2.1.7
rpx 2.1.6
rpx 2.1.5
Improve documentation.
Check for cached PXDataset object validity.
rpx 2.1.4
Fix bug in PXDdataset internal data storage.
New pxCachedProjects() function that return the cached projects.
Fixes and improvements in the documentation.
rpx 2.1.3
PXDatasets are also cached upon creation and retrieved from cache next time they are generated.
cache is now returned by rpxCache().
rpx 2.1.2
rpx 2.1.1
Changes in version 1.5.4
scatterPlot() doesn’t warn anymore that we’re using a deprecated
parm to remove the guide
Changes in version 1.5.1
calculateSimMatrix() now allows using arbitrary keys from Orgdb
packages. Credit: illumination-k. Thanks!
Changes in version 2.10
DEPRECATED AND DEFUNCT
Changes in version 2.24.0
Bug fixes and minor improvements
Changes in version 1.14.0
Changes in version 0.32.0
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 0.99.25 (2021-06-25)
Changes in version 1.22.0
Rename colour_columns_by in plotHeatmap to color_columns_by to match other arguments.
Add color_rows_by and row_annotation_colors arguments to plotHeatmap, similar to analogous column arguments.
Change text_by annotations in plotReducedDim to use geom_text_repel from ggrepel.
Changes in version 1.7.3 (2021-07-26)
scDblFinder now includes both cluster-based and random modes for artificial doublet generation
thresholding has been streamlined
default parameters have been optimized using benchmark datasets
added the
directDblClassification method
Changes in version 1.17.1 (2021-07-21)
Improved PsiNorm vignette.
Fix bug that prevented PSINORM_FN() to be exported.
Changes in version 1.5.2
remove loading warnings
Changes in version 1.5.1
update vignette
Changes in version 1.3.3
docs: created a vignette about advanced usage of scp
Changes in version 1.3.2
docs: created a QFeatures recap vignette
Changes in version 1.3.1
refactor: deprecated rowDataToDF. This function is now replaced by QFeatures::rbindRowData.
Changes in version 1.3 Changes in version 1.3.0
Changes in version 1.7.3 (2021-10-07)
Removing more tests attempting to verify that parallelized outputs perfectly match their serial counterparts.
Changes in version 1.7.2 (2021-09-15)
Removing tests checking that sequential and parallel calls to scPCA() produce identical outputs when BiocParallel’s SerialParam() is used. This due to new handing of random number generation in BiocParallel version 1.28.
Changes in version 0.99.8
Included citation for the package
Changes in version 0.99.7
Removed global assignment in multiAdaSampling.
Changes in version 0.99.6
Revised further to address comments/feedbacks
Changes in version 0.99.5
Fixed NEWS to match the version bump
Changes in version 0.99.4
Minor change to example in matPC function
Changes in version 0.99.3
Cleaned the GSE87795 subset data to a SingleCellExperiment object
Changes in version 0.99.2
version bump with submission to Bioconductor
Changes in version 0.99.1
Cleaning repository to pass BiocCheck
Changes in version 0.99.0
Code formats/documentations have been revised to meet Bioconductor requirements
Changes in version 0.1.1
Changes in version 0.1.0
Changes in version 2.4.0
Regularizer parameter (L2_A/L1_A) was added in cellCellDecomp() (“ntd”, “ntd2”).
Multilinear CX Decompotision was added in cellCellDecomp() (“cx”).
convertNCBIGeneID is removed.
The vignettes were modified.
Support of LRBase.XXX.eg.db-type packages is completely deprecated
Changes in version 0.99.00
Changes in version 1.5.1
Prepare for release
Changes in version 1.4.1
Prepare for release
Changes in version 1.15.1
Changes in version 1.11.2
New functionality
Changes in version 1.7.3 (2021-08-24)
Improved get_targets function by supporting different output format.
Changes in version 1.7.2 (2021-06-14)
Supported automatic downloads of ExperimentHub cached files.
Changes in version 1.19.1
Changes in version 2.3.2 (2021-10-24)
Other refactors and bug fixes
Changes in version 2.3.1 (2021-10-15)
Several bug fixes
Changes in version 2.2.2 (2021-10-10)
Changes in version 1.9.4
Fix: special case when tree root has more than one lineage path
Changes in version 1.9.3
Fix: invalid parallel mutations at divergent node.
Update DESCRIPTION, README and vignettes.
Changes in version 1.9.2
Allow partially plot ‘lineagePath’.
Improved ‘plotMutSites’ function for ‘lineagePath’.
Changes in version 1.9.1
Add ‘useSites’ argument to ‘setSiteNumbering’ function.
First ‘stable’ path as default ‘lineagePath’.
Enable plot functions for ‘parallelSites’.
Changes in version 1.4.0 (2021-09-09)
Changes in version 1.0
Enhancements
Breaking Changes from Pre-release
Changes in version 1.3.0 (2021-09-28)
added S4 wrappers for Seurat and GeoMxSet objects
added custom profile matrix generation from single cell data
added ~75 profile matrices avaliable to download for human and mouse
Changes in version 1.3.2 (2021-07-27)
spatialData moved from colData to int_colData
restructuring of vignette and added imgData section
Changes in version 1.99.0 (2021-10-14)
Implemented overlaying feature: overlay template images in raster format with SHMs, where charcoal and transparency options are provided.
Implemented Spatial Single Cell functionality: co-visualize single cells and bulk tissues by placing single-cell embedding plots (PCA, tSNE, UMAP) and SHMs side by side, cell cluster assignments are defined in the app or provided by users, in dimensionality plots shapes are not restricted to 6, etc.
Spatial enrichment was synced to R command line.
Implemented Sigle and Multiple search mode for gene IDs.
Changes in version 0.99.7
added direct support for GenomicInteractions objects
improved vignettes
removed biomaRt requests
added support for R 4.1
added ‘Transcription’ Bioconductor Views annotation
Changes in version 0.99.0
initial pre-release
Changes in version 1.3
Changes in 1.3.11
Changes in 1.3.10
Changes in 1.3.9
Changes in 1.3.8
Changes in 1.3.7
Changes in 1.3.6
Changes in 1.3.5
Changes in 1.3.4
Changes in 1.3.3
Changes in 1.3.2
Changes in 1.3.1
Changes in version 0.1.0
Changes in version 1.18.0 (2021-10-27)
• Added functionality to simulate directly from empirical values
• Added eqtl.coreg parameter to splatPop
• Fixed a bug where too many cells were simulated in splatPop with multiple batches
• Fixed duplicate cell names in splatPopSimulate
Improved checks for group.prob in SplatParams
Automatically rescale group.prob during setting if it doesn’t sum to 1
Changes in version 1.0.3
Other minor changes.
Changes in version 1.0.2
Bug fix for single sample analysis.
Changes in version 1.0.1.5.3
fix variable_meta assignment
Changes in version 1.5.2
use ontology slots instead of STATO
Changes in version 1.5.7
improve NA handling in fold_change computations
Changes in version 1.5.5
change t-test outputs to data.frame
fix NA bug in feature_boxplot chart
use new ontology system in place of stato
Changes in version 1.5.2
add outputs to auto-generated documentation
fix fold change threshold using median (#56)
add fold change using means (#57)
HSD param “unbalanced” is no longer ignored
Changes in version 1.5.1
fixed broken paired tests
Changes in version 1.4.2
fix fold change threshold using median (#56)
HSD param “unbalanced” is no longer ignored
Changes in version 1.4.1
fixed broken paired tests
Changes in version 1.24.0
NEW FEATURES
Add ‘checkDimnames’ argument to SummarizedExperiment() constructor function
Add showAsCell() method for SummarizedExperiment objects.
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 0.99.6 (2021-10-25)
Fixed text for consistency in package name
Changes in version 0.99.5 (2021-10-21)
Fixed text for consistency in package name
Changes in version 0.99.4 (2021-10-12) Changes in version 0.99.3 (2021-10-11)
Fixed .gitignore file to fix build error
Changes in version 0.99.2 (2021-09-14)
Fixed bug in script
Changes in version 0.99.0 (2021-08-24)
Submitted to Bioconductor
Changes in version 0.99.0 (2021-04-28)
Changes in version 0.99.0 (2021-04-28)
Changes in version 2021-07-02 (2021-07-02)
Changes:
Changes in version 2.17
Changes in version 2.17.3
Changes in version 2.17.2
Changes in version 2.17.1
Changes in version 1.5.4
Added the function EstimageGenomeRearrangements that generates rearrangement scenarios of large scale genomic events using the double cut and join model.
Changes in version 1.5.3
Added the function SequenceSimilarity and made improvements to runtime in DisjointSet.
Changes in version 1.4.1
Changes in version 1.3.15
New Feature
Minor Change
Bump version requirements of spsComps, systemPipeR, systemPipeRdata
In global.R, now use spsOption with the .list argument to set up options instead of the base options function.
Replace includeMardown() by markdown(readLines()) so we don’t need additional {markdown} package as dependency.
Bug Fix
Fix links and image urls that were not working or changed.
Changes in version 1.3.10
New Feature
Add code display buttons to most plots that will show code to reproduce the plot.
Add two args buttonType and placeholder to dynamicFile, now users can specify what bootstrap color the button is and use placeholder to specify initial text on the upload bar.
Enhanced the original shiny fileInput, now users can also specify icon and button bootstrap colors for “server” mode in dynamicFile.
Major Change
Redesign of a few steps in Workflow module. The new version of {systemPipeR} fundamentally changed how the workflow will be run. To sync to this new version, WF module has to been redesigned. Major change happens on workflow step selection. This requires users to install systemPipeR > 1.27.10
New methods to initiate the WF project
New workflow plot
New step selection mechanism
New step editing functionalities
Minor Change
Bug Fix
#85 fix dynamicFile icon not working
Also add some icon validation code
Fix the admin server tabs get loaded twice. Added a flag to prevent this from happening.
Changes in version 1.3.0
Update version number to 1.3.0 per Bioconductor regulation.
Changes in version 0.99
NEW FEATURES
Changes in version 1.5.1 (2021-08-27)
Fixed a bug in createPrimerTrack()
Added citation
Changes in version 1.50.0
NEW FEATURES
FindAllPeaks: Allow for asymmetric RT deviations. Formerly, the window search parameter was plus o minus a tolerance; now it can be different on either side of the expected RT.
ncdf4_convert_from_path: New flag to convert CDF files recursively.
checkRimLim: show multiple samples at the same time, as opposed to a single sample in previous versions.
BUG FIXES
Make sure that the assertion that checks for NULL or NA is operating in a scalar. For vectors use another assertion.
Code clean-up. Remove unneeded files.
Changes in version 1.5.0
Bug Fixes
Major Changes
Minor Changes
Changes in version 2.21.1
Function GDCPrepare for TARGET-ALL-P3 fixed
Function getMC3MAF fixed
Changes in version 1.14.0
Minor changes and bug fixes
Changes in version 1.6.1
Changes in version 1.15
Changes in version 1.15.1
Changes in version 1.3.4
Fix bug in tests when run on Windows due to uninherited namespace imports for testthat::context and testthat::expect_equal inside a bplapply call
Changes in version 1.3.3
Debugging BioC build ERROR caused by updates to CoreGx
Changes in version 1.3.2
For now just deleting protocolData from the metadata of the SummarizedExperiment, but will eventually need to be fixed upstream in ORCESTRA
Changes in version 1.3.1
Molecular profile data is now subset in test to keep package size down
Changes in version 1.3.0
Changes in version 1.29.8
Fix the a typo in read hic data.
Changes in version 1.29.7
Fix the bug ‘breaks’ are not unique
Changes in version 1.29.6
Add smooth curve to the tracks.
Changes in version 1.29.5
Improve gene track plots.
Changes in version 1.29.4
Fix the issue for auto-rescale lolliplot by emphasizing exon region when there are continues exons.
Changes in version 1.29.3
Add the possibility to lolliplot to emphasize exon or intron region.
Changes in version 1.29.2
Fix the yaxis when user supplied yaxis is greater than max scores.
Changes in version 1.29.1
Update documentation lolliplot for rescale parameter.
Changes in version 0.1
Change default of overdispersion_shrinkage to TRUE if overdispersion = TRUE for acosh_transform() and shifted_log_transform()
Changes in version 0.1.0
Changes in version 1.2.2
BUG FIX
Improved tab delimiter processing, argument processing for RCy3::getEdgeInfo()
Changes in version 1.2.1
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.5.1
Object transformation functions condensed into the
treeAndLeaf function, to be made automatically [2020-08-24].
TreeAndLeaf function became more automated.
The igraph object manipulation was upgraded, through the use of RedeR functions.
Changes in version 1.17.2
introduce force.ultrametric parameter in read.mcmctree
Changes in version 1.17.1
Changes in version 0.1.0 (2021-07-03)
Changes in version 0.99.0 (2021-08-15)
Changes in version 1.19.1 (2021-08-30)
Bug fix
Changes in version 0.99.0
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES
None.
Changes in version 0.3.2
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES
None.
Changes in version 0.3.1
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES
None.
Changes in version 0.3.0
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES
None.
Changes in version 0.2.2
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES
The BPPARAM was not being passed through to internal bplapply calls.
Changes in version 0.2.1
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES
None.
Changes in version 0.2.0
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES
Changes in version 1.12.0
NEW FEATURES
New function, sequence_complexity(): Using either the Wootton-Federhen, Trifonov, or DUST algorithms, calculate sequence complexity in sliding windows. A version for small arbitrary strings is also provided: calc_complexity().
New function, mask_ranges(): Similarly to mask_seqs(), mask specific positions in a XStringSet object by replacing the letters with a specific filler character.
New function, motif_range(): Get the min/max range of possible logodds scores for a motif.
New function, calc_windows(): Utility function for calculating coordinates for sliding windows.
New function, window_string(): Utility function for retrieving sliding windows in a string.
New function, slide_fun(): Utility function which wraps window_string() and vapply() together.
motif_pvalue(method): P-values and scores can now be calculated dynamically instead of exhaustively, substantially increasing both speed and accuracy for bigger jobs. The previous exhaustive method can still be used however, as the dynamic method does not allow non-finite values and thus must be pseudocount-adjusted.
scan_sequences(calc.pvals, calc.qvals, motif_pvalue.method, calc.qvals.method): The calc.pvals argument defaults to TRUE. The P-value calculation method now defaults to dynamic P-values (the previous method was an exhaustive calculation), though this can be changed via motif_pvalue.method. Additionally, adjusted P-values can be calculated as either BH, FDR or a Bonferroni-adjusted P-value. More details can be found in the Sequence Searches vignette.
write_homer(threshold, threshold.type): Finer control over the final motif logodds threshold included with the written motif is now available, using the style of argument parsing from scan_sequences(). The previous logodds_threshold argument is now deprecated and set to NULL, but if set (e.g. an older script is being re-run) then the old behaviour of write_homer() will be used.
MINOR CHANGES
New global option, options(pseudocount.warning): Disable the message printed when a motif is pseudocount-adjusted.
Slight performance gains in get_bkg() window code.
motif_pvalue(): Clarify that, indeed, background probabilities are taken into account when calculating P-values from score inputs. The background adjustment takes place during the initial conversion to PWM.
motif_pvalue(): When bkg.probs are provided, use those when converting to a PWM.
scan_sequences(): The default threshold is now 0.0001 (using threshold.type = “pvalue”).
The axis text in view_motifs() is now black instead of grey.
create_motif(): When a named background vector is provided, it is sorted according to the alphabet characters.
scan_sequences(): Check that the sequences aren’t shorter than the motifs.
print.universalmotif_df: Changed warning message when subsetting to an incomplete universalmotif_df object. Also added a way to turn off informative messages/warnings via the boolean universalmotif_df.warning global option.
Miscellaneous changes and additions to the vignettes and various function manual pages.
Changes in version 1.10.2
BUG FIXES
read_homer() now correct parses enrichment P-value and logodds score.
Changes in version 1.10.1
BUG FIXES
Restore temporarily disabled ggtree(layout=”daylight”) example in the MotifComparisonAndPvalues.Rmd vignette, as tidytree is now patched.
Fixed some awkwardness in view_motifs() panel spacing and title justification.
Changes in version 0.99.0 (2021-06-07)
Changes in version 1.3.1
Changes in version 0.0.0.9000
Changes in version 1.7
Changes in version 1.2.0
Changes in version 1.5.1
Changes in version 1.1.3 (2021-10-05)
Changes in version 3.15.5
Disable testing on windows i386, providing some speedup
Disable parallel processing on Windows, causing an issue in testthat on BioC build check
Changes in version 3.15.4
Fix in
plot with
type = "XIC" to plot an empty plot if no data is
present.
Skip re-indexing of peaks to features if not necessary. This results in performance improvements for MS1 only data.
Changes in version 3.15.3
Add
manualFeatures allowing to manually define and add features to
an
XCMSnExp object.
Add
plotChromatogramsOverlay function to support plotting of
multiple EICs
from the same sample into the same plot (eventually stacked).
Add feature grouping by EIC similarity:
EicSimilarityParam.
Import
compareChromatograms from
MSnbase.
Add feature grouping by similar retention time: `SimilarRtimeParams.
Add feature grouping by similarity of feature abundances across
samples:
AbundanceSimilarityParam.
Add feature grouping methodology based on
MsFeatures.
Changes in version 3.15.2
Fix LC-MS/MS vignette.
Changes in version 3.15.1
Compatibility fix for nls() in R >= 4.1, contributed by Rick Helmus.
Changes in version 1.4.0
Add arguments to control how slots are converted in AnnData2SCE() and SCE2AnnData(). Each slot can now be fully converted, skipped entirely or only selected items converted.
Add support for converting the raw slot to an altExp in AnnData2SCE()
Add recursive conversion of lists in AnnData2SCE()
Add progress messages to various functions. These can be controlled by function arguments or a global variable.
Add long tests for various public datasets. This should help to make the package more robust
Fix bug in converting dgRMatrix sparse matrices
Correctly handle DataFrame objects stored in adata.obsm
Changes in version 1.7.1 (2021-06-18)
rmarkdownto Suggests in DESCRIPTION to resolve changes in
knitr
Changes in version 1.0.2
NEW FEATURES
Updated the vignettes.
Changes in version 1.0.1
NEW FEATURES
Changes in version 1.9.1 (2021-06-18)
rmarkdownto Suggests in DESCRIPTION to resolve changes in
knitr
Changes in version 3.2.0
The curatedMetagenomicData() function now has a rownames argument:
“long”, the default character string derived from MetaPhlAn3
“short”, the NCBI Taxonomy species name from the CHOCOPhlAn database
“short” row names are validated against NCBI Taxonomy with taxize
“NCBI”, the NCBI Taxonomy ID from the CHOCOPhlAn database
“NCBI” row names are validated against NCBI Taxonomy with taxize
rowData becomes NCBI Taxonomy ID numbers instead of taxa names
The sparse matrix data structure was switched from dgTMatrix to dgCMatrix
A few studies were reprocessed because of a minor error related to MetaPhlAn3
Changes inside the package were made to address bugs discovered by users
The combined_metadata object has been removed
Changes in version 0.99.4 (2021-10-18)
Update vignette output
Edit DESCRIPTION file
Changes in version 0.99.3 (2021-10-07)
Remove analysis/graphical functions from the master branch
Accepted by Bioconductor
Changes in version 0.99.2 (2021-09-24)
Remove cached files from git history
Modify packages based on reviewer’s comment
Changes in version 0.99.0 (2021-09-16)
The curatedTBData package collects 49 transcriptomic studies
Package vignette is updated to Rmd syntax and uses BiocStyle
All data is reprocessed in R (v4.1)
Move all data to ExperimentHub
Added a NEWS.md file to track changes to the package
Submitted to Bioconductor
Changes in version 1.7.1
21Q3 data added for crispr, copyNumber, TPM, mutationCalls and metadata datasets. Newer versions for the other datasets were not released.
CERES CRISPR data has been deprecated and has been replaced with Chronos CRISPR dependency in 21Q3 and all future releases. For more information, see:
Changes in version 1.5.2 (2021-10-13)
Daniel Dimitrov is assigned as the new maintainer
Changes in version 1.4.2 (2021-10-08)
Fixed lazy data warning
Improved test coverage
Changes in version 1.4.1 (2021-05-25)
Rebuild all regulons
Fixed ambiguously mode of regulation in mouse regulons
Changes in version 0.99.0
All set for the Bioconductor submission!
Changes in version 0.9.0
Getting ready for the submission to Bioconductor
Added a NEWS.md file to track changes to the package.
Changes in version 1.1.1 (2021-05-25)
Changes in version 3.13
Add MSigDB datasets
Add note in vignettes
Changes in version 1.1.5 (2021-09-08)
GrieneisenTS data added
HintikkaXO data added
Minor fixes
Changes in version 1.2.0
added MSigDB v7.4
removed gene-sets from the “archived” category from all collections
removed direct object referencing functions (e.g. msigdb.v7.2.hs.SYM()). Objects should be retrieved using the getMsigdb() function only or by querying the ExperimentHub
added IMEx PPI data
Changes in version 1.23.4
temporarily disable all vignettes until CAMERA issue is fixed
Changes in version 1.23.2
switch to mzML files in the ISA-Tab metadata
temporarily disable the vignette for the old xcms interface causing a build failure
Changes in version 1.23.1
add mzML versions of mzData files converted by OpenMS FileConverter
Changes in version 0.99.3 (2021-09-27)
Now uses BiocFileCache to store a copy of ExperimentHub resources. Allows for faster subsequent recalls
Changes in version 0.99.0 (2021-09-17)
Submitted to Bioconductor
Changes in version 1.1.1 (2021-03-05)
Changes in version 1.31.1
Fix mztab file name (required for new rpx)
Changes in version 1.31.0
New version for Bioc 3.14 (devel)
Changes in version 0.99.6
Changes in version 2.1.1
Temporarily rolled Ensemble version back to 75 to eliminate numerous non-coding transcripts
Methylation array information based on the latest manifest file
Changes in version 2.1.0
Release May 2021
Added annotation for the Mouse Methylation Bead Chip (thanks to Maxi Schoenung for his great contribution!).
Updated SNP information to GRCm38.p4, the last version available through NCBI.
Changes in version 0.99.3
removed usage of paste() function in error handling functions
Changes in version 0.99.2
Added NEWS.md file to track changes to the package.
Formatted functions to shorten lines
Removed usage of T/F in test cases
Removed usage of ‘paste’ in condition signals
Changes in version 0.99.1
added tests for queryATAC function
added new error checking to queryATAC and fetchATAC functions
Changes in version 1.1.1
Changes in version 1.6.0
New features
Bug fixes and minor improvements
Updates to seqFISH vignette and documentation.
Updated to changes in SummarizedExperiment where assayDimnames are checked.
scNMT defaults to version ‘1.0.0’s QC filtered cells. For unfiltered cells see version section in ?scNMT.
Changes in version 0.99.9
Changes in version 0.99.1
Add infoOnly argument to get details about download size
Changes in version 0.99.0
Add documentation
Prepare for Bioconductor submission
Changes in version 0.1.0
Add a NEWS.md file to track changes to the package.
Changes in version 1.2.1
Changes in version 1.0.0
Changes in version 0.99.4
Updated workflow image
Changes in version 0.99.3
Adjusted QC plotting histogram function to remove user-defined limits
Changes in version 0.99.2
Version update for bioconductor build review
Changes in version 0.99.1
NEW FEATURES
No new NEWS to report
Forty seven software packages were removed from this release (after being deprecated in Bioc 3.13): AffyExpress, affyQCReport, AnnotationFuncs, ArrayTools, bigmemoryExtras, BiocCaseStudies, CancerMutationAnalysis,
Please note: CexoR and IntramiRExploreR, previously announced as deprecated in 3.13, fixed their packages and remained in Bioconductor.
Twenty three software packages are deprecated in this release and will be removed in Bioc 3.15: affyPara, ALPS, alsace, BrainStars, destiny, dualKS, ENCODExplorer, ENVISIONQuery, FindMyFriends, GeneAnswers, gramm4R, KEGGprofile, MouseFM, MSGFgui, MSGFplus, MSstatsTMTPTM, PanVizGenerator, predictionet, RGalaxy, scClassifR, slinky, SRGnet, SwimR
Eleven experimental data packages were removed this release (after being deprecated in BioC 3.13): ceu1kg, ceu1kgv, ceuhm3, cgdv17, dsQTL, facsDorit, gskb, hmyriB36, JctSeqData, MAQCsubsetAFX, yri1kgv
Five experimental data packages are deprecated in this release and will be removed in Bioc 3.15: ABAData, brainImageRdata, PCHiCdata, RITANdata, tcgaWGBSData.hg19
Ninety annotation packages were removed from this release (after being deprecated in Bioc 3), greengenes13.5MgDb, ribosomaldatabaseproject11.5MgDb, silva128.1MgDb
One annotation package was deprecated in this release and will be removed in Bioc 3.15: org.Pf.plasmo.db
One workflow package was removed from this release (after being deprecated in Bioc 3.13): eQTL
No workflow packages were deprecated in this release. | https://bioconductor.org/news/bioc_3_14_release/ | CC-MAIN-2021-49 | refinedweb | 22,382 | 52.46 |
9.17. Date and time
These functions deal with either ‘elapsed’ or ‘calendar’ time.
They share the
<time.h> header, which declares the
functions as necessary and also the following:
CLOCKS_PER_SEC
- This is the number of ‘ticks’ per second returned by the
clockfunction.
clock_t
time_t
- These are arithmetic types used to represent different forms of time.
struct tm
This structure is used to hold the values representing a calendar time. It contains the following members, with the meanings as shown.
int tm_sec /* seconds after minute [0-61] (61 allows for 2 leap-seconds)*/ int tm_min /* minutes after hour [0-59] */ int tm_hour /* hours after midnight [0-23] */ int tm_mday /* day of the month [1-31] */ int tm_mon /* month of year [0-11] */ int tm_year /* current year-1900 */ int tm_wday /* days since Sunday [0-6] */ int tm_yday /* days since January 1st [0-365] */ int tm_isdst /* daylight savings indicator */
The
tm_isdstmember is positive if daylight savings time is in effect, zero if not and negative if that information is not available.
The time manipulation functions are the following:
#include <time.h> clock_t clock(void); double difftime(time_t time1, time_t time2); time_t mktime(struct tm *timeptr); time_t time(time_t *timer); char *asctime(const struct tm *timeptr); char *ctime(const time_t *timer); struct tm *gmtime(const time_t *timer); struct tm *localtime(const time_t *timer); size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *timeptr);
The functions
asctime,
ctime,
gmtime,
localtime, and
strftime
all share static data structures, either of type
struct tm or
char [], and calls to one of them may overwrite the data
stored by a previous call to one of the others. If this is likely to cause
problems, their users should take care to copy any values needed.
clock
- Returns the best available approximation to the time used by the current invocation of the program, in ‘ticks’.
(clock_t)-1is returned if no value is available. To find the actual time used by a run of a program, it is necessary to find the difference between the value at the start of the run and the time of interest—there is an implementation-defined constant factor which biases the value returned from clock. To determine the time in seconds, the value returned should be divided by
CLOCKS_PER_SEC.
difftime
- This returns the difference in seconds between two calendar times.
mktime
This returns the calendar time corresponding to the values in a structure pointed to by
timeptr, or
(time_t)-1if the value cannot be represented.
The
tm_wdayand
tm_ydaymembers of the structure are ignored, the other members are not restricted to their usual values. On successful conversion, the members of the structure are all set to appropriate values within their normal ranges. This function is useful to find out what value of a
time_tcorresponds to a known date and time.
time
- Returns the best approximation to the current calendar time in an unspecified encoding.
(time_t)-1is returned if the time is not available.
asctime
Converts the time in the structure pointed to by
timeptrinto a string of the form
Sun Sep 16 01:03:52 1973\n\0
the example being taken from the Standard. The Standard defines the algorithm used, but the important point to notice is that all the fields within that string are of constant width and relevant to most English-speaking communities. The string is stored in a static structure which may be overwritten by a subsequent call to one of the other time-manipulation functions (see above).
ctime
- Equivalent to
asctime(localtime(timer)). See
asctimefor the return value.
gmtime
- Returns a pointer to a
struct tmset to represent the calendar time pointed to by
timer. The time is expressed in terms of Coordinated Universal Time (UTC) (formerly Greenwich Mean Time). A null pointer is returned if UTC is not available.
localtime
- Converts the time pointed to by
timerinto local time and puts the results into a
struct tm, returning a pointer to that structure.
strftime
Fills the character array pointed to by
swith at most
maxsizecharacters. The
formatstring is used to format the time represented in the structure pointed to
timeptr. Characters in the format string (including the terminating null) are copied unchanged into the array, unless one of the following format directives is found—then the value specified below is copied into the destination, as appropriate to the locale.
The total number of characters copied into
*sis returned, excluding the null. If there was not room (as determined by
maxsize) for the trailing null, zero is returned. | http://publications.gbdirect.co.uk/c_book/chapter9/date_and_time.html | crawl-002 | refinedweb | 751 | 50.67 |
The objective of this post is to explain how to connect to a MQTT broker and subscribing to a topic, using the LinkIt Smart Duo.
Introduction
The objective of this post is to explain how to connect to a MQTT broker and subscribing to a topic, using the LinkIt Smart Duo. This will be done on OpenWRT, the board’s Operating System.
The MQTT broker used will be CloudMQTT. You will need to register (there’s a free plan available) and create a broker instance. You will also need the credentials from the broker instance information page: address, port, user and password.
We will use Python and the paho-mqtt library, which we used before in previous posts. Please note that the actual Python coding will be the same of the mentioned post, so we will not cover everything in detail. You can check the functions in more detail in that Python post.
So, the first thing we need to do is to install the MQTT library on the LinkIt Smart. To do so, connect to the LinkIt Smart using Putty and run the following pip command:
pip install paho-mqtt
Check figure 1 for a descriptive image on how to do it.
Figure 1 – Install paho-mqtt on the LinkIt Smart Duo.
Note that it may take a while until the installation starts.
The coding
As usual, we will be using WinSCP to upload the Python file with the code. So, as shown in figure 2, just connect to the LinkIt Smart using WinSCP and create a Python file. In this case, I called it MQTTsubscribe.py. Check here how to use WinSCP to upload files to the LinkIt Smart.
Figure 2 – Creating the Python file.
Now, to create the script, double click on the file and the editor should pop. Start the code by including the previously installed python MQTT module. We will also need the time module, to access sleeping functions.
After that, we will declare some auxiliary variables. The first one will be a global variable indicating the state of the connection to the broker. Thus, it will be initialized with false.
The other variables will contain the broker connection information, previously mentioned in the introduction section.
import paho.mqtt.client as mqttClient import time Connected = False #global variable for the state of the connection broker_address= "m11.cloudmqtt.com" #Broker address port = 12948 #Broker port user = "yourUserName" #Connection username password = "yourPassowrd" #Connection password
Next, we will create a client instance. The constructor receives as argument a unique MQTT client identifier, as a string. We will call the client “Python”.
After this instantiation, we will call the username_pw_set method, in order to set username and password needed to connect to the MQTT broker.
After that, we will need to specify a on_connect callback function, which is executed when the broker responds to the connection request. We won’t be specifying the code for the function know, just assign it.
We will also need to specify a on_message callback function, which is executed when a message is received on a subscribed topic. We will also leave the actual implementation of the function for latter.
client = mqttClient.Client("Python") #create new instance client.username_pw_set(user, password=password) #set username and password client.on_connect= on_connect #attach function to callback client.on_message= on_message #attach function to callback
Now, we will call the connect method, for establishing the connection to the MQTT broker. Note that this is a blocking method. As inputs, this method will receive the broker address and port.
Next, we will call the loop_start method. This method is very important since it will launch a background thread to handle the connection and the sending and receiving of messages. But, since the thread runs in background, it will not block the execution of our code.
Since the connection may take a while to be established, we will poll the previously declared Connected variable in a loop, until its value is set to true. This way, we won’t advance in our code until we know we are already connected to the MQTT broker. Please note that the Connected variable will be set to true in the on_connect handling function, which we still need to specify.
Once the connection is established, we will subscribe to a topic. To do so, we call the subscribe method, passing as argument the name of the topic that we want to subscribe. In this example, we will subscribe to the “python/test” topic. So, when a message is received on this topic, the on_message function, yet to be specified, will run.
client.connect(broker_address, port=port) #connect to broker client.loop_start() #start the loop while Connected != True: #Wait for connection time.sleep(0.1) client.subscribe("python/test")
Now, we will do an infinite loop with a small delay in each iteration, since the messages will be handled in the on_message callback function.
This loop will run inside a try-except block, where the except block will catch a keyboard interrupt. By doing so, we can easily terminate the loop by issuing a ctrl+C command to the LinkIt Smart.
Since the program will finish in the except block, when the exception is caught, we will need to disconnect from the broker and end the background thread started in the initialization. To do so, we call the disconnect method and loop_stop method, both in the except block.
try: while True: time.sleep(1) except KeyboardInterrupt: print "exiting" client.disconnect() client.loop_stop()
Finally we need to specify the on_message callback function. As can be seen here, it receives 3 arguments. Nevertheless, we will only use the argument named message.
We will access a member of this class called payload, to obtain the message received from the previously subscribed topic. Then, we will print the message payload.
def on_message(client, userdata, message): print "Message received: " + message.payload
Check the full source code bellow, ready to use with the on_connect callback function also implemented. Note that we check the rc (result code) argument, which indicates if there was an error on the connection. The value 0 means there was no error and the connection was established. In that case, we set the Connected variable to true.
import paho.mqtt.client as mqttClient import time def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to broker") global Connected #Use global variable Connected = True #Signal connection else: print("Connection failed") def on_message(client, userdata, message): print "Message received: " + message.payload Connected = False #global variable for the state of the connection broker_address= "m11.cloudmqtt.com" #Broker address port = 12948 #Broker port user = "yourUserName" #Connection username password = "yourPassword" ("python/test") try: while True: time.sleep(1) except KeyboardInterrupt: print "exiting" client.disconnect() client.loop_stop()
Testing the code
To test the code, just open the Putty terminal window again and navigate to the directory where you saved the previous code. There, give the following command:
python MQTTsubscribe.py
If you named the file differently, use the name of your file. The program should start running and once the connection is established, you should get the result indicated in figure 3.
Figure 3 – Connection to the broker successful.
To send a message to the subscribed “python/test” topic, we will use an application called MQTTLens. It’s very easy to use, free and it has been the one used in previous tutorials. So, open MQTTLens, connect to the broker and publish a message to the topic, as indicated in figure 4.
Figure 4 – Publishing a message to the LinkIt Smart subscribed topic.
After sending the message, go back to Putty. The message sent should be printed in the console, as indicated in figure 5. In that case, we sent a second message, just for illustration purposes.
Figure 5 – Printing the received MQTT messages.
Related posts
- ESP32: Subscribing to MQTT topic
- ESP32: Publishing messages to MQTT topic
- Python: Subscribing to MQTT topic
- Python: Publishing messages to MQTT topic
- ESP8266: Connecting to MQTT broker
2 Replies to “LinkIt Smart 7688 Duo: Subscribing to MQTT topic” | https://techtutorialsx.com/2017/04/27/linkit-smart-7688-duo-subscribing-to-mqtt-topic/comment-page-1/ | CC-MAIN-2019-51 | refinedweb | 1,341 | 65.12 |
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Populating Your Database with Seed Data5:55 with James Churchill
Let's expand the data set that we're seeding our database with so that we have more data to work.8 -b populating-your-database-with-seed-data
Code
Here's the code for our expanded test data.
var seriesSpiderMan = new Series() { Title = "The Amazing Spider-Man", Description = "The Amazing Spider-Man (abbreviated as ASM)." }; var seriesIronMan = new Series() { Title = "The Invincible Iron Man", Description = )." }; var seriesBone = new Series() { Title = "Bone", Description = "Bone is an independently published comic book series, written and illustrated by Jeff Smith, originally serialized in 55 irregularly released issues from 1991 to 2004." }; var artistStanLee = new Artist() { Name = "Stan Lee" }; var artistSteveDitko = new Artist() { Name = "Steve Ditko" }; var artistArchieGoodwin = new Artist() { Name = "Archie Goodwin" }; var artistGeneColan = new Artist() { Name = "Gene Colan" }; var artistJohnnyCraig = new Artist() { Name = "Johnny Craig" }; var artistJeffSmith = new Artist() { Name = "Jeff Smith" }; var roleScript = new Role() { Name = "Script" }; var rolePencils = new Role() { Name = "Pencils" }; var comicBook1 = new ComicBook() { Series = seriesSpiderMan, IssueNumber = 1, Description = "As Peter Parker and Aunt May struggle to pay the bills after Uncle Bens death, Spider-Man must try to save a doomed John Jameson from his out of control spacecraft. / Spideys still trying to make ends meet so he decides to try and join the Fantastic Four. When that becomes public knowledge the Chameleon decides to frame Spider-Man and steals missile defense plans disguised as Spidey.", PublishedOn = new DateTime(1963, 3, 1), AverageRating = 7.1m }; comicBook1.AddArtist(artistStanLee, roleScript); comicBook1.AddArtist(artistSteveDitko, rolePencils); context.ComicBooks.Add(comicBook1); var comicBook2 = new ComicBook() { Series = seriesSpiderMan, IssueNumber = 2, Description = "The Vulture becomes the city's most feared thief. Spider-Man must find a way to figure out his secrets and defeat this winged menace. / Spider-Man is up against The Tinkerer and a race of aliens who are trying to invade Earth.", PublishedOn = new DateTime(1963, 5, 1), AverageRating = 6.8m }; comicBook2.AddArtist(artistStanLee, roleScript); comicBook2.AddArtist(artistSteveDitko, rolePencils); context.ComicBooks.Add(comicBook2); var comicBook3 = new ComicBook() { Series = seriesSpiderMan, IssueNumber = 3, Description = "Spider-Man battles Doctor Octopus and is defeated, he considers himself a failure until the Human Torch gives a speech to his class which inspires him to go in prepared and win the day, leaving Doctor Octopus under arrest. Spider-Man visits the Torch with words of thanks.", PublishedOn = new DateTime(1963, 7, 1), AverageRating = 6.9m }; comicBook3.AddArtist(artistStanLee, roleScript); comicBook3.AddArtist(artistSteveDitko, rolePencils); context.ComicBooks.Add(comicBook3); var comicBook4 = new ComicBook() { Series = seriesIronMan, IssueNumber = 1, Description = "A.I.M. manages to make three duplicates of the Iron Man armor.", PublishedOn = new DateTime(1968, 5, 1), AverageRating = 7.6m }; comicBook4.AddArtist(artistArchieGoodwin, roleScript); comicBook4.AddArtist(artistGeneColan, rolePencils); context.ComicBooks.Add(comicBook4); var comicBook5 = new ComicBook() { Series = seriesIronMan, IssueNumber = 2, Description = "Stark competitor Drexel Cord builds a robot to destroy Iron Man.", PublishedOn = new DateTime(1968, 6, 1), AverageRating = 6.7m }; comicBook5.AddArtist(artistArchieGoodwin, roleScript); comicBook5.AddArtist(artistJohnnyCraig, rolePencils); context.ComicBooks.Add(comicBook5); var comicBook6 = new ComicBook() { Series = seriesIronMan, IssueNumber = 3, Description = "While helping Stark, Happy once again turns into the Freak.", PublishedOn = new DateTime(1968, 7, 1), AverageRating = 6.8m }; comicBook6.AddArtist(artistArchieGoodwin, roleScript); comicBook6.AddArtist(artistJohnnyCraig, rolePencils); context.ComicBooks.Add(comicBook6); var comicBook7 = new ComicBook() { Series = seriesBone, IssueNumber = 1, Description = "Fone Bone, Smiley Bone and Phoney Bone are run out of Boneville and get separated in the desert. Fone Bone finds his way to the valley.", PublishedOn = new DateTime(1991, 7, 1), AverageRating = 7.1m }; comicBook7.AddArtist(artistJeffSmith, roleScript); comicBook7.AddArtist(artistJeffSmith, rolePencils); context.ComicBooks.Add(comicBook7); var comicBook8 = new ComicBook() { Series = seriesBone, IssueNumber = 2, Description = "While babysitting Miz Possum's children, Bone is chased by Rat Creatures, is saved by the Dragon and finally finds Thorn.", PublishedOn = new DateTime(1991, 9, 1), AverageRating = 6.9m }; comicBook8.AddArtist(artistJeffSmith, roleScript); comicBook8.AddArtist(artistJeffSmith, rolePencils); context.ComicBooks.Add(comicBook8); var comicBook9 = new ComicBook() { Series = seriesBone, IssueNumber = 3, Description = "Grandma Ben returns from Barrelhaven and Phoney Bone and Bone reunite.", PublishedOn = new DateTime(1991, 12, 1), AverageRating = 6.9m }; comicBook9.AddArtist(artistJeffSmith, roleScript); comicBook9.AddArtist(artistJeffSmith, rolePencils); context.ComicBooks.Add(comicBook9); context.SaveChanges();
Additional Learning
- 0:00
When we initially populate our database with data,
- 0:03
we say that we're seeding our database.
- 0:05
Sometimes the seed data is fake or
- 0:08
dummy data that enables the development or testing of the system.
- 0:12
Sometimes, it's data that needs to be present in order for
- 0:15
the system to operate correctly.
- 0:18
In the next two sections, we'll be looking at how to use LINQ with entity framework
- 0:22
to write queries and perform CRUD operations.
- 0:26
To prepare for that,
- 0:27
it'll be helpful to expand the dataset that we're seeding our database with.
- 0:31
So that we have more data to work with,
- 0:34
instead of expanding the code that we've been writing in the program.CS file.
- 0:38
Let's see how we can use a custom EF database initializer to seed our database.
- 0:44
Right-click on the project and select Add>Class.
- 0:50
Name the class Database, Initializer and click Add.
- 0:59
By default, a class without an access modifier is only
- 1:02
visible to other members within the same project.
- 1:06
For the purposes of our database initializer class that will work fine,
- 1:10
as only our context class will need access.
- 1:13
We can be explicit by using the internal access modifier.
- 1:18
To create a custom database initializer,
- 1:20
we can inherit from one of the provided EF database initialize your classes.
- 1:25
Let's use the drop create database if model changes class.
- 1:29
So we're only dropping and creating the database if our model changes.
- 1:34
Add a using statement for the system.Data.Entity namespace.
- 1:40
And set the base class to the DropCreateDatabaseIfModelChanges class.
- 1:48
DropCreateDatabaseIfModelChanges of type context.
- 1:54
Now we override the base classes seed method.
- 1:59
The seed method is just called after the database has been created which
- 2:03
is a convenient time to see the database.
- 2:11
We also need to update our context class constructor to use our custom database
- 2:16
initializer.
- 2:19
So, Database.SetInitializer(new DatabaseInitializer()).
- 2:30
Now we need to move our test data from the program.cs file to our new seed method.
- 2:37
Starting just inside the using statement.
- 2:39
Select all of the code down to and including the call to the context is
- 2:44
saved changes method and cut the selection to the clipboard.
- 2:55
Let's remove the call to the base class method.
- 2:58
And then paste from the clipboard.
- 3:07
And finally, add the missing using directive for
- 3:10
the compactgallerymodel.modelsnamespace.
- 3:15
Let's set a break point just inside of our seed method.
- 3:19
So we can see when it's called and run the app to test our changes.
- 3:26
We didn't have our break point but that makes sense as our model didn't change.
- 3:35
Let's temporarily change our model.
- 3:39
Open the artist.cs file and add a test property.
- 3:51
Run the app again.
- 3:54
This time we hit our breakpoint in the Seed method.
- 3:57
Press F5 and then Enter to continue execution.
- 4:03
And run the app again.
- 4:07
This time we didn't hit our break point which is exactly the behavior that we want
- 4:12
as our database already contains our seed data
- 4:18
Before we wrap up this video, let's update our database initializers
- 4:22
seed method with an expanded set of test data.
- 4:25
I'll switch to Notepad, copy this code to the clipboard.
- 4:30
Switch back to Visual Studio, and replace the contents of the seed method by
- 4:34
selecting the existing code, and pasting from the clipboard.
- 4:50
If you're following along, you can find a copy of this code in the teacher's notes.
- 4:55
Now that we have the final version of our custom database initializer,
- 4:59
let's remove the test property from the artist class, and run our app.
- 5:05
And, here's the output of our final test data.
- 5:08
Let's review what we learned in this section.
- 5:10
[SOUND] We learned about One-to-Many Relationships, and
- 5:14
how to define them using navigation and foreign key entity properties.
- 5:18
Then, we learned about many-to-many relationships and
- 5:22
how to define them with or without an explicit bridge entity or table.
- 5:26
We also learned how to use data annotation attributes, EF conventions and
- 5:31
a fluent API to refine our model.
- 5:34
And lastly,
- 5:35
we created a custom database initializer which improved our database seating.
- 5:41
Our entity data model is now complete.
- 5:44
Great job working your way through the changes and updates in this section.
- 5:47
We covered a lot of ground.
- 5:50
In the next section, we'll see how to use link to write queries.
- 5:54
Let's keep going. | https://teamtreehouse.com/library/populating-your-database-with-seed-data | CC-MAIN-2020-05 | refinedweb | 1,597 | 58.18 |
Search the Community
Showing results for tags 'filter'.
Found 70 results
Water shader approach?
Saltallica posted a topic in Pixi.jsI'm struggling with an approach to add a water effect to an area of container. I'd like to have the area in green distort the area below it via a shader, but also have the ability for this water area to "rise/fall". The rise/fall is of no problem when it's just a sprite I can move up and down as necessary - but being able to apply a shader to just that specific area is throwing me for a loop. Adding a filter directly to the sprite won't distort anything since it's not accounting for the pixels behind it.. Is there are way to capture this particular area, save it to a buffer, and apply a filter, and put it back in place? RenderTexture seems like it might be in the right direction, but I can't see where I can grab an area of an existing container... Any help would be much appreciated!
Applying filter to a texture without clearing it
jfred1979 posted a topic in Pixi.jsI am trying to do the following: draw some shapes to a Graphics object render those shapes to a RenderTexture without clearing it first, so that the shapes are "painted onto the texture" apply a filter (a blur, for example) to the RenderTexture without ever clearing it so the current blur is processing an already blurred texture from the previous frame render to the screen repeat, never clearing the previously rendered display This is basically continuously blurring the display so that the longer something has been displayed, the more blurred it gets. Here is where I am at so far: class Project { constructor() { this.renderer = new PIXI.WebGLRenderer(window.innerWidth, window.innerHeight, { antialias: true }); this.renderTexture = PIXI.RenderTexture.create(this.renderer.width, this.renderer.height); document.body.appendChild(this.renderer.view); this.stage = new PIXI.Container(); this.canvas = new PIXI.Graphics(); this.sprite = new PIXI.Sprite(this.renderTexture); this.blurFilter = new PIXI.filters.BlurFilter(); this.stage.addChild(this.sprite); this.draw(); } draw() { var mousePosition = this.renderer.plugins.interaction.mouse.global; this.canvas.clear(); this.canvas.lineStyle(0); this.canvas.beginFill(0x666666); this.canvas.drawCircle(mousePosition.x, mousePosition.y, 50); // Somehow apply a blur to this.renderTexture without clearing it so the next line renders the // canvas on top of already blurred elements. This display will be fed into the next render // cycle without being cleared so that the blurs are "additive". this.renderer.render(this.canvas, this.renderTexture, false); this.renderer.render(this.stage); requestAnimationFrame(this.draw.bind(this)); } } Does this make sense? Am I on the right track?
cannot apply gray filter to sprite
Yehuda Katz posted a topic in Phaser
Phaser move filter
slaanevil posted a topic in PhaserDear community: We are learning about phaser and we have a doubt for this forum. We are trying to develop a simple shoot game with a plane and enemies. The goal is that when a enemy is killed, a fire animation will be showed. We did this with a spritesheet and the result is good but we want to improve the quality with this filter: The problem is that we can't move the fireball effect over each enemy. The fire is always in the same position (left-bottom corner), and we can not change it. Probably the problem is the opengl code but we are not sure. Anyone can add this fireball effect to be showed when the enemy is killed? I thing that this code will be useful for the developers as us..
-
How do I create a custom filter & mask shape?
kingzee posted a topic in Pixi.jsI'm trying to create an effect where a shape inverts the color of everything it covers. Imagine two Container objects, one rendered behind the other, the one behind is the "main stage" with all the graphics, and the one in front of it contains my shape, I want that shape to invert the color of everything behind it on the first container, that shape is animated too. I just used containers to explain what I want to do, while it is what I have in my current code, I'm open to any solutions, thanks. P-S : Is there really no real-time chat anywhere? Irc, Discord, etc.. It's a shame such a widely use library doesn't have anywhere where to discuss and talk about everything pixijs related..
Adjust the intensity of the DisplacementFilter
oskanberg posted a topic in Pixi.jsHello, I am using a DisplacementFilter to create a water ripple effect (the source & maps kindly borrowed from some other posts on this forum). I would like to be able to have the ripples 'fade' out, i.e. reduce the intensity/magnitude of the displacement. The only way I can think of doing this is by slowly reducing the intensity of the colour in the displacement map (reducing the saturation?), and replacing the filter with the new sprite. Is there a cleaner/easier way of achieving this? This is a snippet of the code I am using: Thanks for your help.
Pixi custom filter access underlying pixels
PrettyMuchBryce posted a topic in Pixi.jsHello. I am trying to build a sort of "Line of sight" shader. I have the a tilemap which is just a Sprite sitting inside of a container. Then I am generating another texture dynamically which represents the "light" data. I want to create a fragment shader to show/hide parts of this tilemap based on the light texture/ I am able to pass this texture into the shader, however I am seeing a problem that I think may be intended behavior, but I'm trying to figure out how to achieve my desired result. The problem is it seems the fragment shader is operating on the screen rather than the underlying pixels in my Container. The container is scaled/translated so I have no way to know which true (non translated/scaled) pixel I am operating on within the shader (vTextureCoord seems to give me coordinates relative to the screen ?). Whereas the lightmap texture I am passing in does not have this same problem. This is my first time playing around with pixi.js filters. Any suggestions ?
Filter on group not working
EvilB posted a topic in PhaserHey all, I'm trying to filter an entire group, but I can't seem to succeed, where applying that same filter to a sprite instantly works. I'm working on my first Typescript project and I like it a lot! I have a MainGame class (mainGame.ts) which extends Phaser.State and I have a Container class (container.ts) which extends Phaser.Group When I apply a filter to a sprite that I simply added like: this.body = this.add.sprite(0, 0, 'bgBase'); this.body.filters = [ new Phaser.Filter.BlurY(this.game, null,'') ]; the blur filter is applied. Now when I try to apply the filter to a container which contains Sprites, like: this.container = new Container(this.game); this.container.filters = [ new Phaser.Filter.BlurY(this.game, null,'') ]; does NOT work. But when I apply the filter directly to a Sprite inside the container, like: this.container.someSprite.filters = [ new Phaser.Filter.BlurY(this.game, null,'') ]; the filter is applied as expected. I must be overlooking something important for how I create or add the group, but I keep missing it. I hope somebody has an idea about where to look. Help will be much appreciated!
Editing PIXI DotFilter - Question
Arron Ferguson posted a topic in Pixi.jsHi all, I'm fairly new to Pixi and extremely new to fragment shaders and am trying to change the PIXI DotFilter fragment shader so that the holes are transparent (which I've done) but I want to set the foreground color to black or preferably any color. The first pic is what the PIXI DotFilter fragment shader renders without changes (i.e., by default) - which is black foreground on white background, and the second one is where I got it to now (transparency). The second picture (after I changed the color.a value to 0.0) has the color as white with the background knocked out. The fragment shader code is as follows: precision mediump float; varying vec2 vTextureCoord; varying vec4 vColor; uniform vec4 filterArea; uniform sampler2D uSampler; uniform float angle; uniform float scale; float pattern() { float s = sin(angle), c = cos(angle); vec2 tex = vTextureCoord * filterArea.xy; vec2 point = vec2( c * tex.x - s * tex.y, s * tex.x + c * tex.y ) * scale; return (sin(point.x) * sin(point.y)) * 4.0; } void main() { vec4 color = texture2D(uSampler, vTextureCoord); float average = (color.r + color.g + color.b) / 3.0; gl_FragColor = vec4(vec3(average * 10.0 - 5.0 + pattern()), color.a); } Like I say, if I change that last line's color.a to 0.0 I knock out the background (which is what I want) but I want to change the color of the fill to black or any other color. I'm not sure what to change to do that. Anyone know how to do this? Thanks in advance!.
Filter not loaded on first load, mobile
md_lasalle posted a topic in PhaserHi, I'm currently developing a game where in the preload phase I load a few images and a shader : this.load.image('title', 'assets/images/title.png'); this.load.image('subtitle', 'assets/images/subtitle.png'); this.load.image('particle', 'assets/images/particle.png'); this.load.bitmapFont('belleza', 'assets/fonts/belleza.png', 'assets/fonts/belleza.xml'); this.load.shader('sphere', 'assets/shaders/sphere.frag'); Unfortunately it seems that on mobile (tested chrome + safari on iphone5s running iOS 10), the page requires a reload for the filter to work. Any idea what I should be looking for? Desktop browser version works fine. Thanks.
The Deepnight Effect Help
Rybar posted a topic in PhaserThe.
is OutlineFilter gone with 4.1.1
GBear posted a topic in Pixi.jshi. i'm updating 4.1.1 from 3.1.1 but i can't find outlineFilter with 4.1.1. pixi-filter doesn't have it.. where can i find it? thx
How to pass vectors and colors to filters uniforms
Xesenix posted a topic in Phaservar
Camera shake artifact when shaders are applied?
poppij posted a topic in Phaser.
Create gradient filter on sprite.
Rodrigo posted a topic in Pixi.jsHi, I've been struggling to create a gradient filter over an sprite using shaders. I have this and is working fine: On the other hand this code creates a nice gradient: precision mediump float; // start and end colors vec3 color1 = vec3(0.0,0.0,1.0); vec3 color2 = vec3(1.0,0.5,0.0); void main( void ) { vec2 uvs = vTextureCoord.xy; vec3 mixCol = mix( color2, color1, uvs.y ); gl_FragColor = vec4(mixCol, 1.0); } But I can't apply that gradient to the image as the first sample. I tried this, but it still generates a solid color on top of the image: precision mediump float; varying vec2 vTextureCoord; varying vec4 vColor; // start and end colors vec3 color1 = vec3(0.0,0.0,1.0); vec3 color2 = vec3(1.0,0.5,0.0); uniform sampler2D uSampler; uniform float customUniform; void main(){ vec2 uvs = vTextureCoord.xy; vec3 mixCol = mix( color2, color1, uvs.y ); vec4 fg = texture2D(uSampler, vTextureCoord); fg = vec4(mixCol, 0.5); gl_FragColor = fg; } I'm not very familiar with the Shaders specific stuff, but definitely I'm missing something here. Any help will be appreciated. Thanks, Rodrigo.?
Shader that used on 2.x is not operating on 3.11
GBear posted a topic in Pixi.jshi this shader was used on pixi.2.x and i wanna use on 3.x so i update black color line only.. but it's not operating .. regards Yun following movie on 2.x bandicam 2016-07-28 22-04-56-145.avi following movie on 3.x bandicam 2016-07-28 22-05-56-130.avi
HueRotate Filter Example
makalu posted a topic in PhaserHi, Does anyone have an example of using the HueRotate filter on a sprite? My hero sprite has a child sprite animation of a shirt that I'd like to change its color, would a HueRotate be able to change its color? Thanks! | http://www.html5gamedevs.com/tags/filter/ | CC-MAIN-2017-47 | refinedweb | 2,067 | 58.79 |
The Loan Calc problem in Java
Hi everyone, I have been trying to solve this loan calc problem for Java. It is for the loops section. Not sure what am I missing here. The hidden test cases fail and. I am unable to complete my certificate since this problem is not solved. Please let me know if any of you faced it also and how did you get it resolved. import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int amount = scanner.nextInt(); int i = 0; //your code goes here if (amount > 0){ while( i <3){ amount = amount - (amount/100 * 10); i++; } System.out.println(amount); } } }
4/13/2021 5:21:50 AMSapna Singh
3 AnswersNew Answer
thank you | https://www.sololearn.com/Discuss/2753496/the-loan-calc-problem-in-java | CC-MAIN-2021-21 | refinedweb | 129 | 76.72 |
User talk:Alpalwriter
From Uncyclopedia, the content-free encyclopedia
edit Welcome!
Hello, Alpalwriter,:Alpal!)
07:51, March 16, 2014 (UTC)
edit User:Alpalwriter/Muhammad: The Authentic Biography
It is an interesting article with humour present however perhaps it could have a bit more words. Short sentences or paragraphs or sentences that you can write between each picture widening the joke in the picture. Otherwise some of it seems an attack on Islam and not funny.:07, March 16, 2014 (UTC)
- Thanks! That might be a difficult job, though I'll try. But it'll take some time. - Alpalwriter (talk) 10:09, March 16, 2014 (UTC)
- Yes. I've notified an admin to see what he thinks of the article as I am a bit unsure as to whether you are going about it the right way. I'm sure you're not intending to cause offence but some of it reads like that to me. Also the article may need to be moved to a title that people will find more easily. We'll see what we can do meanwhile try and widen the story, show Muhammad going to the market and visiting some relatives. If you do an almost "Life of Brian" take on it and show the history of the time more realistically than in religious teaching, without tainting the man himself and offending most of Islam than that would be probably the best way:16, March 16, 2014 (UTC)
- The 9-11 picture was a step too far. Well done for interpreting landscape architect but it is a subtle joke and one which the article claims that the reader is misinterpreting the wrong way. Instead of offending the Islamic prophet divert the blame away from him (as there is no need to point the finger at him, that's stereotyping of a religion) and point the finger at the actual terrorists and say that Muhammad would not have accepted:25, March 16, 2014 (UTC)
PS - I'm going to move this to your namespace as the current version is not good enough for mainspace yet.:28, March 16, 2014 (UTC)
- Oh I see you've moved it from namespace.:29, March 16, 2014 (UTC)
- He has only copied it there; I will delete the mainspace copy.
- I am running with photos disabled. My initial reaction is that the article does not fit, as mainspace is a satire encyclopedia and not a comic book. Photos with funny captions are usually sprinkled in alongside funny text to give the superficial impression that this is a complete encyclopedia, until the reader studies them and sees that they are not on the level either.
- A second reaction coming not long after the first is that the intent of this article is to ridicule Islam in pictures and not to amuse the reader. "Shit be upon him" in the first paragraph, no matter how ScottPat tries to soften it, sets out a point of view (and, if there is a joke, thus begins by spelling it out) and alienates a large number (or perhaps all) of the target audience. The photo captions here, especially the use of the second person, are unfunny and deliberately provocative. I suggest that rather than let other Uncyclopedians twist to make this article acceptable, author ask himself what his goal is here. My guess is that you wrote the case against Islam in photos for the overt purpose of rubbing Muslims' noses in it. Spıke ¬ 12:06 16-Mar-14
- No, thanks. - Alpalwriter (talk) 18:05, March 16, 2014 (UTC)
edit The Satanic Verses of Bhagavad-gita
Thank you for tolerating my occasional deletions from this evolving article. I continue to wonder whether you are writing primarily to amuse yourself by putting slaps against Islam into writing, and whether the average reader who does not share your opinion will be amused. However, mushing together Rushdie with the Bhagavad-Gita is the low level of scholarship that Uncyclopedians relish.
Now, rather than paring back your text, I suggest you need more text in one area. You will find in How To Be Funny And Not Just Stupid that we view piles of photographs in the same way as we view lists of one-liners: They are departures from the business of writing funny stuff, which sometimes tell the same joke over again, and often induce newbies to make unfunny additions to them. I would prefer that you add new sections that use these photos as jokes in passing, rather than keep them stacked up and drag the reader through them all, as though you had the neighbors over for an awful Home Movie.
Regarding one of my deletions, a list of promised future articles, I am not sure we need a "The Satanic Verses of..." series, as it might be telling the same joke over again. For example, given a successful article in which a serious subject is done in the style of Bobcat Goldthwaite, we don't necessarily need a handful of articles done that way. Cheers! Spıke ¬ 22:24 17-Mar-14
- Please be assured that my primary interest is not to amuse myself but to write a good Uncyclopedic article which shall amuse quite a few people. Taking into account your suggestions, I have made some substantial changes and I hope the article as it stands now looks pretty decent and acceptable? - Alpalwriter (talk) 02:49, March 18, 2014 (UTC)
I do not know the underlying material so my review will be superficial. You are very heavy on the initial quotations. We discourage these at UNQUOTE. Yours are, thankfully, attributed to actual people and do relate both to the utteror and to the theme of the article, but I would go with no more than two short ones, and Oppenheimer stating Shiva as shit should not be your first word; suck the reader in first. I am not saying don't use the material; only develop it later on the page. The puns on names are the weakest humor, and NO'Flattery looks like a typo. The cast is full of red-links, and when you introduce Rushdie, you have to confront the relationship between your version and reality, which spoils the joke. Have your "encyclopedia article writer" be firmly in the alternate universe and unaware that he is. On "is reported to be writing," see CoW#A simple style is most encyclopedic.
Thank you for keeping in check the photo gallery and the tales of gang rape, and I'm sorry I can't do a better job of saying whether the result is a good comedy take on Rushdie and Hinduism or suggest improvements on that front. Spıke ¬ 03:00 18-Mar-14
I've tweaked this article again. Of the two initial quotations that remain, I think that putting the longer one first, which seems more scholarly, will make the Shit quotation outrageous in comparison and therefore funnier. I also arranged the photos and graphics differently. If you find yourself having to dictate spacing with <BR>, you're doing something wrong.
Please do not use large lettering. This detracts from the appearance of an encyclopedia. If you have something large to say, use large language. Also because of the "encyclopedia" cover, don't end things with a moral-of-the-story or cheerleading. I took one of these out of the Did You Know, and there is still one at the very end of the article: a statement of the hopes of Uncyclopedians. Please write something different if you need the article to end with a zinger (many do), something that sounds less like Porky Pig's "That's all, folks!" Spıke ¬ 16:54 18-Mar-14
PS--Thanks. Did you notice that JerryJellyson post-edited you at Bhagavad Gita, working your title a little more into the text there? Incidentally, it's See also, no excess capital letters, just as Wikipedia does. Spıke ¬ 17:05 18-Mar-14
Many thanks indeed for nominating the article for VFH and for the time-to-time guidance and suggestions for improvements which surely have made a big difference! Alpalwriter (talk) 03:13, March 19, 2014 (UTC)
edit Learn2Preview
I hate to be picky, but would you please click on Preview to see how your edits will look, then continue editing and click on Save only at major stopping points? I am called on to review edits of new users (which unfortunately still includes you) and would like to be called on a little less often. Spıke ¬ 01:25 19-Mar-14
PS--But having reviewed them, please use exclamation points with extreme rarity and not followed by some other punctuation. Again, it keeps us from looking like an encyclopedia and doesn't add a lot of funny. Spıke ¬ 01:27 19-Mar-14
edit The Satanic Verses of Bhagavad-gita on VFH
Hi, Apalwriter and welcome here! I don't know what Bhagavad-gita is so I cannot judge your article, but I think you need to be a bit more careful with using the word "shit" (this is a possible reason for Funnybony's comment on VFH). If you need any advice, I would suggest trying to be more objective - objective with humour, which would imply not being objective at all but pretending you are. This would also imply not stating your opinion clearly, but letting the reader judge. Nice job and don't take some comments too seriously! Anton (talk) Uncyclopedia United 19:01, March 19, 2014 (UTC)
edit
Yeah as stated before you probably should start using them to prevent clogging up the recent changes feed. In other news, keep up the good, March 20, 2014 (UTC)
- Thank you very much indeed! I'll keep your instructions in mind. (I almost always Preview, but, sadly, sometimes I only realize improvements little later. But I'll try. Thanks again!) Alpalwriter (talk) 11:05, March 20, 2014 (UTC)
You didn't start it, but that VFH ballot is certainly turning into a Forum or talk page! I'm glad Anton199 is working with you on specific wordings. Also note that, twice on the ballot, Shabidoo, who has had the most specific criticism, invites you to contact him at User talk:Shabidoo if you would like Chapter and Verse. Thank you for being one of the calmer participants during your sudden trial-by-fire! Spıke ¬ 11:55 20-Mar-14
- I've a question. Does the article in its current form at all qualify for Uncyclopedia? Does it at least seem to satisfy the bare minimum requirement for inclusion here? So that I can get an idea where, in the eyes of an experienced user such as you, it stands and how far I've to go with it. I mean how would you rate the article? Many thanks. Alpalwriter (talk) 12:16, March 20, 2014 (UTC)
If it were taken to Votes for deletion, I would vote
- I also think it is worthy of inclusion in the mainspace, just not polished enough for a feature. The transitions in the story it tells are just too sudden, and not logical. Also, it is unclear what Rushdie has to do with Krishna, perhaps this is part of the joke, but it doesn't seem to make sense, even in a loose form. For instance, Rushdie makes a comment, then Krisha suddenly becomes Shame as a result of that comment. Why should this deity be influenced by the comment? I like articles that set up a framework and make sense, then surprise the reader with an unexpected ending. Take or leave my suggestions, but don't let the criticism discourage you from writing. You seem to be a promising new writer. -- Simsilikesims(♀UN) Talk here. 22:25, March 20, 2014 (UTC)
- Many thanks for your feedback.
Two things: 1. The framework is already set up in the Plot. 2. Rushdie's comment is just one of many logical accusations brought against Krishna by the team of 5 people. The thin line between Rushdie's dialogue and Krishna's dialogue is supposed to indicate that the former is not immediately followed by the latter. If it was followed, there wouldn't be a line, as there isn't one in a dialogue between Doniger and Krishna. Alpalwriter (talk) 22:37, March 20, 2014 (UTC)
Yes, that is a very important part of writing fantasy in a satire encyclopedia: that it (and its transitions) have a connection to something real; otherwise you won't bring your reader along. You have said on VFH that the connection is in the text, but few of your readers — and none of your reviewers/voters here — know the text. Spıke ¬ 22:30 20-Mar-14
- Hi, good to meet you. As I say on the voting page, you could masterpiece this one. You seem to be a deep thinker, know your stuff, and will learn to do it better as time goes by. It took me almost four months to get my first feature, and I have at least a dozen by now. Religion and the honoring of some forms of conscious-religions set a high-bar for satire, imnho, and you seem to be someone who can get over that. When the dust settles hopefully Funnybony and you can hang out, he'd be a great source for a page such as this, but not in the form that it was nommed. And comments aside, Funnybony does know the Gita material, and spent many years studying in India. A fine fellow well met. Anyway, enjoy, and yes, most of the pages on the site are worth their weight in pixels and nothing more! Aleister 22:47 20=3=14
edit More alternatives
With your Satanic Verses VFH nomination, you are now serving three masters: (1) The desire to make Uncyclopedia readers laugh; (2) the desire to make VFH voters vote yes; and (3) whatever point you originally wrote the article to make. Sometimes, when one has three criteria, one satisfies none of them successfully.
One strategy is to go to Shabidoo for assistance; or request a formal Pee Review. ChiefjusticeDS has just returned to the website, who specializes in useful advice. You have already encountered him at VFH, but only to say that the rest of us are overheating.
Another strategy (for you, not for the article) is to abandon the article, let it go down to defeat (it will remain in the encyclopedia and you won't have a hand lopped off), and pursue something different where you neither need to tell a story nor to win a vote. Pursuing a narrower definition of success might get you there, and we all need small successes in the early stages. The attempt to get on the main page (you may blame me) is perhaps not the best thing for you.
The two typical ways to find something new to write is to look at the requests for new articles, and to visit votes for deletion, where you might find a bad article about to be deleted from the website that you can save. Spıke ¬ 00:19 21-Mar-14
- Many thanks for the advice! However, I believe I can serve all three masters by serving the higher & true master: To write a great satirical article. It'll make Uncy readers laugh, make VFH voters vote yes, and fulfill my original purpose. If the article as it stands makes you feel that it has inner contradictions, that sometimes it is too cheap (when it talks about sex) and sometimes it is too profound (when it talks about metaphysical philosophy), it is I think only because the article is not so finished yet. For example, I could add more dialogues that talk about metaphysics. I'd certainly go to Shabidoo for assistance if the need be. Alpalwriter (talk) 00:37, March 21, 2014 (UTC)
Inspiring! Go for it! Of course, as Aleister notes above, "unfinished" articles are not usually nominated for VFH; but as I note above, you may blame me. (On the other hand, "metaphysics" doesn't make anyone laugh.) Spıke ¬ 00:42 21-Mar-14
- Correct me if I'm wrong, but metaphysics can make people laugh; contradictions and paradoxes can make people laugh; "metaphysical satire" as they call it, I think. I feel this article, owing to the complex nature of its basic topic, could be interesting & enjoyable for a very wide variety of audience. Isn’t that a good thing? Alpalwriter (talk) 01:27, March 21, 2014 (UTC)
Metaphysics never made me laugh. Hell, Calculus never even made me laugh. Carry on, then. Spıke ¬ 01:36 21-Mar-14
- I personally enjoy and have a personal history in metaphysics, and when I mention consciousness info it's something I try to include in many of my articles, although just centered in some. In a little of the stuff I've written here I put in quite a bit of educational material, as I see satire as often both enlightening and as a way to communicate little-known data as well as once in awhile pass along some mind-bending concepts (not everything I write is "funny" per se, to me funny is a by-product of satire but not it's final goal. Spike and I may disagree on that, but a site like this one needs many points of view). I won't read your page for awhile, as I can see you're working on it at a fever pace - which is the way to go sometimes - and for me it's better to read an article in its final stages. When you do feel comfortable that it's at a good point SPike's idea of asking Chief Justice for a peer review may be the way to go - Chief is a master at those and you'd be lucky if he did one for you. Aleister 2:40 20-3-14
edit Make up your mind
The image you swapped out from {{India}} was also used in Curry. I made the same change there and deleted the old .gif, where the uploader said it had been stolen. Now you have uploaded a new image of the Taj Mahal. Please be sure both pages use the same thing when you are done, and use UN:QVFD to request deletion of any images that are abandoned for something better. Spıke ¬ 15:49 26-Mar-14
- I've so far uploaded some images that I used in earlier versions of my articles but later removed for something better and now I may never use those images in future such as this one. Do you want me to go and add "QVFD" on each and every one of them?? I mean is that what you were really asking me to do? It appears most of them have some satirical value and may be used by someone else in some other article here in future. Alpalwriter (talk) 16:27, March 26, 2014 (UTC)
If you do indeed have "something better" then please list the old, "worse" one on QVFD to help clean up the site. There is no controversy in asking that your own, orphaned photos be deleted. If, in your opinion, the photo is begging to be used by someone else, then you can leave it on the website, but please type in such a complete description (with Categories) that people seeking such a photo will be able to find it; for example, don't assume it will be found by its name alone. Spıke ¬ 16:42 26-Mar-14
PS--Please go to UN:QVFD and list the images to be deleted there. The images themselves don't have to be tagged, and in fact we have no way to locate tags on individual images. Spıke ¬ 17:14 26-Mar-14
- Is it okay if I just leave the "QVFD" tag I put on the image pages as it is? Or should I go and remove it (or undo it)? Please let me know. Thanks. Alpalwriter (talk) 17:37, March 26, 2014 (UTC)
- Ah, I see, all deleted, okay, thanks! Alpalwriter (talk) 17:44, March 26, 2014 (UTC)
edit Template:India
You might read the template's talk page and User talk:InMooseWeTrust. This template is getting huge, and that user tried to make it much larger to illustrate by example the diversity and disorder of India, but that is too much to pack into a template. Number bases has a passing connection to India but is not something the reader of the other articles will want to link to. The template should serve the reader by picking good next articles, not everything with some connection. Spıke ¬ 22:24 27-Mar-14
- Unless the connection is articles rewritten (either in part or in full) by me that became features. But I agree - Number Bases fits in with the {{math}} template, not {{India}}. Due to the relationship to India it has been added to the See also section of India though. • Puppy's talk page • 03:42 am 30 Mar 2014
edit Anu Malik
Well-spotted! But this has been on the site since 2006, and the author won't see some tag. I have nominated it at Votes for deletion. Come vote! Spıke ¬ 22:30 27-Mar-14
PS--PuppyOnTheRadio saw it at VFD and knew that this was once a good article that had had its humor replaced by dry facts. I have restored it to its past glory and withdrawn my nomination. Spıke ¬ 20:18 29-Mar-14
- Are you sure you have restored it to its past glory? As far as I can see, there is no change at all since you added VFD to the article on March 27, 2014, at 22:28. Alpalwriter (talk) 21:26, March 29, 2014 (UTC)
Thanks for bringing this to my attention! What happened is that I clicked Save and closed the window (to save megabytes on my metered service) and did not see that, as the restored article had a link to another website, my own Abuse Filter demanded that I confirm my edit before saving it. It is fixed now. Spıke ¬ 21:38 29-Mar-14
PS—We have a new VFD Poopsmith and you should let him tidy up articles after the ballot is closed. Spıke ¬ 22:44 29-Mar-14
PPS—Mimo&maxus has reverted your addition of Anu.jpg to the start of this article. Evidently Malik looks like Dench. I don't get it, but would you two please talk to each other and arrive at the funniest result? Spıke ¬ 23:00 29-Mar-14
edit Talk:G-Wiz
I presume you are talking to me here, but it is dicey to post on the talk page of a random article and assume I am monitoring all changes to the wiki (though it is true at the current level of activity). I agree it is stubby and not very funny. Like the last one, it is too old to dispose of by tagging (see its History). You can nominate it at VFD yourself, and I will vote Delete, but mind the instructions (add {{VFD}} to the article, and don't exceed 20 active ballots on the page). Spıke ¬ 22:55 27-Mar-14
edit The award!
Great job with your articles and your userpage now has a new template! Congratulations! Anton (talk) Uncyclopedia United 13:06, March 29, 2014 (UTC)
- That's great! Thank you very much! Alpalwriter (talk) 14:14, March 29, 2014 (UTC)
edit Malala Yousafzai
Yousafzai's fateful mistake may have been her choice of weapon.
This article in your userspace is beginning with a comedy theme of Slut Humor which, as far as I can tell, is not based on anything in real life, and we already have too much Slut Humor on-site.
As I interpret the Wikipedia article on her, she had made her life work the universal training of accurate marksmanship to all Pakistanis. This is what led Gordon Brown to start his UN petition campaign called "Teach everyone to shoot straight." The incident that propelled her to worldwide fame was either
- Taliban disagreeing with her implication that they were inaccurate shooters, or
- Taliban who had benefitted from her education campaign and wanted to show her so.
What do you think? Spıke ¬ 01:26 30-Mar-14
- That's very intelligent and interesting! Alpalwriter (talk) 01:33, March 30, 2014 (UTC)
Both attributes are frowned on here...but you may use the idea anyway.... Spıke ¬ 01:37 30-Mar-14
- I honestly think your idea is pretty intelligent and interesting but I don't find it that funny. Would it at all be okay if I continue with my slut humour theme and eventually move the article in the mainspace? Alpalwriter (talk) 01:54, March 30, 2014 (UTC)
No one tells an Uncyclopedian not to write humor! But if you think the Slut approach is preferable, I wonder why. Also, I like my concept so much that I might write a competing article along those lines, given that you don't want to use it. Spıke ¬ 12:59 30-Mar-14
With apologies, I am InB4U. Spıke ¬ 14:53 30-Mar-14
- No problem. Congrats! Alpalwriter (talk) 14:55, March 30, 2014 (UTC)
edit Knowledge
Sorry if I stood on you toes changing that caption. Saw the cracked paint on the image and couldn't resist.
Are you thinking of rewriting this article in a more significant manner? I have a couple of sketch ideas that could work, but the problem I have with the article at present is a lack of cohesive concept. It jumps from one idea to another. Let me know what you have planned. (After all, I could always go back an write a proper article for Epistemology instead.) • Puppy's talk page • 03:31 am 30 Mar 2014
- That’s fine.
- No, I’m afraid I’m not thinking of rewriting the article. Alpalwriter (talk) 05:56, March 30, 2014 (UTC)
edit Fallacy
I don't think this article needs a Wikipedia template as the reader would know what fallacy is being a common word in the English language. Wikipedia templates are usually only used when the subject topic is obscure or when the article directly parodies the wikipedia page and so requires a link for comparison otherwise it ruins the joke of a parody site. I'll remove the template now but please write here if you think there is a reason why it should be on the article just let me know:46, March 30, 2014 (UTC)
- Your reason for removal seems to outweigh my reason for inclusion. Thanks for removing it. Alpalwriter (talk) 10:57, March 30, 2014 (UTC)
edit User:Alpalwriter/Everybody Draw Mohammed Day
Just having a look at this article and I'm not getting the funny here. I understand that there is the restriction on Muhammad images, but the topic is covered so well in articles like Political cartoon or with images like File:Mohammed with sausages.jpg or File:Mohammed.jpg - or a number of images in Category:Muhammad. I don't see how the dogs on the beach or the picture of a pig are funny. Crass, definitely, but not funny.
Is there a point behind this - other than trying to break a taboo - that I'm missing here?
Anyways, I've moved it back to your user space as it's not fleshed out enough to be an article in its own right. Let me know if there's something I've missed as - as it stands - it's QVFD material. • Puppy's talk page • 11:19 am 03 Apr 2014
- Since Islam treats pigs as unclean and kind of prohibited creatures, depicting the prophet as a baby pig is I think funny.
- For a dog, getting fucked (perhaps for the very first time) by another dog, is kind of a revelation, which I see as funny. Alpalwriter (talk) 11:31, April 3, 2014 (UTC)
- Our webhost, by comparison, sees stuff like this as "delete on sight." I don't care if it's from Wikipedia. Spıke ¬ 11:38 3-Apr-14
- I'd actually change this into an article, rather than a collection of random images designed to shock rather than amuse. Make it a parody of WP:Victory Day (United States) with elements of WP:Jyllands-Posten Muhammad cartoons controversy included. That Muhammad sausage cartoon covers the piggy element well without being overtly crass. Make it a national holiday in Denmark that is no longer being celebrated except in some obscure area, celebrating the artwork of Dutch masters.
- Having said that, read through HTBFANJS before trying to create an article from scratch. Keep working on improving articles that already exist, and use that to learn how to write funny before trying to leap without a net. My first few articles I created were terrible, but the more I worked on articles that others had written, the more I learned, and the better I wrote. • Puppy's talk page • 12:06 pm 03 Apr 2014
- Dittos. This second comic-book contribution of yours has the obvious point not of humor but of overt blasphemy. (Not that we mind blasphemy, when in the service of humor.) The entire point seems to be to disparage Islam — in a way that's just funny enough to seem to belong on this website. That is polemics, not comedy. Spıke ¬ 12:47 3-Apr-14 | http://uncyclopedia.wikia.com/wiki/User_talk:Alpalwriter | CC-MAIN-2014-52 | refinedweb | 4,931 | 68.91 |
GNU Smalltalk 3.0c
By Paolo Bonzini - Posted on August 9th, 2008
GNU Smalltalk 3.0c will shortly be available from
Version 3.0c is a feature complete development release. The new features compared to 3.0b are:
- Collections and Streams have a common superclass, Iterable. The user-visible aspect of this is that Streams now enjoy a wider range of iteration methods, such as #anySatisfy:, #detect: and #count:.
- Error backtraces include line numbers and filenames.
- FileDescriptor and FileStream raise an exception if #next: cannot return the given number of bytes.
- FileDescriptor is now a subclass of Stream. Its old superclass ByteStream has been removed.
- Functions gst_async_signal and gst_async_signal_and_unregister are now thread-safe, *not* async-signal-safe. To trap signals from Smalltalk, you have to use ProcessorScheduler>>#signal:onInterrupt:.
- ObjectDumper now accepts normal String streams. The old superclass ByteStream has been removed.
- Streams have a set of new methods that allow to eliminate useless copies when moving data from stream to stream, as well as to eliminate useless creation of collections to store the data read from a stream. Besides the standard methods #next, #nextPut: and #atEnd, two more methods can be implemented by Stream subclasses in order to achieve better performance on block transfers, namely #nextAvailable:into:startingAt:, #nextAvailable:putAllOn: and #next:putAll:startingAt:. Another set of methods is implemented by Stream; they all use the above three methods and you should not need to override them. These are #next:into:startingAt:, #next:putAllOn:, #nextAvailable:, #nextAvailable:putAllOn:, #nextAvailablePutAllOn:.
- Together with the above changes, Stream>>#nextHunk was removed. Applications can use #nextAvailable: or, better, should be rewritten to use new stream-to-stream protocol such as #nextAvailablePutAllOn:.
- Support for imports were added to namespaces (via the <import: ...> pragma, as for classes). Unlike the superspace, imports are not made visible through #at:.
- The sockets package (and the namespace it is installed in) was renamed from TCP to Sockets. While the old namespace is still available for backwards compatibility, it is suggested to use the Sockets namespace instead. This was done because the package now supports IPv6 and AF_UNIX sockets too.
- Bindings to OpenGL and GLUT were contributed by Olivier Blanc.
- All the changes between 3.0.3 and 3.0.4 are included. | http://smalltalk.gnu.org/news/gnu-smalltalk-3-0c | CC-MAIN-2016-36 | refinedweb | 372 | 60.11 |
Closed Bug 596614 Opened 12 years ago Closed 12 years ago
focusing the URL field on the awesomescreen should not visibly change categories
Categories
(Firefox for Android Graveyard :: General, defect)
Tracking
(fennec2.0b2+)
People
(Reporter: madhava, Assigned: vingtetun)
References
Details
Attachments
(2 files, 5 obsolete files)
In this situation: - tap title to go to awesomescreen - on awesomescreen, tap on any category other than "All pages" (e.g. Bookmarks) - focus url field again currently, the "All Pages" category is visibly chosen. Even though the resulting set of search items during a search "belongs" to All Pages, we shouldn't visibly switch. When we do (currently) it means that the screen changes twice (first category switch and then result set showing up) _and_ the screen changes in a way that is not entirely expected. Instead, in the case of bookmarks, for example, the Bookmarks category should remain selected (and its content on screen) until the user's typing causes a result set to start appearing.
blocking2.0: --- → ?
Summary: focusing the URL field on the awesomescreen should not visible change categories → focusing the URL field on the awesomescreen should not visibly change categories
blocking2.0: ? → ---
tracking-fennec: --- → ?
OS: Mac OS X → All
Hardware: x86 → All
Version: 1.9.2 Branch → Trunk
I'm a bit afraid that the user will think that he is searching _only_ into his bookmarks or into his history if we do that.
tracking-fennec: ? → 2.0b2+
Assignee: nobody → 21
Currently, when the user taps the URLBar, we switch to the "All Pages" mode - selecting the "All Pages" button and showing the default list of results. I kinda agree with Vivien. If we leave the screen in say "Bookmarks", with the bookmark list displayed, the user might think they are searching/filtering the bookmark list. Beltzner - Thoughts?
The patch is still failing with the VKB on Android, touching the urlbar while you are in an other categories does not bring up the VKB (the field is still readOnly)
(In reply to comment #2) > I kinda agree with Vivien. If we leave the screen in say "Bookmarks", with the > bookmark list displayed, the user might think they are searching/filtering the > bookmark list. > As I've said on IRC I've start to change my mind when playing with the code. I'm currently hesitant between the two options, I don't want to confuse the users but not switching the current screen give a much better feeling when you use it.
This patch works with the VKB and correct bug 591955. It still needs to be improved: * there is a bug dismissing the first letter typed in sometimes * the whole text should be selected when going from a panel to the "All Pages" panel
Attachment #478289 - Attachment is obsolete: true
This one works fine, it still fix bug 591955 and also select the urlbar text the right way when clicking (double click select all seems to be broken, even without this patch, I will check that into an other bug)
Attachment #478812 - Attachment is obsolete: true
Attachment #478916 - Flags: review?(mark.finkle)
Sorry to take so long here; wanted to check with Madhava to understand the original design intent before I made a decision. The intent of the design is that the moment the user begins *typing*, the list of categories disappears, and the only thing shown is the list of filtered items. As this bug points out, though, this leads to an interim state where just selecting the URL field causes there to be a mode switch, which is jittery and potentially confusing. I agree with comment 0; yes, there's a chance that the user will think that they're filtering entirely on the selected category, but it's the cleanest way to execute the interaction with the current design.
Comment on attachment 478916 [details] [diff] [review] Patch > <handler event="keypress" phase="capturing"> > <![CDATA[ > if (event.keyCode == event.DOM_VK_RETURN) > setTimeout(function() { BrowserUI.activePanel = null }, 0); >- else if (this.readOnly) >- this.readOnly = false; >+ else if (BrowserUI.activePanel != AllPagesList) >+ BrowserUI.activePanel = AllPagesList; Someday we should consider removing the explicit calls to BrowserUI and use events or callbacks to handle communicating to the main app. >+ <handler event="keypress" phase="bubbling"> >+ <![CDATA[ >+ // Disable the read-only state in landscape if there is a keypress >+ // because this means there is a kind of hardware keyboard >+ this.readOnly = false; How do we know it's landscape now? How do we know it's a hardware keyboard? >diff -r 8447b3f08dff chrome/content/browser-ui.js >--- a/chrome/content/browser-ui.js Fri Sep 24 19:19:50 2010 -0700 >+++ b/chrome/content/browser-ui.js Tue Sep 28 01:49:29 2010 +0200 >@@ -165,18 +165,23 @@ var BrowserUI = { > this._updateButtons(browser); > this._updateIcon(browser.mIconURL); > this.updateStar(); > }, > > showToolbar: function showToolbar(aEdit) { > this.hidePanel(); > this._editURI(aEdit); >- if (aEdit) >+ if (aEdit) { > this.showAutoComplete(); >+ >+ // Selecting the text is done after showing the autocomplete because >+ // pushDialog remove the selection if it is done before >+ this._edit.select(); Why not put this in the showAutoComplete call? Do we need to obey any preferences when selecting? > // URL textbox events > case "click": >- this.doCommand("cmd_openLocation"); >+ // Don't call the command if there is currently a panel opened, this >+ // way the current panel is not visibly changed until the user starts >+ // to type (bug 596614) >+ if (this.activePanel) { >+ if (this._edit.readOnly) { >+ this._edit.readOnly = false; >+ this._edit.blur(); >+ gFocusManager.setFocus(this._edit, Ci.nsIFocusManager.FLAG_NOSCROLL); >+ >+ if (this._edit.clickSelectsAll) >+ this._edit.select(); I don't like having logic for the URLBar in some many locations in the code >+ else >+ this.doCommand("cmd_openLocation"); Use {}
Comment on attachment 478916 [details] [diff] [review] Patch waiting for new patch
Attachment #478916 - Flags: review?(mark.finkle) → review-
Completely revamped patch: * no more BrowserUI calls inside bindings.xml * the blur/focus logic for the IME state is now attached to the readOnly property of the field which prevent browser-ui.js to care about it * We finally respect the clickSelectsAll property of textbox.xml instead of always selecting all the text * the code related to panel switching into browser-ui.js is done into function closely related to panel * all tests stays green!
Attachment #478916 - Attachment is obsolete: true
Attachment #481217 - Flags: review?(mark.finkle)
Comment on attachment 481217 [details] [diff] [review] Patch v0.2 >diff -r 5cc57f96e2f3 chrome/content/bindings.xml > <method name="invalidate"> > let controller = this.input.controller; > let searchString = controller.searchString; > let items = this._items; >- > // Need to iterate over all our existing entries at a minimum, to make > // sure they're either updated or cleared out. We might also have to > // add extra items. Keep the blank line >diff -r 5cc57f96e2f3 chrome/content/browser-ui.js > >+ this._edit.readOnly = !(aPanel == AllPagesList && Util.isPortrait()); >+#ifndef ANDROID >+ // On devices (and desktop) where it can exists harware keyboard, leave the >+ // focus on the field to allow direct input >+ if (this._edit.readOnly && aPanel != AllPagesList) >+#endif >+#ifdef ANDROID >+ if (this._edit.readOnly) >+#endif >+ this.blurFocusedElement(); I don't think we can hardcode that Android does not have a hard keyboard (and that Meego does have a hard keyboard). The T-mobile G2 (android) has a hard keyboard. > // Give the new page lots of room > Browser.hideSidebars(); > this.closeAutoComplete(true); >+ this.activePanel = null; Shouldn't we put the | activePanel = null | in the closeAutoComplete method? Just asking (just looked - it already is in the closeAutoComplete method so remove it from here) r- for the hardcoded Android code. We need to avoid that
Attachment #481217 - Flags: review?(mark.finkle) → review-
I've replaced the #ifdef by a keydown listener on the window
Attachment #481217 - Attachment is obsolete: true
Attachment #481254 - Flags: review?(mark.finkle)
Attachment #481254 - Flags: review?(mark.finkle) → review+
(In reply to comment #13) > I am currently trying to fix a annoying bug discovered while using a custom build with this patch checked. Sometimes the software keyboard does not appear once the awesome bar is opened. Actually my steps to reproduce are: * launch fennec without any network connection * go to the awesome bar and click on a remote page * go to the awesome bar and click on a remote page (yes, another time) * go to the awesome bar Actual result: * No software keyboard Expected result: * A software keyboard I'm not sure of what's happening here, it sounds like a race condition
The vkb has been hidden/displayed until my device crashed! Yeah! (I really need to find a way to debug the VKB on desktop)
fix a little bug
Attachment #481872 - Attachment is obsolete: true
Attachment #481915 - Flags: review?(mark.finkle)
Comment on attachment 481915 [details] [diff] [review] Patch v0.4 Looks like we could use some tests for this too :)
Attachment #481915 - Flags: review?(mark.finkle) → review+
(In reply to comment #17) > Comment on attachment 481915 [details] [diff] [review] > Patch v0.4 > > Looks like we could use some tests for this too :) I could add test into some of its dependencies, my main problem is much of the pain was for having the virtual keyboard working on device but i'm really not sure how to test that?
Status: NEW → RESOLVED
Closed: 12 years ago
Resolution: --- → FIXED
This isn't fixed in builds when reproducing the steps in comment #0 : Mozilla/5.0 (Maemo; Linux armv71; rv:2.0b8pre) Gecko/20101011 Namoroka/4.0b8pre Fennec/4.0b2pre and Mozilla/5.0 (Android; Linux armv71; rv:2.0b8pre) Gecko/20101011 Namoroka/4.0b8pre Fennec/4.0b2pre
Status: RESOLVED → REOPENED
Resolution: FIXED → ---
As per discussion with aakashd on IRC, this is actually fixed. Verified on: Mozilla/5.0 (Maemo; Linux armv71; rv:2.0b8pre) Gecko/20101011 Firefox/4.0b8pre Fennec/4.0b2pre and Mozilla/5.0 (Android; Linux armv71; rv:2.0b8pre) Gecko/20101011 Firefox/4.0b8pre Fennec/4.0b2pre
Status: REOPENED → RESOLVED
Closed: 12 years ago → 12 years ago
Resolution: --- → FIXED
Status: RESOLVED → VERIFIED | https://bugzilla.mozilla.org/show_bug.cgi?id=596614 | CC-MAIN-2022-27 | refinedweb | 1,639 | 55.95 |
selection lines that are used to indicate which files are added to the database. Third, macro lines define or undefine variables within the config file. Lines beginning with # are ignored as comments.
CONFIG LINES
These lines have the format parameter=value. See URLS for a list of valid urls. database The url from which database is read. There can only be one of these lines. If there are multiple database lines then the first is used. is used. If --verbose or -V is used then the value from that is used. The default is 5. If verbosity is 20 then additional report output is written when doing --check, --update or --compare. report_url The url that the output is written to. There can be multiple instances of this parameter. Output is written to all of them. The default is stdout. gzip_dbout Whether the output to the database is gzipped or not. Valid values are yes,true,no and false. The default is no. This option is available only if zlib support is compiled in. acl_no_symlink_follow Whether to check ACLs for symlinks or not. Valid values are yes,true,no and false. The default is to follow symlinks. This option is available only if acl support is compiled in. warn_dead_symlinks Whether to warn about dead symlinks or not. Valid values are yes,true,no and false. The default is not to warn about dead symlinks. not to summarize the changes. The general format is like the string YlZbpugamcinCAXSE, where Y is replaced by the file-type (f for a regular file, d for a directory, L for a symbolic link, D for a character device, B for a block device, F for a FIFO, s for a unix socket, | for a Solaris door, ! listed in ignore_list_attributes Special group definition that lists parameters which are always printed in the final report for changed files. ignore_list Special group definition that lists parameters which are to be ignored from the final report. config_version The value of config_version is printed in the report and also printed to the database. This is for informational purposes only. It has no other functionality. Group definitions If the parameter is not one of the previous parameters then it is regarded as a group definition. Value is then regarded as an expression. Expression is of the following form. <predefined group>| <expr> + <predefined group> | <expr> - <predif. Special characters in your filenames can be escaped using two-digit URL encoding (for example, %20 to represent a space). Following the regular expression is a group definition as explained above. See EXAMPLES and doc/aide.conf for examples. More in-depth discussion of the selection algorithm can be found in the aide manual.
MACRO LINES
@@define VAR val Define variable VAR to value val. @@undef VAR Undefine variable VAR. @@ifdef VAR, @@ifndef VAR @@ifdef begins an if statement. It must be terminated with an @@endif statement. The lines between @@ifdef and @@endif are used if variable VAR is defined. If there is an @@else statement then the part between @@ifdef and @@else is used is VAR is defined otherwise the part between @@else and @@endif is used. @@ifndef reverses the logic of @@ifdef statement but otherwise works similarly. @@ifhost hostname, @@ifnhost hostname @@ifhost works like @@ifdef only difference is that it checks whether hostname equals the name of the host that aide is running on. hostname is the name of the host without the domainname (hostname, not hostname.aide.org). @@{VAR} @@{VAR} is replaced with the value of the variable VAR. If variable VAR is not defined an empty string is used. Unlike Tripwire(tm) @@VAR is NOT supported. One special VAR is @@{HOSTNAME} which is substituted for the hostname of the current system. @@else Begins the else part of an if statement. @@endif Ends an if statement. @@include VAR Includes the file VAR. The content of the file is used as if it were inserted in this part of the config file.
URLS
Urls can be one of the following. Input urls cannot be used as outputs and vice versa. stdout stderr Output is sent to stdout,stderr respectively. stdin Input is read from stdin. Input is read from filename or output is written to filename. fd:number Input is read from filedescriptor number or output is written to number.
DEFAULT GROUPS
p: permissions ftype: file type i: inode l: link name n: number of links u: user g: group s: size b: block count m: mtime a: atime c: ctime S: check for growing size I: ignore changed filename ANF: allow new files ARF: allow removed files md5: md5 checksum sha1: sha1 checksum sha256: sha256 checksum sha512: sha512 checksum rmd160: rmd160 checksum tiger: tiger checksum haval: haval checksum crc32: crc32 checksum R: p+ftype+i+l+n+u+g+s+m+c+md5 L: p+ftype+i+l+n+u+g E: Empty group >: Growing logfile p+ftype+l+u+g+i+n+S And also the following if you have mhash support enabled gost: gost checksum whirlpool: whirlpool checksum The following are available and added to the default groups R, L and > only when explicitly enabled using configure acl: access control list selinux: selinux attributes xattrs: extended attributes e2fsattrs: file attributes on a second extended file system Please note that 'I' and 'c' are incompatible. When the name of a file is changed, it's ctime is updated as well. When you put 'c' and 'I' in the same rule the, a changed ctime is silently ignored. When 'ANF' is used, new files are added to the new database, but are ignored in the report. When 'ARF' is used, files missing on disk are omitted from the new database, but are ignored in the report.
EXAMPLES
/ R This adds all files on your machine to the database. This is one line is a fully qualified configuration file. !/dev This ignores the /dev directory structure. =/tmp Only /tmp is taken into the database. None of its children are added. All=p+i+n+u+g+s+m+c+a+md5+sha1+tiger+rmd160 This line defines group All. It has all attributes and all md checksum functions. If you absolutely want all digest functions then you should enable mhash support and add +crc32+haval+gost to the end of the definition for All. Mhash support can only be enabled at compile-time.
HINTS
=) | http://manpages.ubuntu.com/manpages/oneiric/en/man5/aide.conf.5.html | CC-MAIN-2015-18 | refinedweb | 1,060 | 67.04 |
Language Overview
Go Up to Delphi Language Guide Index. For the most part, descriptions and examples in this language guide assume that you are using Embarcadero development tools.
Most developers using Embarcadero software development tools write and compile their code in the integrated development environment (IDE). Embarcadero development tools handle many details of setting up projects and source files, such as maintenance of dependency information among units. The product also places constraints on program organization that are not, strictly speaking, part of the Delphi language specification. For example, Embarcadero development tools enforce certain file- and program-naming conventions that you can avoid if you write your programs outside of the IDE and compile them from the command prompt.
This language guide generally assumes that you are working in the IDE and that you are building applications that use the Visual Component Library (VCL). Occasionally, however, Delphi-specific rules are distinguished from rules that apply to all Delphi programming.
This section covers the following topics:
- Program Organization. Covers the basic language features that allow you to partition your application into units and namespaces.
- Example Programs. Small examples of both console and GUI applications are shown, with basic instructions on running the compiler from the command-line.
Contents
Program Organization
Delphi programs are usually divided into source-code modules called units. Most programs begin with a program heading, which specifies a name for the program. The program heading is followed by an optional uses clause, then a block of declarations and statements. The usesfiles, header files, or preprocessor "include" directives.
Delphi Source Files
The compiler expects to find Delphi source code in files of three kinds:
- Unit source files (which end with the .pas extension)
- Project files (which end with the .dpr extension)
- Package source files (which end with the
.dpkextension)
Unit source files typically contain most of the code in an application. Each application has a single project file and several unit files; the project file, which corresponds to the program file in traditional Pascal, organizes the unit files into an application. Embarcadero development tools automatically maintain a project file for each application.
If you are compiling a program from the command line, you can put all your source code into unit (.pas) files. If you use the IDE to build your application, it will produce a project (.dpr) file.
Package source files are similar to project files, but they are used to construct special dynamically linkable libraries called packages.
Other Files Used to Build Applications
In addition to source-code modules, Embarcadero products use several non-Pascal files to build applications. These files are maintained automatically by the IDE, and include
- VCL form files (which have a .dfm extension on Win32)
- Embarcadero the Project Options dialog.
Various tools in the IDE store data in files of other types. Desktop settings (.dsk) files contain information about the arrangement of windows and other configuration options; desktop settings can be project-specific or environment-wide. These files have no direct effect on compilation.
Compiler-Generated Files
The first time you build an application or a package, the compiler produces a compiled unit file (.dcu on Win32) for each new unit used in your project; all the .dcu files in your project are then linked to create a single executable or shared package. The first time you build a package, the compiler produces a file for each new unit contained in the package and then creates both a .dcp and a package file. If you use the GD compiler switch, the linker generates a map file and a .drc file; the .drc file, which contains string resources, can be compiled into a resource file.
When you build a project, individual units are not recompiled unless their source (.pas) files have changed since the last compilation, their .dcu/.dpu files cannot be found, you explicitly tell the compiler to reprocess them, or the interface of the unit depends on another unit which has been changed. In fact, it is not necessary for a unit's source file to be present at all, as long as the compiler can find the compiled unit file and that unit has no dependencies on other units that have changed.
Example Programs
The examples that follow illustrate basic features of Delphi programming. The examples show simple applications that would not normally be compiled from the IDE; you can compile them from the command line.
A Simple Console Application
The program below is a simple console application that you can compile and run from the command prompt:
program Greeting; {$APPTYPE CONSOLE} var MyMessage: string; begin MyMessage := 'Hello world!'; Writeln(MyMessage); end.
The first line declares a program called Greeting. The {$APPTYPE CONSOLE} directive tells the compiler that this is a console application, to be run from the command line. The next line declares a variable called MyMessage, which holds a string. (Delphi has genuine string data types.) The program then assigns the string "Hello world!" to the variable MyMessage, and sends the contents of MyMessage to the standard output using the Writeln procedure. (Writeln is defined implicitly in the System unit, which the compiler automatically includes in every application.)
You can type this program into a file called greeting.pas or greeting.dpr and compile it by entering:
dcc32 greeting
to produce a Win32 executable.
The resulting executable prints the message Hello world!
Aside from its simplicity, this example differs in several important ways from programs that you are likely to write with Embarcadero development tools. First, it is a console application. Embarcadero development tools are most often used to write applications with graphical interfaces; hence, you would not ordinarily call Writeln. Moreover, the entire example program (save for Writeln) is in a single file. In a typical GUI application, the program heading the first line of the example would be placed in a separate project file that would not contain any of the actual application logic, other than a few calls to routines defined in unit files.
A More Complicated Example
The next example shows a program that is divided into two files: a project file and a unit file. The project file, which you can save as greeting.dpr, looks like this:
program Greeting; {$APPTYPE CONSOLE} uses Unit1; begin PrintMessage('Hello World!'); end.
The first line declares a program called greeting, which, once again, is a console application. The uses Unit1; clause tells the compiler that the program greeting depends on a unit called Unit1. Finally, the program calls the PrintMessage procedure, passing to it the string Hello World! The PrintMessage procedure is defined in Unit1. Here is the source code for Unit1, which must be saved in a file called Unit1.pas:
unit Unit1; interface procedure PrintMessage(msg: string); implementation procedure PrintMessage(msg: string); begin Writeln(msg); end; end.
Unit1 defines a procedure called
PrintMessage that takes a single string as an argument and sends the string to the standard output. (In Delphi, routines that do not return a value are called procedures. Routines that return a value are called functions.)
Notice that
PrintMessage is declared twice in
Unit1. The first declaration, under the reserved word interface, makes
PrintMessage available to other modules (such as
greeting) that use
Unit1. The second declaration, under the reserved word implementation, actually defines
PrintMessage.
You can now compile Greeting from the command line by entering
dcc32 greeting
to produce a Win32 executable.
There is no need to include
Unit1 as a command-line argument. When the compiler processes
greeting.dpr, it automatically looks for unit files that the
greeting program depends on. The resulting executable does the same thing as our first example: it prints the message
Hello world!
A VCL Application
Our next example is an application built using the Visual Component Library (VCL) components in the IDE. This program uses automatically generated form and resource files, so you won't be able to compile it from the source code alone. But it illustrates important features of the Delphi Language. In addition to multiple units, the program uses classes and objects.
The program includes a project file and two new unit files. First, the project file:
program Greeting; uses Forms, Unit1, Unit2; {$R *.res} { This directive links the project's resource file. } begin { Calls to global Application instance } Application.Initialize; Application.CreateForm(TForm1, Form1); Application.CreateForm(TForm2, Form2); Application.Run; end.
Once again, our program is called greeting. It uses three units: Forms, which is part of VCL; Unit1, which is associated with the application's main form (Form1); and Unit2, which is associated with another form (Form2).
The program makes a series of calls to an object named Application, which is an instance of the Vcl.Forms.TApplication class defined in the Forms unit. (Every project has an automatically generated Application object.) Two of these calls invoke a Vcl.Forms.TApplication method named CreateForm. The first call to CreateForm creates Form1, an instance of the TForm1 class defined in Unit1. The second call to CreateForm creates Form2, an instance of the TForm2 class defined in Unit2.
Unit1 looks like this:
unit Unit1; interface uses SysUtils, Types, Classes, Graphics, Controls, Forms, Dialogs; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); end; var Form1: TForm1; implementation uses Unit2; {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin Form2.ShowModal; end; end.
Unit1 creates a class named
TForm1 (derived from Vcl.Forms.TForm) and an instance of this class
Form1. The
TForm1 class includes a button --
Button1, an instance of Vcl.StdCtrls.TButton -- and a procedure named
Button1Click that is called when the user presses
Button1.
Button1Click hides
Form1 and displays
Form2 (the call to
Form2.ShowModal).
Form2 is defined in Unit2:
unit Unit2; interface uses SysUtils, Types, Classes, Graphics, Controls, Forms, Dialogs; type TForm2 = class(TForm) Label1: TLabel; CancelButton: TButton; procedure CancelButtonClick(Sender: TObject); end; var Form2: TForm2; implementation uses Unit1; {$R *.dfm} procedure TForm2.CancelButtonClick(Sender: TObject); begin Form2.Close; end; end.
Unit2 creates a class named
TForm2 and an instance of this class,
Form2. The
TForm2 class includes a button (
CancelButton, an instance of Vcl.StdCtrls.TButton) and a label (
Label1, an instance of Vcl.StdCtrls.TLabel). You can not see this from the source code, but
Label1 displays a caption that reads
Hello world! The caption is defined in
Form2's form file,
Unit2.dfm.
TForm2 declares and defines a method
CancelButtonClick that will be invoked at run time whenever the user presses
CancelButton. This procedure (along with
Unit1's
TForm1.Button1Click) is called an event handler because it responds to events that occur while the program is running. Event handlers are assigned to specific events by the form files for
Form1 and
Form2.
When the greeting program starts, Form1 is displayed and Form2 is invisible. (By default, only the first form created in the project file is visible at run time. This is called the project's main form.) When the user presses the button on
Form1,
Form2 displays the
Hello world! greeting. When the user presses the
CancelButton or the
Close button on the title bar,
Form2 closes. | https://docwiki.embarcadero.com/RADStudio/Alexandria/en/Language_Overview | CC-MAIN-2022-40 | refinedweb | 1,842 | 57.27 |
The C library function int fflush(FILE *stream) flushes the output buffer of a stream.
Following is the declaration for fflush() function.
int fflush(FILE *stream)
stream − This is the pointer to a FILE object that specifies a buffered stream.
This function returns a zero value on success. If an error occurs, EOF is returned and the error indicator is set (i.e. feof).
The following example shows the usage of fflush() function.
#include <stdio.h> #include <string that will produce the following result. Here program keeps buffering into the output into buff until it faces first call to fflush(), after which it again starts buffering the output and finally sleeps for 5 seconds. It sends remaining output to the STDOUT before program comes out.
Going to set full buffering on This is tutorialspoint.com This output will go into buff and this will appear when programm will come after sleeping 5 seconds | https://www.tutorialspoint.com/c_standard_library/c_function_fflush.htm | CC-MAIN-2019-39 | refinedweb | 153 | 66.23 |
Toolbox to manage NCBI taxonomical data
Project description
Readme
Status
ncbi-taxonomist is still under development. The basic operations are working and unlikely to change in the near future. Metadata querying is still in development.
Synopsis
ncbi-taxonomist handles and manages phylogenetic data from NCBI. It can:
- map between taxids and names
- resolve lineages
- store obtained taxa and their data locally in a SQLite database
- group taxa into user defined groups (locally)
taxonomist has several simple operations, e.g. map or import, which work together using pipes, e.g. to populate a database, map will fetch data from Entrez and print it to STDOUT while import reads the STDIN to populate a local database. Taxonomic information is obtained from Entrez, but a predownloaded database can be imported as well.
The true strength is to find and link related metadata from other Entrez databases, e.g. fetching data for metagenomic data-sets for specific or diverse group of organisms. It can store phylogenetic groups, e.g. all taxa for a specific project, in a local database.
Install
$pip install ncbi-taxonomist --user
This will fetch and install
ncbi-taxonomist and its required dependencies
(see below) use for an user (no
root required)
Dependencies
ncbi-taxonomist has two dependencies:
entrezpy: to handle remote requests to NCBI's Entrez databases
taxnompy: to parse taxonomic XML files from NCBI
These are libraries maintained by myself and rely solely on the Python standard
library. Therefore,
ncbi-taxonomist is less prone to suffer
dependency hell.
Usage
ncbi-taxonomist <command> <options>
Available commands
call without any command or option to get an overview of available commands.
$ ncbi-taxonomist
Command help
To get the usage for a specific command, use:
$ ncbi-taxonomist <command> -h
For example, to see available options for the command
map, use:
$ ncbi-taxonomist map -h.
Output
ncbi-taxonist uses
JSON as main output because I have no clue what you want
to do with the result.
JSON allows to use or write quick formatter or viewers
and read the data directly from
STDIN.
jq is an excellent tool to filter and
manipulate
JSON data.
An example how to extract attributes from the
ncbi-taxonomist map command
JSON output:
ncbi-taxonomist map -t 2 -n human -r | # ncbi-taxonomist map step jq -r '[.taxon.taxon_id,.taxon.rank, ( .taxon.names | to_entries[] | select(.value=="scientific_name").key) ] | @csv' ^ ^ ^ ^ ^ ^ ^ ^ ^ | | | | jq pipe jq pipe | | | | +-------+-------+ +----------------------------------------------------------------------+ jq | | Add taxon_id and Extract scientific_name from taxon names and add to array | pipe | | rank attribute to | jq csv output | array | from array | | `- create array for csv output for each JSON output line---------------------------------------------+
For more
jq help, please refer to:
Commands
map
map taxonomic information from Entrez phylogeny server or loading a downloaded
NCBI Taxonomy database into a local database. Returns taxonomic nodes in
JSON.
Map taxid and names remotely
ncbi-taxonomist map -t 2 -n human -r
Map taxid and names from local database
ncbi-taxonomist map -t 2 -n human -db taxa.db
Map sequence accessions
ncbi-taxonomist map -t 2 -n human -db taxa.db
Format specific filed from map output to csv using
jq
- Extract taxid, rank, and scientific name from
map
JSONoutput using
jq:
ncbi-taxonomist map -t 2 -n human -r | \ jq -r '[.taxon.taxon_id,.taxon.rank,(.taxon.names|to_entries[]|select(.value=="scientific_name").key)]|@csv'
import
Importing stores taxa in a local SQLite database. The taxa are fetched remotely.
Import taxa
ncbi-taxonomist map -t 2 -n human -r | ncbi-taxonomist import -db testdb.sql
Resolve
Resolves lineages for names and taxids. The result is a
JSON array with the taxa
defining the lineage in ascending order. This guarnatees the query is the first
element in the array.
Further extraction can be done via a script reading
JSON arrays line-be-line or
via othe tools, e.g.
jq [REF]
Resolve and format via
jq
ncbi_taxonomist resolve -n man -db testdb2.sql | \ jq -r '[.[] | .names.scientific_name ]| @tsv'
Resolve accessions remotely
ncbi-taxonomist map -a MH842226.1 NQWZ01000003.1 -r | ncbi-taxonomist resolve -m -r
Extract
Extract nodes from a specified superkingdom and subtree WIP
Group WIP
Collect NCBI taxids into a group for later use
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/ncbi-taxonomist/0.5.0.dev170/ | CC-MAIN-2021-39 | refinedweb | 714 | 53.92 |
Jul 11 2020 02:44 AM
Hello,
I have got in my Azure resource group (tenant - subscription) one Log Analytics Workspace.
Log Analytics Workspace consume data (metrics) from my on-premise virtual machine by Log Analytics Agent.
I see data (metrics) at Logs, that is ok.
But when I want to see data (metrics) at Azure Monitor - Metrics, I do not see any.
Respectively I see empty chart with metrics for example: Avg. Disc sec/Read but
at Logs I have many records from metric Avg. Disc sec/Read.
Can you advice me what I will must do to display data from Logs at Metrics charts?
Thank you in advance for your reply
Lada Cernik
Jul 13 2020 01:57 AM
Jul 13 2020 01:57 AM
Its a little hard to see (maybe my eyesight) from your 5th picture, but its looks like you are trying to look at the metrics of the workspace rather than the resource (Virtual Machine). Swap the namespace to the metric you want to see.
If you look in the Overview:
Logs (where you have the PERF table are in "logs" workspace (one you setup and name), but Metrics are in another workspace (which you don't have to worry about...its provided top customers); so you can just look for the resource.
Jul 17 2020 02:53 AM
Jul 17 2020 02:53 AM
Hi, @Clive Watson.
I think that my problem is
that I collect data only from Windows agent (Log analytics agent at on-promise OS Windows).
I do not collect data from other resources (like Azure VM and so on).
I find out the source... where is:
Data sources include:
Metrics: Platform metrics collected from Azure resources. Applications monitored by Application Insights. Custom defined by application or API.
Logs: Application and resource logs. Monitoring solutions. Agents and VM extensions.
Application requests and exceptions. Azure Security Center. Data Collector API.
Thank you for reply. | https://techcommunity.microsoft.com/t5/azure-monitor/how-to-create-from-logs-a-chart-in-metrics/td-p/1516212 | CC-MAIN-2021-10 | refinedweb | 323 | 75.2 |
Parsing FQL result
Facebook Query Language, or FQL, allows you to use a SQL-style interface to more easily query the same Facebook social data that you can access through other Facebook API methods (assuming your application has access!). Data returned for Facebook ActionScript Api are XML. You can access data via E4X after setting correct namespace. As for now (January 25, 2010), Facebook result defines xmlns=”” , but it may change in future, so lets make it dynamic…
Use e.g. extended FacebookLogger and add these lines
public function fql(query:String):void { var call:FacebookCall = facebook.post(new FqlQuery(query)); call.addEventListener(FacebookEvent.COMPLETE, fqlCallComplete); } private function fqlComplete(event:FacebookEvent):void { var data:FacebookData = FacebookData(event.data); var xml:XML = XML(data.rawResult); var ns:Namespace = xml.namespace(); default xml namespace = ns; var result:Array = []; for each(var user:XML in xml.user) result.push({uid:user.uid.toString(), name:user.name.toString()}); default xml namespace = new Namespace(""); dispatchEvent(new ResultEvent(ResultEvent.RESULT, false, true, result)); }
Notice xml.namespace() line. This method returns Namespace object used in main node (“”), so we can define it as default xml namespace. If you do not set empty default namespace after you finish parsing this XML, it may throw some errors later in parsing another XMLs.
this is our fql query:
FB.fql("SELECT uid, name FROM user WHERE uid = XXX")
and data.rawResult contains following XML object
<?xml version="1.0" encoding="UTF-8"?> <fql_query_response xmlns="" xmlns: <user> <uid>12345678</uid> <name>Some John Smith</name> </user> <user> <uid>12345679</uid> <name>Another John Smith</name> </user>...
Notice xmlns attribute in main node.
i can’t get the xml to behave properly.
i am doing as you say, here is my code:
queries = { “user_stream”:”SELECT post_id, actor_id, target_id, message, attachment FROM stream WHERE source_id IN (SELECT target_id FROM connection WHERE source_id=” + 508510728 + ” AND is_following=1)”
newsFeedCall = facebook.post(new FqlMultiquery(queries));
newsFeedCall.addEventListener(FacebookEvent.COMPLETE, gotResult);
private function gotResult(event : FacebookEvent) : void
{
var data : FacebookData = FacebookData(event.data);
var xml : XML = new XML(data.rawResult);
var ns : Namespace = xml.namespace();
default xml namespace = ns;
for each(var message:XML in xml.stream)
{
trace(message);
}
}
I am having real problems accessing any child nodes of the fql returned xml by name, i’ve had to resort to using multiple .children() accessors which is less than ideal.
Any ideas?
Hi Alex,
, you can debug your results)! So it corrupts your iteration.
is there any purpose you call FqlMultiquery instead of just FqlQuery… it seems you only call one query. All results from FqlMultiquery comes in one xml string, each query has its own node (do not know it by heart but it is something like
1. consider using FqlQuery instead of FqlMultiquery when calling only one fql
2. or change iteration “for each(var message:XML in xml.stream)” to “for each(var message:XML in xml..stream)” or something even more specific
3. or paste here xml result preview so I can help you
Hi Jozef,
Thanks for replying so quickly.
I am using the multi query to gather other information in additional queries, I just didn’t paste that in to the code I showed you as I felt it was irrelevant.
Your tip about using the extra . has solved it. Now I feel stupid 😛
Thank you very much for your help 🙂
[…] fqlComplete method, please read Parsing FQL result […] | http://blog.yoz.sk/2010/01/parsing-fql-result/ | CC-MAIN-2019-30 | refinedweb | 567 | 59.4 |
Backport #8341closed
block_given? (and the actual block) persist between calls to a proc created from a method (using method().to_proc()).
Description
Confirmed on both 2.0.0 and 1.9.2-p290. A testcase (utilizing RSpec) is attached, but the behavior is easy to demonstrate without a testcase or RSpec.
First, we define a method that can optionally accept a block.
def foo
if block_given?
yield
else
puts "No block given."
end
end
Then, we convert the method to a proc and store it in a variable.
method_to_proc = method(:foo).to_proc
Now, we try calling method_to_proc without a block, getting the expected result:
method_to_proc.call
=> No block given.¶
We call it again, this time with a block, and again get the expected result:
method_to_proc.call { puts "Block given." }
=> Block given.¶
But when we call it a third time, again with no block...
method_to_proc.call
=> Block given.¶
...it remembers the previous proc that was passed in.
If we then call it with a new proc, it overwrites the old proc as expected (this is not tested in the testcase, which only tests block_given?):
method_to_proc.call { puts "New block given." }
=> New block given.¶
The testcase verifies this behavior, and also that the behavior does not occur when calling a method in the usual way, or when using method() but not to_proc(), or when using method().to_proc() but not storing the result in the same variable (the last of which isn't that surprising but is included for completeness).
I cannot see any reason that this should be expected behavior. Either block_given? should work the same way in method.to_proc()s as it does in method()s, or it should always return false, and it certainly shouldn't "remember" the last block used.
Files
Also available in: Atom PDF | https://bugs.ruby-lang.org/issues/8341?tab=changesets | CC-MAIN-2022-21 | refinedweb | 296 | 68.67 |
On Fri, Jul 24, 2009 at 11:23:11AM -0700, Frans Pop wrote:> On Friday 24 July 2009, Peter Chubb wrote:> > >>>>> "Sam" == Sam Ravnborg <sam@ravnborg.org> writes:> > Sam> The above change is correct. But I really wonder if the original> > Sam> code was correct? Do we really only want to use the -mtune> > Sam> options for this specific gcc version? If this is indeed the> > Sam> case this deserves a comment explaning this.> >> > I suspect it should be all compilers after this one. -mtune=mckinley> > didn't work very well in the early gcc 3 compilers and didn't exist in> > version 2.> > How would you like to handle that? As it is essentially a separate issue,> my suggestion would be: apply my patch as is and then (if needed) commit> a separate patch to fix the incorrect comparisons on top.Between GCC version 3.4.0 and 4.3.3 (including 3.4.0 and 4.3.3), -mtune=merced isimplemented in GCC. Starting from 4.4.0, -mtune=merced is deprecated.Even implemented in versions between 3.4.0 and 4.3.3, the -mtune=mercedfeature has been broken in some of the versions. For example, GCC 4.1.2 reportsinteranl tuning function errors during kernel building with -mtune=merced. Or GCCBugzilla 16130 reports another -mtune=merced issue on GCC 3.4.1.So I would remove the -mtune=merced from IA64 kernel build. Without this option,kernel on Merced will remain the same except losing an unstable and out-of-dateperformance tunning feature.Since GCC version 3.4.0, -mtune=mckinley has been implemented. The-mtune=mckinley option functions the same as mtune=itanium2. And mtune=itanium2is the default option. So we don't need to add mtune=mckinley either since itsbeen the default option in any GCC version which implements this option.Signed-off-by: Fenghua Yu <fenghua.yu@intel.com>--- arch/ia64/Makefile | 5 ----- 1 files changed, 5 deletions(-)diff --git a/arch/ia64/Makefile b/arch/ia64/Makefileindex 58a7e46..e7cbaa0 100644--- a/arch/ia64/Makefile+++ b/arch/ia64/Makefile@@ -41,11 +41,6 @@ $(error Sorry, you need a newer version of the assember, one that is built from) endif -ifeq ($(call cc-version),0304)- cflags-$(CONFIG_ITANIUM) += -mtune=merced- cflags-$(CONFIG_MCKINLEY) += -mtune=mckinley-endif- KBUILD_CFLAGS += $(cflags-y) head-y := arch/ia64/kernel/head.o arch/ia64/kernel/init_task.o | http://lkml.org/lkml/2009/7/24/314 | CC-MAIN-2017-13 | refinedweb | 395 | 53.27 |
User talk:Lenoxus
From Uncyclopedia, the content-free encyclopedia
edit Article focii
When I put an article in this here section, it means that I like it to a certain degree but feel it should still be edited somehow, and can't think of a way to fix it (or I don't have the time). In reality, this is just my sneaky way to add more in-Uncyclopedia references to the page in question, to increase its chance of being improved. (Feel free to dicusss any changes here or at the article's talkpage, whichever seems to make more sense. Both is actually best, but if you post here, I'm personally more likely to respond.)
I am considering just eliminating this bit because it's obviously redundant to Uncyclopedia:Pee Review. Then again, Pee Review isn't so good at resolving contradictions like the one below, so... hmm....
edit Ten Commandments versus The Ten Commandments:
4/11/06: While the first page is longer, the second definitely has some good points. The two really ought to be merged (I would give the first precence, but use the title of the second), perhaps by referring to those listed in the second as "alternate sources of the Covenant" or something like that.
5/17/06: Did you see that? I totally pulled a 360 just now. So, like, now I think it's cool to have two separate articles, but I think there should be some mention of this on the articles themselves. (I'm such a flip-flopper.) Anyone think they know why God (or whowever) made one set with the word "the" and the other without?
edit Other articles under my watchful eye
Biggest right now: Forum:Review of Featured Content
Also: Mad Libs, Thomas Pain, UnNecessary Articles 1.0 Project, Template:Contradicts, various others to put here when I find the time
edit Harry Potter
Thanks for the improvements to Harry Potter. 90% of the people who stop in there only drop by to vandalize the page. -- Rei 03:02, 27 March 2006 (UTC)
- You're welcome, Rei. I'm going to start a list of cool users now just to put you on it. --User:Lenoxus (I'm not logged in, but I'll fix this sig soon)
edit Insert title here
This page is now semi-protected instead of fully protected. You can make your changes by yourself. Also, I think "Insert ______ " should be used instead of "Insert ______ here" That way, we will still know that something should be inserted. --Sbluen 23:38, 14 May 2006 (UTC)
- Gosh thanks! Now you are cool. I'll try it my way first and see if anyone changes it (I won't mind if they do) — I think phrases like [Chuck Norris reference] should make sense by themselves, but we'll see. Lenoxus 14:08, 15 May 2006 (UTC)
- "Insert" is still used in the Russian Reversal quote and it isn't used anywhere else except in the title. Some areas that are designed to be used are out of brackets, which is where some comments are. Also, you linked the word "Link" only at the end of the [Mandatory two-word section header] section. Aside from these inconsistancies, I think your changes are good. --Sbluen 23:18, 15 May 2006 (UTC)
- OK, I just got your message. Thanks for the explanation (above). I'm wondering: could I make some of the changes you're suggesting (fixing "insert" inconcsistancies, etc.) and see how that works? --Lenoxus 20:25, 17 May 2006 (UTC)
- You can try making your changes. However, I didn't revert your changes. Guest did that. You should discuss your changes with him. Also, you should see the edit histories before assuming anything about the most recent edits. --Sbluen 22:49, 17 May 2006 (UTC)
I did not change the protection, or ban on edits. I cannot do that because I am not an administrator. Algorithm did that after I suggested that it should be done. I only suggested those changes and told you that the page was only semi-protected. This is another reason to look at the edit histories. Please do not say that I did things that only administrators can do because doing so could trick other users into thinking that I am one of them. --Sbluen 02:30, 19 May 2006 (UTC)
- OK, I apologize. You are definitely not an administrator — got that. This is getting kinda silly. Peace out --Lenoxus 14:43, 19 May 2006 (UTC)
- I'm sorry for complaining about a silly thing. I am a little bit new to uncyclopedia and I didn't know that it was obvious that I wasn't an administrator when I complained.
- I could become an administrator soon. Now Algorithm nominated me for administrator, probably because he saw my hard work at Uncyclopedia:QuickVFD. If you want to, you can vote for me at this forum page. --Sbluen 13:00, 31 May 2006 (UTC)
edit Uncyclopedia is the worst
OK, here's an attempt to explain this article. It's a bit of an in-joke, unfortunately. It came about after a derogatory message in the Village Dump [1], which some people thought was funny. Someone suggested it should be expanded into an article, so I just had a field day ripping into Uncyclopedia in a kind of ironic fashion in the same tone as the original post. Almost as if it was written by the person who posted the original message.
However, other people have since edited this and it has transformed into a no-brainer all out jibe at people who slate Uncyc: sort of not the way I originally envisioned it. But, meh, there's nowt much I can do: it's not my baby any more (and in a way it never was).
In summary, it is whatever you believe it to be. Personally, I think there's nothing wrong with self-depreciatory humour. After all, we take the mick out of everything else, so why not ourselves? Have a complimentary T-shirt... --Hindleyite | PL | CUN | Converse 17:58, 19 May 2006 (UTC)
- Where can I get one of those shirts, dude? --Lenoxus 18:16, 19 May 2006 (UTC)
- Sadly, it's still only in the design stage. :-) --Hindleyite | PL | CUN | Converse 18:17, 19 May
You can narrow your search criteria to search for images (example). Unfortunately I don't think images are very well categorized at the moment...perhaps we should start a project for that...also, not to be rude, but please don't post questions in many different places. Your best bet is usually to ask an admin or other active and established user, or start a topic at the Forum. —rc (t) 18:47, 19 May 2006 (UTC)
edit Thanks!
....for the spit shine. Can't spel, can't type. Kin wryte. Sorta. :) ~ T. (talk) 05:10, 2 June 2006 (UTC)
edit Pee Review
- You nutty bunny, posting to Uncyclopedia:Pee Review/American Fundie Magazine, realizing your error, and unposting. Next you'll be voting for it (or against...) on VFH. Then you'll remember it's featured already, and unpost. Yes, I've heard at least once that it would be better subtle. No, I'm not changing it. I wrote it when I was mad/crazy/scared at some dopey sh*t-headed thing that "they" did, and I'm still a bit angry now. Yes, I know that they're a minority, but it's a minority, unfortunately, with a disproportionate amount of power and an agenda that, for the most part, is the exact opposite of what a civilized society needs...
- Thanks for giving me a laugh, anyways. If you want a different take on a different group, I wrote Solid Gold recently. It's still not subtle...but it's closer, I hope.--Sir Modusoperandi Boinc! 22:09, 24 September 2006 (UTC)
edit And....
where have you been? -- Sir Mhaille
(talk to me)
edit Just
since Aug'm
just groovy, thanks. Hard at work, but still keeping my hand in on Uncyc. Its a hard job, but someone needs to
It may please you to know I've deleted UnNews:Vatican condemns subway rescuer for "unclean physical closeness to another man". Disappointning because the title has such potential... any way, read below, and try again,:12, 12 January 2007 (UTC)
Reverend Zim_ulator says: "There are coffee cup stains on this copy, damnit! Now that's good UnJournalism."
Welcome to UnNews, Lenox huh?
Ok, the new article seems good, and I'll probably do it as an audio soon. Becasue I
smoke too much pot have a lousy memory, I seem to remember deleting it because it had no actual article written, but what do I know? I'm baked. May I suggest you use the {{WIP}} (below) template if it was something you were working on, and will finish later? Thanks for your contributions, and sieg heil to me.
WIP template — I, Lenoxus, removed this because it applies to the situation being discussed but not this actual talkpage; that wouldn't make sense. So just imagine that you're seeing such a template. While you're at it, imagine that your government and peer community are doing all they can to help you, and have only your best interests in mind. There, didn't that feel nice?
Oh, and by all means, insult the fuck out of Catholicism to your heart's content, if you please. I do so at any opportunity. This is a parody site, I:23, 12 January 2007 (UTC)
- Uhm... who's high? I've already done the audio and uploaded for podcast (now you're fabulously famous)... apparently you didn't notice... because you're HIGH! You'll be pleased to know that I wasn't high... well, particularly high... well, considering the meds I take for pain and other things, I guess the term HIGH becomes relative. But I didn't specifically smoke some reefer with the express purpose of being stoned when I read your article. As for your other request, you're out of luck. I do these things in one take, with whatever ambient noise is in my
homestudio at the moment, and I seldom listen to them after I've recorded. That way, I can get as many as 20 done in a day if the need arises, and I'm up to it. Please, though, feel free to do an audio or two, take some of the load off of me, as I do have some ideas, and I'm trying to create an actual, albeit cheap, studio here, and want to have the choice of creating shitty or decent audios. Cheers, and thanks for your:47, 15 January 2007 (UTC)
edit BTW
I just wanted to point out that I loved, LOVED the Bill O'Reilly article. Seriously, thought it was great.--Super90 04:27, 17 January 2007 (UTC)
edit Hiroshima
Thanks for the nice improvements to the article. :) -- Rei 18:01, 8 February 2007 (UTC)
edit You're at Guilford?
Dude, I went to Guilford for one year. I spent my time doing drugs out by the ropes course. Then I dropped out and went to NY to chase destiny, or something... I don't remember... must be all the drugs. I was raised Quaker so Guilford made a big effort to recruit me, as there are about 4 quaker kids going off to college in any given year. --Super90 09:49, 15 February 2007 (UTC)
- Your myspace page.--Super90 00:45, 19 February 2007 (UTC)
edit Hmm
Ok, what's going on? —Braydie 01:53, 17 February 2007 (UTC)
edit Thanks for the pee
Thank you for your review of Condominium. I hope you'll check back from time to time and find that I am taking your advice to heart. BTW, the "condo" in the gentrification picture is actually a gingerbread house. It is probably made of frosting or something. Professor Fate 17:39, 18 February 2007 (UTC)
edit Instant Disambig
Please do not un-subst: {{Instant disambig}}. I substituted the template so that it would appear to be like all the older disambig pages, with the added bonus of not attracting mass vandalisim (that will be caused when one template that is on 300 pages gets vandalised). --Brigadier General Sir Zombiebaron 02:02, 20 February 2007 (UTC)
- Also, {{Wikipedia}} is unneccasary for that template, because most of our disambigs are disambigs over at Wikipedia. --Brigadier General Sir Zombiebaron 02:04, 20 February 2007 (UTC)
edit Template:USERLINK
Dunno if you saw my deletion summary, but Special:Mypage will do what I think you were trying to do with that (link to the viewing user's userpage). Just thought you should know and possibly save yourself a headache. —Major Sir Hinoa prepare for trouble • make it double? 03:54, 20 February 2007 (UTC)
edit Thanks
For the tip. Being a n00b I'm taking it all on board.
I've actually taken to writing anything new I do on Word anyway. So the long lits of edits with my name and an "m" next to them should be a thing of the past.
Good noob shepherding there --Sibley 15:18, 23 February 2007 (UTC)
edit Wikipedia Template on H.R. Pufnstuf
Mahaille put Wikipedia Template towards the end of the article because when its placed at the beginning of the article, as you did, it leaves this huge useless area of white space. So I have reverted your edit and hope you understand why I did the revert. Thanks - and if you have any questions, please let me know, Hugs, Dame
GUN PotY WotM 2xPotM 17xVFH VFP Poo PMS •YAP• 22:30, 25 February 2007 (UTC)
- Got it. The most mortifying part is that I didn't even notice the one that was already there... oh well. — Lenoxus 22:38, 25 February 2007 (UTC)
edit Cookie
- This is basically a mad props for helping out on several different things, most recently pointing out two VFD'd pages that should have been redirects. Good job, keep it up. --Brigadier General Sir Zombiebaron 02:39, 26 February 2007 (UTC)
- My obsessive neruoses pay off; take that, Dr. Cullen! — Lenoxus 03:05, 26 February 2007 (UTC)
- Heh -- Dr. Cullen talk
- Making me laugh won't make me give you anouther {{Cookie}} today...maybe tommorow...but I'm a strick "One Cookie A Day Diet"... --Brigadier General Sir Zombiebaron 03:39, 26 February 2007 (UTC)
- Oh, I'm not fishing for anything, honest. Just wrote because, like Martin Luther, I could not do otherwise. Thank you very much if I didn't say so already. — Lenoxus 03:45, 26 February 2007 (UTC)
- And thank you for making my life easier, and funnier. -- Brigadier General Sir Zombiebaron 03:47, 26 February 2007 (UTC)
edit Response from Lstarnes
Sorry about that. I deleted it to save space. I'll restore it later. --Lstarmes 00:00, 28 February 2007 (UTC)
edit We Shall Never Forget
~
17:02, 4 March 2007 (UTC)
edit Thank you for your vote
-- 15Mickey20 (talk to Mickey) 20:08, 8 March 2007 (UTC)
edit Spatz on David Farragut
Thanks for editing last month, I finally David Farragut and made a pee review on it. If you have the time, could you please review it? Thanks.
edit Help with article:02, 27 March 2007 (UTC)
- I'm afraid I've got a ton of schoolwork to focus on, and am planning to take some time off of Uncyclopedia per the message I've just put at the top (some text had actually already said I was on a break, but I don't blame you for not noticing). Anyway, the comments I left on the English gods talkpage reccomended a move, and after a bit of meditation on the subject, I've decided that the best possible title (which may lead to a some needed modification of text) would be Grammar (religion), because that's how Wikipedia would discuss the subject if it existed. When I get back, I'll have a better look at it. Lenoxus 18:16, 29 March 2007 (UTC)
edit WIP move notice of Seat hockey
Hey, your article that was called Seat hockey has been moved to User:Lenoxus/Seat hockey for further development. Feel free to move it back when you have done. Oh, and if you want to reply to this, please reply on my talk page (I do so many of these, I don't get to check them all). Thanks. —Braydie 13:45, 2 April 2007 (UTC)
edit Lord Voldemort (Harry Potter)
I demand that you revert your edit to the Lord Voldemort (Harry Potter) article. He deserves an article which is why I had created one for him and it had great potential. I had just finished cleaning it up and making it incredibly hilarious when I got into an edit conflict because you were busy reverting it to that contemptably ridiculous, You Are Dead article. --86.134.153.111 19:08, 11 May 2008 (UTC)
- You do realize that Lenoxus' last edit was on the 20th of May 2007, right? I think you're thinking edits made by this idiot. -- Brigadier General Sir Zombiebaron 00:09, 12 May 2008 (UTC)
- Ah yes. Thank you. --92.0.46.24 12:32, 12 May 2008 (UTC)
edit Duel!!!
I challange you, Lenoxus, to a duel!! What, don't be a chicken and fight like the little squggle you are!!!!--
- Oh well, you're a pussy
edit I need some advice
I have an article in my sandbox that I was thinking of putting in the Why? namespace. It's not quite done; there are a few more tweeks I want to make before I entrust it to others. Do you think the Why? is the best place for it, or do you think there's a better place? Larrythefunkyferret 05:53, October 6, 2009 (UTC) | http://uncyclopedia.wikia.com/wiki/User_talk:Lenoxus | CC-MAIN-2016-36 | refinedweb | 3,009 | 72.56 |
Re: Unions Redux
- From: Jack Klein <jackklein@xxxxxxxxxxx>
- Date: Wed, 14 Mar 2007 22:05:25 -0500
On 14 Mar 2007 15:10:44 -0700, "Old Wolf" <oldwolf@xxxxxxxxxxxxxx>
wrote in comp.lang.c:
Ok, we've had two long and haphazard threads about unions recently,
and I still don't feel any closer to certainty about what is permitted
and what isn't. The other thread topics were "Real Life Unions"
and "union {unsigned char u[10]; ...} ".
Most of the rambling was caused by the original OP, I think, rather
than the material. I am not criticizing, just observing.
Here's a concrete example:
#include <stdio.h>
int main(void)
{
union { int s; unsigned int us; } u;
u.us = 50;
printf("%d\n", u.s);
return 0;
}
Is this program well-defined (printing 50), implementation-defined, or
UB ?
The program is well-defined, I'll elaborate further down.
Note that the aliasing rules in C99 6.5 are not violated here -- it is
not forbidden under that section to access an object of some type T
with an lvalue expression whose type is the signed or unsigned
version of T.
As you pointed out, it does not violate the alias rules, but there are
other rules to consider. In this particular case, you are accessing
an object of type unsigned int with an lvalue expression of type
signed int. The entire question of the validity of the operation
depends on the object representation compatibility, and has nothing at
all to do with the fact that there is a union involved.
In this particular case, the operation is well-defined because of the
standard's guarantees about corresponding signed and unsigned integer
types. For a positive value within the range of both types, the bit
representation is identical for both.
However, if you had assigned INT_MAX + 1 to u.us, and your
implementation is one of the universal ones where UINT_MAX > INT_MAX,
the behavior would be implementation-defined because, at least
theoretically, (unsigned)INT_MAX + 1 could contain a bit pattern that
is a trap representation for signed int.
In other words, is there anything other than the aliasing rules that
restrict 'free' use of unions?
Personally, I think people get to wound up in the mystical and magical
properties of unions.
They are good for two things:
1. Space saving, such as a struct containing a data type specifier
and a union of all the possible data types. This is a frequent
feature in message passing systems. Generally, type punning is not
used here.
2. Another way to do type punning.
Consider:
int test_lone(long l)
{
int *ip = (int *)&l;
int i = *ip;
return i==l;
}
Is this code undefined, implementation-defined, or unspecified?
Technically it is undefined, but on an implementation like today's
typical desktop, where int and long have the same representation and
alignment, the result will be that the function returns 1. On an
implementation where int and long are different sizes, who knows.
Now consider:
int test_long(long l)
{
union { long ll; int ii } li;
li.ll = l;
return li.ll==li.ii;
}
Is this code undefined? Well, yes, but it is no different in
functionality than the first function. If int and long have the same
representation, it will return 1.
There is no difference in aliasing in a union than there is via
pointer casting.
--
Jack Klein
FAQs for
comp.lang.c
comp.lang.c++
alt.comp.lang.learn.c-c++
.
- Follow-Ups:
- Re: Unions Redux
- From: CBFalconer
- Re: Unions Redux
- From: Yevgen Muntyan
- Re: Unions Redux
- From: Old Wolf
- References:
- Unions Redux
- From: Old Wolf
- Prev by Date: Re: C89, size_t, and long
- Next by Date: Re: Unions Redux
- Previous by thread: Re: Unions Redux
- Next by thread: Re: Unions Redux
- Index(es): | http://coding.derkeiler.com/Archive/C_CPP/comp.lang.c/2007-03/msg02601.html | crawl-002 | refinedweb | 631 | 64 |
By: Nick Hodges
Abstract: This article discusses the genesis and use of the DBXDataSource component in ASP.NET and Delphi
An interesting thing happened on the way to ASP.NET 2.0.
First, let’s talk about typing and databases. You’d think by now that we, as an industry, would have a pretty good grip on the types of fields a database can handle. There are standards for date, time, timestamp and floating point data types. However, not all vendors follow the standard. Competitive pressures, the need for differentiation, and human nature all being what they are, prominent databases seem to handle some fields just a little bit differently. Maybe they have different integer types. Maybe they have one integer type that holds them all. Maybe they have different kinds of floating point numbers, maybe they just have one. In any event, everyone seems to do many common things just a little different.
Now, here at CodeGear, we’ve always prided ourselves on supporting a wide variety of popular databases. We’d like to make it easier for us to support even more than we do. That’s part of the strategy with our dbExpress 4 technology. One of its key design goals was to make it easier to write and maintain database drivers. Now, of course, one of the keys to that is to be able to abstract out the concept of data types, and to provide a set of types that will work for the VCL components that Delphi and C++Builder developers will use. You use the basic types we provide, and we “coerce” them into the right form to fit the database backend you are using. It shouldn’t matter at the code level whether the database is Interbase, Oracle, MySQL, SQL Server, whatever. We just want you to worry about your code, not your database types, and we particularly don’t want you to worry about how your database deals with blobs or Memos or DateTimes.
However, not all companies are so “flexible”. Some of them tend to prefer the database and data types of the database product that they want you to use. This sort of thing sometimes shows up in frameworks that get written. Take, for instance, the SQLDataSource component that is part of the ASP.NET 2.0 framework. This component, in theory, should be able to handle any ADO.NET 2.0 compatible datasource. And to be fair, it does. Sort of. But it uses the System.Type typing system of the .Net Framework. It only handles those types and no others. It also is smart enough to map these types to -- you guessed it -- SQL Server. But those are the only types it handles. So if you want to plug a datasource into it that doesn't exclusively deal with the System.Type namespace of types, well, then you've got some work to do. This is understandable, really – I guess you can’t marshal types for every database out there.
Microsoft themselves realized this, because they have another database engine that people use – Access. Access’s types aren’t the same as SQL Server’s, and they aren’t the same as the System.Type namespace’s types. Therefore, they had to create a new class – AccessDataSource – to connect up to an Access database for ASP.NET. AccessDataSource descends from SQLDataSource, and the basic difference is that it overrides the typing of parameter that pass through it, coercing them into the right types to be handled by Access.
Well, now for the interesting part. dbExpress and the dbExpress drivers are in the same boat as Access was. SQLDataSource deals in types that aren’t perfectly coincident with the world of dbExpress data types. So we had to create our own control for ASP.NET – DBXDataSource. DBXDataSource is a relatively simple control – it merely overrides eight methods of SQLDataSource to provide the type coercion needed to match up the types that ASP.NET uses with the types that our dbExpress drivers use.
The result? If you are developing ASP.NET 2.0 applications with Delphi, and you want to access data via dbExpress, then use the DBXDataSource component, not the SQLDataSource. (SQLDataSource is still there, and you can use it for SQL Server data if you like). With the DBXDataSource driver, you can connect up and use data from any of the nine dbExpress drivers – including InterBase and Blackfish SQL. DBXDataSource works just like SQLDatasource – it’s a direct descendent – so there's no compatibility problem with ASP.NET
And that is pretty much it – there’s nothing else really special going on here. The thing to remember: When accessing data in an ASP.NET application via dbExpress, use DBXDataSource in exactly the same way that you’d use a SQLDataSource component.
So, in the end, the summary is clear: Use DBXDataSource to access dbExpress data in ASP.NET 2.0. But here’s the fun part. This all happened relatively quickly once we realized that it would be an issue. We were able to be “agile” with this. From the time we recognized the problem to the time we had a tested component on the Component Palette was about a week or so. And in the end, you get a flexible, powerful DataSource for serving up ASP.NET Data.
Server Response from: SC1 | http://edn.embarcadero.com/article/37147 | crawl-002 | refinedweb | 895 | 65.52 |
So
on_event works beautifully for me when I apply it to a figure. However, this method is also provided for individual renderers. I figured this was the logical way to say, listen for a mouse scroll event while the mouse is hovering a certain patch, like this:
from bokeh.plotting import figure from bokeh.events import MouseWheel import panel as pn f = figure() p = f.patch([0, 1, 2], [0, 1, 0]) f.on_event(MouseWheel, lambda evt: print("Figure Event", evt)) p.on_event(MouseWheel, lambda evt: print("Patch Event", evt)) pn.pane.Bokeh(f).show()
However, I only ever get the “Figure Event” callback, not the “Patch Event”. This is on bokeh 2.2.3 (latest) with Chrome or Firefox on Windows 10. It’s the same if I try the Tap event.
Am I mis-interpreting or mis-using the patch’s
on_event? Is there another way to listen for events happening over a specific patch?
Thanks a lot in advance!
Jonathan | https://discourse.bokeh.org/t/trouble-with-on-event-for-renderers/6711 | CC-MAIN-2020-50 | refinedweb | 163 | 70.29 |
the parts for each of the NLP techniques and get some surface level insights. Full source code including results here.
Here’s the parts of this post:
- A Summary of Part 1
- Creating Word Clouds from Transcripts
- Word Cloud Function
- Create Word Clouds for Each Transcript
- Combining separate files
- Collecting each NLP analysis into a single file for each technique and lecture
- Further processing on NLP responses
- Most Commonly Named Entities
- Average Sentiment Polarities
- Most Common Phrases
- Summary of Using NLP to Analyze a YouTube Lecture Series
Downloading the YouTube Transcripts and Using The Text API
In part one of using NLP to analyze YouTube Transcripts we downloaded transcripts and used NLP to get the entities, average sentiment values, most common phrases, and summaries of each episode. We used the youtube-transcript-api Python library to download the transcripts and The Text API to run NLP techniques on it. Due to the size of transcripts and internet speed limits, we broke down each transcript to be analyzed in parts. Now we have multiple files for each of the entities, average sentiment values, most common phrases, and summaries for each episode. In this post, we’re going to create word clouds from each of the transcripts and combine the analyzed parts of each lecture into one document for each technique for each lecture.
Creating Word Clouds from Transcripts
Word clouds provide a great image of the vernacular of a text. They give us an easy way to visualize the words in a text. Word clouds may not always give us a great picture of the topics in a text, but they give us a great picture of the vocabulary used. To follow along with this section you’ll need the
matplotlib,
numpy, and
wordcloud libraries. You can install these libraries with the following line in the terminal:
pip install matplotlib numpy wordcloud
Word Cloud Module
We’ll begin our word cloud module with the imports as usual. Our function takes two parameters,
text and
filename. The function will use an image, which you can find here. All we’ll do in this function is use the
WordCloud object to create a word cloud and the
matplotlib library to save the created image. For a more description tutorial, read how to create a word cloud in 10 lines of Python.
from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt import numpy as np from PIL import Image # wordcloud function def word_cloud(text, filename):')
Create Word Clouds for Each Transcript
Now that we’ve created the word cloud function, we’ll create a function that will create a word cloud for each episode. As always, we’ll begin with our imports, we’ll need the
os and
json libraries. We’ll loop through each of the files in our directory containing the transcripts.
For each of the files, we’ll load them up using the
json.load() function to turn the JSON into a list. Each item in the list is a dictionary. Before looping through each of the dictionaries, we’ll create an empty string to hold the text. For each of these items, we’ll add the
text value of the dictionary to our current text string. Finally, we’ll call the word cloud function to create a word cloud.
import json import os for video_transcript in os.listdir("./jp"): with open(f"./jp/{video_transcript}", "r") as f: entries = json.load(f) text = "" for entry in entries: text += entry["text"] + " " word_cloud(text, f"{video_transcript[:-5]}")
Combining Separate Files
As we said earlier, we had to separate each of the transcripts into separate parts to call the APIs. Now that we have separate pieces of each transcript, we have to gather them together.
Gather the Names of All the Files
Let’s create a function that will get all the filenames we need. We’ll start by importing the library we need,
os. We’ll create a function that doesn’t take any parameters. The first thing we’ll do in our function is create an empty list to hold the file names. Next, we’ll go through each of the filenames in the
jp directory that holds all the transcripts and append them to the list. Finally, we’ll return the list of file names.
import os # get filenames def get_filenames(): filenames = [] for filename in os.listdir("./jp/"): filenames.append(filename[:-5]) return filenames
Collect Each NLP Analysis into a Single File
Now let’s collect each of the parts of the files and combine them into one file. First, we’ll import the
os library and the
get_filenames function we created above. Next, we’ll get a list of filenames using the
get_filenames function. Now we’ll loop through all the filenames from the
jp directory and use those to find the partial files. The partial files will match the same prefix as the filename. After getting all the parts for one filename, we’ll sort it based on length so that the partial files ending in two digits like
_11 come after the ones ending in one digit like
_2 or
_3. Note that we only need to loop through one folder to collect the partial file names because they will be the same for each folder.
Now that we have all the filenames and the partial filenames, we will loop through all the filenames and combine the partials. For each directory, the named entities, the most common phrases, the polarities, and the summaries, we’ll create lists to hold the partial values. Then, for each filename, we’ll loop through its parts and read the files corresponding to each part. Next, for each of the directories corresponding to each part, we’ll collect the values from the parts in that directory and put them into their corresponding list. Then we’ll write all the values in the list to the full filename in the directory.) # mcps mcps = [] for part_filename in part_filenames[i]: with open(f"./mcps/{part_filename}", "r") as f: entries = f.read() mcps.append(entries) with open(f"./mcps/{filename}.txt", "w") as f: for entry in mcps: f.write(entry) # polarities polarities = [] for part_filename in part_filenames[i]: with open(f"./polarities/{part_filename}", "r") as f: entries = f.read() polarities.append(entries) with open(f"./polarities/{filename}.txt", "w") as f: for entry in polarities: f.write(entry + '\n') # summaries summaries = [] for part_filename in part_filenames[i]: with open(f"./summaries/{part_filename}", "r") as f: entries = f.read() summaries.append(entries) with open(f"./summaries/{filename}.txt", "w") as f: for entry in summaries: f.write(entry + '\n')
Further Processing on NLP Results
Now, we’ve gathered all the pieces of each NLP analysis together. Let’s do some further processing for the named entities, sentiment polarities, and most common phrases.
Getting the Most Commonly Named Entities
We can learn more from our list of named entities by getting the most commonly named entities in the list. The only import we’ll need for this file is the filenames function. Next, we’ll create a function to build a dictionary out of a list of strings.
The first thing this function will do is create an empty outer dictionary to hold the organized named entities. Next, we’ll loop through each of the pairs of strings in the list of recognized named entities. We’ll split the strings into the type and name of the entity at the first space. Then we’ll check against the entity type’s existence in the outer dictionary and the named entity in the entry and count the number of entries for each list.
Next, we’ll build a function that sorts the list of named entities after they’ve been compiled into a list using the
build_dict function. This will return a dictionary of the highest occurring name corresponding to each entity type. Finally, we’ll create another function that will loop through each entry in the directory and get the most common entities. It will read each file, run it through the
most_common function, and save the results into another file. You can see the files for the most common named entities here with the suffix
most_common.
from get_filenames import get_filenames # build dictionary of NERs # extract most common NERs # expects list strings def build_dict(ners: list): outer_dict = {} for ner in ners: splitup = ner.split(" ", 1) entity_type = splitup[0] entity_name = splitup[1] if entity_type in outer_dict: if entity_name in outer_dict[entity_type]: outer_dict[entity_type][entity_name] += 1 else: outer_dict[entity_type][entity_name] = 1 else: outer_dict[entity_type] = { entity_name: 1 } return outer_dict # def ner_processing(): filenames = get_filenames() for filename in filenames: with open(f"./ners/{filename}.txt", "r") as f: entries = f.read() entries = entries.split('\n') while '' in entries: entries.remove('') print(filename) mce = most_common(entries) with open(f"./ners/{filename}_most_common.txt", "w") as f: for ner in mce.items(): f.write(ner[0] + " " + ner[1] + '\n') ner_processing()
Average Sentiment Polarities
Now that we’ve processed the named entities, let’s also process the sentiment polarities. Each part of each episode has a different polarity value. Let’s get an average. We’ll start by importing the
get_filenames function to get the filenames. Then we’ll create a function that will return the average of a list.
Next, we’ll create our polarity averaging function. This function will start by getting all the file names. It will loop through each episode from the filenames. For each episode, we’ll create a list of polarities from the episode file. Note that we have to convert the string to a float value and get rid of the last entry which will be an empty string. Then we’ll write the average polarity to its own file. You can find the averages and separate sentiment values here.
from get_filenames import get_filenames def avg(_list): return sum(_list)/len(_list) # get average polarities def avg_polarities(): filenames = get_filenames() for filename in filenames: with open(f"./polarities/{filename}.txt", "r") as f: entries = f.read() polarities = [float(entry) for entry in entries.split('\n') if len(entry) > 1] with open(f"./polarities/{filename}_avg.txt", "w") as f: f.write(str(avg(polarities))) avg_polarities()
Most Common Phrases Combined and Reevaluated
Now let’s take a look at the most common phrases. Right now, we have combined files of the 5 most common phrases for each part of an episode. Let’s get the 5 most common phrases for an entire episode based on those. To follow along, you’ll need a free API key from The Text API and to install the Python
requests library. You can install the library with the line in the terminal below:
pip install requests
We’ll begin by importing the libraries we need,
requests and
json, the API key, and the
get_filenames function. Then we’ll create the headers which will tell the server we’re sending JSON data and pass the API key and declare the API URL we need to hit.
We will create one function to get the most common phrases from all the most common phrases. The function will get the file names and then loop through all of them. For each file, we’ll start by getting all the most common phrases and creating a body that will request the five most common phrases. All we need to do from there is send the request, parse the JSON response, and save it to another file. You can find the results here.
import requests import json from text_config import apikey from get_filenames import get_filenames headers = { "Content-Type": "application/json", "apikey": apikey } mcp_url = "" # get most common phrases def collect_mcps(): filenames = get_filenames() for filename in filenames: with open(f"./mcps/{filename}.txt", "r") as f: entries = f.read() body = { "text": entries, "num_phrases": 5 } response = requests.post(mcp_url, headers=headers, json=body) _dict = json.loads(response.text) mcps = _dict["most common phrases"] with open(f"./mcps/{filename}_re.txt", "w") as f: for mcp in mcps: f.write(mcp + '\n') collect_mcps()
Summary of Using NLP to Analyze a YouTube Lecture Series
In this series, we created word clouds from transcripts of two YouTube series and further processed NLP results from the same transcripts. To further process our results, we first combined the partial NLP analyses for each episode into one file for each episode. From there, we ran different processes. We found the most commonly named entities, the average sentiment polarities, and once again found the most common phrases from the already existing most common phrases. | https://pythonalgos.com/using-nlp-to-analyze-a-youtube-lecture-series-part-2/ | CC-MAIN-2022-27 | refinedweb | 2,083 | 64.1 |
In many programming languages, the
switch statement exists - but should it any longer? If you’re a JavaScript programmer, you’re often jumping in and out of Objects, creating, instantiating and manipulating them. Objects are really flexible, they’re at the heart of pretty much everything in JavaScript, and using them instead of the
switch statement has been something I’ve been doing lately.
Table of contents
What is the switch statement?
If you’ve not used
switch before or are a little unsure what it does, let’s walk through it. What
switch does is take input and provide an output, such as code being run.
Let’s look at a usual
switch statement:
var type = 'coke'; var drink; switch(type) { case 'coke': drink = 'Coke'; break; case 'pepsi': drink = 'Pepsi'; break; default: drink = 'Unknown drink!'; } console.log(drink); // 'Coke'
It’s similar to
if and
else statements, but it should evaluate a single value - inside the
switch we use a
case to evaluate against each value.
When you start seeing lots of
else if statements, something is likely wrong and generally you shoud use something like
switch as it’s more suited for the purpose and intention. Here’s some
else if abuse:
function getDrink (type) { if (type === 'coke') { type = 'Coke'; } else if (type === 'pepsi') { type = 'Pepsi'; } else if (type === 'mountain dew') { type = 'Mountain Dew'; } else if (type === 'lemonade') { type = 'Lemonade'; } else if (type === 'fanta') { type = 'Fanta'; } else { // acts as our "default" type = 'Unknown drink!'; } return 'You\'ve picked a ' + type; }
This implementation is too loose, there is room for error, plus it’s a very verbose syntax to keep repeating yourself. There’s also the room for hacks as you can evaluate multiple expressions inside each
else if, such as
else if (type === 'coke' && somethingElse !== 'apples'). The
switch was the best tool for the job, albeit you need to keep adding
break; statements to prevent cases falling through, one of its many issues.
Problems with switch
There are multiple issues with
switch, from its procedural control flow to its non-standard-looking way it handles code blocks, the rest of JavaScript uses curly braces yet switch does not. Syntactically, it’s not one of JavaScript’s best, nor is its design. We’re forced to manually add
break; statements within each
case, which can lead to difficult debugging and nested errors further down the case should we forget! Douglas Crockford has written and spoken about it numerous times, his recommendations are to treat it with caution.
We often use Object lookups for things in JavaScript, often for things we would never contemplate using
switch for - so why not use an Object literal to replace
switch? Objects are much more flexible, have better readability and maintainability and we don’t need to manually
break; each “case”. They’re a lot friendlier on new JavaScript developers as well, as they’re standard Objects.
> the number of “cases” increases, the performance of the object (hash table) gets better than the average cost of the switch (the order of the cases matter). The object approach is a hash table lookup, and the switch has to evaluate each case until it hits a match and a break.
Object Literal lookups
We use Objects all the time, either as constructors or literals. Often, we use them for Object lookup purposes, to get values from Object properties.
Let’s set up a simple Object literal that returns a
String value only.
function getDrink (type) { var drinks = { 'coke': 'Coke', 'pepsi': 'Pepsi', 'lemonade': 'Lemonade', 'default': 'Default item' }; return 'The drink I chose was ' + (drinks[type] || drinks['default']); } var drink = getDrink('coke'); // The drink I chose was Coke console.log(drink);
We’ve saved a few lines of code from the switch, and to me the data is a lot cleaner in presentation. We can even simplify it further, without a default case:
function getDrink (type) { return 'The drink I chose was ' + { 'coke': 'Coke', 'pepsi': 'Pepsi', 'lemonade': 'Lemonade' }[type]; }
We might, however, need more complex code than a
String, which could hang inside a function. For sake of brevity and easy to understand examples, I’ll just return the above strings from the newly created function:
var type = 'coke'; var drinks = { 'coke': function () { return 'Coke'; }, 'pepsi': function () { return 'Pepsi'; }, 'lemonade': function () { return 'Lemonade'; } };
The difference is we need to call the Object literal’s function:
drinks[type]();
More maintainable and readable. We also don’t have to worry about
break; statements and cases falling through - it’s just a plain Object.
Usually, we would put a
switch inside a function and get a
return value, so let’s do the same here and turn an Object literal lookup into a usable function:
function getDrink (type) { var drinks = { 'coke': function () { return 'Coke'; }, 'pepsi': function () { return 'Pepsi'; }, 'lemonade': function () { return 'Lemonade'; } }; return drinks[type](); } // let's call it var drink = getDrink('coke'); console.log(drink); // 'Coke'
Nice and easy, but this doesn’t cater for a “default”
case, so we can create that easily:
function getDrink (type) { var fn; var drinks = { 'coke': function () { return 'Coke'; }, 'pepsi': function () { return 'Pepsi'; }, 'lemonade': function () { return 'Lemonade'; }, 'default': function () { return 'Default item'; } }; // if the drinks Object contains the type // passed in, let's use it if (drinks[type]) { fn = drinks[type]; } else { // otherwise we'll assign the default // also the same as drinks.default // it's just a little more consistent using square // bracket notation everywhere fn = drinks['default']; } return fn(); } // called with "dr pepper" var drink = getDrink('dr pepper'); console.log(drink); // 'Default item'
We could simplify the above
if and
else using the or
|| operator inside an expression:
function getDrink (type) { var drinks = { 'coke': function () { return 'Coke'; }, 'pepsi': function () { return 'Pepsi'; }, 'lemonade': function () { return 'Lemonade'; }, 'default': function () { return 'Default item'; } }; return (drinks[type] || drinks['default'])(); }
This wraps the two Object lookups inside parenthesis
( ), treating them as an expression. The result of the expression is then invoked. If
drinks[type] isn’t found in the lookup, it’ll default to
drinks['default'], simple!
We don’t have to always
return inside the function either, we can change references to any variable then return it:
function getDrink (type) { var drink; var drinks = { 'coke': function () { drink = 'Coke'; }, 'pepsi': function () { drink = 'Pepsi'; }, 'lemonade': function () { drink = 'Lemonade'; }, 'default': function () { drink = 'Default item'; } }; // invoke it (drinks[type] || drinks['default'])(); // return a String with chosen drink return 'The drink I chose was ' + drink; } var drink = getDrink('coke'); // The drink I chose was Coke console.log(drink);
These are very basic solutions, and the Object literals hold a
function that returns a
String, in the case you only need a
String, you could use a
String as the key’s value - some of the time the functions will contain logic, which will get returned from the function. If you’re mixing functions with strings, it might be easier to use a function at all times to save looking up the
type and invoking if it’s a function - we don’t want to attempt invoking a
String.
Object Literal “fall through”
With
switch cases, we can let them fall through (which means more than one case can apply to a specific piece of code):
var type = 'coke'; var snack; switch(type) { case 'coke': case 'pepsi': snack = 'Drink'; break; case 'cookies': case 'crisps': snack = 'Food'; break; default: drink = 'Unknown type!'; } console.log(snack); // 'Drink'
We let
coke and
pepsi “fall through” by not adding a
break statement. Doing this for Object Literals is simple and more declarative - as well as being less prone to error. Our code suddenly becomes much more structured, readable and reusable:
function getSnack (type) { var snack; function isDrink () { return snack = 'Drink'; } function isFood () { return snack = 'Food'; } var snacks = { 'coke': isDrink, 'pepsi': isDrink, 'cookies': isFood, 'crisps': isFood, }; return snacks[type](); } var snack = getSnack('coke'); console.log(snack); // 'Drink'
Summing up
Object literals are a more natural control of flow in JavaScript,
switch is a bit old and clunky and prone to difficult debugging errors. Objects are more extensible, maintainable, and we can test them a lot better. They’re also part of a design pattern and very commonly used day to day in other programming tasks. Object literals can contain functions as well as any other Object type, which makes them really flexible! Each function in the literal has function scope too, so we can return the closure from the parent function we invoke (in this case
getDrink returns the closure).
Some more interesting comments and feedback on Reddit. | https://ultimatecourses.com/blog/deprecating-the-switch-statement-for-object-literals | CC-MAIN-2021-21 | refinedweb | 1,411 | 60.79 |
Basher rogue nzemplois
Nous sommes une brasserie artisanale et cherchons un designer pour la créatuon de 4-5 étiquettes. Des exemples de style : Brewdog Great Dive Rogue
...exemples : [se connecter pour voir l'URL] [se connecter pour voir l'URL] [se connecter pour voir l'URL] Chaque mois, un pays est mis à l'honneur sur l'ensemble de nos jeux
...exemples : [se connecter pour voir l'URL] [se connecter pour voir l'URL] [se connecter pour voir l'URL] Chaque mois, un pays est mis à l'honneur sur l'ensemble de nos jeux
.. / cowboy builder
I need a list of all franchises specifically in Australia and NZ to be provided in a csv or xml format for upload to a franchise directory via this XML. We will organise the XML conversion costs using this system. [se connecter pour voir l'URL] Must include quality images of the franchise and all other relevant data to populate the directory
...images Articles similar to the following are acceptable [se connecter pour voir l'URL] [se connecter pour voir l'URL] Clever use of image here –although another image further down would have helped break up the long text Please quote a estimated price or how
...and rise of Hartin Film Cinema 4 was a movie theater in Rockport, Texas. Hartin went their twice for two years to see the new Star Wars movies The Force Awakens (2015) and Rogue One (2016). in August of 2017 Hurricane Harvey has approached the Coast and wrecked everything, after a month in a half, some of the people were able to return and repair most
Looking to rebrand my business and need a classy logo. Name of business is Inertia NZ - We specialise in digital marketing Must look 2019 and FUN! nothing too boring, don't be afraid to try something different, be experimental file and have
Please ...collective.
First Phase PRoject [se connecter pour voir l : [se connecter pour voir l'URL] eg2 : [se connecter pour voir l'URL] not as complex as above examples but somewhat similar
I need someone to install/write the software and configure the hardware for a device that will capture the cell phone numbers of all nearby cell ...the cell phone numbers of all nearby cell phones. This link shows instructions on one way to accomplish this. [se connecter pour voir l'URL]
Family Travel Logo
.. containing text details, images
...know shopify liquid, and jquery ajax well, it should only be a 5 mins work as there are many examples on the net. The logic is something like this if location.country_code == 'NZ', 'US', 'CA', 'GB' etc then redirect to another URL endif Use the free shopify [se connecter pour voir l.
...(my team will be providing the final audio and graphics) - and I will be taking over the unity coding after you have built the core mechanics for the prototype. My budget is NZ$90-160 (max) I need the following elements: 1. entering a shop and attempting to buy items (including cigarettes) 2. walking around outside the shop and map creation 3. looking
Update existing Wordpress website. Current site is [se connecter pour voir l'URL] and the new layout is attached as a PDF. Require pri...scripts and layouts • Ongoing client changes up to 'Go Live' • Additional milestone for 1 month developer support following 'Go Live' • Ideally need to be contactable during NZ time of day from 0:700 - 10:00 hours.
Logo designer required for ongoing project, paid in NZ$ fortnightly. Paham English bagus dah.
..
..'m running a new website on wordpress and requiere help to improve the traffic, ranki...speed up the loading time of my site. i want someone who can help to target SEO from around the world but specially from English speaking countries like USA, CAD, UK, IE, AUS & NZ Have to mention I'm interested in white hat services The budget is up to €70.00
I am looking for an affordable Chartered Accountant for a small
Content For [se connecter pour voir l'URL] [se connecter pour voir l'URL] [se connecter pour voir l'URL] [se connecter pour voir l'URL] [se connecter pour voir l'URL] For [se connecter pour voir l'URL] [se connecter pour voir l'URL] [se connecter pour voir l'URL] [se connecter pour voir l [se connecter pour voir l'URL], [se connecter pour voir l'URL] etc.
I need logo and brand design for my buisness based around bubblewaffles that's a hongkong street food. sells out of a food trailer in Christchurch NZ Company: Bubblewaffles ltd Domain: [se connecter pour voir l'URL] Email Gardencitywaffles@[se connecter pour voir l'URL]
We need to get pricing from our competitors in Australia & NZ | https://www.fr.freelancer.com/job-search/basher-rogue-nz/ | CC-MAIN-2019-04 | refinedweb | 793 | 67.28 |
Hi,
First off I am new to java and I am doing some self-study.
I have wrote a program that asks the user to enter two numbers and displays the sum of these two numbers, it then gives the user a opportunity to have another go or to quit the program:
public class Numbers
{
public static void main(String[] args)
{
int num1, num2;
char choice;
do
{
System.out.print("Enter a number: ");
num1 = EasyIn.getInt();
System.out.print("Enter another number: ");
num2 = EasyIn.getInt();
System.out.println("The sum of the two numbers is "
+ (num1 + num2));
System.out.print ("Do you want another go (y/n): ");
choice = EasyIn.getChar();
}while(choice == 'y');
}
}
I have a couple of questions:
• How could I adapt the above program so the user would be given another go irrespective of whether or not an upper case or lower case ‘y’ is entered?
• How could I make it so instead of displaying the sum of the numbers, it asks the user to enter the sum. Then if it is correct a congratulations message is displayed and if incorrect then the correct answer is displayed.
Any feedback would be much appreciated. | http://forums.devx.com/printthread.php?t=140657&pp=15&page=1 | CC-MAIN-2015-11 | refinedweb | 195 | 61.97 |
A sealed class is like a normal class but we cannot inherit it.
The Main use of the sealed class is to take the inheritance component from the class users so they cannot derive a class from it.
A sealed class is used to stop a class to be inherited.
A sealed class can restrict access to the classes and their members with the help of a sealed keyword and we can also avoid inheriting the defined classes from other classes.
Similarly if a method is declared using sealed keyword, we cannot override it.
A sealed class can define constructors in C#.
Let’s get started.
Step-1: create a new project and select a console application and click on the Next button
Step-2: give the project name and set it to the location and click on the Next button
Step-3: choose the target framework click on the Next button
Step-4:In the following code, I create a sealed class SealedClass and use it from Program class.
using System; // Sealed class public sealed class SealedClass { public int Add(int x, int y) { return x + y; } } class program { static void Main(string[] args) { SealedClass sealedCls = new SealedClass(); int total = sealedCls.Add(4, 5); Console.WriteLine("Total = " + total.ToString()); } }
Step-5: Here is the output of the sealed class we created.
Step-6: if you try to derive a class from the SealedClass, you will get an error.
public class Animal { public virtual void eat() { Console.WriteLine("eating..."); } public virtual void run() { Console.WriteLine("running..."); } } public class Dog: Animal { public override void eat() { Console.WriteLine("eating bread..."); } public sealed override void run() { Console.WriteLine("running very fast..."); } } public class BabyDog: Dog { public override void eat() { Console.WriteLine("eating biscuits..."); } //when we try to override sealed method error is generated //public override void run() { Console.WriteLine("running slowly..."); } } class Program { static void Main(string[] args) { BabyDog d = new BabyDog(); d.eat(); d.run(); } }
when we try to inherit a sealed class this is the compile-time error
Hope the concept of sealed class is clear. | https://www.thecodehubs.com/sealed-class-in-c/ | CC-MAIN-2022-21 | refinedweb | 345 | 64.71 |
Technical Support
Support Resources
Product Information
Information in this article applies to:
Is it possible to use long pointer arithmetic with the far memory
support in Cx51? I'm using a device has a extended XDATA address
space. I know that a far object can only be up to 64KB in size and
resides within a 64KB segment, but I need to generic pointer access
to the whole memory for FLASH programming. Is this possible directly
in C?
Yes. In C51 Version 7 we have introduced long pointer arithmetic
on far variables for exactly this purpose. For example,
#include <absacc.h>
bit verify (void) {
unsigned long addr;
for (addr = 0; addr < 0x40000; addr++) {
if (FVAR (unsigned char, addr) != FCVAR (unsigned char, addr + 0x10000L)) {
return (0);
}
}
}
This program compares the XDATA RAM starting at address 0 with the
CODE ROM starting at address 0x10000. You may use similar functions
to check that the FLASH was programmed correctly.
Last Reviewed: Monday, July 18,. | http://www.keil.com/support/docs/2276.htm | CC-MAIN-2020-10 | refinedweb | 161 | 63.8 |
NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.
Microcontroller Programming » Making a library?
Has anyone started a thread where they explain how to make a library and how to store and use them once created?
i know that i need a .H file and .c file included but am not real sure how to create one form scratch.
Thanks
Jim
Jim -
I've read one or two threads on the subject on this forum, but they were mostly abstract discussions and Makefile questions. I'm assuming you want to create a library like the Nerdkits library of lcd.c, delay.c etc and not the full blown <stdio.h> type libraries.
The .c and .h files are text files like any other source code files. It is when you compile them that the differences show up. Take the delay.c source code file for instance. Since it does not have a "main()" function in it, it cannot be compiled into an executable program ( for AVR an executable has the .hex extension). What you can do though, is create an object file from it (.o extention). That is the basic goal of a making a library module...the object file. If you look at the "Makefile" inside the "libnerkits" directory you will see the command line you can use to create an object file from your source code file (i.e. text file). As an example if you hid the "delay.o" file from your computer, you can re-create it with this command line:
avr-gcc -g -Os -Wall -mmcu=atmega168 -o delay.o -c delay.c
Once you have an object file, you can link that object file into any program you want.
The .h header files are used when a new program wants to used previously created functions from that .h file. When you type "include delay.h" into your new source code (.c file) the compiler will search "delay.h" for the definition of any particular function. That definition includes the name of the function, the return type of variable and the types of arguments supplied to that function. From there the comiler can create an object file from your new .c file. In the final step, you will need the delay.o file to link with your new .o file to create the final .hex file.
Hope I didn't muddy the question too much.
Thanks PCbolt, I am trying to learn several things at the same time and it occurred to me that it would be good to know how to create a library to store items to use in several projects...
I agree completely. I don't consider a project finished until I have a working 'library' that incorporates all the code needed to operate a certain piece of hardware. I just finished making a 2-wire shift register interface for the LCD screen and all I had to do was modify the Nerdkit library a little bit and use the same function calls the previous projects used. BTW it is really convenient to only need to hookup 2 wires instead of 6 when changing the LCD from one project to another (saves some valuable port pins too). Good luck on your project!
Ahem,
I just finished making a 2-wire shift register interface for the LCD screen
I just finished making a 2-wire shift register interface for the LCD screen
Gee, what a good article that would make in the Nerdkit Community Library.
I use Ricks_S's I2C LCD pcb Backpack that he had made up.
With his I2C LCD library.
It is really great to have such a clean breadboard and to have PORTD available.
It would really be interesting to have a shift register method in the library so that there is a ready reference to the two 2 wire LCD methods.
I imagine the shift register would be faster than I2C.
Ralph
Ralph -
I got most of the information HERE. Zoran (aka Wayward) put together a great webpage describing the nuts and bolts of the project (he posted a link on the forum page). The really interesting part is how to get away with using only two pins and one diode/resistor pair to create an AND gate. My only changes to the project are using a dedicated high-speed shift register instead of a flip-flop, and I only needed to modify a small section of the original Nerdkit LCD code. I'm on a business trip now, but when I get back, I'll try to post a pic or two along with the modified portions of the code.
Here are the pics I promised...
pcbolt, nice neat proto board.
You must have drastically changed something to get that <= 120.
That large font is rather attractive.
I'd like to see that on my 4x40 LCD.
Actually, the funny thing is, to make the large digits you only need to introduce 3 new characters in the LCD RAM. All the digits can be made from these 3 new "characters", a blank space (0x20) and the "full" character (0xff). The arrows took up more LCD RAM than the digits (4 new characters for left and right arrows). I'll post some code when I get a chance.
Here you go Ralph -
Start with some includes:
#include <inttypes.h>
#include <avr/pgmspace.h>
#include "../libnerdkits/lcd.h"
#include "../libnerdkits/delay.h"
Next I just charted out the individual characters the way I wanted them to look (this isn't code just a comment section) and assigned a hex value for each bit pattern:
/******************************************************************************
CGRAM bitmap patterns for LCD
// NUMBERS
// Symbol "1" // Symbol "2" // Symbol "3"
(0b00011111) 0x1F (0b00000000) 0x00 (0b00011111) 0x1F
(0b00011111) 0x1F (0b00000000) 0x00 (0b00011111) 0x1F
00011111) 0x1F (0b00011111) 0x1F
(0b00000000) 0x00 (0b00011111) 0x1F (0b00011111) 0x1F
// ARROWS
// Symbol "4" // Symbol "5" // Symbol "6" // Symbol "7"
(0b00000001) 0x01 (0b00011111) 0x1F (0b00010000) 0x10 (0b00011111) 0x1F
(0b00000001) 0x01 (0b00001111) 0x0F (0b00010000) 0x10 (0b00011110) 0x1E
(0b00000011) 0x03 (0b00000111) 0x07 (0b00011000) 0x18 (0b00011100) 0x1C
(0b00000011) 0x03 (0b00000111) 0x07 (0b00011000) 0x18 (0b00011100) 0x1C
(0b00000111) 0x07 (0b00000011) 0x03 (0b00011100) 0x1C (0b00011000) 0x18
(0b00000111) 0x07 (0b00000011) 0x03 (0b00011100) 0x1C (0b00011000) 0x18
(0b00001111) 0x0F (0b00000001) 0x01 (0b00011110) 0x1E (0b00010000) 0x10
(0b00011111) 0x1F (0b00000001) 0x01 (0b00011111) 0x1F (0b00010000) 0x10
*********************************************************************************/
Then I packed the hex codes into program memory to save MCU RAM space:
uint8_t symbols[] PROGMEM = {0x1F,0x1F,0x00,0x00,0x00,0x00,0x00,0x00, // Symbol "1"
0x00,0x00,0x00,0x00,0x00,0x00,0x1F,0x1F, // Symbol "2"
0x1F,0x1F,0x00,0x00,0x00,0x00,0x1F,0x1F, // Symbol "3"
0x01,0x01,0x03,0x03,0x07,0x07,0x0F,0x1F, // Symbol "4"
0x1F,0x0F,0x07,0x07,0x03,0x03,0x01,0x01, // Symbol "5"
0x10,0x10,0x18,0x18,0x1C,0x1C,0x1E,0x1F, // Symbol "6"
0x1F,0x1E,0x1C,0x1C,0x18,0x18,0x10,0x10}; // Symbol "7"
Now you just need the character pattern to go with each numeral you are printing. There are 3 horizontal characters per numeral and 2 vertical so they can be split apart into "top" and "bot" sequences (again packed away nicely into program space):
uint16_t top[] PROGMEM = {0x0919,0x0190,0x0339,0x0139,0x0929,0x0933,0x0933,0x0119,0x0939,0x0939};
uint16_t bot[] PROGMEM = {0x0929,0x0292,0x0922,0x0229,0x0009,0x0229,0x0929,0x0009,0x0929,0x0229};
As an example, take the second entry in "top[]" which is the printing sequence for the top of numeral "1" is 0x0910. As you will see later, the first "nibble" 0 is ignored, the second nibble 9 is code for the "all black" character (0xff), the third nibble 1 will print the custom "Symbol 1" above and the fourth nibble 0 will print a space character (0x20).
The first function used is for storing the bit patterns into the LCD CGRAM and assigning them a character code:
void init_big_num(){
uint8_t i, j, value;
for (j = 0; j < 7; j++){
lcd_set_type_command();
lcd_write_byte(0x40 | ((j + 1) << 3)); // assign char code # (j + 1) in CGRAM
lcd_set_type_data();
for (i = 0; i < 8; i++){
value = pgm_read_byte(&(symbols[(j * 8) + i]));
lcd_write_byte(value);
delay_ms(1);
}
}
return;
}
To print a numeral at a specific location you call this function:
void draw_big_digit(uint8_t row, uint8_t col, uint8_t digit){
int8_t i, symbol;
if (digit > 9) digit = 0;
if (row > 2) row = 2;
if (col > 17) col = 17;
lcd_goto_position(row, col); // write top row
for (i = 0; i < 3; i++){
symbol = ((pgm_read_word(&(top[digit]))) >> ((2 - i) * 4)) & 0x0f;
if (symbol == 9) symbol = 0xff;
if (symbol == 0) symbol = 0x20;
lcd_write_data(symbol);
}
lcd_goto_position(++row, col); // write bottom row
for (i = 0; i < 3; i++){
symbol = ((pgm_read_word(&(bot[digit]))) >> ((2 - i) * 4)) & 0x0f;
if (symbol == 9) symbol = 0xff;
if (symbol == 0) symbol = 0x20;
lcd_write_data(symbol);
}
return;
}
This just unpacks the sequence of symbols and prints them. I made the "draw arrows" functions easier:
void draw_left_arrow(uint8_t row, uint8_t col){
if (row > 2) row = 2;
if (col > 17) col = 17;
lcd_goto_position(row, col);
lcd_write_data(4);
lcd_write_data(2);
lcd_write_data(2);
lcd_goto_position(++row, col);
lcd_write_data(5);
lcd_write_data(1);
lcd_write_data(1);
return;
}
void draw_right_arrow(uint8_t row, uint8_t col){
if (row > 2) row = 2;
if (col > 17) col = 17;
lcd_goto_position(row, col);
lcd_write_data(2);
lcd_write_data(2);
lcd_write_data(6);
lcd_goto_position(++row, col);
lcd_write_data(1);
lcd_write_data(1);
lcd_write_data(7);
return;
}
Feel free to use this for your 4x40 LCD. I created it to use outdoors at a distance to guide a (slow moving!) vehicle operator to drive a straight line at the right location.
Typo alert!
Should read:
Please log in to post a reply. | http://www.nerdkits.com/forum/thread/2383/ | CC-MAIN-2018-09 | refinedweb | 1,570 | 67.89 |
Which interval would be the best first (leftmost) interval to keep? One that ends first, as it leaves the most room for the rest. So take one with smallest
end, remove all the bad ones overlapping it, and repeat (taking the one with smallest
end of the remaining ones). For the overlap test, just keep track of the current end, initialized with negative infinity.
Ruby
Take out intervals as described above, so what's left is the bad overlapping ones, so just return their number.
def erase_overlap_intervals(intervals) end_ = -1.0 / 0 intervals.sort_by(&:end).reject { |i| end_ = i.end if i.start >= end_ }.size end
Alternatively,
i.start >= end_ and end_ = i.end works, too.
Python
def eraseOverlapIntervals(self, intervals): end = float('-inf') erased = 0 for i in sorted(intervals, key=lambda i: i.end): if i.start >= end: end = i.end else: erased += 1 return erased
I personally prefer to initialize an infinitely small number with
None, because
None is smaller than any number. Is it a good idea or bad idea?
@NoAnyLove I think it's bad. It's not terribly natural, it's not in the Python specification but only an implementation detail of the current CPython implementation, and in Python 3 it was removed.
@StefanPochmann I see, thanks a lot.
@NoAnyLove On the other hand, I did just abuse it in a solution for another problem. It was just too convenient, and that solution isn't serious anyway :-)
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/65672/short-ruby-and-python | CC-MAIN-2018-05 | refinedweb | 259 | 68.97 |
One of the nice features of 3.0 is that differences between classes defined in C and Python (other than speed) are mostly erased or hidden from the view of a Python programmer.
However, there are still sometimes surprising and quite visible differences between 'functions' written in C and Python. Can these be better unified also?
In particular, built-in functions, in spite of of being labeled 'builtin_function_or_method', are not usable as methods because they lack the __get__ method needed to bind function to instance.
[Q. Any reason to not shorten that to 'built-in function'?]
So, as a c.l.p poster discovered, within a class statement,
__hash__ = lambda x: id(x) # works, while the apparently cleaner __hash__ = id # raises TypeError: id() takes exactly one argument (0 given)
[Irony: trivial lambda wrapping, lambda x: f(x) has been described here as useless and diseased, but is seems that casting 'built-in function' to 'function' is not so completely useless. ;-]
In this case, __hash__ = object.__hash__ is available, as is object.__repr__, but this is not true in general for C functions.
The difference between a C function and a C method wrapper is tantalizingly small:
i = set(dir(id)) h = set(dir(object.__hash__)) i-h
{'__module__', '__self__'}
h-i
{'__objclass__', '__get__'}
Similarly, for
def f(): pass
ff = set(dir(f)) ff - i
{'__defaults__', '__annotations__', '__kwdefaults__', '__globals__', '__closure__', '__dict__', '__code__', '__get__'}
the only un-obvious difference is __get__,
So I cannot help but wonder: is this is essential? or could it be removed but has not yet? Could the object wrapper for C functions get a __get__ method so they become methods when accessed via a class just like Python functions do?
Terry Jan Reedy | https://mail.python.org/archives/list/python-dev@python.org/message/RWBVE64L272NYKD7B4OGNOXHJNR36KBX/ | CC-MAIN-2021-25 | refinedweb | 286 | 63.09 |
|< C Storage Class & Memory Functions | Main | C Run-Time 2 >| Site Index | Download |
MODULE A
IMPLEMENTATION SPECIFIC
MICROSOFT C Run-Time 1
My Training Period: hours
Note:). All programs are in debug mode, run on Windows 2000 and Xp Pro.
- The Compiler Options, Preprocessor Directives and other configuration settings can be accessed from Project menu → your_project_name Properties... sub menu.
- It also can be accessed by selecting your project directory (in the Solution Explorer pane) → Right click → Select the Properties menu as shown below.
Figure 1
- The following Figure is a project Property pages.
Figure 2.
- If you link your program from the command line without a compiler option that specifies a C run-time library, the linker will use LIBC.LIB by default.
- To build a debug version of your application, the _DEBUG flag must be defined and the application must be linked with a debug version of one of these libraries.
- However in this Module and that follows we will compile and link by using the Visual C++ .Net IDEs’ menus instead of command line :o).
- The run-time libraries also include .lib files that contain the iostream library and the Standard C++ Library. You should never have to explicitly link to one of these .lib files; the header files in each library link in the correct .lib file.
- The programs that use this old iostream library will need the .h extension for the header files.
- Before Visual C++ 4.2, the C run-time libraries contained the iostream library functions. In Visual C++ 4.2 and later, the old iostream library functions have been removed from LIBC.LIB, LIBCD.LIB, LIBCMT.LIB, LIBCMTD.LIB, MSVCRT.LIB, and MSVCRTD as shown in the following Table.
- The new iostream functions, as well as many other new functions, that exist in the Standard C++ Library are shown in the following Table.
- The programs that use this new iostream library will need the header files without the .h extension such as <string>.
- The Standard C++ Library and the old iostream library are incompatible, that is they cannot be mixed and only one of them can be linked with your project.
- The old iostream library created when the standard is not matured yet.
-, for example:
▪ If you include a Standard C++ Library header in your code, a Standard C++ Library will be linked in automatically by Visual C++ at compile time. For example:
#include <ios>
▪ If you include an old iostream library header, an old iostream library will be linked in automatically by Visual C++ at compile time. For example:
#include <ios.h>
- preprocessor directives are automatically defined. Also read Module 23 for the big picture.
- As a conclusion, for typical C and C++ programs, by providing the proper header files just let the compiler determine for you which libraries are appropriate to be linked in.
- The following sections will dive more detail some of the functions available in the C run-time library.
- These functions used to create routines that can be used to automate many tasks in Windows that not available in the standard C/C++.
- We will start with category, then the functions available in that category and finally followed by program examples that use some of the functions.
- The functions discussed here mostly deal with directories and files.
- For complete information please refer to Microsoft Visual C++ documentation (online MSDN: Microsoft Visual C++). As a remainder, the following are the things that must be fully understood when you want to use a function, and here, _chsize() is used as an example.
1. What is the use of the function? This will match with "what are you going to do or create?" Keep in mind that to accomplish some of the tasks you might need more (several) than one function. For example:
_chsize() used to change the file size.
2. What is the function prototype, so we know how to write (call) a proper syntax of the function. For example:
int _chsize(int handle, long size);
3. From the function prototype, how many parameters, the order and what are their types, so we can create the needed variables. For example:
4. What header files need to be included? For example the _chsize needs:
<io.h>
5. What is the return type and value? For example:
_chsize returns 0 if the file size is successfully changed. A return value of –1 indicates an error: errno is set to EACCES if the specified file is locked against access, to EBADF if the specified file is read-only or the handle is invalid, or to ENOSPC if no space is left on the device.
- Hence, you are ready to use the function in any of your programs. If you still blur about functions, please read C & C++ Functions tutorial. Not all the needed information is provided here and for complete one, please refers to the Microsoft Visual C++/MSDN/SDK Platform documentations or HERE.
- For C++, together with the classes, it is used when you develop programs using Microsoft Foundation Class (MFC) and Automatic Template Library (ATL).
- The notation convention used for identifiers in MSDN documentation is Hungarian Notation and is discussed C/C++ Notations.
--------------------The Story and Program Examples---------------------
- Functions available in this category used to access, modify, and obtain information about the directory structure and are listed in the following Table.
- Notice that most of the function names are similar to the standard C wherever available, except prefixed with underscore ( _ ) :o). The functions available in this category are listed in the following Table.
Directory Management Functions
- The following Table lists functions used for directory control and management.
- The following is an example of the needed information in order to use the _getdrives() function.
- The following program example uses the _getdrives() function to list the available logical drives in the current machine.
#include <windows.h>
#include <direct.h>
#include <stdio.h>
#include <tchar.h>
//Buffer, be careful with terminated NULL
//Must match with ++mydrives[1]...that is one space
//Example if no one space: "A:"--> ++mydrives[0];
TCHAR mydrives[] = " A: ";
//Or char mydrives[] = {" A: "};
//Or char mydrives[] = " A: ";
int main()
{
//Get the drives bit masks...1 is available, 0 is not available
//A = least significant bit...
ULONG DriveMask = _getdrives();
//If something wrong
if(DriveMask == 0)
printf("_getdrives() failed with failure code: %d\n", GetLastError());
else
{
printf("This machine has the following logical drives:\n");
while (DriveMask)
{ //List all the drives...
if(DriveMask & 1)
printf(mydrives);
//Go to the next drive strings with one space
++mydrives[1];
//Shift the bit masks binary
//to the right and repeat
DriveMask >>= 1;
}
printf("\n");
}
return 0;
}
The output:
This machine has the following logical drives:
A: C: D: E: F: G: H: I: J: K: L:
Press any key to continue
- The following is an example of the needed information in order to use the _getdiskfree() function.
- The following program example uses the _getdiskfree() function to list logical drives information in the current machine.
#include <windows.h>
#include <direct.h>
#include <stdio.h>
#include <tchar.h>
TCHAR g_szText[] = _T("Drive Total_clus Available_clus Sec/Cluster Bytes/Sec\n");
TCHAR g_szText1[] = _T("----- ---------- -------------- ----------- ---------\n");
TCHAR g_szInfo[] = _T("-> \n");
//For data display format...
//Right justified, thousand comma separated and other format
//for displayed data
void utoiRightJustified(TCHAR* szLeft, TCHAR* szRight, unsigned uValue)
{
TCHAR* szCur = szRight;
int nComma = 0;
if(uValue)
{
while(uValue && (szCur >= szLeft))
{
if(nComma == 3)
{
*szCur = ',';
nComma = 0;
}
else
{
*szCur = (uValue % 10) | 0x30;
uValue /= 10;
++nComma;
}
--szCur;
}
}
else
{
*szCur = '0';
--szCur;
}
if(uValue)
{
szCur = szLeft;
while(szCur <= szRight)
{//If not enough field to display the data...
*szCur = '*';
++szCur;
}
}
}
int main()
{
TCHAR szMsg[4200];
struct _diskfree_t df = {0};
//Search drives and assigns the bit masks to
//uDriveMask variable...
ULONG uDriveMask = _getdrives();
unsigned uErr, uLen, uDrive;
printf("clus - cluster, sec - sector\n");
printf(g_szText);
printf(g_szText1);
for(uDrive = 1; uDrive <= 26; ++uDrive)
{
//If the drive is available...
if(uDriveMask & 1)
{ //Call _getdiskfree()...
uErr = _getdiskfree(uDrive, &df);
//Provide some storage
memcpy(szMsg, g_szInfo, sizeof(g_szInfo));
szMsg[3] = uDrive + 'A' - 1;
//If _getdiskfree() is no error, display the data
if(uErr == 0)
{
utoiRightJustified(szMsg+4, szMsg+15, df.total_clusters);
utoiRightJustified(szMsg+18, szMsg+29, df.avail_clusters);
utoiRightJustified(szMsg+27, szMsg+37, df.sectors_per_cluster);
utoiRightJustified(szMsg+40, szMsg+50, df.bytes_per_sector);
}
else
{//Print system message and left other fields empty
uLen = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, uErr, 0, szMsg+8, 4100, NULL);
szMsg[uLen+6] = ' ';
szMsg[uLen+7] = ' ';
szMsg[uLen+8] = ' ';
}
printf(szMsg);
}
//shift right the found drive bit masks and
//repeat the process
uDriveMask >>= 1;
}
return 0;
}
The output:
clus - cluster, sec - sector
Drive Total_clus Available_clus Sec/Cluster Bytes/Sec
----- ---------- -------------- ----------- ---------
-> A 2,847 834 1 512
-> C 2,560,351 62,315 8 512
-> D 2,560,351 1,615,299 8 512
-> E 2,560,351 2,310,975 8 512
-> F 2,560,351 2,054,239 8 512
-> G 2,353,514 2,039,396 8 512
-> H 2,560,351 2,394,177 8 512
-> I 2,381,628 1,618,063 8 512
-> J 321,935 0 1 2,048
-> L 63,419 20,706 16 512
Press any key to continue
- Note that J: is CD-RW, L: is thumb drive and A: is a floppy. For floppy and CD-ROM, you have to insert the media.
- The following is an example of the needed information in order to use the _getdrive() function.
- The following Table lists the needed information in order to use the _chdir(), _wchdir() functions.
- will be changed as well.
- For example, if A is the default drive letter and \BIN is the current working directory, the following call changes the current working directory for drive C and establishes C as the new default drive:
_chdir("c:\\te | http://www.tenouk.com/ModuleA.html | crawl-001 | refinedweb | 1,614 | 62.98 |
Ctrl+P
With this extension, view a live WebGL preview of GLSL shaders within VSCode, similar to shadertoy.com by providing a "Show GLSL Preview" command.
To run the command, either open the "Command Palette" and type "Shader Toy: Show GLSL Preview" or right-click inside a text editor and select "Shader Toy: Show GLSL Preview" from the context menu.
Running the command splits the view and displays a fullscreen quad with your shader applied. Your fragment shader's entry point is void main() or if that is unavailable void mainImage(out vec4, in vec2) where the first parameter is the output color and the second parameter is the fragments screen position.
void main()
void mainImage(out vec4, in vec2)
An alternative command "Shader Toy: Show Static GLSL Preview" is available, which will open a preview that does not react to changing editors. An arbitrary amount of those views can be opened at one time, which enables a unique workflow to edit shaders that rely on multiple passes.
At the moment, iResolution, iGlobalTime (also as iTime), iTimeDelta, iFrame, iMouse, iMouseButton, iDate, iSampleRate, iChannelN with N in [0, 9] and iChannelResolution[] are available uniforms.
iResolution
iGlobalTime
iTime
iTimeDelta
iFrame
iMouse
iMouseButton
iDate
iSampleRate
iChannelN
N in [0, 9]
iChannelResolution[]
The texture channels iChannelN may be defined by inserting code of the following form at the top of your shader
#iChannel0 ""
#iChannel1 ""
#iChannel2 ""
#iChannel2 "self"
#iChannel4 ""
This demonstrates using local and remote images as textures (Remember that power of 2 texture sizes is generally what you want to stick to.), using another shaders results as a texture, using the last frame of this shader by specifying self or using audio input. Note that to use relative paths for local input you will have to open a folder in Visual Code.
To influence the sampling behaviour of a texture, use the following syntax:
self
#iChannel0::MinFilter "NearestMipMapNearest"
#iChannel0::MagFilter "Nearest"
#iChannel0::WrapMode "Repeat"
Though keep in mind that, because of the WebGL standard, many options will only work with textures of width and height that are power of 2.
Cubemaps may be specified as any other texture, the fact that they are cubemaps is a combination of their path containing a wildcard and their type being explicitly stated.
#iChannel0 "{}.jpg" // Note the wildcard '{}'
#iChannel0::Type "CubeMap"
The wildcard will be resolved by replacement with values from any of the following sets
If any of the six files can not be found, the next set is tried, starting from the first.
Note: By default audio input is disabled, change the setting "Enable Audio Input" to use it.
Audio input is not supported from within Visual Studio Code, since ffmpeg is not shipped with Visual Studio Code, so you will have to generate a standalone version and host a local server to be able to load local files (or fiddle with your browsers security settings) if you want to use audio in your shaders.
If your channel defines audio input, it will be inferred from the file extension. The channel will be a 2 pixels high and 512 pixels wide texture, where the width can be adjusted by the "Audio Domain Size" setting. The first row containing the audios frequency spectrum and the second row containing its waveform.
2
512
If you want to use keyboard input you can prepend #iKeyboard to your shader. This will expose to your shader the following functions:
#iKeyboard
bool isKeyPressed(int);
bool isKeyReleased(int);
bool isKeyDown(int);
bool isKeyToggled(int);
Additionally it will expose variables such as Key_A to Key_Z, Key_0 to Key_9, Key_UpArrow, Key_LeftArrow, Key_Shift, etc. Use these constants together with the functions mentioned above to query the state of a key.
Key_A
Key_Z
Key_0
Key_9
Key_UpArrow
Key_LeftArrow
Key_Shift
You may also include other files into your shader via a standard C-like syntax:
#include "some/shared/code.glsl"
#include "other/local/shader_code.glsl"
#include "d:/some/global/code.glsl"
These shaders may not define a void main() function and as such can be used only for utility functions, constant definitions etc.
To use custom uniforms define those directly in your shader, giving an initial value as well as an optional range for the uniform.
#iUniform float my_scalar = 1.0 in { 0.0, 5.0 } // This will expose a slider to edit the value
#iUniform float my_discreet_scalar = 1.0 in { 0.0, 5.0 } step 0.2 // This will expose a slider incrementing at 0.2
#iUniform float other_scalar = 5.0 // This will expose a text field to give an arbitrary value
#iUniform color3 my_color = color3(1.0) // This will be editable as a color picker
#iUniform vec2 position_in_2d = vec2(1.0) // This will expose two text fields
#iUniform vec4 other_color = vec4(1.0) in { 0.0, 1.0 } // This will expose four sliders
The following is an example of a shader ported from shadertoy.com:
// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
// Created by S.Guillitte
void main() {
float time = iGlobalTime * 1.0;
vec2 uv = (gl_FragCoord.xy / iResolution.xx - 0.5) * 8.0;
vec2 uv0 = uv;
float i0 = 1.0;
float i1 = 1.0;
float i2 = 1.0;
float i4 = 0.0;
for (int s = 0; s < 7; s++) {
vec2 r;
r = vec2(cos(uv.y * i0 - i4 + time / i1), sin(uv.x * i0 - i4 + time / i1)) / i2;
r += vec2(-r.y, r.x) * 0.3;
uv.x;
gl_FragColor = vec4(r, g, b, 1.0);
}
Note that compared to shadertoy.com gl_FragCoord replaces fragCoord and gl_FragColor replaces fragColor in the original demo. There is however a rudimentary support for inserting a trivial void main() which will delegate to a void mainImage(out vec4, in vec2) function. The definition of void main() is found by matching the regex /void\s+main\s*\(\s*\)\s*\{/g, thus if you require to define void main() in addition to the extension generating a definition you may define it as void main(void). This might be necessary, for example, if your main definition would be processed away by the preprocessor and should thus not be picked up by the extension.
Since compatibility is achieved with a simple regex match it is only semi-reliable. If you only use shaders from shadertoy.com that do things such as defining mainImage via macros you may want to enable the "Shader Toy Strict Compatibility" setting, which disables the ability to use shaders that define void main() and only allows shaders that define mainImage in some way. Alternatively you can use #StrictCompatibility in your shader to have this feature localized to just that shader.
gl_FragCoord
fragCoord
gl_FragColor
fragColor
/void\s+main\s*\(\s*\)\s*\{/g
void main(void)
mainImage
#StrictCompatibility
You can enable support for glslify in the settings, but because glslify does not support line mappings pre and post its transform, line numbers on errors will unfortunately be disabled as long as you have the setting enabled. Using glslify allows using a node.js-style module system for your shaders:
#pragma glslify: snoise = require('glsl-noise/simplex/2d')
float noise(in vec2 pt) {
return snoise(pt) * 0.5 + 0.5;
}
void main () {
float r = noise(gl_FragCoord.xy * 0.01);
float g = noise(gl_FragCoord.xy * 0.01 + 100.0);
float b = noise(gl_FragCoord.xy * 0.01 + 300.0);
gl_FragColor = vec4(r, g, b, 1);
}
The extension provides a pause button inside the GLSL Preview to stop the progression of time. In conjunction with this you can use the screenshot button provided inside the GLSL Preview to capture and save a frame. The resolution of the saved screenshot will by default be the same resolution as the GLSL Preview, though a setting is available that allows the user to override the resolution with an arbitrary value. Lastly the extension provides a superficial view into the shaders performance and memory consumption.
The extension also supports highlighting of compilation errors in the text editor, for single shaders but also for multiple passes. It does so by showing errors as diagnostics directly in the text editor as well as presenting them in a digestible format inside the GLSL Preview and allowing the user to interact with the error messages to jump to the relevant lines, and open the relevant files if necessary:
Contributions of any kind are welcome and encouraged.
GitHub Project Page
Visual Studio Marketplace
This patch adds the ability to view GLSL compiler errors. They are currently displayed as a list in the preview viewport.
Fix for error when settings.json is not present (no textures defined)
Adds support for texture channels.
Add support for a few more of the uniforms, and implements a 1 second time delay between modifying the source and recompilation.
Initial release of shadertoy for vscode. Many uniforms not available.
Screenshot feature's camera icon made by Smashicons from. | https://marketplace.visualstudio.com/items?itemName=stevensona.shader-toy | CC-MAIN-2021-21 | refinedweb | 1,458 | 54.63 |
Basic geometric transformations – OpenCV 3.4 with python 3 Tutorial 12
import cv2 import numpy as np img = cv2.imread("red_panda.jpg") rows, cols, ch = img.shape print("Height: ", rows) print("Width: ", cols) scaled_img = cv2.resize(img, None, fx=1/2, fy=1/2) matrix_t = np.float32([[1, 0, -100], [0, 1, -30]]) translated_img = cv2.warpAffine(img, matrix_t, (cols, rows)) matrix_r = cv2.getRotationMatrix2D((cols/2, rows/2), 90, 0.5) rotated_img = cv2.warpAffine(img, matrix_r, (cols, rows)) cv2.imshow("Original image", img) cv2.imshow("Scaled image", scaled_img) cv2.imshow("Translated image", translated_img) cv2.imshow("Rotated image", rotated_img) cv2.waitKey(0) cv2.destroyAllWindows()
Files:
4 Comments
- Sergio Canu July 11, 2018 at 3:43 pm
Hi Mustafa,
it’s easy. It works in the same way but inside a loop, as for a video you need to process frame by frame.
Here is the code for a video:
[python]
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
# Git first frame to take the size of frame
_, frame = cap.read()
rows, cols, ch = frame.shape
print("Height: ", rows)
print("Width: ", cols)
while True:
_, frame = cap.read()
scaled_img = cv2.resize(frame, None, fx=1 / 2, fy=1 / 2)
matrix_t = np.float32([[1, 0, -100], [0, 1, -30]])
translated_img = cv2.warpAffine(frame, matrix_t, (cols, rows))
matrix_r = cv2.getRotationMatrix2D((cols / 2, rows / 2), 90, 0.5)
rotated_img = cv2.warpAffine(frame, matrix_r, (cols, rows))
cv2.imshow("Original image", frame)
cv2.imshow("Scaled image", scaled_img)
cv2.imshow("Translated image", translated_img)
cv2.imshow("Rotated image", rotated_img)
key = cv2.waitKey(1)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
[/python]
- Hanan Avraham March 26, 2019 at 9:38 am
Hi,
part of my final project to software engineer study we need to calculate Plant area.
we need to take photo of the plant each day, and calculate the area to check the Growth of the Plant.
do you have ant solution for me please..?
Thanks.
- Sergio Canu March 27, 2019 at 9:06 pm
Hi Hanan, it seems a simple task to achieve.
You could create a mask by the color of the plant (you can see here how) and then calculate the area of the white part in the sergio
my name ist mustafa im a student in germany and i have projekt with opencv. I saw your Tutorial 12 and would like to ask you how i can do the same with cv2.videocapture(0) .
i would appreciate it if you could help me with this. | https://pysource.com/2018/02/12/basic-geometric-transformations-opencv-3-4-with-python-3-tutorial-12/ | CC-MAIN-2019-35 | refinedweb | 413 | 79.56 |
On Tue, 2008-04-08 at 17:53 -0700, H. Peter Anvin?In short application migration. When you move a running applicaitonfrom one machine to another you want to be able to keep the same pseudodevices.The isolation that you have noticed is also an important application andlike the rest of the namespaces if we can solve the duplicate identifierproblem needed to restore checkpoints we also largely solve theisolation problem.This problem is much larger then ptys. ptys are the really in your faceaspect of it. There are a more pseudo devices in the kernel and it isthe device number to device mapping that we are abstracting. So thisreally should be done as a device namespace not a pty namespace.I would be happy if the first version of the device namespace could notmap anything but pty's (assuming an incremental implementation path). Ireally don't think we should do a special case for each kind of device.Oh and just skimming the patch summary I'm pretty certain thisimplementation breaks /sys/class/tty/ptyXX/uevent. Which is anotherreason why it would be good to have a single device namespace. So weonly to capture one more namespace and figure out how to deal with itwhen mounting sysfs. Eric | http://lkml.org/lkml/2008/4/9/326 | CC-MAIN-2017-22 | refinedweb | 208 | 56.45 |
Available items
The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:
Bounding Volume | partial | partial | accepts | seconds | accepts | accepts | | ------------------------------------------------------------------ AABB MIN,MAX | 0 | 152349412 | 39229 | 4.8294 AABB X,Y,Z | 34310232 | 1154457 | 39229 | 4.1507 7-Sided AABB | 0 | 172382 | 39229 | 3.0046 AABO | 0 | 67752 | 33793 | 2.1660 Tetrahedron | 0 | 0 | 67752 | 0.3200
In computer graphics and computational geometry, a bounding volume for a set of objects is a closed volume that completely contains the union of the objects in the set. Bounding volumes are used to improve the efficiency of geometrical operations by using simple volumes to contain more complex objects. Normally, simpler volumes have simpler ways to test for overlap.
The axis-aligned bounding box and bounding sphere are considered to be the simplest bounding volumes, and therefore are ubiquitous in realtime and large-scale applications.
There is a simpler bounding volume unknown to industry and literature. By virtue of this simplicity it has nice properties, such as high performance in space and time. It is the Axis-Aligned Bounding Simplex.
In 3D, a closed half-space is a plane plus all of the space on one side of the plane. A bounding box is the intersection of six half-spaces, and a bounding tetrahedron is the intersection of four.
In two dimensions a simplex is a triangle, and in three it is a tetrahedron. Generally speaking, a simplex is the fewest half-spaces necessary to enclose space: one more than the number of dimensions, or N+1. By contrast, a bounding box is 2N half-spaces.
In three dimensions a simplex has four (3+1) half-spaces and a bounding box has six (3*2). That’s 50% more work in order to determine intersection.
We will work in two dimensions first, since it is simpler and extends trivially to three dimensions and beyond.
AABB is well-understood. Here is an example of an object and its 2D AABB, where X bounds are red and Y are green:
The axis-aligned bounding triangle is not as well known. It does not use the X and Y axes - it uses the three axes ABC, which could have the values {X, Y, -(X+Y)}, but for simplicity’s sake let’s say they are at 120 degree angles to each other:
The points from the horse image above can each be projected onto the ABC axes, and the minimum and maximum values for A, B, and C can be found, just as with AABB and X, Y:
Interestingly, however, {maxA, maxB, maxC} are not required to do an intersection test. {minA, minB, minC} define an upward-pointing triangle, so we can use that in isolation as a bounding volume:
To perform efficient intersection tests against a group of objects bounded by {minA, minB, minC}, your query object would need to be in the form of {maxA, maxB, maxC}, which defines a downward-pointing triangle:
struct UpTriangle { float minA, minB, minC; };
struct DownTriangle { float maxA, maxB, maxC; };
When testing for intersection, if the down triangle's maxA < the up triangle's minA (or B or C), the triangles do not intersect. The above triangles don't intersect, because maxA < minA.
bool Intersects(UpTriangle u, DownTriangle d) { return (u.minA <= d.maxA) && (u.minB <= d.maxB) && (u.minC <= d.maxC); }
If we stop here, we have a novel bounding volume with roughly the same characteristics as AABB, but needing 3 instead of 4 values in 2D, and 4 instead of 6 values in 3D, 5 instead of 8 in 4D, etc. If your only concern is determining proximity and you don't care if the bounding volume is tight, this is probably the best you can do.
struct Triangles { UpTriangle *up; // triangles that point up };
bool Intersects(Triangles world, int index, DownTriangle query) { return Intersects(world.up[index], query); }
If you don't have a DownTriangle handy, you can find the smallest DownTriangle that encloses an Uptriangle, like so:
DownTriangle UpTriangle::GetCircumscribed() { const float ABC = minA + minB + minC; return DownTriangle{minA - ABC, minB - ABC, minC - ABC}; }And should you need the largest DownTriangle enclosed by an UpTriangle...
DownTriangle UpTriangle::GetInscribed() { const float ABC = (minA + minB + minC) * 0.5; return DownTriangle{minA - ABC, minB - ABC, minC - ABC}; }We can layer on another set of triangles to get even tighter bounds than AABB, while remaining faster than AABB. And, since the first layer remains, we can continue to do fast intersections with it alone when speed is most important. In addition to the up-pointing bounding triangle, we can have a down-pointing bounding triangle, and the intersection defines an axis-aligned bounding hexagon:
The axis-aligned bounding hexagon has six half-spaces, which makes it 50% bigger than a 2D AABB with four half-spaces:
struct Box { float minX, minY, maxX, maxY; };
struct UpTriangle { float minA, minB, minC; };
struct DownTriangle { float maxA, maxB, maxC; };
struct Hexagons { UpTriangle *up; // triangles that point up, one per hexagon DownTriangle *down; // triangles that point down, one per hexagon };
However, the hexagon has the nice property that it is made of an up and down triangle, each of which can be used in isolation for a faster intersection check. And, when checking one hexagon against another for intersection, unless they are almost overlapping, one triangle test is sufficient to determine that the hexagons don't intersect.
Therefore, except in cases where hexagons almost overlap, a hexagon-hexagon check has the same cost as a triangle-triangle check.
bool Intersects(Hexagons world, int index, Hexagon query) { return Intersects(world.up[index], query.down) && Intersects(query.up, world.down[index]); // this rarely executes }
No three of a 2D AABB's four half-spaces define a closed shape. If you were to try to check for intersection with less than four of an AABB's half-spaces, the shape defined by the half-spaces would have infinite area. This is larger than the finite area of an hexagon's first triangle. That is the essential advantage of the hexagon.
For example, {minX, minY, maxX} is not a closed shape - it is unbounded in the direction of +Y. The same is true of any three of a 2D AABB's four half-spaces. The {minA, minB, minC} of a hexagon, however, is always an equilateral triangle, and so is {maxA, maxB, maxC}.
In 2D, a hexagon uses 6/4 the memory of AABB, but takes 3/4 as much energy to do an intersection check.
And... a hexagon can do two flavors of fast hexagon-triangle intersection check, in addition to hexagon-hexagon checks. None produce false negatives. An AABB offers nothing like that.
bool Intersects(Hexagons world, int index, UpTriangle query) { return Intersects(query, world.down[index]); }
bool Intersects(Hexagons world, int index, DownTriangle query) { return Intersects(world.up[index], query); }
Everything above extends trivially to three and higher dimensions. In three dimensions, an axis-aligned bounding box, axis-aligned bounding tetrahedron, and axis-aligned bounding octahedron have the following structure:
struct Box { float minX, minY, minZ, maxX, maxY, maxZ; };
struct UpTetrahedron { float minA, minB, minC, minD; };
struct DownTetrahedron { float maxA, maxB, maxC, maxD; };
struct Octahedra { UpTetrahedron *up; // tetrahedra that point up, one per octahedron DownTetrahedron *down; // tetrahedra that point down, one per octahedron };
AABO uses 8/6 the memory of an AABB, but since only one of the two tetrahedra need be read usually, an AABO check uses 4/6 the energy of an AABB check. And an AABO has 8/6 the planes, for making a tighter bounding volume.
If your data is in an AoS (Array of Structures) (e.g. struct AABB{ vec3 min, max };) and your code is anywhere near data-bound, as it should be if performance is your concern, AABB will use 50% more energy to intersect than AABO, as explored above.
But what about the case of SoA (Structure of Arrays)? It's possible with AABB to organize data like so:
struct AABBs { vector *minX, *minY, *minZ; vector *maxX, *maxY, *maxZ; }: int Intersects(AABBs world, int index, AABB query) { int mask = all_lessequal(world.minX[index], query.maxX) & all_lessequal(query.minX, world.maxX[index]) if(mask == 0) return 0; // can avoid reading all but first 2 data mask &= all_lessequal(world.minY[index], query.maxY) mask &= all_lessequal(query.minY, world.maxY[index]) if(mask == 0) return 0; // can avoid reading all but first 4 data mask &= all_lessequal(world.minZ[index], query.maxZ) mask &= all_lessequal(query.minZ, world.maxZ[index]); return mask; }The above code checks first if the object intersects the query in the interval {minX,maxX}, and only if an intersection is found, it proceeds to check Y and Z. This is often a pretty good idea, as most queries and objects are fairly small compared to the world they inhabit, so the probability of one intersecting the other in any one-dimensional interval is pretty small.
Whenever this initial interval check strategy is a good idea, we can do it with AABO as well:
struct Octahedra { vector *minA, *minB, *minC, *maxD; vector *maxA, *maxB, *maxC, *maxD; }: int Intersects(Octahedra world, int index, Octahedron query) { int mask = all_lessequal(world.minA[index], query.maxA) & all_lessequal(query.minA, world.maxA[index]); if(mask == 0) return 0; // can avoid reading all but first 2 data mask &= all_lessequal(world.minB[index], query.maxB) mask &= all_lessequal(query.minB, world.maxB[index]) if(mask == 0) return 0; // can avoid reading all but first 4 data mask &= all_lessequal(world.minC[index], query.maxC) mask &= all_lessequal(query.minC, world.maxC[index]); if(mask == 0) return 0; // can avoid reading all but first 6 data mask &= all_lessequal(world.minD[index], query.maxD) mask &= all_lessequal(query.minD, world.maxD[index]); return mask; }The first six planes generate identical code in AABB and AABO. In either case the shape enclosed by the six planes is a rhombohedron. It is quite unlikely that the AABO test will actually perform the D plane test.
Unfortunately for AABB, this initial interval check strategy is not always a good idea.
An initial interval check is not effective when the probability of an object intersecting the slab is high. When it is 80% likely for an object to intersect the slab, then the test has only a 20% chance of avoiding the next four plane tests, which means for AABB on average 0.8 tests are avoided, for an average of 5.2 plane tests per object. This is more expensive than an AABO's initial tetrahedron test with 4 planes total.
An initial interval check is not effective when the degree of SIMD in the target platform is high. This is because, if just one lane intersects the slab, we can't take the branch to avoid reading in more data.
On platforms such as GCN there are 64 SIMD lanes. For all of them to report no intersection with a slab 4% likely to intersect, the probability is 0.9664 or 0.073. That means for AABB an average of 5.7 plane tests, more than the AABO's initial tetrahedron test with 4 planes total.
In cases where probability of slab intersection is a few percent, and degree of SIMD is 8 or more, their effects combine to make the initial interval check ineffective. In these cases, AABO can fall back on its initial tetrahedron check: ``` bool Intersects(AABBs world, AABB query) { if(IntervalCheckIsSmart()) return IntervalIntersect(world, query); else return IntervalIntersect(world, query); // oh no }
bool Intersects(Octahedra world, Octahedron query) { if(IntervalCheckIsSmart()) return IntervalIntersect(world, query); else return TetrahedronIntersect(world, query); // nice } ``` AABB can not choose an alternate strategy for when the initial interval check isn't worth doing. And, AABO is never slower than AABB at doing an initial interval check. So, we can say that in SoA, AABO is never worse than AABB, and sometimes better.
Christer Ericson’s book “Real-Time Collision Detection” has the following to say about k-DOP, whose 8-DOP is similar to Axis Aligned Bounding Octahedron:
k-DOP is similar to the ideas in this paper, in the following ways:
k-DOP is different from the ideas in this paper, in the following ways:
struct DOP8 { float min[4]; // maybe not a tetrahedron, in same cacheline as float max[4]; // this, which maybe isn't a tetrahedron. }; ```
A bounding sphere has four scalar values - the same as a tetrahedron:
struct Tetrahedron { float A, B, C, D; };
struct Sphere { float X, Y, Z, radius; };
In terms of storage a sphere can be just as efficient as a tetrahedron, but a sphere-sphere check is inherently more expensive, as it requires multiplication and its expression has a deeper dependency graph than a convex polyhedron check.
If the data are stored in very low precision such as uint8_t, the sphere-sphere check will overflow the data precision while performing its calculation, which necessitates expansion to a wider precision before performing the check.
Convex polyhedra have no such problem. Their runtime check requires only comparisons, which can be performed by individual machine instructions in a variety of data precisions.
A bounding sphere can have exactly one shape, but each AABO can be wide and flat, or tall and skinny, or roughly spherical, etc. So, in comparison to an AABO, a bounding sphere may not have very tight bounds.
Though axes ABC that point at the vertices of an equilateral triangle are elegant and unbiased:
Transforming between ABC and XY coordinates is costly, and can be avoided by choosing these more pragmatic axes:
A=X B=Y C=-(X+Y)
The pragmatic axes look worse, and are worse, but still make triangles that enclose objects pretty well. With these axes, it is possible to construct a hexagon from a pre-existing AABB, that has exactly the same shape as the AABB, and where the final half-space check is unnecessary:
{minX, minY, -(maxX + maxY)} {maxX, maxY, -(minX + minY)}
This hexagon won't trivially reject any more objects than the original AABB, but the hexagon will take less time to reject objects, because there are (usually) 3 checks instead of 4.
At first, the three half-spaces of a triangle are checked, and only if that check passes, two more half-spaces are checked. The intersection of the five half-spaces is identical to the four half-spaces of a bounding box, but in most cases, only the first three half-spaces will be checked.
In 3D the above needs 7 half-spaces, and is equivalent to a 3D AABB. In all tests I made, this 7-Sided AABB outperforms the 6-Sided AABB. The 7th half-space - the diagonal one - serves no purpose, other than to prevent maxX, maxY, and maxZ from being read into memory. Once they are read into memory, it becomes superfluous, as above.
If you construct the hexagon from the object's vertices instead, you can trivially reject more objects than an AABB can:
{minX, minY, -max(X+Y)} {maxX, maxY, -min(X+Y)}
If it's unclear how a hexagon is superior to AABB when doing a 3 check initial trivial rejection test, the image below may help to explain. Even if you were to do 3 checks first with an AABB, no matter which 3 of the 4 checks you pick, the resulting shape is not closed. It fails to exclude an infinite area from the rejection test.
If you liked this paper, but suspect that a tetrahedron is a poor bounding volume for the skyscraper in your videogame, you are correct! For you, there is this paper, instead: Hexagonal Prism | https://xscode.com/bryanmcnett/aabo | CC-MAIN-2020-45 | refinedweb | 2,605 | 58.62 |
How to invert color of seaborn heatmap colorbar
I use an heatmap to visualize a confusion matrix. I like the standard colors, but I would like to have 0s in light orange and highest values in dark purple.
I managed to do so only with another set of colors (light to dark violet), setting:
colormap = sns.cubehelix_palette(as_cmap=True) ax = sns.heatmap(cm_prob, annot=False, fmt=".3f", xticklabels=print_categories, yticklabels=print_categories, vmin=-0.05, cmap=colormap)
But I want to keep these standard ones. This is my code and the image I get.
ax = sns.heatmap(cm_prob, annot=False, fmt=".3f", xticklabels=print_categories, yticklabels=print_categories, vmin=-0.05)
The default cmap is
sns.cm.rocket. To reverse it set cmap to
sns.cm.rocket_r
Using your code:
cmap = sns.cm.rocket_r ax = sns.heatmap(cm_prob, annot=False, fmt=".3f", xticklabels=print_categories, yticklabels=print_categories, vmin=-0.05, cmap = cmap)
How to reverse colorscales in seaborn heatmap, I believe seaborn uses a cubehelix colormap by default. So you'd do: from matplotlib import pyplot import seaborn as sns colormap = pyplot.cm.cubehelix_r The Colorbar gives information about the color represented by the visualized data and also represents the range of values that depicts the data plotted by the Heatmaps. By default, a colorbar is present in the Heatmap. If we wish to remove the colorbar from the heatmap, the below syntax can help you out with it: seaborn.heatmap(data,cbar=False)
To expand on Ben's answer, you can do this with most if not any color map.
import matplotlib.pyplot as plt import numpy as np import seaborn as sns X = np.random.random((4, 4)) sns.heatmap(X,cmap="Blues") plt.show() sns.heatmap(X,cmap="Blues_r") plt.show() sns.heatmap(X,cmap="YlGnBu") plt.show() sns.heatmap(X,cmap="YlGnBu_r") plt.show()
#92 Control color in seaborn heatmaps – The Python Graph Gallery, 2/ Diverging palette: 2 contrasting colors; 3/ Discrete data. Sequential palettes translate the value of a variable to the intensity of one color: from bright to dark. The attribute cbar of heatmap is a Boolean attribute which if set to true tells if it should appear in the plot or not. If the cbar attribute is not defined, the color bar will be displayed in the plot by default. To remove the color bar, set cbar to False: >>> heat_map = sb.heatmap(data, annot=True, cbar=False) >>> plt.show()
Did you try to invert the colormap?
sns.cubehelix_palette(as_cmap=True, reverse=True)
Choosing color palettes, import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set() It is generally not possible to know what kind of color palette or colormap is best common to use them as a colormap in functions like kdeplot() and heatmap() You can also control how dark and light the endpoints are and even reverse How to add a label to Seaborn Heatmap color bar? Ask Question It is worth noting that cbar_kws can be handy for setting other attributes on the colorbar such as
seaborn.light_palette, seaborn. light_palette (color, n_colors=6, reverse=False, as_cmap=False, input='rgb')¶. Make a palette or cmapseaborn color palette or matplotlib colormap. cmap is color map and we can choose another built-in colormaps too from here. interpolation is the interpolation method that could be nearest, bilinear, hamming, etc. 2D heatmap with Seaborn library. The Seaborn library is built on top of Matplotlib. We could use seaborn.heatmap() function to create 2D heatmap.
Seaborn heatmap tutorial (Python Data Visualization), Sequential colormap. The sequential color map is used when the data range from a low value to a high value. The cmap matplotlib colormap name or object, or list of colors, optional. The mapping from data values to color space. If not provided, the default will depend on whether center is set. center float, optional. The value at which to center the colormap when plotting divergant data. Using this parameter will change the default cmap if none is specified.
Seaborn heatmap colors are reversed - pandas - html, Seaborn heatmap colors are reversed - pandas. same code and the same pandas dataframe): I'm unable to find why the color gradient is inverted and The colormap looks this way now: You can always use the cmap argument and specify Building color palettes¶.). | http://thetopsites.net/article/50768188.shtml | CC-MAIN-2020-34 | refinedweb | 715 | 59.4 |
The Phoenix framework has been growing with popularity at a quick pace, offering the productivity of frameworks like Ruby on Rails, while also being one of the fastest frameworks available. It breaks the myth that you have to sacrifice performance in order to increase productivity.
So what exactly is Phoenix?
Phoenix is a web framework built with the Elixir programming language. Elixir, built on the Erlang VM, is used for building low-latency, fault-tolerant, distributed systems, which are increasingly necessary qualities of modern web applications. You can learn more about Elixir from this blog post or their official guide.
If you are a Ruby on Rails developer, you should definitely take an interest in Phoenix because of the performance gains it promises. Developers of other frameworks can also follow along to see how Phoenix approaches web development.
In this article we will learn some of the things in Phoenix you should keep in mind if you are coming from the world of Ruby on Rails.
Unlike Ruby, Elixir is a functional programming language, which is probably the biggest difference that you may have to deal with. However, there are some key differences between these two platforms that anyone learning Phoenix should be aware of in order to maximize their productivity.
Naming conventions are simpler.
This is a small one, but it’s easy to mess up if you are coming from Ruby on Rails.
In Phoenix, the convention is to write everything in the singular form. So you would have a “UserController” instead of a “UsersController” like you would in Ruby on Rails. This applies everywhere except when naming database tables, where the convention is to name the table in the plural form.
This might not seem like a big deal after learning when and where to use the plural form in Ruby on Rails, but it was a bit confusing at first, when I was learning to use Ruby on Rails, and I am sure it has confused many others as well. Phoenix gives you one less thing to worry about.
Routing is easier to manage.
Phoenix and Ruby on Rails are very similar when it comes to routing. The key difference is in how you can control the way a request is processed.
In Ruby on Rails (and other Rack applications) this is done through middleware, whereas in Phoenix, this is done with what are referred to as “plugs.”
Plugs are what you use to process a connection.
For example, the middleware
Rails::Rack::Logger logs a request in Rails, which in Phoenix would be done with the
Plug.Logger plug. Basically anything that you can do in Rack middleware can be done using plugs.
Here is an example of a router in Phoenix:
defmodule HelloWorld.Router do use HelloWorld.Web, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", HelloWorld do pipe_through :browser get "/", HelloController, :index end scope "/api", HelloWorld do pipe_through :api end end
First, let’s look at the pipelines.
These are groups of plugs through which the request will travel. Think of it as a middleware stack. These can be used, for example, to verify that the request expects HTML, fetch the session, and make sure the request is secure. This all happens before reaching the controller.
Because you can specify multiple pipelines, you can pick and choose which plugs are necessary for specific routes. In our router, for example, we have a different pipeline for pages (HTML) and API (JSON) requests.
It doesn’t always make sense to use the exact same pipeline for different types of requests. Phoenix gives us that flexibility.
Views and templates are two different things.
Views in Phoenix are not the same as views in Ruby on Rails.
Views in Phoenix are in charge of rendering templates and providing functions that make raw data easier for the templates to use. A view in Phoenix most closely resembles a helper in Ruby on Rails, with the addition of rendering the template.
Let’s write an example that displays “Hello, World!” in the browser.
Ruby on Rails:
app/controllers/hello_controller.rb:
class HelloController < ApplicationController def index end end
app/views/hello/index.html.erb:
<h1>Hello, World!</h1>
Phoenix:
web/controllers/hello_controller.ex:
defmodule HelloWorld.HelloController do use HelloWorld.Web, :controller def index(conn, _params) do render conn, "index.html" end end
web/views/hello_view.ex:
defmodule HelloWorld.HelloView do use HelloWorld.Web, :view end
web/templates/hello/index.html.eex:
<h1>Hello, World!</h1>
These examples both display “Hello, World!” in the browser but have some key differences.
First, you have to explicitly state the template that you wish to render in Phoenix unlike in Ruby on Rails.
Next, we had to include a view in Phoenix which stands in between the controller and the template.
Now, you may be wondering why we need a view if it’s empty? The key here is that, under the hood, Phoenix compiles the template into a function roughly equal to the code below:
defmodule HelloWorld.HelloView do use HelloWorld.Web, :view def render("index.html", _assigns) do raw("<h1>Hello, World!</h1>") end end
You can delete the template, and use the new render function, and you will get the same result. This is useful when you just want to return text or even JSON.
Models are just that: data models.
In Phoenix, models primarily handle data validation, its schema, its relationships with other models, and how it’s presented.
Specifying the schema in the model may sound weird at first, but it allows you to easily create “virtual” fields, which are fields that are not persisted to the database. Let’s take a look at an example:
defmodule HelloPhoenix.User do use HelloPhoenix.Web, :model schema "users" do field :name, :string field :email, :string field :password, :string, virtual: true field :password_hash, :string end end
Here we define four fields in the “users” table: name, email, password, and password_hash.
Not much is interesting here, except for the “password” field which is set as “virtual.”
This allows us to set and get this field without saving the changes to the database. It’s useful because we would have logic to convert that password into a hash, which we would save in the “password_hash” field and then save that to the database.
You still need to create a migration; the schema in the model is needed because the fields are not automatically loaded into the model like in Ruby on Rails.
The difference between Phoenix and Ruby on Rails is that the model does not handle the persistence to the database. This is handled by a module called “Repo” which is configured with the database information, as shown in the example below:
config :my_app, Repo, adapter: Ecto.Adapters.Postgres, database: "ecto_simple", username: "postgres", password: "postgres", hostname: "localhost"
This code is included in the environment specific configuration files, such as
config/dev.exs or
config/test.exs. This allows us to then use Repo to perform database operations such as create and update.
Repo.insert(%User{name: "John Smith", example: "[email protected]"}) do {:ok, user} -> # Insertion was successful {:error, changeset} -> # Insertion failed end
This is a common example in controllers in Phoenix.
We provide a User with a name and an email and Repo attempts to create a new record into the database. We can then, optionally, handle the successful or failed attempt as shown in the example.
To understand this code better, you need to understand pattern matching in Elixir. The value returned by the function is a tuple. The function returns a tuple of two values, a status, and then either the model or a changeset. A changeset is a way to track changes and validate a model (changesets will be discussed in the next section).
The first tuple, from top to bottom, that matches the pattern of the tuple returned by the function that attempted to insert the User into the database, will run its defined function.
We could have set a variable for the status instead of an atom (which is basically what a symbol is in Ruby), but then we would match both successful and failed attempts and would use the same function for both situations. Specifying which atom we want to match, we define a function specifically for that status.
Ruby on Rails has the persistence functionality built into the model through ActiveRecord. This adds more responsibility to the model and can sometimes make testing a model more complex as a result. In Phoenix, this has been separated in a way that makes sense and prevents bloating every model with persistence logic.
Changesets allow clear validation and transformation rules.
In Ruby on Rails, validating and transforming data can be the source of hard to find bugs. This is because it’s not immediately obvious when data is being transformed by callbacks such as “before_create” and validations.
In Phoenix, you explicitly do these validations and transformations using changesets. This is one of my favorite features in Phoenix.
Let’s take a look at a changeset by adding one to the previous model:
defmodule HelloPhoenix.User do use HelloPhoenix.Web, :model schema "users" do field :name, :string field :email, :string field :password, :string, virtual: true field :password_hash, :string end def changeset(struct, params \\ %{}) do struct |> cast(params, [:name, :email, :password]) |> validate_required([:email, :password]) end end
Here the changeset does two things.
First, it calls the “cast” function which is a whitelist of permitted fields, similar to “strong_parameters” in Ruby on Rails, and then it validates that the “email” and “password” fields are included, making the “name” field optional. This way, only the fields you allow can be modified by users.
The nice thing about this approach is that we aren’t limited to one changeset. We can create multiple changesets. A changeset for registration and one for updating the user is common. Maybe we only want to require the password field when registering but not when updating the user.
Compare this approach to what is commonly done in Ruby on Rails, you would have to specify that the validation should be run only on “create”. This sometimes makes it hard in Rails to figure out what your code is doing once you have a complex model.
Importing functionality is straightforward, yet flexible.
Much of the functionality of a library called “Ecto” is imported into the models. Models usually have this line near the top:
use HelloPhoenix.Web, :model
The “HelloPhoenix.Web” module is located in “web/web.ex”. In the module, there should be a function called “model” as follows:
def model do quote do use Ecto.Schema import Ecto import Ecto.Changeset import Ecto.Query end end
Here you can see what modules we are importing from Ecto. You can remove or add any other modules that you want here and they will be imported into all models.
There are also similar functions such as “view” and “controller” which serve the same purpose for the views and controllers, respectively.
The
quote and
use keywords might seem confusing. For this example, you can think of a quote as directly running that code in the context of the module that is calling that function. So it will be the equivalent to having written the code inside of quote in the module.
The use keyword also allows you to run code in the context of where it’s called. It essentially requires the specified module, then calls the
__using__ macro on the module running it in the context of where it was called. You can read more about quote and use in the official guide.
This really helps you understand where certain functions are located in the framework and helps reduce the feeling that the framework is doing a lot of “magic”.
Concurrency is at the core.
Concurrency comes for free in Phoenix because it is a main feature of Elixir. You get an application that can spawn multiple processes and run on multiple cores without any worries about thread safety and reliability.
You can spawn a new process in Elixir this simply:
spawn fn -> 1 + 2 end
Everything after
spawn and before
end will run in a new process.
In fact, every request in Phoenix is handled in its own process. Elixir uses the power of the Erlang VM to bring reliable and efficient concurrency “For free.”
This also makes Phoenix a great choice for running services that use WebSockets, since WebSockets need to maintain an open connection between the client and the server (which means you need to build your application so that it can handle possibly thousands of concurrent connections).
These requirements would add a lot of complexity to a project built on Ruby on Rails, but Phoenix can meet these requirements for free through Elixir.
If you want to use WebSockets in your Phoenix application, you are going to need to use Channels. It is the equivalent of
ActionCable in Ruby on Rails, but less complex to set up because you don’t need to run a separate server.
Phoenix makes building modern web apps painless.
While we’ve largely been focusing on the differences, Phoenix does have some things in common with Ruby on Rails.
Phoenix roughly follows the same MVC pattern as Ruby on Rails, so figuring out what code goes where should not be difficult now that you know about the main differences. Phoenix also has similar generators as Ruby on Rails for creating models, controllers, migrations, and more.
After learning Elixir, you will slowly approach Ruby on Rails levels of productivity once you are more comfortable with Phoenix.
The few times I feel not as productive is when I encounter a problem that was solved by a gem in Ruby, and I can’t find a similar library for Elixir. Luckily, these gaps are slowly being filled by the growing Elixir community.
The differences in Phoenix help solve a lot of the pain that came with managing complex Ruby on Rails projects. While they don’t solve all issues, they do help push you in the right direction. Choosing a slow framework because you want productivity is no longer a valid excuse, Phoenix lets you have both. | https://www.toptal.com/phoenix/phoenix-rails-like-framework-web-apps | CC-MAIN-2019-26 | refinedweb | 2,379 | 64.1 |
ADO.NET :: Insert Update And Delete Records Using Entity Framework Data Model?Nov 22, 2010
How can i insert,update and delete records using entity framework data model.View 1 Replies
How can i insert,update and delete records using entity framework data model.
I have two roles "Admin" and "Basic". I also have a listview on the web page.
My goal is that to make "Admin" role has the highest privilege to deal with records such as "insert", "update" and "delete".
For the role "Basic", it only can update the records.
I have an Events table and an InstallmentPlans table. The relationship is 0..1 : an Event can have 0 or 1 Installment plans. If I want to remove the existing InstallmentPlan for an event, how do I do this? Setting it to null doesn't seem to work:
_event.InstallmentPlan = null;
I get an cast exception when i am trying to insert an entity in Entity Framework (using code-first). From this code :
public virtual T Insert(T entity)
{
return Context.Set<T>().Add(entity);
}
The cast exception is like "impossible to cast ...Collection'1(Entity) to type (Entity)" I can't figure out why. I am pretty sure ive done everything right. Post entity
public class Post
{
public long PostId { get; private set; }
public DateTime date { get; set; }
[Required]
public string Subject { get; set; }
public User User { get; set; }
public Category Category { get; set; }
[Required]
public string Body { get; set; }
public virtual ICollection<Tag> Tags { get; private set; }
public Post()
{
Category = new Category();
if (Tags == null)
Tags = new Collection<Tag>();
}................................
I want to know how to Update / delete the table records in ASPNETDB.MDF in single update / delete query ?View 1 Replies
I want to add recored and immediately after add get id value of that record.View 1 Replies
I made a few changes to the DB in SQL server management studio then right clicked on the .edmx doc to get it to update. That seemed to work fine but when i compiled the app everything that referenced the EF seems to be broken.The Error list now contains the below error for all classes that used it.
The type or namespace name '' could not be found (are you missing a using directive or an assembly reference?)
I have an EDM, it includes the entities extension and history. My goal is to use history to keep track of all the changes made to extension entity. For example, if extension with ID 223 has its property 'Name_Display' changed - I want the history entity to record this.
I'm using ASP.NET with VB.NET. Where in my code do I put the hook to say, "update the history entity" and what should that hook look like?
I use ADO.net Entity Data model for work with database.
In my program, I want to update a record of user table, so I use the code below to do this.
In this function I send changed user info and then overwrite the information with the current user information.
After I run objUser = _user; and then call objContext.SaveChanges(); to save the changes.
But when I do this, the changes are not persisted to the database. I use this code for another programs but in this case the code does not work!
public void Update(tbLiUser _user)
{
LinkContext objContext = this.Context;
tbLiUser objUser = objContext.tbLiUsers.First(u => u.tluId == _user.tluId);
objContext.Attach(objUser);
objUser = _user;
objContext.SaveChanges();
}?View 1 Replies mapping a stored procedure to an entity by right clicking on the entity (in the .edmx) and selecting "Stored Procedure Mapping." This brings you to a Mapping Details - "Name of Entity" Window that allows you to select the insert, update, and delete stored procedures associated with the Entity. It also maps the stored procedure parameter to the Entity "Property" (Column).
I'm gettin an error "error 2042: Parameter Mapping specified is not valid." The cause of the error is fairly obvious, in the Insert stored procedure that has been selected, a 'CHAR' parameter is being mapped to an Int32 Entity Property. I altered the stored procedure parameter to match the entity, I deleted the stored procedure, readded, and reslected it as the Insert function. I also cleaned, validated, updated model from database. No matter what I do, the parameter list in the mapping details doesn't reflect the change to the stored procedure. It's stuck on a char --> int32 mapping, even though it has been changed, like it's buried deep in meta data some where.
i am calling stored procedure through entity model like result=ctx.spname(parmas), i am expecting 0 or 1 as a result after the execution of sp, but its returning unknown values like 178 for number records.View 2 Replies
I am working with entity frame work to insert data into data base for that I write a web method and query function but data can’t insert data base following my function and web method.
/////////////////////////
function AddGridviewData() {
var AddRow = new Array();
$('[id*=Test_gridview]').find('tr:has(td)').each(function () {
var NewRow = {};
NewRow. name = $(this).find("td:eq(1)").html();
[Code] ...
There are no error and no insert the data into data base.
I have three table like above, table C is mapping table which has foreign key of Table A and B.How can i select and insert data in Table C using Entity Frame Work I generate entity framework model by clicking button in browser in client-side and save it back to web server PC?View 2 Replies.can someone give me any example that connects to a sample oracle database and use LINQ to oracle
I want to do bulk insert,bulk edit,multiple delete records in gridview.View 1 Replies | http://asp.net.bigresource.com/ADO-NET-insert-update-and-delete-records-using-entity-framework-data-model--Xq8U5U9yg.html | CC-MAIN-2018-39 | refinedweb | 963 | 65.73 |
Decoding json on Silverlight with System.Json (plus implicit conversion operators in IronPython)
As I explained we're writing a Silverlight application that communicates with our Django server and exchanges a lot of json with it.
Unfortunately, due to what is apparently just an oversight, the codecs module is incomplete for IronPython on Silverlight. This means that recent versions of simplejson don't work.
What we've been using is an older version of simplejson, that pulls in the obsolete and huge sre module in as one of its dependencies. On top of bloating up our application and adding several seconds to the startup importing it all the performance is not exactly blazing.
Fortunately part of the Silverlight SDK is System.Json.dll. Using this API from IronPython is pretty simple. The following code defines a loads function (load string - the same API as simplejson) that takes a string and parses it.
import clr clr.AddReference('System.Json') from System import Boolean from System.Json import JsonValue, JsonType String = clr.GetClrType(str) def loads(inString): thing = JsonValue.Parse(inString) return handle_value(thing) def handle_value(inValue): if inValue is None: return None elif inValue.JsonType == JsonType.String: return clr.Convert(inValue, String) elif inValue.JsonType == JsonType.Boolean: return Boolean.Parse(str(inValue)) elif inValue.JsonType == JsonType.Number: return get_number(inValue.ToString()) elif inValue.JsonType == JsonType.Object: return dict((pair.Key, handle_value(pair.Value)) for pair in inValue) elif inValue.JsonType == JsonType.Array: return [handle_value(value) for value in inValue] # Should be unreachable - but if it happens I want to know about it! raise TypeError(inValue) def get_number(inString): try: return int(inString) except ValueError: return float(inString)
As with my custom json emitter there is a lot it doesn't do. It handles the following types:
- None
- lists
- dictionaries
- strings
- floats and integers
- booleans
If you want it to handle decmials or dates you'll have to add that yourself. How it works is mostly straightforward, but there is one little piece of 'magic' in there. When you call ToString() (or str() they do the same thing) you get the original json back. For numbers and booleans this is fine as we can easily turn them into the objects they represent. For strings this is a nuisance as we get double quoted, escaped strings. The correct way to get the value we want is to use implicit conversion. In C# this looks something like:
string value = jsonArray["key"];
Declaring the result as a string calls the appropriate JsonValue implicit conversion operator for us. IronPython doesn't have implicit conversion operators as we don't declare types and with a dynamic type system you rarely need to cast. Up until version 2.6 it wasn't possible to call implicit operators, but in IronPython 2.6 we gained a new function in the clr module; clr.Convert:
>>> print clr.Convert.__doc__ object Convert(object o, Type toType) Attempts to convert the provided object to the specified type. Conversions that will be attempted include standard Python conversions as well as .NET implicit and explicit conversions. If the conversion cannot be performed a TypeError will be raised.
The implicit conversion to string is done with the code:
clr.Convert(jsonValue, clr.GetClrType(str))
I cover some of the other goodies new in IronPython 2.6 (like CompileSubclassTypes) in Dark Corners of IronPython.
I haven't yet written the code to do json encoding, but the JsonValue class (and friends) can be used for encoding as well as decoding, so I expect the code will pretty much be the opposite of the snippet shown above...
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2009-12-28 22:56:22 | |
Categories: Python, IronPython, Work Tags: silverlight, json
Resolver One 1.7, BioPython and 3D Graphics
Although I've left Resolver Systems I still follow closely what they're up to. Resolver One, the IronPython powered spreadsheet with the programming model right at its heart, is an innovative and unique product [1] that deserves to flourish. Despite the horrific loss Resolver One seems to still be moving forward at great pace without me.
Major features in this new release, the last one in which I have been involved in the development [2], include:
- Button-click handlers are now executed without blocking the rest of Resolver One. This means that if you accidentally write a handler that never finishes, or just one that takes longer than you want, you can cancel it while it's running and fix the problem.
- Added long-awaited dialog for setting wrapping and aligment for cells.
- External imported modules now shared between documents and RunWorkbook (better performance for RunWorkbook in particular).
- Faster install time.
- Improved responsiveness when dragging tabs and switching between tabs.
- [Shift] while clicking Recalc toolbar button now now forces reload of all imported modules (like Shift-F9 has always done).
- A few minor bugfixes.
Giles Thomas and team have also produced screencasts of a couple of particularly interesting uses of Resolver One:
Using OpenGL and Resolver One for 3D visualization of stock prices:
This one uses Yahoo! Finance to download the close prices over the last two years for every stock that's currently in the Dow Jones index, then charts them in a 3D window which you can pan and zoom using the mouse. Here's a video showing it in action...
If you're interested in OpenGL Giles has a blog exploring WebGL, OpenGL in the browser: Learning WebGL.
Resolver One includes built-in support for Python C extensions like Numpy through the Resolver Systems sponsored open-source project Ironclad. Ironclad overcomes IronPython's inability to use compiled C-extensions. This video demonstrates the use of one such powerful library, BioPython, from within a Resolver One spreadsheet, to compare the molecular shapes of proteins. (3m12s)
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2009-11-24 15:00:56 | |
Categories: IronPython, Work Tags: resolverone, spreadsheets, opengl, biopython, webgl
IronPython Training in New York, January 21st 2010
In association with Holdenweb I'll be taking an IronPython training course on January 21st in New York.
The details of the course:
Michael Foord is an early adopter of IronPython, having used it for (among other things) the creation of the Resolver One Python-driven spreadsheet product. He is the author of Manning's IronPython in Action and a well-known speaker at Python conferences throughout the world.
IronPython is the implementation of Python for the .NET framework and Mono. IronPython combines the power of the .NET framework with the expressiveness and flexibility of the Python programming language. In this workshop you'll get hands on experience with using IronPython: from the basics of integrating with the framework assemblies and classes to embedding IronPython in .NET applications.
This workshop is aimed at .NET developers with an interest in IronPython, and Python developers interested in IronPython. We'll cover how IronPython integrates with the .NET framework, including some of the tricky details that previous experience of Python or C# alone won't have prepared you for. We'll also be covering the IronPython hosting APIs and how to embed IronPython.
Reasons you might want to consider IronPython include:
- Using Python libraries from .NET
- Using .NET libraries from Python
- Writing multi-threaded Python code without a GIL
- Embedding IronPython in .NET applications for user scripting
- Exploring new assemblies and classes with the interactive interpreter
- System administration and scripting
- Developing for Silverlight (Python in the browser)
Previous programming experience of Python is assumed, but no specific experience with Python or .NET is required. Places are limited, so reserve yours straight away.
Course Outline
The Interactive Interpreter
Getting started with IronPython, basic .NET integration, executing IronPython scripts. Using the interactive interpreter as a tool to explore live assemblies and classes.
IronPython for Python Developers
Why should a Python developer be interested in IronPython? From multithreading without a GIL, to multiple and sandboxed Python engines, to native user interface libraries (plural!) on Windows or even cross platform development with Mono; we'll be looking at some of what the .NET framework and IronPython has to offer Python developers.
Python for .NET Developers
A whirlwind guide to Python syntax and the wonders of dynamic languages for .NET programmers.
Tools and IDEs
A rundown of the options for developing with IronPython and the different IDEs available, including their different capabilities. Application Development with IronPython
Using Python and .NET libraries to build applications with IronPython. From simple scripting system administration tasks, to web applications to desktop applications. Using Ironclad for compatibility with Python C extensions, using the Python standard library and working with the .NET framework.
Advanced .NET Integration
Using a dynamic language on a statically typed framework. Many of the features of the .NET framework require specialised knowledge to use them from IronPython; including making use of new features in IronPython 2.6 like the __clrtype__ metaclass. Embedding IronPython and the IronPython Compliler
Using the IronPython hosting API for embedding in .NET applications. This can be used for creating hybrid applications with parts in C# and user scripting. With Pyc the compiler tool it can also be used for deploying IronPython applications as binary form. We'll also see how .NET 4 makes interacting with IronPython and the Dynamic Language Runtime simpler from C#. Python in the Browser with Silverlight
The basics of creating a Silverlight application with IronPython and the development process. Plus an overview of the APIs available in Silverlight; for building user interfaces, making web requests, and interacting with Javascript and the browser DOM.
There will also be plenty of time for Q&A throughout the session.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2009-11-24 00:52:26 | |
Categories: IronPython, Python Tags: training, New York, Silverlight, Mono
Testable file Type and File I/O in Try Python
A few weeks ago I announced Try Python, a Python tutorial with interactive interpreter that runs in the browser using IronPython and Silverlight.
Because it runs in Silverlight, which is sandboxed from the local system, the parts of the tutorial that show how to do file I/O didn't work. I've finally fixed this with a pretty-much-complete implementation of the file type and open function that use local browser storage (IsolatedStorage) to store the files.
You can try this out by going direct to the Reading and Writing Files part of the tutorial (page 32).
The implementation is split into two parts, the file type and open function in storage.py and the backend that uses the IsolatedStorage API in storage_backend.py. There are also extensive tests of course.
In Silverlight you use it like this:
import storage.backend
storage.backed = storage_backend
storage.replace_builtins()
This sets the IsolatedStorage based backed in the storage module and then replaces the builtin file and open with the versions in storage. There is a corresponding restore_builtins function to put the original ones back. You could use this for convenient file usage inside Silverlight applications, but the code is neither efficient nor elegant so I wouldn't recommend it for production!
You can also call storage.file and storage.open directly without having to replace the builtin versions. If you use the browser backend in Silverlight then files will be persisted in browser storage and be available when an application is revisited later (unless the user clears the browser cache).
Note
The tests require Python 2.5 or more recent as they use the with statement. The actual implementation should be compatible with Python 2.4 or even earlier. (In fact because they use the storage_backend the tests will only run on Silverlight but it would be very easy to get them to run on CPython.)
You can see the tests run in the browser (slowly - as I run them in a background thread) at: storage module tests.
The storage module does have a default dictionary based backend for when used outside Silverlight. This simply stores files as strings in a dictionary using the full file path as the key (it has no concept of dictionaries). You could implement an alternative backend by implementing the four functions in the storage_backend module (or the method on the backend class in the storage module). This leads to an interesting potential use case.
Unit testing code that does file I/O is notoriously difficult. You can either let your unit tests do real file access or modify your production code to use something like dependency injection so that you can mock out the file access during the tests. Using this implementation you can swap out the builtin file type during the test, controlling how it behaves using the dictionary backend, without having to change the way you write your production code just to make it testable.
For this to be really useful it needs an implementation of functions in the os and os.path module (like os.listdir, os.remove, os.makedir(s), os.path.isfile, os.path.isdir and so on). This should be easy to do and I will get round to it as they would be nice things to cover in the Try Python tutorial.
There are several (mostly minor) differences between this and the standard file type, plus a few things still on the TODO list:
Differences from standard file type:
- Attempting to set the read-only attributes (like mode, name etc) raises an AttributeError rather than a TypeError
- The exception messages are not all identical (some are better!)
- Strict about modes. Unrecognised modes always raise an exception
- The deprecated readinto is not implemented
Still todo:
- The buffering argument to the constructor is not implemented
- The IOError exceptions raised don't have an associated errno
- encoding, errors and newlines do nothing
- Behavior of tell() and seek() for text mode files may be incorrect (it should treat '\n' as '\r\n' in text mode)
- Behaves like Windows, writes '\n' as '\r\n' unless in binary mode. A flag to control this?
- Universal modes not supported
- Missing __format__ method needed when we move to 2.6
- Implementations of os and os.path that work with storage_backend
As an added bonus for Try Python the IronPython team have created a new .NET interop tutorial for IronPython and it is in written in ReStructured Text. It will be very easy for me to add this to Try Python as well as the Python tutorial; I'll wait a bit until it has stabilised though.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2009-10-15 17:33:37 | |
Categories: Python, IronPython, Projects Tags: silverlight, testing_7<<
Every code example has a button that allows you to execute it the interpreter that is on the right of the interface:
Archives
This work is licensed under a Creative Commons Attribution-Share Alike 2.0 License.
Counter... | http://www.voidspace.org.uk/python/weblog/arch_IronPython.shtml | CC-MAIN-2018-26 | refinedweb | 2,488 | 56.35 |
fgetc, getc
From cppreference.com
Reads the next character from the given input stream. getc() may be implemented as a macro.
[edit] Parameters
[edit] Return value
The obtained character on success or EOF on failure.
If the failure has been caused by end-of-file condition, additionally sets the eof indicator (see feof()) on
stream. If the failure has been caused by some other error, sets the error indicator (see ferror()) on
stream.
[edit] Example
fgetc with error checking
Run this code
#include <stdio.h> #include <stdlib.h> int main(void) { FILE* tmpf = tmpfile(); fputs("abcde\n", tmpf); rewind(tmpf); int ch; while ((ch=fgetc(tmpf)) != EOF) /* read/print characters including newline */ printf("%c", ch); /* Test reason for reaching EOF. */ if (feof(tmpf)) /* if failure caused by end-of-file condition */ puts("End of file reached"); else if (ferror(tmpf)) /* if failure caused by some other error */ { perror("fgetc()"); fprintf(stderr,"fgetc() failed in file %s at line # %d\n", __FILE__,__LINE__-9); exit(EXIT_FAILURE); } return EXIT_SUCCESS; }
Output:
abcde End of file reached | http://en.cppreference.com/w/c/io/fgetc | CC-MAIN-2014-42 | refinedweb | 173 | 57.77 |
55586/how-to-convert-json-file-to-avro-file-and-vise-versa
Hi All,
I want to convert my json file to avro and vice versa but facing some difficulty. Can anyone please help me debugging this?
val df = spark.read.json(“path to the file”)
df.write.format(“com.databricks.spark.avro”).save(“destination location”)
But I am getting the below error:
org.apache.spark.sql.AnalysisException: Failed to find data source: com.databricks.spark.avro.
Try including the package while starting the spark-shell:
spark-shell --packages com.databricks:spark-avro_2.10:2.0.1
And then import:
import com.databricks.spark.avro._
You can do this by turning off ...READ MORE
Source tags are different:
{ x : [
{ ...READ MORE
You can save the RDD using saveAsObjectFile and saveAsTextFile method. ...READ MORE
SqlContext has a number of createDataFrame methods .. command used:
val df ...READ MORE
You can do it using a code ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/55586/how-to-convert-json-file-to-avro-file-and-vise-versa | CC-MAIN-2020-16 | refinedweb | 163 | 54.79 |
Installing Orange in Suse and openSuse (based on text by Ignacio Arriaga Sánchez)
Download sources
Download the last Orange version, select the sources package and extract it.
Install dependencies
For Python scripting we have to install the common building tools:
sudo zypper install make gcc-c++
And then we need the numpy library. Download numpy from.
tar -xvf numpy-1.3.0.tar. cd numpy-1.3.0 python setup.py build sudo python setup.py installFor Orange Canvas:
We need the qt toolkit (if you use kde will be already installed and its Python bindings.
sudo zypper install libqt4 libqt4-devel python-qt4
And then we need the QWT library which extends the Qt framework with widgets for scientific and engineering applications. We will install directly the Python bindings because the library is included in the installation package. Download the source package from (Option 6). And then:
tar -xvf PyQwt-5.1.0.tar.gz cd PyQwt-5.1.0/qwt-5.1 qmake make sudo make install
This will install the qwt library. Then install the Python bindings:
cd cd ../configure python configure.py -Q ../qwt-5.1 make sudo make install
For further information about installing PyQWT you could read the documentation (Doc/html/pyqwt/install.html).
Compiling and Installing Orange
Compile the C++ sources:
cd .. make
Transfer files:
cd .. sudo mkdir /usr/lib64/python2.6/site-packages/orange tar -cf - -- /usr/lib64/python2.6/site-packages/orange.pth" sudo ln -s /usr/lib64/python2.6/site-packages/orange/liborange.so /usr/lib64/liborange.so
Running Orange
To use Orange in python scripts, import "orange" in the python interpreter. You can also run the Orange Canvas (widgets) with:
python /usr/lib64/python2.6/site-packages/orange/OrangeCanvas/orngCanvas.pyw
Installing C45 Plug-in (optional, Orange has its own reimplementation of the algorithm)
- Download the C4.5 (Release 8) sources from. Then extract it in a temporary directory.
- Download buildC45.zip and unzip its contents into the C4.5 directory R8/Src.
- Open buildC45.py and, after the last line add:
print "Installation path: %s" % orangedir,
- Then execute buildC45.py as root:
sudo python buildC45.py
- The script will output, something line this: "Installation path: /usr/lib64/site-packages/orange/". Then you have to create a symbolic link to the library that has been generated:
ln -s /usr/lib64/site-packages/orange/c45.so /usr/lib64/c45.so
- In the python interpreter try to write:
import orange orange.C45Learner()If there are no errors the plug-in have been installed correctly. | http://orange.biolab.si/installation_suse.html | CC-MAIN-2014-15 | refinedweb | 423 | 52.97 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.