text:
Q: Why is Invariance, Covariance and Contravariance necessary in typed languages Ok not really sure if I'm right.
I only recently learned that I needed to have contravariant interface to be able to pass that interface as a parameter in C# and this feature was only added in .NET 4.0.
So obviously there is some reason you can't do this Covariant or Invariant interfaces and it probably has something to do with passing in, getting out the generic class.
I'm not really sure what the limitation here is, and know that I've seen where Contravariant interface can be used where the others can't where can I use Covariant (when is that neccesary?).
This is all out of curiosity (I'm very interested in programming concepts surrounding some languages). I would love to see (link would be fine) some examples of why it is necessary to use these features, what would break if you would allow covariant/invariant into contravariant scene and vice versa and where each one shines.

A:
I only recently learned that I needed to have contravariant interface to be able to pass that interface as a parameter in C# and this feature was only added in .NET 4.0.

.NET 4 added co/contra-variance for generics. The variance concept though exists in any language with subtyping.
When doing type checking, a parameter type is acceptable if it is the same type as what is expected or more specific. Or simply, the types are covariant. This is straight-forward. If your method is working on Person then passing in a Student or a Teacher is irrelevant.
The gotcha for this feature is generic parameters. In some cases, it is safe to use generic types covariantly: eg Action<Base> can be assigned to a variable of type Action<Derived>; Who cares if a Derived is passed in, Action<Base> can work with it.
Likewise there are cases where generic types can be used contravariantly: Func<Derived> can be assigned to a variable of type Func<Base>. Who cares if a Derived is always returned, anything that calls Func<Base> can deal with the result.
And there are cases where the generic types cannot be used co- or contra- variantly. List<T> is a good example. You can't assign List<Derived> to a List<Base> (or vice versa) because then some functions would not be of the correct type.
The basic idea is that the type system is correct. Allowing user specified generic variance allows the user to tell the type system where it is possible for generic types to be co/contra-variant. The concepts though exist in any type system with sub-typing regardless of explicit notation.

A: This is mostly a rewording of this excellent blog by Eric Lippert:
C# sub types have always been assignment compatible with their base types e.g. given that Teacher is derived from Person Person p = new Teacher(); is valid i.e. there is a relation isAssignable(x,y) which is true IFF x= y is allowed.
before C# 4 generic collections of sub types were not assignment compatible with generic collections of base types (i.e. IEnumerable<Teacher> does not derive from IEnumerable<Person> so you could not assign IEnumerable<Teacher> to a IEnumerable<Person>) i.e. isAssignable(IEnumerable<x>,IEnumerable<y>) was always false regardless of the value of isAssignable(x,y)
C# 4 adds variance for generic types, this allows a generic type to be *variant over a projection from T -> A<T>. which means that for covariant parameters, relations which hold for T,U hold for A<T>,A<U>, and for contra-variant the relation is reversed. i.e. for the relationship isAssignable(x,y) a types that are covariant over the projection like IEnumerable<>s has the same relations as their generic parameters so isAssignable(x,y) == isAssignable(IEnumerable<x>,IEnumerable<y>)

A: The different forms of variance are only needed because you have two independent axes of polymorphism going on:

*

*Subtype polymorphism: A function that is defined to operate on values of type Base can also operate on values of type Derived, if Derived is a subtype of Base.  Within the function, only the operations exposed by type Base may be used (unless reflection or run-time type inspection are used).

*Parametric polymorphism: A generic function that is parameterized over a type T (e.g. void Foo<T>()) can operate on values of type A, B, etc., if those types match the where clause restrictions (if any) on the type of T.  Within the function, only operations which are valid for the entire bounds of the type parameter can be used.  (So if there are no bounds on T, then only operations that are guaranteed to be valid for all objects may be used.)
Each axis makes sense on its own.  But you run into problems when you try to act polymorphically in both axes at once.
For example, given classes Base, Derived, and SomethingElse:

*

*A method void Foo(Base b) can accept a value of type Derived as a parameter, by subtype polymorphism.

*The method void Add(T item) on the type List<T> can accept values of any of Base or SomethingElse, etc, provided the type has been instantiated as List<Base>, List<SomethingElse>, etc.

*The method void Add(T item) on the type List<T>, when the type has been instantiated as List<Base>, is treated as if it were declared as void Add(Base item), and thus can accept a value of type Base.

*Additionally, the method void Add(T item) on the type List<T>, when the type has been instantiated as List<Base>, can accept a value of type Derived, due to the combination of both parametric polymorphism (the parameterized type of Base) and subtype polymorphism (the is-a relationship between Derived and Base).

*However, given a function void Foo(List<Base> list), and a value of type List<Derived>, the method void Add(T item) on the type List<Derived> is treated as if it were declared as void Add(Derived item), which is incompatible with the method void Add(T item) on the type List<Base> (which is treated as if were declared as void Add(Base item)).
This is because the value which is required for the formal parameter list of void Foo(List<Base> list) must be an object that has an Add() method that is able to accept values of type Base, but the value which is being supplied (a value of type List<Derived>) does not accept values of type Base in its Add() method!
Now, if you are only dealing with one axis of polymorphism at a time, then this isn't a problem:

*

*If all you have is subtype polymorphism, then we're just like the type system of C# 1.0: there are no generics, and thus no way for problems of covariance and contravariance to come up.  (Actually, the problems can come up, it's just that they appear at run time, not compile time.  For example, see ArrayTypeMismatchException.)

