text:
Q: Cannot upload to FTP server in Python I am trying to upload files via FTP, I have the following code:
def ftp_upload(localfile, remotefile):
    fp = open(localfile, 'rb')
    ftp.storbinary('STOR %s' % os.path.basename(localfile), 'rb', 1024)
    fp.close()
    print ("after upload " + localfile + " to " + remotefile)

The code executes with out error but does not upload any file.

A: Why your code does not work
You are using 'rb' as the file pointer, where you should be using the file pointer you opened
Example code [Source (slightly modified)]
def placeFile():
    filename = 'exampleFile.txt'
    open_file = open(filename, 'rb')
    ftp.storbinary('STOR '+filename, open_file)
    ftp.quit()
placeFile()


text:
Q: Using sub queries to create JSON file I'm trying to create a JSON file for a new project that I'm currently looking into I've got most of it working as expected but I'm now at a  point where I'm trying to use sub queries in order to format the JSON correctly.
I've tried to use the following sub query but SQL doesn't like the formatting.
`    SELECT
'Admin User TEST ONLY PLEASE IGNORE' AS AdditionalNotes

(
   SELECT v.atFault
   FROM dbo.ic_DP_AX ax
   CROSS APPLY (VALUES (ax.Acc_fault1), (ax.Acc_fault2)) v (atFault)
   FOR JSON AUTO
   ) AS InsuredPartyClaims,
   (
   SELECT Acc_fault3 AS atFault
   FROM dbo.ic_DP_AX
   FOR JSON AUTO
   ) AS InsuredPartyConvictions
FOR JSON PATH) ROOT('InsuredParties')

FROM

    dbo.icp_Daprospect AS p INNER JOIN
    dbo.icp_Dapolicy AS d ON p.Branch@ = d.Branch@ AND p.ClientRef@ =
 d.ClientRef@ LEFT OUTER JOIN
    dbo.ic_DP_AX AS  ax ON P.Branch@ = ax.B@ AND ax.PolRef@ = d.PolicyRef@
LEFT OUTER JOIN
WHERE
    d.PolicyRef@ = '' AND
    d.Branch@ = 0`

FOR JSON PATH
The output I'm trying to achieve is:
"InsuredParties": [
    {
        "InsuredPartyClaims": [
            {
                "atFault": false
            },
            {
                "atFault": true
            }
        ],
        "InsuredPartyConvictions": [
           {
                "atFault": false
           },

Can anyone see what I'm doing wrong? I'm trying to keep this as simple as possible.

A: It's always difficult without sample data, but the foolowing example is a possible solution:
Table:
CREATE TABLE dbo.ic_DP_AX (Acc_fault1 bit, Acc_fault2 bit, Acc_fault3 bit)
INSERT INTO dbo.ic_DP_AX (Acc_fault1, Acc_fault2, Acc_fault3)
VALUES (0, 1, 0)

Statment:
SELECT
   (
   SELECT v.atFault
   FROM dbo.ic_DP_AX ax
   CROSS APPLY (VALUES (ax.Acc_fault1), (ax.Acc_fault2)) v (atFault)
   FOR JSON AUTO
   ) AS InsuredPartyClaims,
   (
   SELECT Acc_fault3 AS atFault
   FROM dbo.ic_DP_AX
   FOR JSON AUTO
   ) AS InsuredPartyConvictions
FOR JSON PATH, ROOT('InsuredParties')

Result:
{
  "InsuredParties":[
    {
      "InsuredPartyClaims":[
        {
          "atFault":false
        },
        {
          "atFault":true
        }
      ],
      "InsuredPartyConvictions":[
        {
          "atFault":false
        }
      ]
    }
  ]
}

A: The subqueries need to return JSON as well.
Try
(
  (SELECT ax.Acc_fault1 AS [atFault] FROM dbo.ic_DP_AX AS ax FOR JSON PATH) AS [PartyClaims]
  (SELECT ax.Acc_fault2 AS [atFault] FROM dbo.ic_DP_AX AS ax FOR JSON PATH) AS [PartyClaims]
  (SELECT ax.Acc_fault3 AS [atFault] FROM dbo.ic_DP_AX AS ax FOR JSON PATH) AS [PartyConvictions]
) FOR JSON PATH AS [InsuredParties]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does formatting an SSD shorten its lifespan? I would like to perform a format on my SSD. I've read several files on shortening the SSD's lifespan, but never read anything about formatting.
Does formatting an SSD shorten its lifespan?

A: In general, formatting a solid-state drive will not impact its lifetime, unless you perform a full format - and even then, it depends how often.  Most formatting utilities allow you to do a quick or full format.  The quick format just overwrites the partition and file tables, but does not actually physically delete anything off of the disk.
In contrast, a full format will go through each sector on a disk and "reset" it.  This can degrade the lifetime of the SSD.  That being said, MLC solid state drives have a write limit of around 10,000 before the sectors begin to fail.
So long as you don't do it often, (fully) formatting the drive a few times won't seriously impact on the drive lifespan.

A: Formatting = writing.
Modern SSDs have a command for clearing all data, ATA Secure Erase. Take a look in the software provided by your SSD manufacturer.


text:
Q: UITableViewCell didSelectRowAt in UIView with UITapGestureRecognizer I can't figure this out.
I have big UIView with UITapGestureRecognizer.
On this view I put (smaller) UITableView. And now, if I tap on cell,
didSelectRowAt is not called, because UIView tap recognizer detect the tap. (It's method is called.)
How do I solve this, that UITableView don't pass touch through to the view.
I try with setting
table.isUserInteractionEnabled = true

and
table.isExclusiveTouch = true

but it doesn't help
EDIT :
A lot of your answers suggest that I have a tableView below view, which is not the case.
I will paste some of my code (changed a little bit for convenience):
class Panel: UIView {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setTapGesture()
    }

    func setTapGesture() {

        tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(UIControlCenterPanel.tapOnPanel(recogniser:)))
        self.addGestureRecognizer(tapGesture)
    }

    func tapOnPanel(recogniser : UITapGestureRecognizer) {
        print("Tap was made")
    }
 }

  class MyPanel: Panel, UITableViewDelegate {
      let table = MyTable()

      override init(frame: CGRect) {
          super.init(frame: frame)

          table.table.delegate = self
          table.isUserInteractionEnabled = true  // This was added as a test
          table.table.isExclusiveTouch = true    // This was added as a test
          table.translatesAutoresizingMaskIntoConstraints = false
          addSubview(table)
          .... // constraints added below
      }

      func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
          print("cell tapped")
      }
  }

  class MyTable: UIView {

      let table = UITableView()

      override init(frame: CGRect) {
          super.init(frame: frame)

          table.translatesAutoresizingMaskIntoConstraints = false
          addSubview(table)
      }
  }

If I click on the cell now, it print:
Tap was made

If I comment out the gesture recogniser like this :
func setTapGesture() {

       // tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(UIControlCenterPanel.tapOnPanel(recogniser:)))
       // self.addGestureRecognizer(tapGesture)
}

then it is printed :
cell tapped

A: You can override your container UIView's hitTest method to only let subviews (if any) receive touch events, but never itself. This allows search to continue to unrelated views below. Just replace your UIView with an instance of this class:
class PassThroughView: UIView {

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let result = super.hitTest(point, with: event)
        return result == self ? nil : result
    }
}

A: Returning appropriate BOOL values in gestureRecognizer:shouldReceiveTouch: will enable you to propagate touches to desired subviews.
Some sample code to achieve this can be like:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{

    if([touch.view isDescendantOfView:table]){
        return NO; // or YES, as desired
    }
}

*

*This function needs to be implemented in the ViewController.m

*You'll need an instance of table, either as an @propertyor extracted via viewWithTag:

A:
let tap = UITapGestureRecognizer(target: self, action:
  Selector("handleTap:")) tap.delegate = self tap.cancelsTouchesInView =
  false
  view.addGestureRecognizer(tap)// default view
func handleTap(sender: UITapGestureRecognizer? = nil) {
      view.endEditing(true) // keyboars hides }

A: Try this code
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
    if touch.view.isDescendantOf(yourTableView) {
        return false
    }
    return true
}

A: You can refer to the answers stated in the question.
Link: UITapGestureRecognizer breaks UITableView didSelectRowAtIndexPath
Setting delegate to filter valid touches according to the type of touched view is the best solution. Some answers suggest to use cancelsTouchesInView = false to tackle this problem but it actually fire both the UITableView didSelectRowAt and also the UITapGestureRecognizer selector at the same time. Choose the right one for yourself.


