text:
Q: Fill remaining dates between dates in SQL Server I have the following data in a table:

ItemID
Date
Status

001
2021-01-12
Active

001
2021-01-16
Discontinued

001
2021-01-20
Active

I need to fill in the remaining dates like this:

ItemID
Date
Status

001
2021-01-12
Active

001
2021-01-13
Active

001
2021-01-14
Active

001
2021-01-15
Active

001
2021-01-16
Discontinued

001
2021-01-17
Discontinued

001
2021-01-18
Discontinued

001
2021-01-19
Discontinued

001
2021-01-20
Active

Also, I need suggestions on will it be efficient to fill data like this or create two different columns for Valid from and to dates in Data Warehouse?

A: I have a working solution, but I am sure there are better ways to do this. I assume you would like a working solution, and then you can investigate the performance and optimize it if need be.
As pointed out in the comments, to solve this it is easiest if you have a calendar table. I assume you do not have anything, so I start from scratch. I generate the numbers 0 - 9 and then through successive CROSS JOINS I use those numbers to generate the numbers 0 - 10,000. I did make the assumption that there are not more than 10,000 days between the minimum date and the maximum date, but if this is not correct you can change the code to generate more numbers.
My approach uses several common table expressions as this is how I work to incrementally solve a problem. So first generate the digits, then generate numbers, then determine the minimum and maximum dates for each ItemID, then create a recordset that includes all the dates between the minimum and maximum dates for each ItemID, then I LEFT JOIN this to copy the Status. Finally, you have the interesting problem of how to get the last non NULL value for a column, and there are several approaches. Here is one article of many you can see different approaches: https://www.mssqltips.com/sqlservertip/7379/last-non-null-value-set-of-sql-server-records/  I used the approach that uses the MAX function in a window.
So, putting this all together into a script and starting with your data in a table variable (as well as adding some records for another test), the whole things looks like this:
DECLARE @Data TABLE([ItemID] VARCHAR(3), [Date] DATE, [Status] VARCHAR(15));

INSERT INTO @Data ([ItemID],[Date],[Status])
VALUES ('001', '2021-01-12', 'Active'), ('001', '2021-01-16','Discontinued'),('001', '2021-01-20','Active'),
('002','2022-02-01','Active'), ('002','2022-03-01','Discontinued');