*Conversely, if all you have is parametric polymorphism (a.k.a. generics), then it is never allowed to pass a type Derived to a function that expects a value of type Base, since functions cannot act polymorphically with respect to a subtype relationship.
(While this restriction seems hopelessly restrictive to someone coming from an OO background, it's actually quite common in some functional programming languages.  It does change how you go about structuring your code, however.)
Now, the problems of covariance and contravariance can occur just as easily in a dynamically typed language as in a statically typed one.  The only difference is that dynamic language code is necessarily more resilient to unexpected types.
For example, in a Python program, you might have a class that represents a list of strings, and an add(item) method that adds an item to the list.  However, the type system does not enforce the invariant of the class -- any caller can pass a value of any type they like to the add() method.  Therefore, the code must either defend against illegal values somehow (e.g. by doing a check in the add() method to ensure that a non-string doesn't get added), or cope gracefully with finding a non-string in its internal storage.
These kinds of problems are exactly what covariance and contravariance are about: cases where code can be "surprised" by the type of values.  In a statically type-checked language, the type checker is responsible for proving that code can never be surprised by the type of a value: if you have a local variable that was declared with type string, it will never contain a value of type double, no matter what.  If, due to the way you're using different forms of polymorphism together, the type checker can no longer prove that, it will reject your program with a type error.
Basically, this is the trade-off of static versus dynamic type checking: a static type checker can prove that certain kinds of undesirable behavior are not present in your program (in this case, "surprising" types of values), but only at the cost of rejecting some interesting programs.  That is, a type checker is by necessity conservative.
In order to make type checkers more flexible (and thus allow more interesting programs to be checked by them), modern languages like C# have introduced new language constructs (like the in and out keywords to identify covariant and contravariant type parameters), which allow more fine-grained control over the type checker's proof.  Generally, this is considered a good thing: it allows us to have the advantage of a type checker proving useful things about our program, while still allowing the maximum number of interesting programs through.

A: The need for covariance and contravariance can be best understood with an example.
Let's say you have a function that accepts a parameter of type List<Base>, where Base is a base class that other classes inherit from.  You would intuitively think that it would be just fine to pass a List<Derived1> to this routine, if Derived1 inherits from Base, and you would be mostly right.  It would be fine if the function treated the list as read-only, but otherwise you'd have a problem.
Since all the function sees is a List<Base>, it could theoretically call the Add method and add a Derived2 instance to the list, which is a different, incompatible class derived from Base.  And then the function returns, and you've got a Derived2 in your list of Derived1 objects, and you've violated type-safety.  Then you try to iterate over the list and call some method on each object that doesn't exist on Derived2, and the whole thing blows up in your face.
Covariance and contravariance requirements exist to prevent this sort of scenario by enforcing extra constraints on the parameters.  For example, in this example, the function could be made type-safe by ensuring that no methods that add new objects to the list can be called.  If the compiler can use variance requirements to prove that, then it's safe to create a function like this.  Otherwise, it isn't.


text:
Q: App Link is not working in mobile browser using intent I am trying to open app(digital wallet app) directly from web browser(if it is a mobile).
I already referred the following links
Make a link in the Android browser start up my app?
Launch custom android application from android browser
For your information i am working on integrating payment gateway(digital wallet) in my website which has a payment type like QR code(scan and pay) and another one is deep app link, so what i am implementing is, if website then payment type will be QR code(already implemented) but if it is mobile it will be deep app link(provided by digital wallet payment gateway).
Here is the intent filter available in manifest.xml file, but i can't edit that(as that app is from third party).

My intention is If the user visit from mobile browser and make a payment in my website? then i want to redirect to the digital wallet app using deep link(provided by the payment gateway) to complete the payment.
This is the deep link provided in halalah digital wallet payment gateway
https://halalah.sa/wp-content/uploads/2018/12/HalalaH-Deep-Linking-Guide.pdf

halalahewallet://transaction?terminal=HG00001&amount=0.02&referenceNo=london50&billNo=london123&memo=memo

so for that i tried the following code as a link
Pay using App

while i test this above code that parameter value is not take it into action(hence app is not launch to perform payment, instead it goes to their play store page), though i installed and configured that app in my side.
I checked using deep link tester app (https://play.google.com/store/apps/details?id=com.manoj.dlt&hl=en) with above deep link uri - it launch website without any issue, i guess the problem is happen from web browser or from my above tried intent code? i want to launch that app from browser directly with required parameters to perform payment.

A: Try to add target="_blank" in the a tag
pay throw Halalah App

and for more information about Halalah integration check this link:
https://github.com/halalah/HalalaH-Integration-Guides

redpajama_set_name: RedPajamaStackExchange


text:
Q: Forming a new hash structure by merging two hashes I have two hashes of the same format. My target is to create a new hash by taking values from the two hashes, changing the keys inside first. I have explained in My Goal down below what I would like to have as an output. I couldnot go forward from here, please help.
What I have
h1 = {
 "x"=> {
  "imp"=> {"a"=>1, "b"=>2},
  "ctr"=> {"a"=>3, "b"=>4}
  },
 "y"=> {
  "imp"=> {"c"=>1, "d"=>2},
  "ctr"=> {"c"=>3, "d"=>4}
  },
 "z"=> {
  "imp"=> {"e"=>10, "f"=>20, "g"=> 111},
  "ctr"=> {"e"=>30, "f"=>40, "g"=> 222}
   }
}

h2 = {
 "x"=> {
  "imp"=>{"a"=>11, "b"=>22},
  "ctr"=>{"a"=>33, "b"=>44}
 },
 "y"=> {
  "imp"=> {"c"=>11, "d"=>22},
  "ctr"=>{"c"=>33, "d"=>44}
 },
 "z"=> {
  "imp"=>{"e"=>11, "f"=>22, "g"=> 333},
  "ctr"=>{"e"=>55, "f"=>66, "g"=> 444}
 }
}

MY GOAL
{segment=>"x=a", "imp"=>1, "ctr"=>3, "imp_of_h2"=>11, "ctr_of_h2"=>33},
{segment=>"x=b", "imp"=>2, "ctr"=>4, "imp_of_h2"=>22, "ctr_of_h2"=>44},
{segment=>"y=c", "imp"=>1, "ctr"=>3, "imp_of_h2"=>11, "ctr_of_h2"=>33},
{segment=>"y=d", "imp"=>2, "ctr"=>4, "imp_of_h2"=>22, "ctr_of_h2"=>44},
{segment=>"z=e", "imp"=>10, "ctr"=>4, "imp_of_h2"=>22, "ctr_of_h2"=>55},
{segment=>"z=f", "imp"=>20, "ctr"=>40, "imp_of_h2"=>22, "ctr_of_h2"=>66},
{segment=>"z=g", "imp"=>111, "ctr"=>222, "imp_of_h2"=>333, "ctr_of_h2"=>444}

What I tried so far.. But it is only functional for one hash only. I needed to achieve this for the two hashes.
data_final = []
h1.flat_map do |segment, attrs|
  segments = attrs.values.flat_map(&:keys).uniq
  # create a segment entry for each unique letter
  segments.map do |seg|
    row = {"segment" => "#{segment}=#{seg}"}
    row.merge! Hash[attrs.keys.map {|key| [key,attrs[key][seg]]}]
    data_final << row
  end
end

A: Pragmatically speaking, is this what you wanted? (Don't forget to install y_support gem for Array#>> method.)
require 'y_support/core_ext' # gem install y_support if necessary

labels = "imp", "ctr"
h2_suffix = "_of_h2"

result = [ [?x, ?a], [?x, ?b], [?y, ?c], [?y, ?d], [?z, ?e], [?z, ?f], [?z, ?g] ].map do
  |coordinate, letter|
  [ "segment", *labels, *labels.map { |lbl| lbl + h2_suffix } ] >>
    [ "#{coordinate}=#{letter}",
      *labels.map { |label| h1[coordinate][label][letter] },
      *labels.map { |label| h2[coordinate][label][letter] } ]
end


text:
Q: How do I wipe a harddrive with Ubuntu on it? I want to completely wipe a harddrive with Ubuntu on it, so I can put Windows back on it. How do I do that? I don't want to dual boot either, I just want to wipe the drive and put Windows on it. How do I do this? Thanks!
-Trace

A: You can do this directly from Windows installer, just select "Advanced" partitioning, remove all partitions of your drive, create a new one (Windows will create addtitional partitions - recovery and ESP) and proceed as in normal installation.
Alternatively you could use Live CD/Live USB of some Linux distribution, e.g. drive you installed Ubuntu from. Click "Try Ubuntu without installing". There are variety of tools you can use at this point. For GUI operation I'd recommend GParted, you can install it using apt-get install gparted like you'd do on regular Ubuntu installation. Operation is preety straightforward, but in case of problems you can refer to manual.
Please note that this will remove all your data from the drive you kept Ubuntu on!


text:
Q: Compiling Code on Linux Server Seems to Run Differently I couldn't think of a good way to name this question, as the description of the issue is pretty lengthy.  Basically, the issue I'm having is, code that I wrote in Xcode on my mac isn't running the same after I upload to a linux server for my school.  I've never had this issue before.  Its not a syntax issue, which is something that I might run into (IE maybe I dont need to include a certain header file on Xcode that needs to be included to run on the linux server, so I get an error when I try to compile there), but its a logic error.  One specific if-else statement is evaluating entirely wrong.  It works correctly in Xcode, but with the same .cc file uploaded to the linux server and compiled with a makefile, it has a totally different result, using the same exact input that was used in Xcode.  I even open the .cc file with emacs after uploading to make sure none of the code has been altered from a botched upload, but nothing has changed at all.  This is very strange.  I've never ran into this sort of issue before.  I'd like to provide the code, but it might be entirely too long, so I need to break it down into a smaller example.  For now, I'd like to know if this is something anyone else has ever ran into.  The assignment deals with graph theory.  I'm typing in 'A' and 'B' to draw edges between two vertices.  You can see it works from the Xcode build, but not from the Linux build.

A: I found the error.  In Xcode, for some reason, I was inputting a character into a string like as 'cin >> string[0]' which worked fine, but this was causing the issue when compiling on the linux servers.  It wouldn't accept the array style input and I had to use 'cin >> string'


text:
Q: How can I retrieve Latitude and Longitude of a postal address using Bing Maps? I want to be able to retrieve the geographical coordinates (latitude and longitude) for a given address. I'm hoping I can do that if I have the full address (street address + city + state + zip).
If it matters, I am using Bing Maps. The skeleton code I've got is this (fullAddress, AddPushpin(), and getGeoCordsForAddress() are the most pertinent parts):
private void btnSave_Click(object sender, EventArgs e)
{
    string fullAddress = string.Empty;
    if (MissingValues()) return;

    mapName = cmbxMapName.SelectedItem.ToString();
    locationName = txtbxLocation.Text;
    address = txtbxAddress.Text;
    city = txtbxCity.Text;
    st8 = txtbxSt8.Text;
    zip = txtbxZip.Text;
    mapDetailNotes = richtxtbxMapNotes.Text;
    fullAddress = string.Format("{0} {1} {2} {3}", address, city, st8, zip);

    if (InsertIntoCartographerDetail())
    {
        MessageBox.Show("insert succeeded");
        AddPushpin(fullAddress);
        ClearControls();
    }
    else
    {
        MessageBox.Show("insert failed");
    }
}

private void AddPushpin(string fullAddress)
{
    GeoCoordinate geoCoord = getGeoCordsForAddress(fullAddress);
    Pushpin pin = new Pushpin();
    pin.Location = new Location(geoCoord.Latitude, geoCoord.Longitude);
    . . .
}

private GeoCoordinate getGeoCordsForAddress(string fullAddress)
{
   GeoCoordinate gc = new GeoCoordinate();
   . . . // What goes here?
   return gc;
}

A: Microsoft has an official BingMapsRESTToolkit which helps you to work with Bing Maps REST Services easily. To do so, you need to install BingMapsRESTToolkit NuGet Package.
Here, you are interested in GeocodeRequest to get location by address.
Example - Get latitude and longitude by address and create a pushpin on map
Install BingMapsRESTToolkit NuGet Package and run the following code:
private async void button1_Click(object sender, EventArgs e)
{
   var request = new GeocodeRequest();
   request.BingMapsKey = "YOUR MAP KEY";

   request.Query = "172 Jalan Pinang, 50088 Kuala Lumpur, " +
           "Federal Territory of Kuala Lumpur, Malaysia";
   //OR
   //request.Address = new SimpleAddress()
   //{
   //    CountryRegion = "Malaysia",
   //    AddressLine = "172 Jalan Pinang",
   //    AdminDistrict = "Kuala Lumpur, Federal Territory of Kuala Lumpur",
   //    PostalCode = "50088",
   //};

   var result = await request.Execute();
   if (result.StatusCode == 200)
   {
       var toolkitLocation = (result?.ResourceSets?.FirstOrDefault())
               ?.Resources?.FirstOrDefault()
               as BingMapsRESTToolkit.Location;
       var latitude = toolkitLocation.Point.Coordinates[0];
       var longitude = toolkitLocation.Point.Coordinates[1];
       var mapLocation = new Microsoft.Maps.MapControl.WPF.Location(latitude, longitude);
       this.userControl11.myMap.SetView(mapLocation, 15);
       var p = new Pushpin() { Location = mapLocation, ToolTip = "KLCC Park" };
       this.userControl11.myMap.Children.Add(p);
   }
}

How to use WPF Bing Maps in Windows Forms:

*

*How can I add a Bing Maps Component to my C# Winforms app?

*Getting Bing Maps key
Bing Maps REST Toolkit related resources:

*

*Getting Started

*API Reference

*Project Homepage

*NuGet Package


text:
Q: Invocar una función de JS, escrita en un archivo, por consola Quiero crear una funcion en un archivo js que se muestre por la consola. La función debe tomar el valor e imprimirlo.
Actualmente, hice esto en el archivo js:
function saludo (prueba){

console.log('Hola ' + prueba);

}

Pero en la consola sale esto:
Uncaught ReferenceError: saludo is not defined
    at <anonymous>:1:1

¿Alguna solución?
El html completo es solo esto:

        <title>Hola Mundo

Y esta es la carpeta:

A: Tienes un error al cerrar la etiqueta <title>
Fíjate que el título de la web es: "Hola mundo


text:
Q: Sending data to my master page I'm working on an intranet (correcting bugs and adding features) - but there's an issue with the display of the administrator tab, it display either way !
I am now able to know if the Employee is an administrator or not with the following SQL request :
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    // Variables
    string isAdministrator;
    bool isAdmin;

    // Checks the admin status of logging in user
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
    {
        using (SqlCommand command = new SqlCommand("SELECT isAdministrator FROM Employee WHERE Login = '" + model.UserName + "'", connection))
        {
            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    isAdministrator = reader[0].ToString();
                    isAdmin = Convert.ToBoolean(isAdministrator);
                    ViewData["isAdmin"] = isAdmin;
                }
            }
         }
     }

      // Not relevant things related to logging in
  return View(model);
}

The behavior should be : if isAdmin is true, display Administration tab (or simply deny its access) if not, don't.
But I have two major issues :

*

*I wonder where I can fill my isAdmin variable to have it filled no matter what (so that I don't have to log in to have it filled)

*And I don't know how to pass it's value to my Site.Master

A: Use for example ViewBag.IsAdmin = 1 like:
...
while (reader.Read())
{
    isAdministrator = reader[0].ToString();
    isAdmin = Convert.ToBoolean(isAdministrator);
    ViewBag.IsAdmin = isAdmin;
    break;
}
...

and then in the _Layout.cshtml you can use variable from ViewBag like:
@if(ViewBag.IsAdmin == 1)
{

}

But In my opinion you should look for the SimpleMembership functionality.
Then you can use:
@if(HttpContext.Current.User.IsInRole("Administrator"))
{

}


text:
Q: Is there a Python way to modify the input function= I'm trying to modify the existing input function in a project just so that it can loop if the input given is not an integer, but I can't seem to find out how.
If this is a normal function it works:
def getInput():
    while True:
        try: x = int(input()); break
        except ValueError: print("Number not integer. Try again.")
    return x

numberOfNodes = getInput()

I've thought of changing this to def __input__(): but it does not modify the built-in function. Is there a way to re-write built-in functions? This piece of code is pretty much all I need but I was just curious to see if I can make it the default behavior for input.

A: To summarize the discussion in the comments:
old_input = input

def input(*args):
  while True:
    try:
      return int(old_input(*args))
    except ValueError:
      print("Number not integer. Try again.")


text:
Q: Can a binary integer linear program be converted to a linear program? I need to solve the following binary integer linear program:
$$
\max \textbf{c}^T \textbf{x}
$$
Subject to:
$$
\textbf{Ax} \le \textbf{b}
$$
Where $ \textbf{b} \in \mathbb{Z}^n $, $\textbf{A} \in \mathbb{Z}^{m \times n} $, all the entries of $\textbf{c}$ are equal to $1$ and all the entries of $\textbf{x}$ are either $0$ or $1$. I thought about relaxing the problem by allowing the entries of $\textbf{x}$ to be real numbers between $0$ and $1$, and then solving the relaxed problem using Simplex. However, in order to ensure integral solutions from Simplex, the program must be Totally Dual Integral (TDI). Total unimodularity is unfeasible because $\textbf{A}$ can have entries different from $\pm 1$. I read that a linear program can be converted into a TDI one by adding sufficiently many redundant inequalities, as long as the polyhedron defined by $\textbf{Ax} \le \textbf{b}$ is rational (Giles-Pulleyblank theorem). However, I have not found an algorithmic way of defining these redundant constraints. Is it possible to convert the relaxed problem into a TDI one, by using a general construction of redundant inequalities?


text:
Q: Using MapKit, But default location is in CA, USA. Need to change it to default Okay using mapkit. The user can move and drag the red pin. However when i run it, the default location is in CA. When i want it to where the user currently is.
Here is the code.
#import "MapKitDragAndDropViewController.h"
#import "DDAnnotation.h"
#import "DDAnnotationView.h"

@interface MapKitDragAndDropViewController ()
- (void)coordinateChanged_:(NSNotification *)notification;
@end

@implementation MapKitDragAndDropViewController

@synthesize mapView;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    CLLocationCoordinate2D theCoordinate;
    theCoordinate.latitude = 37.810000;
    theCoordinate.longitude = -122.477989;

    DDAnnotation *annotation = [[[DDAnnotation alloc] initWithCoordinate:theCoordinate addressDictionary:nil] autorelease];
    annotation.title = @"Drag to Move Pin";
    annotation.subtitle = [NSString stringWithFormat:@"%f %f", annotation.coordinate.latitude, annotation.coordinate.longitude];

    [self.mapView addAnnotation:annotation];
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    // NOTE: This is optional, DDAnnotationCoordinateDidChangeNotification only fired in iPhone OS 3, not in iOS 4.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(coordinateChanged_:) name:@"DDAnnotationCoordinateDidChangeNotification" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];

    // NOTE: This is optional, DDAnnotationCoordinateDidChangeNotification only fired in iPhone OS 3, not in iOS 4.
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DDAnnotationCoordinateDidChangeNotification" object:nil];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

    self.mapView.delegate = nil;
    self.mapView = nil;
}

- (void)dealloc {
    mapView.delegate = nil;
    [mapView release];
    [super dealloc];
}

#pragma mark -
#pragma mark DDAnnotationCoordinateDidChangeNotification

// NOTE: DDAnnotationCoordinateDidChangeNotification won't fire in iOS 4, use -mapView:annotationView:didChangeDragState:fromOldState: instead.
- (void)coordinateChanged_:(NSNotification *)notification {

    DDAnnotation *annotation = notification.object;
    annotation.subtitle = [NSString stringWithFormat:@"%f %f", annotation.coordinate.latitude, annotation.coordinate.longitude];
}

#pragma mark -
#pragma mark MKMapViewDelegate

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState {

    if (oldState == MKAnnotationViewDragStateDragging) {
        DDAnnotation *annotation = (DDAnnotation *)annotationView.annotation;
        annotation.subtitle = [NSString stringWithFormat:@"%f %f", annotation.coordinate.latitude, annotation.coordinate.longitude];
    }
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {

    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }

    static NSString * const kPinAnnotationIdentifier = @"PinIdentifier";
    MKAnnotationView *draggablePinView = [self.mapView dequeueReusableAnnotationViewWithIdentifier:kPinAnnotationIdentifier];

    if (draggablePinView) {
        draggablePinView.annotation = annotation;
    } else {
        // Use class method to create DDAnnotationView (on iOS 3) or built-in draggble MKPinAnnotationView (on iOS 4).
        draggablePinView = [DDAnnotationView annotationViewWithAnnotation:annotation reuseIdentifier:kPinAnnotationIdentifier mapView:self.mapView];

        if ([draggablePinView isKindOfClass:[DDAnnotationView class]]) {
            // draggablePinView is DDAnnotationView on iOS 3.
        } else {
            // draggablePinView instance will be built-in draggable MKPinAnnotationView when running on iOS 4.
        }
    }

    return draggablePinView;
}

A: You need to have code similar to the following:
    lm = [[CLLocationManager alloc] init];
    lm.delegate = self;
    lm.desiredAccuracy = kCLLocationAccuracyBest;
    [lm startUpdatingLocation];

This uses the CLLocationManager object to locate the current position of the user


text:
Q: Limit the Calculated Value to a max Value - SwiftUI If Values are inserted in the app and not in the "lets say prefer order" a big value occurs, it is correct but it doesn't look good.
For example if the second Textfield (userData.Rent) is filled before the first Textfield(userData.BPrice) a value for the "return Brutto" is 24 thousand % ...
How can the calculated value be limited to a certain value, for example it cannot go higher than 20% or any other value. But below this value it moves freely.
It should more or less stop at lets say 20%
// ContentView:
struct ContentView: View {
    @EnvironmentObject var userData: UserData

    var Brutto: Double{
        let price = Double(userData.BPrice) ?? 0
        let rent = Double(userData.Rent) ?? 0

        let Brutto = rent * 12 / price * 100

        return Brutto
    }

    var body: some View {
        VStack {
            Text ("\(Brutto, specifier: "%.1f")")
        }
        VStack{
             TextField("BPrice", text: $userData.BPrice)
               .keyboardType(.decimalPad)
         }
         VStack{
              TextField("Rent", text: $userData.Rent)
               .keyboardType(.decimalPad)
          }
    }

// UserData File:
class UserData : ObservableObject {

  private static let userDefaultBPrice = "BPrice"
  private static let userDefaultRent = "Rent"

  @Published var BuyingPrice = UserDefaults.standard.string(forKey: UserData.userDefaultBPrice) ?? ""
  {
    didSet {
      UserDefaults.standard.set(self.BPrice, forKey: UserData.userDefaultBPrice)
    }
  }

  @Published var Rent = UserDefaults.standard.string(forKey: UserData.userDefaultRent) ?? "" {
    didSet {
      UserDefaults.standard.set(self.Rent, forKey: UserData.userDefaultRent)
    }
  }
  private var canc: AnyCancellable!

}

Thanks


text:
Q: Type erasure, generics and existential types I have a List of a parametric type, List[Field[_]], and I want something like this:
sealed trait FieldType[K] { val name: String }
sealed trait StringField extends FieldType[String]
case object publisher extends StringField { val name = "publisher" }
// ...

trait Field[K] {
  val field: FieldType[K]
  val value: K
}

case class Publisher(value: String) extends Field[String] { val field = publisher }
// ...

def get[K](l: List[Field[_]], key: FieldType[K]) : Option[K] =
  l match {
  case Nil => None
  case (a:Field[K]) :: rest  => Some(a.value)
  case (a:Field[_]) :: rest => get(rest, key)
}

which doesn't work, because K is erased. I tried typetags, but I must confess I got lost. Any quick way to get what I want?

A: Yes, you can use type tags to get the compiler to generate the erased type information. According to the Scala documentation there are three ways to optain a tag.
By adding an implicit evidence parameter of type ClassTag, the compiler will generate the missing type information if it cannot find a suitable implicit value. Given the evidence, we can obtain the runtime class and compare it to the runtime class of the value of your Field.
def get[A](l: List[Field[_]])(implicit evidence: ClassTag[A]): Option[A] =
  l match {
    case Nil => None
    case (a: Field[A]) :: rest if evidence.runtimeClass == a.value.getClass =>
      Some(a.value)
    case a :: rest =>
      get[A](rest)
  }

However, note that in this example, get[Int] will produce a ClassTag with the runtime class Int whereas value.getClass will return a java.lang.Integer
Given case class Other(value: Int) extends Field[Int], this will yield the following result:
def main(args: Array[String]): Unit = {
  println(get[String](Other(4) :: Other(2) :: Publisher("foo") :: Nil)) // Some(foo)
  println(get[Integer](Other(4) :: Other(2) :: Publisher("foo") :: Nil)) // Some(4)
  println(get[Int](Other(4) :: Other(2) :: Publisher("foo") :: Nil)) // None
}

Note that I removed the parameter key, as it did not serve a purpose. If the key is supposed to be unique, then, instead of checking the type tag, I would suggest matching against the key, thereby not using reflection:
def get[A](l: List[Field[_]], key: FieldType[A]): Option[A] = l match {
  case Nil => None
  case a :: rest if a.field == key => Some(a.value.asInstanceOf[A])
  case a :: rest => get(rest, key)
}

Edit: To address your questions from the comments:
is the asInstanceOf necessary? ... I was under the impression that having to resort to it is sort of bad practice/to be avoided/unsafe. Is that correct?
Since l is of type List[Field[_]], a is of type Field[_], meaning that a.value has the existential type, i.e., the compiler does not know it is of type A. However, because of the relation between a.key and a.value, we know that if a.field is of type FieldType[A], then value is of type A, so this particular type cast is safe (as long as you do not change the code).
You are absolutely correct that having to use a type cast indicates a flaw in the design, so maybe the best solution is to redesign Field, or the list l. Actually, I'd ask myself why you need to put various different types of Field in a list and then extract a certain type of Field later on? Maybe List is the wrong data structure? Would a Map[FieldType[_], List[Field[_]] be a better choice to store your fields? Or a Map[Class[_], List[Field[_]]? Or maybe a custom data structure?
Note that you can get rid of the asInstanceOf in the following way:
def get[A](l: List[Field[_]], key: FieldType[A]): Option[A] = l match {
  case Nil => None
  case (a: Field[A]) :: rest if a.field == key => Some(a.value)
  case a :: rest => get(rest, key)
}

but this does not give you more static safety, because type erasure makes Field[A] match against any generic version of Field. I'd say this variant is worse because it makes the explicit type cast implicit, hence this code is more error prone.
 I was trying to use TypeTag[] and typeOf[] instead of ClassTag and runtimeClass, as those where the example I found on the documentation page you linked (and elsewhere). What's the difference? Most of all, I want information regarding the _ in Field[_], so why oh why the ClassTag is on A?!?
There are three type tags that were introduced as a replacement for Manifest:

*

*TypeTag

*WeakTypeTag

*ClassTag
From the ScalaDoc:

ClassTags are a weaker special case of scala.reflect.api.TypeTags#TypeTags, in that they wrap only the runtime class of a given type, whereas a TypeTag contains all static type information.

While you could probably also solve the problem using TypeTag, I figured that it suffices to compare the runtime class.
The problem is that the existential type can really be any superclass of A, because the list l can contain all kinds of Fields. In the example I gave, we have a list of Field[Int] :: Field[Int] :: Field[String] :: Field[Int], hence the existential type in this case must be Any, the least common supertype of Int and String. In other words: You benefit nothing from deriving the existential type of l: List[Field[_]].
However, what you actually want to do is find the first element in the list whose value is of type A. Because A is erased, the only way to obtain information about its runtime type is by passing the information as an additional argument, e.g., using the implicit ClassTag evidence. Now all that remains is finding out which element has a value of the corresponding type, hence a.value.getClass == evidence.runtimeClass.


text:
Q: c# progress bar does not update I am trying to do a progress bar in c# but I am having trouble updating it gets to 90% and resets. but if I show a message box then it will fill up.
This code fills it all the way up
    public void mess(string s)
    {
        MessageBox.Show("l");
    }
    public void ProgressForm1Method(double min, double max)
    {
        ts.Maximum = (int)max;
        ts.Value = (int)min;
        this.Update();
        Application.DoEvents();
        if (ts.Value == ts.Maximum)
        {
            mess("l");
            ts.Value = 0;
        }
        ts.Invalidate();
    }

this does not
    public void mess(string s)
    {
        MessageBox.Show("l");
    }
    public void ProgressForm1Method(double min, double max)
    {
        ts.Maximum = (int)max;
        ts.Value = (int)min;
        this.Update();
        Application.DoEvents();
        if (ts.Value == ts.Maximum)
        {
            ts.Value = 0;
        }
        ts.Invalidate();
    }

A: That's because you set the value to 0 the moment it hits maximum. So it gives you the impression that it only fills up to 90%. Whereas, in your first example, you show the message box right before ts.Value = 0.
ts.Value = 0 doesn't fire until you click close the message box, so it shows up to 100%


text:
Q: Structure member alignment in GCC version below 4.0.0 When I have just a single array of chars included in a struct like in6_addr, what alignment issues should I be aware of when this in6_addr is combined with other data types in another struct?
I have an issue on SOLARIS generating bus error using GCC version 3.4.3.

A: A char cannot be misaligned, not even if it's a member of an array. Other data types should still be aligned at appropriate offsets to the start of the structure. Is the structure itself properly aligned?


text:
Q: How to control direct url access? How to control direct url access in jsf 2.0, struts 2 and spring 3 ? I mean not login user  type url and display always home or login page.

A: You can either use a project like spring-security to integrate with your application, or write your own servlet-filter
The stackoverflow servlet-filter tag has a good overview of servlet filters. For most servlet compatible web frameworks you can integrate a filter to intercept requests and redirect invalid or unauthorized requests to where they belong.

A: I suggest you to use Apache Shiro filter for control direct access for a certain url.
Look at the Apache Shiro configuration ini file where are the control of url access shown.
[main]
logout = org.apache.shiro.web.filter.authc.LogoutFilter
roles  = org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
authc.loginUrl=/faces/login.xhtml
authc.successUrl=/faces/index.xhtml
roles.unauthorizedUrl = /faces/unauthorized.xhtml
logout.redirectUrl = /faces/login.xhtml?status=loggedOut
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = SELECT PASSWORD FROM USERS WHERE USERS.USERNAME = ?
jdbcRealm.userRolesQuery = SELECT ROLE_NAME FROM ROLES, USER_ROLE, USERS WHERE  ROLES.ROLE_ID = USER_ROLE.ROLE_ID AND USERS.USR_ID = USER_ROLE.USR_ID AND USERS.USERNAME = ?
jdbcRealm.permissionsQuery = SELECT PERMISSIONS.PERM_NAME FROM ROLES, PERMISSIONS_ROLE, PERMISSIONS WHERE  ROLES.ROLE_ID = PERMISSIONS_ROLE.ROLE_ID AND PERMISSIONS.PERM_ID = PERMISSIONS_ROLE.PERM_ID AND ROLES.ROLE_NAME = ?
ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource
ds.user = maqraa
ds.password = maqraa
ds.databaseName = maqraa
ds.serverName = localhost
ds.portNumber = 3306
jdbcRealm.dataSource = $ds
securityManager.realms = $jdbcRealm

[urls]
/faces/login.xhtml = authc
/faces/admin/** = authc, roles[admin]
/faces/teacher/** = authc, roles[teacher]
/faces/reports/** = authc, roles[admin]
/faces/officer/** = authc, roles[officer]
/faces/manager/** = authc, roles[manager]
/faces/roles/** = authc, roles[admin]

Looking at the previous url(s) you will find out that any access for /faces/login.xhtml must be done by authenticated user in addition to access some of url(s) you must be a playing for a specific role(s).
Review Shiro tag on stackoverflow or see the Apache Shiro site.
I hope that help you.
Thanks.


text:
Q: How to allocate full memory pages In C or C++, on Linux, I want to allocate heap memory in full pages of the system's memory page size.
(The purpose is that I want to increase the likelihood that harmful buffer overflows cause segmentation faults.)
When I allocate memory with C++ array new (pointer = new char[size]), where size is a multiple of sysconf(_SC_PAGESIZE), then still the (virtual) address the allocated memory will usually not be a multiple of sysconf(_SC_PAGESIZE), indicating that I've got a subset of a larger chunk, confirmed by the fact that writing to pointer[size] and a little bit beyond (forced buffer overflow) usually does not cause a segmentation fault.
My question here is, can I influence the memory allocation somehow to give me full memory pages.
The processor architecture I am interested in is x86_64 aka amd64. Operating system is either latest Ubuntu, or stable CentOS Linux (7.3), the latter comes with kernel 3.10 and gcc-4.8.
I do not care if the solution is in C or C++, therefore I ask to leave the C tag in this question.

A: 1) Just switching from pointer = new char[size] to pointer = aligned_alloc(sysconf(_SC_PAGESIZE), size) resulted in proper page alignment and (so far, with small test programs) consistent generation of segmentation faults when exceeding the allocated range. As @JohnBollinger pointed out in his first comment to the question, the generation of segmentation faults is not guaranteed from the method of allocation alone. This can be fixed with 2):
2) The Linux man page for the function mprotect contains a complete example for restricting access to memory pages. The example also provides a signal handler for SIGSEGV, which I'm not interested in, default action (abort) is good enough for me. The example section from the man page follows. Note that applying mprotect to memory areas unrelated to mmap is a Linux-specific extension not covered by POSIX.

EXAMPLE
The  program  below  allocates four pages of memory, makes the third
  of these pages read-only, and then  executes  a  loop  that  walks
  upward through the allocated region modifying bytes.
An example of what we might see when running the program is the
  following:
       $ ./a.out
       Start of region:        0x804c000
       Got SIGSEGV at address: 0x804e000

Program source
   #include <unistd.h>
   #include <signal.h>
   #include <stdio.h>
   #include <malloc.h>
   #include <stdlib.h>
   #include <errno.h>
   #include <sys/mman.h>

   #define handle_error(msg) \
       do { perror(msg); exit(EXIT_FAILURE); } while (0)

   static char *buffer;

   static void
   handler(int sig, siginfo_t *si, void *unused)
   {
       printf("Got SIGSEGV at address: 0x%lx\n",
               (long) si->si_addr);
       exit(EXIT_FAILURE);
   }

   int
   main(int argc, char *argv[])
   {
       char *p;
       int pagesize;
       struct sigaction sa;

       sa.sa_flags = SA_SIGINFO;
       sigemptyset(&sa.sa_mask);
       sa.sa_sigaction = handler;
       if (sigaction(SIGSEGV, &sa, NULL) == -1)
           handle_error("sigaction");

       pagesize = sysconf(_SC_PAGE_SIZE);
       if (pagesize == -1)
           handle_error("sysconf");

       /* Allocate a buffer aligned on a page boundary;
          initial protection is PROT_READ | PROT_WRITE */

       buffer = memalign(pagesize, 4 * pagesize);
       if (buffer == NULL)
           handle_error("memalign");

       printf("Start of region:        0x%lx\n", (long) buffer);

       if (mprotect(buffer + pagesize * 2, pagesize,
                   PROT_READ) == -1)
           handle_error("mprotect");

       for (p = buffer ; ; )
           *(p++) = 'a';

       printf("Loop completed\n");     /* Should never happen */
       exit(EXIT_SUCCESS);
   }

Attribution of the preceding quote:

This page is part of release 4.04 of the Linux  man-pages  project.
  A description  of  the project, information about reporting bugs, and
  the latest    version    of    this    page,    can     be     found  at http://www.kernel.org/doc/man-pages/.


text:
Q: How to plot a equation like ay + bx + c = 0 in matlab? I've already searched it here but I couldn't found it the way I was looking for.
I kind managed to do it using Symbolic Math but I don't understand it quite well. For exemple, after doing that

syms y x
    ezplot(-y + x + 1 == 0)

i get a nice graph, but can I use this expression later to calculate its value? like, first I want to plot -y + x + 1 == 0 and at another moment I want to solve f(3) for exemple, where f(x) = x + 1 (same equation).
I know I can write a function to do that, but as a function I don't know how to plot it. In the other way, I know how to plot using symbolic math, but I don't know how to calculate it after.
I'm writing a PLA algorithm and them I need to generate the 'a', 'b' 'c' for the equation, that why I need to know how to plot and solve in a "systematic code" way, and not typing one by one.
Thanks in advance!

A: Just define f to be a function of the symbolic variable x:
>> syms x
>> f = x+1;

Then you can use f as the input to ezplot:
>> ezplot(f)

which produces the graph

On the other hand, to solve the equation f(x)=0 use solve as follows:
>> solve(f)
ans =
-1

ezplot and solve can be used with string inputs as well, but the string has to be different in either case. To plot the graph:
>> ezplot('x+1');

To solve the equation:
>> solve('x+1=0')
ans =
-1

A: The equation you gave us is a straight line, so a polynomial. The coefficients are y= -b/a*x -c/a.
% ay + bx + c = 0 reads y = -b/a*x - c/a*1
a = -1;
b = 1;
c = 1;
p = [-b/a, -c/a];   % polynomial representing your equation

% plot like this
x = linspace(-2,2, 50);
figure
plot(x, polyval(p,x)) % evaluate polynomial p at the positions x

% find the solution
roots(p) # -1

If you need or want to use ezplot, you can put the polyval-expression in an inline function and you can call ezplot with that handle:
f = @(x) polyval(p, x); % the function
ezplot(f)


text:
Q: Bookmark Directories In Terminal Looking for a solution to quickly navigate to long paths in a shell (particularly Max OS X Terminal.app).
Say my path is ~/This/Is/A/Really/Long/Path/That/I/Would/Rather/Not/Type/Frequently
Instead of cd ~/This/Is/A/....
I would like to be able to store favorites/bookmark directories so I could do "cd myPath"
Are there any binaries or tools available to do something like this?

A: I've found the packages 'Apparix' and 'Goto' which together make the stuff dreams are made of for us terminal junkies.
Naturally, I had trouble installing Apparix, but I figured it out in the end.
How To Install Apparix on Mac OS X:

*

*Download the tarball from Apparix's homepage.

*Unpack the tarball, cd to the unpacked folder.

*Run this command ./configure --prefix=$HOME/local && make && make install.

*Run man apparix, scroll down to the heading BASH-style functions, copy everything within that section (delimited with ---) and paste it into ~/.bash_profile.

That's it. You should now have Apparix up and running on OS X (further install info and usage is on Apparix's homepage).