text:
Q: No coercion operator is defined between types 'System.String' and 'System.Nullable`1[System.DateTime]' I am using AutoMapper for object mapping. Sometime the source value is null so i want to substitute it with "" rather than putting NULL in database.
The source object have many nullable data types like Date, Decimal and Int.
Currently i am using
public class Invoice
    {
        public Guid Id { get; set; }
        public string Number { get; set; }
        public Contact Contact { get; set; }
        public InvoiceType Type { get; set; }
        public InvoiceStatus Status { get; set; }
        public LineAmountType LineAmountTypes { get; set; }
        public DateTime? Date { get; set; }
        public DateTime? DueDate { get; set; }
        public DateTime? ExpectedPaymentDate { get; set; }
        public DateTime? PlannedPaymentDate { get; set; }
        public decimal? SubTotal { get; set; }
        public decimal? TotalTax { get; set; }
        public decimal? Total { get; set; }
        public decimal? TotalDiscount { get; set;
        public decimal? CurrencyRate { get; set; }
        public DateTime? FullyPaidOnDate { get; set; }
        public decimal? AmountDue { get; set; }
        public decimal? AmountPaid { get; set; }
        public decimal? AmountCredited { get; set; }

    }

public partial class TempInvoice
    {
        public int RowId { get; set; }
        public System.Guid InvoiceID { get; set; }
        public string InvoiceNumber { get; set; }
        public Nullable<System.Guid> ContactID { get; set; }
        public string Type { get; set; }
        public string Status { get; set; }
        public string LineAmountType { get; set; }
        public Nullable<System.DateTime> InvoiceDate { get; set; }
        public Nullable<System.DateTime> DueDate { get; set; }
        public Nullable<System.DateTime> ExpectedPaymentDate { get; set; }
        public Nullable<System.DateTime> PlannedPaymentDate { get; set; }
        public Nullable<decimal> SubTotal { get; set; }
        public Nullable<decimal> TotalTax { get; set; }
        public Nullable<decimal> Total { get; set; }
        public Nullable<decimal> TotalDiscount { get; set; }
        public Nullable<decimal> CurrencyRate { get; set; }
        public Nullable<System.DateTime> FullyPaidOnDate { get; set; }
        public Nullable<decimal> AmountDue { get; set; }
        public Nullable<decimal> AmountCredited { get; set; }
    }

    public class InvoiceMapper : Profile
        {
            public InvoiceMapper()
            {
                CreateMap<Invoice, TempInvoice>()
                    .ForMember(des => des.PaymentID, map => map.MapFrom(src => src.Id))
                    .ForMember(des => des.InvoiceID, map => map.MapFrom(src => src.Invoice.Id))
                    .ForMember(des => des.PaymentDate, map => map.MapFrom(src => src.Date))
                    .ForAllMembers(src => src.NullSubstitute(""))//this doesn't work
                    ;
            }
        }

But i am getting the above error.
Is there a way i can exclude the datatime type and set int or decimal to 0 and string to "" ? Is there a generic method i can use for all datatypes?
Thanks

A: You could use a resolver function with ResolveUsing, using your own custom mapping function that returns an empty string if the destination is a string, otherwise null.
For example:
    private static object MyMapperResolver(object source, bool returnEmptyString = true) {
        return source ?? (returnEmptyString ? "" : source);
    }

    public static IMapper InitMappings() {
        Mapper.Initialize(cfg => {
            cfg.CreateMap<Invoice, TempInvoice>()
                .ForMember(des => des.PaymentID, map => map.ResolveUsing(src => MyMapperResolver(src.Id)))
                .ForMember(des => des.InvoiceID, map => map.ResolveUsing(src => MyMapperResolver(src.Invoice.Id)))
                .ForMember(des => des.PaymentDate, map => map.ResolveUsing(src => MyMapperResolver(src.Date, false)))
                ;
        });
        return Mapper.Instance;
    }

A: You can use AddTransform
public class InvoiceMapper : Profile
{
    public InvoiceMapper()
    {
        CreateMap<Invoice, TempInvoice>()
            .ForMember(des => des.PaymentID, map => map.MapFrom(src => src.Id))
            .ForMember(des => des.InvoiceID, map => map.MapFrom(src => src.Invoice.Id))
            .ForMember(des => des.PaymentDate, map => map.MapFrom(src => src.Date))
            .AddTransform<string>(s => string.IsNullOrWhiteSpace(s) ? "" : s); // this line
    }
}


text:
Q: Execute Asynccallback truly asynchronously while retrieving delegate return value So basically I'm invoking a delegate with BeginInvoke I'm passing the AsyncCallback as well. Whenever the callback gets executed I want to retrieve the delegate return value and do something with it but to do that I need to call EndInvoke which Blocks main thread which is not what I desire. I want that callback to execute truly asynchronously. Can It be done in this way ? if not are there any other ways ? my async callback method looks like this for now
private void RegisterUserAsyncCallback(IAsyncResult result)
{
    var something = (Something)result.AsyncState;
    var asyncCaller = (AsyncMethodCaller)((AsyncResult)result).AsyncDelegate;
    var responce = asyncCaller.EndInvoke(result);

    if (responce.Success)
    {
        something.SomeId = SomeId.Active;
        someDAL.UpdateSomething(something );
    }
}


text:
Q: Undoing a decade of singleton pattern and class-level configuration Overview
I need to duplicate a whole inheritance tree of classes. Simply deep-copying the class objects does not work; a proper factory pattern involves a huge amount of code changes; I'm not sure how to use metaclasses to accomplish this.
Background
The software I work on implements support for specialized external hardware, connected to the host computer via USB. Many years ago, it was assumed that there would only ever be one type of hardware in use at a time. Consequently, the hardware object is used as a singleton. Along the years, secondary classes were configured based on the currently active hardware class.
At the moment, it is impossible to use this library with two types of hardware at the same time, since the classobjects cannot be configured for both hardware at the same time.
In recent years, we have avoided this issue by creating one python process for each hardware, but this is becoming untenable.
Here is an extremely simplified example of the architecture:
# ----------
# Hardware classes
class HwBase():
    def customizeComponent(self, compDict):
        compDict['ComponentBase'].hardware = self

class HwA(HwBase):
    def customizeComponent(self, compDict):
        super().customizeComponent(compDict)
        compDict['AnotherComponent'].prop.configure(1,2,3)

class HwB(HwBase):
    def customizeComponent(self, compDict):
        super().customizeComponent(compDict)
        compDict['AnotherComponent'].prop.configure(4,5,6)

# ----------
# Property classes
class SpecialProperty(property):
    def __init__(self, fvalidate):
        self.fvalidate = fvalidate
        # handle fset, fget, etc. here.
        # super().__init__()

# ----------
# Component classes
class ComponentBase():
    hardware = None

    def validateProp(self, val):
        return val < self.maxVal

    prop = SpecialProperty(fvalidate=validateProp)

class SomeComponent():
    """Users directly instantiate and use this compoent via an interactive shell.
    This component does complex operations with the hardware attribute"""

    def validateThing(self, val):
        return isinstance(val, ComponentBase)

    thing = SpecialProperty(fvalidate=validateThing)

class AnotherComponent():
    """Users directly instantiate and use this compoent via an interactive shell
    This component does complex operations with the hardware attribute"""
    maxVal = 15

# ----------
# Initialization

def initialize():
    """ This is only called once perppython instance."""
    #activeCls = HwA
    activeCls = HwB

    allComponents = {
            'ComponentBase': ComponentBase,
            'SomeComponent': SomeComponent,
            'AnotherComponent': AnotherComponent
    }

    hwInstance = activeCls()
    hwInstance.customizeComponent(allComponents)

    return allComponents

components = initialize()

# ----------
# User code goes here
someInstance1 = components['SomeComponent']()
someInstance2 = components['SomeComponent']()

someInstance1.prop = 10
someInstance2.prop = 10

The overarching goal would be to interact with both HwA and HwB at the same time. Since most interactions are done via components instead of the Hw objects themselves, I believe the solution involves having multiple versions of the components, e.g.: two separate inheritance trees, for a total of 6 final components, one tree/set configured for each hardware. This is what I need help with.

Potential solutions
Consider that I have around tens different hardware do configure for. Furthermore, there are hundreds of different leaf components classes, with many extra bases and mixin classes.
Move all configuration steps in the component's init method
Not possible due to the use of properties; these need to be set on the class.
Deepcopy the classobjects
Copy all classobjects, swap in the appropriate __bases__. Mutable class variables need to be carefully handled. However, I'm not sure how to deal with properties for this, since classbody references within the property objects (such as fvalidate) need to be updated to that of the copied class.
This requires a significant amount of manual intervention to work. Not impossible, but prone to breaking in the long term.
Factory pattern
Wrap all component definition in a factory function:
def ComponentBaseFactory(hw):
    class SomeComponent(cache[hw].ComponentBase):
        pass

and have some sort of component cache which would handle creating all classobjects during initialize()
This is what I consider the most architecturally-correct option available. Since the class body is re-executed
on every factory call, the attributes of the properties will reference the appropriate class object.
Downside: huge code footprint. I am familiar with doing codebase-wide changes via sed or python scripts, but this would be quite a lot.
Add metaclasses on components
I am not sure how to proceed for this. Based on the python data model (py3.7), the following happens at class creation (which happens right after the class definition indentation ends):

*

*MRO entries are resolved;

*the appropriate metaclass is determined;

*the class namespace is prepared;

*the class body is executed;

*the class object is created.

I would need to redo these steps after the class has been defined (like a factory function!), but i'm not sure how to redo step 4. Specifically, the python documentation states in section 3.3.3.5 that the class body is executed as with a "special?" form of the exec() builtin. How can I re-exec the class body with a different set of locals/globals? Even if I access the class body's code with inspect shenanigans, i'm not sure i'll be able to reproduce the module environment properly.
Even if I mess with __prepare__ and __new__, I don't see how I can fix the cross-references introduced in the class code block regarding the property instantiation.
Components as metaclasses
A metaclass is a class factory, just like a class is an object factory. SomeComponent and AnotherComponent could be declared as metaclasses, then get instantiated with the Hw object during initialize():
SomeComponent = SomeComponentMeta(hw)

This is similar to the factory pattern, but would also require quite a few code changes: a lot of class code would have to be moved to the metaclass __init__.

A: I'd have to spend a lot more of time here to proper understand what you need, but if your "TL;DR" of executing the class body with different globals/nonlocal variables is the bottom line, the factory approach is a very clean and readable way, as you had considered.
At first, I don't think a metaclass could be a good approach here - although it could be used to customize your special properties (in my first read, I could not figure out what they actually do, and how they should differ between your final classes). If the function as a class factory can specialize your properties, it would work nonetheless.
If what you need is that the properties are independent for Hwa and HwB like in accessing a different list object in HwA than is accessed in HwB, yes, a metaclass could take care of that, by automatically recreating any properties when creating a subclass (so that the property objects themselves are not shared with the supper-classes and across the hierarchy).
If that i what you need, leave a comment, I can write some proof of concept code.
Anyway, it is possible to create a metaclass that, upon instantiating a subclass, will look upon the hierarchy for all SpecialProperty and create new-instances of those for the subclass - so that a base value set on a superclass remains valid for the subclasses, but when configuration runs, each class will have an independent configuration. (as it turns out, no metaclass is needed: we are covered by __init_subclass__ )
Another thing to take care of is that subclassses of property   cannot be simply copies with Python's copy.copy (tested empirically), so we need a way to create reliable copies of those. I include one function bellow, but it might need to be improved to work with the actual SpecialProperty class.
from copy import copy

def copy_property(prop):
    cls = prop.__class__
    new_prop = cls.__new__(cls)
    # Initialize the attributes that can't be set from Python code, inplace:
    property.__init__(new_prop, prop.fget, prop.fset, prop.fdel)
    if hasattr(prop, "__dict__"): # only exists for subclasses of property
        # Possible adaptation needed: it may be that for some attributes of
        # SpecialProperty, a deepcopy would be needed.
        # But for the given example attribute of "fvalidate" a simple copy is better:
        new_prop.__dict__ = copy(prop.__dict__)
    return new_prop

# Python 3.6 introduced `__init_subclass__` which is called at subclass _creation_
# time. With it, the logic can be inserted in ComponentBase and there is no need for
# a metaclass.

class ComponentBase():

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        for attrname in dir(cls):
            attr = getattr(cls, attrname)
            if not isinstance(attr, SpecialProperty):
                continue
            new_prop = copy_property(attr)
            setattr(cls, attrname, new_prop)

    hardware = None
    ...

As you see- theres some workarounds that had to be done because your project opted for subclassing property. I am leaving this remark here as a remainder that unless  property fits one exact needs, it is more clean to write a new class implementing the Descriptor Protocol - just by implementing __set__, __get__ and __delete__ directly.


text:
Q: React MUI: Matching the heights of two grid sections Using MUI have two separate grids next to each other, both taking up 50% of a larger grid.
As seen in the image below, I am having a hard time matching the heights of the two sections. I would like the smaller grid items (cards) to dynamically fill in the height of the left portion and match the height of the right portion.
How is this possible with Mui?
Here is my current code:
import React from "react";
import Grid from "@mui/material/Grid";
import Box from "@mui/material/Box";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Typography from "@mui/material/Typography";
import Chart from "./testChart.js";

function GeneralDashboard(props) {
  const defaultStats = [
    { name: "Opportunitys Entered", value: 102 },
    { name: "Wins Reported", value: 23 },
    { name: "Win Rate", value: "60%" },
    { name: "Total Revenue", value: "$20m" },
  ];
  return (
    <>
      <Box sx={{ flexGrow: 1 }}>
        <Grid
          container
          spacing={{ xs: 1, sm: 2, lg: 2 }}
          columns={{ xs: 8, sm: 8, md: 8, lg: 8 }}
        >
          <Grid item xs={8} sm={8} md={4} lg={4}>
            <Box sx={{ flexGrow: 1 }}>
              <Grid
                container
                spacing={{ xs: 1, sm: 2, lg: 2 }}
                columns={{ xs: 4, sm: 4, md: 8, lg: 8 }}
              >
                {defaultStats.map((stat) => {
                  return (
                    <>
                      <Grid item xs={2} sm={4} md={4}>
                        <Card>
                          <CardContent>
                            <Typography
                              sx={{ fontSize: 14 }}
                              color="text.secondary"
                              gutterBottom
                            >
                              {stat.name}
                            </Typography>
                            <Typography variant="h3" component="div">
                              {stat.value}
                            </Typography>
                          </CardContent>
                        </Card>
                      </Grid>
                    </>
                  );
                })}
              </Grid>
            </Box>
          </Grid>
          <Grid item xs={8} sm={8} md={4} lg={4}>
            <Box sx={{ flexGrow: 1 }}>
              <Grid container spacing={{ xs: 1, sm: 1, lg: 1 }}>
                <Grid item xs={12}>
                  <Card>
                    <CardContent>
                      <Typography
                        sx={{ fontSize: 14 }}
                        color="text.secondary"
                        gutterBottom
                      >

                            Re-entry{" "}
                            timing by industry

                      </Typography>
                      <Chart />
                    </CardContent>
                  </Card>
                </Grid>
              </Grid>
            </Box>
          </Grid>
        </Grid>
      </Box>
    </>
  );
}

A: You need to set the height of all containers and the item to 100%:
<Box sx={{ flexGrow: 1, height: "100%" /* <----------------------- (1) */ }}>
  <Grid
    sx={{ height: "100%" /* <----------------------- (2) */ }}
    container
    spacing={{ xs: 1, sm: 2, lg: 2 }}
    columns={{ xs: 4, sm: 4, md: 8, lg: 8 }}
  >
    {defaultStats.map((stat) => {
      return (
        <>
          <Grid item xs={2} sm={4} md={4}>
            <Card sx={{ height: "100%" /* <----------------------- (3) */ }}>


text:
Q: .NET System.Timers.Timer How to pass parameters to a delegate function? I need to call a function on a set timer. Currently I'm using the system.timers.timer sample code from http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed(v=vs.110).aspx
iaTimer = New System.Timers.Timer(60000)
'Hook up the Elapsed event for the time
AddHandler aTimer.Elapsed, (AddressOf OnTimedEvent)
aTimer.Enabled = True

'The event handler for the Timer.Elapsed event.
Public Sub OnTimedEvent(source As Object, e As System.Timers.ElapsedEventArgs, ByVal companies() As companyAccount)
    timermain(companies)
End Sub

I do not know how to pass parameters to the delegate. The array companies() is an array of companyAccount objects which are basically structs.  I need these parameters to be fed to the timermain function. Elsewhere in the code I have a delegate that accepts parameters to update textboxes, So this should be possible.
I think this question is similar.  How to pass the sender parameter to the system.timers.timer

A: You cannot change the Timer.Elapsed event signature (or generally change the signature of events) to pass additional parameters. Instead, you should declare your companies variable in a scope that will be accessible to the event handler.
You can do this by making it class-level, if all this code is in the same class.
Class SomeClass
    Private companies() As CompanyAccount

    Sub SetupTimer()
        iaTimer = New System.Timers.Timer(60000)
        ' Hook up the Elapsed event for the time
        AddHandler aTimer.Elapsed, (AddressOf OnTimedEvent)
        aTimer.Enabled = True
    End Sub

    ' The event handler for the Timer.Elapsed event.
    Public Sub OnTimedEvent(source As Object, e As System.Timers.ElapsedEventArgs)
        timermain(companies)
    End Sub
End Class

You may also be able to use a lambda expression:
Dim companies() As CompanyAccount
companies = ...
iaTimer = New System.Timers.Timer(60000)
AddHandler aTimer.Elapsed, Sub(sender, e) timermain(companies)
aTimer.Enabled = True


text:
Q: How to redirect a wget output to a newly created directory So I want to write a shell script which first creates a folder based on the year and month.
Then it is followed by a wget command which downloads a file.
mkdir $(date + "%Y%b") #create a new directory
wget https:www.testweb.com/file=312

How do i make sure that the wget command outputs the file downloaded to the newly created directory in the first line?


text:
Q: Can I setup a single Sparsebundle in RAID 1? My goal is the following: use my iMac as a TimeMachine Server (under OS X Lion Server) to backup my MBP via the network.
What I did is to choose, in the TimeMachine Server configuration, the internal drive (1TB) of the iMac as a target for the backup.
However I would like to have redundancy, not for the whole iMac data, but for that backup.
If I backup the sparsebundle created on my iMac (using CCC for example), then I'll have to copy the entire content all the time.
So would it be possible to create a virtual RAID 1 drive whose two drives are two sparsebundles, one located on the iMac internal drive and the other one on an external drive.
I think that would be a very interesting solution for what I want to do, and it would be possible to scale it for 3 drives.

A: You can setup a RAID 1 mirror over FireWire and connect the internal/external drives. However, I wouldn't recommend it.
First, you'll need the same size drives to do the mirror. Second, the speed of both drives will be limited by the type of connection to the external drive, so if its USB, the computer will run at USB speeds. If you are just using this iMac for backup, that may not be an issue, but it's still going to slow everything down.
RAID mirroring is intended mostly for much faster eSATA connections, as that keeps everything at nearly native speeds. What I might recommend in your case is to buy an external RAID and use that for backup. That way you aren't locked in to the internal drive on the iMac, and you can always move it to a different computer if need be (especially in the event of a restore, as it'd be faster plugged directly in than over the network.

A: Yes - the Disk Utility should allow you to erase both the internal drive and the external drive and allow them to be part of a RAID.
If I were doing this and wanted to preserve the data on the current Time Machine destination drive:

*

*Turn off Time Machine server - disable any new backups to that drive

*Use Disk Utility to move all the contents (restore) from the internal drive to the external drive.

*Verify the backup worked - mount the bundle, count files, etc...

*Learn and practice mirroring a RAID set using cheap USB drives and expendable data.

*Set up the internal drive as a Mirrored RAID drive

*Copy the data back to the internal drive.

*Erase and join the external drive with no data to the internal drive.

Once the OS has mirrored the data (block by block) you can detach and re-attach the drive.

As you can see, it's possible but you might instead look to some backup software like CrashPlan or others to get incremental backups of the data. You can use CrashPlan between your own machines without needing to pay for hosted offsite storage.


text:
Q: Can I incorporate my existing Bot build to run in Bot Composer I have an existing Bot build on bot framework sdk but now I need to shift that into Bot Framework composer so that in future all the developments can happen over composer. Can anyone help me with steps to migrate existing bot into composer.

A: Unfortunately there are no documented steps for migrating a bot to Composer. My recommendation is to familiarize yourself with the Composer documentation and practice using it until you're confident enough to rebuild your bot's functionality in Composer.
Composer uses declarative dialogs which in turn use adaptive dialogs. In the unlikely scenario that your bot already uses either of those things, the transition will be easier. In the more likely scenario that your bot isn't already using adaptive dialogs, the logic of your bot will need to be rebuilt in an entirely new format and so there's no way to simplify that process into easy steps.


text:
Q: How to make elements stop popping out of div that I made? I want to make a box(in a form of div) that could arrange and move around objects in.
But, when I try to make objects to alight to left they pop out of it.
How can I fix this issue?

A: #slide
 {
 margin: 100px 100px;
 background:green;
 height:200px;
 width:100px;
 overflow: hidden;
 clear:both;
}

Try this(replace your class)

A: Edited found the answer:
just add position:relative;
to #slide in css file
HTMl
    <!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="style.css">

Css
   #slide
   {
   margin: 100px 100px;
   background:green;
   height:200px;
   width:100;
   }
   #right
   {
   top:40%;
   height:20px;
   width:20px;
   background:black;
   right:0;
   position:absolute;
   }
   #left
   {
   top:40%;
   height:20px;
   width:20px;
   background:black;
   left:0;
   position:absolute;
   }


text:
Q: Selecting items from generic list based on true condition from another list I am wondering if there would be any LINQ/Lambda expression solution for the problem below.
I have 2 generic lists
List 1
public class Data
{
  public string ID { get; set;}
  public string Package { get; set;}
}

List<Data> listData = new List<Data>();

Data data1 =  new Data { ID = "1", Package = "Test" };
Data data2 =  new Data { ID = "2", Package = "Test2" };
Data data3 =  new Data { ID = "3", Package = "Test2" };
Data data4 =  new Data { ID = "4", Package = "Test4" };

listData.Add(data1);
listData.Add(data2);
listData.Add(data3);
listData.Add(data4);

List 2
List<int> listFilter =  List<int>();

listFilter.Add(1);
listFilter.Add(0);
listFilter.Add(0);
listFilter.Add(1);

I would like to filter "listData" based on the true (1) criteria from "listFilter". For the above example, I must be able to pull data1 and data4 into a new list.
At the moment, I am using a for loop to achieve this as below.
List<Data> listResult =  new List<Data>();
for(int index=0; index<listData.Count; index++)
{
    if(listFilter[index]==1)
    {
       listResult.Add(listData[index]);
    }

}

I would appreciate if someone could show me to use LINQ or Lambda expression to achieve this.
Thanks
Balan

A: In the general case, you can do:
var result = listData.Zip(listFilter, (data, filter)
                          => new { Data = data, Filter = filter })
                     .Where(tuple => tuple.Filter == 1)
                     .Select(tuple => tuple.Data)
                     .ToList();

A: var results = listData.Where((item, index) => listFilter[index] == 1);

Note that this will fail if listData is longer than listFilter, same as your code.

A: var listResult = listData
    .Where((data, index) => listFilter[index] == 1)
    .ToList();

Reference:
http://msdn.microsoft.com/en-us/library/bb548547.aspx


text:
Q: Getting a happy face to show up in Java I'm having trouble with displaying my image file, src/happyFace.gif, in my Java GUI. The goal is to display an image of a smiling face that seems to glide across the program window at an angle, bouncing off of the window edges.
I think my problem is with the image variable (type ImageIcon) in src/ReboundPanel.java, because the ImageIcon class might not be compatible with future swing releases (according to Oracle's documentation: https://docs.oracle.com/javase/7/docs/api/javax/swing/ImageIcon.html). If this is true, I think the ImageIcon class might not be able to be supported by the swing library. I don't know how to check my swing library for this.
src/happyFace.gif

My Output Window

src/Rebound.java:
//********************************************************************
// Rebound.java Java Foundations
//********************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Rebound{
//-----------------------------------------------------------------
// Displays the main frame of the program.
//-----------------------------------------------------------------
    public static void main (String[] args){
        JFrame frame = new JFrame ("Rebound");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new ReboundPanel());
        frame.pack();
        frame.setVisible(true);
    }
}

src/ReboundPanel.java:
//********************************************************************
// ReboundPanel.java Java Foundations
//
// Represents the primary panel for the Rebound program.
//********************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ReboundPanel extends JPanel{
    private final int WIDTH = 300, HEIGHT = 100;
    private final int DELAY = 20, IMAGE_SIZE = 35;
    private ImageIcon image;
    private Timer timer;
    private int x, y, moveX, moveY;
    //-----------------------------------------------------------------
    // Sets up the panel, including the timer for the animation.
    //-----------------------------------------------------------------
    public ReboundPanel(){
        timer = new Timer(DELAY, new ReboundListener());
        image = new ImageIcon ("happyFace.gif");
        x = 0;
        y = 40;
        moveX = moveY = 3;
        setPreferredSize (new Dimension(WIDTH, HEIGHT));
        setBackground (Color.black);
        timer.start();
    }
    //-----------------------------------------------------------------
    // Draws the image in the current location.
    //-----------------------------------------------------------------
    public void paintComponent (Graphics page){
        super.paintComponent (page);
        image.paintIcon (this, page, x, y);
    }
    //*****************************************************************
    // Represents the action listener for the timer.
    //*****************************************************************
    private class ReboundListener implements ActionListener{
        //-----------------------------------------------------------------
        // Updates the position of the image and possibly the direction
        // of movement whenever the timer fires an action event.
        //-----------------------------------------------------------------
        public void actionPerformed (ActionEvent event){
            x += moveX;
            y += moveY;
            if (x <= 0 || x >= WIDTH-IMAGE_SIZE)
                moveX = moveX * -1;
            if (y <= 0 || y >= HEIGHT-IMAGE_SIZE)
                moveY = moveY * -1;
            repaint();
        }
    }
}

A: In ReboundPanel class,
change image = new ImageIcon("happyFace.gif");
to image = new ImageIcon("src/happyFace.gif");

Note that this kind of solution should only be used for testing purposes. As stated in Andrew Thompson's comment, the correct way to store and load the image is using an embedded resource.


text:
Q: Can I compose ReadS and ReadP? I am trying to compose a parser with ReadP, and I wanted to use read to parse numbers. But I must be missing something because even the most trivial example misbehaves:
λ import Text.ParserCombinators.ReadP
λ (readP_to_S . readS_to_P $ (read :: ReadS Int)) "123" :: [(Int, String)]
*** Exception: Prelude.read: no parse

I even specified the types everywhere, but it just does not work. What am I doing wrong?

A: You need to replace your use of read with reads:
> (readP_to_S . readS_to_P $ (reads :: ReadS Int)) "123" :: [(Int, String)]
                              ^^^^^
[(123,"")]

It's unfortunate that it typechecked with read, but it's because the type signature for read is so general.  In fact, the parser read :: ReadS Int is trying to parse a list of tuples of integers and strings!!!
> (read :: ReadS Int) "[(1,\"hi\"),(2,\"bye\")]"
[(1,"hi"),(2,"bye")]

which is definitely not what you want.


text:
Q: Cannot Access Hash Values Code inside index.php:
<!DOCTYPE html>

        <meta charset="utf-8" />

Trash

This is undeletable item.

Code inside trash.php is:
<?php
    $id = $_POST['trashid'];
  $error = false;
  $success = false;
  if ($id) {
    $success = trash_post($id);
    $response = array(
      'success' => $success,
      'error' => $error
    );
  }
  echo json_encode( $response );

  function trash_post( $target_id ) {
    return true;
  }

Please look at the first code snippet in index.php where:
console.log(response);  // Output: {"success":true,"error":false}

but when I want to access success:
console.log(response.success);  //   undefined

Why does it give me undefined instead of true? I have come across a few posts on Stackoverflow similar to mine, but they were not helpful for me.

A: Probably response is just a string but not a Object
try
var a = JSON.parse(response);
console.log(a.success);

or try adding this at the top of your php file
header('Content-Type: application/json');

this set's the content type of php file as JSON

A: Try using this
response['success'] == true

Instead of
response.success == true

A: Try not to use success or error flags for your response, instead make use of the status codes and build a proper response. You can use http_response_code() function to do that. Ex:
<?php
http_response_code(200);
?>

And then to handle the response in your ajax call properly, do this:
$.ajax({
    url: trashurl,
    type: "POST",
    data: { "trashid": trashid },
    datatype: "json"
})
  .done(function (response) { //response status code is 200
       trashlink.parents("li").fadeOut(300, function() {
           trashlink.parents("li").remove();
       });
  })
  .fail(function (xh) {
      //Handle failed response
  });


text:
Q: PHPMyAdmin - Table privileges selection list size In PHPMyAdmin, when i need to select to select only several fields in a table for a user, the place to select the fields is really tiny. So when you have long names, it shows you only the begining of each names and very often, you can't understand what you are selecting.
I'm nearly sure that it is something from the past, when screens were 800x600 or something like that.
But by now, I haven't been able to find any option / parameter / solution to increase this size.
So when it is impossible to be sure about what i select, i need to modify the privileges through a SQL request.
Does anybody know if there is a solution ?
Best regards.


text:
Q: css nth-child(1) chose the second element, why? What I want: To understand nth-child(n). My understanding is that the nth-
child(1) will choose every first element. So apple, fruit, banana should be chosen to display red.
What actually shows: But tomato and mango were also chosen and displayed red.
Code:

a {
    text-decoration: none;
    color: black;
}

:nth-child(1) {
    color: red;
}

apple

tomato

        fruit
        juice

        banana
        mango

A: First, :nth-child(1) also includes html:nth-child(1), which means all text will be red. Also note that ul is the first child of body. (html and body elements are added when you run the snippet.)
The reason almost all text is red is somewhat complicated:

*

*apple: red because it is text in the first li element of the ul

*tomato: red because it inherits the color of ul, which is the first element in body

*fruit: red because it is the text of the first a in an li element (styling of :nth-child(1) wins)

*juice: black because it is the text of an a element that is not the first child of another element (styling of a is used)

*banana: red because it is the text of the first child of a span element

*mango: red because em inherits the text color of its parent (span) which is the first child of a div, so the styling of :nth-child(1) is applied

Also note that any text in the div will be red, because the div inherits the color from html (which is a first child). You may want to specify an explicit text color for html which can be used instead.

A: Mr.Arjan answer is perfect. In addition to that I have changed your code for your better understanding.

apple

tomato

        fruit
        juice

        banana
        mango

Working Fiddle here
and this link will help you to understand better to know more about nth-child in css http://nthmaster.com/


text:
Q: Comparing two rows in PostgreSQL I have an employee table in two different servers with the same structure. I want to shift all the data to main server but there are some records already exists in main server that are duplicate of local one's but are incomplete, now i want to compare these records so i can chose the most completed one and delete the incomplete one from one of the servers. surely i will use dblink to compare but what would be the SQL query for it?
in short some of the records are incomplete in local server while some of them are incomplete in main. is there any way to compare them and chose the completest one?
Thank you in advance.

A: instead of dblink, I recommend you to use potgres_fdw.
When you map the foreign table, you can use a simple SELECT INSERT to solve your problem. E.g.:
INSERT INTO remote.employee
SELECT local.* FROM public.employee AS local
WHERE NOT EXISTS (
     SELECT 1 FROM remote.employe AS remote
     WHERE local.id = remote.id
)

Remember to fix the WHERE filter to fit your table's primary keys.

EDIT: I make a small sample how to compare the rows of both tables as a gist: https://gist.github.com/sebastianwebber/7b4ab352733e8aab8b03f94d8aa0c7a9

The easy way to compare the rows is:
SELECT
    e1.id as e1_pk,
    e2.id as e2_pk,
    COALESCE(e1.* = e2.*, false) as equal
FROM employee1 as e1
RIGHT JOIN employee2 as e2 USING (id);

Hope it helps.

A: Typically, if you have the key column with the same values for the corresponding records you can use full outer join, and use the key column (i.e. ID) as the join key.
the query would be like
select a.id, a.name, a.surname.., b.id, b.name, b.surname..
from local_customer a full outer join remote_customer b on a.id = b.id

If there is a chance that the same ID points to different customers in those databases, you have to use other columns, like name, address, zip code etc - potentially creating a composite join key.
select a.id, a.name, a.surname.., b.id, b.name, b.surname..
from local_customer a full outer join remote_customer b
on a.name = b.name and a.surname = b.surname

I wrote a data comparison utility, and a free version is available for download. Have a look if it might be of use to you.
https://selectcompare.com


text:
Q: Android problem: null exception error when dereferencing CheckBox I'm running into a strange problem.
I have a CheckBox defined in a resource file:

When trying to see if the checkbox is checked or not, I use the following code:
CheckBox cb1 = (CheckBox)findViewById(R.id.check1);
when I execute the following:
if (cb1.isChecked())
{
}
I get a null exception error. I cannot figure out why this is happening.
Thanks for any help.

A: cb1 is null, which means that findViewById() couldn't find the view whose ID you specified. Do you have a CheckBox in your layout file with android:id="@+id/check1"?


text:
Q: Font Awesome Accessibility I have been using Font Awesome and according to their accessibility docs,
If your icon has semantic meaning, all you need to do is throw a title="meaning" attribute.
Auto-accessibility takes care of the rest, adding the following:
Proper ARIA role (role="img")
title tag with a proper id attribute
aria-labelledby attribute and wire it to the title tag.
But I tried it and it does not add aria-labelledby
And on testing with Site Improve, it throws error saying icon does not have alt text. How do I fix this?
working Code below:
https://codesandbox.io/s/40v5jk6no7
Code here
import React from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import fontawesome from "@fortawesome/fontawesome";
import FontAwesomeIcon from "@fortawesome/react-fontawesome";
import faCalendar from "@fortawesome/fontawesome-free-regular/faCalendar";
import faSquare from "@fortawesome/fontawesome-free-regular/faSquare";
import solid from "@fortawesome/fontawesome-free-solid";

fontawesome.config = {
  familyPrefix: "far"
};

fontawesome.library.add(faCalendar, faSquare);

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};

const App = () => (

    <Hello name="CodeSandbox" />

Start editing to see some magic happen {"\u2728"}

    Favorite calendar: <FontAwesomeIcon icon="calendar" title="magic" />
    Icon from regular: <FontAwesomeIcon icon={["far", "calendar"]} />

);

render(<App />, document.getElementById("root"));


text:
Q: Struts2: How to set a specific rendering for one of my Radio buttons label? In my web page, i need to display a list of several choice through radio buttons. And for one of these choice, the label is completed with an icon that could display a tooltip when the mouse is over it.
The html rendering is as below:

Available on..

As you can see, the label contains a link and an iconic font. I need to put this link for this specific radio button but i don't know how is it possible when i use the struts2 radio tag to display the list of radio buttons.
My Radio tag is :
<s:radio name="filter" list="filterList" listKey="id" listValue="label" value="%{#attr['filter']}" />

The html rendering is classic:
<input id="filter0" type="radio" value="0" name="filter">
Tout

And as i said before, i need to add a link in the label tag or juste after...
How is it possible ?

A: Try this
<s:iterator value="filterList" var="a" status="s">
    <input type="radio" name="filter" title="${a.label}" value="${a.id}" id="filter${a.id}"/>
    ${a.label}
</s:iterator>


text:
Q: How to resolve POJO dependency with DRL in Guvnor? I have imported the DRL file and required pojo as individual jar file in guvnor. I could see the dependent classes appearing as fact for individual rule and Guvnor exposes those rules via URL. I use changeset to consume the URL and apply the rules for my data. When I do that, I get below exception message for all the class I imported in the DRL file.

Unable to Analyse Expression
[Error: unable to resolve method using strict-mode: org.drools.spi.KnowledgeHelper.***]

Can someone help me in resolving this issue?
Thanks in advance!

A: Without seeing the DRL, I'll take a guess. I suspect that you're using the 'mvel' dialect, but your DRL is doing things which assume the Java dialect. Try changing that. You can see an example of this here:
Throwing exception in Guvnor (Guided Editor Rule)
If you post the DRL, then I may well need to reconsider and change/delete this answer. :)


text:
Q: android canvas draw line with pointer ended arrows both side. can anyone help me out with it.? @Override
public void onDraw(Canvas canvas) {
    /*canvas.drawLine(0, 0, 20, 20, paint);
    canvas.drawLine(200, 0, 0, 200, paint);*/
    /*canvas.drawLine(downxpos, downypos, upxpos, upypos, paint);*/
    for (Line l : lines) {

        canvas.drawLine(l.startX, l.startY, l.stopX, l.stopY, paint);
    }
}

example image
I Would like to draw the line like the image I show in canvas. I can draw the line but don't know how to add arrows to it.

A: Use these Methods to draw Arrow on both sides.
private void drawArrow1(Canvas canvas, Paint paint) {
    double degree = calculateDegree(x, x1, y, y1);
    float endX1 = (float) (x1 + ((10) * Math.cos(Math.toRadians((degree-30)+90))));
    float endY1 = (float) (y1 + ((10) * Math.sin(Math.toRadians(((degree-30)+90)))));

    float endX2 = (float) (x1 + ((10) * Math.cos(Math.toRadians((degree-60)+180))));
    float endY2 = (float) (y1 + ((10) * Math.sin(Math.toRadians(((degree-60)+180)))));

    canvas.drawLine(x1,y1,endX1,endY1,paint);
    canvas.drawLine(x1, y1, endX2,endY2,paint);
}

private void drawArrow(Canvas canvas, Paint paint) {

    double degree1 = calculateDegree(x1, x, y1, y);
    float endX11 = (float) (x + ((10) * Math.cos(Math.toRadians((degree1-30)+90))));
    float endY11 = (float) (y + ((10) * Math.sin(Math.toRadians(((degree1-30)+90)))));

    float endX22 = (float) (x + ((10) * Math.cos(Math.toRadians((degree1-60)+180))));
    float endY22 = (float) (y + ((10) * Math.sin(Math.toRadians(((degree1-60)+180)))));

    canvas.drawLine(x,y,endX11,endY11,paint);
    canvas.drawLine(x,y,endX22,endY22,paint);
}

public double calculateDegree(float x1, float x2, float y1, float y2) {
    float startRadians = (float) Math.atan((y2 - y1) / (x2 - x1));
    System.out.println("radian=====" + Math.toDegrees(startRadians));
    startRadians += ((x2 >= x1) ? 90 : -90) * Math.PI / 180;
    return Math.toDegrees(startRadians);
}

Where x,y is starting point and x1,y1 is ending point.


text:
Q: How to add disk to VMware's VM host more efficiently by using Ansible offical module? Env

*

*OS Version: CentOS 7.5

*Ansible Version: 2.8.4 with python 2.7.5

*ESXi and VCenter Version: 6.5.2

Purpose
I have already completed my code, but I wondering if there are more better way to add disk to VM host by  Ansible offical module.
My Method
The return message from vmware_guest_disk_facts
TASK [get VM info] *******************************************************************************************************
ok: [TFGH0001.TFGH.COM -> localhost] => changed=false
  guest_disk_facts:
    '0':
      backing_datastore: VCENTER01_DS01
      backing_eagerlyscrub: false
      backing_filename: '[VCENTER01_DS01] TFGH0001/TFGH0001-000001.vmdk'
      backing_thinprovisioned: false
      backing_type: FlatVer2
      backing_uuid: 6000C294-d22d-06a9-c89b-119e13fffe33
      backing_writethrough: false
      capacity_in_bytes: 32212254720
      capacity_in_kb: 31457280
      controller_key: 1000
      key: 2000
      label: Hard disk 1
      summary: 31,457,280 KB
      unit_number: 0
    '1':
      backing_datastore: VCENTER01_DS01
      backing_eagerlyscrub: false
      backing_filename: '[VCENTER01_DS01] TFGH0001/TFGH0001_3.vmdk'
      backing_thinprovisioned: false
      backing_type: FlatVer2
      backing_uuid: 6000C293-ae37-30f6-b684-d5b2416ff2f8
      backing_writethrough: false
      capacity_in_bytes: 10737418240
      capacity_in_kb: 10485760
      controller_key: 1000
      key: 2001
      label: Hard disk 2
      summary: 10,485,760 KB
      unit_number: 1

My Playbook
---
  - hosts: all
    remote_user: kai
    become: yes
    become_user: root
    become_method: sudo
    gather_facts: true

    vars:
      vcenter_host: "VCENTER01"
      vcenter_username: "TFGH\\kaikudou"
      vcenter_password: xxxxxxxxx
      target_host: "TFGH0001"

    tasks:

    - name: get VM info
      vmware_guest_disk_facts:
        hostname: "{{ vcenter_host }}"
        username: "{{ vcenter_username }}"
        password: "{{ vcenter_password }}"
        validate_certs: False
        datacenter: "{{ vcenter_host }}"
        name: "{{ target_host }}"
      delegate_to: localhost
      register: vm_disk_info

    # - name: show vm_disk_info
    #   debug:
    #     msg: "{{ vm_disk_info.guest_disk_facts['0'].backing_datastore }}"

    - name: Set empty list to store varialbe
      set_fact:
        all_scsi_number_list: []  # A list to store all scsi device number
        scsi_0: []  # A list to store scsi 0's device for counting the quantity
        scsi_1: []  # A list to store scsi 1's device for counting the quantity
        scsi_2: []  # A list to store scsi 2's device for counting the quantity
        scsi_3: []  # A list to store scsi 3's device for counting the quantity
        all_unit_number_list: []  # A list to store the device number from scsi controller

    - name: Set variable of datastore
      set_fact:
        host_datastore: "{{ vm_disk_info.guest_disk_facts['0'].backing_datastore }}"

    - name: Store scsi_number into all_scsi_number_list
      set_fact:
        all_scsi_number_list: "{{ all_scsi_number_list + [vm_disk_info.guest_disk_facts[item].controller_key] }}"
      loop: "{{ vm_disk_info.guest_disk_facts.keys() }}"

    - name: Find out scsi_controller 0 and store into scsi_0
      set_fact:
        scsi_0 : "{{ scsi_0 + [item] }}"
      loop: "{{ all_scsi_number_list }}"
      when: item == 1000

    - name: Find out the scsi_controller 1 and store into scsi_1
      set_fact:
        scsi_1 : "{{ scsi_1 + [item] }}"
      loop: "{{ all_scsi_number_list }}"
      when: item == 1001

    - name: Find out the scsi_controller 2 and store into scsi_2
      set_fact:
        scsi_2 : "{{ scsi_2 + [item] }}"
      loop: "{{ all_scsi_number_list }}"
      when: item == 1002

    - name: Find out the scsi_controller 3 and store into scsi_3
      set_fact:
        scsi_3 : "{{ scsi_3 + [item] }}"
      loop: "{{ all_scsi_number_list }}"
      when: item == 1003

    - name: Calcualte the quantity of scsi_*
      set_fact:
        scsi_0_number: "{{ scsi_0 | length }}"
        scsi_1_number: "{{ scsi_1 | length }}"
        scsi_2_number: "{{ scsi_2 | length }}"
        scsi_3_number: "{{ scsi_3 | length }}"

    - name: Verify the scsi controller's number because snapshot will also cost the device so less than 7 to prevent
      set_fact:
        scsi_number: "{{ item.src }}"
      loop:
        - { src: "0", when: "{{ (scsi_0_number <= '6' and scsi_0_number != '0') or (scsi_0_number == '0') }}" }
        - { src: "1", when: "{{ (scsi_1_number <= '6' and scsi_1_number != '0') or (scsi_1_number == '0') }}" }
        - { src: "2", when: "{{ (scsi_2_number <= '6' and scsi_2_number != '0') or (scsi_2_number == '0') }}" }
        - { src: "3", when: "{{ (scsi_3_number <= '6' and scsi_3_number != '0') or (scsi_3_number == '0') }}" }
      when: item.when

    # - name: Show scsi_number which we get
    #   debug:
    #     msg: "{{ scsi_number }}"

    - name: Change the scsi_number we obtained to 4 digit number
      set_fact:
        scsi_digit_number: "{{ item.src | int }}"
      loop:
        - { src: "1000", when: "{{ scsi_number == '0' }}" }
        - { src: "1001", when: "{{ scsi_number == '1' }}" }
        - { src: "1002", when: "{{ scsi_number == '2' }}" }
        - { src: "1003", when: "{{ scsi_number == '3' }}" }
      when: item.when

    # - name: Show scsi_digit_number which we get
    #   debug:
    #     msg: "{{ scsi_digit_number }}"

    - name: Check the number of devices from the scci_number we obtained
      set_fact:
        all_unit_number_list: "{{ all_unit_number_list + [vm_disk_info.guest_disk_facts[item].unit_number] }}"
      loop: "{{ vm_disk_info.guest_disk_facts.keys() }}"
      when: vm_disk_info.guest_disk_facts[item].controller_key == scsi_digit_number | int

    # - name: Show all_unit_number_list which we get
    #   debug:
    #     msg: "{{ all_unit_number_list | length | type_debug }}"

    - name: Find the max number in all_unit_number_list then plus 1 to add new disk
      set_fact:
        disk_number: "{{ all_unit_number_list | max + 1 }}"
      ignore_errors: yes

    - name: If we have to add new scsi controller then the all_unit_number_list will be empty list, so we need to prevent it failed
      set_fact:
        disk_number: 0
      when: all_unit_number_list | length == 0

    - name: add disk
      vmware_guest_disk:
        hostname: "{{ vcenter_host }}"
        username: "{{ vcenter_username }}"
        password: "{{ vcenter_password }}"
        validate_certs: False
        datacenter: "{{ vcenter_host }}"
        name: "{{ target_host }}"
        disk:
          - size_gb: 2
            type: thin
            state: present
            datastore: "{{ host_datastore }}"
            # autoselect_datastore: True
            scsi_controller: "{{ scsi_number | int }}"
            unit_number: "{{ disk_number | int }}"
            scsi_type: 'paravirtual'

According to VMware offical document 1 VM host can only have 4 scsi controller and each of them can have 15 devices to attach. So I have to write many condition to prevent it.
The strange thing is that when adding a hard disk from VCenter, it will not trigger the problem that the number of hard disks exceeds 7. However, Ansible's module cannot increase the hard disk when unit_number exceeds 7, and must change another SCSI Controller.
Is there any other better way besides doing this? or something I can refer to and study it?
Thank you for your help and advice!

A: I tried to rephrase the problem a bit. This is far from perfect as it will not take into a account "holes" in numbering (i.e. disk or controllers removed from the sequence). But I don't think your current implementation does either. Mine should work with far less variable assignment and will gracefully fail if there are no more slots available.

*

*Get disk info from guest (pasted in a var for the example).

*From info, loop on number of configured controller. For each controller record its key, number, number of devices and max configured device id.

*Extract from the list the first controller having an available slot

*If this fail create an empty controller info incrementing the scsi device number or fail if max is reached.

Note: I used json_query so you will need to pip(3) install jmespath on your ansible controller machine to run the example.
The playbook:
---
- name: My take to your vmware disk management question
  hosts: localhost
  gather_facts: false

  vars:
    # Info copied from your example.
    vcenter_host: "VCENTER01"
    vcenter_username: "TFGH\\kaikudou"
    vcenter_password: xxxxxxxxx
    target_host: "TFGH0001"

    # Max number of devices per scsi controller
    scsi_max_devices: 15
    # Max id for scsi controllers
    scsi_max_controller_id: 3

    # Calling the two following vars before getting facts will fail
    # but since we don't need to loop to get them they can be statically
    # declared in playbook vars
    scsi_controller_unique_keys: >-
      {{
        vm_disk_info.guest_disk_facts
        | dict2items
        | map(attribute='value.controller_key')
        | list
        | unique
        | sort
      }}
    host_datastore: "{{ vm_disk_info.guest_disk_facts['0'].backing_datastore }}"

    # Your example data to play with (minified, single line)
    # To take from module call return IRL.
    vm_disk_info: {"guest_disk_facts":{"0":{"backing_datastore":"VCENTER01_DS01","backing_eagerlyscrub":false,"backing_filename":"[VCENTER01_DS01] TCB0945/TFGH0001-000001.vmdk","backing_thinprovisioned":false,"backing_type":"FlatVer2","backing_uuid":"6000C294-d22d-06a9-c89b-119e13fffe33","backing_writethrough":false,"capacity_in_bytes":32212254720,"capacity_in_kb":31457280,"controller_key":1000,"key":2000,"label":"Hard disk 1","summary":"31,457,280 KB","unit_number":0},"1":{"backing_datastore":"VCENTER01_DS01","backing_eagerlyscrub":false,"backing_filename":"[VCENTER01_DS01] TFGH0001/TFGH0001_3.vmdk","backing_thinprovisioned":false,"backing_type":"FlatVer2","backing_uuid":"6000C293-ae37-30f6-b684-d5b2416ff2f8","backing_writethrough":false,"capacity_in_bytes":10737418240,"capacity_in_kb":10485760,"controller_key":1000,"key":2001,"label":"Hard disk 2","summary":"10,485,760 KB","unit_number":1}}}

  tasks:

    - name: Create a list holding all the info we need for each existing controller
      vars:
        scsi_controller_devices_query: >-
          [?to_string(value.controller_key)=='{{ controller_key }}'].value.unit_number[]
        scsi_controller_devices: >-
          {{
            vm_disk_info.guest_disk_facts |
            dict2items |
            json_query(scsi_controller_devices_query)
          }}
        # Construct object directly as json so that we retain int type for further comparison usage.
        current_controller: >-
          {
            "controller_number": {{ controller_number | int }},
            "controller_key": {{ controller_key | int }},
            "number_of_devices": {{ scsi_controller_devices | length | int }},
            "max_unit_number": {{ scsi_controller_devices | max | int }},
          }
      set_fact:
        scsi_controllers_info: "{{ scsi_controllers_info | default([]) + [current_controller] }}"
      loop: "{{ scsi_controller_unique_keys }}"
      loop_control:
        loop_var: controller_key
        index_var: controller_number

    - block:

        # Note: This was already sorted when we got controllers list in our first loop
        - name: "Extract first controller having less than {{ scsi_max_devices }} disks"
          set_fact:
            scsi_controller: >-
              {{
                (
                  scsi_controllers_info |
                  selectattr('number_of_devices', '<', scsi_max_devices) |
                  list
                ).0
              }}

      rescue:

        - name: Fail if we cannot add an other controller id
          # i.e.controllernumber of our last element in list is equal (or greater for tests) that scsi_max_controller_id
          fail:
            msg: All scsi controllers are full, disk cannot be added.
          when: scsi_controllers_info[-1].controller_number >= scsi_max_controller_id

        - name: Return an empty controller with incremented id
          set_fact:
            scsi_controller: >-
              {
                "controller_number": {{ scsi_controllers_info[-1].controller_number + 1 | int }},
                "controller_key": {{ scsi_controllers_info[-1].controller_key + 1 | int }},
                "number_of_devices": 0,
                "max_unit_number": -1,
              }

    - name: Show what the call to vmware_guest_disk would look like
      vars:
        vmware_guest_disk_params:
          hostname: "{{ vcenter_host }}"
          username: "{{ vcenter_username }}"
          password: "{{ vcenter_password }}"
          validate_certs: False
          datacenter: "{{ vcenter_host }}"
          name: "{{ target_host }}"
          disk:
            - size_gb: 2
              type: thin
              state: present
              datastore: "{{ host_datastore }}"
              # autoselect_datastore: True
              scsi_controller: "{{ scsi_controller.controller_number }}"
              unit_number: "{{ scsi_controller.max_unit_number + 1 }}"
              scsi_type: 'paravirtual'
      debug:
        msg: "{{ vmware_guest_disk_params }}"


text:
Q: How do I add a signed integer to an unsigned integer in Rust? Do I have to branch on the sign of the signed integer, like in the example below? (In the real program y is calculated to change the index pointing into a 64K array, and wraparound is the desired behavior)
fn main() {
    let mut x: u16 = 100;
    let y: i8 = -1;
    //x += y;
    if y < 0 {
        x -= i8::abs(y) as u16;
    } else {
        x += i8::abs(y) as u16;
    }
    println!("{}", x);
}

A: *

*Signed integers are twos complement

*numeric cast sign extends an i8 as u16
That means you can cast y as u16 it will turn into a twos complement value that a wrapping_add will rightfully handle if y was negative.
In short: do as @Veedrac said.
fn main() {
    let mut x: u16 = 100;
    let y: i8 = -1;
    x = x.wrapping_add(y as u16);
    println!("{}", x);
}

A: Rustc 1.66+ support mixed integer ops. Note, this was previously unstable under mixed_integer_ops.
With this you can do:
#[feature(mixed_integer_ops)]
fn main() {
    let mut x: u16 = 100;
    let y: i8 = -1;
    //x += y;
    x = x.wrapping_add_signed(y); // wraps on overflow
    println!("{}", x);
}

There's wrapping_, checked_, saturating_, and overflowing_ variants, depending on what behavior you want on overflow; and the methods are on both signed and unsigned integers, named _unsigned and _signed respectively (so the above could also be expressed as x = y.wrapping_add_unsigned(x);)

A:
In the real program y is calculated to change the index pointing into a 64K array , and wraparound is the desired behavior)