;WITH digits (I) AS
(
    SELECT I
    FROM  (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS digits (I)
)
,integers (I) AS (
    SELECT D1.I + (10*D2.I) + (100*D3.I) + (1000*D4.I)
    FROM digits AS D1 CROSS JOIN digits AS D2 CROSS JOIN digits AS D3 CROSS JOIN digits AS D4
), itemMinMaxDates AS (
    SELECT [ItemID], MIN([Date]) AS [MinDate], MAX([Date]) AS [MaxDate]
    FROM @Data GROUP BY [ItemID]
), itemsWithAllDates AS
(
    SELECT [imm].[ItemID], DATEADD(DAY,i.I, imm.[MinDate]) AS [Date] FROM [itemMinMaxDates] AS imm CROSS JOIN [integers] AS i
    WHERE DATEADD(DAY,i.I, imm.[MinDate]) BETWEEN imm.[MinDate] AND imm.[MaxDate]
), itemsWithAllDatesAndStatus AS
(
    SELECT [allDates].[ItemID], [allDates].[Date], [d].[Status] FROM [itemsWithAllDates] AS allDates
    LEFT OUTER JOIN @Data AS d ON [allDates].[ItemID] = [d].[ItemID] AND [allDates].[Date] = d.[Date]
), grp AS
(
    SELECT [itemsWithAllDatesAndStatus].[ItemID],
       [itemsWithAllDatesAndStatus].[Date],
       [itemsWithAllDatesAndStatus].[Status],
       MAX(IIF([itemsWithAllDatesAndStatus].[Status] IS NOT NULL, [itemsWithAllDatesAndStatus].[Date], NULL)) OVER (PARTITION BY [itemsWithAllDatesAndStatus].[ItemID] ORDER BY [itemsWithAllDatesAndStatus].[Date] ROWS UNBOUNDED PRECEDING) AS grp
    FROM itemsWithAllDatesAndStatus
)
SELECT [grp].[ItemID], [grp].[Date],
MAX([grp].[Status]) OVER (PARTITION BY [grp].[ItemID], grp  ORDER BY [grp].[Date] ROWS UNBOUNDED PRECEDING) AS [Status]
FROM [grp]
ORDER BY [grp].[ItemID], [grp].[Date];

The result is what you have shown (as well as the data I included for a test):

ItemID
Date
Status

001
2021-01-12
Active

001
2021-01-13
Active

001
2021-01-14
Active

001
2021-01-15
Active

001
2021-01-16
Discontinued

001
2021-01-17
Discontinued

001
2021-01-18
Discontinued

001
2021-01-19
Discontinued

001
2021-01-20
Active

002
2022-02-01
Active

002
2022-02-02
Active

002
2022-02-03
Active

002
2022-02-04
Active

002
2022-02-05
Active

002
2022-02-06
Active

002
2022-02-07
Active

002
2022-02-08
Active

002
2022-02-09
Active

002
2022-02-10
Active

002
2022-02-11
Active

002
2022-02-12
Active

002
2022-02-13
Active

002
2022-02-14
Active

002
2022-02-15
Active

002
2022-02-16
Active

002
2022-02-17
Active

002
2022-02-18
Active

002
2022-02-19
Active

002
2022-02-20
Active

002
2022-02-21
Active

002
2022-02-22
Active

002
2022-02-23
Active

002
2022-02-24
Active

002
2022-02-25
Active

002
2022-02-26
Active

002
2022-02-27
Active

002
2022-02-28
Active

002
2022-03-01
Discontinued

Like I said, this is a working solution, but it is likely not the best or most efficient solution - but it gets you up and running.


text:
Q: Does the native RAID in Ubuntu support RAID configurations with hard drives of different sizes? have 8 hard drives of different sizes that I want in a RAID 5 or 6 configuration, the OS is Ubuntu 12.04 desktop.
Does the native RAID in Ubuntu support RAID configurations with hard drives of different sizes? Can i grow the RAID in the future?
If not, is ZFS a good alternative to this?
I have looked at other alternatives like FlexRAID (support is terrible and documentation is just as reliable), UnRAID, and snapRAID but there seems to be limitations with each of them. But, ZFS seems to be a good long term solution for RAID management and growth.

A: Btrfs can also manage RAID5/6 in last versions

A: Use ZFS.
ZFS uses zpools which are made up of vdevs, which accommodates different hard drive sizes.
A more detailed explanation is found here. http://en.wikipedia.org/wiki/Zfs#Storage_pools

redpajama_set_name: RedPajamaStackExchange


text:
Q: EntityManager doesn't refresh the data after querying My current project uses HSQLDB2.0 and JPA2.0 .
The scenario is: I query DB to get list of contactDetails of person. I delete single contactInfo at UI but do not save that data (Cancel the saving part).
I again do the same query, now the result list is 1 lesser than previous result coz I have deleted one contactInfo at UI. But that contactInfo is still available at DB if I cross check.
But if I include entityManager.clear() before start of the query, I get correct results every time.
I dont understand this behaviour. Could anyone make it clear for me?

A: The behaviour of clear() is explained in its javadoc:

Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.

That is, removal of contactInfo is not persisted.
ContactInfo is not getting removed from the database because you remove the relationship between ContactDetails and ContactInfo, but not ContactInfo itself. If you want to remove it, you need either do it explicitly with remove() or specify orphanRemoval = true on the relationship.

A: Rather than querying again, try this:
entityManager.refresh(person);

A more complete example:
EntityManagerFactory factory = Persistence.createEntityManagerFactory("...");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();

Person p = (Person) em.find(Person.class, 1);
assertEquals(10, p.getContactDetails().size()); // let's pretend p has 10 contact details
p.getContactDetails().remove(0);
assertEquals(9, p.getContactDetails().size());

Person p2 = (Person) em.find(Person.class, 1);
assertTrue(p == p2); // We're in the same persistence context so p == p2
assertEquals(9, p.getContactDetails().size());

// In order to reload the actual patients from the database, refresh the entity
em.refresh(p);
assertTrue(p == p2);
assertEquals(10, p.getContactDetails().size());
assertEquals(10, p2.getContactDetails().size());

em.getTransaction().commit();
em.close();
factory.close();


text:
Q: Displaying JSON Weather API Response in PHP After looking through so many other questions here I'm still stuck with this. First I've never used JSON data ever before and am finding what should be rather simple to be rather tricky.
I have a JSON response like this from the DarkSky Weather API
{
    "latitude": -26.202271,
    "longitude": 28.043631,
    "timezone": "Africa\/Johannesburg",
    "daily": {
        "summary": "Light rain throughout the week, with high temperatures peaking at 28\u00b0C on Saturday.",
        "icon": "rain",
        "data": [
            {
                "time": 1549317600,
                "summary": "Mostly cloudy throughout the day.",
                "icon": "partly-cloudy-day",
                "sunriseTime": 1549338410,
                "sunsetTime": 1549385960,
                "moonPhase": 0.02,
                "precipIntensity": 0.0737,
                "precipIntensityMax": 0.6121,
                "precipIntensityMaxTime": 1549368000,
                "precipProbability": 0.14,
                "precipType": "rain",
                "temperatureHigh": 22.68,
                "temperatureHighTime": 1549364400,
                "temperatureLow": 15.14,
                "temperatureLowTime": 1549422000,
                "apparentTemperatureHigh": 22.68,
                "apparentTemperatureHighTime": 1549364400,
                "apparentTemperatureLow": 15.14,
                "apparentTemperatureLowTime": 1549422000,
                "dewPoint": 13.85,
                "humidity": 0.74,
                "pressure": 1015.08,
                "windSpeed": 1.84,
                "windGust": 7.01,
                "windGustTime": 1549342800,
                "windBearing": 40,
                "cloudCover": 0.73,
                "uvIndex": 8,
                "uvIndexTime": 1549357200,
                "visibility": 14.03,
                "ozone": 263.92,
                "temperatureMin": 15.02,
                "temperatureMinTime": 1549339200,
                "temperatureMax": 22.68,
                "temperatureMaxTime": 1549364400,
                "apparentTemperatureMin": 15.02,
                "apparentTemperatureMinTime": 1549339200,
                "apparentTemperatureMax": 22.68,
                "apparentTemperatureMaxTime": 1549364400
            },
            {
                "time": 1549404000,
                "summary": "Mostly cloudy throughout the day.",
                "icon": "partly-cloudy-day",
                "sunriseTime": 1549424856,
                "sunsetTime": 1549472325,
                "moonPhase": 0.05,
                "precipIntensity": 0.0432,
                "precipIntensityMax": 0.2819,
                "precipIntensityMaxTime": 1549454400,
                "precipProbability": 0.13,
                "precipType": "rain",
                "temperatureHigh": 24.32,
                "temperatureHighTime": 1549454400,
                "temperatureLow": 15.83,
                "temperatureLowTime": 1549508400,
                "apparentTemperatureHigh": 24.32,
                "apparentTemperatureHighTime": 1549454400,
                "apparentTemperatureLow": 15.83,
                "apparentTemperatureLowTime": 1549508400,
                "dewPoint": 13.06,
                "humidity": 0.67,
                "pressure": 1013.86,
                "windSpeed": 1.34,
                "windGust": 6.01,
                "windGustTime": 1549414800,
                "windBearing": 341,
                "cloudCover": 0.71,
                "uvIndex": 8,
                "uvIndexTime": 1549443600,
                "visibility": 16.09,
                "ozone": 258.39,
                "temperatureMin": 15.14,
                "temperatureMinTime": 1549422000,
                "temperatureMax": 24.32,
                "temperatureMaxTime": 1549454400,
                "apparentTemperatureMin": 15.14,
                "apparentTemperatureMinTime": 1549422000,
                "apparentTemperatureMax": 24.32,
                "apparentTemperatureMaxTime": 1549454400
            },
            {
                "time": 1549490400,
                "summary": "Light rain overnight.",
                "icon": "rain",
                "sunriseTime": 1549511300,
                "sunsetTime": 1549558690,
                "moonPhase": 0.08,
                "precipIntensity": 0.16,
                "precipIntensityMax": 0.6096,
                "precipIntensityMaxTime": 1549573200,
                "precipProbability": 0.23,
                "precipType": "rain",
                "temperatureHigh": 25.43,
                "temperatureHighTime": 1549540800,
                "temperatureLow": 16.47,
                "temperatureLowTime": 1549591200,
                "apparentTemperatureHigh": 25.43,
                "apparentTemperatureHighTime": 1549540800,
                "apparentTemperatureLow": 16.61,
                "apparentTemperatureLowTime": 1549591200,
                "dewPoint": 14.17,
                "humidity": 0.69,
                "pressure": 1013.06,
                "windSpeed": 2.28,
                "windGust": 7.57,
                "windGustTime": 1549497600,
                "windBearing": 342,
                "cloudCover": 0.52,
                "uvIndex": 12,
                "uvIndexTime": 1549533600,
                "visibility": 16.09,
                "ozone": 251.95,
                "temperatureMin": 15.83,
                "temperatureMinTime": 1549508400,
                "temperatureMax": 25.43,
                "temperatureMaxTime": 1549540800,
                "apparentTemperatureMin": 15.83,
                "apparentTemperatureMinTime": 1549508400,
                "apparentTemperatureMax": 25.43,
                "apparentTemperatureMaxTime": 1549540800
            },
            {
                "time": 1549576800,
                "summary": "Mostly cloudy throughout the day.",
                "icon": "partly-cloudy-day",
                "sunriseTime": 1549597745,
                "sunsetTime": 1549645053,
                "moonPhase": 0.11,
                "precipIntensity": 0.2819,
                "precipIntensityMax": 1.1481,
                "precipIntensityMaxTime": 1549584000,
                "precipProbability": 0.39,
                "precipType": "rain",
                "temperatureHigh": 25.17,
                "temperatureHighTime": 1549627200,
                "temperatureLow": 16.64,
                "temperatureLowTime": 1549677600,
                "apparentTemperatureHigh": 25.19,
                "apparentTemperatureHighTime": 1549627200,
                "apparentTemperatureLow": 16.64,
                "apparentTemperatureLowTime": 1549677600,
                "dewPoint": 15.46,
                "humidity": 0.77,
                "pressure": 1013.3,
                "windSpeed": 1.21,
                "windGust": 5.91,
                "windGustTime": 1549580400,
                "windBearing": 310,
                "cloudCover": 0.91,
                "uvIndex": 7,
                "uvIndexTime": 1549616400,
                "visibility": 16.09,
                "ozone": 249.44,
                "temperatureMin": 16.47,
                "temperatureMinTime": 1549591200,
                "temperatureMax": 25.17,
                "temperatureMaxTime": 1549627200,
                "apparentTemperatureMin": 16.61,
                "apparentTemperatureMinTime": 1549591200,
                "apparentTemperatureMax": 25.19,
                "apparentTemperatureMaxTime": 1549627200
            },
            {
                "time": 1549663200,
                "summary": "Rain overnight.",
                "icon": "rain",
                "sunriseTime": 1549684188,
                "sunsetTime": 1549731414,
                "moonPhase": 0.14,
                "precipIntensity": 0.221,
                "precipIntensityMax": 0.7645,
                "precipIntensityMaxTime": 1549670400,
                "precipProbability": 0.27,
                "precipType": "rain",
                "temperatureHigh": 27.92,
                "temperatureHighTime": 1549713600,
                "temperatureLow": 16.84,
                "temperatureLowTime": 1549760400,
                "apparentTemperatureHigh": 27.92,
                "apparentTemperatureHighTime": 1549713600,
                "apparentTemperatureLow": 16.93,
                "apparentTemperatureLowTime": 1549760400,
                "dewPoint": 14.08,
                "humidity": 0.67,
                "pressure": 1011.76,
                "windSpeed": 0.19,
                "windGust": 6.53,
                "windGustTime": 1549688400,
                "windBearing": 145,
                "cloudCover": 0.94,
                "uvIndex": 7,
                "uvIndexTime": 1549702800,
                "visibility": 16.09,
                "ozone": 253.47,
                "temperatureMin": 16.64,
                "temperatureMinTime": 1549677600,
                "temperatureMax": 27.92,
                "temperatureMaxTime": 1549713600,
                "apparentTemperatureMin": 16.64,
                "apparentTemperatureMinTime": 1549677600,
                "apparentTemperatureMax": 27.92,
                "apparentTemperatureMaxTime": 1549713600
            },
            {
                "time": 1549749600,
                "summary": "Rain in the morning.",
                "icon": "rain",
                "sunriseTime": 1549770632,
                "sunsetTime": 1549817775,
                "moonPhase": 0.17,
                "precipIntensity": 1.0668,
                "precipIntensityMax": 4.2316,
                "precipIntensityMaxTime": 1549760400,
                "precipProbability": 0.43,
                "precipType": "rain",
                "temperatureHigh": 24.07,
                "temperatureHighTime": 1549803600,
                "temperatureLow": 17.25,
                "temperatureLowTime": 1549854000,
                "apparentTemperatureHigh": 24.07,
                "apparentTemperatureHighTime": 1549803600,
                "apparentTemperatureLow": 17.25,
                "apparentTemperatureLowTime": 1549854000,
                "dewPoint": 14.73,
                "humidity": 0.72,
                "pressure": 1011.87,
                "windSpeed": 2.52,
                "windGust": 7.58,
                "windGustTime": 1549778400,
                "windBearing": 358,
                "cloudCover": 0.72,
                "uvIndex": 14,
                "uvIndexTime": 1549792800,
                "visibility": 15.58,
                "ozone": 257.27,
                "temperatureMin": 16.84,
                "temperatureMinTime": 1549760400,
                "temperatureMax": 24.07,
                "temperatureMaxTime": 1549803600,
                "apparentTemperatureMin": 16.93,
                "apparentTemperatureMinTime": 1549760400,
                "apparentTemperatureMax": 24.07,
                "apparentTemperatureMaxTime": 1549803600
            },
            {
                "time": 1549836000,
                "summary": "Mostly cloudy starting in the afternoon.",
                "icon": "partly-cloudy-night",
                "sunriseTime": 1549857075,
                "sunsetTime": 1549904134,
                "moonPhase": 0.2,
                "precipIntensity": 0.0381,
                "precipIntensityMax": 0.2489,
                "precipIntensityMaxTime": 1549886400,
                "precipProbability": 0.13,
                "precipType": "rain",
                "temperatureHigh": 26.19,
                "temperatureHighTime": 1549890000,
                "temperatureLow": 15.78,
                "temperatureLowTime": 1549944000,
                "apparentTemperatureHigh": 26.19,
                "apparentTemperatureHighTime": 1549890000,
                "apparentTemperatureLow": 15.78,
                "apparentTemperatureLowTime": 1549944000,
                "dewPoint": 12.99,
                "humidity": 0.61,
                "pressure": 1008.71,
                "windSpeed": 2.54,
                "windGust": 8.12,
                "windGustTime": 1549857600,
                "windBearing": 326,
                "cloudCover": 0.47,
                "uvIndex": 15,
                "uvIndexTime": 1549879200,
                "visibility": 16.09,
                "ozone": 246.75,
                "temperatureMin": 17.25,
                "temperatureMinTime": 1549854000,
                "temperatureMax": 26.19,
                "temperatureMaxTime": 1549890000,
                "apparentTemperatureMin": 17.25,
                "apparentTemperatureMinTime": 1549854000,
                "apparentTemperatureMax": 26.19,
                "apparentTemperatureMaxTime": 1549890000
            },
            {
                "time": 1549922400,
                "summary": "Rain in the afternoon.",
                "icon": "rain",
                "sunriseTime": 1549943518,
                "sunsetTime": 1549990493,
                "moonPhase": 0.24,
                "precipIntensity": 0.3912,
                "precipIntensityMax": 1.6332,
                "precipIntensityMaxTime": 1549972800,
                "precipProbability": 0.48,
                "precipType": "rain",
                "temperatureHigh": 22.24,
                "temperatureHighTime": 1549983600,
                "temperatureLow": 16.23,
                "temperatureLowTime": 1550030400,
                "apparentTemperatureHigh": 22.24,
                "apparentTemperatureHighTime": 1549983600,
                "apparentTemperatureLow": 16.23,
                "apparentTemperatureLowTime": 1550030400,
                "dewPoint": 13.89,
                "humidity": 0.72,
                "pressure": 1008.8,
                "windSpeed": 1.88,
                "windGust": 8.13,
                "windGustTime": 1549972800,
                "windBearing": 1,
                "cloudCover": 0.94,
                "uvIndex": 6,
                "uvIndexTime": 1549958400,
                "visibility": 16.09,
                "ozone": 244.47,
                "temperatureMin": 15.78,
                "temperatureMinTime": 1549944000,
                "temperatureMax": 22.24,
                "temperatureMaxTime": 1549983600,
                "apparentTemperatureMin": 15.78,
                "apparentTemperatureMinTime": 1549944000,
                "apparentTemperatureMax": 22.24,
                "apparentTemperatureMaxTime": 1549983600
            }
        ]
    },
    "offset": 2
}

What I am trying to achieve now is to extract the temperatureHigh and temperatureLow for the next 5 days excluding today or yesterday.
Based on the above code being fresh from today 2019-02-05 the first two days need to be excluded. So I want to start the forecast data I extract from the timestamp 1549490400
What I would like to end up with is the following display of echoed data.
Johannesburg
Wednesday [weathericon] MAX: `temperatureHigh` °C LOW: `temperatureLow` °C
Thursday [weathericon] MAX: `temperatureHigh` °C LOW: `temperatureLow` °C
Friday [weathericon] MAX: `temperatureHigh` °C LOW: `temperatureLow` °C
Saturday [weathericon] MAX: `temperatureHigh` °C LOW: `temperatureLow` °C
Sunday [weathericon] MAX: `temperatureHigh` °C LOW: `temperatureLow` °C
Monday [weathericon] MAX: `temperatureHigh` °C LOW: `temperatureLow` °C

I would also like to perhaps do only a 3-day forecast like this
Johannesburg
Wednesday [weathericon] MAX: `temperatureHigh` °C LOW: `temperatureLow` °C
Thursday [weathericon] MAX: `temperatureHigh` °C LOW: `temperatureLow` °C
Friday [weathericon] MAX: `temperatureHigh` °C LOW: `temperatureLow` °C

Where I say [weathericon] I need to pull the "icon": "rain" for example from each day and match it with a locally stored .jpg / .png with the same name. ie. rain.png or rain.jpg
I have tried various loops, foreach examples on other answers here but nothing seems to get me to display the data properly.
Here's something I got partially working but due to my lack of understanding of JSON not sure why I am getting all the blank rows.
<?php
header('Content-Type: application/json');
$json_string = file_get_contents("https://api.darksky.net/forecast/MYAPIKEY/-26.202271,28.043631?exclude=[currently,minutely,hourly,alerts,flags]&units=si");
$jsondata = json_decode($json_string, true);
//Echo Data
foreach ($jsondata as $max) {
  echo "MAX: ".$max['data'][2]['temperatureHigh']."\n";
  echo "MAX: ".$max['data'][3]['temperatureHigh']."\n";
  echo "MAX: ".$max['data'][4]['temperatureHigh']."\n";
}
?>

The above gives me this output
MAX:
MAX:
MAX:
MAX:
MAX:
MAX:
MAX:
MAX:
MAX:
MAX: 25.43
MAX: 25.17
MAX: 27.92
MAX:
MAX:
MAX:

A: You are missing the right array index. Go for:
foreach($jsondata['daily']['data'] as $dayData) {
    $dayData['temperatureHigh'];
}


text:
Q: What are the best weights after training a model? Lowest loss? Validation loss? I'm using Keras to solve a regression task. There, the options for saving the model weights are:

*

*Use the model weights at the end of the training procedure (for me: early stopping if loss didn't improve for ten epochs),

*use the weights that produced the best loss or

*use the weights what produced the best validation loss.

If I select the model weights based on the validation loss, my results will be biased towards the validation set. But then again, same goes for the training set.
I could also save all of the above weights and test which one performs best on a test set - which produces a bias towards the test set. So which one to use?
This questions seems really basic to me but unfortunately, I wasn't able to find an answer for myself. If there is an article about that which I miss, feel free to just post the link instead of an answer.

A: I suppose people usually choose a model with the best validation performance, and then evaluate the model performance on test set.  While the model selection may potentially introduce bias towards the validation set, the test set provides an unbiased evaluation of the model performance for unseen data.
I think this scikit-learn page provides a concise explanation of the concept.
http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html
If I remember correct, Andrew Ng's machine learning course covers the topic as well. https://www.coursera.org/learn/machine-learning


text:
Q: Solving $a^2x_1x_2+abx_1+abx_2+b^2=a(x_1+x_2)+b$ in terms of $a,b$ Suppose that $f \colon (\mathbb{R}, +) \to (\mathbb{R}, \cdot)$ has the form
$$f(x) = ax + b$$
where $a, b \in \mathbb{R}$. Under which conditions on $a$ and $b$ is $f$ operation preserving?
{Answer:} For operation preservation mapping, we seek  $f(x_1) \star_Y f(x_2)=f(x_1 \star_X x_2)$
$f(x_1) \star_Y f(x_2)=f(x_1) \cdot f(x_2)=(ax_1+b) \cdot (ax_2+b)=a^2x_1x_2+abx_1+abx_2+b^2$
$f(x_1 \star_X x_2)=f(x_1 +  x_2)=a(x_1+x_2)+b$
Equating these two equations, we get $a^2x_1x_2+abx_1+abx_2+b^2=a(x_1+x_2)+b$
Can someone please help me in solving this in terms of $a,b$? I can't seem to figure out the algebra for some reason.

A: The key is that the equation needs to hold for arbitrary $x_1$ and $x_2$, so you can pick whatever values you like for those that are most convenient.  In particular, choosing $x_1 = -x_2$ leads to the equation $$a^2 x_1^2 = b - b^2$$  However, the only way a non-constant expression, $a^2 x_1^2$, can equal a constant one, $b - b^2$, is if $a = 0$.
So now the equation is reduced to $$b^2 = b$$ which I'm sure you can easily solve.  You can then verify that the definition of $f$ satisfies the laws for the solution(s) you get.


text:
Q: Sliding window based on Akka actor source not behaving as expected Using below code I'm attempting to use an actor as a source and send messages of type Double to be processed via a sliding window.
The sliding windows is defined as sliding(2, 2) to calculate each sequence of twp values sent.
Sending the message:
        actorRef.tell(10, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());
        actorRef.tell(30, ActorRef.noSender());
        actorRef.tell(40, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());

Should calculate the average as follows :
10 + 20 / 2 = 15
30 + 40 / 2 = 35

But the calculation does not appear to be invoked in below code.
Here I output the value :
    movingAverage.runForeach(n -> {
        if( n > 0){
            System.out.println(n);
        }
    }, system);

src code:
import akka.Done;
import akka.actor.ActorRef;
import akka.stream.CompletionStrategy;
import akka.stream.OverflowStrategy;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;

import java.util.Optional;

public class FilterThreshold {

    public static void main(String[] args) {

        final akka.actor.ActorSystem system = akka.actor.ActorSystem.create("Source");

        final int bufferSize = 1;
        final Source<Double, ActorRef> source =
                Source.actorRef(
                        elem -> {
                            // complete stream immediately if we send it Done
                            if (elem == Done.done()) {
                                return Optional.of(CompletionStrategy.immediately());
                            } else {
                                return Optional.empty();
                            }
                        },
                        // never fail the stream because of a message
                        elem -> Optional.empty(),
                        bufferSize,
                        OverflowStrategy.dropHead());
        ActorRef actorRef = source.to(Sink.foreach(System.out::println)).run(system);

        actorRef.tell(10, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());
        actorRef.tell(30, ActorRef.noSender());
        actorRef.tell(40, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());

        Source<Double, ActorRef> movingAverage = source
                .sliding(2, 2)
                .map(window -> (window.stream().mapToDouble(i -> i).sum()) / window.size());

        movingAverage.runForeach(n -> {
            if( n > 0){
                System.out.println(n);
            }
        }, system);

    }
}

I've edited the code from https://doc.akka.io/docs/akka/current/stream/operators/Source-or-Flow/sliding.html
How to apply the sliding window function defined as movingAverage to calculate the values sent via the Akka actor actorRef ?
Update:
The method permaterialize takes an actor system as a parameter.
Updating the code from:
final Pair<ActorRef, Source<Double, ActorRef>> prematPair = source.preMaterialize();

to:
final Pair<ActorRef, Source<Double, ActorRef>> prematPair = source.preMaterialize(system);

results in a compile time error:
Required type:
Pair
<ActorRef,
Source<Double, ActorRef>>

Provided:
Pair
<ActorRef,
Source<Double, NotUsed>>

Is there an alternative method I should use ?
Updated code posted:
import akka.Done;
import akka.NotUsed;
import akka.actor.ActorRef;
import akka.japi.Pair;
import akka.stream.CompletionStrategy;
import akka.stream.OverflowStrategy;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Source;

import java.util.Optional;

public class FilterThreshold {

    public static void main(String[] args) {

        final akka.actor.ActorSystem system = akka.actor.ActorSystem.create("Source");

        final int bufferSize = 1;
        final Source<Double, ActorRef> source =
                Source.actorRef(
                        elem -> {
                            System.out.println("elem is "+elem);
                            // complete stream immediately if we send it Done
                            if (elem == Done.done()) {
                                return Optional.of(CompletionStrategy.immediately());
                            } else {
                                return Optional.empty();
                            }
                        },
                        // never fail the stream because of a message
                        elem -> Optional.empty(),
                        bufferSize,
                        OverflowStrategy.dropHead());

        // source is as before
        final Pair<ActorRef, Source<Double, ActorRef>> prematPair = source.preMaterialize(system);

        Flow<Double, Double, NotUsed> movingAverageFlow =
                Flow.of(Double.class)
                        .sliding(2, 2)
                        .map(window -> (window.stream().mapToDouble(i -> i).sum()) / window.size());

        final Source<Double, ActorRef> prematSource = prematPair.second();

        prematSource.via(movingAverageFlow).runForeach(n -> {
            System.out.println("n is "+n);
            if (n > 0) {
                System.out.println(n);
            }
        }, system);

        final ActorRef actorRef = prematPair.first();

        actorRef.tell(10, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());

    }
}

Update2 :
Using code :
import akka.Done;
import akka.NotUsed;
import akka.actor.ActorRef;
import akka.japi.Pair;
import akka.stream.CompletionStrategy;
import akka.stream.OverflowStrategy;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Source;

import java.util.Optional;

public class FilterThreshold {

    public static void main(String[] args) {

        final akka.actor.ActorSystem system = akka.actor.ActorSystem.create("Source");

        final int bufferSize = 1;
        final Source<Double, ActorRef> source =
                Source.actorRef(
                        elem -> {
                            System.out.println("elem is "+elem);
                            // complete stream immediately if we send it Done
                            if (elem == Done.done()) {
                                return Optional.of(CompletionStrategy.immediately());
                            } else {
                                return Optional.empty();
                            }
                        },
                        // never fail the stream because of a message
                        elem -> Optional.empty(),
                        bufferSize,
                        OverflowStrategy.dropHead());

        // source is as before
        final Pair<ActorRef, Source<Double, NotUsed>> prematPair = source.preMaterialize(system);
        final ActorRef actorRef = prematPair.first();
        final Source<Double, NotUsed> prematSource = prematPair.second();

        Flow<Double, Double, NotUsed> movingAverageFlow =
                Flow.of(Double.class)
                        .sliding(2, 2)
                        .map(window -> (window.stream().mapToDouble(i -> i).sum()) / window.size());

        prematSource.via(movingAverageFlow).runForeach(n -> {
            System.out.println("n is "+n);
            if (n > 0) {
                System.out.println(n);
            }
        }, system);

        actorRef.tell(10, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());
        actorRef.tell(20, ActorRef.noSender());

        prematSource.run(system);

    }
}

prints:
elem is 10
elem is 20
elem is 20
elem is 20
elem is 20

So it seems the messages are being sent correctly but the moving average is not being materialized.
Is using prematSource.run(system); not the correct way to materialize the value ?

A: The short answer is that your source is a recipe of sorts for materializing a Source<Double, ActorRef> and each materialization ends up being a different source.
In your code, source.to(Sink.foreach(System.out::println)).run(system) is one stream with the materialized actorRef being only connected to this stream, and
movingAverage.runForeach(n -> {
    if( n > 0){
        System.out.println(n);
    }
}, system);

is a completely separate stream with a different materialized ActorRef (which ultimately gets thrown away since runForeach materializes as a CompletionStage<Done>.
When dealing with Source.actorRef, it's often a good idea to prematerialize the source before running the stream:
import akka.NotUsed
import akka.japi.Pair
import akka.stream.javadsl.Flow

// source is as before
final Pair<ActorRef, Source<Double, NotUsed>> prematPair = source.preMaterialize(system);
final ActorRef actorRef = prematPair.first();
final Source<Double, NotUsed> prematSource = prematPair.second();

Flow<Double, Double, NotUsed> movingAverageFlow =
    Flow.of(Double.class)
        .sliding(2, 2)
        .map(window -> (window.stream().mapToDouble(i -> i).sum()) / window.size());

prematSource.via(movingAverageFlow).runForeach(n -> {
    if (n > 0) {
      System.out.println(n);
    }
}, system);

(Apologies, my Java is quite rusty)


text:
Q: How to change Bootstrap tab by pagination Hi I am new to bootstrap and jQuery. I have created a bootstrap Tab, which is working fine. The tabs are changing by header, but I also needs pagination to change Tab, which I am not able to do. Following is my scenario,
Tab 1 --> next button --> go to tab 2
Tab 1  <-- previous -- Tab 2 -- next ---> Tab 3
Tab 2  <-- previous -- Tab 3

Can any one help. Following is my HTML. This is just an example, I can have variable number of tabs.

                Question - 1

                Question - 2

                Question - 3

Some Text Tab 1

Next →

Some Text Tab 2

← Previous

Next →

Some Text Tab 3

← Previous

A: *

*Updated jQuery script to attach to the previouse/next link.

*Updated class="active" to the li tag for Question-1.

            Question - 1

            Question - 2

            Question - 3

Some Text Tab 1

Next →

Some Text Tab 2

← Previous

Next →

Some Text Tab 3

← Previous


text:
Q: How to apply filter condition during Pandas Merge operation but retain them in the result DF? I'm trying to do something with pandas equivalent to the following SQL command:
select *
from tableA as A
left join tableB as B
on A.key = B.key and substr(A.value,1,2) not in ('something', 'something else')

As you can see in the sql query above, A.value have a filter condition applied during the join, but since it's a left join, the on condition not in criteria does not persist to the result dataset, it only applies during the join operation, such that the join operation will not consider any rows fulfilling the A.value not in ('something', 'something else') criteria.
I tried the following python code, but it results in filtering out the A.value rows from the result dataset, I need all the rows via the left join, but i don't want the merge operation on the rows as specified by the a.value not in condition, just like the SQL statement logic above.
df_output = df_input1[~df_input1['value'].str[:2].isin(['something', 'something_else'])].merge(df_input2, left_on = 'key', right_on = 'key', how='left')

Thank you all in advance!

A: A bit hacky, but the idea is to create a new column for joining in df1 and to only fill in this column for rows that you want to merge with:
import pandas as pd

df_input1 = pd.DataFrame({
    'fruit':['apple','banana','mango'],
    'quantity':[3,4,5],
})

df_input2 = pd.DataFrame({
    'fruit':['apple','banana','mango'],
    'in_stock':[True,False,True],
})

minimum_quantity = 4
ind = df_input1['quantity'].ge(minimum_quantity)
df_input1.loc[ind, 'merge_column'] = df_input1.loc[ind, 'fruit']

merge_filtered_fruits = df_input1.merge(
    df_input2,
    left_on = 'merge_column',
    right_on = 'fruit',
    how = 'left'
).drop(columns=['merge_column'])

print(merge_filtered_fruits)

Output:
  fruit_x  quantity fruit_y in_stock
0   apple         3     NaN      NaN
1  banana         4  banana    False
2   mango         5   mango     True

I'm curious what a better method could be


text:
Q: Git popping strange errors in Jenkins after my project changed of gitlab group I have a project, which git URL is :
git@gitlab.mycomp.fr:mygroup/myproject.git
I've just changed it from an other group to "mygroup".
Now, when I do git clone git@gitlab.mycomp.fr:mygroup/myproject.git it works perfectly.
But Jenkins is not using "git clone" command, it uses :
git init /var/lib/jenkins/jobs/PROJET/workspace

then :
git fetch --tags --progress git@gitlab.mycomp.fr:mygroup/myproject.git +refs/heads/*:refs/remotes/origin/*

which ends in :
GitLab: The project you were looking for could not be found.
fatal: Could not read from remote repository.

What am I doing wrong here ?
I've tried to create a new Jenkins project to get rid of any cache problem, but it has the same result.


text:
Q: Finding missing data in a sequence in MySQL Is there an efficient way to find missing data not just in one sequence, but many sequences?
This is probably unavoidably O(N**2), so efficient here is defined as relatively few queries using MySQL
Let's say I have a table of temporary employees and their starting and ending months.
employees  | start_month | end_month
------------------------------------
Jane         2017-05       2017-07
Bob          2017-10       2017-12

And there is a related table of monthly payments to those employees
employee | paid_month
---------------------
Jane       2017-05
Jane       2017-07
Bob        2017-11
Bob        2017-12

Now, it's clear that we're missing a month for Jane (2017-06) and one for Bob too (2017-10).
Is there a way to somehow find the gaps in their payment record, without lots of trips back and forth?
In the case where there's just one sequence to check, some people generate a temporary table of valid values, and then LEFT JOIN to find the gaps. But here we have different sequences for each employee.
One possibility is that we could do an aggregate query to find the COUNT() of paid_months for each employee, and then check it versus the expected delta of months. Unfortunately the data here is a bit dirty so we actually have payment dates that could be before or after that employee start or end date. But we're verifying that the official sequence definitely has payments.

A: Form a Cartesian product of employees and months, then left join the actual data to that, then the missing data is revealed when there is no matched payment to the Cartesian product.
You need a list of every months. This might come from a "calendar table" you already have, OR, it MIGHT be possible using a subquery if every month is represented in the source data)
e.g.
select
    m.paid_month, e.employee
from (select distinct paid_month from payments) m
cross join (select employee from employees) e
left join payments p on m.paid_month = p.paid_month and e.employee = p.employee
where p.employee is null

The subquery m can be substituted by the calendar table or some other technique for generating a series of months. e.g.
select
        DATE_FORMAT(m1, '%Y-%m')
from (
        select
              '2017-01-01'+ INTERVAL m MONTH as m1
        from (
            select @rownum:=@rownum+1 as m
            from (select 1 union select 2 union select 3 union select 4) t1
            cross join (select 1 union select 2 union select 3 union select 4) t2
            ## cross join (select 1 union select 2 union select 3 union select 4) t3
            ## cross join (select 1 union select 2 union select 3 union select 4) t4
            cross join(select @rownum:=-1) t0
            ) d1
        ) d2
where m1 < '2018-01-01'
order by m1

The subquery e could contain other logic (e.g. to determine which employees are still currently employed, or that are "temporary employees")

A: First we need to get all the months between start date and end_date in a temporary table then need do a left outer join with the payments table on paid month filtering all non matching months ( payment employee name is null )
select e.employee, e.yearmonth as missing_paid_month from (
 with t as (
     select e.employee, to_date(e.start_date, 'YYYY-MM') as start_date, to_date(e.end_date, 'YYYY-MM') as end_date from employees e
  )
  select distinct t.employee,
  to_char(add_months(trunc(start_date,'MM'),level - 1),'YYYY-MM') yearmonth
  from  t
  connect by trunc(end_date,'mm') >= add_months(trunc(start_date,'mm'),level - 1)
  order by t.employee,  yearmonth
 ) e
left outer join payments p
on p.paid_month = e.yearmonth
where p.employee is null

output
EMPLOYEE    MISSING_PAID_MONTH
Bob         2017-10
Jane        2017-06

SQL Fiddle http://sqlfiddle.com/#!4/2b2857/35


text:
Q: How to set ID or css selector for new row added in table using javascript I have written a code which is used to add new row to the table,see the code below
$("#example tbody tr").each(function(i, object) {
        var safeHtml= gwt.@com.my.sample.client.gwt.GWTExpandCollapse::getRowValue(I)(i);//Calling GWT Java Method which return HTML
         $(object).after(safeHtml); //Inserting new row
        //How to assign (ID or CSS) to the above inserted row
    });

The above code is working fine,but i need to assign (ID or CSS Selector) to the newly inserted row,I search it but didn't find any clue.How to do this using Javascript?Any Help?
Note:see the below image,the newly row which is added might contain any think inside the row.

A: You can use .attr()
    $("#example tbody tr").each(function(i, object) {
        var safeHtml= gwt.@com.my.sample.client.gwt.GWTExpandCollapse::getRowValue(I)(i);//Calling GWT Java Method which return HTML
        var newSafeHtml = $.parseHTML(new String(safeHtml.toString()).replace("
", "
"));
         $(object).after(newSafeHtml); //Inserting new row
    });

A: Demo
html

        Jill
        Smith
        50

        Eve
        Jackson
        94

css
.yourclassname1 {
    color:red;
}
.yourclassname2 {
    color:green;
}

jquery
var i = 1;
$("tr").each(function () {
    var safeHtml = '
test	test	test
';
    $(this).after(safeHtml);
    $(this).next().addClass("yourclassname"+i);
    i = i+1;
});

A: Set the css selector using the below code,
$("#example tbody tr").each(function(i, object) {
        var safeHtml= gwt.@com.my.sample.client.gwt.GWTExpandCollapse::getRowValue(I)(i);
         $(object).after(safeHtml); //Inserting new row
         $(object).next().addClass("hideShow");
    });


text:
Q: find text in calculated field All,
i am trying to extract part of a string in a calculated field.
The calculated field is looking in the title field, of an item in the library, for the word "DIS".
The formula I am using is the following:
=IF(ISNUMBER(FIND("DIS",Title,10)),MID(Title,INT(FIND("DIS"),Title,10)),13),"")
When it finds the word "DIS" I want the code to extract 13 characters. This code is working fine until the title consists of more than one instance of "DIS". For example when it runs into the word "DISTANCE".
I tried to get the last instance using RIGHT()
function in the formula because the characters I am looking for are always somewhere at the end of the title. I cant get this to work.
Can anyone help with that?

A: If the word "DIS" will only appear once or twice, then we can add a If condition to help us get the last "DIS". RIGHT() needs the correct index so it will not be the function for this scenario. My formula is like this
=MID(Text,IF(ISNUMBER(FIND("DIS",Text,(FIND("DIS",Text,1)+1))),FIND("DIS",Text,(FIND("DIS",Text,1)+1)),FIND("DIS",Text,1)),13)

The word text refers to the column you are searching, just use Title in you list.
The demo works like below:

Update: The new formula below shall work for the worst case (DIS appears 3 times)
=MID(A1,IF(ISNUMBER(FIND("DIS",A1,(FIND("DIS",A1,(FIND("DIS",A1,1)+1))+1))),FIND("DIS",A1,(FIND("DIS",A1,(FIND("DIS",A1,1)+1))+1)),IF(ISNUMBER(FIND("DIS",A1,(FIND("DIS",A1,1)+1))),FIND("DIS",A1,(FIND("DIS",A1,1)+1)),FIND("DIS",A1,1))),13)


text:
Q: Overriding ComboBox to select item by pressing index through keyboard in C# I want to override a combobox such that it can be selected by its position in the list by pressing key through keyboard.
Example:
ComboBoxMonths
  - Jan
  - Feb
  - Mar
  - Apr
  - May
  - Jun
  . . .

When 'J' is pressed Jan is selected, and 'F' for 'Feb',....
I want to use it like this, when
1 is pressed then Jan ,
2 for Feb , etc.
Is it possible ? If yes, How can I achieve that ?

A: This only works properly if the combo is set to DropDownList, which makes sense in your example.  It also only covers 1-9.  If you want to handle more than one digit, it requires more logic with timers.
public class MyComboBox : ComboBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        var index = e.KeyChar - '1';
        if( index >= 0 && index < this.Items.Count )
            this.SelectedIndex = index;

        base.OnKeyPress(e);
    }
}


text:
Q: Having objects spawn, with random size within set range, with equal distance between them regardless of framerate I am creating a script that spawns random sized cubes (later to replaced with low-poly buildings) that fly past the player on the x-axis to give the illusion of being on a moving train.
I have the buildings moving at a set speed, that is constant no matter the framerate using Time.deltaTime.
My script is written to wait enough time for the first spawned object to move out of the way, before spawning the next, and it works perfectly with a set size for the objects, but can't seem to keep up if I randomize the size of the object slightly each frame.
It looks like this:
public GameObject buildingPrefab;
    public GameObject spawnPoint;
    public float spawningRatio;
    public float randomSize;
    public float distanceBetween;
    public float ranMin;
    public float ranMax;

    float nextBuilding;
    float speed;

    // Start is called before the first frame update
    void Start()
    {
        ranMin = 10f;
        ranMax = 15f;
        distanceBetween = 5f;
        randomSize = 1;
        speed = buildingPrefab.GetComponent<ScrollingBuilding>().speed;
    }

    // Update is called once per frame
    void Update()
    {
        if(Time.time > nextBuilding)
        {
            spawningRatio = ((randomSize / 2) + (buildingPrefab.transform.localScale.x / 2) + distanceBetween) / (speed);

            nextBuilding = Time.time + spawningRatio;

            buildingPrefab.transform.localScale = new Vector3(randomSize, randomSize, randomSize);

            Instantiate(buildingPrefab, spawnPoint.transform.position, Quaternion.identity);

            randomSize = Random.Range(ranMin, ranMax);
        }
    }
}

The problem I am having is that the distance between the buildings isn't always the same, most likely due to the framerate not being completely stable. I tried to put the function into FixedUpdate(), but it suddenly became a lot more intensive and unsmooth.
My question is how to solve the issue, and make the distance between the objects constant, regardless of framerate here.
Thanks.


text:
Q: Swift Inherit from Generic Type I'm trying to inherit from a generic type, so that I can insert a type into a hierarchy:
class Foo < T:AnyObject > : T {}

but I get error
inheritance from non-protocol, non-class type 'T'

but I'm ensuring T is a class (even if I change AnyObject to some other class).  Is this just not possible?

A: Isn't CRTP (Curiously recurring template pattern) different than in the OP anyways?
It's totally fine to design that pattern in Swift (<= 3.0), but it's currently bugged and will lock on initialization without any error during runtime.
class Template<T> { ... }

class RealThing : Template<RealThing> { ... }

I recently discovered this pattern in bridged UIKit API. You can read that in my short blog post here.
I also translated the example from wiki into Swift 3.0:
protocol Constructor {
    init()
}

protocol Shape {
    func cloned() -> Shape
}

typealias ShapeProtocols = Constructor & Shape

class Shape_CRTP<T> : ShapeProtocols {

    required init() {}

    func  cloned() -> Shape {
        let new = Shape_CRTP<T>()
        // copy everything to `new` from `self`
        return new
    }
}

extension Shape_CRTP where T : ShapeProtocols {

    func cloned() -> Shape {
        let new = T()
        // copy everything to `new` from `self`
        return new
    }
}

// First non-crtp proof of concept
class Square : ShapeProtocols {

    required init() {}
    func cloned() -> Shape {
        return Square()
    }
}

let clone = Shape_CRTP<Square>().cloned() // creates a new `Shape`
type(of: clone) // Square.Type

// now CRTP but this is bugged: http://blog.devandartist.com/posts/swift-crtp
class Circle : Shape_CRTP<Circle> {}

Circle().cloned()

print("this will never print because of the described bug")

A: You can't inherit from something if you don't know what it is, for multiple reasons.

*

*For one, the compiler needs to know how to lay out an instance of your class in memory. To do that, it needs to know what instance variables (stored properties) it has: both those the class specifies and those inherited from a superclass.

*The compiler also needs to know about the superclass' properties and initializers to make sure that an instance of your class is properly initialized. If the superclass' properties are unknown, there's no way to know if you've initialized all the state that you should (and none that you shouldn't) before your initializer ends. If the superclass' initializers are unknown, the compiler can't enforce that you call a superclass' designated initializer from your own.

*How will you write method implementations that reference properties and methods of the superclass if you don't know what the superclass is? If you write code that references self.view, then somehow instantiate a version of your class that doesn't inherit from a class with that property, that code would break.
There are probably several more reasons, but these should be enough. :)
Though there are a few places where you're expected to subclass, Cocoa (whether in Swift or ObjC) generally favors composition instead of inheritance for customization.
If you're adding a bunch of functionality to various view controllers, and reusing the code for such by factoring it out into its own class, the simple solution is to make your view controller classes all own an instance of that class instead of trying to be that class.  If you have places where you want to enforce that certain view controller classes must own a Foo, you can define a protocol that expresses that requirement.
If you're trying to add functionality to an existing class, you can use an extension. You might not be able to use an extension to add stored properties, but you can certainly fake it. For example, you could use computed properties, and define your own storage within their implementation. One way to do that might be to use the associated objects feature of the ObjC runtime (which AFAIK is still accessible from Swift).


text:
Q: Location aware links I have a webpage that enables users to visit multiple search engine, the only thing I'd love to do next is enable location aware searches: If someone is searching from the UK, I'd like it to be the British Uk and not the greek for example.
Is there any way to detect the country the user's at using Javascript?

A: Geolocation API:
http://html5doctor.com/finding-your-position-with-geolocation/


text:
Q: Google Compute Engine, always running? does the virtual machine on Google Compute Engine continue to run along with the settings and task schedules i setup without me opening or connecting to it?

A: Yes, GCE workloads are meant to run continuosly by default. You can stop/shutdown or suspend (Alpha functionality) VM instances manually, though.

A: Yes it is, VM instance continue to run if you did not manually shut it down. You may also perform a shutdown scripts using this link: https://cloud.google.com/compute/docs/shutdownscript.


text:
Q: Are there effective methods of finding coefficients to $n$th-degree polynomials, given specific solutions to an equation? Sorry for the long title. I recently watched this video on youtube: https://youtu.be/C7A3uFC76G0 . After solving the problem I wanted to see if I could  make some kind of generalization, as a challenge to myself. I will try to briefly describe my process here.
So the problem goes as follows: Solve for all $x\in \mathbb{R}$
\begin{equation}
\label{eqpolyexp}
(x^{2}-7x+11)^{x^{2}-13x+42}=1.
\end{equation}
The problem boils down to considering three cases:

*

*$k^{o}=1$ for all $k\neq 0$.

*$(-1)^{2i}=1$ for all $i\in \mathbb{Z}$.

*$1^{j}=1$ for all $j\in \mathbb{Z}$.

After some simple calculations we find the following solutions: $x=2~,3~,4~,5~,6$ and $7$.
So, I thought it was rather interesting that the ''solution set'' ($x=2~,3~,4~,5~,6$ and $7$) to the equation looked like it did and wondered how the coefficients and constants of two quadratic polynomials $f_{2}(x)=x^{2}+ax+b$ and $g_{2}(x)=x^{2}+cx+d$ had to look like in order for the equation $$f_{2}(x)^{g_{2}(x)}=1$$ to have solutions $x\in\{m ,m +1,m+2,m+3,m+4,m+5\}$ where $m$ is some integer. I could derive the following:
Let $m\in \mathbb{Z}$ be a given positive integer. If $$f(x)=x^{2}-(2m+3)x+(m^{2}+3m+1)$$ and $$g(x)=x^{2}-(2m+9)x+(m^{2}+9m+20),$$ then the equation $$f(x)^{g(x)}=1$$ has solutions $$x\in \{m ,m+1, m+2, m+3, m+4, m+5\}.$$
My question is whether this can be generalized further? I would also like to know if there are any efficient methods of finding the coefficients and constants of an $n$th degree polynomial, given some specific solutions? I would like to give an answer to the following problem
What $n$:th-degree polynomials $f_{n}(x),g_{n}(x)$ have solutions $x\in \{\nu _{n} ,\nu _{n} +1,\ldots ,  \nu _{n} +(3n-1)\}$ to the equation $$f_{n}(x)^{g_{n}(x)}=1$$ for some positive integer $\nu _{n}\in \mathbb{Z}$?


text:
Q: LibreOffice Calc "Find" command matches row indices I wanted to search a certain value in a column, so I naturally selected the column, CTRL+F, and entered the value to the box. However, LibreOffice matches all cells with a row index containing my number (e.g. for 12 it matches rows 12, 112, 120, 121, etc). How can I make it not to do this, and only match the cell values? Is this a feature or a bug?
Edit: Said column contained formulas, after "burning" in the values the matches are correct. Nevertheless, I think this counts as a bug.

A: Press Ctrl+H, enable Current select only. Press Find Next or Find All. Only the cells containing 12 on the column (current selection) will be found.


text:
Q: how to run batch queries in sql ce? for example:
  StringBuilder query = new StringBuilder();

                    foreach (KeyValuePair<string, string> key in list)
                    {
                        string name = key.Key;
                        string emails = key.Value;
                        query.AppendFormat("insert into contacts(name, emails) values('{0}', '{1}');", name, emails);
                    }

   string queries = query.ToString(); //how to run it?

it is possible?

A: Your best option is to begin a transaction before the loop, execute each statement rather than adding it to stringbuilder, and commit after the loop (or every n number of records).
Also, you should use a parameterized command, something along the lines of:
SqlCeCommand oCommand = conn.CreateCommand();
oCommand.CommandText = "insert into contacts(name, emails) values(?, ?)";
// I can't remember if the param names need @ or not
oCommand.Parameters.Add("@name", SqlDbType.VarChar);
oCommand.Parameters.Add("@email", SqlDbType.VarChar);

SqlCeTransaction oTrans = conn.BeginTransaction();
try {
  foreach (KeyValuePair<string, string> key in list) {
     oCommand.Parameters[0].Value = key.Key;
     oCommand.Parameters[1].Value = key.Value;
     oCommand.ExecuteNonQuery();
  }
  oTrans.Commit();
} catch (Exception ex) {
  oTrans.Rollback();
}

Alternatively, you can use the SQL Compact Bulk Insert Library from codeplex. I believe that this uses a TableDirect SqlCeCommand on top of a SqlCeResultSet, which should bypass the query processor and be about as fast as you can get.

A: This is not a supported feature in V3.5 of the compact edition.  Not sure if it changed in V4.
The opening of a connection/transaction and looping is your only option really.
Sorry it's bad news!


text:
Q: Python3 streaming string replacement I have a python3 "file-like object" whose read() method returns a string - it comes from either an opened file or an object streamed from s3 using boto3.
I want to sanitize the stream before passing it to csv.DictReader, in particular because that module barfs on NUL characters on the input.
The CSV files I'm processing may be large, so I want to do this "streaming", not reading the entire file/object into memory.
How do I wrap the input object so that I can clean up every string returned from read() with a call like: .replace('\x00', '{NUL}')?
I think that the io library is where to look, but I couldn't find something that obviously did what I want - to be able to intercept and transform every call to .read() on the underlying file-like object and pass the wrapper to csv, without reading the whole thing at once.

A: You can use a simple generator function that fixes the data before passing it on to csv.reader:
import io
import csv

def denull(line_gen):
    for line in line_gen:
        yield line.replace('\x00', '{NUL}')

data = io.StringIO("""
hello;world
asdf;h\x00pla
""".strip())

for row in csv.reader(denull(data), delimiter=";"):
    print(row)

prints out
['hello', 'world']
['asdf', 'h{NUL}pla']


text:
Q: Faces Message after download a file in JSF Good Day, I have download file function in Java that is being called in JSF.
But after the file was downloaded, the FacesMessage is not shown in the page..
Is there any reason behind it?
I have a code in xhtml:
<h:commandButton id="submit" value="#{message.btn_submit}" action="#{bean.doProcess}"/>

in Backing bean:
public void doProcess() {
MessageUtil.addMessage("SOME MESSAGE");
FacesContext faces = FacesContext.getCurrentInstance();
                       HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();
                       response.setContentType("application/pdf");
                       response.setContentLength(pdf.length);

                       List<String> ids= request.getIds();
                       String fname = utilsFactory.getPDFFilename(hwbs);

                       StringBuilder sb = new StringBuilder("attachment; filename=\"")
                        .append(fname)
                        .append("\"");
                       String removeNewLine = sb.toString().replaceAll("\\r|\\n", "");

                    response.setHeader("Content-disposition", removeNewLine);
                       try {
                           ServletOutputStream out;
                           out = response.getOutputStream();
                           out.write(pdf);
                       } catch (IOException e) {
                           LOGGER.error("Unable to print to outputstream", e);
                       }
                       faces.responseComplete();
}


text:
Q: Bokeh: Updating of legend when using different views I have an issue with updating legend_groups in bokeh:
My data is based on four columns: x-values, y-values, categorization, geography. I created a scatterplot in Bokeh with all scatter points coming from the same x- and y-column. I split the scatter points into two categories (0 and 1) based on the categorization column. I then used factor_mark and factor_color to display the two categories with different colors (orange vs blue).
I further used legend_group to create the legend for the scatter plot. That works fine. The legend looks like this:

0 orange 1 blue

Here a code snippet:
renderer_scatter = plot.scatter(
    x='x', y='y', source=data_provider,
    view=data_provider.geography, size=5, fill_alpha=0.4,
    marker=factor_mark('x', ['hex', 'triangle'], 'categorization'),
    color=factor_cmap('x', 'Category10_3', 'categorization'), legend_group='categorization')

I further added a drop-down to my dashboard which specifies the views of my data based on geography.
Unfortunately, the legend_group does not update appropriately when I change the view. Depending on the geography it looks like this:

0 blue 1 blue

or

0 orange 1 orange

or

0 orange 1

and so on.
The scatterplot itself updates perfectly fine.
Do you have any idea what the issue might be?
Thanks a lot in advance!

A: legend_group is a shorthand convenience for computing legend entries once, up front, when the figure is created in Python. If you need something that reacts to data changes dynamically, then you want to use legend_field which is computed on the "JavaScript side" in the browser. (Or alternatively, you can manage LegendItem objects completely manually, adding and removing as the data changes.)


text:
Q: Windows 10 - Unable to change domain password when password has expired and computer is locked We have recently migrated over to Windows 10 Pro Version 1511. Prior to that we were on Windows 7 Pro.
We have fast user switching disabled for all computers by group policy in our domain. It is quite common that users don't change their password even though they are given password expiration notice.
On Windows 7 clients when a domain users account password had expired after they had logged in and the computer gets locked (for lunch or they were idle) they came back to login and they were able to change the password as they had a switch user option as shown below.

(source: imgsafe.org)
However, in Windows 10 when the same situation happens we get the following prompt:
"Your password has expired. To set a new password, select OK, select Switch user, re-enter your current password, then follow the prompts on the screen.
So we click ok and now there is no longer a switch user option?

(source: imgsafe.org)
Has anyone come across this yet? Wonder if this is a bug in Windows 10 or a limitation of some kind?

A: The switch user option is likely disabled in your environment, for security reasons.

*

*Have the customer log onto another computer.

*Let whoever does account management in your organization do their
job and reset the user's password.  It is not a workaround, it the
simplest solution.

*Also, the customer probably will not be able to unlock their session,
and will probably have to restart the computer anyway, so that's
another way.

As for allowing customers to change their own passwords, they already can.  However, you need to ensure that they get ample warning of account expiration.  If they have to click past a warning for two weeks to get into their account, they have no one to blame but themselves for the inconvenience of contacting the service desk to get a password reset.

A: Might be related to windows update from August which disables falling back to NTLM from Kerberos https://technet.microsoft.com/en-us/library/security/ms16-101.aspx


text:
Q: Pygame not loading image I cannot display the image that is in the same source folder as my project. Also it gives me squiggly lines under (x, y) and it tells me
"Shadows name "x" & "y" from outer scope"
It shows each one for the "x" and "y" so I just put &
Lastly my quit() at the end tells me
"PEP 8: blank line at the end of file"
Completely new to python and pygame
I am not sure what to try
import pygame

pygame.init()

display_Width = 400
display_Height = 400

gameDisplay = pygame.display.set_mode((display_Height, display_Width))
pygame.display.set_caption('Shonen Run Project')

black = (0, 0, 0)
white = (255, 255, 255)

clock = pygame.time.Clock()
crashed = False
heroImg = pygame.image.load('harper.png')

def hero(x, y):
    gameDisplay.blit(heroImg, (x, y))

x = (display_Width * 0.45)
y = (display_Height * 0.8)

while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True

    gameDisplay.fill(white)
    hero(x,y)

    pygame.display.update()
    clock.tick(60)

pygame.quit()
quit()

A: I guess you use a IDE. The image loading of your code seems fine, just note that it does only work if the current working directory is actually the directory your python file and your image file is in. A simple way to ensure this is:
import os
import sys
os.chdir(sys.path[0])

The other issues are just warnings.
You have two global variables x and y, and a function def hero(x, y): which has also two arguments x and y. The warning tells you that if you access x or y inside hero, you actually access the local x or y and you have no way to access the global x or y (they are shadowed).
I would suggest renaming the global x and y variables to a more meaningful name, and also remove the hero function, since it is pretty useless.
PEP 8 is the python style guide. You should follow it, as it helps to keep your code readable, especially if other people than yourself are going to read your code. But of course it's not a law, and a missing blank line at the end of file will probably bother no one...


text:
Q: Jquery Change class click This is so simple problem but i don't understand problem.
I was click div change class but it does not work when I click on the changing div

$(".one").click(function() {
$(this).attr('class', 'two');
});

$(".two").click(function() {
$(this).attr('class', 'one');
});
.one {width: 50px; height: 50px; background-color:red;}
.two {width: 50px; height: 50px; background-color:blue;}

A: $(".one").click(function() {
$(this).toggleClass('one');
$(this).toggleClass('two');
});

$(".two").click(function() {
$(this).toggleClass('one');
$(this).toggleClass('two');
});


text:
Q: Append Alpacajs form to existing form I'm trying to create a means of user input calculation, where input fields and calculation formula are set dynamically. For example, a have Number of apples and Price for one apple inputs, so I multiply inputs to get the price. In another case I have length, width and height inputs to calculate volume.
I decided to store inputs, data and calculation function and reassemble the form form json with Alpacajs
But calculation fields are only a part of a bigger form.
So using
$("#alpacaForm").alpaca(window.alpacaForm.object);

adds a new form inside the alpacaForm element.
Is there a way to append fields generated by alpacajs to an existing form?

A: The only way I've managed to do it is by rendering into a separate element and copying the elements over.
For example:
<form id="my-form">

  Foo
  <input id="foo">

  Bar
  <input id="bar">

</form>

The JavaScript (and jQuery):
var $myForm = $('#my-form');
var $schemaControlContainer = $myForm.find('.schema-control-container');
var mySchema = JSON.parse(mySchemaJson);

var $scratchpad = $('

').hide().
    insertAfter($myForm);

function postRender (control) {

  // I actually have multiple forms, so I need to make sure the IDs are unique.
  $scratchpad.find('.alpaca-control').each(function (i, alpacaControl) {
    alpacaControl.id = $myForm.attr('id') + '-' + alpacaControl.id;
  });
  $scratchpad.find('.alpaca-control-label').each(
      function (i, alpacaControlLabel) {
    alpacaControlLabel.htmlFor = $myForm.attr('id') + '-' +
        alpacaControlLabel.htmlFor;
  });

  // Select elements we want to copy. Note that I haven't tried this with any
  // particularly complicated JSON schemata, so this may be naïve.
  var $goodies = $scratchpad.find('.alpaca-control,.alpaca-control-label');

  // Optional: mark schema controls as such, and allow autocompletion.
  $goodies.filter('.alpaca-control').addClass('my-schema-datum').
      attr('autocomplete', null);

  // Remove Alpaca classes and Bootstrap crap. (I hate Bootstrap, but the 'web'
  // version of Alpaca doesn't seem to work right now. TODO: Update after
  // https://github.com/gitana/alpaca/issues/507 is fixed.)
  $goodies.removeClass('alpaca-control').removeClass('alpaca-control-label').
      removeClass('form-control').removeClass('control-label');

  // Move the goodies to the schema control container, in the form.
  $schemaControlContainer.append($goodies);

  // Clean up the clutter we don't need.
  $scratchpad.empty();
}

// Have Alpaca render the schema into the scratchpad, and then run the function
// we just defined.
$scratchpad.alpaca({ schema: mySchema, postRender: postRender });

I was hoping to find an Alpaca option to prevent needing to do all this, but there doesn't seem to be one.


text:
Q: Backbutton event preventDeafult [phonegap + onsenUI] I'm building a simple app with phonegap + OnsenUI but Ive noticed th OnsenUI is taking control of my BackButton event so i cant use evt.preventDefault();
This is what im trying to do:
document.addEventListener("backbutton", backButtonFire, false);
function backButtonFire(evt) {
  evt.preventDefault();
  evt.stopPropagation();
  alert(1);
}

When the event is fired i see the alert(1) but the app still going to the background.
How can I use preventDefault in this situation?

A: Found the answer, I found this at the onsenui.js:
  /**
   * Disable this framework to handle cordova "backbutton" event.
   */
  disableDeviceBackButtonHandler: function() {
    this._getOnsenService().DeviceBackButtonHandler.disable();
  },

so i just used:
ons.disableDeviceBackButtonHandler();

Now its working great but it disables all the OnsenUI backbutton handler settings so you need to set one by yourself.


text:
Q: How to know when to use "someone" or "anyone"? I am trying to write a grammar rule that will be able to identify when to use someone or anyone, and I got confused. I couldn't find any clear way to do this.
For instance, "anyone can do it" is totally different from "someone can do it", but since both are pronouns referring to unknown entities, it's extremely difficult to predict the correctness of the grammar.
Any suggestions or am I missing something?

A:
Someone can do it.

There is at least one person who can do it. The others may or may not be able to do, it is not stated.

Anyone can do it.

Every single member can do it. There is no one who cannot do it.

A: You are correct. There is no clear way to do this. Robin Lakoff's paper entitled "Some Reasons Why There Can't Be some ~ any Rule" is precisely about this situation.
Short summary of a few of the reasons:

*

*Any is a Negative Polarity Item, but some isn't.

*Many environments (like questions) allow NPIs like any, but don't disallow some.

*There are several kinds of any, including NPI any, and "Free Choice" any, as in

*

*Any idiot can solve this problem.

A: Use "someone" when some elements of a certain group are involved, but not all of the elements. So "someone can do it" means that not everyone from that group can do it, but some can.
Use "anyone" when all elements of a group are involved, but you don't necessarily mean all of them. So "anyone can do it" would mean that everybody in that group could do it, even though it doesn't take them all to do it.


text:
Q: C# solution design to display web content from a complex calculation? I need to process a complex calculation to generate a report and display as a webpage.  It has to be run periodically to recalculate the formula based on new input.
I have a few ideas:
1. Create a web service to process and cache the content and then create a web application to request the content via HTTP periodically.
2. Create a service to output a file periodically and then create a web application to read the file.
3. Create a web application which has a task in there running periodically to generate the output and then create a webpage to display it.
I have read some of the old threads but I want to know which is the better approach, the pros and cons or if there are a newer way of implementing this?

A: JiTE!
I did a program that is similar to yours. The task is to generate a report when a user asks the application to do.  Usually it is a daily report, but the calculation costs several minutes, for there are too many records, and the fomular is complex, too.
We created a periodly thread to check wether it is time to calucate.Thus the thread will calute and store the condition and result into SqlServer. When users click the button to view the daily report, yet the report is in DB and the application just needs to read it out from DB, and show it on the screen.
Let disscuss your solutions: solution 1 and 2 seems good, but sulution 3 does not match the DesignPatterns, because all tasks are put in a single application.
Hope everything goes well!
                                                         David Liu


text:
Q: How to determine whether the number is 32-bit or 64-bit integer in Python? I want to differentiate between 32-bit and 64-bit integers in Python. In C it's very easy as we can declare variables using int_64 and int_32. But in Python how do we differentiate between 32-bit integers and 64-bit integers?

A: There's no need.  The interpreter handles allocation behind the scenes, effectively promoting from one type to another as needed without you doing anything explicit.

A: Basically, you don't.  There's no reason to.  If you want to deal with types of known bit size, look at numpy datatypes.
If you want to put data into a specified format, look at the struct module.

A: The struct module mentioned in the other answers is the thing you need.
An example to make it clear.
import struct

struct.pack('qii', # Format string  here.
            100, # Your 64-bit integer
            50, # Your first 32-bit integer
            25) # Your second 32-bit integer

# This will return the following:
'd\x00\x00\x00\x00\x00\x00\x002\x00\x00\x00\x19\x00\x00\x00'

documentation for the formatting string.

A: The following snippet from an ipython interpreter session indicates one way of testing the type of an integer.  Note, on my system, an int is a 64-bit data type, and a long is a multi-word type.
In [190]: isinstance(1,int)
Out[190]: True
In [191]: isinstance(1,long)
Out[191]: False
In [192]: isinstance(1L,long)
Out[192]: True

Also see an answer about sys.getsizeof.  This function is not entirely relevant, since some additional overhead bytes are included.  For example:
In [194]: import sys
In [195]: sys.getsizeof(1)
Out[195]: 24
In [196]: sys.getsizeof(1L)
Out[196]: 28


text:
Q: Django migrate Integer to BigInteger I am using South for migrations.
Is it possible to edit a field, that was previously using IntegerField as its datatype to use BigIntegerField as its datatype?
Does south support such migrations or will I have to perform multiple migrations for the same (Adding another column followed by a data migration and finally dropping the old column)?

A: The South docs appear to support this change:

South will detect if you change a field, and should correctly change
  the field type, with one exception:
If you alter to a field with a CHECK constraint (e.g.
  PositiveIntegerField) the constraint won't be added to the column (it
  is removed if you alter away, however). This will be fixed in a future
  release.


text:
Q: how to make a copy from csv file to edit it when i'm trying to make a copy from csv file to edit it away of the original
then I apply the effects to the original
import csv
import shutil
from tempfile import NamedTemporaryFile

filename = "data1.csv"
temp_file = NamedTemporaryFile(delete=False)
print(temp_file.name)
with open(filename, "r",encoding='utf8') as csvfile, temp_file:
    reader = csv.DictReader(csvfile)
    fieldnames = ["id", "name", "email", "sent"]
    writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
    # writer.writeheader()
    for row in reader:
        writer.writerow({
            "id":row["id"],
            "name":row["name"],
            "email":row["email"],
            "sent":""
        })

I get this error :/
C:\Users\Arafat\AppData\Local\Temp\tmpwgkcslas
Traceback (most recent call last):
  File "C:\Users\Arafat\Desktop\30dpython\hungry_data.py", line 49, in <module>
    "sent":""
  File "C:\Users\Arafat\AppData\Local\Programs\Python\Python36-32\lib\csv.py", line 155, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\Users\Arafat\AppData\Local\Programs\Python\Python36-32\lib\tempfile.py", line 483, in func_wrapper
    return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str'

A: The error is the result of your temp_file being opened in binary mode rather than text mode (the default is w+b). Change it to:
temp_file = NamedTemporaryFile(mode='w', encoding='utf8', delete=False)

(the encoding is not strictly necessary, but since you're specifying it on the input, makes sense to specify it on the output).
See https://docs.python.org/3/library/tempfile.html


text:
Q: Angular's bindings don't work with elements added in directives My directive is
myApp.directive('myRequired', function ($compile, gettextCatalog) {
    return {
        link: function (scope, element, attrs) {
            var noticeContainer = '
{{errorMessage}}
';
            element.after(noticeContainer);

        scope.$on("submitstart", function (event, data) {
            scope.showSomeNotices = false;
            if (!element.val()) {
                scope.errorMessage = gettextCatalog.getString("Empty field");
                scope.showSomeNotices = true;

            }
        });
    }};
});

But ng-show and bracets {{errorMessage}} ignores connected variables. I always see {{errorMessage}} as text on my page. How to fix?

A: Mentioned in the comments above you must compile the string like this:
…
var noticeContainer = '
{{errorMessage}}
',
    content = $compile(noticeContainer)(scope);

element.after(content);
…

I've created a plunkr for you: https://plnkr.co/edit/9HKoLg401Thip2cLHYsb?p=preview


text:
Q: How to convert character in dataframe to numeric without the loss of decimal Assume a database in the below format
Voltage Global_intensity Sub_metering_1
 <chr>   <chr>            <chr>
1 234.840 18.400           0.000
2 233.630 23.000           0.000
3 233.290 23.000           0.000
4 233.740 23.000           0.000
5 235.680 15.800           0.000
6 235.020 15.000           0.000
7 235.090 15.800           0.000
8 235.220 15.800           0.000
9 233.990 15.800           0.000
10 233.860 15.800           0.000
# ... with 2,075,249 more rows

I want to convert this character variables of column types to numeric without loss of decimal digits
df1$Voltage <-as.double(df1$Voltage,options(digits = 8))

 Voltage Global_intensity Sub_metering_1
     <dbl> <chr>            <chr>
 1    235. 18.400           0.000
 2    234. 23.000           0.000
 3    233. 23.000           0.000
 4    234. 23.000           0.000
 5    236. 15.800           0.000
 6    235. 15.000           0.000
 7    235. 15.800           0.000
 8    235. 15.800           0.000
 9    234. 15.800           0.000
10    234. 15.800           0.000
# ... with 2,075,249 more rows

Now I get a result like this with loss of decimal digits. How to rectify it?

A: The key point is to distinguish between what is shown and what is stored.  Voltage is still stored at full precision.
DF[] <- lapply(DF, as.numeric)
DF$Voltage
## [1] 234.84 233.63 233.29 233.74 235.68 235.02 235.09 235.22 233.99 233.86

Note
Lines <- "Voltage Global_intensity Sub_metering_1
1 234.840 18.400           0.000
2 233.630 23.000           0.000
3 233.290 23.000           0.000
4 233.740 23.000           0.000
5 235.680 15.800           0.000
6 235.020 15.000           0.000
7 235.090 15.800           0.000
8 235.220 15.800           0.000
9 233.990 15.800           0.000
10 233.860 15.800           0.000"

library(tibble)
DF <- as_tibble(read.table(text = Lines, colClasses = "character"))


text:
Q: Horizontally align elements shifted by a float In the following test page there are a video and an iframe elements, both with margin-left: auto; margin-right: auto; CSS style.
The video element is shifted toward right by a float: left; element containing a few textual lines, therefore it is misaligned with the lower iframe.
I'd like the iframe to be centrally aligned with the video, keeping the video in its current position.

    A few colored entries here.

    <video src="..."
    style="display: block; margin-left: auto; margin-right: auto;">
    </video>

A: You need to wrap the whole thing in a wrapper div. Then you can float both divs to the left and still have the insides automatically center.

        A few colored entries here.

            <video src="..."      style="display: block; margin-left: auto; margin-right: auto;">      </video>

#Wrapper { overflow: hidden; }
.leftColumn { float: left; border-right: thin solid; width:  200px; }
.rightColumn { float: left; width: 800px; }

I didn't test the code, but it should work.

A: How about putting the two divs that are on the right in their own div, then floating that to the right and using margin:auto (like you have currently) to center them.  That way instead of being centered on the page they are centered on the same div, and one shouldn't be pushed farther than the other regardless of the other float.

    A few colored entries here.

    <video src="..."
    style="display: block; margin-left: auto; margin-right: auto;">
    </video>

If I misunderstood and you didn't want to float those to the right, just ignore that and use margins instead.  Either way adding a container div around the ones you want centered together should take care of it.


text:
Q: Verification of Proof: Define the image and possibilities for ker$\phi$ Assume $\phi: \mathbb{Z}\rightarrow G$ is defined by $\phi(n)=a^n$.
We know this is a homomorphism already.  Its image, clearly is the cyclic subgroup of $G$ generated by $a$.  What I don't get is the following explanation:
If $\langle a\rangle$ is an infinite cyclic group then the kernel is $0$.  If $\langle a\rangle$ is a cyclic group of order $n$ then the kernel is $n\mathbb{Z}$.
How do you get this?  If possible please explain in detail.

A: Hint
Assume the kernel is different from $0.$ Then, for some $n$ it is $\phi(n)=a^n=1.$ What is $\phi(n+1)=a^{n+1}?$ More generally, what is $\phi(n+k)=a^{n+k}$ for $k=1,\cdots, n?$ Can the cyclic subgroup generated by $a$ be infinite?


text:
Q: Cofree construction, thought process
Let $F: \mathbf{A} \to \mathbf{B}$ be any functor and $B$ an object of $\mathbf{B}$. We say the pair $(A,\epsilon)$, with $A$ and object of $\mathbf{A}$ and $\epsilon: FA \to B$ is a morphism of $\mathbf{B}$ is cofree over B with respect to $F$ just in case $\epsilon:FA \to B$ has the universal property that  given any morphism $f:FA^\prime \to B$ (with $A^\prime$ an object of $\mathbf{A}$) there exists unique $A$-morphism $\psi: A^\prime \to A$ such that the appropriate diagram commutes, namely
  $$
\epsilon \circ F\psi = f.
$$

The above definition is taken word for word from Arbib. He goes on to say that if the $F$ is $\cdot \times X_0: A \mapsto A\times X_0$, then the corresponding $A$ should be $B^{X_0}$ and $\epsilon$ should be the evaluation map, namely
$$
\epsilon: B^{X_0}\times X_0 \to B, \ \ \epsilon (f,x):=f(x).
$$
My question is this, given the co-universal definition, how does one think in order to construct the appropriate $A$ and $\epsilon$. I am interested in the thought process that leads someone to "discovering" both the set $A$ and the map $\epsilon$.
For example if I take the functor $F$ to be from the category of vector spaces, and let it assign $F: V \to V\otimes V$, then what would the pair $(A,\epsilon)$ be in this case, that would satisfy the co-free property?

A: I agree with Derek Elkins' suggestion in the comments: If you want to have intuition for what cofree morphisms are, since cofree morphisms are the counits of adjunctions, one way to go is to study the constructions in the adjoint functor theorem, though I also suggest just looking at more examples of adjoints in general.

My question is this, given the co-universal definition, how does one think in order to construct the appropriate $A$ and $ϵ$. I am interested in the thought process that leads someone to "discovering" both the set $A$ and the map $ϵ$.

One powerful part of category theory is just how intuitive some of the definitions are, once you get used to what they mean. In particular, the notion of natural transformation describes accurately what it means to "naturally" have arrows between $F(a)\to G(a)$ for all $a$ when $F,G$ are functors. Thus one way to understand certain definitions in category theory is to take advantage of its intuitive notions, such as naturality.
For example, let's rephrase the definition of cofree that you gave. A cofree arrow $f: FA \to B$ gives a correspondence between arrows from $FA'$ to $B$ and arrows $A' \to A$ via the universal property. In other words, there is a natural bijection between the functors Hom$(-,A)$ and Hom$(F-,B)$. In a Yoneda Lemma-like manner, we can look at the arrow corresponding to the identity in Hom$(A,A)$ to get an arrow in Hom$(FA,B)$ that is our original cofree arrow. Thus we see that a cofree arrow is exactly given by a natural bijection Hom$(-,A) \cong$ Hom$(F-,B)$.
Thus finding the cofree arrow amounts to finding an $A$ such that arrows from $A'$ to $A$ "naturally correspond" to arrows from $FA'$ to $B$.
For example in the case $F$ is $- \times X$, the condition is Hom$(A',A) \cong$  Hom$(A'\times X,B)$. We would like set such that a function $f: A'\times X \to B$ "can be thought of as" a map $A' \to A$.
If $f(a,x) = b$, then we would like to repackage this function in a way to make it only a function of $A'$ while not losing or gaining information. Then it shouldn't be too surprising that the correct object to do this is $B^X$, as we can send $a$ to the function that sends $x$ to $f(a,x)$ which gives the natural correspondence we want.

For example if I take the functor $F$ to be from the category of vector spaces, and let it assign  $F:V→V\otimes V$ , then what would the pair $(A,ϵ)$ be in this case, that would satisfy the co-free property?

Let's try this. We would like to find a vector space W such that Hom$(V',W) \cong$ Hom$(V'\otimes V',V)$. Note now that the set of homomorphisms is no longer just a set, but a vector space. If we expect a nice, truly natural isomorphism to exist, we had better expect it to be an isomorphism of vector spaces, not just of sets.
But this leads to a problem. If we let $V,V'$ be finite dimensional, then we have dim$($Hom$(V'\otimes V',V))$ = dim$(V')^2$dim$(V)$ whereas Hom$(V',W)$ has dimension dim$(V')$dim$(W)$. Now certainly we can't choose the dimension of $W$ such that $n^2$dim$(V)$ = $n$dim$(W)$ for all $n$, so we shouldn't expect $W$ to exist.
Here is an example that does work.
We can consider the tensor product functor in the category of vector spaces, $(-)\otimes V$, and ask if there is a cofree arrow to $W$. In other words we would like to find a $W'$ such that Hom$(V',W') \cong$ Hom$(V'\otimes V,W)$. However one definition of the tensor product of two vector spaces $V',V$ is a vector space such that bilinear maps $V\times V' \to W$ correspond to linear maps $V\otimes V' \to X$. However, a bilinear map is nothing more than a linear map to a vector space of linear maps, or an element of Hom$(V',$Hom$(V,W))$, so we have an isomorphism Hom$(V',$Hom$(V,W)) \cong$ Hom$(V'\otimes V,W)$, and Hom$(V,W)$ is then the $W'$ that we want.
We can now recover the cofree arrow by considering the map corresponding to the identity, which is the evaluation map Hom$(V,W)\otimes V \to W$.
The reason this works is the tensor-hom adjunction, which characterizes the tensor product, and is why tensor products are so useful and important.
I hope these examples gave at least a little insight into how to think about the existence of cofree arrows. I will just note once again that the majority of good examples will be examples of adjoints, which are good to look into to better understand this.


