text:
Q: What deterministic garbage collection algorithms are out there? By deterministic I vaguely mean that can be used in critical real-time software like aerospace flight software. Garbage collectors (and dynamic memory allocation for that matter) are big no-no's in flight software because they are considered non-deterministic. However, I know there's ongoing research on this, so I wonder if this problem has been solved yet.
I'm also including in the question any garbage collection algorithms that put restrictions on how they're used.

A: Happened to be searching through Stack Overflow and noticed this rather old post.
Jon Anderson mentioned JamaicaVM.  Since these posts have been up for over 4 years now,
I think its important to respond to some of the information posted here.
I work for aicas, the developers and marketers of JamaicaVM, JamaicaCAR, and Veriflux.
JamaicaVM does have a hard realtime garbage collector.  It is fully preemptive.  The exact
same behavior required in a realtime operating system.  Although the preemption latency is
CPU speed dependent, assume that on a Ghz class processor preemption of the garbage collector is less than 1 microsecond.  There is a 32 bit singlecore version that supports up to 3 GB of memory per process address space.  There is a 32 bit multicore version that supports 3 GB of memory per process address space and multiple cores.  There are also 64 bit singlecore and multicore versions that support up to 128 GB of memory per process address space.  The performance of the garbage collector is independent of the size of memory.  In response to one of the responses regarding running the GC completely out of memory, for a hard realtime system you would not design your program to ever do that.  Although you can, in fact, use a hard realtime GC in this scenario, you would have to account for a worst case execution time that probably would not be acceptable to your application.
Instead, the correct approach would be to analyze your program for maximum memory allocation, and then configure the hard realtime garbage collector to incrementally free blocks during all previous allocations so that the specific scenario described never occurs.  This is known as thread-distributed, work-paced garbage collection.
Dr. Siebert's book on Hard Realtime Garbage Collectors describes how to accomplish this and presents a formal proof that the garbage collector will keep up with the application, while not becoming an O(N) operation.
It is very important to understand that realtime garbage collection means several things:

*

*The garbage collector is preemptible, just like any other operating system service

*It can be proven, mathematically that the garbage collector will keep up, such that memory will not be exhausted because some memory has not been reclaimed yet.

*The garbage collector does not fragment memory, such that as long as there is memory available, a memory request will succeed.

*Additionally, you will need this to be part of a system with priority inversion protection, a fixed priority thread scheduler and other features.  Refer to the RTSJ for some information on this.

Although hard realtime garbage collection is needed for safety-critical applications, it can be used mission critical, and general purpose Java applications as well.  There is no inherent limitations in using a hard realtime garbage collector.  For general use, you can expect smoother program execution since there are no long garbage collector pauses.

A: To me, 100% real-time Java is still very much a hit-and-miss technology, but I don't claim to be an expert.
I'd recommend reading up on these articles - Cliff Click blog. He's the architect of Azul, has pretty much coded all of the standard 1.5 Java concurrent classes etc... FYI, Azul is designed for systems which require very large heap sizes, rather than just standard RT requirements.

A: It's not GC, but there are simple O(1) fixed sized block allocation/free schemes you can use for simple usage. For example, you can use a free list of fixed sized blocks.
struct Block {
   Block *next;
}

Block *free_list = NULL; /* you will need to populate this at start, an
                          * easy way is to just call free on each block you
                          * want to add */

void release(void *p) {
    if(p != NULL) {
        struct Block *b_ptr = (struct Block *)p;
        b_ptr->next = free_list;
        free_list = b_ptr;
    }
}

void *acquire() {
    void *ret = (void *)free_list;
    if(free_list != NULL) {
        free_list = free_list->next;
    }
    return ret;
}

/* call this before you use acquire/free */
void init() {
    /* example of an allocator supporting 100 blocks each 32-bytes big */
    static const int blocks = 100;
    static const int size = 32;
    static unsigned char mem[blocks * size];
    int i;
    for(i = 0; i < blocks; ++i) {
        free(&mem[i * size]);
    }
}

If you plan accordingly, you could limit your design to only a few specific sizes for dynamic allocation and have a free_list for each potential size. If you are using c++, you can implement something simple like scoped_ptr (for each size, i'd use a template param) to get simpler yet still O(1) memory management.
The only real caveat, is that you will have no protection from double frees or even accidentally passing a ptr to release which didn't come from acquire.

A: Sun has extensively documented their real-time garbage collector, and provided benchmarks you can run for yourself here.  Others mentioned Metronome, which is the other major production-grade RTGC algorithm.  Many other vendors of RT JVMs have their own implementations -- see my list of vendors over here and most of them provide extensive documentation.
If your interest is particularly in avionics/flight software, I suggest you take a look at aicas, an RTSJ vendor who specifically markets to the avionics industry.  Dr. Siebert's (aicas CEO) home page lists some academic publications that go into great detail about PERC's GC implementation.

A: I know I might get a lot of down-votes for this reply, but if you are already trying to avoid dynamic memory in the first place, because you said it's a no-no, why do you use GC at all? I'd never use GC in a real-time system where predictable runtime speed is the major concern. I'd avoid dynamic memory wherever possible, thus there are very, very little dynamic objects to start with and then I'd handle the very few dynamic allocations I have manually, so I have 100% control when something is released and where it is released. After all not just GC is not deterministic, free() is as little deterministic as malloc() is. Nobody says that a free() call just has to mark the memory as free. It might as well try to combine smaller free memory blocks surrounding the free'd one to a big one and this behavior is not deterministic, nor is the runtime for it (sometimes free won't do that and malloc will do that instead on next allocation, but nowhere is written that free mustn't do that).
In a critical realtime system, you might even replace the system standard malloc()/free() with a different implementation, maybe even writing your own one (it's not as hard as it sounds! I've done that before just for the fun of it) that works most deterministic. For me GC is a plain convenience thingy, it is to get programmers away from focusing on sophisticated malloc()/free() planing and instead having the system deal with this automatically. It helps doing rapid software development and saves hours of debugging working finding and fixing memory leaks. But just like I'd never use GC within an operating system kernel, I'd never use it within a critical realtime application either.
If I need a more sophisticated memory handling, I'd maybe write my own malloc()/free() that works as desired (and most deterministic) and write my own reference counting model on top of it. Reference counting is still manual memory management, but much more comfortable than just using malloc()/free(). It is not ultra fast, but deterministic (at least increasing/decreasing the ref counter is deterministic in speed) and unless you may have circular references, it will catch all dead memory if you follow a retain/release strategy throughout your application. The only non deterministic part about is that you won't know if calling release will just decrease the ref counter or really free the object (depending if the ref count goes to zero or not), but you could delay the actual free by offering a function to say "releaseWithoutFreeing", which decreases the ref counter by one, but even if it reaches zero, it won't free() the object yet. Your malloc()/free() implementation can have a function "findDeadObjects" that searches for all objects with a retain counter of zero, that have not yet been released and free them (at a later point, when you are in a less critical part of your code that has more time for such kind of tasks). Since this is also not deterministic, you could limit the amount of time it may use for this like "findDeadObjectsForUpTo(ms)", and ms is the amount of milliseconds it may use for finding and freeing them, coming back as soon as this time quantum has been used, so you won't spent too much time in this task.

A: Metronome GC and BEA JRockit are two deterministic GC implementations that I'm aware of (both for Java).

A: You may have some luck with the following PhD thesis
CMU-CS-01-174 - Scalable Real-time Parallel Garbage Collection for Symmetric Multiprocessors.

A: Real-time means a guaranteed upper bound on response time.  This means an upper bound on the instructions that you can execute until you deliver the result.  This also puts an upper limit on the amount of data you can touch.  If you don't know how much memory you're going to need, it is extremely likely that you'll have a computation for which you cannot give an upper limit of its execution time.  Otoh, if you know the upper bound of your computation, you also know how much memory gets touched by it (unless you don't really know what your software does).  So, the amount of knowledge you have about your code obviates the need for a GC.
There are features, like regions in RT-Java, that allow for expressiveness beyond local and global (static) variables.  But they will not relieve you from your obligation to manage the memory you allocate, because otherwise you cannot guarantee that the next upcoming allocation will not fail because of insufficient memory resources.
Admittedly:  I've gotten somewhat suspicious about things that call themselves "realtime garbage collectors".  Of course, any GC is real time if you assume that every allocation runs a full collection (which still doesn't guarantee that it will succeed afterwards, because all memory blocks might found to be reachable).  But for any GC that promises a lower time bound on allocation, consider its performance on the following example code:
// assume that on `Link` object needs k bytes:
class Link {
    Link next = null;
    /* further fields */
    static Link head = null;
}

public static void main (String args) {
    // assume we have N bytes free now
    // set n := floor (N/k), assume that n > 1

    for (int i = 0; i < n; i ++) {
        Link tmp = new Link ();
        tmp.next = Link.head;
        Link.head = tmp;
    }
    // (1)
    Link.head = Link.head.next; // (2)
    Link tmp = new Link ();  // (3)
}

*

*At point (1),  we have less than k
bytes free (allocation of another
Link object would fail), and all
Link objects allocated so far are
reachable starting from the
Link.static Link head field.

*At point (2),

*

*(a) what used to be the first entry in the list is now not reachable, but

*(b) it is still allocated, as far as the memory management part is concerned.

*At
point (3), the allocation should
succeed because of (2a) - we can use
what used to be the first link - but,
because of (2b), we must start the
GC, which will end up traversing n-1
objects,  hence have a running time
of O(N).
So, yes, it's a contrived example.  But a GC that claims to have a bound on allocation should be able to master this example as well.

A: I know this post is a bit dated, but I have done some interesting research and want to make sure this is updated.
Deterministic GC can be offered by Azul Systems "Zing JVM" and JRocket.  Zing comes with some very interesting added features and is now "100% software based" (can run on x86 machines).  It is only for Linux at this time though ...
Price:
If you are on Java 6 or before Oracle is now charging a 300% uplift and forcing support for this capability ($15,000 per processor & $3,300 support).  Azul, from what I have heard is around $10,000 - $12,000, but charges by physical machine, not core / processor.  Also, the process are graduated by volume so the more servers you leverage the deeper the discounting.  My conversations with them showed them to be quite flexible.  Oracle is a perpetual license and Zing is subscription based ... but if you do the math and add in other features that Zing has (see differences below).
You can cut cost by moving to Java 7, but then incur development costs.  Given Oracle's roadmap (a new release every 18 months or so), and the fact that they historically only offer the latest plus one older versions of Java SE updates for free, the "free" horizon is expected to be 3 years from the initial GA release if any major version. Since initial GA releases are typically not adopted in production for 12-18 months, and that moving production systems to new major java releases typically carries major costs, this means that Java SE support bills will start hitting somewhere between 6 and 24 months after initial deployment.
Notable differences:
JRocket does still have some scalability limitations in terms of RAM (though improved from days of old).  You can improve your results with a bit of tuning.  Zing has engineered their algorithm to allow continuous, concurrent, compaction (no stop the world pauses and no "tuning" required).  This allows Zing to scale without a theoretical memory ceiling (they are doing 300+ GB heaps without suffering stop the world or crashing).  Talk about a paradigm changer (think of the implications to big data).  Zing has some really cool improvements to locking giving it amazing performance with a bit of work (if tuned, can go sub-millisecond average).  Finally, they have visibility into classes, methods, and thread behavior in production (no overhead).  We are considering this as a huge time saver when considering updates, patches, and bug-fixes (e.g. leaks & locks).  This can practically eliminate the need to recreate many of the issues in Dev / Test.
Links to JVM Data I found:
JRocket Deterministic GC
Azul Presentation - Java without Jitter
Azul / MyChannels Test