A: Another solution is to use Bashmarks, which allows you to this
$ cd ~/This/Is/A/Really/Long/Path/That/I/Would/Rather/Not/Type/Frequently
$ s shortname # save current path as `shortname`
$ cd /
$ g shortname # cd to ~/This/Is/A/Really/Long/Path/That/I/Would/Rather/Not/Type/Frequently

A: You can use aliases (stick them in your ~/.bash_profile if you want them to always load)
alias cd_bmark1='cd ~/This/Is/A/Really/Long/Path/That/I/Would/Rather/Not/Type/Frequently'
Then use by just typing
cd_bmark1
into the console

A: I know you already found an answer that worked for you, but a couple of more lightweight suggestions that might help others looking for similar things

*

*If your directories are relatively fixed, just long and far away from each other, you can use the CDPATH environment variable to add directories to the search path when typing the "cd" command.  If the directory name you try to cd to isn't in the current directory, the other entries in your CD path will also be looked at (and it's also tab complete aware, at least in bash and zsh).

*Switching to zsh rather than bash and using the excellent directory stacks abilities.  With it, you can maintain a history of directories that you've visited, view the history with the "dh" alias, and easily switch to a directory by using quick shortcuts (ex: cd -3 to switch to the 3rd directory in your history stack).

A: Why not having a symlink ?
ln -s ~/This/Is/A/Really/Long/Path/That/I/Would/Rather/Not/Type/Frequently bmark
cd bmark