text:
Q: How to add a generic property of Class inside of an existing Class Not really sure how to explain it in a one-liner but here's my situation.
I have an abstract base class called "Deal" which has a property in it which is of a class "Inventory"
Now a deal can be either Cash, Finance, Lease, Wholesale or Rent-To-Own which is why it's of type Deal. It's also abstract as each of the deal types have some properties that don't apply to other but they all have a set of shared so the various deal types (i.e. - Finance, Lease, etc.) inherit from the base class Deal and have their own added methods and properties.
The same is true with another abstract class of "Inventory". Inventory can be things like car, truck, boat, RV, etc.) so therefore I have a class of Inventory.
Here's the issue:
A deal must contain a unit in inventory. For example, you finance a car or you lease an RV then you have a Deal with an inventory property of type Inventory or whatever the case may be.
When I create the Deal class and I add a property to it like SoldUnit as type Inventory, the T is inherited from the Deal class. How can I create a generic property of type Inventory inside of the Deal class?
Deal won't really work because of the number of possibilities, so how could I make a generic "SoldUnit" property which references an Inventory class inside of the Deal class? And while maintaining strict typing? I know I could make a property called SoldUnit with a type of object or dynamic, but is there a better way?
Thanks!
EDIT:
Sorry, here is an excerpt of the code: It doesn't work because type T is already a DealType, but it's the two properties [ ret.Vehicle = new Car(); and ret.SoldUnit = new Car(); ] that I'm trying to populate with a specific inventory type (car, truck, rv, boat, etc.) in the Get() method. The specific inventory type is determined by a flag in the database field.
Thanks again!
public abstract class Deal<T>
{
    public string Uid { get; set; } = Guid.NewGuid().ToString();
    public DealTypes DealType { get; set; } = DealTypes.Finance;

