text:
Q: Roomba not responding to roombacomm I've got a Discovery series iRobot Roomba and an iRobot Create USB cable. I've hooked them up to my Ubuntu 10.04 laptop. The roombacomm software recognizes the /dev/ttyUSB0 connection, and when I send commands the cable's LEDs light up, but the Roomba is unresponsive :( The software has the message: "Checking for Roomba... No Roomba. :(  Is it turned on?" (The Roomba is turned on.)
The software has the same error message if the Roomba is not plugged into the Create cable. The cable does not light up when the Roomba is not plugged in. The cable lights up in the middle when it's plugged in to the Roomba, and on one side when a command is issued through the roombacomm GUI. So the GUI must have the correct port and be talking to the cable.
Do you have any troubleshooting tips? Are there any alternative software libraries I could try?
Thanks!
--Erin

A: Perhaps you're using the wrong port.  These instructions at iRobotReviews suggest using a higher numbered port to avoid conflicts.

A: Not all Discovery series Roombas have the Open Interface installed.
http://en.wikipedia.org/wiki/Roomba#Hacking_and_extending_Roomba
If you're sure that your Roomba can be programmed, try using a terminal program. Turn on Roomba while listening with the terminal program at 57600 bps (8n1). You'll see a stream of data. To test outgoing data, send a 128 (number, not ascii). You should hear a beep from the Roomba.
If your Roomba doesn't respond to a 128, you may need to acquire a "Hacker Osmo". You can still get them from various third parties.


text:
Q: Change the text color for all print command I'm using python 3 to build my system. I want to change all the print commands in my code to print in the same color.
I'm familiar with colorama and the option to print in different color using
print(%s Hello World % colorama.Fore.BLUE)

Is there any option to define the color of the print only once?
I'm using Ubuntu 16.04 and python 3.5

A: How about using something like this:
import colorama

def colorprint(text):
    print("{}{}".format(colorama.Fore.BLUE,text))

colorprint("123")

Or multiple colors:
import colorama

d = {"blue":colorama.Fore.BLUE,
     "black":colorama.Fore.BLACK,
     "yellow":colorama.Fore.YELLOW}

def colorprint(text,color):
    c = d[color]
    print("{}{}".format(c,text))

colorprint("123","yellow")

redpajama_set_name: RedPajamaStackExchange


text:
Q: CRM 2011 plugin to check whether an Account has a parent I'm writing a plugin in C# for Dynamics CRM 2011 (On Prem).
The plugin is to prevent grandfathering in Account records (Accounts can have children OR a parent, but not both at the same time).
I'm struggling to check whether the Account has an associated parent or not, the attribute for parent ID is always null and I don't understand why.
I've correctly generated the early bound classes using crmsvcutil.exe and added the file to my project.
The generated code for the parent ID looks like this:
/// <summary>
/// Unique identifier of the parent account.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("parentaccountid")]
public Microsoft.Xrm.Sdk.EntityReference ParentAccountId
{
    get
    {
        return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("parentaccountid");
    }
    set
    {
        this.OnPropertyChanging("ParentAccountId");
        this.SetAttributeValue("parentaccountid", value);
        this.OnPropertyChanged("ParentAccountId");
    }
}

A basic version of my plugin looks like this:
namespace NoGrandparentAccounts
{
    using CRM2011GeneratedBusinessModel; // Namespace for crmsvcutil generated early bound classes
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using System;
    using System.ServiceModel;

    public class Main : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // OBTAIN EXECUTION CONTEXT
            var context(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // TRACING SERVICE FOR LOGGING
            var tracingService =
            (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // WILL REPRESENT THE CURRENT ENTITY
            Entity entity = null;

            // INPUTPARAMETERS COLLECTION CONTAINS ALL DATA PASSED IN THE MESSAGE REQUEST
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                // SET ENTITY TO THE CURRENT ENTITY
                entity = (Entity)context.InputParameters["Target"];

                // CHECK WE'RE IN ACCOUNTS ENTITY
                if (context.PrimaryEntityName != "account")
                    return;

                // CHECK WE'RE CREATING OR UPDATING THE ENTITY
                if (context.MessageName != "Create" && context.MessageName != "Update")
                    return;
            }
            else
            {
                return;
            }

            try
            {
                // GET ORGANIZATION SERVICE
                var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = serviceFactory.CreateOrganizationService(context.UserId);

                // GET CURRENT ACCOUNT
                var account = entity.ToEntity<Account>();

                // HAS A PARENT ACCOUNT?
                var hasParent = (account.ParentAccountId != null && account.ParentAccountId.Id != Guid.Empty);
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                tracingService.Trace($@"Exception: {ex.Message} - {ex.StackTrace}");
                throw new InvalidPluginExecutionException(@"An error occurred in the plugin.", ex);
            }
            catch (Exception ex)
            {
                tracingService.Trace($@"Exception: {ex.Message} - {ex.StackTrace}");
                throw new InvalidPluginExecutionException(@"An error occurred in the plugin.", ex);
            }
        }
    }
}

Unfortunately hasParent is always false because account.ParentAccountId is null. I don't know why because there is most definitely a parent account associated with this record and the attribute name is definitely parentaccountid.

The call to find the child Accounts works fine using parentaccountid:
// FETCH CHILDREN
var cExpr = new ConditionExpression("parentaccountid", ConditionOperator.Equal, account.Id);
var qExpr = new QueryExpression(Account.EntityLogicalName);
qExpr.ColumnSet = new ColumnSet(new string[] { "accountid" });
qExpr.Criteria.AddCondition(cExpr);
var results = service.RetrieveMultiple(qExpr);

// HAS CHILDREN
var hasChildren = results.Entities.Count > 0;

The entity count shows correctly as 3 and therefore hasChildren is true.
I've checked whether the attributes for this entity contains parentaccountid and it returns false which I assume is related to the problem:
if (entity.Attributes.Contains("parentaccountid"))
{
    // Never gets here as this is false!?
}

What am I doing wrong?

A: The Target entity itself contains only basic entity identity data.  If you want to access attributes for the entity you should configure a suitable PreImage or PostImage with the attributes that you want to access context.PreEntityImages, and you can then retrieve this via context.PreEntityImages or context.PostEntityImages.  Alternatively (and less optimally) you can retrieve the latest version of the entity from within the PlugIn with the attributes you desire.

A: Do this
 // GET CURRENT ACCOUNT
 var account = (Account)service.Retrieve("account", entity.Id, new ColumnSet(new string[] { "accountid", "parentaccountid" }));

Instead of this
// GET CURRENT ACCOUNT
var account = entity.ToEntity<Account>();

As Josh Painter indicated in his comment, its possible that the event you registered against isn't passing in this value to the PluginExecutionContext.InputParameters["Target"], and thus the attribute becomes null when casting the Entity to an Account.  Above is how to do a query to get the full record within the plugin, and that will always be populated, unless the plugin is registered pre-stage create (in which case your current code will work just fine, but since you're getting a null value, I assume you're not registering on pre-stage create).


text:
Q: How to fix this scala jar error "Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/sql/types/DataType" The scala spark object runs good when it is run in intelliJ. But after building artifact and executing as jar, I am getting this error below.

Exception in thread "main" java.lang.NoClassDefFoundError:org/apache/spark/sql/types/DataType

How to fix this? Appreciate your inputs on this.
IntelliJ IDEA:

jar file generated by File>Project Structure>Project Setting>Artifacts> + > Jar > from modules with dependencies
  Check Box "Include in project build" selected
  Apply > OK
  Tab:Build>Build Artifacts>poc:jar>Build

Jar Error:

build.sbt
name := "poc"
version := "0.1"
scalaVersion := "2.11.12"
libraryDependencies ++= Seq(
  "org.apache.spark" % "spark-core_2.11" % "2.4.3",
  "org.apache.spark" % "spark-sql_2.11" % "2.4.3",
  "com.datastax.spark" % "spark-cassandra-connector_2.11" % "2.4.1",
  "org.apache.hadoop" % "hadoop-aws" % "2.7.1"
)

poc.scala
import org.apache.spark.sql.types.{ IntegerType, StringType, StructField, StructType}
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.SparkSession

object dataload {
  def main(args: Array[String]): Unit =
  {
    val awsAccessKeyId: String     = args(0)
    val awsSecretAccessKey: String = args(1)
    val csvFilePath: String        = args(2)
    val host: String               = args(3)
    val username: String           = args(4)
    val password: String           = args(5)
    val keyspace: String           = args(6)

    println("length args: " + args.length)

    val Conf = new SparkConf().setAppName("Imp_DataMigration").setMaster("local[2]")
      .set("fs.s3n.awsAccessKeyId", awsAccessKeyId)
      .set("fs.s3n.awsSecretAccessKey", awsSecretAccessKey)
      .set("fs.s3n.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem")
      .set("spark.cassandra.connection.host", host)
      .set("spark.cassandra.connection.port","9042")
      .set("spark.cassandra.auth.username", username)
      .set("spark.cassandra.auth.password", password)

    val sc = new SparkContext(Conf)
    val spark = SparkSession.builder.config(sc.getConf).getOrCreate()

    val schemaHdr = StructType(
      StructField("a2z_name", StringType) ::
        StructField("a2z_key", StringType) ::
        StructField("a2z_id", IntegerType) :: Nil
    )

    val df = spark.read.format( source = "csv")
      .option("header", "true")
      .option("delimiter", "\t")
      .option("quote", "\"")
      .schema(schemaHdr)
      .load( path = "s3n://at-spring/a2z.csv")

    println(df.count())

    df.write
      .format( source = "org.apache.spark.sql.cassandra")
      .option("keyspace","poc_sparkjob")
      .option("table","a2z")
      .mode(org.apache.spark.sql.SaveMode.Append)
      .save

    sc.stop()

  }

}

A: Spark applications are typically submitted via the spark-submit script. It is possible to to submit jobs using java -jar ..., but you will have a much more difficult time dealing with classpath issues, as you see to be experiencing right now.
Relatedly, you will want to mark your Spark/Hadoop dependencies as "provided", e.g. "org.apache.spark" % "spark-core_2.11" % "2.4.3" % "provided", as spark-submit will locate and add the necessary .jar files to the classpath from your local install.

A: Fixed this issue by building a fat jar using sbt assembly.
This post helped me
How to build an Uber JAR (Fat JAR) using SBT within IntelliJ IDEA?


text:
Q: JQuery variable received via dropdown not applying css I understand that it is possible to use a variable as the css property to be applied by jQuery (using .css('property',variable)) but for some reason the variable that is successfully got is not being put into the css.
Here is the JQuery code that I have:
    $('#color-scheme').change(function(){
      var colorScheme = $('#color-scheme').val();
      $('.wppw-title-font-color').css('color','');
      $('.wppw-background-color').css('background-color','');
      $('.wppw-title-font-color').css('color',colorScheme);
      $('.wppw-background-color').css('background-color',colorScheme);
      console.log(colorScheme);
    });