A: I use to.sh daily to create and navigate bookmarked paths in bash. It supports tag autocompletion and the ability to easily add/remove bookmarks.
https://github.com/Grafluxe/to.sh

Full disclosure, I wrote this tool :)


text:
Q: Trouble batching cubes in libgdx I am trying to develop a game where I am rendering up to 300 cubes on screen. The performance of modelBatch when creating new modelInstance for each cube is terrible. There is no 3d batch that batches all the cubes to one draw call as far as I know. So I am desperately trying to batch them somehow.
This question is directly related to this one: LibGDX 3D increase perfomance
The answer posted batches all the cubes successfully but when environment is added to get some lighting it appears that the cubes have missing sides or something else is wrong with them.
Heres a picture:

Here is my cube class (pretty much copied from answer above)
public class Cube {

  int index;
  int vertexFloatSize;
  int posOffset;
  int norOffset;
  boolean hasColor;
  int colOffset;
  private Vector3 position = new Vector3();
  private Matrix4 rotationTransform = new Matrix4().idt();

  private Color color = new Color();
  public float halfWidth, halfHeight, halfDepth;
  private boolean transformDirty = false;
  private boolean colorDirty = false;

  static final Vector3 CORNER000 = new Vector3();
  static final Vector3 CORNER010 = new Vector3();
  static final Vector3 CORNER100 = new Vector3();
  static final Vector3 CORNER110 = new Vector3();
  static final Vector3 CORNER001 = new Vector3();
  static final Vector3 CORNER011 = new Vector3();
  static final Vector3 CORNER101 = new Vector3();
  static final Vector3 CORNER111 = new Vector3();