A: I know azul systems has a jvm whose GC is hardware assisted. It can also run concurrently and collect massive amounts of data pretty fast.
Not sure how deterministic it is though.


text:
Q: Can enums be subclassed to add new elements? I want to take an existing enum and add more elements to it as follows:
enum A {a,b,c}

enum B extends A {d}

/*B is {a,b,c,d}*/

Is this possible in Java?

A: The recommended solution to this is the extensible enum pattern.
This involves creating an interface and using that where you currently use the enum. Then make the enum implement the interface. You can add more constants by adding an additional enum/class that also extends the interface. Here is the general idea:
public interface TrafficLights {
  public abstract String getColour();
}
public enum StandardTrafficLights implements TrafficLights {
  RED, YELLOW, GREEN;
  public String getColour() {
    return name();
  }
}
public enum WeirdTrafficLights implements TrafficLights {
  DOUBLE_RED;
  public String getColour() {
    return name();
  }
}

Note that if you want something like TrafficLights.valueof(String) you will have to implement it yourself.

A: This is how I enhance the enum inheritance pattern with runtime check in static initializer.
The BaseKind#checkEnumExtender checks that "extending" enum declares all the values of the base enum in exactly the same way so #name() and #ordinal() remain fully compatible.
There is still copy-paste involved for declaring values but the program fails fast if somebody added or modified a value in the base class without updating extending ones.
Common behavior for different enums extending each other:
public interface Kind {
  /**
   * Let's say we want some additional member.
   */
  String description() ;

  /**
   * Standard {@code Enum} method.
   */
  String name() ;

  /**
   * Standard {@code Enum} method.
   */
  int ordinal() ;
}

Base enum, with verifying method:
public enum BaseKind implements Kind {

  FIRST( "First" ),
  SECOND( "Second" ),

  ;

  private final String description ;

  public String description() {
    return description ;
  }

  private BaseKind( final String description ) {
    this.description = description ;
  }

  public static void checkEnumExtender(
      final Kind[] baseValues,
      final Kind[] extendingValues
  ) {
    if( extendingValues.length < baseValues.length ) {
      throw new IncorrectExtensionError( "Only " + extendingValues.length + " values against "
          + baseValues.length + " base values" ) ;
    }
    for( int i = 0 ; i < baseValues.length ; i ++ ) {
      final Kind baseValue = baseValues[ i ] ;
      final Kind extendingValue = extendingValues[ i ] ;
      if( baseValue.ordinal() != extendingValue.ordinal() ) {
        throw new IncorrectExtensionError( "Base ordinal " + baseValue.ordinal()
            + " doesn't match with " + extendingValue.ordinal() ) ;
      }
      if( ! baseValue.name().equals( extendingValue.name() ) ) {
        throw new IncorrectExtensionError( "Base name[ " + i + "] " + baseValue.name()
            + " doesn't match with " + extendingValue.name() ) ;
      }
      if( ! baseValue.description().equals( extendingValue.description() ) ) {
        throw new IncorrectExtensionError( "Description[ " + i + "] " + baseValue.description()
            + " doesn't match with " + extendingValue.description() ) ;
      }
    }
  }

  public static class IncorrectExtensionError extends Error {
    public IncorrectExtensionError( final String s ) {
      super( s ) ;
    }
  }

}

Extension sample:
public enum ExtendingKind implements Kind {
  FIRST( BaseKind.FIRST ),
  SECOND( BaseKind.SECOND ),
  THIRD( "Third" ),
  ;

  private final String description ;

  public String description() {
    return description ;
  }

  ExtendingKind( final BaseKind baseKind ) {
    this.description = baseKind.description() ;
  }

  ExtendingKind( final String description ) {
    this.description = description ;
  }

}

A: Based on @Tom Hawtin - tackline answer we add switch support,
interface Day<T> {
    ...
  T valueOf();
}

public enum Weekday implements Day<Weekday> {
    MON, TUE, WED, THU, FRI;
   Weekday valueOf(){
     return valueOf(name());
   }
}

public enum WeekendDay implements Day<WeekendDay> {
    SAT, SUN;
   WeekendDay valueOf(){
     return valueOf(name());
   }
}

Day<Weekday> wds = Weekday.MON;
Day<WeekendDay> wends = WeekendDay.SUN;

switch(wds.valueOf()){
    case MON:
    case TUE:
    case WED:
    case THU:
    case FRI:
}

switch(wends.valueOf()){
    case SAT:
    case SUN:
}

A: I tend to avoid enums, because they are not extensible. To stay with the example of the OP, if A is in a library and B in your own code, you can't extend A if it is an enum. This is how I sometimes replace enums:
// access like enum: A.a
public class A {
    public static final A a = new A();
    public static final A b = new A();
    public static final A c = new A();
/*
 * In case you need to identify your constant
 * in different JVMs, you need an id. This is the case if
 * your object is transfered between
 * different JVM instances (eg. save/load, or network).
 * Also, switch statements don't work with
 * Objects, but work with int.
 */
    public static int maxId=0;
    public int id = maxId++;
    public int getId() { return id; }
}

public class B extends A {
/*
 * good: you can do like
 * A x = getYourEnumFromSomeWhere();
 * if(x instanceof B) ...;
 * to identify which enum x
 * is of.
 */
    public static final A d = new A();
}

public class C extends A {
/* Good: e.getId() != d.getId()
 * Bad: in different JVMs, C and B
 * might be initialized in different order,
 * resulting in different IDs.
 * Workaround: use a fixed int, or hash code.
 */
    public static final A e = new A();
    public int getId() { return -32489132; };
}

There are some pits to avoid, see the comments in the code. Depending on your needs, this is a solid, extensible alternative to enums.

A: Under the covers your ENUM is just a regular class generated by the compiler. That generated class extends java.lang.Enum. The technical reason you can't extend the generated class is that the generated class is final. The conceptual reasons for it being final are discussed in this topic. But I'll add the mechanics to the discussion.
Here is a test enum:
public enum TEST {
    ONE, TWO, THREE;
}

The resulting code from javap:
public final class TEST extends java.lang.Enum<TEST> {
  public static final TEST ONE;
  public static final TEST TWO;
  public static final TEST THREE;
  static {};
  public static TEST[] values();
  public static TEST valueOf(java.lang.String);
}

Conceivably you could type this class on your own and drop the "final". But the compiler prevents you from extending "java.lang.Enum" directly. You could decide NOT to extend java.lang.Enum, but then your class and its derived classes would not be an instanceof java.lang.Enum ... which might not really matter to you any way!

A: No, you can't do this in Java. Aside from anything else, d would then presumably be an instance of A (given the normal idea of "extends"), but users who only knew about A wouldn't know about it - which defeats the point of an enum being a well-known set of values.
If you could tell us more about how you want to use this, we could potentially suggest alternative solutions.

A: I suggest you take the other way around approach.
Instead of extending the existing enumeration, create a larger one and create a subset of it.
For exemple if you had an enumeration called PET and you wanted to extend it to ANIMAL you should do this instead:
public enum ANIMAL {
    WOLF,CAT, DOG
}
EnumSet<ANIMAL> pets = EnumSet.of(ANIMAL.CAT, ANIMAL.DOG);

Be careful, pets is not an immutable collections, you might want to use Guava or Java9 for more safety.

A: Enums represent a complete enumeration of possible values. So the (unhelpful) answer is no.
As an example of a real problem take weekdays, weekend days and, the union, days of week. We could define all days within days-of-week but then we would not be able to represent properties special to either weekdays and weekend-days.
What we could do, is have three enum types with a mapping between weekdays/weekend-days and days-of-week.
public enum Weekday {
    MON, TUE, WED, THU, FRI;
    public DayOfWeek toDayOfWeek() { ... }
}
public enum WeekendDay {
    SAT, SUN;
    public DayOfWeek toDayOfWeek() { ... }
}
public enum DayOfWeek {
    MON, TUE, WED, THU, FRI, SAT, SUN;
}

Alternatively, we could have an open-ended interface for day-of-week:
interface Day {
    ...
}
public enum Weekday implements Day {
    MON, TUE, WED, THU, FRI;
}
public enum WeekendDay implements Day {
    SAT, SUN;
}

Or we could combine the two approaches:
interface Day {
    ...
}
public enum Weekday implements Day {
    MON, TUE, WED, THU, FRI;
    public DayOfWeek toDayOfWeek() { ... }
}
public enum WeekendDay implements Day {
    SAT, SUN;
    public DayOfWeek toDayOfWeek() { ... }
}
public enum DayOfWeek {
    MON, TUE, WED, THU, FRI, SAT, SUN;
    public Day toDay() { ... }
}

A: enum A {a,b,c}
enum B extends A {d}
/*B is {a,b,c,d}*/

can be written as:
public enum All {
    a       (ClassGroup.A,ClassGroup.B),
    b       (ClassGroup.A,ClassGroup.B),
    c       (ClassGroup.A,ClassGroup.B),
    d       (ClassGroup.B)
...

*

*ClassGroup.B.getMembers() contains {a,b,c,d}

How it can be useful: Let say we want something like:
We have events and we are using enums. Those enums can be grouped by similar processing. If we have operation with many elements, then some events starts operation, some are just step and other end the operation. To gather such operation and avoid long switch case we can group them as in example and use:
if(myEvent.is(State_StatusGroup.START)) makeNewOperationObject()..
if(myEnum.is(State_StatusGroup.STEP)) makeSomeSeriousChanges()..
if(myEnum.is(State_StatusGroup.FINISH)) closeTransactionOrSomething()..

Example:
public enum AtmOperationStatus {
STARTED_BY_SERVER       (State_StatusGroup.START),
SUCCESS             (State_StatusGroup.FINISH),
FAIL_TOKEN_TIMEOUT      (State_StatusGroup.FAIL,
                    State_StatusGroup.FINISH),
FAIL_NOT_COMPLETE       (State_StatusGroup.FAIL,
                    State_StatusGroup.STEP),
FAIL_UNKNOWN            (State_StatusGroup.FAIL,
                    State_StatusGroup.FINISH),
(...)

private AtmOperationStatus(StatusGroupInterface ... pList){
    for (StatusGroupInterface group : pList){
        group.addMember(this);
    }
}
public boolean is(StatusGroupInterface with){
    for (AtmOperationStatus eT : with.getMembers()){
        if( eT .equals(this))   return true;
    }
    return false;
}
// Each group must implement this interface
private interface StatusGroupInterface{
    EnumSet<AtmOperationStatus> getMembers();
    void addMember(AtmOperationStatus pE);
}
// DEFINING GROUPS
public enum State_StatusGroup implements StatusGroupInterface{
    START, STEP, FAIL, FINISH;