There is no consensus of how things should be done, but here's my advice: Provide to the user two functions:
fn add(&mut self, index: u16) -> u16 { // return previous index why not
    // ..
}

fn sub(&mut self, index: u16) -> u16 {
    // ..
}

You could also add a helper function that should not be used lightly:
fn offset(&mut self, offset: i16) -> u16 {
    // ..
}

The purpose is that the user should know whenever use sub or add, the user should manage only unsigned type. That question is opinion oriented so I understand if people don't agree.
Full example:
use std::mem;

#[derive(Debug, PartialEq, PartialOrd)]
struct MyIndex {
    index: u16,
}

impl MyIndex {
    fn new(index: u16) -> Self {
        Self { index }
    }

    fn add(&mut self, index: u16) -> u16 {
        let index = self.index.wrapping_add(index);
        self.replace(index)
    }

    fn sub(&mut self, index: u16) -> u16 {
        let index = self.index.wrapping_sub(index);
        self.replace(index)
    }

    fn offset(&mut self, offset: i16) -> u16 {
        if offset > 0 {
            self.add(offset as u16)
        } else {
            self.sub(offset as u16)
        }
    }

    fn replace(&mut self, index: u16) -> u16 {
        mem::replace(&mut self.index, index)
    }
}

fn main() {
    let mut index = MyIndex::new(42);

    let mut other_index = MyIndex::new(84);

    let (x, first) = if index > other_index {
        (index.index - other_index.index, true)
    }
    else {
        (other_index.index - index.index, false)
    };

    // ...

    if first {
        index.sub(x);
    }
    else {
        other_index.sub(x);
    }
    println!("{:?} {:?}", index, other_index);

    index.sub(21);
    println!("{:?}", index);

    index.offset(-1);
    println!("{:?}", index);
}