    public Buyer Customer { get; set; }
    public Inventory<T> Vehicle { get; set; }
    public Location Location { get; set; }
    public Inventory<T> SoldUnit { get; set; }

    public abstract T Add(string id);
    public abstract T Update(string id);
    public abstract T Get(string id);
}

public abstract class Inventory<T>
{
    public string Uid { get; internal set; } = Guid.NewGuid().ToString();
    public Location Location { get; set; }
    public string StockNumber { get; set; } = "";
}

public class Cash : Deal<Cash>
{
    public decimal TradeAllowance { get; set; }
    public decimal TradePayoff { get; set; }
    public decimal TotalDown { get; set; }
    public decimal DueOnDelivery { get; set; }

    public override Cash Get(string id)
    {
        var ret = new Cash();
        ret.Customer = new Buyer();
        ret.Vehicle = new Car();
        ret.Location = new Location();
        ret.SoldUnit = new Car();
   }
}

public class Car : Inventory<Car>
{
    public decimal GrossWeight { get; set; }
    public decimal NetWeight { get; set; }
    public string Branded { get; set; } = "";
    public string FuelType { get; set; } = "";
    public string Trim { get; set; } = "";
    public string Body { get; set; } = "";
    public int Cylinders { get; set; }
    public decimal EngineSize { get; set; }
    public string TransmissionType { get; set; } = "";
    public string Suspension { get; set; } = "";
    public string InteriorColor { get; set; } = "";