    private List<AtmOperationStatus> members = new LinkedList<AtmOperationStatus>();

    @Override
    public EnumSet<AtmOperationStatus> getMembers() {
        return EnumSet.copyOf(members);
    }

    @Override
    public void addMember(AtmOperationStatus pE) {
        members.add(pE);
    }
    static { // forcing initiation of dependent enum
        try {
            Class.forName(AtmOperationStatus.class.getName());
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException("Class AtmEventType not found", ex);
        }
    }
}
}
//Some use of upper code:
if (p.getStatus().is(AtmOperationStatus.State_StatusGroup.FINISH)) {
    //do something
}else if (p.getStatus().is(AtmOperationStatus.State_StatusGroup.START)) {
    //do something
}

Add some more advanced:
public enum AtmEventType {

USER_DEPOSIT        (Status_EventsGroup.WITH_STATUS,
              Authorization_EventsGroup.USER_AUTHORIZED,
              ChangedMoneyAccountState_EventsGroup.CHANGED,
              OperationType_EventsGroup.DEPOSIT,
              ApplyTo_EventsGroup.CHANNEL),
SERVICE_DEPOSIT     (Status_EventsGroup.WITH_STATUS,
              Authorization_EventsGroup.TERMINAL_AUTHORIZATION,
              ChangedMoneyAccountState_EventsGroup.CHANGED,
              OperationType_EventsGroup.DEPOSIT,
              ApplyTo_EventsGroup.CHANNEL),
DEVICE_MALFUNCTION  (Status_EventsGroup.WITHOUT_STATUS,
              Authorization_EventsGroup.TERMINAL_AUTHORIZATION,
              ChangedMoneyAccountState_EventsGroup.DID_NOT_CHANGED,
              ApplyTo_EventsGroup.DEVICE),
CONFIGURATION_4_C_CHANGED(Status_EventsGroup.WITHOUT_STATUS,
              ApplyTo_EventsGroup.TERMINAL,
              ChangedMoneyAccountState_EventsGroup.DID_NOT_CHANGED),
(...)

At above if we have some fail (myEvent.is(State_StatusGroup.FAIL)) then iterating by previous events we can easily check if we must revert money transfer by:
if(myEvent2.is(ChangedMoneyAccountState_EventsGroup.CHANGED)) rollBack()..

It can be useful for:

*

*including explicite meta-data about processing logic, less to remember

*implementing some of multi-inheritance

*we don't want to use class structures, ex. for sending short status messages

A: As an aid to understanding why extending an Enum is not reasonable at the language implementation level to consider what would happen if you passed an instance of the extended Enum to a routine that only understands the base Enum. A switch that the compiler promised had all cases covered would in fact not cover those extended Enum values.
This further emphasizes that Java Enum values are not integers such as C's are, for instances: to use a Java Enum as an array index you must explicitly ask for its ordinal() member, to give a java Enum an arbitrary integer value you must add an explicit field for that and reference that named member.
This is not a comment on the OP's desire, just on why Java ain't never going to do it.

A: Having had this same problem myself I'd like to post my perspective. I think that there are a couple motivating factors for doing something like this:

*

*You want to have some related enum codes, but in different classes. In my case I had a base class with several codes defined in an associated enum. At some later date (today!) I wanted to provide some new functionality to the base class, which also meant new codes for the enum.

*The derived class would support both the base classes' enum as well as its own. No duplicate enum values! So: how to have an enum for the subclass that includes the enum's of its parent along with its new values.

Using an interface doesn't really cut it: you can accidentally get duplicate enum values. Not desirable.
I ended up just combining the enums: this ensures that there cannot be any duplicate values, at the expense of being less tightly tied to its associated class. But, I figured the duplicate issue was my main concern...

A: In the hopes this elegant solution of a colleague of mine is even seen in this long post I'd like to share this approach for subclassing which follows the interface approach and beyond.
Please be aware that we use custom exceptions here and this code won't compile unless you replace it with your exceptions.
The documentation is extensive and I hope it's understandable for most of you.
The interface that every subclassed enum needs to implement.
public interface Parameter {
  /**
   * Retrieve the parameters name.
   *
   * @return the name of the parameter
   */
  String getName();

  /**
   * Retrieve the parameters type.
   *
   * @return the {@link Class} according to the type of the parameter
   */
  Class<?> getType();

  /**
   * Matches the given string with this parameters value pattern (if applicable). This helps to find
   * out if the given string is a syntactically valid candidate for this parameters value.
   *
   * @param valueStr optional - the string to check for
   * @return true in case this parameter has no pattern defined or the given string
   *         matches the defined one, false in case valueStr is
   *         null or an existing pattern is not matched
   */
  boolean match(final String valueStr);

  /**
   * This method works as {@link #match(String)} but throws an exception if not matched.
   *
   * @param valueStr optional - the string to check for
   * @throws ArgumentException with code
   *

   *
PARAM_MISSED

   *
if valueStr is null

   *
PARAM_BAD

   *
if pattern is not matched

   *

   */
  void matchEx(final String valueStr) throws ArgumentException;

  /**
   * Parses a value for this parameter from the given string. This method honors the parameters data
   * type and potentially other criteria defining a valid value (e.g. a pattern).
   *
   * @param valueStr optional - the string to parse the parameter value from
   * @return the parameter value according to the parameters type (see {@link #getType()}) or
   *         null in case valueStr was null.
   * @throws ArgumentException in case valueStr is not parsable as a value for this
   *           parameter.
   */
  Object parse(final String valueStr) throws ArgumentException;

  /**
   * Converts the given value to its external form as it is accepted by {@link #parse(String)}. For
   * most (ordinary) parameters this is simply a call to {@link String#valueOf(Object)}. In case the
   * parameter types {@link Object#toString()} method does not return the external form (e.g. for
   * enumerations), this method has to be implemented accordingly.
   *
   * @param value mandatory - the parameters value
   * @return the external form of the parameters value, never null
   * @throws InternalServiceException in case the given value does not match
   *           {@link #getType()}
   */
  String toString(final Object value) throws InternalServiceException;
}

The implementing ENUM base class.
public enum Parameters implements Parameter {
  /**
   * ANY ENUM VALUE
   */
  VALUE(new ParameterImpl<String>("VALUE", String.class, "[A-Za-z]{3,10}"));

  /**
   * The parameter wrapped by this enum constant.
   */
  private Parameter param;