text:
Q: Combine list of items into a single bucket with a certain value, then create pie chart I need to create a pie chart with four levels of risk from high to low risk. I have a list of items that I will manually assign a risk level. I then need to group those representing a single level creating four different level groups. These I will need to graph using a pie chart. How do I do this?

A: Before creating the pie chart, you should perform the calculation of the information that will go into the chart.
Here's an example:

The A column holds the data, and the D column holds the results of the formula. C is just there to be a little more clear of what you're seeing.
In this example, if we want to get the percentage of 1s in column A, the formula would be =(COUNTIF(A:A, "=1")/COUNT(A:A)), where "=1" gets replaced with whatever you are searching for. In D1, it's "=1", in D2 it's "=2", and so on.
Once you have this information calculated correctly, creating a pie chart will be as easy as adding the chart and selecting the four D rows (in this example).


text:
Q: Swift - "use of unresolved identifier" I am studying Swift!
I want create Main interface on xib.
But have error "use of unresolved identifier".

Add code from MainViewController
import Foundation

public class MainViewController : BaseViewController {

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        // TODO: Write your test code here
        // ...
    } }

UPD:(Add image)

A: This same issue happened with me too. I've only one target membership and still, I was getting "use of unresolved identifier". I build the project and nothing changed.
I tried to uncheck and recheck the target membership and the issue was resolved.
If this doesn't resolve your issue, try building the project, check for typo error or use autocompletion and Quick Help to find recognized identifiers.