  static final Vector3[] FACE0 = {CORNER000, CORNER100, CORNER110, CORNER010};
  static final Vector3[] FACE1 = {CORNER101, CORNER001, CORNER011, CORNER111};
  static final Vector3[] FACE2 = {CORNER000, CORNER010, CORNER011, CORNER001};
  static final Vector3[] FACE3 = {CORNER101, CORNER111, CORNER110, CORNER100};
  static final Vector3[] FACE4 = {CORNER101, CORNER100, CORNER000, CORNER001};
  static final Vector3[] FACE5 = {CORNER110, CORNER111, CORNER011, CORNER010};
  static final Vector3[][] FACES = {FACE0, FACE1, FACE2, FACE3, FACE4, FACE5};

  static final Vector3 NORMAL0 = new Vector3();
  static final Vector3 NORMAL1 = new Vector3();
  static final Vector3 NORMAL2 = new Vector3();
  static final Vector3 NORMAL3 = new Vector3();
  static final Vector3 NORMAL4 = new Vector3();
  static final Vector3 NORMAL5 = new Vector3();
  static final Vector3[] NORMALS = {NORMAL0, NORMAL1, NORMAL2, NORMAL3, NORMAL4, NORMAL5};

  float[] meshVertices;

  public Cube(float x, float y, float z, float width, float height, float depth, int index,
        VertexAttributes vertexAttributes, float[] meshVertices){

      position.set(x,y,z);
      this.halfWidth = width/2;
      this.halfHeight = height/2;
      this.halfDepth = depth/2;
      this.index = index;
      this.meshVertices = meshVertices;

      NORMAL0.set(0,0,-1);
      NORMAL1.set(0,0,1);
      NORMAL2.set(-1,0,0);
      NORMAL3.set(1,0,0);
      NORMAL4.set(0,-1,0);
      NORMAL5.set(0,1,0);

      vertexFloatSize = vertexAttributes.vertexSize/4; //4 bytes per float
      posOffset = getVertexAttribute(Usage.Position, vertexAttributes).offset/4;
      norOffset = getVertexAttribute(Usage.Normal, vertexAttributes).offset/4;

      VertexAttribute colorAttribute = getVertexAttribute(Usage.Color, vertexAttributes);
      hasColor = colorAttribute!=null;
      if (hasColor){
          colOffset = colorAttribute.offset/4;
          this.setColor(Color.WHITE);
      }
      transformDirty = true;

  }

  public void setDimensions(float x, float y , float z){

      this.halfWidth = x/2;
      this.halfHeight = y/2;
      this.halfDepth = z/2;

  }

  public void setIndex(int index){

      this.index = index;
      transformDirty = true;
      colorDirty = true;

  }

  /**
   * Call this after moving and/or rotating.
   */
  public void update(){

      if (colorDirty && hasColor){
          for (int faceIndex= 0; faceIndex<6; faceIndex++){
              int baseVertexIndex = (index*24 + faceIndex*4)*vertexFloatSize;//24 unique vertices per cube, 4 unique vertices per face
              for (int cornerIndex=0; cornerIndex<4; cornerIndex++){
                  int vertexIndex = baseVertexIndex + cornerIndex*vertexFloatSize + colOffset;
                  meshVertices[vertexIndex] = color.r;
                  meshVertices[++vertexIndex] = color.g;
                  meshVertices[++vertexIndex] = color.b;
                  meshVertices[++vertexIndex] = color.a;
              }
          }
          colorDirty = false;
      }

      if (!transformDirty){
          return;
      }

      transformDirty = false;

      CORNER000.set(-halfWidth,-halfHeight,-halfDepth).rot(rotationTransform).add(position);
      CORNER010.set(-halfWidth,halfHeight,-halfDepth).rot(rotationTransform).add(position);
      CORNER100.set(halfWidth,-halfHeight,-halfDepth).rot(rotationTransform).add(position);
      CORNER110.set(halfWidth,halfHeight,-halfDepth).rot(rotationTransform).add(position);
      CORNER001.set(-halfWidth,-halfHeight,halfDepth).rot(rotationTransform).add(position);
      CORNER011.set(-halfWidth,halfHeight,halfDepth).rot(rotationTransform).add(position);
      CORNER101.set(halfWidth,-halfHeight,halfDepth).rot(rotationTransform).add(position);
    CORNER111.set(halfWidth,halfHeight,halfDepth).rot(rotationTransform).add(position);

      NORMAL0.set(0,0,-1).rot(rotationTransform);
      NORMAL1.set(0,0,1).rot(rotationTransform);
      NORMAL2.set(-1,0,0).rot(rotationTransform);
      NORMAL3.set(1,0,0).rot(rotationTransform);
      NORMAL4.set(0,-1,0).rot(rotationTransform);
      NORMAL5.set(0,1,0).rot(rotationTransform);

      for (int faceIndex= 0; faceIndex<6; faceIndex++){
          int baseVertexIndex = (index*24 + faceIndex*4)*vertexFloatSize;//24 unique vertices per cube, 4 unique vertices per face
          for (int cornerIndex=0; cornerIndex<4; cornerIndex++){
              int vertexIndex = baseVertexIndex + cornerIndex*vertexFloatSize + posOffset;
              meshVertices[vertexIndex] = FACES[faceIndex][cornerIndex].x;
              meshVertices[++vertexIndex] = FACES[faceIndex][cornerIndex].y;
              meshVertices[++vertexIndex] = FACES[faceIndex][cornerIndex].z;

              vertexIndex = baseVertexIndex + cornerIndex*vertexFloatSize + norOffset;
              meshVertices[vertexIndex] = NORMALS[faceIndex].x;
              meshVertices[++vertexIndex] = NORMALS[faceIndex].y;
              meshVertices[++vertexIndex] = NORMALS[faceIndex].z;
          }
      }
  }

  public Cube setColor(Color color){

      if (hasColor){
          this.color.set(color);
          colorDirty = true;
      }
      return this;
  }

  public void setAlpha(float alpha) {

       if (hasColor){

           this.color.set(this.color.r, this.color.g, this.color.b, alpha);
           colorDirty = true;

       }
  }

  public Cube translate(float x, float y, float z){
      position.add(x,y,z);
      transformDirty = true;
      return this;
  }

  public Cube setPosition(float x, float y, float z){
      position.set(x,y,z);
      transformDirty = true;
      return this;
  }

public Cube setPosition(Vector3 position1) {

       position.set(position1);
       transformDirty = true;
       return this;

  }

  public VertexAttribute getVertexAttribute (int usage, VertexAttributes attributes) {
      int len = attributes.size();
      for (int i = 0; i < len; i++)
          if (attributes.get(i).usage == usage) return attributes.get(i);

      return null;
  }

  public Vector3 getPosition() {

      return this.position;
  }

}

And here is a test case that i created to test the cubes.
public class TestCase {

    ModelInstance mBatchedCubesModelInstance;
    Mesh mBatchedCubesMesh;
    float[] mBatchedCubesVertices;
    Array<Cube> mBatchedCubes;