  /**
   * Constructor.
   *
   * @param param mandatory - the value for {@link #param}
   */
  private Parameters(final Parameter param) {
    this.param = param;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String getName() {
    return this.param.getName();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Class<?> getType() {
    return this.param.getType();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean match(final String valueStr) {
    return this.param.match(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void matchEx(final String valueStr) {
    this.param.matchEx(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Object parse(final String valueStr) throws ArgumentException {
    return this.param.parse(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString(final Object value) throws InternalServiceException {
    return this.param.toString(value);
  }
}

The subclassed ENUM which "inherits" from base class.
public enum ExtendedParameters implements Parameter {
  /**
   * ANY ENUM VALUE
   */
  VALUE(my.package.name.VALUE);

  /**
   * EXTENDED ENUM VALUE
   */
  EXTENDED_VALUE(new ParameterImpl<String>("EXTENDED_VALUE", String.class, "[0-9A-Za-z_.-]{1,20}"));

  /**
   * The parameter wrapped by this enum constant.
   */
  private Parameter param;

  /**
   * Constructor.
   *
   * @param param mandatory - the value for {@link #param}
   */
  private Parameters(final Parameter param) {
    this.param = param;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String getName() {
    return this.param.getName();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Class<?> getType() {
    return this.param.getType();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean match(final String valueStr) {
    return this.param.match(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void matchEx(final String valueStr) {
    this.param.matchEx(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Object parse(final String valueStr) throws ArgumentException {
    return this.param.parse(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString(final Object value) throws InternalServiceException {
    return this.param.toString(value);
  }
}

Finally the generic ParameterImpl to add some utilities.
public class ParameterImpl<T> implements Parameter {
  /**
   * The default pattern for numeric (integer, long) parameters.
   */
  private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]+");

  /**
   * The default pattern for parameters of type boolean.
   */
  private static final Pattern BOOLEAN_PATTERN = Pattern.compile("0|1|true|false");

  /**
   * The name of the parameter, never null.
   */
  private final String name;

  /**
   * The data type of the parameter.
   */
  private final Class<T> type;

  /**
   * The validation pattern for the parameters values. This may be null.
   */
  private final Pattern validator;

  /**
   * Shortcut constructor without validatorPattern.
   *
   * @param name mandatory - the value for {@link #name}
   * @param type mandatory - the value for {@link #type}
   */
  public ParameterImpl(final String name, final Class<T> type) {
    this(name, type, null);
  }

  /**
   * Constructor.
   *
   * @param name mandatory - the value for {@link #name}
   * @param type mandatory - the value for {@link #type}
   * @param validatorPattern - optional - the pattern for {@link #validator}
   *

   *
Note:
   *
The default validation patterns {@link #NUMBER_PATTERN} or
   *          {@link #BOOLEAN_PATTERN} are applied accordingly.
   *

   */
  public ParameterImpl(final String name, final Class<T> type, final String validatorPattern) {
    this.name = name;
    this.type = type;
    if (null != validatorPattern) {
      this.validator = Pattern.compile(validatorPattern);

    } else if (Integer.class == this.type || Long.class == this.type) {
      this.validator = NUMBER_PATTERN;
    } else if (Boolean.class == this.type) {
      this.validator = BOOLEAN_PATTERN;
    } else {
      this.validator = null;
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean match(final String valueStr) {
    if (null == valueStr) {
      return false;
    }
    if (null != this.validator) {
      final Matcher matcher = this.validator.matcher(valueStr);
      return matcher.matches();
    }
    return true;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void matchEx(final String valueStr) throws ArgumentException {
    if (false == this.match(valueStr)) {
      if (null == valueStr) {
        throw ArgumentException.createEx(ErrorCode.PARAM_MISSED, "The value must not be null",
            this.name);
      }
      throw ArgumentException.createEx(ErrorCode.PARAM_BAD, "The value must match the pattern: "
          + this.validator.pattern(), this.name);
    }
  }

  /**
   * Parse the parameters value from the given string value according to {@link #type}. Additional
   * the value is checked by {@link #matchEx(String)}.
   *
   * @param valueStr optional - the string value to parse the value from
   * @return the parsed value, may be null
   * @throws ArgumentException in case the parameter:
   *

   *
does not {@link #matchEx(String)} the {@link #validator}

   *
cannot be parsed according to {@link #type}

   *

   * @throws InternalServiceException in case the type {@link #type} cannot be handled. This is a
   *           programming error.
   */
  @Override
  public T parse(final String valueStr) throws ArgumentException, InternalServiceException {
    if (null == valueStr) {
      return null;
    }
    this.matchEx(valueStr);

    if (String.class == this.type) {
      return this.type.cast(valueStr);
    }
    if (Boolean.class == this.type) {
      return this.type.cast(Boolean.valueOf(("1".equals(valueStr)) || Boolean.valueOf(valueStr)));
    }
    try {
      if (Integer.class == this.type) {
        return this.type.cast(Integer.valueOf(valueStr));
      }
      if (Long.class == this.type) {
        return this.type.cast(Long.valueOf(valueStr));
      }
    } catch (final NumberFormatException e) {
      throw ArgumentException.createEx(ErrorCode.PARAM_BAD, "The value cannot be parsed as "
          + this.type.getSimpleName().toLowerCase() + ".", this.name);
    }

    return this.parseOther(valueStr);
  }

  /**
   * Field access for {@link #name}.
   *
   * @return the value of {@link #name}.
   */
  @Override
  public String getName() {
    return this.name;
  }

  /**
   * Field access for {@link #type}.
   *
   * @return the value of {@link #type}.
   */
  @Override
  public Class<T> getType() {
    return this.type;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public final String toString(final Object value) throws InternalServiceException {
    if (false == this.type.isAssignableFrom(value.getClass())) {
      throw new InternalServiceException(ErrorCode.PANIC,
          "Parameter.toString(): Bad type of value. Expected {0} but is {1}.", this.type.getName(),
          value.getClass().getName());
    }
    if (String.class == this.type || Integer.class == this.type || Long.class == this.type) {
      return String.valueOf(value);
    }
    if (Boolean.class == this.type) {
      return Boolean.TRUE.equals(value) ? "1" : "0";
    }

    return this.toStringOther(value);
  }

  /**
   * Parse parameter values of other (non standard types). This method is called by
   * {@link #parse(String)} in case {@link #type} is none of the supported standard types (currently
   * String, Boolean, Integer and Long). It is intended for extensions.
   *

   *
Note:
   *
This default implementation always throws an InternalServiceException.
   *

   *
   * @param valueStr mandatory - the string value to parse the value from
   * @return the parsed value, may be null
   * @throws ArgumentException in case the parameter cannot be parsed according to {@link #type}
   * @throws InternalServiceException in case the type {@link #type} cannot be handled. This is a
   *           programming error.
   */
  protected T parseOther(final String valueStr) throws ArgumentException, InternalServiceException {
    throw new InternalServiceException(ErrorCode.PANIC,
        "ParameterImpl.parseOther(): Unsupported parameter type: " + this.type.getName());
  }

  /**
   * Convert the values of other (non standard types) to their external form. This method is called
   * by {@link #toString(Object)} in case {@link #type} is none of the supported standard types
   * (currently String, Boolean, Integer and Long). It is intended for extensions.
   *

   *
Note:
   *
This default implementation always throws an InternalServiceException.
   *

   *
   * @param value mandatory - the parameters value
   * @return the external form of the parameters value, never null
   * @throws InternalServiceException in case the given value does not match
   *           {@link #getClass()}
   */
  protected String toStringOther(final Object value) throws InternalServiceException {
    throw new InternalServiceException(ErrorCode.PANIC,
        "ParameterImpl.toStringOther(): Unsupported parameter type: " + this.type.getName());
  }
}

A: In case you missed it, there's a chapter in the excellent Joshua Bloch's book "Effective Java, 2nd edition".

*

*Chapter 6 - Enums and Annotations

*Item 34 : Emulate extensible enums with interfaces
Just the conclusion :

A minor disadvantage of the use of interfaces to emulate extensible enums is
those implementations cannot be inherited from one enum type to another. In the
case of our Operation example, the logic to store and retrieve the symbol associated
with an operation is duplicated in BasicOperation and ExtendedOperation.
In this case, it doesn't matter because very little code is duplicated. If there were a
a larger amount of shared functionality, you could encapsulate it in a helper class or
a static helper method to eliminate the code duplication.

In summary, while you cannot write an extensible enum type, you can
emulate it by writing an interface to go with a basic enum type that implements
the interface. This allows clients to write their own enums that implement
the interface. These enums can then be used wherever the basic enum type can be
used, assuming APIs are written in terms of the interface.

A: Here is a way how I found how to extend a enum into other enum, is a very straighfoward approach:
Suposse you have a enum with common constants:
public interface ICommonInterface {

    String getName();

}

public enum CommonEnum implements ICommonInterface {
    P_EDITABLE("editable"),
    P_ACTIVE("active"),
    P_ID("id");

    private final String name;

    EnumCriteriaComun(String name) {
        name= name;
    }

    @Override
    public String getName() {
        return this.name;
    }
}

then you can try to do a manual extends in this way:
public enum SubEnum implements ICommonInterface {
    P_EDITABLE(CommonEnum.P_EDITABLE ),
    P_ACTIVE(CommonEnum.P_ACTIVE),
    P_ID(CommonEnum.P_ID),
    P_NEW_CONSTANT("new_constant");

    private final String name;

    EnumCriteriaComun(CommonEnum commonEnum) {
        name= commonEnum.name;
    }

    EnumCriteriaComun(String name) {
        name= name;
    }

    @Override
    public String getName() {
        return this.name;
    }
}

of course every time you need to extend a constant you have to modify your SubEnum files.

A: My way to code that would be as follows:
// enum A { a, b, c }
static final Set<Short> enumA = new LinkedHashSet<>(Arrays.asList(new Short[]{'a','b','c'}));

// enum B extends A { d }
static final Set<Short> enumB = new LinkedHashSet<>(enumA);
static {
    enumB.add((short) 'd');
    // If you have to add more elements:
    // enumB.addAll(Arrays.asList(new Short[]{ 'e', 'f', 'g', '♯', '♭' }));
}

LinkedHashSet provides both that each entry only exists once, and that their order is preserved. If order doesn't matter, you can use HashSet instead. The following code is not possible in Java:
for (A a : B.values()) { // enum B extends A { d }
    switch (a) {
        case a:
        case b:
        case c:
            System.out.println("Value is: " + a.toString());
        break;
        default:
            throw new IllegalStateException("This should never happen.");
    }
}

The code can be written as follows:
for (Short a : enumB) {
    switch (a) {
        case 'a':
        case 'b':
        case 'c':
            System.out.println("Value is: " + new String(Character.toChars(a)));
        break;
        default:
            throw new IllegalStateException("This should never happen.");
    }
}

From Java 7 onwards you can even do the same with String:
// enum A { BACKWARDS, FOREWARDS, STANDING }
static final Set<String> enumA = new LinkedHashSet<>(Arrays.asList(new String[] {
        "BACKWARDS", "FOREWARDS", "STANDING" }));

// enum B extends A { JUMP }
static final Set<String> enumB = new LinkedHashSet<>(enumA);
static {
    enumB.add("JUMP");
}

Using the enum replacement:
for (String a : enumB) {
    switch (a) {
        case "BACKWARDS":
        case "FOREWARDS":
        case "STANDING":
            System.out.println("Value is: " + a);
        break;
        default:
            throw new IllegalStateException("This should never happen.");
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: iAd didFailToReceiveAdWithError called before viewDidLoad I have an iAdBannerView instaniated by IB and connected properly along with the delegate. When I start up the app, I see didFailToReceiveAdWithError being called before the viewDidLoad method. In the stack trace I see [ADBannerView _sanitizeAndForwardErrorToDelegate:].
This doesn't seem quite right, but I have to ask, is this normal behavior?
The bannerViewDidLoadAd is never called and yes, I'm in the US and connected to network.
This is happening in both the simulator and the iOS device.


text:
Q: Equivalent code in Python to PHP I need the equivalent code for this python code in PHP.
val would be a string containing two words seperated by a "-" and the code would separate them into two different strings
Here is the Python Code:
def function(val) :
    s= False
    ar = ""
    so = ""
    For x in val :
        if s == true :
            x.append(so)
        elif x <> "-" :
            x.append(ar)
        elif x == "-" :
            s= true

A: $result = explode('-', $val);

$result contains an array of strings, split at the hyphen, i.e. $result[0], etc
http://php.net/explode

A: function func($val)
{
    if(!strpos($val,'-')) return false;
    $vars   =   explode('-',$val);
    return array($vars[0],$vars[1]);
}


text:
Q: Why does my simple code not work when invoking a function using inputted values? As an exercise I have been tasked with writing a function that will check if a given container contains a searched value, returning True if it does and False if it doesn't. I have created the following function:
setContainer = {i for i in range(1000)}
listContainer = [i for i in range(1000)]

def does_it_contain(container, value):
    if value in container:
        return True
    if value not in container:
        return False

which works fine when I invoke the function explicitly.
However I am trying to add some code to let the user search for a value in the container of his choice like:
checkValue = input("Search for: ")
checkContainer = input("Seach in container named: ")

print(does_it_contain(checkContainer, checkValue))

But this seems to always yield False, and I can't figure out why. Where have I gone wrong?

A: Because checkContainer is a string, passing a string to does_it_contain function will let it to check whether the value is in the particular checkContainer string instead of the container object.
If you want to find the correct container by its name, you could create a dictionary.
# Using dictionary

dict = {
    "a": [...],
    "b": {...}
}

def func(name, val):
    print(val in dict[name])

A: The problem is that the user inputs a string which can be identical to the name of your container's name, but it won't be the container object you defined in your code.
Instead you should create a mapping, e.g. a dictionary, in which you store the reference of your containers, and you can pick the right one based on the user's input:
setContainer = {i for i in range(1000)}
listContainer = [i for i in range(1000)]

container_switcher = {
    "setContainer": setContainer,
    "listContainer": listContainer,
}

def does_it_contain(container, value):
    if value in container:
        return True
    if value not in container:
        return False

checkValue = input("Search for: ")
checkContainer = input("Seach in container named: ")

container = container_switcher.get(checkContainer, None)
if container is None:
    print("Invalid container name: " + checkContainer)
else:
    print(does_it_contain(container, int(checkValue)))

Note that you have to convert the checkValue to an integer when passing to the does_it_contain function, otherwise you will pass it as a string and it will also always return False.

A: There are two problems in your code. You are searching for a string in a set of integers, and that you are just getting a string containing either setContainer or listContainer, and not the variable values themselves.
To fix the first issue, use str(i) for i in range(1000) instead of i for i in range(1000).
For the second issue, change if value in container: to if value in containers[container]: and to the same for the second if statement. Then, change
setContainer = {i for i in range(1000)}
listContainer = [i for i in range(1000)]

to
containers = {
  'setContainer': {str(i) for i in range(1000)},
  'listContainer': [str(i) for i in range(1000)]
}

so that you can access the values using a string like so: containers[container].
containers = {
  'setContainer': {str(i) for i in range(1000)},
  'listContainer': [str(i) for i in range(1000)]
}

def does_it_contain(container, value):
    if value in containers[container]:
        return True
    if value not in containers[container]:
        return False

checkValue = input("Search for: ")
checkContainer = input("Seach in container named: ")

print(does_it_contain(checkContainer, checkValue))

This will throw an error if the container doesn't exist, so you'll have to wrap print(does_it_contain(checkContainer, checkValue)) in a try...except block to check if the user entered an invalid container name.

A: As also noted in other answers, your code has two issues: looking up a string in a list of int's and passing a string with the intent to pass a variable name. Workarounds for both can be found in these answers.
That being said, if you really wanted to directly get the variable name using an input field, there are different possibilities for that as well. See Convert a string to preexisting variable names for details and also for hints on how not to do it (i.e. don't use eval()!)
One way would be to use the globals() function in python that gives you a dictionary of all defined variables:
setContainer = {str(i) for i in range(1000)}
listContainer = [str(i) for i in range(1000)]

def does_it_contain(container, value):
    if value in container:
        return True
    if value not in container:
        return False

checkValue = input("Search for: ")
checkContainerVarName = input("Seach in container named: ")

print(does_it_contain(globals()[checkContainerVarName], checkValue))

will do what you originally intended.


text:
Q: will redis list of large size store data in multiple redis nodes in a cluster? I have started reading Redis and have a query of how it internally works in multi-node distributed environment ?
1.) I created Redis list and adding 1M elements which is of size 20GB .
2.) Lets say my node capacity is 12 GB .
3.) Will redis internally split list into multiple nodes ? If so , how does it take care of insertion order while retrieving elements ?

A: I think one node of Redis cluster will crash.
Because redis cluster distribute key by hash-slot, which means keys with the same hash will be distributed to the same node, and one key will only be holded on one node.So 20GB data will go to one node by key's (type is list) hash, and this node(only with 12 GB memory) will crash.


text:
Q: Return empty bracket [ ] when web scraping I try to print all the titles on nytimes.com. I used requests and beautifulsoup module. But I got empty brackets in the end. The return result is [ ]. How can I fix this problem?
import requests
from bs4 import BeautifulSoup

url = "https://www.nytimes.com/"
r = requests.get(url)
text = r.text
soup = BeautifulSoup(text, "html.parser")
title = soup.find_all("span", "balanceHeadline")
print(title)

A: I am assuming that you are trying to retrieve the headlines of nytimes. Doing title = soup.find_all("span", {'class':'balancedHeadline'}) will not get you your results. The <span> tag found using the  element selector is often misleading. What you have to do is to look into the source code of the page and find the tags wrapped around the title.
For nytimes its a little tricky because the headlines are wrapped in the <script> tag with a lot of junk inside. Hence what you can do is to "clean" it first and deserialize the string by convertinng it into a python dictionary object.
import requests
from bs4 import BeautifulSoup
import json

url = "https://www.nytimes.com/"
r = requests.get(url)

r_html = r.text
soup = BeautifulSoup(r_html, "html.parser")

scripts = soup.find_all('script')
for script in scripts:
    if 'preloadedData' in script.text:
        jsonStr = script.text
        jsonStr = jsonStr.split('=', 1)[1].strip() # remove "window.__preloadedData = "
        jsonStr = jsonStr.rsplit(';', 1)[0] # remove trailing ;
        jsonStr = json.loads(jsonStr)

for key,value in jsonStr['initialState'].items():
    try:
        if value['promotionalHeadline'] != "":
            print(value['promotionalHeadline'])
    except:
        continue

outputs
Jeffrey Epstein Autopsy Results Conclude He Hanged Himself
Trump and Netanyahu Put Bipartisan Support for Israel at Risk
Congresswoman Rejects Israel's Offer of a West Bank Visit
In Tlaib's Ancestral Village, a Grandmother Weathers a Global Political Storm
Cathay Chief's Resignation Shows China's Power Over Hong Kong Unrest
Trump Administration Approves Fighter Jet Sales to Taiwan
Peace Road Map for Afghanistan Will Let Taliban Negotiate Women's Rights
Debate Flares Over Afghanistan as Trump Considers Troop Withdrawal
In El Paso, Hundreds Show Up to Mourn a Woman They Didn't Know
Is Slavery's Legacy in the Power Dynamics of Sports?
Listen: 'Modern Love' Podcast
'The Interpreter'
If You Think Trump Is Helping Israel, You're a Fool
First They Came for the Black Feminists
How Women Can Escape the Likability Trap
With Trump as President, the World Is Spiraling Into Chaos
To Understand Hong Kong, Don't Think About Tiananmen
The Abrupt End of My Big-Girl Summer
From Trump Boom to Trump Gloom
What Are Trump and Netanyahu Afraid Of?
King Bibi Bows Before a Tweet
Ebola Could Be Eradicated — But Only if the World Works Together
The Online Mob Came for Me. What Happened to the Reckoning?
A German TV Star Takes On Bullies
Why Is Hollywood So Scared of Climate Change?
Solving Medical Mysteries With Your Help: Now on Netflix

A: title = soup.find_all("span", "balanceHeadline")

replace it with
title = soup.find_all("span", {'class':'balanceHeadline'})


text:
Q: Pytest: Update a global variable in test I am new to Python and am using pytest for testing
I am executing the pytest from within the python script. I have a global variable in the script which I modify based on the result in the test. The updated global variable is again used after the tests are executed.
import pytest
global test_suite_passed
test_suite_passed = True

def test_toggle():
   global test_suite_passed
   a = True
   b = True
   c = True if a == b else False
   test_suite_passed = c
   assert c

def test_switch():
   global test_suite_passed
   one = True
   two = False
   three = True if one == two else False
   if test_suite_passed:
      test_suite_passed = three
   assert three

if __name__ == '__main__':
   pytest.main()
   if not test_suite_passed:
      raise Exception("Test suite failed")
   print "Test suite passed"

I have two questions:
1) The above code snippet prints "Test suite passed", whereas I am expecting an Exception to be raised as the second test case has failed.
2) Basically, I want a handle to the result of the pytest, through which I can get to know the number of test cases passed and failed. This shows up in the test summary. But I am looking for a object which I can use further in the script after the tests are executed

A: pytest is designed to be called from command line, not from inside your test script. Your global variable does not work, because pytest imports your script as module, which has it's own namespace.
To customize the report generation, use the post-process-hook:
http://doc.pytest.org/en/latest/example/simple.html#post-process-test-reports-failures

A: This can be solved using the exit code return when calling pytest.main()  The global variable is not necessary
import pytest

def test_toggle():
    a = True
    b = True
    c = True if a == b else False
    assert c

def test_switch():
    one = True
    two = False
    three = True if one == two else False
    assert three

if __name__ == '__main__':
    exit_code = pytest.main()
    if exit_code == 1:
        raise Exception("Test suite failed")
    print "Test suite passed"


text:
Q: rake db:schema:dump doesn't provide data migration info - is there an automated way to get this? rake db:schema:dump

This command gives you the schema of a legacy database and you can build a migration for that database off the generated schema.
But if that database had data in it, it would be nice if there was a rake command to retrieve the data in a migration file generated by Rails.
Perhaps I'm dreaming - it's probably asking too much to think that Rails could look at the data in the legacy database and construct a migration for you from the existing data - something like this:
class LoadDefaultData < ActiveRecord::Migration
  def self.up
    bopeep = User.find_by_username 'bopeep'
    BlogPost.create(:title => 'test', :content => 'test', :author_id => bopeep.id, :status => 'ok')
  end

  def self.down
  end
end

Or is there a way?

A: Tobias Lütke needed to migrate a database from one architecture to another but needed to copy the data across intact. To ensure that the format would be architecture agnostic, he's created a plugin that dumps the data to YAML and then reloads it back into the database at the other end. It's a simple rake task, and Tobi gives quick and easy instructions.
http://blog.leetsoft.com/2006/5/29/easy-migration-between-databases
This may help.
You may also like to look at YamlDB plugin http://opensource.heroku.com/ which can back up from one db type and restore to another. Here are some instructions


text:
Q: How to search and replace with regex in Notepad++ I have a txt files with some lines containing GPS data, which I need to shorten.
So I have
5|{"mResults":0.0|0.0|"mProvider":"fused"|"mDistance":0.0|"mTime":1395061255413|"mAltitude":161.0|"mLongitude":29.0459152|"mLon2":0.0|"mLon1":0.0|"mLatitude":41.0854122|"mLat1":0.0|"mLat2":0.0|"mInitialBearing":0.0|"mHasSpeed":true|"mHasBearing":false|"mHasAltitude":true|"mHasAccuracy":true|"mAccuracy":15.0|"mSpeed":0.425211|"mBearing":0.0}|1395061255413

and I need to extract only the coordinates,
so convert it into this :
29.0459152|41.0854122

Edit:
Turns out I need this:
GPS|29.0459152|41.0854122|0|1395061255413

Please note that I need to :

*

*add GPS| in front, and |0 at the end.

*and also I need to append the timestamp value (the last value in the original one) |1395061255413
How can I do this with Notepad++?
Thanks for any help !

A: Here is how you could do that in Notepad++:

*

*use Ctrl+H to open the Replace pop-up

*tick Regular expression in the Search mode section

*search for this pattern: .*?"mLongitude":(\d+(?:\.\d+)?).*?"mLatitude":(\d+(?:\.\d+)).*

*replace the matched string by \1|\2

*click on Replace all ;)

How it works:
The regex pattern featured in my answer extracts the values for the longitude and latitude from each line and replaces the whole line by:

*

*the mLongitude value,

*a literal "|" and

*the mLatitude value.

Would you like to have this pattern explained in more details, please check out this permalink on regex101.

EDIT:
To include the timestamp you're referring to, you need to use this regex:
.*?"mLongitude":(\d+(?:\.\d+)?).*?"mLatitude":(\d+(?:\.\d+)).*\|(\d+)

Then, you just have to change the formatting of your replacement string to this:
GPS|\1|\2|0|\3

You probably got that already but let's still write down the complete usable solution ;)
I hope this helps!

A: I solved my problem by this :
search:
.*?"mTime":(\d+(?:\.\d+)?).*?"mLongitude":(\d+(?:\.\d+)).*?"mLatitude":(\d+(?:\.\d+)).*

replace :
GPS|\2|\3|0|\1

But this is because the same data (timestamp) was also inside the string. So this does not extract the timestamp from the end, but from the middle of the string.
So if @ccjmne edits the answer that extracts it from the end, I will accept that answer.


text:
Q: C Programming- How to delete a line containing a specific word from file? I have created a stock inventory program for a jewelry store.
However, I cannot seem to figure out how to search for a specific word in a file containing the items (in a table form) and delete the entire line which the word was on.
For example, I can delete earring from the list but not the quantity as well which would be a few spaces away on the same line.
#include <stdio.h>

int main() {
    FILE *fp1, *fp2;

    //consider 40 character string to store filename
    char filename[40];
    char c;
    int del_line, temp = 1;

    //asks user for file name
    printf("Enter file name: ");

    //receives file name from user and stores in 'filename'
    scanf("%s", filename);

    //open file in read mode
    fp1 = fopen(filename, "r");
    c = getc(fp1);

    //until the last character of file is obtained
    while (c != EOF) {
        printf("%c", c);
        //print current character and read next character
        c = getc(fp1);
    }
    //rewind
    rewind(fp1);
    printf(" \n Enter line number of the line to be deleted:");
    //accept number from user.
    scanf("%d", &del_line);

    //open new file in write mode
    fp2 = fopen("copy.c", "w");
    c = getc(fp1);
    while (c != EOF) {
        c = getc(fp1);
        if (c == '\n')
            temp++;
        //except the line to be deleted
        if (temp != del_line) {
            //copy all lines in file copy.c
            putc(c, fp2);
        }
    }

    //close both the files.
    fclose(fp1);
    fclose(fp2);

    //remove original file
    remove(filename);

    //rename the file copy.c to original name
    rename("copy.c", filename);
    printf("\n The contents of file after being modified are as  follows:\n");

    fp1 = fopen(filename, "r");
    c = getc(fp1);

    while (c != EOF) {
        printf("%c", c);
        c = getc(fp1);
    }
    fclose(fp1);
    return 0;
}

A: Your code has several issues:

*

*You read the filename with an unprotected call to scanf, if the name typed by the user exceeds 39 characters, you invoke undefined behavior.  Make the buffer larger as filenames tend to be long nowadays and protect the format this way:
char filename[256];

if (scanf("%255s", filename) != 1) {
    /* end of file reached, deal with this error */
    ...
}

*Your method for reading a file byte by byte is incorrect: c should be defined as an int otherwise you cannot reliably detect EOF. The standard idiom for this is:
int c;

//until the last character of file is obtained
while ((c = getc(fp1)) != EOF) {
    //print current character and read next character
    putchar(c);
}

*In the copy phase, you drop the first character of the file.

*You ignore errors.  Not only do you invoke undefined behavior, you may actually erase the file after failing to copy its contents.

*You ask for a line number from the user, but you do not show the line numbers in the echo phase.  Doing so would help.
Here is a improved version:
#include <stdio.h>

int main(void) {
    FILE *fp1, *fp2;

    //consider 255 character string to store filename
    char filename[256];
    int c, last, del_line, lineno;

    //asks user for file name
    printf("Enter file name: ");

    //receives file name from user and stores in 'filename'
    if (scanf("%255s", filename) != 1) {
        perror("missing filename");
        return 1;
    }

    //open file in read mode
    fp1 = fopen(filename, "r");
    if (fp1 == NULL) {
        perror("cannot open file");
        return 1;
    }

    //until the last character of file is obtained
    last = '\n';
    lineno = 0;
    while ((c = getc(fp1)) != EOF) {
        if (last == '\n') {
            printf("%4d: ", ++lineno);
        }
        //print current character and read next character
        putchar(c);
        last = c;
    }

    rewind(fp1);
    printf("\nEnter line number of the line to be deleted: ");
    //accept number from user.
    if (scanf("%d", &del_line) != 1) {
        perror("missing line number");
        return 1;
    }
    if (del_line < 1 || del_line > lineno) {
        printf("no such line: %d\n", del_line);
        return 1;
    }

    //open new file in write mode
    fp2 = fopen("copy.c", "w");
    if (fp2 == NULL) {
        perror("cannot open copy.c");
        return 1;
    }

    lineno = 1;
    while ((c = getc(fp1)) != EOF) {
        //except the line to be deleted
        if (lineno != del_line) {
            //copy all lines in file copy.c
            putc(c, fp2);
        }
        if (c == '\n')
            lineno++;
    }

    //close both files.
    fclose(fp1);
    if (fclose(fp2)) {
        perror("write error to copy.c");
        return 1;
    }

    // remove original file (unsafe)
    // uncomment this if your system does not allow rename
    // to overwrite existing files
    // if (remove(filename)) {
    //     perror("cannot remove source file");
    //     return 1;
    // }

    //rename the file copy.c to original name
    if (rename("copy.c", filename)) {
        perror("cannot rename file");
        return 1;
    }

    printf("\nThe contents of file after being modified are as  follows:\n");

    fp1 = fopen(filename, "r");
    if (fp1 == NULL) {
        perror("cannot re-open modified file");
        return 1;
    }

    while ((c = getc(fp1)) != EOF) {
        putchar(c);
    }
    fclose(fp1);
    return 0;
}


text:
Q: Relationship hasMore on laravel getting twin results I try to display data that has entered into postlocation to be displayed at each location, if the data is there then the color of the location will be green

        Location

            @foreach ($locations as $location)
                @foreach ($postlog->postlocationget as $postlocation)
                        @if($location->id == 1)
                        @else

location == $location->id) badge-success @else badge-info @endif" id="badgeloc{{$location->id}}">{{$location->location}}

                        <input hidden="hidden" type="checkbox" id="checkloc{{$location->id}}">
                        @endif
                @endforeach
            @endforeach


text:
Q: Jax-ws not supported by IBM WebSphere 8.5 Liberty Profile While trying to deploy a JAX-WS application in WebSphere 8.5 Liberty profile is throwing "JAXWS" not supported error. Tried to configure the feature manager but cant find JAX-WS plugin in it.

A: Which version you downloaded? Please download the latest one from here . For jax-ws you need to download and install also extended part - wlp-extended-8.5.5.5.jar.
To verify that you have jax-ws-2.2 feature run the following command:
C:\WebSphere\wlp\bin>productInfo featureInfo

you should have: jaxws-2.2 [1.0.0] in the list.
Once you install the feature, if you are using Eclipse, you will need to refresh the available features. Do following:

*

*Go to Window > Preferences > Server Runtime Environments

*Select Liberty runtime and click Edit

*Click Advanced options... link

*And click Refresh.

Then jax-ws feature should be visible while configuring server.xml.


text:
Q: How to use sortProperties: ['lastName'] I'd like to sort an Array or users which gets fetched by ember-data. I can't figure out to sort the array be lastName. The following code doesn't do the job. How can I fix it?
app.js
App.UsersRoute = Ember.Route.extend({
  model: function() {
    return App.User.find();
  }
});

App.UsersController = Ember.ArrayController.extend({
  sortProperties: ['lastName'],
  sortAscending: true
})

index.html

A: Kudos to Bradley Priest for answering the question. Using this in the template does the trick.
index.html


text:
Q: Including columns using MAP and dictionary in a dataframe I am trying to include a column in a dataframe. I am using MAP tool in order to add it because it should be referenced to one variable.
Here is the current dataframe:
  X      Y            Z
  xx    high         10
        slow         20
        fat          30
  xy    high         15
        slow         10
        fast         30

I would like to include a column D taking X as a reference. This new column should be based on a dict (dictionary) with the following values:
{'xx': -4.50, 'xy': -10.21}

So I did:
df['D'] = df['X'].map(dicc)

However, when I run the code a message appears KeyError: 'X' . Am I missing something in the code or it is an issue in the data type (str / float)?
Any help would be appreciated.
Thanks a lot!
EDIT:
I get the dataframe from a groupby taking Xand Y as reference (thanks for the comment).

A: You can use a simple list comprehension to do it
df = pd.DataFrame({'X':['xx', 'xx', 'xx', 'xy', 'xy', 'xy'],
                   'Y':['high', 'slow', 'fat']*2,
                   'Z':[10, 20, 30, 15, 10, 30]})

dicc = {'xx': -4.5, 'xy':-10.21}

df['D'] = [dicc[i] for i in df['X']]

e
Extra:If your df comes from a grouby and the code says an error because it can't find column 'X', it's because 'X' is now an index column. To fix that just say df = df.reset_index() to get your DF to look like the one in this answer.

A: You can use map, but first is necessary convert level of MultiIndex to_series:
dicc = {'xx': -4.50, 'xy': -10.21}

L = [df.index.get_level_values('X').to_series().map(dicc),
     df.index.get_level_values('Y')]

df.index = pd.MultiIndex.from_arrays(L, names = df.index.names)
#alternative solution
#df = df.set_index(pd.MultiIndex.from_arrays(L, names = df.index.names))

print (df)
              Z
X      Y
-4.50  high  10
       slow  20
       fat   30
-10.21 high  15
       slow  10
       fast  30


text:
Q: how can I integrate sementic ui in rails 6 application I'm new at Ruby on Rails. I couldn't find any installation procedure on the internet related to how to integrate sementic Ui in rails 6 application

A: *

*Add gem 'semantic-ui-sass' to your Gemfile

*Import Semantic in your SCSS file (e.g. application.scss) @import "semantic-ui";
You can also include modules @import "semantic-ui/collections/menu";


text:
Q: Return elements from list that satisfy condition of another list to then compare with a fourth list python I have two lists:
listA = [230, 232, 230, 229, 237, 212, 245, 233, 220, 230]
listB = [232, 231, 234, 230, 234, 228, 244, 236, 227, 229]

How do I compare the lists and only return the points at which listA was greater than listB into a third list listC while preserving the indices so that the result looks like:
listC = [   , 232,    ,    , 237,    , 245,    ,    , 230]

After all that, there is a fourth list listD:
listD = [1,2,3,4,5,6,7,8,9,10]

and I am trying to collate it with listC so that I end up with list C & D matching in terms of indices:
Final Result:
listD = [ 2 , 5 , 7 , 10]
listC = [233,237,245,230]

I was looking into list comprehension as I was told it would help, but I'm not really sure how to apply what I've read.

A: This is a perfect use-case for itertools.compress:
>>> from itertools import compress, starmap
>>> from operator import gt

Get a new list of booleans where True means item in listA was greater than corresponding item in listB.
>>> bools = list(starmap(gt, zip(listA, listB)))
>>> bools
[False, True, False, False, True, False, True, False, False, True]

Now we filter listA and listD based on bools using compress.
>>> list(compress(listA, bools))
[232, 237, 245, 230]
>>> list(compress(listD, bools))
[2, 5, 7, 10]

A: I'd not use a list comprehension here; you are building two lists, not one, and that's just easier with a regular for loop:
listC = []
listD_filtered = []
for a, b, d in zip(listA, listB, listD):
    if a > b:
        listC.append(a)
        listD_filtered.append(d)

Using zip() you can iterate over lists in parallel, removing the need to track indices altogether.
You can still use a comprehension here, but then you'd build a sequence with (a, d) values, and then use zip() again to split that result into two separate lists:
listC, listD = zip(*((a, d) for a, b, d in zip(listA, listB, listD) if a > b))

This however becomes harder to follow and explain, and you actually have tuples, not lists, in that case (depending on your usecase you'd have to convert those to lists again).
Demo:
>>> listA = [230, 232, 230, 229, 237, 212, 245, 233, 220, 230]
>>> listB = [232, 231, 234, 230, 234, 228, 244, 236, 227, 229]
>>> listD = [1,2,3,4,5,6,7,8,9,10]
>>> listC = []
>>> listD_filtered = []
>>> for a, b, d in zip(listA, listB, listD):
...     if a > b:
...         listC.append(a)
...         listD_filtered.append(d)
...
>>> listC
[232, 237, 245, 230]
>>> listD_filtered
[2, 5, 7, 10]
>>>
>>> listC, listD = zip(*((a, d) for a, b, d in zip(listA, listB, listD) if a > b))
>>> listC
(232, 237, 245, 230)
>>> listD
(2, 5, 7, 10)

A: Get the result by list comprehension:
In [6]: listC = [i for i, j in zip(listA, listB) if i>j]
In [7]: listC
Out[7]: [232, 237, 245, 230]

In [9]: listD = [i for i, (a, b) in enumerate(zip(listA, listB), 1) if a>b]
In [10]: listD
Out[10]: [2, 5, 7, 10]


text:
Q: Редактирование свойств выбранного объекта В программе есть возможность редактировать свойства выбранного объекта.
Это реализовано через свойство SelectedObject во ViewModel.
Проблема в следующем. Если я выбираю объект, редактирую его свойства и кликаю в пределах текущего TabItem, то свойство обновляется. Но если же я редактирую свойство и, не убирая курсор с текстового поля, переключаюсь на другую вкладку, то изменения в свойстве не сохраняются.
Установка UpdateSourceTrigger=PropertyChanged в моем случае не подходит. Нужен именно LostFocus.
Как это пофиксить?

Набросал пример, который отражает проблему.

Code-behind:
public class PersonVm : BaseVm
{
    private string _name;
    private string _lastname;

    public string Name
    {
        get => _name;
        set
        {
            _name = value;
            OnPropertyChanged();
        }
    }

    public string Lastname
    {
        get => _lastname;
        set
        {
            _lastname = value;
            OnPropertyChanged();
        }
    }
}

public class MainVm : BaseVm
{
    private PersonVm _selectedPerson;

    public MainVm()
    {
        Class1.Add(new PersonVm { Name = "Алексей", Lastname = "Алексеев" });
        Class1.Add(new PersonVm { Name = "Иван", Lastname = "Иванов" });

        Class2.Add(new PersonVm { Name = "Петр ", Lastname = "Петров" });
        Class2.Add(new PersonVm { Name = "Николай", Lastname = "Николаев" });
    }
    public ObservableCollection<PersonVm> Class1 { get; } = new ObservableCollection<PersonVm>();
    public ObservableCollection<PersonVm> Class2 { get; } = new ObservableCollection<PersonVm>();

    public PersonVm SelectedPerson
    {
        get => _selectedPerson;
        set
        {
            _selectedPerson = value;
            OnPropertyChanged();
        }
    }
}

XAML:
<Window.Resources>
    <DataTemplate x:Key="DataTemplate">
        <ListBox ItemsSource="{Binding}"
                 SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.SelectedPerson}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}" />
                        <TextBlock Text="{Binding Lastname}"
                                   Margin="5,0,0,0"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
            </ListBox>
    </DataTemplate>
</Window.Resources>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*"/>
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <TabControl>
        <TabItem Header="Class1"
                 Content="{Binding Class1}"
                 ContentTemplate="{StaticResource DataTemplate}" />

        <TabItem Header="Class2"
                 Content="{Binding Class2}"
                 ContentTemplate="{StaticResource DataTemplate}" />
    </TabControl>

    <StackPanel Grid.Column="1">
        <TextBlock Text="Имя" />
        <TextBox Text="{Binding SelectedPerson.Name}" />
        <TextBlock Text="Фамилия" />
        <TextBox Text="{Binding SelectedPerson.Lastname}" />
    </StackPanel>
</Grid>

A: На данный момент получается, что при возникновении события LostFocus привязки уже нет, поэтому она не срабатывает. Из всех PreviewXXX-событий у TextBox есть только PreviewLostKeyboardFocus, если подписаться на него и посмотреть отладчиком что лежит в Text, то мы увидим, что в нем привязка пока еще есть, значит это событие нам подойдет.
Действительно, давайте попробуем в подписчике принудительно обновить привязку, добавьте в обработчик такой код:
(sender as TextBox).GetBindingExpression(TextBox.TextProperty).UpdateSource();

и вы увидите, что все работает как вы и хотели.
Что можно с этим сделать? Можно, например, добавить обработчик события для всех нужных TextBox, или реализовать наследника TextBox с таким поведением, ну или, наконец, сделать Attached Behavior.
Первый вариант, я считаю, плох, т.к. нужно будет добавлять обработчики такие во всех окнах/контролах где нам нужен TextBox с таким поведением, ну и если вдруг для какого-то из TextBox нам понадобится еще один обработчик этого события - его придется вешать из кода.
Поэтому я покажу последние два варианта.
Наследник TextBox, все предельно просто, я создал такой класс:
public class MyTextBox : TextBox
{
    protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
    {
        base.OnPreviewLostKeyboardFocus(e);
        GetBindingExpression(TextProperty).UpdateSource();
    }
}

Всё. Это уже работает, достаточно вместо стандартного TextBox использовать local:MyTextBox. Но у этого подхода есть минус - если вы стилизуете стандартные TextBox, то эти кастомные штатно не будут подхватывать стили и их придется стилизовать отдельно, хотя, по сути, у нас тот же самый TextBox.
Поэтому наиболее оптимальным решением видится сделать прикрепляемое поведение.
Подключите к проекту сборку System.Windows.Interactivity и создайте класс:
class TextBoxLostFocusUpdateBindingBehavior : Behavior<TextBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.PreviewLostKeyboardFocus += OnPreviewLostKeyboardFocus;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.PreviewLostKeyboardFocus -= OnPreviewLostKeyboardFocus;
    }

    private void OnPreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        AssociatedObject.GetBindingExpression(TextBox.TextProperty).UpdateSource();
    }
}

Теперь в XAML добавьте пространство имен: xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
И у нужных TextBox укажите это поведение:
<TextBox Text="{Binding SelectedPerson.Lastname}">
    <i:Interaction.Behaviors>
        <local:TextBoxLostFocusUpdateBindingBehavior/>
    </i:Interaction.Behaviors>
</TextBox>

PS.: Что примечательно, технология Binding в WPF достаточно интеллектуальна для того, чтобы не обновлять одну и ту же привязку, если с момента прошлого обновления изменений не было. Поэтому нам не нужно предпринимать никаких дополнительных действий чтобы отключить обновление привязки по LostFocus, она просто не будет никогда там обновляться, обновление теперь будет происходить всегда по PreviewLostKeyboardFocus


text:
Q: Validate JSON Schema properties with at least one containing specific value I would like to know if I can define a JSON schema (draft 4) that requires at least one of many properties to have a specific value.
To illustrate, here is an example JSON I expect to FAIL the validation:
{
    "daysOfWeek": {
        "mon": false,
        "tue": false,
        "wed": false,
        "thu": false,
        "fri": false,
        "sat": false,
        "sun": false
    }
}

But if any (one or more) of the above properties is set to true, only then I'd expect it to PASS the validation.
So what would the Schema be?
{
    "daysOfWeek": {
        "type": "object",
        "properties": {
            "mon": { "type": "boolean" },
            "tue": { "type": "boolean" },
            "wed": { "type": "boolean" },
            "thu": { "type": "boolean" },
            "fri": { "type": "boolean" },
            "sat": { "type": "boolean" },
            "sun": { "type": "boolean" }
        },
        "anyOf": [{
            // ?
        }]
    }
}

Many thanks in advance!

A: @Jason's answer is good (and readable) for the case you have here.  In the general case (where you might have arbitrary numbers of properties), there's a more concise way (but less readable):
You could rephrase your requirement as "The properties are not all allowed to be false", in which case a schema could be:
{
    "type": "object",
    "properties": {...},
    "not": {
        "additionalProperties": {"enum": [false]}
    }
}

The additionalProperties is in a sub-schema, so it's not connected to the properties value at the root level.  It therefore applies to all the properties.
The subschema inside not will only pass if all properties are false - therefore the outer schema will only pass if not all the properties are false.

A: You can use the enum keyword to specify that a property has a specific value.  You can combine that trick with anyOf to get the desired validation behavior.
{
  "type": "object",
  "properties": {
    "daysOfWeek": {
      "type": "object",
      "properties": {
        "mon": { "type": "boolean" },
        "tue": { "type": "boolean" },
        "wed": { "type": "boolean" },
        "thu": { "type": "boolean" },
        "fri": { "type": "boolean" },
        "sat": { "type": "boolean" },
        "sun": { "type": "boolean" }
      },
      "anyOf": [
        {
          "properties": {
            "mon": { "enum": [true] }
          }
        },
        {
          "properties": {
            "tue": { "enum": [true] }
          }
        },
        {
          "properties": {
            "wed": { "enum": [true] }
          }
        },
        {
          "properties": {
            "thu": { "enum": [true] }
          }
        },
        {
          "properties": {
            "fri": { "enum": [true] }
          }
        },
        {
          "properties": {
            "sat": { "enum": [true] }
          }
        },
        {
          "properties": {
            "sun": { "enum": [true] }
          }
        }
      ]
    }
  }
}


text:
Q: Python_grouping multidimensional list I have an example multidimensional list:
    example_list=[
        ["a","b","c", 2,4,5,7],
        ["e","f","g",0,0,1,5],
        ["e","f","g", 1,4,5,7],
        ["a","b","c", 3,2,5,7]
    ]

How is it possible to put them in groups like this:
out_list=[
         [["a","b","c", 2,4,5,7],
           ["a","b","c",3,2,5,7]
         ],
         [["e","f","g", 0,0,1,5],
          ["e","f","g", 1,4,5,7]
         ]
 ]

I have tried this:
example_list=[["a","b","c", 2,4,5,7],["e","f","g", 0,0,1,5],["e","f","g",1,4,5,7],["a","b","c", 3,2,5,7]]
unique=[]
index=0
for i in range(len(example_list)):
    newlist=[]
    if example_list[i][:3]==example_list[index][:3]:
        newlist.append(example_list[i])
    index=index+1
    unique.append(newlist)
print unique

My results is this:
[[['a', 'b', 'c', 2, 4, 5, 7]], [['e', 'f', 'g',0, 0, 1, 5]], [['e', 'f', 'g', 1, 4, 5, 7]], [['a', 'b', 'c', 3, 2, 5,7]]]
I could not figure it out.

A: If the grouping is decided by the first three elements in each list following code will do what you're asking for:
from collections import defaultdict

example_list=[["a","b","c", 2,4,5,7],["e","f","g",0,0,1,5],["e","f","g", 1,4,5,7],["a","b","c", 3,2,5,7]]
d = defaultdict(list)
for l in example_list:
    d[tuple(l[:3])].append(l)

print d.values() # [[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7]], ...]

This will use defaultdict to generate a dictionary where keys are the first three elements and values are list of lists which start with those elements.

A: First sort the list simply using sorted(), providing a lambda function as key.
>>> a = sorted(example_list, key=lambda x:x[:3])
[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7], ['e', 'f', 'g', 0, 0, 1, 5], ['e', 'f', 'g', 1, 4, 5, 7]]

And then use itertools.groupby() on the sorted list:
>>> [list(v) for k, v in groupby(a, lambda x:x[:3])]
[
    [['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7]],
    [['e', 'f', 'g', 0, 0, 1, 5], ['e', 'f', 'g', 1, 4, 5, 7]]
]


text:
Q: VBScript - Read environment variable in if statement What changes must I make for the if statement in my code extract below to work as expected?
dim warn, txtfilelocate, txtcontent, file, txtfile, content

call START
sub START
   do while len(txtfilelocate) = 0
   txtfilelocate = inputbox ("Please enter the full path of the text file containing your email content", "CDO Email Sender")
      if isempty(txtfilelocate) then
      wscript.quit()
      end if
   loop
end sub

txtcontent = DQ(txtfilelocate)
wscript.echo txtcontent

set file = createobject("scripting.filesystemobject")

   if file.fileexists(txtcontent) then
      set txtfile = file.opentextfile(txtcontent, 1)
      content = txtfile.readall
      wscript.echo content
      txtfile.close
      call HELLO
   else
      warn = msgbox(txtcontent & " was not found", 0, "CDO Email Sender")
      call START
   end if

sub HELLO
   wscript.echo "hello"
end sub

function DQ(str)
   DQ = chr(34) & str & chr(34)
end function

I suspect it has something to do with expanding environment variables, but as a novice I would appreciate clarification on what I'm doing wrong, and what I should be doing for this to work. Thanks.

A: Your txtcontent in:
if file.fileexists(txtcontent) then

contains a quoted file spec. Such quoting is good/necessary when you use .Run or .Exec to shell out, because the shell's parser uses blanks/spaces as separators. The FileSystemObject's method 'know' if an argument is meant as a path/file spec and are not fooled by blanks/spaces, but take spurious quotes literally. So pass txtcontent unquoted to .FileExists.
Evidence:
>> WScript.Echo goFS.FileExists(WScript.ScriptFullName)
>>
-1
>> WScript.Echo goFS.FileExists(qq(WScript.ScriptFullName))
>>
0
>>

Update wrt comment:
Your script is still a mess. In addition to mixing top level code and Subs/Functions, you simulate a logical loop (repeat until the dumb user has entered a valid file spec) by calling a Sub from different contexts. Put
a line like
   WScript.Echo "START called. txtfilelocate is", DQ(txtfilelocate)

at the top of Sub START, and you'll see that START is entered, but not the loop, because txtfilelocate contains the garbage the user entered before.


text:
Q: Why is the !important required? I believe the specificity is right, and I checked the compiled CSS, but I have to include the !important for this to work. I'm getting kind of angry because of this to be frank. Any help will be greatly appreciated, and feel free to help me clean up some of the other code too, I know it's not perfect :)
// Content
.section {
  padding: clamp(50px, 5vh, 200px) 0;

  .section__content {
    width: clamp(300px, 60vw, 100vw);
    margin: 0 auto;

    h2 {
      font-family: $ff-header;
      font-size: clamp(24px, 1.1vw + 1rem, 50px);
      margin-bottom: 1.3rem;
      line-height: 1;
    }

    p {
      font-family: $ff-content;
      font-size: 1rem;
      line-height: 120%;
    }

    &.section--hasImage {
      display: flex;
      gap: 2rem;
      justify-content: space-between;
      align-items: center;

      .col {
        width: 45%;
      }
    }
  }
}

// Breakpoints
@media (max-width: 50em) {
  .hero {
    justify-content: center;

    .hero__content {
      text-align: center;
      margin: 0;

      h1 {
        font-size: clamp(30px, 10vw + 1rem, 2000px);
      }

      p {
        font-size: clamp(24px, 1vw + 1rem, 1800px);
      }
    }
  }

  section > .section__content {
    width: clamp(10px, 85vw, 85vw);

    &.section--hasImage {
      display: block !important;

      .col {
        width: 100% !important;

        &:last-of-type {
          margin-top: 2rem;
        }
      }
    }
  }
}


text:
Q: Cannot change the Terminal Shell in Mac OSX Catalina I'm using mac Catalina and trying to change the terminal shell, but can't do it.
I did terminal => preferences => select command and type " /bin/zsh " => quit the terminal and re-open it => typed echo $SHELL on the terminal
I can see my username with -zsh on top of the terminal but after I run the command I can only see /bin/bash, not /bin/zsh.
Can anyone tell me how to fix this issue? I've been trying about ten times but still having the same problem...

A: In your terminal, type this:
$> chsh -s /bin/zsh

Close your terminal and open it again. You should be in zsh.
If you want to know what shell you are running, type:
$> echo $0
-zsh


text:
Q: Java Thread Serialization , why serialized Thread Object can be started A thread in java can't be restarted in Java, so I implemented a java Thread , and then tried to restart the thread after getting the serialized object of Thread.
import java.io.Serializable;

public class ThreadSerialization extends Thread implements Serializable {

    int iCheck = 10;
    @Override
    public void run() {
        System.out.println("STARTING");
        for(int i=0;i<10;i++){
            iCheck+=i;
        }
    }

}

and Serializing algo-
public class CallingThreadSerializable {

    public static void main(String[] args) {
        ThreadSerialization ser = new ThreadSerialization();
        ser.start();
        FileOutputStream fos = null;
        ObjectOutputStream out = null;
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fos = new FileOutputStream("thread.ser");
            out = new ObjectOutputStream(fos);
            out.writeObject(ser);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        try {
            fis = new FileInputStream("thread.ser");
            ois = new ObjectInputStream(fis);
            ThreadSerialization ser1 = (ThreadSerialization) ois.readObject();
            System.out.println("---> " + ser1.iCheck);
            ser1.start();
            System.out.println("---> " + ser1.iCheck);
            ois.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

OUTPUT-
STARTING
---> 55
---> 55
STARTING

Why the ser1 object is starting again ?

A: If you deserialize(?) an Object then you are essentially creating a new instance of that class with the same properties as the original Object.
It is not the same Object.
As well, since Thread itself doesn't implement Serializable, startedness is effectively part of the transient state in any Serializable subclass (as is interruptedness), because serialization doesn't restore fields inherited from a non-Serializable superclass. Any class that extends Thread implements Serializable, assuming there's a good reason to do so at all, should probably have its own fields to track startedness and interruptedness, and call Thread.start() and Thread.interrupt() in readObject() or readResolve() to restore those elements of its state.

A: There are two points:
First: Thread is NOT Serializable and hence the following excerpt from the serializable JavaDoc applies:

To allow subtypes of non-serializable classes to be serialized, the
    subtype may assume responsibility for saving and restoring the
    state of the supertype's public, protected, and (if accessible)
    package fields.

Which mean, your class ThreadSerialization would have the responsibility to store and restore the state of Thread. But you cannot do that due to many private fields in Thread. Therefore all private field in Thread are default initialized. Now look at implementation of Thread.start() :
    //...
    if (threadStatus != 0)
        throw new IllegalThreadStateException();
    // ...
    start0();
    //...

Because threadStatus has not been stored/restored properly you can start a second time.
Second: Don't confuse the actual operating system thread and the "manager" object java.lang.Thread - they are only loosely coupled. In your example you only serialize the manager but not the OS-thread which has no representation in Java. After deserialization you have a second manager instance which no attached OS-thread. So telling the manager to start will succeed.

A: During serialization the Objects instance variables are sucked out, and converted to bytes and written on a file (typically a file with .ser extension) then, during deserialization the bytes are read from the file, and then converted to instance variables, and are used to create new object identical to the one which was serialized. Their constructor are never called, so it reaches the state when it was serialized not when it was created.
You can check the hashcode of the object before serialization, and then after deserialization, they will never be same, as hashcode is provided by JVM depending on where the object is create on the heap, and its obvious the 2 objects cant be created on the heap at the same address...so they are diff objects but with identical state.

A: To make an object serializable, the respective class should explicitly implement Serializable interface. However certain system classes defined by java like "Thread", "OutputStream", "Socket" are not serializable. Why so? Lets take a step back - now what is the use of serializing the Thread running in System1 JVM using System1 memory and then deserializing it in System2 and trying to run in System2 JVM. Makes sense right! Hence these classes are not serializable.
Coming to your program.
ThreadSerialization ser1 = (ThreadSerialization) ois.readObject();// Thread started in System2.
ser1.start();// Thread once again started here in System2.

It is very bad to have a class which implements serializable and extends Thread or implemeting Runnable.
In Summary
Don't use thread in sealization or stream and socket process.

A: regardless of any other responses in this "thread" :)
Thread class cannot be serialized due to call to Native Methods!!!
period!
EDIT:
if you are working within a single process, you can declare a global variable.
If you create multiple threads, you can create a class that will contain a list of active threads.

*

*This class contains the hash map.

*Hash map contains a key (id) as String and value as weak reference to thread.

*Threads are identified by id

*You do not have to worry about GC If your thread finishes or finish it yourself class method returns null.

import java.lang.ref.WeakReference;
import java.util.HashMap;

public class ThreadsMap {

    private HashMap<String, WeakReference<Thread>> _threadHashMap;

    public ThreadsMap() {
        _threadHashMap = new HashMap<>();
    }

    public void add(String id, Thread thread) {
        WeakReference<Thread> threadWeakReference = new WeakReference<>(thread);
        _threadHashMap.put(id, threadWeakReference);
    }

    public Thread get(String id) {
        WeakReference<Thread> threadWeakReference = _threadHashMap.get(id);
        return threadWeakReference.get();
    }

}


text:
Q: Tethered VPN on Macbook fails to connect, but standard VPN over WiFi works I have a MacBook using the Cisco client and it works fine except when I use the special Mac/iPad ability to tether over the iPad data connection.
For those that are unfamiliar with this, the Mac and iPad can tether over Bluetooth to leverage the iPad's internet connection.
I'm not the network administrator of the Cisco VPN target, but I want to give them the most accurate/relevant information to fix this.
How do I troubleshoot/collect information to make our network admin's life easier?