A: 1) Right Click your MainViewController.swift
2) Select Show File Inspector
3) On Right side panel, look at Target Membership
4) Add your class to target by check the box :)

A: You likely didn't add the class to the target. Click on the MainViewController class and open the utilities tab on the upper right corner in Xcode:

Make sure the appropriate target is checked.
EDIT: Apparently you don't have target membership there - which is bizarre in and of itself. Try re-creating the MainViewController class from scratch and make sure the correct target is selected:

A: Just a tip for those who found this question with this issue like mine.
This issue tortured me for days!  I can run the project but the red error sign kept showing up. At first blamed this to Xcode (Sorry, Xcode).
But after I read all the answers in this thread and checked my source file's Target Membership, I realized that I was wrong to blame Xcode.
The file where this issue was reported had three Target Membership: the main one, the one for tests and another for ui tests. But the variable it refer to was in a file that had only one Target Membership, the main one.
So to recap: check the Target Membership of the file where issue is reported, and of the one where the unresolved identifier is declared. Make sure Membership the later contains that of the formal.


text:
Q: Table has duplicate data and can't get two aggregates functions to work in SQL Query The problem is that the table "addresses" has multiple entries where a user has updated their address. I just need the latest one. I tried to use MAX(uPDATED_AT) in the "addresses" table but get an error. Well, I first wrote the code below and realized many rows are duplicates or close to duplicates. I just need to grab their last change to their address but I get errors when trying to add another aggregate to the HAVING clause. Can someone please assist? I am a newbie at SQL but would love to know the issue and correct it going forward.
I am using PostgreSQL by the way
Select
  last_name,
  first_name,
  donator,
  customer_id,
  phone,
  address,
  city,
  state,
  zipcode,
  events.buyer_id

  from events

  join addresses on events.buyer_id = addresses.buyer_id
  inner join customer_extras on addresses.buyer_id = customer_extras.buyer_id
  inner join Customer_roles on events.buyer_id = Customer_roles.buyer_id
  inner join People on Customer_roles.buyer_id = People.id

  group by
  customer_id,
  member_status,
  events.event_type,
  first_name,
  last_name,
  address,
  city,
  state,
  phone,
  donator,
  zipcode,
  events.buyer_id

  HAVING MIN(events.created_at) between '2015-06-01'
  and '2015-08-01' and event_type ILIKE 'MEMBER_TABLET%' and member_status IN
  ('moved','never answered', 'refused', 'complete')