    public bool OdometerExceedsLimit { get; set; }
    public bool OdometerTrueMileageUnknown { get; set; }
    public bool OdometerFiveDigit { get; set; }

    public string TitleNumber { get; set; } = "";
    public DateTime? TitleDate { get; set; }
    public string TitleState { get; set; } = "";
    public DateTime? TitleDue { get; set; }
    public DateTime? TitleReceived { get; set; }
}

A: I've simplified your code down somewhat to the necessary elements to make this work, but you do need to have your base classes defined like Deal<D, I> where D : Deal<D, I> where I : Inventory<D, I> & Inventory<D, I> where D : Deal<D, I> where I : Inventory<D, I> respectively.
Your code would then look like this:
public abstract class Deal<D, I> where D : Deal<D, I> where I : Inventory<D, I>
{
    public I Vehicle { get; set; }

    public abstract D Get(string id);
}

public abstract class Inventory<D, I> where D : Deal<D, I> where I : Inventory<D, I>
{ }

public class Cash : Deal<Cash, Car>
{
    public override Cash Get(string id)
    {
        return new Cash() { Vehicle = new Car() };
    }
}

public class Car : Inventory<Cash, Car>
{ }

This is what you need to do to have a strongly-typed Vehicle property and Get (etc) method.


text:
Q: How to get mailchimp list name and list id using php How to get mailchimp list name and list unique id?
I have tried to get it by using mailchimp api but it show the blank result.

A: Please follow the instructions available here
https://github.com/mailchimp/mcapi2-php-examples


text:
Q: Brace expansion and compound command I do not understand why these two loops are different.  It must have something to do with when the brace expansion is performed and how white space is interpreted
for i in b{e,\ }s ; do echo $i ; done

for i in bes b s ; do echo $i ; done

and consider this too
for i in $(echo b{e,\ }s) ; do echo $i ; done

A: When you do for i in b{e,\ }s ; do echo $i ; done, the brace expansion b{e,\ }s is expanded into two arguments, one is bes and another is b s so the for loop has two values to iterate over. Note that here b s is a single argument.
On the other hand, in for i in bes b s ; do echo $i ; done, you are explicitly mentioning three arguments to iterate over (separated by spaces), namely bes, b and s.
In the third case, the command substitution $(echo b{e,\ }s) will generate three arguments bes, b and s so again the for loop have three values to iterate over just like the second case.