    TestCase(){

            int width = 5;
            int height = 5;
            int length = 5;
            int numCubes = width*height*length;

            ModelBuilder mb = new ModelBuilder();
            mb.begin();
            MeshPartBuilder mpb = mb.part("cubes", GL20.GL_TRIANGLES, (Usage.Position | Usage.Normal | Usage.Color), new Material());
            for (int i=0; i<numCubes; i++){
                mpb.box(1, 1, 1);
            }
            Model model = mb.end();
            mBatchedCubesModelInstance = new ModelInstance(model);

            mBatchedCubesMesh = model.meshes.get(0);
            VertexAttributes vertexAttributes = mBatchedCubesMesh.getVertexAttributes();
            int vertexFloatSize = vertexAttributes .vertexSize / 4; //4 bytes per float
            mBatchedCubesVertices = new float[numCubes * 24 * vertexFloatSize]; //24 unique vertices per cube
            mBatchedCubesMesh.getVertices(mBatchedCubesVertices);

            mBatchedCubes = new Array<Cube>(numCubes);
            int cubeNum = 0;
            for (int x = 0; x < width; x++) {
                    for (int y = 0; y < height; y++) {
                            for (int z = 0; z < length; z++) {
                                    mBatchedCubes.add(new Cube((x-(width/2f))*1.5f, -((y-(height/2f)) * 1.5f), -(z-(length/2f))*1.5f, 1,1,1, cubeNum++, vertexAttributes, mBatchedCubesVertices ).setColor(Colors.getMixedColor()));
                            }
                    }
            }

    }

    public void render(ModelBatch batch, Environment environment){

            for (Cube cube : mBatchedCubes){ //must update any changed cubes.
                cube.update();
            }
            mBatchedCubesMesh.setVertices(mBatchedCubesVertices); //apply changes to mesh

            if(environment!=null) batch.render(mBatchedCubesModelInstance,environment);
            else batch.render(this.mBatchedCubesModelInstance);

    }

}

The cubes don't even move in my game so I don't even need the transformation. I just need to set the colors (including alpha channel) every frame. The batched mesh should work with libgdx shadow mapping also (I hope it automatically works when you have a properly batched modelInstance).
Could anyone tell me what is wrong with my code and why some faces don't show up. I understand I might be asking much so I will put a bounty on this question (50 points) after two days.
EDIT: After the answer from Tenfour04 things got a lot better. Alpha channel seems to work, strange face problem seems to have disappeared. However When I applied the changes to my real game I noticed that sometimes flour draws on top of in game terrain. I updated the test to illustrate the problem by adding big plane in the middle of cubes. Made a video: https://www.youtube.com/watch?v=LQhSMJfuyZY.
I would also like to clarify that I am not using any custom shader. Using only ModelBatch.begin() and .end() methods with no additional openGl calls.

A: I see a couple problems:

*

*You have blending off and/or your shader isn't setting the alpha value

*You aren't culling back faces.
So when you create your new material, instead of just using new Material(), use:
new Material(
    IntAttribute.createCullFace(GL20.GL_FRONT),//For some reason, libgdx ModelBuilder makes boxes with faces wound in reverse, so cull FRONT
    new BlendingAttribute(1f), //opaque since multiplied by vertex color
    new DepthTestAttribute(false), //don't want depth mask or rear cubes might not show through
    ColorAttribute.createDiffuse(Color.WHITE) //white since multiplied by vertex color
    );

You will also need to sort the cubes by distance from camera to get their alphas to layer correctly. Here's an updated Cube class that supports sorting. It has to be able to track color independently from the vertices array in case its index changes:
public class Cube implements Comparable<Cube>{

    private int index;
    int vertexFloatSize;
    int posOffset;
    int norOffset;
    boolean hasColor;
    int colOffset;
    private Vector3 position = new Vector3();
    private Matrix4 rotationTransform = new Matrix4().idt();
    public float halfWidth, halfHeight, halfDepth;
    private boolean transformDirty = false;
    private boolean colorDirty = false;
    private Color color = new Color();
    float camDistSquared;

    static final Vector3 CORNER000 = new Vector3();
    static final Vector3 CORNER010 = new Vector3();
    static final Vector3 CORNER100 = new Vector3();
    static final Vector3 CORNER110 = new Vector3();
    static final Vector3 CORNER001 = new Vector3();
    static final Vector3 CORNER011 = new Vector3();
    static final Vector3 CORNER101 = new Vector3();
    static final Vector3 CORNER111 = new Vector3();

    static final Vector3[] FACE0 = {CORNER000, CORNER100, CORNER110, CORNER010};
    static final Vector3[] FACE1 = {CORNER101, CORNER001, CORNER011, CORNER111};
    static final Vector3[] FACE2 = {CORNER000, CORNER010, CORNER011, CORNER001};
    static final Vector3[] FACE3 = {CORNER101, CORNER111, CORNER110, CORNER100};
    static final Vector3[] FACE4 = {CORNER101, CORNER100, CORNER000, CORNER001};
    static final Vector3[] FACE5 = {CORNER110, CORNER111, CORNER011, CORNER010};
    static final Vector3[][] FACES = {FACE0, FACE1, FACE2, FACE3, FACE4, FACE5};

    static final Vector3 NORMAL0 = new Vector3();
    static final Vector3 NORMAL1 = new Vector3();
    static final Vector3 NORMAL2 = new Vector3();
    static final Vector3 NORMAL3 = new Vector3();
    static final Vector3 NORMAL4 = new Vector3();
    static final Vector3 NORMAL5 = new Vector3();
    static final Vector3[] NORMALS = {NORMAL0, NORMAL1, NORMAL2, NORMAL3, NORMAL4, NORMAL5};

    public Cube(float x, float y, float z, float width, float height, float depth, int index,
        VertexAttributes vertexAttributes, float[] meshVertices){
    position.set(x,y,z);
    this.halfWidth = width/2;
    this.halfHeight = height/2;
    this.halfDepth = depth/2;
    this.index = index;

    vertexFloatSize = vertexAttributes.vertexSize/4; //4 bytes per float
    posOffset = getVertexAttribute(Usage.Position, vertexAttributes).offset/4;
    norOffset = getVertexAttribute(Usage.Normal, vertexAttributes).offset/4;

    VertexAttribute colorAttribute = getVertexAttribute(Usage.Color, vertexAttributes);
    hasColor = colorAttribute!=null;
    if (hasColor){
        colOffset = colorAttribute.offset/4;
        this.setColor(Color.WHITE, meshVertices);
    }
    transformDirty = true;
    }

    public void updateCameraDistance(Camera cam){
    camDistSquared = cam.position.dst2(position);
    }

    /**
     * Call this after moving and/or rotating.
     */
    public void update(float[] meshVertices){

    if (transformDirty){
        transformDirty = false;

        CORNER000.set(-halfWidth,-halfHeight,-halfDepth).rot(rotationTransform).add(position);
        CORNER010.set(-halfWidth,halfHeight,-halfDepth).rot(rotationTransform).add(position);
        CORNER100.set(halfWidth,-halfHeight,-halfDepth).rot(rotationTransform).add(position);
        CORNER110.set(halfWidth,halfHeight,-halfDepth).rot(rotationTransform).add(position);
        CORNER001.set(-halfWidth,-halfHeight,halfDepth).rot(rotationTransform).add(position);
        CORNER011.set(-halfWidth,halfHeight,halfDepth).rot(rotationTransform).add(position);
        CORNER101.set(halfWidth,-halfHeight,halfDepth).rot(rotationTransform).add(position);
        CORNER111.set(halfWidth,halfHeight,halfDepth).rot(rotationTransform).add(position);

        NORMAL0.set(0,0,-1).rot(rotationTransform);
        NORMAL1.set(0,0,1).rot(rotationTransform);
        NORMAL2.set(-1,0,0).rot(rotationTransform);
        NORMAL3.set(1,0,0).rot(rotationTransform);
        NORMAL4.set(0,-1,0).rot(rotationTransform);
        NORMAL5.set(0,1,0).rot(rotationTransform);

        for (int faceIndex= 0; faceIndex<6; faceIndex++){
        int baseVertexIndex = (index*24 + faceIndex*4)*vertexFloatSize;//24 unique vertices per cube, 4 unique vertices per face
        for (int cornerIndex=0; cornerIndex<4; cornerIndex++){
            int vertexIndex = baseVertexIndex + cornerIndex*vertexFloatSize + posOffset;
            meshVertices[vertexIndex] = FACES[faceIndex][cornerIndex].x;
            meshVertices[++vertexIndex] = FACES[faceIndex][cornerIndex].y;
            meshVertices[++vertexIndex] = FACES[faceIndex][cornerIndex].z;

            vertexIndex = baseVertexIndex + cornerIndex*vertexFloatSize + norOffset;
            meshVertices[vertexIndex] = NORMALS[faceIndex].x;
            meshVertices[++vertexIndex] = NORMALS[faceIndex].y;
            meshVertices[++vertexIndex] = NORMALS[faceIndex].z;
        }
        }
    }

    if (colorDirty){
        colorDirty = false;

        for (int faceIndex= 0; faceIndex<6; faceIndex++){
        int baseVertexIndex = (index*24 + faceIndex*4)*vertexFloatSize;//24 unique vertices per cube, 4 unique vertices per face
        for (int cornerIndex=0; cornerIndex<4; cornerIndex++){
            int vertexIndex = baseVertexIndex + cornerIndex*vertexFloatSize + colOffset;
            meshVertices[vertexIndex] = color.r;
            meshVertices[++vertexIndex] = color.g;
            meshVertices[++vertexIndex] = color.b;
            meshVertices[++vertexIndex] = color.a;
        }
        }
    }
    }

    public Cube setColor(Color color, float[] meshVertices){
    if (hasColor){
        this.color.set(color);
        colorDirty = true;

    }
    return this;
    }

    public void setIndex(int index){
    if (this.index != index){
        transformDirty = true;
        colorDirty = true;
        this.index = index;
    }
    }

    public Cube translate(float x, float y, float z){
    position.add(x,y,z);
    transformDirty = true;
    return this;
    }

    public Cube translateTo(float x, float y, float z){
    position.set(x,y,z);
    transformDirty = true;
    return this;
    }

    public Cube rotate(float axisX, float axisY, float axisZ, float degrees){
    rotationTransform.rotate(axisX, axisY, axisZ, degrees);
    transformDirty = true;
    return this;
    }

    public Cube rotateTo(float axisX, float axisY, float axisZ, float degrees){
    rotationTransform.idt();
    rotationTransform.rotate(axisX, axisY, axisZ, degrees);
    transformDirty = true;
    return this;
    }

    public VertexAttribute getVertexAttribute (int usage, VertexAttributes attributes) {
    int len = attributes.size();
    for (int i = 0; i < len; i++)
        if (attributes.get(i).usage == usage) return attributes.get(i);

    return null;
    }

    @Override
    public int compareTo(Cube other) {
    //the cube has a lower index than a cube that is closer to the camera
    if (camDistSquared>other.camDistSquared)
        return -1;
    return camDistSquared<other.camDistSquared ? 1 : 0;
    }
}

And you would sort it like this:
for (Cube cube : mBatchedCubes){
    cube.updateCameraDistance(camera);
}
mBatchedCubes.sort();
int index = 0;
for (Cube cube : mBatchedCubes){
    cube.setIndex(index++);
}