A: You need to use windowing functions, your query will look like this
select t.*, dense_rank() over (partition by <column_with_duplicate_values> order by <date> desc) dr from ...

Above query gives ranks in descending order. You need to enclose in another query
select * from (<above_query>) q where dr=1;

A: Assuming your addresses table has a field named create_date (I'm guessing, but you can sub your actual field name), I think you want to use my favorite analytic function, row_number:
with most_recent_address as (
  select a.*, row_number() over (partition by buyer_id order by create_date desc) as rn
  from addresses as a  -- fix is here
)
Select
  last_name, first_name, donator, customer_id,
  phone, address, city, state, zipcode,
  events.buyer_id
from events
  join most_recent_address a on events.buyer_id = a.buyer_id and a.rn = 1
  inner join customer_extras on addresses.buyer_id = customer_extras.buyer_id
  inner join Customer_roles on events.buyer_id = Customer_roles.buyer_id
  inner join People on Customer_roles.buyer_id = People.id
where
  event_type ILIKE 'MEMBER_TABLET%' and
  member_status IN ('moved','never answered', 'refused', 'complete')
group by
  customer_id, member_status, events.event_type,
  first_name, last_name, address, city,
  state, phone, donator, zipcode, events.buyer_id
HAVING
  MIN(events.created_at) between '2015-06-01' and '2015-08-01'

Again, if the ranking mechanism is not create_date, change it to whatever it should be.
Depending on the size of your data, you may want to switch to the max analytic.  It does not invoke an order by and therefore should be O(n).  However, note that if you have two of the same create_date values for the same buyer_id, this will yield two records instead of one.  You know your data better than I do, so you can probably assess the risk of this vs the improved performance:
with most_recent_address as (
  select a.*, max(create_date) over (partition by buyer_id) as max_date
  from addresses as a
)
Select
  last_name, first_name, donator, customer_id,
  phone, address, city, state, zipcode,
  events.buyer_id
from events
  join most_recent_address a on events.buyer_id = a.buyer_id and a.create_date = a.max_date
  inner join customer_extras on addresses.buyer_id = customer_extras.buyer_id
  inner join Customer_roles on events.buyer_id = Customer_roles.buyer_id
  inner join People on Customer_roles.buyer_id = People.id
where
  event_type ILIKE 'MEMBER_TABLET%' and
  member_status IN ('moved','never answered', 'refused', 'complete')
group by
  customer_id, member_status, events.event_type,
  first_name, last_name, address, city,
  state, phone, donator, zipcode, events.buyer_id
HAVING
  MIN(events.created_at) between '2015-06-01' and '2015-08-01'

Also, and you didn't ask this, but you may notice I moved two of your conditions from the having to the where clause.  This should help improve query performance, as you are eliminating rows BEFORE the grouping rather than after.  Having is only necessary (over where) when you apply the condition to a grouping function.  Since ordering/grouping is among the most expensive operations on the database, this can make a big difference with large datasets.


text:
Q: Como recuperar um intervalo de meses entre duas datas? public function getMesesAtraso()
    {
        $data_debito= date_create($this->data_debito);
        return date_diff(date_create(now('m')), $data_debito)->format('%m');
    }

Só retorna meses dentro de 2019

A: Você não consegue comparar meses diretamente em anos diferentes pois o php arredonda o valor. Por exemplo, se a diferença for de 13 meses, ele irá gerar 1 ano e 1 mês. Então, quando você faz o filtro pelo format ele trará uma informação inesperada. Criei uma alternativa que explicarei a seguir, veja:
$data1 = new DateTime("2019-07-26");
$data2 = new DateTime("2020-08-26");

$diff = $data1->diff($data2); // comparação
$meses = $diff->y * 12 + $diff->m; // quantidade de meses final

echo  $meses;

Nesse pequeno script eu faço a comparação, depois eu multiplico por 12 a quantidade de anos de diferença e somo com a quantidade de meses.
O resultado será exatos 13 meses.


text:
Q: Looping hash but showing the entire set in last loop I have the following code in Rails 3.2:
Changeset: <%= @version.changeset %>

Length: <%= @version.changeset.length %>

<%= @version.changeset.each_with_index do |(key, value), i| %>
  <%= i %> - <%= key %> - <%= value %>

<% end %>

Output is:
Changeset: {"getting_there"=>["a", "b"], "description"=>["c", "d"]}

Length: 2

0 - getting_there - ["a", "b"]
1 - description - ["c", "d"]
{"getting_there"=>["a", "b"], "description"=>["c", "d"]}

I have no idea why the last {"getting_there"=>["a", "b"], "description"=>["c", "d"]} is showing. It shouldn't be shown.

A: Instead of:
<%= @version.changeset.each_with_index do |(key, value), i| %>

you need to have:
<% @version.changeset.each_with_index do |(key, value), i| %>

This = means that in the end value of each_with_index call (which is hash on which you call this) will be displayed.


text:
Q: fast numpy addnan I would like to add thousands of 4D arrays element wise and accounting for nans.
A simple example using 1D arrays would be:
X = array([4,7,89,nan,89,65, nan])
Y = array([0,5,4, 9,  8, 100,nan])
z = X+Y
print z = array([4,12,93,9,97,165,nan])

I've written a simple for loop around this but it takes forever - not a smart solution.
Another solution could be creating a larger array and use bottleneck nansum but this would take too much memory for my laptop. I need a running sum over 11000 cases.
Does anyone have a smart and fast way to do this?

A: You could do something like:
arr1 = np.array([1.0, 1.0, np.nan, 1.0, 1.0, np.nan])
arr2 = np.array([1.0, 1.0, 1.0, 1.0, 1.0, np.nan])
flags = np.isnan(arr1) & np.isnan(arr2)
copy1 = arr1.copy()
copy2 = arr2.copy()
copy1[np.isnan(copy1)] = 0.0
copy2[np.isnan(copy2)] = 0.0
out = copy1 + copy2
out[flags] = np.NaN
print out
array([  2.,   2.,   1.,   2.,   2.,  NaN])

to find the locations in the arrays where both have a NaN in that index. Then, do essentially what @mgilson suggested, as in make copies and replace the NaNs with 0.0, add the two arrays together, and then replace the flagged indices above with np.NaN.

A: import numpy as np
z=np.nansum([X,Y],axis=0)

A: Here is one possibility:
>>> x = np.array([1, 2, np.nan, 3, np.nan, 4])
... y = np.array([1, np.nan, 2, 5, np.nan, 8])
>>> x = np.ma.masked_array(np.nan_to_num(x), mask=np.isnan(x) & np.isnan(y))
>>> y = np.ma.masked_array(np.nan_to_num(y), mask=x.mask)
>>> (x+y).filled(np.nan)
array([  2.,   2.,   2.,   8.,  nan,  12.])

The real difficulty is that you seem to want nan to be interpreted as zero unless all values at a particular position are nan.  This means that you must look at both x and y to determine which nans to replace.  If you are okay with having all nan values replaced, then you can simply do np.nan_to_num(x) + np.nan_to_num(y).

A: Not sure how this would perform, but it's worth a shot :)
def nan_to_zero(array):
    new_arr = array.copy()
    new_arr[np.isnan(array)] = 0.
    return new_arr

sum( nan_to_zero(arr) for arr in array_generator )

This doesn't result in a NaN in the last place of your array though.  It results in a 0 ...

A: I see several simpler solutions:

*

*(EDITED) Using np.ma
mX = np.ma.masked_array(X, mask=np.isnan(X))
mY = np.ma.masked_array(Y, mask=np.isnan(Y))
mZ = np.ma.masked_array(mX.filled(0) + mY.filled(0),
                        mask=mX.mask * mY.mask)
Z = mZ.filled(np.nan)

*(EDITED) Not using np.ma
mx = np.isnan(x)
my = np.isnan(y)
z = np.where(mx,0,x) + np.where(my,0,y)
z[mx&my] = np.nan


text:
Q: Expected time to type a certain sequence I have a simplified version of the monkey typing ABRACADABRA problem and my approach to it does not yield the correct answer but I haven't been able to spot the error in my reasoning.
The problem is as follows. There is a typewriter with three characters on it, namely A, B and C. There is also a monkey hitting a key on the typewriter randomly such that after $n$ hits, the resulting sequence is $X_1X_2\ldots X_n$ where $(X_i)_i$ is an iid sequence with $P\{X_1 = A\} = P\{X_1 = B\} = P\{X_1 = C\} = 1/3$. Let $T$ be the random time (in this case also a stopping time) the sequence ABC first appears once the monkey starts typing. What is the expected value of $T$?
My approach was based on conditioning the expectation of $T$ on the first hits as follows.
\begin{align}
E[T] &= E[T\mid A]\frac{1}{3} + \underbrace{E[T\mid B]}_{E[T] + 1}\frac{1}{3} + \underbrace{E[T\mid C]}_{E[T] + 1}\frac{1}{3} \\
E[T\mid A] &= \underbrace{E[T\mid AA]}_{E[T\mid A] + 1}\frac{1}{3} + E[T\mid AB]\frac{1}{3} + \underbrace{E[T\mid AC]}_{E[T] + 2}\frac{1}{3} \\
E[T\mid AB] &= \underbrace{E[T\mid ABA]}_{E[T\mid A] + 2}\frac{1}{3} + \underbrace{E[T\mid ABB]}_{E[T] + 3}\frac{1}{3} + \underbrace{E[T\mid ABC]}_{3}\frac{1}{3} \\
\end{align}
Here I can solve for $E[T],E[T\mid A],E[T\mid AB]$ but I get $E[T] = 3$, which I know is not the right answer. Can someone point out where I am going wrong?

A: My set up is quite similar to yours, but I get an expected value of $27$, which I believe is correct (by calculating it a different way).
Let $E$ be the expected number of steps until ABC appears.
Let $E_A$ be the expected number of steps after an A, and $E_{AB}$ be the expected number of steps after an AB.
Then, on the first step, either an A appears (probability 1/3) or it doesn't (probability 2/3).  If it doesn't, then we've take one step, and are back where we started, so
$$
E = \frac{1}{3}(1+E_A) + \frac{2}{3}(1+E).
$$
If the current step was an A, then one of three things happens: we type a B, an A, or neither, each with 1/3 probability.  Hence:
$$
E_A = \frac{1}{3}(1+E_{AB}) + \frac{1}{3}(1+E_A) + \frac{1}{3}(1+E).
$$
If we've reached the AB state, then one of three things happens: we type a C (and we're done), we type an A, or neither, each with probability 1/3.  Hence:
$$
E_{AB} = \frac{1}{3}(1) + \frac{1}{3}(1+E_A) + \frac{1}{3}(1+E)
$$
where $E$ is the expected number of steps until $ABC$, $E_A$ is the expected number of steps following an $A$, and $E_{AB}$ is the expected number of steps following $AB$.
Solving this system, I find $E=27$.
In your system, you have some expressions like $E(T)+2$ and $E(T)+3$ which should be $E(T)+1$, since you have already counted the other steps by earlier $E(T)+1$ expressions.