A demo of the project I am currently doing can be found here:
http://codepen.io/zephyr/pen/ipsHu
I want the user to be able to change the styles of my fancybox via the menu that I have created. (I'd only want to be using JQuery to do this open to suggestions on changes that I can do on the menu as well to more easily get the desired result.)
Thanks!
Thanks for the replies, turns out I was a dunce and didn't remove the !important on the css properties, my bad!

A: It is not working because of the !important rules attached to the things you are trying to change. Try this instead:
$('#color-scheme').change(function(){
  var colorScheme = $(this).val();
  $('.wppw-title-font-color').css('cssText', 'color: ' + colorScheme + ' !important;');
  $('.wppw-background-color').css('cssText', 'background-color: ' + colorScheme + ' !important;');
  console.log(colorScheme);
});

There are also other ways to do this, have a look at this question.
EDIT:
To make this work for your font selection, you need to remove the semi-colons (;) from the end of the values in the select.

A: The issue may be in your css you have given color as important.
.wppw-title-font-color:hover {color: #660000 !important;}
try remove !important;
.wppw-title-font-color:hover {color: #660000}
OR
in you jquery try like this.
$('#color-scheme').change(function(){
  var colorScheme = $('#color-scheme').val() +" !important";
  $('.wppw-title-font-color').css('color','');
  $('.wppw-background-color').css('background-color','');
  $('.wppw-title-font-color').css('color',colorScheme);
  $('.wppw-background-color').css('background-color',colorScheme);
  console.log(colorScheme);
});


text:
Q: DDD (Domain Driven Design), how to handle entity state changes, and encapsulate business rules that requires large amount of data to be processed public class Person
{
    public IList<String> SpecialBirthPlaces;
    public static readonly DateTime ImportantDate;
    public String BirthPlace {get;set;}

    public DateTime BirthDate
    {
        set
        {
            if (BirthPlace!=null &&
                value < ImportantDate &&
                SpecialBirthPlaces.Contains(BirthPlace))
            {
                BirthPlace = DataBase.GetBirthPlaceFor(BirthPlace, value);
            }
        }
    }
}

This is an attempt to encapsulate a simple rule in my domain model. The rule I'm trying to capture is: when, for some reason, we update a person's birth date (e.g. there was a mistake in the original user input) we need to check the person's birthplace and replace it with some other value from a database, if it is listed in our database as a special birthplace.
However, I have 2 problems implementing it:

*

*This rule modifies domain entity state (property) and I need to reflect this change in the user interface. My domain model is POCO. I could put this logic in the ViewModel, but this is wrong because it's not UI logic. It's an important domain rule which I need to capture.

*My list of SpecialBirthPlaces is pretty big and I don't want to populate it every time I get a customer from database. Also, I need to get a replacement for Birthplace when the rule is satisfied. As I said the list of special birthplaces and replacements for this is very big and is stored in the DB.
How to implement the logic I need in DDD style?

A: The way I've encapsulated this problem, which is modification tracking, is with the Unit of Work pattern. I have my DDD repositories associated with a unit of work, and I can query the unit of work for any set of entities which I get from any of the repositories to see which are modified.
As for the large collection, it appears to be a read-only set. One way to handle this is to preload and cache this locally if it is ever accessed, then the repositories can run queries against the in-memory version. I use NHibernate, and it is easy to handle this case with it. If it is way too big to store in RAM (like 100s of MB or more), you'll probably need to special case repository queries against it, so that the SpecialBirthPlaces.Contains(BirthPlace) query is executed on the database (perhaps in a stored proc, ha!). You'd probably want to express SpecialBirthPlaces as a repository of entities, rather than just a big collection of strings, which would allow the "Query" pattern to free you from needing to load the entire thing.
After this lengthy narrative, here's some example:
public class BirthPlace
{
    public String Name { get; set; }
}

public class SpecialBirthPlace : BirthPlace
{
}

public class Person
{
    public static readonly DateTime ImportantDate;
    public BirthPlace BirthPlace { get; set; }

    public DateTime BirthDate
    {
        get; private set;
    }

    public void CorrectBirthDate(IRepository<SpecialBirthPlace> specialBirthPlaces, DateTime date)
    {
        if (BirthPlace != null && date < ImportantDate && specialBirthPlaces.Contains(BirthPlace))
        {
            BirthPlace = specialBirthPlaces.GetForDate(date);
        }
    }
}

Having a method where you pass in the corrected birth date is a better design since it tells you via the parameters what is needed to actually correct the birth date: a repository (i.e collection) of SpecialBirthPlace entities and the correct date. This explicit contract makes it clear what the domain is doing, and makes the business needs clear just by reading the entity contracts, where putting the whole collection in the state of the entity hides it.
Now that we've made BirthPlace into an entity, we can see that there may be one more optimization to make the domain model a bit flatter. We don't really need to specialize BirthPlace but we do need to indicate if it is special. We can add a property to the object (some people begrudge properties on domain objects, but I don't, since it makes queries easier, especially with LINQ) to indicate if it is special. Then we can get rid of the Contains query altogether:
public class BirthPlace
{
    public BirthPlace(String name, Boolean isSpecial = false)
    {
        Name = name;
        IsSpecial = isSpecial
    }

    public String Name { get; private set; }
    public Boolean IsSpecial { get; private set; }
}

public class Person
{
    public static readonly DateTime ImportantDate;
    public BirthPlace BirthPlace { get; set; }

    public DateTime BirthDate
    {
        get; private set;
    }

    public void CorrectBirthDate(IRepository<BirthPlace> birthPlaces, DateTime date)
    {
        if (BirthPlace != null && date < ImportantDate && BirthPlace.IsSpecial)
        {
            BirthPlace = birthPlaces.GetForDate(date);
        }
    }
}

A: I think the statements "I need to reflect this change in the user interface" and "It's an important domain rule which I need to capture" describe two different problems. Clearly, the first one needs to be solved; it isn't clear that the second one does.
If other parts of your domain model need to know about changes here, you would do well to have a look at Domain Events (for example, Udi Dahan's implementation). You could also use this to set the BirthPlace property when the BirthDate gets set, even asynchronously if it is a potentially lengthy operation.
Otherwise, let's just look at the UI issue. First of all, in my domain model, I would have each entity abstracted as an interface. If you don't, then you may need to at least make some properties virtual. I'd also be using a layer of abstraction for generation/returning my entities, such as IoC/factory/repository. I consider this layer to be outside the bounds of the domain model itself.
Now, we need a mechanism to notify the UI of changes to properties in domain entities, but of course the domain model itself is in a sense a closed system: we don't want to introduce new members or behaviours to satisfy the needs of any outside concern.
What if we decorate the entity in question with an implementation that implements INotifyPropertyChanged? We could do this in our repository, which we've established is outside the bounds of the domain, so we would not be modifying the domain model itself, only using composition to wrap the entities with functionality that the system outside the domain model needs. To restate, the recalculation of BirthPlace remains a concern of the domain model, while the UI notification logic remains a concern outside of the domain model.
It would look something like this:
public class NotifyPerson : IPerson, INotifyPropertyChanged
{
    readonly IPerson _inner;

    public NotifyPerson(IPerson inner) // repository puts the "true" domain entity here
    {
        _inner = inner;
    }

    public DateTime BirthDate
    {
        set
        {
            if(value == _inner.BirthDate)
                return;

            var previousBirthPlace = BirthPlace;
            _inner.BirthDate = value;
            Notify("BirthDate");

            if(BirthPlace != previousBirthPlace)
                Notify("BirthPlace");
        }
    }

    void Notify(string property)
    {
        var handler = PropertyChanged;
        if(handler != null) handler(this, new PropertyChangedEventArgs(property));
    }
}

If not using interfaces, you would simply inherit from Person and override the BirthDate property, calling members on base instead of _inner.

A: The following is a sample implementation. This implementation consists of several layers: the domain layer, the service layer and the presentation layer. This purpose of the service layer is to expose the functionality of your domain layer to other layers, such as the presentation layer or a web service. To that end, its methods correspond to specific commands that can be processed by the domain layer. In particular we have the command to change the birthday. Furthermore, this implementation uses Udi Dahan's version of a domain event framework. This is done to decouple the domain entity from the business logic associated with changing the birthday. This can be regarded as both a benefit and a drawback. The drawback is that your overall business logic is spread across multiple classes. The benefit is that you gain a lot of flexibility in how you handle domain events. Additionally, this approach is more extensible, since you can add subscribers to the BirthDateChangedEvent which perform auxiliary functions. Yet another benefit, (which contributed to the reasoning behind Udi's implementation) is that your Person entity no longer needs to be aware of any repositories, which seem outside the scope of the domain entity. Overall, this implementation calls for quite a bit of infrastructure, however if you envision investing greatly into your domain then it is worth the initial trouble. Also note, that this implementation assumed an ASP.NET MVC based presentation layer. In a stateful UI, the presentation logic would need to change and the ViewModel would need to provide change notifications.
/// <summary>
/// This is your main entity, while it may seem anemic, it is only because
/// it is simplistic.
/// </summary>
class Person
{
    public string Id { get; set; }
    public string BirthPlace { get; set; }

    DateTime birthDate;

    public DateTime BirthDate
    {
        get { return this.birthDate; }
        set
        {
            if (this.birthDate != value)
            {
                this.birthDate = value;
                DomainEvents.Raise(new BirthDateChangedEvent(this.Id));
            }
        }
    }
}

/// <summary>
/// Udi Dahan's implementation.
/// </summary>
static class DomainEvents
{
    public static void Raise<TEvent>(TEvent e) where TEvent : IDomainEvent
    {
    }
}

interface IDomainEvent { }

/// <summary>
/// This is the interesting domain event which interested parties subscribe to
/// and handle in special ways.
/// </summary>
class BirthDateChangedEvent : IDomainEvent
{
    public BirthDateChangedEvent(string personId)
    {
        this.PersonId = personId;
    }

    public string PersonId { get; private set; }
}

/// <summary>
/// This can be associated to a Unit of Work.
/// </summary>
interface IPersonRepository
{
    Person Get(string id);
    void Save(Person person);
}

/// <summary>
/// This can implement caching for performance.
/// </summary>
interface IBirthPlaceRepository
{
    bool IsSpecial(string brithPlace);
    string GetBirthPlaceFor(string birthPlace, DateTime birthDate);
}

interface IUnitOfWork : IDisposable
{
    void Commit();
}

static class UnitOfWork
{
    public static IUnitOfWork Start()
    {
        return null;
    }
}

class ChangeBirthDateCommand
{
    public string PersonId { get; set; }
    public DateTime BirthDate { get; set; }
}

/// <summary>
/// This is the application layer service which exposes the functionality of the domain
/// to the presentation layer.
/// </summary>
class PersonService
{
    readonly IPersonRepository personDb;

    public void ChangeBirthDate(ChangeBirthDateCommand command)
    {
        // The service is a good place to initiate transactions, security checks, etc.
        using (var uow = UnitOfWork.Start())
        {
            var person = this.personDb.Get(command.PersonId);
            if (person == null)
                throw new Exception();

            person.BirthDate = command.BirthDate;

            // or business logic can be handled here instead of having a handler.

            uow.Commit();
        }
    }
}

/// <summary>
/// This view model is part of the presentation layer.
/// </summary>
class PersonViewModel
{
    public PersonViewModel() { }

    public PersonViewModel(Person person)
    {
        this.BirthPlace = person.BirthPlace;
        this.BirthDate = person.BirthDate;
    }

    public string BirthPlace { get; set; }
    public DateTime BirthDate { get; set; }
}

/// <summary>
/// This is part of the presentation layer.
/// </summary>
class PersonController
{
    readonly PersonService personService;
    readonly IPersonRepository personDb;

    public void Show(string personId)
    {
        var person = this.personDb.Get(personId);
        var viewModel = new PersonViewModel(person);
        // UI framework code here.
    }

    public void HandleChangeBirthDate(string personId, DateTime birthDate)
    {
        this.personService.ChangeBirthDate(new ChangeBirthDateCommand { PersonId = personId, BirthDate = birthDate });
        Show(personId);
    }
}

interface IHandle<TEvent> where TEvent : IDomainEvent
{
    void Handle(TEvent e);
}

/// <summary>
/// This handler contains the business logic associated with changing birthdates. This logic may change
/// and may depend on other factors.
/// </summary>
class BirthDateChangedBirthPlaceHandler : IHandle<BirthDateChangedEvent>
{
    readonly IPersonRepository personDb;
    readonly IBirthPlaceRepository birthPlaceDb;
    readonly DateTime importantDate;

    public void Handle(BirthDateChangedEvent e)
    {
        var person = this.personDb.Get(e.PersonId);
        if (person == null)
            throw new Exception();

        if (person.BirthPlace != null && person.BirthDate < this.importantDate)
        {
            if (this.birthPlaceDb.IsSpecial(person.BirthPlace))
            {
                person.BirthPlace = this.birthPlaceDb.GetBirthPlaceFor(person.BirthPlace, person.BirthDate);
                this.personDb.Save(person);
            }
        }
    }
}

A: IMO the best approach performance-wise would be to create a stored procedure in your db and mark entity on property changed event to invoke it when committing changes to db (SaveChanges() call). ObjectContext.ExecuteFunction is your friend in that case.
Put all your logic of birthplace lookup and update in that sproc. Make sure sproc is included in the transaction - so that changes are rolled back if update fails.
Edit:
Sorry for not DDD related answer.


text:
Q: Jenkins failing to send e-mail to group mail Id but works on individual Id When my build fails, Jenkins is sending an email to individual email id's but when I am using group id its not sending an email to all the individuals listed under that group.
All the global settings are configured correctly.

A: Email-ext 2.38 is latest version i was using the same and it is working perfectly for me to send mail to a group_id.Upgrade your Email-ext plugin and check.


text:
Q: How to extract elements from `head` section of HTML string? I have a variable (s) which holds entire HTML document (as a string). I would like to extract some elements from its head section. With body it is not a problem, I pack entire data into jQuery variable and call find.
But with head section is different story. When I pack it to jQuery object I can see it creates an array for it, and I see the elements I would like to extract (so to this point it works as I would wish). But when I run find against it, jQuery ignores head and its content entirely.
So how to extract the elements from the head?
Just for the record, currently I am trying to extract link nodes to get urls for CSS files.

A: For top level elements in your DOM, it seems you have to use filter() instead of find().
var html = $.parseHTML('<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><link rel="stylesheet" href="/css/inuit.css"><link rel="stylesheet" href="/css/inuit.css"><link rel="stylesheet" href="/css/inuit.css">');

$(html).filter("link").each(function(i, link) {
    alert(link);
});

This alerts the three links from the string.

A: For the URL of your CSS files, this regexp should do the trick:
var patt = /.*<link(.*href="(.*)"|.*rel="stylesheet"|.*type="text\/css"){1,}.*>.*/gi;
var array_of_ccs_files = head_as_str.match(patt);
for (var i = 1; i < array_of_ccs_files.length; ++i) {
    console.log(array_of_ccs_files[i]);
}

A: You can just query the jQuery object for it...
var sHtmlString = ....;
var oDom = $(sHtmlString);
oDom.find("head > link");


text:
Q: Google BigQuery API Python I am trying to generate queries in python and querying with them. I am working with pandas_gbq. My code looks like this:
def generate_query(
    filter=['CENTRAL BANK','DRAGHI','FRANKFURT'],
    date ='20171214',
    datetimeformat='%Y%m%d',
    weekly_data=True
):
    filter = str(filter).replace('[','').replace(']','')
    if weekly_data == False:
        query = '''SELECT * FROM `gdelt-bq.gdeltv2.events` WHERE SQLDATE = {date}'''.format(date = date)
    else:
        date = datetime.datetime.strptime(date, datetimeformat)
        week = generate_week(date)
        query = '''SELECT * FROM `gdelt-bq.gdeltv2.events` WHERE SQLDATE IN ({week})'''.format(
            week = week).replace('[','').replace(']','')
    return query, date

Did not figure how to indent the code on stackoverflow. The problem occurs when trying to query multiple dates:
'SELECT * FROM `gdelt-bq.gdeltv2.events` WHERE SQLDATE IN (\\'20171211\\', \\'20171212\\', \\'20171213\\', \\'20171214\\', \\'20171215\\')'

I have no idea where the backslashes are coming from. Any idea why this is happening?
The function generate_week:
def generate_week(date):
week = []
referenceday = date - datetime.timedelta(days = date.weekday())
for i in range(0,5):
    day = referenceday + datetime.timedelta(days = i)
    week.append(day.strftime('%Y%m%d'))
return week

The returned error is the following:
pandas_gbq.gbq.GenericGBQException: Reason: 400 No matching signature for operator IN for argument types INT64 and {STRING} at [1:55]

I would be extremely thankful for some help here! :)

A: I believe your issue is with the date format. Unless you specify otherwise standard BQ expects yyyy-mm-dd format. Read more here. If you use strftime("%Y-%m-%d") that should be enough.
Also worth pointing out that:

*

*If you use tuples instead of lists, SQL will share the same syntax as the Python, so you could avoid replacing the square brackets (makes life easier).

*You can use SQL's BETWEEN with the beginning and ending dates (inclusive) instead of listing every date if its a continuous, sequential time period.

*If you're using Python 3.6+ f-strings are a little nicer than .format in this case. Including the change in bullet 1 (but not bullet 2), you could instead write:
f'''SELECT * FROM `gdelt-bq.gdeltv2.events` WHERE SQLDATE IN {week}'''


text:
Q: Spring component scan error(schema_reference.4: Failed to read schema document 'https://www.springframework.org/schema/beans/spring-beans-4.3.xsd') I have created a simple dynamic project without maven in eclipse. Only when I use tag context:component-scan, I face below error in Spring dispatcher file :-
schema_reference.4: Failed to read schema document 'https://www.springframework.org/schema/beans/spring-beans-4.3.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root
 element of the document is not .
Not sure from where version 4.3 is refered. I am using spring version 5.0.0.RELEASE and have added all jars in lib. Below is the content of spring dispatcher file :-
<?xml version="1.0" encoding="UTF-8"?>

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        <context:component-scan base-package="com.example.controller"/>
        </beans>

I cant find fix for this issue. Suitable help will be appreciated.

A: There are many possibilities for this problem.

*

*Initially you added ..../spring-beans-4.3.xsd and then you removed the version but error is still showing. It is because eclipse is reading from cache. Try removing cache in prefences->General->Network->cache

*Even if you project is not maven, right click on the project go to properties and add "Maven Dependencies" in your Build Path. This resolved the similar error for me once.

*If the above two does not work for you, try copy pasting this code

<?xml version="1.0" encoding="utf-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:ctx="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd ">

    <ctx:annotation-config></ctx:annotation-config>
    <ctx:component-scan base-package="com.*"></ctx:component-scan>


text:
Q: Fatal error creating an order in Prestashop I'm calling to a Prestashop Webservice with a petition like this:
<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<order>
    <id_address_delivery>1999</id_address_delivery>
    <id_address_invoice>1999</id_address_invoice>
    <id_cart>12102</id_cart>
    <id_currency>1</id_currency>
    <id_lang>1</id_lang>
    <id_customer>1728</id_customer>
    <id_carrier>282</id_carrier>
    <module>cheque</module>
    <payment>NTPM</payment>
    <total_discounts>0</total_discounts>
    <total_paid>4.7999996</total_paid>
    <total_paid_real>4.7999996</total_paid_real>
    <total_products>4.7999996</total_products>
    <total_products_wt>4.363636</total_products_wt>
    <conversion_rate>1</conversion_rate>
    <associations>
        <order_rows>
            <order_row>
                <product_id>12</product_id>
                <product_quantity>1</product_quantity>
            </order_row>
        </order_rows>
    </associations>
</order>
</prestashop>

I've checked that If I send all the fields the same error is returned. Only:
Fatal error

The cart, the address, the customer and the product exist. The article is the same in the cart and is active and has stock too.
The Prestashop version is 1.6.

A: Today I experience the same error and the solution for us was setting to the cart the id of the created customer and also the secure_key. Because PaymentModule class check if secure_key from customer and content->cart->secure_key fields match before create the order.
I hope these can help.


text:
Q: how to select multiple static rows with one SQL query in mysql We all know that:
select 1,2,3

will give us:
|1|2|3|

However, what I want to get is:
|1|
|2|
|3|

I am aware that it can be achieved by "union"s like:
select 1 union select 2 union select 3

And WITHOUT the temporary table or predefined table.
Is there any better solution? Thanks.

A: Your solution is basically fine, but you should use union all:
select 1 union all select 2 union all select 3

union incurs overhead for removing duplicates, and you don't want to do that.
An alternative solution would be to use a numbers table, if you have one handy.
Another solution would be to take any sufficiently large table and use:
select (@rn := @rn + 1) as n
from t cross join
     (select @rn := 0) params
limit 3;

This is handy if you want to expand to larger numbers.

A: Your UNION version is perfectly fine. As alternative with MariaDB 10.3.3 or later you can use VALUES:
VALUES(1),(2),(3);

db<>fiddle


text:
Q: Could I override the grails.env during runtime Grails seems to build the artefacts per env.
with the command "grails -Dgrails.env=test war
Is it possible for me to override the running environment programmatically?
The issue here is that we produce the war file using production env config. But I want to run the same war file in other environments, like Test, Staging, DR etc.
There are two options:
1. set grails.env in command line
2. programmatically set the current env in the code.
I wonder how could I achieve option2. Our deploy script is shared, not grails specific. There is a generic environment variable named SYSTEM is passed in command line. If I could map that env to the grails.env in code, that would be idea.


text:
Q: How do I add a bash module to my startup profile?
*

*How do I install the bash module that came in the zipfile that appears in this page?

http://ss64.com/pass/command-line.html

*

*How do I install any module (not necessarily in startup profile)?

*How do I install modules from Github?

Many thanks

A: First, in this case, extract the module from the Zip file to your home directory:
#   pipe from-zipfile          a-contained-file         to    a-new-file
unzip -p strongpw.zip strongpw_bash_module/strongpw.bash > ~/strongpw.bash

Then add the following line to your ~/.bashrc file:
. ~/strongpw.bash

The contents of ~/.bashrc are run at the start of every new interactive bash shell.  The . FILENAME causes ~/.bashrc to also include that file within the new shell allowing it to define functions there, in this case strongpw.


text:
Q: How array works internally in Java? This query is posted to basically understand points like

*

*An object is class instance or an array;

*An array is a subclass of Object class;

*Everything that is instantiated other than primitive is an object in Java.
Here is my understanding of working with arrays in Java.
Considering the below program,
/* dummy.java */
class C {
    private int i;
    public C() {
        i = 1;
        System.out.println("Am in constructor");
    }
}
public class dummy {
    public static void main(String[] args) {
        C[] c = new C[2]; // Line 11
        c[0] = new C();
        System.out.println(c);
    }
}

An object of type class [LC is created in run-time after running,
C[] c = new C[2]; //Line 11

In the above code. class [LC is an immediate subclass of Object class. Reference variable c points to this object (shown in red boundary below) after running Line 12 in the above code. Reference variables sit in stack and an object of type class C will go in heap.

For a below change of line 11 & 12 in the above code
C[][] c = new C[2][2];
c[0][0] = new C();

will make the representation as shown below.

Is my understanding correct? If yes, Can you please explain more on usage of class [LC in run time to instantiate an object?
Note: C[].class gives the actual type in run-time, which is class [LC.

A: To answer your question: yes, in Java (and C#), nearly everything is split into multiple discrete chunks of memory accessed by pointers.  This not only include your bidimensional array but also any embedded object inside your object C.  In C++, if you have an array (single dimensional or not) of 10 objects and each of these object contains 10 embedded objects, you can allocate all this with a single piece of memory.  In C# and Java, you will have a minimum of 101 memory allocations for storing all this (if all of the embedded objects are simple objects) in the case of a mono-dimensional array and more in the case of a multi-dimensional array.
However, this explosion of pieces of memory shouldn't be seen a something very bad because it's free you of the difficulty of managing yourself the allocation of memory as you can have with C/C++ and in most cases, the power of any modern CPU is generally sufficient to pull it forward at a sufficient speed.


text:
Q: How to edit a label thats in a different scene in Xcode
*

*Yes there is already a similar question but it does not give me an answer

Back Story - feel free to skip
I have been creating a game where you have to stop 'monsters' getting past your characters by firing projectiles at them, this is all (finally) working perfectly.
Problem
However, I tried to create a coin counter that would be shown whenever the scene 'flips' back to the start screen (its called playScene and the actually game is called GameScene). I was wondering how I can create a counter that is edited in a different scene to where the scoring happens?

A: You have 2 scenes: GameScene and ScoreScene.
ScoreScene is the scene where player gets redirected after he dies. Like a lost scene where you show his stats. We start by creating a global variable called score and set it default to 0.
class ScoreScene: SKScene {

    let score : Int = 0

    override func didMove(to view: SKView)
    {
        print("Score = \(score)")  // Score = 0
    }
}

User enters in the GameScene, kills monster and then he dies at score 87. Before presenting the ScoreScene, you pass the score.
class GameScene: SKScene {

    func change_scene()
    {
        let transition = SKTransition.flipVertical(withDuration: 0.75)
        let next_scene = ScoreScene() // at this point, score = 0
        next_scene.score = 87         // at this point, score = 87
        self.view?.presentScene(next_scene!, transition: transition)
    }
}

You can pass values from a scene to another by creating a global value in our case score and giving it a value before you presentScene.


text:
Q: How do I select from IF(....) as 'A' Sorry I Don't know what to say it.
It was like
SELECT

(IF(ISNULL(fieldA),'it is null','fieldA')) AS 'I_want_this',

'I_want_this' as 'Show'

from table

A: Is it:
select
   case when fieldA is NULL then 'It is null' else fieldA as I_Want_This
from Table

?

A: You can use COALESCE(). It will print the value of first parameter if it's not null other will print second parameter.
Schema and insert statements:
 create table tableA(fieldA varchar(10));
 insert into tableA values(null);
 insert into tableA values('a');
 insert into tableA values('b');
 insert into tableA values(null);
 insert into tableA values('c');

Query:
 SELECT COALESCE(fieldA,'it is null') AS 'I_want_this'
 from tableA

Output:

I_want_this

it is null

a

b

it is null

c

db<>fiddle here


text:
Q: Making my Artificial Intelligence visuals that react with sound change So basically I have created an A.I assistant and was wondering if anyone had suggestions on how to make visuals that react with the sound?

A: You can just measure the loudness of the voice command spoken in mDb. You can then process these numbers to change the UI.
Like , higher the loudness makes the bar longer. Let me know which speech to text engine are you using so that I can provide further help.


text:
Q: OpenStack: Can I convert a volume into an image? I am trying to figure out the path of least resistance in OpenStack to get from a live CD to a disk image that can be used for deploying new guest instances.
If you boot an OpenStack instance from a live CD, you can install an OS onto the "ephemeral" disk (which will, in this case, be /dev/vda)...
...that's great, but there's no way to create an image from that disk; the image-create command will attempt (and fail) to snapshot the live CD itself (because this is the boot volume).
You can create and attach a new volume (using volume-create and volume-attach) and then install the OS on that, but there's doesn't appear to be any way to convert this volume into a Glance-hosted image for use by other instances.
As an administrator I can obviously log in to the storage host and create a new glance image directly from the volume block device, but this isn't an avenue available to anyone interacting via the API or web GUI.
Are there any other options available?

A: In Icehouse and later you can convert Cinder volume to Glance image with upload-to-image command:
cinder upload-to-image <volume> <image-name>

A: I've successfully built images for openstack using KVM on my local linux machine using a local disk image file (raw or qcow2), converted the image file to a compressed qcow2, and uploaded that with glance.
Some tips:

*

*you'll need cloud-init or an /etc/rc.local script or similar to fetch the instance metadata (ssh keys, IP address, hostname, userdata, etc) from http://169.254.169.254/ and configure the VM with it.
cloud-init works best on ubuntu, but has been ported to Debian, and I've even seen a port for RH.

*Cleaning up the image (erasing logs and shell history, disabling passwords, deleting /etc/udev/rules.d/70-persistent-net.rules, and so on) and zero-filling the disk image before making a compressed qcow2 to upload is a good idea.  You can quite easily shrink a VM image with a 10GB disk to 300-500MB, which is faster to upload and faster to copy when openstack launches an instance.
The simplest way to zerofill the disk is something like 'dd if=/dev/zero of=/root/junk ; rm -f /root/junk'.  Alternatively, you can shutdown the VM, loopback mount it (you can use qemu-nbd if the image is already a qcow2), and then zerofill it.  If the filesystem is ext2/3/4 you can use a tool called zerofree to zerofill it (must be unmounted or mounted RO).  If it's some other fs you could use sfill from secure-delete (secure-delete's home page has vanished).
BTW, even if your 'source' image is already compressed qcow2, it's still worthwhile 'converting' it to a fresh compressed qcow2 before uploading. That gets rid of the old data left behind when a file is copied-on-write.

A: Simple way to convert cinder volume to glance image convert LVM partition to qcow2 format with qemu-img.
Example:
sudo qemu-img convert -c -f raw -O qcow2 /dev/stack-volumes/volume-6e4eb1d5-71fa-45a1-9178-ac6611351404 test.img

Next step add image to glance:
glance image-create --name test_converted --disk-format qcow2 --container-format bare < test.img

A: This is an old question, but what you want to do is use kvm to make a raw disk image using the cdrom iso file and an empty volume.  Then, you can upload the raw disk to glance and use it to boot others.
This is how you make a base Debian, Ubuntu or other linux host, for example.


text:
Q: $\text{Cocone}(D,Y)\simeq \mathscr C(X,Y)\implies X=\text{colim} D$ I'm transferring here the discussion from the comments in this question.
The problem is as follows: Suppose $D:I\to \mathscr C$ is a diagram (= functor) and suppose there's a bijection $$\text{Cocone}(D,Y)\simeq \mathscr C(X,Y)$$
between the cocones on $D$ with vertex $Y$ and arrows $X\to Y$, and this bijection is natural in $Y$. How to prove that $X=\text{colim} D$? The definition of colimit can be found here (p. 126).
I understand how to prove the reverse implication, but the implication described above is unclear.
Consider a cocone $(f_i:D(i)\to Y)_{i\in I}$. We know that there is a unique arrow $\bar f:X\to Y$. That's all I can do. For example, it's not clear what the coprojections $D(i)\to X$ are.

A: I'll follow tkf's hint.
Suppose we have a bijection $$\text{Cocone}(D,Y)\simeq \mathscr C(X,Y)$$ that is natural in $Y$.
Let's write $$\text{Cocone}(D,Y)\to\mathscr C(X,Y)$$ as $$(f_i)_{i\in I}\mapsto \bar f$$ and its inverse $$\mathscr C(X,Y)\to \text{Cocone}(D,Y)$$ as $$g\mapsto (\widehat g_i)_{i\in I}$$
We show that $((\widehat {1_X})_i: D(i)\to X)_{i\in I}$ is a limit cocone on $D$ in $\mathscr C$. Suppose $(f_i:D(i)\to Y)_{i\in I}$ is a cocone on $D$ in $\mathscr C$. We know that there exists a unique $\bar f:X\to Y$. To prove that $((\widehat {1_X})_i: D(i)\to X)_{i\in I}$ is a limit cocone, it remains to prove that $\bar f\circ (\widehat{1_X})_i=f_i$ for all $i\in I$.
To this end, we use the naturality of the given bijection in $Y$ with respect to $\bar f:X\to Y$. This naturality amounts to saying that the following diagram commutes:

Since bar and hat are inverses of each other, the equality at the bottom says $$(\bar f \circ (\widehat{1_X})_i)_{i\in I}=(f_i)_{i\in I}$$
implying that $\bar f\circ (\widehat{1_X})_i=f_i$ for all $i\in I$.


text:
Q: Computed Custom Property Won't Show on Page in Polymer I'm trying to get a calculated property on the page in my project, and nothing seems to be working. I'm getting the sum of some values from my Firebase database, and I'm trying to return it as the value of a custom property. I know the function itself works, but it's not showing the returned value. Is there something that I'm not doing correctly, or something I can change? Thanks!
Here's where the value is supposed to be showing (the countedWords property):

[[theProject.title]]

[[theProject.author]]

[[theProject.category]] [[theProject.genre]]

Word Count: {{countedWords}} of [[theProject.goal]]

And here is the property and the function to return the value:
properties: {
  ...
  countedWords: {
    type: String,
    computed: '_countedWords(pattern)'
  }
},

_countedWords: function(pattern) {
  // var pathname = window.location.pathname;
  // var project = pathname.substring(pathname.lastIndexOf('/'));
  // var projId = project.substring(1);
  var total = 0;
  var keys = [];
  var counts =[];

  var ref = firebase.database().ref().child('/scenes/' + pattern).orderByChild('wordcount');
  ref.once('value', function(snap) {
    snap.forEach(function(item) {
      var itemVal = item.val();
      keys.push(itemVal);
    });

    for (i=0; i < keys.length; i++) {
      counts.push(keys[i].wordcount);
    }

    function getSum(total, num) {
        return total + num;
    }

    total = counts.reduce(getSum);
    words = total.toString();
    console.log(words);
    return words;
  });
},

A: Your computed property's function isn't actually returning anything. The return words statement returns a value to the callback to ref.once() (which actually has no effect) instead of to _countedWords(). Since the result of ref.once() is async, you'll have to switch from the computed property to an observer on pattern that sets this.countedWords.
Polymer({
  properties: {
    pattern: String,
    countedWords: {
      type: Number,
      value: 0
    }
  },

  observers: ['_countedWords(pattern)'],

  _countedWords: function(pattern) {
    // ...
    ref.once('value', function(snap) {
      // ...
      this.countedWords = words;
    }.bind(this));
  },

  // ...
});


text:
Q: How to convert from String to Enum dynamically? I'm trying to build a dynamic wrapper that uses reflection to access properties of objects. My approach works with different kinds of objects – but I still have an issue with Enums.
Let's assume I already have the proper setter und getter and I want to invoke them in different situations. For example I'm trying to save a given value via the following code:
public void save() {
    try {
        // Enums come in as Strings... we need to convert them!
        if (this.value instanceof String && this.getter.getReturnType().isEnum()) {

            // FIXME: HOW?

        }
        this.setter.invoke(this.entity, this.value);
    }
    catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
        throw new RuntimeException("Die Eigenschaft " + this.property + " von Entity " + this.entity.getClass().getSimpleName() + " konnte nicht geschrieben werden!", ex);
    }
}

How can I convert the String object to the proper Enum value?
I know about MyEnum.valueOf(String)... but what if I can't name the Enum in my source code? I've not managed to use something like
this.value = Enum.valueOf(this.getter.getReturnType(), this.value);

A: Given a Enum class and a string value you can convert to the Enum object corresponding to the string via the following static method defined in java.lang.Enum:
static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)

e.g.
java.awt.Window.Type type = Enum.valueOf(java.awt.Window.Type.class, "NORMAL");

Note that Enum.valueOfthrows an IllegalArgumentException if there is no corresponding enum constant.
You can't invoke Enum.valueOf without a cast from your method, since getter.getReturnType() is a Class<?>.
So a helper function might handle the cast:
@SuppressWarnings("unchecked")
private static <E extends Enum<E>> E getEnumValue(Class<?> c, String value)
{
     return Enum.valueOf((Class<E>)c, value);
}

and you just use it in your code:
if (this.value instanceof String && this.getter.getReturnType().isEnum())
     this.value = getEnumValue(getter.getReturnType(), (String)this.value));

Note that any solution which loops over Enum.getEnumConstants() will create a temporary array for the constants, whereas Enum.valueOf uses an internal cache.

A: Just found one way... but it seems "dirty"... any better?
if (this.value instanceof String && this.getter.getReturnType().isEnum()) {
    for (Object v : this.getter.getReturnType().getEnumConstants()) {
        if (v.toString().equals(this.value)) {
            this.value = v;
            break;
        }
    }
}


text:
Q: Sampling model / likelihood using Poisson distribution in Bayesian inference? I'm trying to solve a problem/question from my professor. The problem/question is we want to know the proportion of the population in city A who is infected with COVID-19. For that, an examination was taken on 500 people. Of the 500 people, 10 were infected with COVID-19. The problem will be solved using Bayesian inference. My professor state that the sampling model/likelihood that must be used is Poisson distribution.
But I am very confused about the PDF (Probability Density Function) form of the Poisson distribution for this problem and how to determine its parameters as well as the description of the parameters. Because in my opinion there is no known information about the time or space for the problem, so I don't think Poisson distribution is the right sampling model/likelihood to choose.
Can anyone help me in determining the PDF form and the description of the parameters of the Poisson distribution?

A: Each person is either infected (with probability $p$) or not infected. Thus it follows Bernoulli distribution. Then the probability that the number of infected persons among the population of $n$ follows binomial distribution. When $n$ is large and $p$ is small, the binomial distribution approaches (or is well approximated by) Poisson distribution with $\lambda = np$.


text:
Q: How to catch SIGTERM in a pod with Minikube I'm using the simplest docker ever:
FROM ubuntu
COPY script.sh /script.sh
CMD /script.sh

Where all the script does is:
#!/bin/bash

function sigterm() {
    echo "Got SIGTERM"
    exit
}

trap sigterm SIGTERM

i=1
while true; do
    echo "$(date +%H:%M:%S) | $((i++)) | $HOSTNAME"
    sleep 1
done

I'm running this container in Minikube, but I can't get it to catch any SIGTERM from kubernetes.
I tried deleting the pod/deployment or to scale it up and down. In no case it got SIGTERM before being deleted. It respects the terminationGracePeriodSeconds But doesn't seem to run the preStop command or send the SIGTERM before killing the pod.
Is that due to using minikube? or am I doing something else wrong?
(the deployment is not part of a service, it's just a deployment)
(SSH into the pod and manually kill-ing it works as expected)

A: Reading the Dockerfile documentation on CMD

The CMD instruction has three forms:

*

*CMD ["executable","param1","param2"] (exec form, this is the preferred form)

*CMD ["param1","param2"] (as default parameters to ENTRYPOINT)

*CMD command param1 param2 (shell form)

If you use the shell form of the CMD, then the  will execute in /bin/sh -c

So you are using the shell form, which means your command is /bin/sh -c script.sh. Then, when kubernetes sends a SIGTERM to the container, is not the script.sh process the one receiving the signal, but the /bin/sh process. That's why you don't see the "Got SIGTERM" message.
When creating a Dockerfile, make sure you use the exec form. Otherwise the application will be started as a subcommand of /bin/sh -c, which does not pass signals. The container's PID1 will be the shell, your application will not receive any signals.
Try changing your Dockerfile to use the exec form
FROM ubuntu
COPY script.sh /script.sh
CMD ["/script.sh"]


text:
Q: R: what is 'adjusted by' in survival analysis? male_data:
          surgery   age   cancer  survival
a00001        yes  <=50        0        10
a00002        yes   >50        1        15
a00003        no    >50        0         2
.
.
.
.

Result:
Call:
coxph(formula = Surv(survival, cancer) ~ surgery + age, data = male_data)

n= 550517, number of events= 3276

               coef  exp(coef) se(coef)    z  Pr(>|z|)
surgery:yes   -0.03    0.97     0.04   -0.88   0.377
age:>50        3.26   26.09     0.04    78.5  <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

             exp(coef)   exp(-coef)   lower .95   upper .95
surgery:yes      0.97         1.03          0.9        1.04
age:>50         26.09         0.04        24.05       28.3

Concordance= 0.817  (se = 0.005 )
Likelihood ratio test= 7607  on 2 df,   p=<2e-16
Wald test            = 6182  on 2 df,   p=<2e-16
Score (logrank) test = 13993  on 2 df,   p=<2e-16

Now I need to fill the result in a new form. But I do not know what "adjusted by" means. Can I find this value in the result? I would appreciate any advice!

A: In any observational study, you need to define clearly your exposure and outcome of interest. It seems that your exposure of interest is whether the patient had surgery or not and the outcome either the incidence of cancer or death from cancer. If this is the case, your results are adjusted by age.
You are the only person who can answer this question! It truly depends on the research question and the underlying causal structure you are thinking about.


text:
Q: WHS 2011, how to extend existing 2nd sub tab? In the SDK, there is a sample on how to extend an existing tab. If I deploy this sample in the "Server Folders and Hard Drives" tab, this custom extension will be applied to the "Server Folders" only.
How do I extend the second tab, "Hard Drives"?

A: Well, darn it. It's a limitation by design.


text:
Q: VB.NET: ExecuteReader(CommandBehavior.CloseConnection) hangs after running SQL Query I am trying to execute a SELECT SQL statement which returns a value to me. The following is my code to Get the value from the SQL select statement.
Private objSQLHelper As SQLHelper

Private Const SQL_Error_Query = "SELECT field1 FROM TESTTBL WHERE field1ID = @field1ID;"

Public Function GetField1(ByVal field1ID As Integer) As Boolean
    Dim sdr As SqlClient.SqlDataReader = Nothing
    Dim sqlParams As New ArrayList
    Dim resultBool As Boolean

    sqlParams.Add(New SqlClient.SqlParameter("field1ID", SqlDbType.Int))
    sqlParams(0).value = field1ID

    sdr = objSQLHelper.sdrExecuteReader(sqlConnectionString, CommandType.Text, SQL_Error_Query, sqlParams)

    While sdr.Read()
        resultBool = CBool(sdr("field1"))
    End While

    sqlParams.Clear()

    Return resultBool
End Function

Inside the sdrExecuteReader function, the code always gets stuck at the line with CommandBehavior.CloseConnection. For the above GetField1 function, this simple SELECT query statement caused this. However, other SELECT queries that belong to other files is working and they also call the same sdrExecuteReader function. Thus, I am unsure why for the GetField1 function the code hangs at the line with CommandBehavior.CloseConnection. Below is how the sdrExecuteReader function looks like:
Public Function sdrExecuteReader(ByVal sqlConnectionString As String, ByVal commandType As CommandType, ByVal commandString As String, ByVal sqlParams As ArrayList) As SqlClient.SqlDataReader
    Dim sqlCommand As New SqlClient.SqlCommand
    Dim sqlConnection As SqlClient.SqlConnection = Nothing

    Try
        openingConnection = New SqlClient.SqlConnection(sqlConnectionString)
        PrepareCommand(sqlCommand, sqlConnection, Nothing, commandType, commandString, sqlParams)

        ' Code always gets stuck or hangs at this line
        sdrExecuteReader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection)
    End Try
End Function

Questions:

*

*Does anyone know why this happens? I do not wish to change my sdrExecuteReader function as much as possible because many functions rely on it.

*Is there anything I can write in my GetField1 function to debug or anything I can include to fix the code inside that function?

*If qns 1 and 2 cannot be answered, what are the reasons that this is happening?

Note: When I change SQL_Error_Query to "SELECT field1 = 1" (basically hard coded), it works. Possibly the sql connection is not working? but other select queries are working though...

A: you can enclose lines with try/catch and use debugger. have a look to PrepareCommand : problem can be in SQL connexion, in Query or in parameter.
as I don't know SQLHelper wrapper, I test your query by using standard SQLclient. this is the code (tested OK). maybe help you to investigate.
Imports System.Data.SqlClient

    Public ConnSQL As New SqlConnection("your connexion string;")
    Const SQL_Error_Query = "SELECT field1 FROM TESTTBL WHERE field1ID = @field1ID;"

    Public Function GetField1(ByVal field1ID As Integer) As Boolean

        Dim resultBool As Boolean

        Dim sqlParams As New SqlParameter
        sqlParams.ParameterName = "field1ID"
        sqlParams.SqlDbType = SqlDbType.Int
        sqlParams.Value = field1ID

        ConnSQL.Open()
        Try
            Dim cmdSQL As New SqlCommand(SQL_Error_Query, ConnSQL)
            cmdSQL.Parameters.Add(sqlParams)
            Dim sdr As SqlClient.SqlDataReader = cmdSQL.ExecuteReader()
            While sdr.Read()
                resultBool = CBool(sdr(0))
            End While
        Catch ex As Exception
        End Try

        ConnSQL.Close()

        Return resultBool
    End Function

A: In sdrExecuteReader instead of returning the sqldatareader directly to the caller, create a dataset that holds the data and return another datareader that references this dataset. Try this and see if it resolves your issue.


text:
Q: Gitlab-ci: how to run python script with cl arguments I want to run a python script, which expects cl arguments, before the actual build, so I added the following piece in .gitlab-ci.yml:
.deploy_template: &template_name
  variables:
  - arg1: "https://some/url/"
  - arg2: "https://another/url/"
  - arg3: "https://one/more/url/"
  script:
  - python3 some/script/file.py $arg1 $arg2 $arg3

but I am getting the following error:
usage: file.py [-h] arg1 arg2 arg3

file.py: error: the following arguments are required: arg1 arg2 arg3

If the arguments are just strings (i.e. not variables), then it works fine, but it does not read the variables $arg1 etc.
In the gitlab docs it is mentioned, that I can use the bash syntax to supply variables, so $arg1 must the correct reference.
I use argparse in the script to get the cl arguments.
What is the correct way to call the variables in gitlab-ci.yml as the python script arguments?

A: Your variables is a list, but it requires a dictionary. Just remove the - from it.
.deploy_template: &template_name
  variables:
    arg1: "https://some/url/"
    arg2: "https://another/url/"
    arg3: "https://one/more/url/"
  script:
  - python3 some/script/file.py $arg1 $arg2 $arg3

More about yaml syntax


text:
Q: ipyleaflet heatmap intensity not reflecting correctly Say I have a list of 5 locations with coordinates, and each location has a number I want to show on a heatmap, so I can visualize which loation has most 'hits'. For example
Location 1: x,y,80

Location 2: x,y,1

Location 3: x,y,20

Location 4: x,y,40

Location 5: x,y,30

I'm creating the heatmap by adding the location to the heatmap with the intensity set to the number of times the count is, so
heatmapLocations = []
for location in locations
                heatmapLocations.append((x,y,count))
heatmap = Heatmap(locations=heatmapLocations)

My heatmap is showing, and it shows the highest count as a red circle, so that's correct, also location 3 with count 20 is shown as light yellow, which is also correct, but location 4 and 5 are shown the same as location 1, especially when I zoom in, as if they have the same density, although there value is half of location 1. How can I reflect this? I tried the different heatmap parameters as max_zoom, radius, etc, but can't seem to get it right.


text:
Q: Trigger to update field value in one table from another that get insertion I have an SQL database table named ItemMenu with 5 fields named: PLU (primary key), description, size, price, department. This table is populated with active records.
Now, I created another table with only 2 fields, one of which is called PLU and the other is Price. This new table is named Price_import and gets its records from an MS Access linked table whenever I want to send records to SQL table ItemMenu.
I am trying to create a trigger that would update only the price of a certain PLU in the ItemMenu every time I send that change to the Price_import table in SQL. Once the the price is updated in the ItemMenu table I would like to have records cleared from the Price_import table automatically if possible, but it is not that important. I am just an enthusiast who wants to know how SQL works, therefore; would appreciate some help with this.

A: MyDatabase        set ANSI_NULLS ON
        set QUOTED_IDENTIFIER ON
        GO
--This trigger is attached to the Price_Import Table so when this table gets new price values the trigger will update the price of such items in the Mydatabase MenuItem Table which is the main item table in Mydatabase
     ALTER TRIGGER [dbo].[trgafterinsertinto_Price_Import_Table] ON [dbo].[Price_Import]
AFTER INSERT
    AS
    BEGIN
    SET NOCOUNT ON;

-- update your table, using a set-based approach
-- from the "Inserted" pseudo table which CAN and        -- WILL
-- contain multiple rows!
     UPDATE [dbo].[MenuItem]
SET [Price] = i.[Price] ,[Cost] = i.[Cost]
    FROM Inserted i
   WHERE MenuItem.PLU = i.PLU
   DELETE FROM dbo.Price_Import
   END


text:
Q: CASE expression for two unique values being compared to another table Using SQL-Server 2008 / T-SQl
Background:
My query seeks to compare codes assigned to across two versions (highest value vs next highest).  The versions are assigned to the same ID (i.e. they are versions of that ID).  However, the final piece in the jigsaw (where I am struggling) is to see if the code was assigned to another version of the same ID other than the previous version.  The way the dataset is built (through use of temp tables) is so that the previous version will never have the same code as the current version.
Table 1:
ID | CurVer | CurCode | PrevVer | PrevCode |
------------------------
 1  |   4   | 1234    |   3     |   4321

Basically, although 1234 is assigned to version 4 but not to 3, I want to run a yes/no or 1/0 checker on another table, table 2, to see if was assigned to versions 1 or 2 of the same ID.
Table 2:
     ID | Ver   | Code
    ------------------------
     1  |   1   | 1234
     1  |   2   | 4321
     1  |   3   | 4321
     1  |   4   | 1234

So, what I want to do is join table 2 to table 1 and introduce a column to table one which gives a '1' if the code is assigned to versions which are not the CurVer in table 2.
My query goes like this:
SELECT  DISTINCT
t1.ID
,t1.CurVer
,t1.CurCode
,t1.PrevVer
,t1.PrevCode
    ,(Case WHEN
    t1.ID = t2.ID AND t1.CurVer != t2.Ver and t1.CurCode = t2.Code THEN 1
    ELSE 0
    END)
FROM #table1 as t1
LEFT JOIN #table2 as t2 ON t1.ID = t2.ID

Without the distinct it will list the results four times for the four versions in table2, with '1's against the matching codes.  The DISTINCT gives me a dataset of:
 ID | CurVer | CurCode | PrevVer | PrevCode | Checker
-----------------------------------------------------
 1  |   4   | 1234    |   3     |   4321    |   1
 1  |   4   | 1234    |   3     |   4321    |   0

I don't want the '0' entries to appear, only the '1'. Obviously if there were no other match in t2 it just shows a 0.  This works for the other IDs (there's only one line) as there's no '1' to handle.
I would be grateful for any ideas on how to not show the '0' values and just show the '1's when the code is found against versions before the PrevVer.  Please also note I am doing this over a dataset of nearly 4000 IDs.

A: You can get the output by below query with ignoring 0 and showing only 1 value :
SELECT DISTINCT
                         t1.ID, t1.CurVer, t1.CurCode, t1.PrevVer, t1.PrevCode, (CASE WHEN t1.ID = t2.ID AND t1.CurVer != t2.Ver AND t1.CurCode = t2.Code THEN 1 ELSE 0 END)
                         AS Expr1
FROM            table1 AS t1 LEFT OUTER JOIN
                         table2 AS t2 ON t1.ID = t2.ID
WHERE        ((CASE WHEN t1.ID = t2.ID AND t1.CurVer != t2.Ver AND t1.CurCode = t2.Code THEN 1 ELSE 0 END) > 0)

A: This is the answer to the stated question
And you probably don't need the ditinct
SELECT DISTINCT
       t1.ID
      ,t1.CurVer
      ,t1.CurCode
      ,t1.PrevVer
      ,t1.PrevCode
      ,1 as 'checker'
  FROM #table1 as t1
  JOIN #table2 as t2
    ON t1.ID = t2.ID
   AND t1.CurVer != t2.Ver
   and t1.CurCode = t2.Code;


text:
Q: Java, How to collect filtered out values in Spark My Input is a collection of strings, Say :
Chicago
Washington
Seattle
San Francisco
Chicago
Newyork
Dallas

I have the below code which filters out certain values:
        List<String> filteredValues =  new ArrayList<String>();
        JavaRDD<String> filteredOutput = inputText.filter(line -> {

                if(line.toLowerCase().contains("chicago")) {
                    filteredValues.add(line);
                    return false;
                }
                return true;

        });
       System.out.println("Filtered values are" + filteredValues.toString());
    }
}

I expected "filteredValues" list to contain [Chicago, Chicago].
But its empty. Can someone help me out.

A: Spark is more functional, so updating a variable won't work.* You should use the output from the filter and call collect.
Also, you need to return true if you want to keep an item. It appears you've got this backwards.
*closed over variables are COPIED to each worker. So the updates are only the worker local copy.


text:
Q: How were they flying in Chronicle I know that they had telekinesis, but what were they moving? Were they moving themselves or some other way?

A: They were moving themselves.  Apparently their telekinesis is reactionless, which allows them to push heavy objects without having their bodies feel the equal and opposite reaction.  This also allows counter-intuitive things like them moving their own bodies with the telekinesis.  When they fly, this is what they're doing, using the telekinesis to lift themselves.


text:
Q: Get Connection's IP Address in SQL Server without VIEW SERVER STATE permission? Is there a way to get the IP Address of a connection without the user being in the SysAdmin Role or being granted VIEW SERVER STATE? One of these is required to issue this query:
select client_net_address from sys.dm_exec_connections where session_id = @@spid

I want to log the IP Address inside an Instead-Of Trigger, but I don't want to go granting the VIEW SERVER STATE permission to all users.
Thanks for any suggestions.

Followup 2013-10-05:
Thanks for the various comments. What are the dangers in granting VIEW SERVER STATE to all users?

A: You can set the trigger to execute as owner:
ALTER TRIGGER dbo.whatever_instead
ON dbo.whatever
WITH EXECUTE AS OWNER
INSTEAD OF INSERT
AS
BEGIN
  SET NOCOUNT ON;

  INSERT dbo.log_table(column1, ...)
  SELECT client_net_address, ...
    FROM sys.dm_exec_connections
    WHERE session_id = @@SPID;

  ... other stuff here I'm sure ...
END
GO

However, by default, you should get the following error:

Msg 15562, Level 16, State 1, Procedure whatever_instead
   The module being executed is not trusted. Either the owner of the database of the module needs to be granted authenticate permission, or the module needs to be digitally signed.
  The statement has been terminated.

One way to work around this is to set your database to TRUSTWORTHY:
ALTER DATABASE database_name SET TRUSTWORTHY ON;

Do not take this setting lightly:

*

*Guidelines for using the TRUSTWORTHY database setting in SQL Server

*The TRUSTWORTHY Database Property Explained – Part 1

A: CREATE PROCEDURE Some_Proc
WITH EXECUTE AS 'User_With_Permission'
AS
BEGIN
    SET NOCOUNT ON;
        select client_net_address from sys.dm_exec_connections where session_id = @@spid
END

Call this proc from your trigger


text:
Q: Decomposition and harmonic analysis of $L^2(S^n)$ Deitmar and Echterhoff write in their book Principles of Harmonic Analysis that `It follows from the Peter-Weyl theorem that the $SU(2)$ representation on $L^2(S^3)$ is isomorphic to the orthogonal sum $\oplus_{m\ge 0}(m+1)P_m$ where $P_m$ is the space of homogeneous polynomials of degree $m$.'
They provide no further explanation of this statement, so here is my attempt at understanding it: we can use the homeomorphism $SU(2)\simeq S^3$ and let $SU(2)$ act on $L^2(S^3)\simeq L^2(SU(2))$ by
$$(\pi(g)f)(x)=f(xg).$$
Since the group acting, namely $SU(2)$ is compact the Peter-Weyl theorem says that $L^2(S^3)$ decomposes as a hilbert space direct sum of irreducible representations, namely $(\pi_m, P_m)$ each appearing with multiplicity $\dim \text{Hom} (\pi_m, \pi)$. So it remains to prove that $\dim \text{Hom} (\pi_m, \pi)=m+1.$
Now my first question is whether computing the dimension of the space of intertwiners is elementary.
Second, are there any concrete applications for harmonic analysis on $S^3$ that this result might be helpful for?
Lastly, how can one come to grips with the decomposition of $L^2(S^n)$ for $n>3$?
Any (partial) answers to any of these questions is highly appreciated.

A: 1) Your formula for the decomposition of the regular representation is not the whole statement of the Peter-Weyl theorem.  It is part of the Peter-Weyl theorem that the multiplicity $\dim(Hom(\pi_m,\pi))$ in the regular representation equals the dimension of the representation $\dim(\pi_m)$ which is of course $(m+1)$.
2) Computation and properties of spherical harmonics is the most classical applications, and most others stem from that.  See below.
3)  In that case $S^n$ is not itself isomorphic to a Lie group; however, it is still a symmetric space $\textrm{SO}(n)/\textrm{SO}(n-1)$ and we can still use Peter-Weyl theory, only in a more delicate way.  Spherical harmonics arise here as well; see http://www.springer.com/cda/content/document/cda_downloaddocument/9781461479710-c1.pdf?SGWID=0-0-45-1445132-p175259457 for an introduction to these things.

A: Peter-Weyl says a bit more than even what guest states: it tells you how $L^2(G)$ decomposes under the natural $G \times G$ action given by multiplication by $g \in G$ on the left and multiplication by $g^{-1} \in G$ on the right. This decomposition is as a Hilbert space direct sum
$$\bigoplus_V V \boxtimes V^{\ast}$$
where $\boxtimes$ denotes the external tensor product and the direct sum runs over all irreducible representations of $G$. This is exactly what one expects from the finite case, since in the finite case $\mathbb{C}[G]$ is naturally isomorphic to the direct sum $\bigoplus_V \text{End}(V)$ of the endomorphism algebras of the irreducible representations of $G$. Restricting to one copy of $G$ gives the desired multiplicity result, that $V$ appears with multiplicity $\dim V^{\ast} = \dim V$.


text:
Q: Filter GeoJSON by attribute in Leaflet using a button I have a GeoJSON point layer group styled as a circle marker; it has a color attribute which can be one of many values: white, black, blue, red etc.
I want to create a filter based on that attribute, so I created a Bootstrap button with a Dropdown for a selection of four attributes.
I tried the built-in filter as pointed in this question,
var redcolor = L.geoJson(colors, {filter: redFilter})

function redFilter(feature) {
  if (feature.properties.hue === "red") return true
}

and assigning it to its respective button using jQuery:
$("#red").click(function(event) {
    event.preventDefault();
    if(map.hasLayer(redcolor)) {
        $(this).removeClass('selected');
        map.removeLayer(redcolor);
    } else {
        map.addLayer(redcolor);
        $(this).addClass('selected');
   }
})

but I don't want to create a separate layer group; the filtering should happen in the original one.

A: You need to create a grouplayer and from that you can add or remove the layer, in that way refreshing the data with the filter from the same dataset.
Here are two working examples: the first using buttons, the second radio buttons.
http://bl.ocks.org/zross/47760925fcb1643b4225
http://www.gistechsolutions.com/leaflet/DEMO/filter/filter.html

A: Here is an example of using a dropdown to filter out values in the geojson layer.
JS Bin: https://jsbin.com/sasojat/edit?html,js,output
There are many possible solutions, but this one works like this:

*

*Create a variable to store the layergroup and a variable to contain the filter-out value.
var dataLayerGroup;
var filterval = document.getElementById("filter").value;

*Write your filter function to test for not-matching the filter-out variable.
var colorFilter = function (feature) {
if (feature.properties.color !== filterval) return true}

*Create a function that deletes the layer if it exists, then adds it again.
function addLayerToMap(){
 //remove the layer from the map entirely
 if (map.hasLayer(dataLayerGroup)){
     dataLayerGroup.remove();
 }
 //add the data layer and style based on attribute.
 dataLayerGroup = L.geoJson(pointsData, {
     filter: colorFilter,
     pointToLayer: function(feature, latlng) {
         return new L.CircleMarker(latlng, {radius: 8, fillOpacity: 0.85});
     },
     onEachFeature: function (feature, layer) {
         layer.bindPopup(feature.properties.color);
     },
     style: function(feature){
         return{color:  feature.properties.markercolor};
       },
     }).addTo(map);
 }

*Create a listener for the filter input
 $("#filter").on("input", function(){
 filterval = document.getElementById("filter").value;
 console.log("the filter was changed to ", filterval);
 //add the layer to the map again, now that we have changed the filter value.
 addLayerToMap();
 });

*Call the function to add the layer to the map for the first time
 addLayerToMap();

I'm still slightly unclear on why you don't want to use separate layergroups for each filter option, like the links that Bill posted do, but maybe this alternative will help you.


text:
Q: How to decrypt OpenSSL Ruby encrypted file by using terminal openssl command? I am encrypting a file with AES-256-CBC with the help of OpenSSL:
# Encrypt a file with openSSL
require 'openssl'

class Encryptor

  def initialize
    @src_file = 'test.txt'
    @dst_file = 'test.enc'
    @key = "1234567890ABCDEF1234567890ABCDEF"
    @iv  = "1234567890ABCDEF"
    @algorithm = 'AES-256-CBC'
  end

  #
  def encrypt
    cipher = OpenSSL::Cipher.new(@algorithm)
    cipher.encrypt
    cipher.key = @key
    cipher.iv = @iv
    buffer = ""
    File.open(@dst_file,'wb') do |outf|
      File.open(@src_file, 'rb') do |inf|
        while inf.read(4096, buffer)
          outf << cipher.update(buffer)
        end
        outf << cipher.final
      end
    end
  rescue Exception => e
    "#{e}"
  end

end

enc = Encryptor.new
enc.encrypt

and then I am trying to decrypt it by using terminal:
openssl enc -aes-256-cbc -d -in test.enc -K "1234567890ABCDEF1234567890ABCDEF" -iv "1234567890ABCDEF" -out test_dec.txt

What I get is an error:
bad decrypt
29152:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-64/src/crypto/evp/evp_enc.c:330:

mostly known as "bad_decrypt".
I've tried with & without an iv, changing -k to -K, using -a, decrypt with base64 first among other things and of course nothing worked. Any ideas how to fix this ?


text:
Q: Extract longest word in string I would like to find and extract the longest word of a string, if possible using a tidyverse package.
library(tidyverse)

tbl <- tibble(a=c("ab cde", "bcde f", "cde fg"), b=c("cde", "bcde", "cde"))
tbl
# A tibble: 3 x 1
   a
<chr>
1 ab cde
2 bcde f
3 cde fg

The result I am looking for is:
# A tibble: 3 x 2
   a     b
  <chr> <chr>
1 ab cde   cde
2 bcde f  bcde
3 cde fg   cde

The closest post to the question I have found is this: longest word in a string. Does anyone have an idea for an even simpler way?

A: And here is a possible tidyverse version of @PoGibas's answer

library(tidyverse)
tbl <- tibble(a=c("ab cde", "bcde f", "cde fg"))

tbl %>%
  mutate(b = map_chr(strsplit(a, " "), ~ .[which.max(nchar(.))]))

#> # A tibble: 3 x 2
#>        a     b
#>    <chr> <chr>
#> 1 ab cde   cde
#> 2 bcde f  bcde
#> 3 cde fg   cde

A: Solution using base R:
# Using OPs provided data
tbl$b <- sapply(strsplit(tbl$a, " "), function(x) x[which.max(nchar(x))])

Explanation:

*

*Split each line into words (strsplit)

*Determine word length (nchar)

*Select which word is longest in line (which.max)


text:
Q: PostMessage call steals focus from siblings Good Evening.
I understand the question may seem kind of odd, so let me explain my problem a little bit : Ii'm building a Windows From Application, that is able to open multiple Child Form, each one containing a WebBrowser component that loads a Flash animaion.
Now, I need to simulate a click on a given opened form, without it showing up on top of every other. To simulate the click, I'm using a code quite similar to https://stackoverflow.com/a/11161632/533599 : I had to implement 2 changes

*

*I have to stop to the "Internet Explorer_Server" , since I don't
have a "MacromediaFlashPlayerActiveX" in the handles chain

*For the
    click to fire, I have to "make it double", that is, mouse down, up,
    down, up.

The code works quite well, and the click is fired, but everytime it does, the target Form gets focus and pops up on top of all his siblings ( but stays behind every other window I've opened over them). Is there a way to prevent this behaviour?

A: At the moment I managed to do something similar to what i need with
[DllImportAttribute("user32.dll", EntryPoint = "SetForegroundWindow")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow([InAttribute()] IntPtr hWnd);

[DllImportAttribute("user32.dll", EntryPoint = "GetForegroundWindow")]
public static extern IntPtr GetForegroundWindow();

[DllImportAttribute("user32.dll", EntryPoint = "BringWindowToTop")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool BringWindowToTop([InAttribute()] IntPtr hWnd);

IntPtr old = GetForegroundWindow();
LeftClick(hw, x, y);
SetForegroundWindow(old);
BringWindowToTop(old);

The downside is, the "clicked" form still pops up for a graction of second, giving a bad style effect. Any other hint that helps keeping the form in the background is wellcome :)


text:
Q: Casting type parameter The title might be a bit vague, but what I want is to achieve this, but then without using the extra lambda in the create method:
public class Wrapper
{
    public static Wrapper Create<T>(Func<T, bool> someFunc) where T : Stream
    {
        return new Wrapper(a => someFunc(a as T)); // Works, but lambda
        return new Wrapper((Func<Stream, bool>)(object)someFunc); // Runtime error
        return new Wrapper((Func<Stream, bool>)someFunc); // Compile error
    }

    Func<Stream, bool> _someFunc;
    private Wrapper(Func<Stream, bool> someFunc)
    {
        _someFunc = someFunc;
    }
}

Is it possible to do this, if so, how?
EDIT: The stream class is just as example.
In my code I won't be using a stream class, and as for why the type-parameter, because it's returned from a generic method, which is an extension method.
Also, the call will always be type-safe, I wanted to make the 'Wrapper' class itself generic, but then it'd be unable to add it to generic collections, because they'd have different type-parameters.

A: There's no way to do what you want without a lambda. A Func<Stream, bool> must accept any type of Stream as a parameter, so a method that takes a T (which is a specific kind of Stream) is not compatible with the signature of Func<Stream, bool>
Anyway, in the code you posted the generic parameter is completely useless; so just remove it, and make the method non-generic.

A: This can't be casted (even with contravariance support) because it is not a safe cast.
If I have a function that acts on FileStream, then try to pass it into Wrapper, I've passed it in as a function that claims it can act on any Stream.  If I then invoke that function from within Wrapper using a MemoryStream, for instance, then the delegate binding fails.  The Func<Stream, bool> is not really a Func<Stream, bool> at all.

if you want to make Wrapper generic (Wrapper<T>), you might consider exposing a non-generic interface IWrapper implemented by the generic. This way you can create a collection of IWrapper instances and expose the functionality that is valid to perform on any Wrapper<T>, while still maintaining type-safety inside each instance.


text:
Q: Is an eigen recognition model picklable? I have a python-based face recognition script running several processes (threads?) all doing different things. I am attempting to use one of these to re-train the model once the training images have been changed/updated.
I have tried sending the model through the python pipe function:
pipe.send(model)

I am not hit with any exceptions, it just hangs there indefinitely.
I fear that either the model is either unpicklable, or simply just too big!

A: multiprocessing uses pickle (or cPickle, depending on the version).  Have you tried checking like this?
>>> import pickle
>>> pik = pickle.dumps(model)
>>> _model = pickle.loads(pik)

If that succeeds, it's serializable by pickle.  If it's not, you might try using a more powerful serializer, and a fork of multiprocessing that utilizes said better serializer (i.e. dill and pathos.multiprocessing).


text:
Q: Access exportspreadsheet ignoring order by clause I'm exporting a query from access with the ImportExportSpreadsheet macro function, and it seems to be ignoring the "order by" clause in the query, and the data gets mixed up in the resulting excel file. The only issue I can think of that is causing the issue, is that the field the query is ordered by is not an actual data point in the results. I'm ordering by an ID field in the data, but I don't want that in the exported final product.
Do I need to include that field for the export to follow the order in the query?
Below is the code of the query
SELECT [CW Log Deposits].Date, [CW Log Deposits].[Pay To], [CW Log Deposits].[Check Date], [CW Log Deposits].[Rec'd From], [CW Log Deposits].Attn, [CW Log Deposits].[Street 1], [CW Log Deposits].[Street 2], [CW Log Deposits].City, [CW Log Deposits].State, [CW Log Deposits].Zip, [CW Log Deposits].[City, State, Zip], Replace([Check Num],"CK#","") AS [Check No], [CW Log Deposits].Amount, [CW Log Deposits].Memo
FROM [CW Log Deposits]
ORDER BY [CW Log Deposits].[CW Log Num];


text:
Q: Handle Akka actor bounded mailbox MessageQueueAppendFailedException To avoid OOM, I'm bounding the mailbox size of some of my Akka 1.1.3 actors with a shared custom dispatcher. For example:
object Static {
    val dispatcher = Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher(
        "customDispatcher",
        1000,
        BoundedMailbox(capacity = 10)
    )
}

class MyActor extends Actor {
    self.dispatcher = Static.dispatcher
    ...
}

I'd like to react to the mailbox overflowing so I can message the upstream producers to pause (side note: it sadly looks like actor.stop(), wait, and actor.start() will throw an ActorStartException). Some data loss is acceptable between the queue filling up and the queue draining a bit.
Akka's chapter on Dispatchers says

When trying to send a message to the Actor it will throw a
  MessageQueueAppendFailedException("BlockingMessageTransferQueue
  transfer timed out") if the message cannot be added to the mailbox
  within the time specified by the pushTimeout.

Where can I catch this exception?
The documentation makes it sound like I need to wrap every myActor ! message in a try/catch. Is that right? I'd really like to centralize its handling. Can my Supervisor perhaps intercept it and run my handler?

A: Try using cc.spray.json._ since it is built on top of akka or twitter's finagle.


text:
Q: Draw line or rectangle on cocos2d Layer Can you let me know what is the best way to draw a line or rectangle on a scene layer using Cocos2d ios4 iphone.
So far have tried Texture2d, but it is more like a paint brush and is not so good. Tried drawing a line using draw method, but previous line disappears on drawing another line.
Basically want to draw multiple horizontal ,vertical, oblique beams. Please suggest. Any code would help a lot .
The code to draw using texture is below:
CGPoint start = edge.start;
            CGPoint end = edge.end;
            // begin drawing to the render texture
            [target begin];

            // for extra points, we'll draw this smoothly from the last position and vary the sprite's
            // scale/rotation/offset
            float distance = ccpDistance(start, end);
            if (distance > 1)
            {
                int d = (int)distance;
                for (int i = 0; i < d; i++)
                {
                    float difx = end.x - start.x;
                    float dify = end.y - start.y;
                    float delta = (float)i / distance;
                    [brush setPosition:ccp(start.x + (difx * delta), start.y + (dify * delta))];
                    [brush setScale:0.3];
                    // Call visit to draw the brush, don't call draw..
                    [brush visit];
                }
            }
            // finish drawing and return context back to the screen
            [target end];

The rendering is not good esp. with oblique lines as the scaling affects the quality.
Cheers

A: You could create a separate layer and call the draw method like this:
-(void) draw
{
    CGSize s = [[Director sharedDirector] winSize];

    drawCircle( ccp(s.width/2,  s.height/2), circleSize, 0, 50, NO);

It's for a circle but the principle is the same.  This is from a project I made a while back and it worked then.  Don't know if anything has changed since.

A: You need to add draw method to your layer:
-(void) draw {
    // ...
}

Inside it you can use some openGL like functions and cocos2d wrapper methods for openGL.
Hint: other methods can be called inside draw method.
But keep in mind that using other name for method
containing openGL instructions, that's not called inside draw mentioned above simply won't work.
Even when called from update method or other method used by scheduleUpdate selector.
So you will end up with something like this:
-(void) draw {
    glEnable(GL_LINE_SMOOTH);
    glColor4ub(255, 0, 100, 255);
    glLineWidth(4);
    CGPoint verts[] = { ccp(0,200), ccp(300,200) };
    ccDrawLine(verts[0], verts[1]);

    [self drawSomething];
    [self drawSomeOtherStuffFrom:ccp(a,b) to:ccp(c,d)];

    [someObject doSomeDrawingAsWell];
}

For more information check out cocos2d-iphone programming guide :
http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:draw_update?s[]=schedule#draw


text:
Q: Count number of parameters passed to a procedure in TSQL I have a procedure in which I have allowed variable number of arguments i.e
CREATE Procedure OutputProcedure
 @FirstName nvarchar(20) = null,
 @MiddleName nvarchar(20) = null,
 @LastName nvarchar(20) = null,
 @City nvarchar(20) = null,
 @AveragePercentage int out

AS
BEGIN
/*CODE*/
End

Now, I want to be able to count the number of arguments which were passed to the procedure inside of this procedure itself. How can I do this?
I found This but it takes the name of the procedure being checked for the arguments which I think should not be the case if I was to do count inside of the same procedure only.

A: You can do this inside the SP. Try this.
Declare @cnt int

select @cnt = case when @FirstName is not null then 1 else 0 End+
       case when @MiddleName is not null then 1 else 0 End+
       case when @LastName is not null then 1 else 0 End+
       case when @City is not null then 1 else 0 End

Select @cnt


text:
Q: How to simulate printf's %p format when using std::cout? unsigned char *teta = ....;
...
printf("data at %p\n", teta); // prints 0xXXXXXXXX

How can I print variable address using iostreams? Is there a std::??? feature like std::hex to do this kind of conversion (address -> string), so std::cout << std::??? << teta << std::endl will print that address?
(no sprintf's, please ;))

A: Cast to void*:
unsigned char* teta = ....;
std::cout << "data at " << static_cast<void*>(teta) << "\n";

iostreams generally assume you have a string with any char* pointer, but a void* pointer is just that - an address (simplified), so the iostreams can't do anything other than transforming that address into a string, and not the content of that address.

A: Depending on wheter or not you want to use more formatting options printf gives, you could consider using sprintf
By it, you could format a string just like you'd do with printf, and afterwards print it out with std::cout
However, this would involve using a temporary char array so the choice depends.
An example:
unsigned char *teta = ....;
...
char formatted[ 256 ]; //Caution with the length, there is risk of a buffer overflow
sprintf( formatted, "data at %p\n", teta );
std::cout << formatted;