text:
Q: Confluent Connect on Different Port Not Working I'm setting up the Confluent-Stack using portainer on a Linux computer. One of my other containers is already using port 8083 (the default confluent-connect port) - so I replaced 8083 in the docker-compose.yml file with 8089. However, when everything starts up, I cannot see a connect cluster in the control center at all.
This is my base docker-compose.yml file:
https://raw.githubusercontent.com/confluentinc/cp-all-in-one/7.0.1-post/cp-all-in-one/docker-compose.yml
I got this link from here:
https://docs.confluent.io/platform/current/quickstart/ce-docker-quickstart.html
I've spun up the stack in portainer (not using a docker-compose command as suggested in the above tutorial) using the .yml file edited a little to replace the "8083:8083" with "8089:8089" and replace other "8083" occurences with "8089".
I also initially used port 7777 as a replacement, in this case I though I should replace "8083:8083" with "7777:8083" and the other "8083"'s I replaced with "7777". I'm a little new to these ports and clearly not understanding how one is supposed to set this up?
Please help. Thanks!

A: I ended up being able to reroute the other container that was using the 8083 port without issues, so I could use the default docker-compose file for the confluent stack and then everything worked fine. So my problem is solved, but the issue may still haunt me.


text:
Q: How to use Switch with dictionary values? In my code, I'd like to work with textual names of the items that are coded as one symbol in packets.
In a usual situation, 1012 would mean cat, dog, cat, frog to me, but there are many more pairs like this, so it's hard to remember all of them. Sometimes they need to be changed, so I thought I should use a Dictionary<string, int> for that purpose. But then…
switch (symbol)
{
    case "0": { /* ... */ }
    case "1": { /* ... */ }
    case "2": { /* ... */ }
    case "n": { /* ... */ }
}

…becomes…
switch (symbol)
{
    case kvpDic["cat"]: { /* ... */ }
    case kvpDic["dog"]: { /* ... */ }
    case kvpDic["frog"]: { /* ... */ }
    case kvpDic["something else"]: { /* ... */ }
}

and the studio says I need to use constants for my switch.
How do I make it work?
Upd: number of such animals and their value pairs are only known at runtime, so the code must not use constants (I guess).

A: You could store a Func<T> or Action in the dictionary instead.
var dict = new Dictionary<int, Action>();
dict.Add(1, () => doCatThing());
dict.Add(0, () => doDogThing());
dict.Add(2, () => doFrogThing());

Then, use it like so:
var action = dict[1];
action();

A: It's not a VS restriction, it's a language restriction. So you won't be able to do exactly what you want. One idea would be to use an enum. An enum can't use a char value for it's entries, look at Why we can't have "char" enum types for some info on that.

A: You want to use an enum, not a dictionary.
enum AnimalsEnum { Dog, Cat, Bird, Fish };

public whathuh(AnimalsEnum whichAnimal) {
 switch(whichAnimal) {
   case AnimalsEnum.Dog:
   case AnimalsEnum.Cat:
...
}

}


text:
Q: What kind of creature was the "God" in Star Trek V: The Final Frontier? In Star Trek V: The Final Frontier, the Enterprise goes to a planet where they find a creature that claims to be God.

What kind of creature was that?
Does that species show up in any other Star Trek show?
Is it related to the Cytherian that appears in the Star Trek TNG episode, The Nth Degree?

A: Canonically we know only what was shown during the course of Star Trek V: The Final Frontier, and nothing more. The being in question was a powerful entity capable of manipulating and deceiving others, but no other information about its origins are shown. There is no indication that it is directly related to any of the other "god-like" beings encountered over the course of the subsequent series.
Non-canonically, according to the novel Q-strike by Greg Cox, the entity in question was a being known as "The One" and was brought into the universe by Q and one of his associates, along with Gorgan and the Beta XII-A Entity. The Q continuum banished The One beyond the galactic barrier after the creature committed various atrocities.


text:
Q: Dapr binding for RabbitMQ not working using Dapr pub/sub sample I've taken the Dapr pub/sub How-to sample and tried to update it to use RabbitMQ
I've downloaded the Docker rabbitmq:3 image from DockerHub and it should be listening on amqp://localhost:5672.
I have created a new component file for RabbitMQ called rabbitmq.yaml and placed it in the .dapr/components directory. My component configuration for RabbitMQ is:
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: my-rabbitmq
spec:
  type: pubsub.rabbitmq
version: v1
metadata:
  - name: host
    value: amqp://localhost:5672
  - name: durable
    value: true # Optional. Default: "false"
  - name: deletedWhenUnused
   value: false # Optional. Default: "false"
  - name: ttlInSeconds
    value: 60
  - name: prefetchCount
    value: 0

My subscription is defined in subscription-rabbitmq.yaml located in the same .dapr/components directory. and it looks as follows:
apiVersion: dapr.io/v1alpha1
kind: Subscription
metadata:
  name: rabbitmq-subscription
spec:
  topic: deathStarStatus
  route: /dsstatus
  pubsubname: my-rabbitmq
scopes:
- app2

When I run the sample using the Redis Streams component and subscription, the node application receives the message and displays in within the output of the dapr run command.
dapr publish --topic deathStarStatus --pubsub pubsub --data '{ "message": "This is a test" }'
but when I publish a message to RabbitMQ, it states the "Event Published Successfully", but the node app doesn't receive the message.
dapr publish --topic deathStarStatus --pubsub my-rabbitmq --data '{ "message": "This is a test" }'
Here is the node app and the command to run it:
dapr run --app-id app2 --app-port 3000 node app2.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json({ type: 'application/*+json' }));

const port = 3000

// app.get('/dapr/subscribe', (req, res) => {
//     res.json([
//         {
//             pubsubname: "my-rabbitmq",
//             topic: "deathStarStatus",
//             route: "dsstatus"
//         }
//     ]);
// })

app.post('/dsstatus', (req, res) => {
    console.log(req.body);
    res.sendStatus(200);
});

app.listen(port, () => console.log(`consumer app listening on port ${port}!`))

What am I doing wrong?

A: It turns out that a "topic" in RabbitMQ (Dapr world) is really an Exchange and not a Queue.
When running "app2" with RabbitMQ subscription, a queue is created with a prepended appid (e.g. {appid}-{queueName}), but the Exchange was not created.  Not sure if this is by design or my specific configuration.
I ended up creating an Exchange called "deathStarStatus" and mapped that Exchange to my queue called "app2-deathStarStatus" and everything worked.


text: Q: Accessing C-Objective code from within delphi? I was wondering if it is possible to access C-Objective code from within delphi. In a research i've done that seems to be possible but the posts i've seen they were not that detailed so i couldn't figure out how the process works. For the android platform i've found that it could be done this way https://stackoverflow.com/a/29840534 . Actually this is what i am trying to do, to run the camera of the specified platform. So any help or directions about what should i read would be more than welcome.


text:
Q: RPi.GPIO interrupt not calling function long enough So I'm trying to design an LCD screen to have a Menu and a bunch of different functions and its supposed to take 4 buttons. A select, a menu, and an up and down. Right now I'm just trying to work on the Menu button. I want it to always display the clock unless the menu button is pressed. But when I press the button it doesn't stay on screen for the 5 seconds it's supposed to. I have no idea why it wont either. I've looked up the RPi interrupt and followed it, but it still won't stay up. The "hi" appears for not even half a second. I'm also using the raspberry pi spy's LCD library which I can link if needed be. The only thing I did was modify some timing things to match those of my displays and added the abilty to add text to any of the four rows at once seeings that I have a 20x4 display. If someone could help me, it would be greatly appreciated.
Here's the code:
#!usr/bin/python3
import RPi.GPIO as GPIO
import time
import sys
sys.path.append('/home/pi/Downloads')
import lcd

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
#GPIO.setup(33, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)

lcd.lcd_init()

def start():
    for x in range(0,8):
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}>----TestOS----<{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}<>---TestOS-----{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}-<>--TestOS-----{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}--<>-TestOS-----{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}---<>TestOS-----{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}----<TestOS>----{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}-----TestOS<>---{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}-----TestOS-<>--{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}-----TestOS--<>-{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}-----TestOS---<>{]", 1)
        time.sleep(0.1)

    lcd.lcd_init()

    for x in range(0,120):
        lcd.lcd_byte(0xFF,True)

    time.sleep(5)
    lcd.lcd_init()

def Menu():
    lcd.lcd_init()
    lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
    lcd.lcd_string("hi", 1)
    lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
    lcd.lcd_string("hi", 1)
    time.sleep(5)

def clock():
    lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
    lcd.lcd_string("+------------------+", 1)
    lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
    lcd.lcd_string(time.strftime("|%I:%M %p          |"), 1)
    lcd.lcd_byte(lcd.LCD_LINE_3, lcd.LCD_CMD)
    lcd.lcd_string(time.strftime("|%a, %b %d, %Y |"), 1)
    lcd.lcd_byte(lcd.LCD_LINE_4, lcd.LCD_CMD)
    lcd.lcd_string("+------------------+", 1)
    time.sleep(1)
    lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
    lcd.lcd_string("+------------------+", 1)
    lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
    lcd.lcd_string(time.strftime("|%I %M %p          |"), 1)
    lcd.lcd_byte(lcd.LCD_LINE_3, lcd.LCD_CMD)
    lcd.lcd_string(time.strftime("|%a, %b %d, %Y |"), 1)
    lcd.lcd_byte(lcd.LCD_LINE_4, lcd.LCD_CMD)
    lcd.lcd_string("+------------------+", 1)
    time.sleep(1)

GPIO.add_event_detect(11, GPIO.FALLING, callback=Menu, bouncetime=100)

start()
try:
    while True:
        clock()

finally:
    lcd.lcd_init()
    lcd.GPIO.cleanup()
    GPIO.cleanup()

PS:The lcd.lcd_init doubles to clear the screen which is why I call it so much.

A: Your method clock() which is running in infinite loop, always override text on display with time.
You must stop clock() method when Menu() function runs.
I added global variable menu pressed:
#!usr/bin/python3
import RPi.GPIO as GPIO
import time
import sys
sys.path.append('/home/pi/Downloads')
import lcd

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
#GPIO.setup(33, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)

menupressed = False

lcd.lcd_init()

def start():
    for x in range(0,8):
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}>----TestOS----<{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}<>---TestOS-----{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}-<>--TestOS-----{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}--<>-TestOS-----{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}---<>TestOS-----{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}----<TestOS>----{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}-----TestOS<>---{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}-----TestOS-<>--{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}-----TestOS--<>-{]", 1)
        time.sleep(0.1)
        lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
        lcd.lcd_string("[}-----TestOS---<>{]", 1)
        time.sleep(0.1)

    lcd.lcd_init()

    for x in range(0,120):
        lcd.lcd_byte(0xFF,True)

    time.sleep(5)
    lcd.lcd_init()

def Menu():
    global menupressed
    menupressed = True
    lcd.lcd_init()
    lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
    lcd.lcd_string("hi", 1)
    lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
    lcd.lcd_string("hi", 1)
    time.sleep(5)
    menupressed = False