text:
Q: Is there a way to detect if the cursor is inside an element? I'm making a website, and I need to detect whether or not the cursor is within an element (specifically any div with the class element)
However, it's not as simple as that. I want to be able to detect which element is the one activating the function, and activate it behind an element div that the mouse is dragging around.
I've seen stuff like this before, but they didn't work behind other elements period, let alone an element that matches the conditions of the if statement.
I want the code to, when someone lets go of dragging an element, check if the cursor is inside another element behind it. If it is, delete the element the cursor was dragging around and change the text inside that element behind.
Here's the relevant code:
function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  var xoffset = 0, yoffset = 0;
  if (document.getElementById(elmnt.id + "header")) {
    // if present, the header is where you move the DIV from:
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    elmnt.parentNode.appendChild(elmnt);
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
    if (???????) {
      //get that element and merge
      mergeElements(?????);
    }
  }

  function mergeElements(behind) {
    //delete the held element
    elmnt.parentNode.removeChild(elmnt);
    //change the text on the element behind it
    behind.innerHTML = "MERGE TEST"
  }
}

TEST1

TEST2

TEST3

LINE TESTING

OVERFLOW TESTING

If you need more code, please say so. I'm not exactly sure what's really relevant or not.


text:
Q: How to use windows application installed on server from remote computers? I have an C#.Net windows application developed and has installed it on server (which is nothing but my pc) now I want to allow remote computers to use that application, but I am getting error as this particular remote computer Login to this user "abc" is failed.
I searched for solutions and have tried giving permissions to the public users in SQL server database and have done all the methods which is mentioned in this following link, step by step procedure. http://msdn.microsoft.com/en-us/library/ms345343(v=sql.100).aspx
then too I am not able to find solution for this. Please help me solving this. I would appreciate if someone suggests me step by step procedure.
As I am very new to the development, this is my first job and I am all alone to develop this application since I am the only software developer in our company.