def clock():
    if(menupressed):
         return #when menu button is pressed, return - dont show nothing on display
    lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
    lcd.lcd_string("+------------------+", 1)
    lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
    lcd.lcd_string(time.strftime("|%I:%M %p          |"), 1)
    lcd.lcd_byte(lcd.LCD_LINE_3, lcd.LCD_CMD)
    lcd.lcd_string(time.strftime("|%a, %b %d, %Y |"), 1)
    lcd.lcd_byte(lcd.LCD_LINE_4, lcd.LCD_CMD)
    lcd.lcd_string("+------------------+", 1)
    time.sleep(1)
    lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
    lcd.lcd_string("+------------------+", 1)
    lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
    lcd.lcd_string(time.strftime("|%I %M %p          |"), 1)
    lcd.lcd_byte(lcd.LCD_LINE_3, lcd.LCD_CMD)
    lcd.lcd_string(time.strftime("|%a, %b %d, %Y |"), 1)
    lcd.lcd_byte(lcd.LCD_LINE_4, lcd.LCD_CMD)
    lcd.lcd_string("+------------------+", 1)
    time.sleep(1)

GPIO.add_event_detect(11, GPIO.FALLING, callback=Menu, bouncetime=100)

start()
try:
    while True:
        clock()

finally:
    lcd.lcd_init()
    lcd.GPIO.cleanup()
    GPIO.cleanup()

Hope it was helpful


text:
Q: Conversion failed when converting date and/or time from character string [The error disappear with top (xxxx)] Environment:

*

*SQL Server 14 Express on Ubuntu 16.04

*SQL Server Management Studio v 17.4

I observed a very wearied question but I believe there is an explanation. When I attempted to run the following SQL command:
SELECT *
FROM
    (SELECT
         CONVERT(DATE, clinicaldate, 6) AS NEWDATE,
         [id],
         [DateCreated] ...
     FROM
         myDatabase) t1
WHERE
    t1.newdate BETWEEN CONVERT(DATETIME, '01/09/2015', 103)
                   AND CONVERT(DATETIME, '30/09/2015', 103)

I get the following error:

Incorrect syntax near the keyword 'convert'

However, if I use top (XXX) in select, everything works fine. Please notice that the total record is less than 500000, which means I actually select all of them.
SELECT *
FROM
    (SELECT TOP(500000)
         CONVERT(DATE, clinicaldate, 6) AS NEWDATE,
         [id],
         [DateCreated] ...
     FROM
         myDatabase) t1
WHERE
    t1.newdate BETWEEN CONVERT(DATETIME, '01/09/2015', 103)
                   AND CONVERT(DATETIME, '30/09/2015', 103)

A: You have an invalid date in the column.  It is not in the rows chosen when you use top, so the problem is rare.
Don't use convert() on constants.  Just use:
WHERE  t1.newdate BETWEEN '2015-09-01' AND '2015-09-30'

Easier to write and read.  (One caveat:  There is one internationalization setting where you need to drop the hyphens).
Then, find the problematic dates using try_convert():
select clinicaldate
from t
where try_convert(DATE, clinicaldate, 6) is null;

You can fix your data error by using try_convert() rather than convert(), but it is better to fix the data.


text:
Q: Identifying multiple (graphical) object's edges from points I've got an application which is identifying motion in a webcam image. It produces something like the following...

Areas in black indicate motion. This is largely done on a per-pixel basis (although nearby pixels are taken into account)
So... Now that I've got a movement true/false for each pixel, I need to use that information to identify object outlines.
What I'd like is something like the following.

Outlines don't have to be precise and I could accept a bounding box. There are also some areas of noise which are more visible if I show you both combined...

As you can see there are a couple of "movement" pixels outside the objects. Presumably, I'd eliminate these by specifying a minimum area for an object.
So, what algorithm(s) are there for identifying the edges of objects. Ideally, I'd then be able to use this information to calculate the approximate center of each object.
Note: As mentioned by @mmgp, the images above are all full RGB, even the B&W one. This is due to the way I'm generating the image for export. Internally, it's a Bit array.

A: This seems to be a perfect task for Mathematical Morphology. To remove the small objects that, in this case, is a form a noise, perform a morphological opening by area. The area is easily estimated in your problem, as the interest regions are much larger than the unwanted ones. Now you also want to eliminate holes inside the large objects (notice there are some of these in your example). To do this you perform a operation that is called hole filling, which will simply discard those points that cannot be reached from the background of your image. At this point you can proceed to detect the centroids of your objects, but if you want to make the borders of your objects more uniform, you can use morphological dilations with small structuring elements or maybe morphological closing to possibly preserve more of the object.
These tasks are performed in Matlab as:
f = imread('http://i.stack.imgur.com/DexHs.png');
% The PNG is in RGB, but it actually describes a binary image.
f = ~im2bw(f, 0);
g = bwareaopen(f, 100); % 100 is the maximum area for unwanted objects here
h = imfill(g, 'holes');
l = bwlabel(h);
cent = regionprops(l, 'centroid');

Which results in:

The two closed white curves are the boundaries of the remaining objects and in yellow you see their centroids. If you want a "softer" boundary as described in the initial comments of this answer:
h1 = imclose(h, strel('disk', 3));

I see you tagged this as .net, but I would expect these tools to be readily available in some .net package as they are very basic and common.

A: My advice is for you to use emgu (opencv) for those tasks, it is a bit more complex than matlab has you probably know, but it is faster.
OpenCV has erode and dilate morphology operations implemented for you:
http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=morphology#dilate
http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=morphology#erode
Or morphologyex suitable for more generic morphology operations:
http://docs.opencv.org/modules/imgproc/doc/filtering.html?highlight=morphology#morphologyex
It also has the findContours function, you can think of it as a blob detector. In your case you could feed it your first image (probably after some noise-removing pre-processing) and it will return you those shapes. Those returned shapes are very easy to filter by area, if needed.
findContours docs:
http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#findcontours


text:
Q: Editing protected Custom Metadata Type in subscriber org through LMA org I do have verified that the Protected custom settings are editable when logged in through LMA org. However, I just want to confirm this behavior is the same in the case of the protected Custom Metadata Type records.
Also, the metadata record is upgradable via Package/Patch release?

A: Good question - and based on a quick test now, I believe the answer is no - you cannot see/edit protected Custom Metadata in an subscriber org when you login via LMA Org. The only CMD objects I can see are ones marked as public by the package
But to answer the second question, yes, you can add/update CMD records via package upgrade process if they are marked as protected in the package
There are limitations to be aware of though:
https://help.salesforce.com/articleView?id=custommetadatatypes_req_managed_pkgs.htm&type=5
And make sure to read the ISV Guide for full details about what is upgradeable and deleteable:
https://resources.docs.salesforce.com/220/latest/en-us/sfdc/pdf/salesforce_packaging_guide.pdf


text:
Q: Webmatrix session_destroy() I have written a simple code for $_SESSION variable in the first php file:
 <?php
    session_start();
    $_SESSION["name"] = "John";
 ?>

and in another php file to render this:
  <?php
      session_start();
      echo $_SESSION["name"];
   ?>

But after that i used session_unset(); and session_destroy(); and after that i can't render any new $_SESSION variable nor the existing one. I am using Microsoft WebMatrix program and Chrome as main browser. Any suggestions? Thank you in advance.

A: That is because session_destroy(); destroys the current session and also sends a header to the browser to delete the session variable. In the same time the session is deleted on the server (in PHP) and the $_SESSION variables can no longer be used. You can always try to save the $_SESSION in another variable;
session_start();
$_SESSION['test'] = 'foo';

Next page:
session_start();
$saveSession = $_SESSION;
session_destroy();
var_dump($_SESSION); //Gives an empty array
var_dump($saveSession); //Still has ['test' => 'foo']

More information: http://php.net/manual/en/function.session-destroy.php and http://php.net/manual/en/book.session.php
Also, sidenote, you do not need to open and close PHP tags if they are combined;
  <?php
  session_start();
  echo $_SESSION["name"];
  ?>

works just as well as
  <?php
  session_start();
  ?>
  <?php
  echo $_SESSION["name"];
  ?>


text:
Q: Using multiple model fields to regroup list in Django template I'm using the regroup tag in a Django template to list a number of items, grouped by Customer. My model is:
class Customer(models.Model):
  name = models.CharField(max_length=25)
  city = models.CharField(max_length=25)

I can list the items customer.name (or customer.city), by what I really want is to order them as "Name, City". According to the documentation "Any valid template lookup is a legal grouping attribute for the regroup tag, including methods, attributes, dictionary keys and list items." [1] How to I define a method for this? And how do I call it from my template?
[1] https://docs.djangoproject.com/en/dev/ref/templates/builtins/
Update: As i understand the regroup functionality, and are using it now, I group the list using one of the object's fields. The separator, customer.grouper, displays the name of that particular field. In my case "customer.name" or "customer.city". My goal is to present this together, like "customer.name, customer.city" (i.e. "Microsoft, Redmond"). The documentation mentions this briefly but I cannot figure it out.
def display_name(self):
  return "%s, %s" (self.name, self.city)

I have tried a method like above, as part of my Customer model, to fix my problem. But I'm not sure how to call it from my template.

A: Your model function is correct but it should contain a % before the braces:
def display_name(self):
  return "%s, %s" %(self.name, self.city)

Your view should pass a list of objects and not values.
Let the list be tp, so your template code should be something like this:
{% regroup tp by display_name as tp_list %}

{% for t in tp_list %}

{{ t.grouper }}

        {% for item in t.list %}
            <...something of your code....>
        {% endfor %}

{% endfor %}

This should work out for you well enough.


text:
Q: create a bar like the dock bar in SWF flash format by adobe flash cc I want to create a Mac-OS style of dock bar (see image below) in SWF format by using Adobe Flash CC.

A: ITS  been a while me used actionscript but i think you should make a Scroll add all elements to the scroll. See ScrollControl
And if you have all icons in a array you can always change the scaling of one element in front and one back and of the element. Detecting MouseEvents you can check if the mouse is over it or no.
 //FOR FINDING SCREENSIZE
var _stage:Stage=this.stage;
function displaySettings(): void {
        _stage.align = StageAlign.TOP_LEFT;
        _stage.scaleMode = StageScaleMode.NO_SCALE;
        _width = _stage.stageWidth;
        _height = _stage.stageHeight;

        if (_height < _width) {
            var num: Number = _height;
            _height = _width;
            _width = num;
        }

    }
    //for scaling the object according to height
    public function scalingheight(clip: Object, percent: Number) {
        var ratio = clip.width / clip.height;
        clip.height = percent * _height;
        clip.width = clip.height * ratio;
    }

    //Scale according to width
    public function scalingwidth(clip: Object, percent: Number) {
        var ratio = clip.height / clip.width;
        clip.width = percent * _width;
        clip.height = clip.width * ratio;
    }

Please do a bit more research before asking a question it would be appreciated.