A: I don't know if you mean to share a windows desktop application over your network with others, or a web application to share with others.
For the first one (windows desktop), y'll have to make a installation of the application. (Menu Build => publish {project name }
For the other option you need a web-server. Mostly available by a provider, but also to create for internal use, (server 2012).
Beside that, there a small solution that will create a similar environment.
Lets flow the information to help you to get along

A: For the desktop. You've choose by publish "cd or dvd"or "from a unc path or file share"  option to set it up for installation? other wise that's the case.
If you authenticate with the database, i'll understand the authentication error.
That's the last part.
I think your database(DB) has a local connection which works only on your machine.
Your DB got to have a access(connection) where all application can reach it.
I'll can't remember it for msSQL (Ask google), mySQL takes care of it by ip of the machine where you have the DB engine running and (standard) port 3306.
If you'll tell the application in his connectionstring (app.config) this information it will connect from all places (even your local machine) with that connection and will work on all computers who can reach the DB.
Hope it helps you futher


text:
Q: Python and CodeEval: Why isn't my solution to this Multiplication Table challenge not correct? So I've been digging into some of the challenges at CodeEval during the last couple of days. One of them asks you to print a pretty-looking multiplication table going up to 12*12. While on my computer this solution works properly, the site does not accept it.
Can somebody help me out?
for i in range(1,13):
    for j in range(1,13):
       if j==1:
        print i*j,
       elif i>=10 and j==2:
        print '{0:3}'.format(i*j),
       else:
        print '{0:4}'.format(i*j),
    print

Here's a description of the challenge:

Print out the table in a matrix like fashion, each number formatted to a width of 4 (The numbers are right-aligned and strip out leading/trailing spaces on each line).

A:
Print out the table in a matrix like fashion, each number formatted to a width of 4
  (The numbers are right-aligned and strip out leading/trailing spaces on each line).

I think that following code may pass, according to the given rules. But it's only a guess
as I'm not playing on codeeval.
# python3 code, use from __future__ import print_function if you're using python2
for i in range(1,13):
    for j in range(1,13):
        print('{:4}'.format(i*j), end="")
    print ("")

I guess your problem is that you're having a 5 alignment because you forgot that the print foo,
syntax in python 2 is adding a space. Also they say width of 4, whereas you tried to be smart, and
align accordingly to the size of the value.
edit: here's more details about what's wrong in your code, let's take two lines of your output:
1    2    3    4    5    6    7    8    9   10   11   12
10  20   30   40   50   60   70   80   90  100  110  120
AA␣BBB␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣

so what your code is doing is:
if j==1: print i*j,

outputs the AA␣,
elif i>=10 and j==2:
    print '{0:3}'.format(i*j),

outputs the BBB␣ and
else:
    print '{0:4}'.format(i*j),

outputs the CCCC␣.
The ␣ is an extra space added by python because of the use of the , at the end of the print, to get that, see that snippet:
>>> def foo():
...  print 1234,
...  print 1234,
...  print
...
>>> foo()
1234 1234

The format '{0:3}' right aligns the integer to the right as expected, but only with a padding of three, whereas the '{0:4}' does it according to the rules. But as you're adding an extra space at the end, it's not working as you're writing it. That's why it's better to use python3's print expression that makes it simpler, using the end keyword.

A:
Print out the table in a matrix like fashion, each number formatted to a width of 4 (The numbers are right-aligned and strip out leading/trailing spaces on each line).

However, the output fails to meet this requirement which is made more visible by timing bars.
1    2    3    4    5    6    7    8    9   10   11   12^N
2    4    6    8   10   12   14   16   18   20   22   24^N
3    6    9   12   15   18   21   24   27   30   33   36^N
||||----||||----||||----||||----||||----||||----||||----

This correct padding for a "width of 4, right-aligned" should look like
   1   2   3   4   5   6   7   8   9  10  11  12^N
||||++++||||++++||||++++||||++++||||++++||||++++

And then with "strip out leading/trailing spaces on each line" the correct result is
1   2   3   4   5   6   7   8   9  10  11  12^N
|++++||||++++||||++++||||++++||||++++||||++++

While the current incorrect output, with the timing bars for correct output looks like
1    2    3    4    5    6    7    8    9   10   11   12^N
|++++||||++++||||++++||||++++||||++++||||++++???????????


text:
Q: How do I use TestNG with Apache Ivy? I tried to use TestNG with Apache Ivy, but was unsuccessful. Here is my ivy.xml:
<ivy-module version="2.0">

    <info organisation="me" module="myproject"/>

    <dependencies>
      <dependency org="org.testng" name="testng" rev="5.8" />
    </dependencies>

</ivy-module>

This fails to actually download a TestNG jarfile. It seems to be because TestNG has a jarfile for jdk14 and jdk15. Here's the output from ivy:retrieve:
[ivy:retrieve] :: resolving dependencies :: me#myproject;working@jared-mbp17
[ivy:retrieve]  confs: [default]
[ivy:retrieve]  found org.testng#testng;5.8 in public
[ivy:retrieve] :: resolution report :: resolve 1139ms :: artifacts dl 11ms
    ---------------------------------------------------------------------
    |                  |            modules            ||   artifacts   |
    |       conf       | number| search|dwnlded|evicted|| number|dwnlded|
    ---------------------------------------------------------------------
    |      default     |   1   |   1   |   1   |   0   ||   1   |   0   |
    ---------------------------------------------------------------------
[ivy:retrieve]
[ivy:retrieve] :: problems summary ::
[ivy:retrieve] :::: WARNINGS
[ivy:retrieve]      [FAILED     ] org.testng#testng;5.8!testng.jar:  (0ms)
[ivy:retrieve]  ==== shared: tried
[ivy:retrieve]    /Users/jared/.ivy2/shared/org.testng/testng/5.8/jars/testng.jar
[ivy:retrieve]  ==== public: tried
[ivy:retrieve]    http://repo1.maven.org/maven2/org/testng/testng/5.8/testng-5.8.jar
[ivy:retrieve]      ::::::::::::::::::::::::::::::::::::::::::::::
[ivy:retrieve]      ::              FAILED DOWNLOADS            ::
[ivy:retrieve]      :: ^ see resolution messages for details  ^ ::
[ivy:retrieve]      ::::::::::::::::::::::::::::::::::::::::::::::
[ivy:retrieve]      :: org.testng#testng;5.8!testng.jar
[ivy:retrieve]      ::::::::::::::::::::::::::::::::::::::::::::::
[ivy:retrieve]
[ivy:retrieve] :: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS

In the repository you can see two different jarfiles:
http://repo1.maven.org/maven2/org/testng/testng/5.8/testng-5.8-jdk14.jar
http://repo1.maven.org/maven2/org/testng/testng/5.8/testng-5.8-jdk15.jar
How do I specify either jdk14 or jdk15?

A: You need to specify the classifier of the artifact you want.
There is a related fix as of 2.1.0-RC1. You can use the element artifact within the dependency element to specify the classifier you want. In this case, the classifier should be jdk14 or jdk15. If you want jdk15 your ivy.xml would then be:
<ivy-module version="2.0"
            xmlns:e="http://ant.apache.org/ivy/extra">

    <info organisation="me" module="myproject"/>

    <dependencies>
      <dependency org="org.testng" name="testng" rev="5.8"
                  transitive="false">
        <artifact name="testng" type="jar" ext="jar" e:classifier="jdk15" />
      </dependency>
    </dependencies>

</ivy-module>

Note the specification of the XML namespace "http://ant.apache.org/ivy/extra" as an attribute of the ivy-module element. Without that the e:classifier won't work.


text:
Q: Maven + Java package declaration We have a Maven project (packaged as JAR) with Java files. A new Java source file was recently added to this project. The path in which the Java file was added, does not match its package declaration. As expected, Eclipse shows an error in the class for the mismatch. However, Maven builds the project just fine. In the generated JAR file, the .class file is present in the path indicated by the package declaration. We tried moving the Java source file to other incorrect folders (i.e. different from the package declaration), but every time Maven builds the project fine.
So, does Maven ignore the actual directory in which the .java file is present? Does it only consider package declaration?

A: The Maven Compiler plugin internally assembles a command line call containing the arguments passed to javac, one argument per source file (using the sourcefiles version of the javac call). It does pass the actual source folders also for meta-capabilities like annotation processing, but when individual source files are passed to javac, these take precedence and the compiler has no efficient way to find out which file belongs to which source folder and hence can't validate the package structure.
The Maven Compiler Plugin internally uses the Plexus Compiler API, and you can find the relevant code in these two classes:

*

*plexus-compiler-api: AbstractCompiler

*plexus-compiler-javac: JavacCompiler