text:
Q: How to get more space on /dev/mapper/centos-root The following is df -h result. /dev/mapper/centos-root is 100%.
/dev/mapper/centos-root    50G   50G   20K  100% /
devtmpfs                  3.8G     0  3.8G    0% /dev
tmpfs                     3.9G  8.0K  3.9G    1% /dev/shm
tmpfs                     3.9G  8.9M  3.8G    1% /run
tmpfs                     3.9G     0  3.9G    0% /sys/fs/cgroup
/dev/mapper/centos-home   406G  5.0G  401G    2% /home
/dev/sda3                 497M  303M  195M   61% /boot
tmpfs                     780M     0  780M    0% /run/user/0
tmpfs                     780M     0  780M    0% /run/user/1000

I removed a lot of large files (nGB) in $HOME and $HOME/Downloads. But there is no change in df -h result.
Could you tell me where I should remove files to get more space on /dev/mapper/centos-root?

A: Your Home directory is mounted from partition
/dev/mapper/centos-home

Try deleting unimportant files for example in
/tmp/

If you want to examine the file sizes have a look at the du command

A: The following is df -i result. /dev/mapper/vg00-lv_var 6553600 6553600 0  100% /var
Filesystem                 Inodes   IUsed    IFree IUse% Mounted on
/dev/mapper/vg00-lv_root 49856512  220435 49636077    1% /
devtmpfs                 16444850     583 16444267    1% /dev
tmpfs                    16448811       6 16448805    1% /dev/shm
tmpfs                    16448811     986 16447825    1% /run
tmpfs                    16448811      16 16448795    1% /sys/fs/cgroup
/dev/sda2                   32768      35    32733    1% /boot
/dev/sda1                       0       0        0     - /boot/efi
/dev/mapper/vg00-lv_var   6553600 6553600        0  100% /var
tmpfs                    16448811      17 16448794    1% /run/user/42
tmpfs                    16448811       1 16448810    1% /run/user/0
tmpfs                    16448811       1 16448810    1% /run/user/99


text:
Q: Routing not working with dynamic URL See my code in Plunker: https://plnkr.co/edit/knuf4Z64Kla2vPQRociv?p=info
I am trying to get the routing part working with a dynamic URL.
my Component.js (only metadata, full code is in plnkr.co)
sap.ui.core.UIComponent.extend("com.myapp.Component", {
    metadata: {
        rootView: "myapp.main",
        routing: {
            config: {
                routerClass: "sap.m.routing.Router",
                viewType: "JS",
                viewPath: "myapp",
                controlId: "mainapp",
                controlAggregation: "pages",
                transition: "slide"
            },
            routes: [{
                pattern: "main",
                name: "main",
                target: "main"
            }, {
                pattern: "agent",
                name: "agent",
                target: "agent"
            }],
            targets: {
                main: {
                    viewName: "main",
                    viewLevel: 1
                },
                agent: {
                    viewName: "agent",
                    viewLevel: 2
                }
            }
        }
    }
});

A: Check this: https://sapui5.hana.ondemand.com/sdk/#docs/guide/cf3c57c89ef0491793d1ce327ab4f9b2.html
You need to specify a routerClass in your config. That is most probably why router is undefined in your scenario.
Furthermore you will need to specify a rootView as well as a controlId and a controlAggregation in your routing config.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deserialize JSON to type containing reference to another deserialized object in C# I have a following model:
public interface IEntity
{
    string Id { get; }
}

public class EntityParent : IEntity
{
    public string Id { get; }

    public EntityChild EntityChild { get; }

    [JsonConstructor]
    public EntityParent(string id, EntityChild entityChild)
    {
        Id = id;
        EntityChild = entityChild;
    }
}

public class EntityChild : IEntity
{
    public string Id { get; }

    public int Age { get; }

    [JsonConstructor]
    public EntityChild(string id, int age)
    {
        Id = id;
        Age = age;
    }
}

Next I have some JSON that I need to deserialize to collections of the above types:
{
            "Children":
            [
                {
                    "Id"          : "Billy",
                    "Age"         : 42
                }
            ],

            "Parents" :
            [
                {
                    "Id"          : "William",
                    "EntityChild" : "Billy"
                }
            ]
}

Eventually I want to have a list of EntityChildren and a list of EntityParents that will (optionally) contain references to objects in the first list , or at least references to instances of EntityChild. I have attempted to write a custom JsonConverter (I am using Newtonsoft.Json 9.0.1 NuGet package), where in the ReadJson() method I am looking for a child with specific Id, like so:
public class ParentConverter<TEntity> : JsonConverter where TEntity : IEntity
{
    private readonly IEnumerable<TEntity> _children;

    public ParentConverter(IEnumerable<TEntity> children)
    {
        _children = children;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        JObject jObject = JObject.Load(reader);

        TEntity target = _children.FirstOrDefault(d => d.Id == jObject["Id"].ToString());

        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(TEntity).IsAssignableFrom(objectType);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Here's a simple test:
public class JsonTest
{
    const string Json = @"
        {
            ""Children"": [
                {
                    ""Id""          : ""Billy"",
                    ""Age""         : 42
                }
            ],

            ""Parents"" : [
                {
                    ""Id""          : ""William"",
                    ""EntityChild"" : ""Billy""
                }
            ]
        }";

    public static void Main()
    {
        JObject jObject = JObject.Parse(Json);
        var children =
            JsonConvert.DeserializeObject<List<EntityChild>>(jObject["Children"].ToString());
        var parents =
            JsonConvert.DeserializeObject<List<EntityParent>>(jObject["Parents"].ToString(),
                new ParentConverter<EntityChild>(children));
    }
}

children are deserialized properly, but parents throw a JsonReaderException when attempting to call JObject.Load(reader); in ReadJson(), saying "Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '[0].EntityChild'."
Does anyone know how I should go about it? Thanks in advance.
Edit: Updated the EntityChild with extra property to emphasize that the property on EntityParent has to be of EntityChild type, and not a string.

A: Entity parent should be as below:
public class EntityParent : IEntity
{
    public string Id { get; }

    public string EntityChild { get; }

    [JsonConstructor]
    public EntityParent(string id, string entityChild)
    {
        Id = id;
        EntityChild = entityChild;
    }
}

And in main() change as below:
var parents = JsonConvert.DeserializeObject<List<EntityParent>>(jObject["Parents"].ToString());

and it works.

A: The following is sort of a workaround using LINQ, where I basically join the parent JObjects with children JObjects to build the parent and the child:
    public static void Main()
    {
        JObject jObject = JObject.Parse(Json);

        IEnumerable<EntityParent> parents =
            from parent in jObject["Parents"]
            join child in jObject["Children"] on parent["EntityChild"] equals child["Id"]
            select
                new EntityParent(
                    parent["Id"].ToString(),
                    new EntityChild(
                        child["Id"].ToString(),
                        child["Age"].ToObject<int>()));
    }

If children list would exist already, then the join could be performed on that list instead, like so:
    public static void Main()
    {
        JObject jObject = JObject.Parse(Json);

        var children =
            JsonConvert.DeserializeObject<List<EntityChild>>(jObject["Children"].ToString());

        IEnumerable<EntityParent> parents =
            from parent in jObject["Parents"]
            join child in children on parent["EntityChild"] equals child.Id
            select new EntityParent(parent["Id"].ToString(), child);
    }


text:
Q: Как Apache Spark будет параллельно(или не) брать и обрабатывать данные? Я решил попытаться разобраться с Apache Spark, и в ходе знакомства с документацией и примерами у меня возник следующий вопрос:
Как спарк будет параллельно(или нет) брать и обрабатывать данные?

*

*В документации существует куча примеров с sc.textFile("example.txt"), но нет примеров с parallelize, получается все это будет обрабатываться в 1 потоке(для каждого spark-submit)?

*Есть примеры с HBase, HDFS, скажите, а как будут браться данные из hdfs, по 1 куску или сразу пачкой(и будут как-то распределятся и суммироваться)? и как всё это будет обрабатываться? параллельно(распределено различными воркерами)?
Что будет в случае использования hbase? а в случае с JDBC(POSTGRES)? Как распределять задания в таком случае?
В дополнение:
Как отправлять данные в spark? я вижу только spark-submit, а существуют ли другие способы и как получить только результат, а не весь мусор?

A: Apache Spark в принципе предназначен для того, чтобы обрабатывать данные распределённо и параллельно. В связи с этим можно сказать, что он всегда старается запускать обработку в параллели, если не сказано другого. Запускать приложение с использованием Spark можно либо с использованием скрипта spark-submit, либо как обычное Java-приложение, используя Spark как библиотеку. В любом случае при запуске необходимо указание параметра master, который определяет где и как будет выполнен код.
Основные варианты для параметра master следующие:

*

*local[*] - запуск кода локально на пользовательской машине, а не на кластере. Если в квадратных скобочках звёздочка - для работы используются все доступные ядра ЦПУ (т.е. происходит работа в параллели). Вместо звёздочки можно указать число - сколько ядер использовать. Если написать просто local - работать будет аналогично local[1], т.е. в один поток без распараллеливания.

*yarn - запуск кода с использованием YARN-кластера. Без предварительного конфигурирования кластера и Spark'а запускается один контейнер для выполнения кода драйвера (процесс, контролирующий выполнение задачи) и два для экзекьюторов, на которых непосредственно обрабатываются данные (т.е. тоже в параллели). Также при запуске spark-submit можно указать параметр --num-executors, где можно точно прописать необходимое количество экзекьюторов.

Теперь же о том, что такое sc.textFile(...) и чем отличается sc.parallelize(...):

*

*sc.textFile(...) - чтение данных из файла (локального или лежащего в HDFS). Принимает в качестве параметра соответствующее имя файла (или папки - в этом случае на вход будут отправлены все файлы внутри указанной папки).

*sc.parallelize(...) просто принимает на вход коллекцию объектов и преобразует её в RDD для последующей обработки.

Эти методы никак не влияют на параллелизм. Однако, есть другие методы, которые действительно могут на это повлиять - repartition и coalesce (подробнее здесь: https://spark.apache.org/docs/latest/rdd-programming-guide.html#transformations).

A: Ну я как бы только изучаю spark, но всё же посоветовал бы разобраться в том как устроен HDFS, YARN. Предположим что файл который храниться в HDFS разбит на 10 частей. И для каждой части, на каждой машине будет создан контейнер куда зальётся рабочий код спарка. Тоесть грубо говоря будет файл обрабатывать в 10 потоках и на разных машинах.
Не скажу точно, но я думаю что метод parallelize в продакшине не используется, и он скорей всего для тестирования, и наглядных примеров.


text:
Q: Reference on (discrete) log-concave probability distributions A discrete distribution $p$ over $\mathbb{N}$ is said to be log-concave if it satisfies the following conditions:

*

*The support of $p$ is a contiguous interval, i.e. $\exists a \leq b$ s.t. $p_i > 0$ iff $a\leq i \leq b$.

*for all $i\in\mathbb{N}$, $p_i^2 \geq p_{i-1}p_{i+1}$.

(in the literature, condition (1) is sometimes forgotten). This is the discrete analogue of continuous log-concave densities, and includes many families of usual discrete distributions.
What I am looking for is a set of lecture notes, papers or more generally references that provides an exhaustive (or as comprehensive as possible) list of theorems and properties of discrete log-concave distributions. As for now, I am aware of Devroye '87 and (part of) An '97, but not much more.

A: There is a very nice 36-page review on log-concavity and unimodality in the discrete setting by Richard Stanley, published in 1989. It is titled "Log-concave and unimodal sequences in algebra, combinatorics, and geometry" and available online here:
http://onlinelibrary.wiley.com/doi/10.1111/j.1749-6632.1989.tb16434.x/abstract
As one might expect from the title, this survey does not focus as much on log-concave probability distributions on the positive integers; however, there are many useful things that one can learn here in any case (imposing the requirement of the sum of the sequence being 1 if necessary).
There is also the notion of ultra-log-concavity (discussed briefly in the Saumard-Wellner survey mentioned in the previous answer); this has beautiful connections not just to probability (where it can be interpreted as relative log-concavity with respect to binomial or Poisson distributions), but also to combinatorics. For recent papers that utilize this notion, see for example:
Kahn and Neiman: "A strong log-concavity property for measures on Boolean algebras", JCT(A), 2011.
and
Nayar and Oleszkiewicz: "Khinchine type inequalities with optimal constants via ultra log-concavity", Positivity, 2012.

A: There is a 67 page review from last year, Log-concavity and strong log-concavity: a review, A. Saumard, J.A. Wellner (2014):

We review and formulate results concerning log-concavity and
  strong-log-concavity in both discrete and continuous settings. We show
  how preservation of log-concavity and strongly log-concavity on $\mathbb{R}$
  under convolution follows from a fundamental monotonicity result of
  Efron (1969). We provide a new proof of Efron's theorem using the
  recent asymmetric Brascamp-Lieb inequality due to Otto and Menz
  (2013). Along the way we review connections between log-concavity and
  other areas of mathematics and statistics, including concentration of
  measure, log-Sobolev inequalities, convex geometry, MCMC algorithms,
  Laplace approximations, and machine learning.

This review contains many references, including some to older reviews and monographs. A few references are listed here, with hyperlinks:

*

*A universal generator for discrete log-concave distributions,
W Hörmann (1994).

*A simple universal generator for continuous and discrete univariate T-concave distributions, J. Leydold (2001).

*Preservation of log-concavity on summation, O. Johnson, C. Goldschmidt (2005).

*Log-concavity and the maximum entropy property of the Poisson
distribution, O. Johnson (2006).

*On the entropy and log-concavity of compound Poisson measures, O. Johnson, I. Kontoyiannis, M.
Madiman (2008).

*Log-concavity, ultra-log-concavity, and a maximum entropy property of discrete
compound Poisson measures, O. Johnson, I. Kontoyiannis, M.
Madiman (2009).

*Strong log-concavity is preserved by convolution, J.A. Wellner
(2010).

*Asymptotics of the discrete log‐concave maximum likelihood estimator
and related applications, F. Balabdaoui, H. Jankowski, K. Rufibach, M. Pavlides, (2011).

A: J Pitman's 1997 article, https://www.stat.berkeley.edu/~pitman/453.pdf, deals with a condition slightly stronger than log concave, PF (Polya frequency), and has a lot of fascinating results and estimates.


text:
Q: How to get device MAC address in Flutter DART? I need to access the MAC address of the device.
I tried many packages like get_mac, mac_address, macadress_gen from pub.dev but always got 02:00:00:00:00:00 as my MAC address, but nothing seems to work.

A: All Android devices return that as the MAC address, to prevent it from being used as a hardware ID.  To get the real id you need the LOCAL_MAC_ADDRESS and ACCESS_FINE_LOCATION permissions


text:
Q: Margin on JTable with 1px border I have JTable inside a JScrollPane inside a JPanel inside a JFrame. Normally the table or the scroll pane have a grey 1px-thick border. To add margin, I learned to use EmptyBorder, but this overrides the old border. Is there a way to keep the grey 1px-thick border and set a margin of 15px?

A: I don't remember if the Border is defined on the tabel or the scrollpane. If you want the 15 pixels between the table and the scrollpane then you can try either of the following approaches:

*

*add the EmptyBorder to the table

*use a CompoundBorder. Use the EmptyBorder as the outer Border and use scrollPane.getBorder() as the inner border.

Or maybe you just want the EmptyBorder on the panel. I can't really tell you exact requirement. Anyway, you have enough information to play around. The trick to it just add the Border to the proper component.

A: Do this:
table.setBorder(BorderFactory.createLineBorder(Color.RED,2));


text:
Q: Creating XML Transform file for MS Access import I need help creating an XSLT transform file for following XML code.
In the end the imported data in access should have following columns:
"Message UID", "Time", "IRCPTACTION", "TRACKERID", "ORCPTS", "DELIVER", "ACCEPT", "TLS_RECEIVED", "SENDER", "SOURCE", "SUBJECT"... and so on.
I tried to create my XSLT file base on some of the examples on this site but since Im pre noob status when it comes to XML I did not get very far.
Can Someone help me build the first part of the XSLT File?
    <message UID="d4622233-f99ff70000003b12-f4-59b0dc8a55f9">
    <events>
        <event time="1504763018" name="IRCPTACTION">Test@test.com|deliver</event>
        <event time="1504763018" name="TRACKERID">Test@test.com|iiiiiddddddd</event>
        <event time="1504763018" name="ORCPTS">Test@test.com</event>
        <event time="1504763019" name="DELIVER">192.168.1.1:25|Test@test.com</event>
        <event time="1504763018" name="ACCEPT">192.168.1.2:33564</event>
        <event time="1504763018" name="TLS_RECEIVED">yes</event>
        <event time="1504763018" name="SENDER">Me</event>
        <event time="1504763018" name="SOURCE">external</event>
        <event time="1504763018" name="SUBJECT">Test Message</event>
        <event time="1504763018" name="MSGID">Message_ID;</event>
        <event time="1504763018" name="MSG_SIZE">2</event>
        <event time="1504763018" name="EHLO">MyServer</event>
        <event time="1504763018" name="LOGICAL_IP">192.168.1.1</event>
        <event time="1504763018" name="FIRED">Test@test.com|none</event>
        <event time="1504763018" name="VERDICT">Test@test.com|none|default</event>
        <event time="1504763018" name="UNTESTED">Test@test.com|has_urls|dz_document|</event>
    </events>
</message>
<message UID="d4622233-f81ff70000003b12-c8-59b0105f670f">
    <events>
                    <event time="1504763018" name="IRCPTACTION">Test@test.com|deliver</event>
        <event time="1504763018" name="TRACKERID">Test@test.com|iiiiiddddddd</event>
        <event time="1504763018" name="ORCPTS">Test@test.com</event>
        <event time="1504763019" name="DELIVER">192.168.1.1:25|Test@test.com</event>
        <event time="1504763018" name="ACCEPT">192.168.1.2:33564</event>
        <event time="1504763018" name="TLS_RECEIVED">yes</event>
        <event time="1504763018" name="SENDER">Me</event>
        <event time="1504763018" name="SOURCE">external</event>
        <event time="1504763018" name="SUBJECT">Test Message</event>
        <event time="1504763018" name="MSGID">Message_ID;</event>
        <event time="1504763018" name="MSG_SIZE">2</event>
        <event time="1504763018" name="EHLO">MyServer</event>
        <event time="1504763018" name="LOGICAL_IP">192.168.1.1</event>
        <event time="1504763018" name="FIRED">Test@test.com|none</event>
        <event time="1504763018" name="VERDICT">Test@test.com|none|default</event>
        <event time="1504763018" name="UNTESTED">Test@test.com|has_urls|dz_document|</event>
    </events>
</message>

A: Simply re-write the <message> and <event> nodes by mapping @name attribute to element name and retaining text. MESSAGE_UID and TIMER run once since it is same for all children.
XSLT (assumes <messages> is the root with no xmlns namespace)
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/messages">
        <xsl:copy>
            <xsl:apply-templates select="message"/>
        </xsl:copy>
    </xsl:template>

    <!-- RE-WRITE MESSSAGE NODE -->
    <xsl:template match="message">
        <xsl:copy>
            <MESSAGE_UID><xsl:value-of select="@UID"/></MESSAGE_UID>
            <TIMER><xsl:value-of select="events/event/@time"/></TIMER>
            <xsl:apply-templates select="events/event"/>
        </xsl:copy>
    </xsl:template>

    <!-- MAP ATTRIBUTE TO NEW NODE NAMES, RETAINING EVENT TEXT -->
    <xsl:template match="events/event">
    <xsl:element name="{@name}">
            <xsl:value-of select="."/>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

Output (flat enough to import into MS Access table)
<?xml version="1.0"?>
<messages>
  <message>
    <MESSAGE_UID>d4622233-f99ff70000003b12-f4-59b0dc8a55f9</MESSAGE_UID>
    <TIMER>1504763018</TIMER>
    <IRCPTACTION>Test@test.com|deliver</IRCPTACTION>
    <TRACKERID>Test@test.com|iiiiiddddddd</TRACKERID>
    <ORCPTS>Test@test.com</ORCPTS>
    <DELIVER>192.168.1.1:25|Test@test.com</DELIVER>
    <ACCEPT>192.168.1.2:33564</ACCEPT>
    <TLS_RECEIVED>yes</TLS_RECEIVED>
    <SENDER>Me</SENDER>
    <SOURCE>external</SOURCE>
    <SUBJECT>Test Message</SUBJECT>
    <MSGID>Message_ID;</MSGID>
    <MSG_SIZE>2</MSG_SIZE>
    <EHLO>MyServer</EHLO>
    <LOGICAL_IP>192.168.1.1</LOGICAL_IP>
    <FIRED>Test@test.com|none</FIRED>
    <VERDICT>Test@test.com|none|default</VERDICT>
    <UNTESTED>Test@test.com|has_urls|dz_document|</UNTESTED>
  </message>
  <message>
    <MESSAGE_UID>d4622233-f81ff70000003b12-c8-59b0105f670f</MESSAGE_UID>
    <TIMER>1504763018</TIMER>
    <IRCPTACTION>Test@test.com|deliver</IRCPTACTION>
    <TRACKERID>Test@test.com|iiiiiddddddd</TRACKERID>
    <ORCPTS>Test@test.com</ORCPTS>
    <DELIVER>192.168.1.1:25|Test@test.com</DELIVER>
    <ACCEPT>192.168.1.2:33564</ACCEPT>
    <TLS_RECEIVED>yes</TLS_RECEIVED>
    <SENDER>Me</SENDER>
    <SOURCE>external</SOURCE>
    <SUBJECT>Test Message</SUBJECT>
    <MSGID>Message_ID;</MSGID>
    <MSG_SIZE>2</MSG_SIZE>
    <EHLO>MyServer</EHLO>
    <LOGICAL_IP>192.168.1.1</LOGICAL_IP>
    <FIRED>Test@test.com|none</FIRED>
    <VERDICT>Test@test.com|none|default</VERDICT>
    <UNTESTED>Test@test.com|has_urls|dz_document|</UNTESTED>
  </message>
</messages>


text:
Q: Ternary operator for multiple conditions in Julia I have Julia code as shown
if cxp1_v1 < cxp1_v2
    d_min = cxp1_v1
    d_max = cxp1_v2
else
    d_min = cxp1_v2
    d_max = cxp1_v1
end

or
if cxp1_v1 < cxp1_v2 d_min, d_max = cxp1_v1, cxp1_v2 else d_min,  d_max  = cxp1_v2, cxp1_v1 end

Is there a way to accomplish this same in the ternary operator? I tried something like as shown
cxp1_v1 < cxp1_v2 ? d_min, d_max = cxp1_v1, cxp1_v2:d_min,  d_max  = cxp1_v2, cxp1_v1

but I get
syntax: colon expected in "?" expression

Stacktrace:
 [1] top-level scope
   @ In[422]:11
 [2] eval
   @ ./boot.jl:373 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1196

A: cxp1_v1 < cxp1_v2 ? (d_min, d_max) = (cxp1_v1, cxp1_v2) : (d_min, d_max) = (cxp1_v2, cxp1_v1)

but I would probably write it as:
d_min, d_max = cxp1_v1 < cxp1_v2 ? (cxp1_v1, cxp1_v2) : (cxp1_v2, cxp1_v1)

since it seems a bit easier to read, or even:
d_min, d_max = minmax(cxp1_v1, cxp1_v2)


text:
Q: UI drawed twice in some apps Some apps (as VLC and most other video players, VirtualBox "New machine" window as shown on the screenshot below) are drawn incorrectly - some elements are drawn multiple times, which makes those applications completely impossible to use.
Except the above, other applications don't have such issues.
Video driver: NVidia
OS: Kubuntu 20.04


text:
Q: Two regex matches with space between the matches I'm trying to match a string with this regex:
The regex:
[ ](\d{4}|\d{4}[A-Za-z]{3})[ ]

NOTE: there might be 3 characters after the numbers, that's why [A-Za-z]{3} is in there.
This is the string I wan't to match in:
281320Z 26015KT 9999 3333 FEW028 SCT033 BKN053 16/10 Q1007=

So in this case it will only select 9999
since there's a space that match1 will reserve.
In this case:
281320Z 26015KT 9999 3333 4444 FEW028 SCT033 BKN053 16/10 Q1007=

9999 and 4444 will be selected.
How can i do so 9999, 3333, 4444 get selected?

A: You could use a regex like this:
\b(\d{4})(?:\b|[A-Z]{3})

Working demo

A: \b(\d{4})(?:[A-Za-z]{3})?\b should do the trick.
(?:) is a non-capturing group, we use it with ? to indicate that its content could appear zero or one time.
Retrieve the four digits by using $1


text:
Q: Can I calculate the geometric mean with django annotation? Is there a way to use it like
Foo.objects.annotate(geometric_mean=GeometricMean('bars__value'))

or
Foo.objects.annotate(geometric_mean=Power(Prod('bars__value'), Count('bars'))

A: You can do something quite similar: you can calculate the average of the natural logarithms:
from django.db.models import Avg
from django.db.models.functions import Ln

Foo.objects.annotate(geometric_mean=Avg(Ln('bars__value')))
then the geometric mean is the exponent of this. If you really need the geometric mean itself, then you can use Exp [Django-doc] on that result:
from django.db.models import Avg
from django.db.models.functions import Exp, Ln

Foo.objects.annotate(geometric_mean=Exp(Avg(Ln('bars__value'))))
but you do not need this if you for example only want to order by two geometric means, since the exponent leaves the order relation intact: ea≤eb implies a≤b and vice versa.
This works because ln(x1×x2×…×xn) is equivalent to ln(x1)+ln(x2)+…+ln(xn), and ln(xy) is equivalent to y×ln(x).


text:
Q: Git Merge only string.xml file New to git! We added Spanish to our product with two developers while the rest of the team went on to add other features. We put the Spanish version into our Development branch and now need to merge in the changes in for everyone else. I wanted to just merge the string tables first and do the rest of the merge in small chunks instead of trying to do it all at once.
I tried:
git checkout develop
git merge OtherBranch res\values\strings.xml

and got the result:
merge: res\values\strings.xml - not something we can merge

Thanks in advance. I know this would just merge my English strings.xml but I should be able to figure it out from here, once I know what I was doing wrong.

A: If the file was never modified on develop, you can simply take the version from OtherBranch :
git checkout develop
git checkout OtherBranch -- res\values\strings.xml
# check your 'git status', and 'git diff --cached' to review the file
# if all is ok :
git commit

note : this does not merge the contents, it completely overwrites the content of strings.xml on develop with the content that is stored in OtherBranch.

If you need to actually merge the file -- eg : changes that were brought to strings.xml on branch develop while otehr people worked on OtherBranch -- you can create a branch which only has the modifications brought to strings.xml :
git checkout OtherBranch
git log -1  # write down the commit ID of current commit

# here is the fork point of develop and OtherBranch :
git merge-base develop OtherBranch
git checkout -b Translations [commit id of fork point]  # give whatever name you want to this branch
git checkout OtherBranch -- res\values\strings.xml
git commit  # just to have a reference somewhere : mention in this commit message
            # that this version comes from OtherBranch, with the commit id you saw
            # at line 2.

# you can now merge Translations into develop :
git checkout develop
git merge Translations

# or cherry-pick the single commit from Translations :
git checkout develop
git cherry-pick Translations


text:
Q: Member plugin - register approval, restrict downloads, members only pages I've seen a few members plugins but was wondering if any of them can do a few things i need.
1) I need two different types of users. One is a standard user another is a Partner. The standard user needs to be able to register without any approval, but the Partners need to have the account approved to ensure they are actually a partner.
2) I have file upload fields on one of my custom post types. I need to only allow registered users to view the files. When someone who isn't logged in clicks on one of the files they get taken to the registration/login page, then when they login they get taken back to the page they were on.
3) Members only pages. There needs to be some pages that only user that are logged in can see and view. So the page isn't even visible in the menu unless the user is logged in. These pages will contain downloads as well for members only. There will be a couple of different sections for members only. Some only for Partners the rest for all members.
Is there any plugin that can do this?
Thanks

A: Your best bet would be the Role Scoper plugin, possibly used in conjunction with Theme My Login.
These two in combination are quite powerful and can greatly add to the CMS aspect of wordpress.


text:
Q: Add an element to existing json in angularJs I have 2 Json object as follows.
var j1={"fname":"XYZ","lname":"qwe"};

and
var j2 = {"id":"10"}

I want to merge j1 and j2
I tried with var ob = angular.merge({},j1,j2);
but its showing angular.merge is not a function
I tried with push and concat. But these also gave same kind of error.
please help,
thank you.

A: If your version of Angular does not support angular.merge yet, you can use angular.extend instead.

angular.module('app', [])
.controller('TestController', ['$scope', function(){
  var j1 = {"fname":"XYZ","lname":"qwe"};
  var j2 = {"id": 10};
  var obj = angular.extend({}, j1, j2);

  console.log(obj);
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="TestController">
</div>

Note: angular.merge is only available from version 1.4 to the latest


text:
Q: Need help understanding a line in tsocks FAQ Over here they explain an error I am getting running tsocks:

I keep getting an error like "SOCKS server is not on a local subnet!",
  what's going on?
By definition SOCKS servers in the tsocks configuration file must be
  on networks specified by a "local" subnet statement. Remember that a
  'local' subnet doesn't describe a subnet that the machine is directly
  attached to but rather networks that the machine can reach without the
  aid of any SOCKS server (thus such networks are "local" networks).
When you think about it, if a SOCKS server were on a network that
  wasn't local then you would need a SOCKS server in order to be able to
  reach the SOCKS server (which can actually occur in some strange
  networks but tsocks doesn't yet support that sort of network).
To fix your problem just define the network your SOCKS server is on in
  a local subnet statement.

The error is the same thing they have mentioned - ... is not on a local subnet!failed: Connection refused.
Can you please explain what is meant by:

To fix your problem just define the network your SOCKS server is on in
  a local subnet statement.

How can I "define" the network my SOCKS server is on in my local subnet ?

A: It sounds like you just need to define the subnet which the server you are trying to connect to lives in as a local subnet in the tsocks.conf file.
From the documentation here: http://linux.die.net/man/5/tsocks.conf

The basic structure of all lines in the configuration file is:
<directive> = <parameters>
...
local
An IP/Subnet pair specifying a network which may be accessed
  directly without proxying through a SOCKS server (e.g "local =
  10.0.0.0/255.0.0.0"). Obviously all SOCKS server IP addresses must be in networks specified as local, otherwise tsocks would need a SOCKS
  server to reach SOCKS servers.

So if you are trying to connect to say 10.10.10.10 then you need a line like one of the below (depending on how wide you want to define your subnet):
local=10.10.10.10/255.255.255.255
local=10.10.10.0/255.255.255.0
local=10.10.0.0/255.255.0.0
local=10.0.0.0/255.0.0.0

Obviously these are just a few of the possible 32 subnet masks you can use :))


text:
Q: Why is the big O of pop() different from pop(0) in python Shouldn't they both be O(1), as popping an element from any location in a Python list involves destroying that list and creating one at a new memory location?

A: Python's list implementation uses a dynamically resized C array under the hood, removing elements usually requires you to move elements following after up to prevent gaps.
list.pop() with no arguments removes the last element. Accessing that element can be done in constant time. There are no elements following so nothing needs to be shifted.
list.pop(0) removes the first element. All remaining elements have to be shifted up one step, so that takes O(n) linear time.

A: To add to Martijn's answer, if you want a datastructure that has constant time pops at both ends, look at collections.deque.


text:
Q: Can I upload the app bundle .aab file as an update of .apk (app signed APK) file? Hello All,
I have gone through the android blog and found that there is two ways for creating the APK file in android:
1. Android App Bundle (.aab)
2. Signed Apk (.apk).
I have gone through the details and found that the size of both the files are different the .aab file size is low compare to .apk file.
Now my question is that my app is live and I use to upload the .apk file for the new update, So can I upload the .aab file this time as new update.
will it work?

A: Yes, it will work with .aab file.


text:
Q: NUnit Unit Test has "ExpectedException" but still failing on exception I have a unit test that is failing because a System.ArgumentException is being thrown, even though I am expecting it and it's deliberate behaviour - what have I missed?
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "Seconds from midnight cannot be more than 86400 in 010100712386401000000012")]
public void TestParsingCustomReferenceWithInValidSecondsFromMidnight()
{
    // I am expecting this method to throw an ArgumentException:
    CustomReference.Parse("010100712386401000000012");
}

I've also tried without the ExpectedMessage being set - no difference.

A: Have you tried the assertion syntax?
Assert.Throws<ArgumentException>(
    () => CustomReference.Parse("010100712386401000000012"),
    "Seconds from midnight cannot be more than 86400 in 010100712386401000000012"
);

A: Is the expected message correct? Is that the exact same message that CustomReference.Parse(string) throws? For example, it is not what is being displayed in the NUnit console.
I wouldn't know another reason why this would not work. What version of NUnit are you using?

A: What happens if you do this?
[TestFixture]
public class CustomReferenceTests
{
    [Test]
    [ExpectedException(typeof(ArgumentException))]
    public void TestParsingCustomReferenceWithInValidSecondsFromMidnight()
    {
        // I am expecting this method to throw an ArgumentException:
        CustomReference.Parse("010100712386401000000012");
    }

    [Test]
    [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Seconds from midnight cannot be more than 86400 in 010100712386401000000012")]
    public void TestParsingCustomReferenceWithInValidSecondsFromMidnightWithExpectedMessage()
    {
        // I am expecting this method to throw an ArgumentException:
        CustomReference.Parse("010100712386401000000012");
    }
}

public class CustomReference
{
    public static void Parse(string s)
    {
        throw new ArgumentException("Seconds from midnight cannot be more than 86400 in 010100712386401000000012");
    }
}


text:
Q: Show that a polynomial of degree 2 is reducible if it has roots. A polynomial $f\in k[x]$ is irreducible if :
1. $\deg(f)\geq 1$
2. If $f=gh$ then $\deg(g)=0$ or $\deg(h)=0$
First of all, this definition confuses me. For example, Let $f=2x^2+2$ and the field be $\mathbb{R}$. By this definition f is irreducible because $f=2(x^2+1)$ and $\deg(2)=0$. Is this correct? I would have thought $f$ is reducible since it can be divided by two..
Anyway, on with the proof:
If $f$ is reducible then $f=gh$ where $g,h\in k[x]$.
There are two cases, either $\deg(g)=\deg(h)=1$ or $\deg(g)=2 \text{ and } \deg(h)=0$. If the first case is true then this implies $f$ has roots. If the second case is true then either $\deg(g)=0 \text{ or } \deg(h)=0$ which would imply that f is irreducible according to the above definition?
Am I missing something or should the second criterion of irreducibility be:
If$~~f=gh \text{ then }\deg(g)=-\infty \text{ or } \deg(h)=-\infty$

A: The second part of the definition has an implied universal quantor: "For all polynomials g and h such that f=g.h, at least one of g or h has degree 0 (i.e., is constant)"
This is really just a definition. A polynomial is irreducible if and only if it cannot be divided by any nonconstant polynomial. Division by a constant such as 2 does not count.

A: It is much simpler to consider  Euclidean division for polynomials: for any $\alpha \in k$, divide $f$ by $x-\alpha$:
$$f(x)=q(x)(x-\alpha) +r$$
Furthermore, $r=f(\alpha)$, hence

$\alpha$ is a root of $f$ if and only if $f(x)$ is divisible by $x-\alpha$.

Thus $f(x) $  has a root if and only if $f(x)$ is divisible by some $x-\alpha$, which implies $f$ is reducible.


text:
Q: Calculating rates Administrators at Massachusetts General Hospital believe that the hospital's
expenditures $E(B)$, measured in dollars, are a function of how many beds $B$ are in use with $$E(B) = 14000 + (B +1)^2$$
On the other hand, the number of beds $B$ is a function of time $t$, measured in days, and is estimated that $$B(t) = 20\sin(\frac{t}{10} )+ 50$$
At what rate are the expenditures decreasing when $t = 100$ ?
I know the answer is $135$ dollars per day but I don't know how to get into that. I'm confused how it is decreasing. When I tried getting $E'(B(t))$ I got approximately $215$ which is wrong. Please help.

A: *

*Substitute the function B(t) for B in the first equation. The result is:
$E(t) = 14000 + (20sin(\frac{t}{10}) + 51)^2  $

*Take the derivative of $E(t)$ using chain rule.
$E'(t) = 4cos(\frac{t}{10})(20sin(\frac{t}{10}) + 51)$

*Evaluate at $t = 100$ and round to receive your answer of $135$.

A: What we want to find is $\frac{d}{dt}E(t)$, so I'll just get rid of the B(t) by substitution... it should be pretty easy here if we just plug in $B(t)$
$$E(t) = 14000 + \left(20\sin(\frac{t}{10} )+ 51\right)^2$$
We now just use the chain rule to simplify this a bit
$$E'(t) = 2\left(20\sin(\frac{t}{10} )+ 51\right)\frac{d}{dt}\left(20\sin(\frac{t}{10}\right)$$
$$= 4\cos\left(\frac{t}{10}\right)\left(20\sin(\frac{t}{10} )+ 51\right)$$
Now we just apply the condition $t=100$
$$E'(100)= 4\cos\left(10\right)\bigg(20\sin(10 )+ 51\bigg)$$
Now we note that $\color{red}{\text{IN DEGREES}}$ this is a little under $\$215$, but we always work in radians in calculus... if we calculate this in radians we get $\color{red}{\approx -134.65}$. This matches our predictions; the slope is decreasing. Since the question asks how fast it is decreasing we take the absolute value to get $\color{red}{\approx 134.65}$


text:
Q: Continuity of $m(E\cap B(x,r))$ with respect to $r.$ I was a little curious about continuity of the lebesgue measure. There was a question about showing that for all $E\subseteq \mathbb{R}$ with $0<m(E)<\infty,$ to show that for all $a\in(0,1)$ there exists $I$ an interval with $m(E\cap I)=am(I)$. I was thinking to by Lebesgue Differentiation choosing a point $x$ with
$$m(E\cap B(x,r))/m(B(x,r))\to 1.$$
Then as $m(E)$ is finite, we can choosing $n$ large we find
$$m(E\cap B(x,r))/m(B(x,r))<a.$$
Now assuming continuity with respect to $r$ the desired result should just be the intermediate value theorem, correct?


text:
Q: angular6 reactive forms chrome autocomplete not setting value in the input box We are using Angular with reactive forms.
On an input box for address if u start typing ex: '7' and select a value from the autocomplete drop down, the selected value is not set and it goes back to the value I typed like '7'.

      Address

    <input type="text" class="profile-info-form__input" formControlName="address" />
    Enter your Address
    Invalid

This doesn't happen if u pick a value on focus of the input field.
Any help on this issue is appreciated

A: just ran into same thing today. for now i had to add autocomplete="nope" on all inputs to get around it ("off" didn't do it ref). interestingly i tried in an older angular 5.2.5 app and didnt seem to have this problem..


text:
Q: I found some misspelling in my Ubuntu calendar My name is Mahdi Vojoudi and Im from Iran .When I choosed persian calendar for my Ubuntu I found some misspelling .I will be so happy if I can help Ubuntu developers
to correct this .I can translate the words from english to persian for making Ubuntu better .

A: If you want to point out only a few mistakes in the Persian translation of the Calendar, filing a bug as karel suggest is the way.
I'm not sure, but I get the impression that you are interested in contributing to the Persian translation of Ubuntu beyond the Calendar. In that case I would recommend that you get in touch with the Ubuntu Persian Translation Reviewers team. They should be able to give you the guidance you need to get started.


text:
Q: Do I actually need to call FileStream.Close/Dispose I see a lot of example code that wraps FileStream use in a using block or calls Dispose() explicitly.
Do I actually need to do this?
In my (possibly simplistic) understanding, C# is a garbage-collected language and when an object goes out of scope, it is flagged for collection. I assume that the garbage collector is smart enough to call Dispose for me on any object that is IDisposable. Is that true?
Furthermore, I understand that GC in C# is non-deterministic and does not happen directly in response to objects going out of scope, for performance reasons. So, if I am opening a million files per second and not Disposing them, I may be creating a lot of file handles. Is this actually a problem?
I could imagine that the garbage collector in C# is fancy enough to GC in response to a program that gobbles system resources like file handles. Even if it didn't, I could imagine that open file handles are basically free in a modern server OS.
So is calling Dispose being pedantic?

A: I think that the dozens or hundreds of existing questions regarding IDisposable do a decent job of covering this question. That said, addressing your specific ones:

*

*"I assume that the garbage collector is smart enough to call Dispose for me on any object that is IDisposable. Is that true?"

Yes and no. Objects which implement IDisposable usually also implement a finalizer. It's that which causes the GC to dispose the object prior to being collected.
Note that there is significant overhead in dealing with the finalizer, overhead which is suppressed if you dispose an object explicitly. That alone is reason enough to justify making sure you dispose objects correctly.

*"I may be creating a lot of file handles. Is this actually a problem?"

Yes, this is actually a problem. Windows has a lot more handle table space now than it used to, but it's still a constrained resource.
Furthermore, the file is still open until the handle is closed. This could prevent other processes from accessing the file when they need to, or could allow the file to be accessed before it's been flushed and so is incompletely written.

*"So is calling Dispose being pedantic?"

No. Calling Dispose() on objects (which you own and know no longer need to be used) implementing IDisposable is an important part of any correct program.

A: If I recall correctly, a using block just allocates an object for the lifetime of whatever is inside the braces. This requires the object being created to implement IDisposable, which was intended to release unmanaged resources.
If you use managed resources, it should (eventually) be cleaned up by the GC and it's your call as to whether to use it or not, but it provides a nice syntactic sugar to deal with unmanaged resources by means of a common interface.


text:
Q: Mount point to access the site's assets I'm developing a Sharepoint Online website, and I'd like to use git's versioning on my CSS/JS/HTML assets.
The ideal solution for me would be to have a mount point pointing to my Sharepoint assets, so that I could even edit them from any computer (without having to use Sharepoint Designer).
And even more ideally, the solution would work on non-Windows system. There seem to be some webdav support in Sharepoint, at least to access Sharepoint's folders and files, but I'm not sure about access to the HTML/CSS of the Sharepoint site itself.

A: I'd just put the assets in a library with versioning enabled along with check out and approval. This gives you version control and the ability to publish changes and see how they look before approving them. Once approved, they are then visible to the rest of the user base.
My experience with WebDAV in SharePoint is abysmal. It is too slow and too chatty to be a worth while tool.


text:
Q: Program recognizes "700" and "70" as 7 I have to input whole numbers and the program has to stop if I put in a negative number. It has to sum up every whole number I've inputed that has a "7" in it, but for some reason, it counts "70" as "7". I'm quite new with programming and I'm stuck on this.
#include <stdio.h>
int main() {
    int number = 1, temp_var = 0, sum = 0;
    while (number >= 0) {
        printf("Put in a number: ");
        scanf_s("%d", &number);
        while (number >= 1) {
            temp_var = number % 10;
            if (temp_var == 7)
            {
                sum = sum + number;
                break;
            }
            number = number / 10;
        }
    }
    printf("%d", sum);
    return 0;
}

A: Your code is incorrect: you modify number in order to test if it has 7 among the digits of its base 10 representation so you do not add the original value if the test succeeds. You should use a separate variable to test the digit values.
The termination test if number is negative works, but is not straightforward for the casual reader.
Here is a modified version:
#include <stdio.h>

int main() {
    int number, temp_number, sum = 0;
    for (;;) {
        printf("Put in a number: ");
        if (scanf("%d", &number) != 1 || number < 0)
            break;
        for (temp_number = number; temp_number; temp_number /= 10) {
            if (temp_number % 10 == 7) {
                sum = sum + number;
                break;
            }
        }
    }
    printf("%d\n", sum);
    return 0;
}

A: You are modifying number then adding that modified value when the least significant digit becomes zero (so 70 adds 7, while 770 or 771 for example  would both add 77).
You should retain the original input value and add that whilst modifying a copy of the original to detect the digit 7.
Alternatively accept a string input, scan it for '7' characters and if so convert to an integer and add it.  For example:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>

int main()
{
    char input[16] = "" ;
    int sum = 0;
    bool got_input = false ;

    do
    {
        got_input = scanf_s( "%s", input, sizeof(input) ) != 0 ;
        for( const char* scan = input;
             got_input && *scan != 0 && isdigit((int)(*scan));
             scan++ )
        {
            if( *scan == '7' )
            {
                sum += atoi( input ) ;
                break ;
            }
        }
    }
    while( got_input && isdigit((int)(*input)) ) ;

    printf("Sum: %d", sum );

    return 0;
}

If the input starts with any non-digit/non-whitespace character the input loop terminates. Trailing non-digit characters in input are ignored.

A: There are some issues:

*

*You are looping on number and it eventually becomes zero.

*When you try to add to the sum, you want the original value of number but you're using the partially modified value.

*You want to preserve the original value and use a temp copy in the loop.

*The while (number >= 0) in the outer loop won't stop immediately if a negative number is executed (i.e. an extra loop iteration is performed). We want to use an if after the scanf_s.

*Because number gets trashed by the inner loop, the outer loop will only execute once.

Here's the refactored code. It is annotated:
#include <stdio.h>

int
main(void)
{
    int number = 1,
        temp_var = 0,
        sum = 0;

// NOTE/BUG: this will loop once too often
#if 0
    while (number >= 0) {
#else
    while (1) {
#endif

        printf("Put in a number: ");
        scanf("%d", &number);
// NOTE/FIX: correct way to stop on negative number
#if 1
        if (number < 0)
            break;
#endif

// NOTE/FIX: to prevent "number" from being trashed, we should use a temp
// value in the loop
        int temp_number = number;

        while (temp_number >= 1) {
            temp_var = temp_number % 10;

            if (temp_var == 7) {
                sum = sum + number;
                break;
            }

            temp_number = temp_number / 10;
        }
    }

    printf("%d\n", sum);

    return 0;
}

In the code above, I used cpp conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif

#if 1
// new code
#endif

Here's a slightly cleaned up version that puts the digit match code in a function:
#include <stdio.h>

// hasdigit -- decide if a given number contains a given decimal digit
int
hasdigit(int number,int dig)
{
    int temp_var;
    int match = 0;

    while (number != 0) {
        temp_var = number % 10;

        match = (temp_var == dig);
        if (match)
            break;

        number = number / 10;
    }

    return match;
}

int
main(void)
{
    int number;
    int sum = 0;

    while (1) {
        printf("Put in a number: ");
        scanf("%d", &number);
        if (number < 0)
            break;

        if (hasdigit(number,7))
            sum += number;
    }

    printf("%d\n", sum);

    return 0;
}


text:
Q: Cast exception in UrlImageViewHelper library, while trying to cast BitmapDrawable I am using the UrlImageViewHelper lib developed by Koushik Dutta (Koush). Here is what I am doing

*

*Load images from a url into imageview which are inside a gridview.

*Image loading works perfectly and is quite fast.

I am trying to save the image loaded inside the imageview, as a wallpaper but it crashes and throws up a casting exception.
The code
UrlViewImageHelper.setURLDrawable(imageView,"some url here");
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

The above line throws this exception
02-26 06:54:07.987: E/AndroidRuntime(19659): java.lang.ClassCastException: com.koushikdutta.urlimageviewhelper.UrlImageViewHelper$ZombieDrawable

How do I get the image inside the imageView as a bitmap? What am I doing wrong?
I understand that I can use some other library such as Android Universal Image Loader (have not tried it yet),SmartImageView (good but slow), but koush's library is quite fast and simple to use.

A: URLViewImageHelper downloads the image in separate thread asynchronously, hence at the point you call imageView.getDrawable(), the image not loaded yet.
What u can try is to register a callback object to be notified when image finished loading:
UrlViewImageHelper.setURLDrawable(imageView,url, defaultResource, new UrlImageViewCallback() {
    @Override
    public void onLoaded(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) {
        // your method here
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

    }
}) ;


text:
Q: How to infer parameter type of a overloaded callback? I'm trying to define a type-safe nodejs-style callback in typescript. I would like to have err defined as Error if present or data as T if not.

*

*If I use this code

export interface SafeCallback<T> {
    (err: unknown): void;
    (err: undefined, data: T): void;
}

const subscribe = <T>(callback: SafeCallback<T>) => {
    let result: T;
    try {
        // result = something
    } catch (e) {
        callback(e);
        return;
    }

    callback(undefined, result);
};

subscribe<{id: string}>((err, data?) => {
    if (!err) {
        console.log(data.id);
    }
});

I get 'data' is of type 'unknown'.

*If I remove the question mark from data I get
Argument of type '(err: undefined, data: { id: string; }) => void' is not assignable to parameter of type 'SafeCallback<{ id: string; }>'
I tried both cases defining err: Error in the first overload but it didn't change anything.
Anything else I should try?
Thanks!

A: with a conditionnal type may be ?
export type SafeCallback<T> = {
    <errorType>(err: errorType, data: errorType extends undefined ? T : null): void;
};

const subscribe = <T>(callback: SafeCallback<T>) => {
    let result: T;
    try {
      // result logic
    } catch (e) {
        callback(e, null);
        return;
    }

    callback(undefined, result);
};

subscribe<{ id: string }>((err, data) => {
    if (data !== null) {
        console.log("data  = " + data.id);
    } else {
        console.log("err = " + err);
    }
});

edit :
just seeing @jcalz reply. Taking something from his response :
export interface SafeCallback3<T> {
    <errorType>(...args:( errorType extends undefined ? [err: undefined, data: T] : [err: errorType] )): void;
}

which prevent to cast error in catch.
const subscribe3 = <T>(callback: SafeCallback3<T>) => {
    let result: T;
        try {
        // ...
        } catch (e) {
            callback(e);
            return;
    }

    callback<undefined>(undefined, result);
};

subscribe3<{ id: string }>((...args) => {
  const [err, data] = args;
  if (!err) {
    console.log(data.id);
  } else {
    err.message
  }
});


text:
Q: Cannot scroll while moving mouse in Ubuntu VirtualBox guest Applications in Ubuntu, such as Chromium or the GNOME Terminal, are not responsive to mouse wheel scroll events when moving the mouse cursor at the same time. I am running Ubuntu 18.04.6 LTS as guest OS using VirtualBox 6.1 with a Windows 10 host.
I am facing the exact same problem, as described in this question. I have tried to apply its accepted solution but it is not working: When running xev | grep -e "ButtonPress" -e "ButtonRelease", I can see that scrolling events are indeed recorded while moving the mouse cursor.
I am also getting the exact same output with xinput:
⎡ Virtual core pointer                          id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ VirtualBox mouse integration              id=9    [slave  pointer  (2)]
⎜   ↳ VirtualBox USB Tablet                     id=10   [slave  pointer  (2)]
⎜   ↳ ImExPS/2 Generic Explorer Mouse           id=12   [slave  pointer  (2)]
⎣ Virtual core keyboard                         id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Sleep Button                              id=7    [slave  keyboard (3)]
    ↳ Video Bus                                 id=8    [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=11   [slave  keyboard (3)]

However, while disabling VirtualBox mouse integration with xinput disable 9, as suggested by the accepted solution, does make my applications more responsive to mouse wheel scroll events, it also has the undesirable side effect of disabling mouse pointer movement altogether (clicking still works though).


text:
Q: Send FB invite to website from iOS/Android app Looks like it's a popular place to get stuck, but nevertheless I've not found an up-to-date solution neither in FB docs nor here.
I need to send invite to FB app that has no Canvas platform from my Android app.

*

*As I can see, sending AppInviteContent through AppInviteDialog is not an option (invite is successfully sent but never reach the
addressee also it works fine if I add Canvas platform to FB app).

*According to https://developers.facebook.com/docs/apps/faq#friend_invite

If your app is not a game and has a mobile or web presence:
  You can also use the Message Dialog on iOS and Android...

But sending ShareLinkContent through MessageDialog doesn't work - canShow() == false for it.
Maybe there is a 3rd approach to do the job (using Android FB SDK)?


text:
Q: Find the variance of a quadratic cost function
Given a beta distribution $f (y)=2 (1-y)$ and $C=10+20Y+4Y^2$, find $\mbox{Var} [C]$.

I already know $\alpha=1$ and $\beta=2$, so $\mu =\frac13$ and $\sigma^2=\frac{1}{18}$.
I also found that $\mathbb{E} (C)=\frac{52}{3}$ using the fact that $\mathbb{E} (aY+b)=a\mathbb{E} (Y)+b$. I tried calculating $\mathbb{E} (C^2)-[\mathbb{E} (C)]^2$ but got stuck because didn't know how to do $E [aY^3]$ or $E [aY^4]$.
Can anyone help? This is problem 4.97 in Wackerly 6th ed, btw.

A: \begin{align}
\mathbb{E}[Y^n]&= \int_0^1 y^nf(y) dy \\
&= 2\int_0^1y^n (1-y) dy \\
&= 2\int_0^1y^n -y^{n+1} dy \\
&= 2 \left[ \frac{1}{n+1}-\frac{1}{n+2}\right]\\
&=\frac{2}{(n+1)(n+2)}
\end{align}
Also use the properties that $\mathbb{E}[aY^n] = a\mathbb{E}[Y^n]$, you should be able to solve the problem.

A: In matrix form,
$$C = \begin{bmatrix} 10\\ 20\\ 4\end{bmatrix}^{\top} \begin{bmatrix} 1\\ Y\\ Y^2\end{bmatrix}$$
It's not hard to show that
$$\begin{array}{rl} \mbox{Var} (C) &= \begin{bmatrix} 10\\ 20\\ 4\end{bmatrix}^{\top} \left( \begin{bmatrix} \mathbb E (1) & \mathbb E (Y) & \mathbb E (Y^2)\\ \mathbb E (Y) & \mathbb E (Y^2) & \mathbb E (Y^3)\\ \mathbb E (Y^2) & \mathbb E (Y^3) & \mathbb E (Y^4)\end{bmatrix} - \begin{bmatrix} \mathbb E (1) & \mathbb E (Y) & \mathbb E (Y^2)\\ \mathbb E (Y) & \mathbb E (Y) \, \mathbb E (Y) & \mathbb E (Y) \, \mathbb E (Y^2)\\ \mathbb E (Y^2) & \mathbb E (Y^2) \, \mathbb E (Y) & \mathbb E (Y^2) \, \mathbb E (Y^2)\end{bmatrix} \right) \begin{bmatrix} 10\\ 20\\ 4\end{bmatrix}\\ &= \begin{bmatrix} 10\\ 20\\ 4\end{bmatrix}^{\top} \begin{bmatrix} 0 & 0 & 0\\ 0 & \mathbb E (Y^2) - \mathbb E (Y) \, \mathbb E (Y) & \mathbb E (Y^3) - \mathbb E (Y) \, \mathbb E (Y^2)\\ 0 & \mathbb E (Y^3) - \mathbb E (Y^2) \, \mathbb E (Y) & \mathbb E (Y^4) - \mathbb E (Y^2) \, \mathbb E (Y^2)\end{bmatrix} \begin{bmatrix} 10\\ 20\\ 4\end{bmatrix}\\ &= \begin{bmatrix} 20\\ 4\end{bmatrix}^{\top} \begin{bmatrix} \mbox{Var} (Y) & \mathbb E (Y^3) - \mathbb E (Y) \, \mathbb E (Y^2)\\ \mathbb E (Y^3) - \mathbb E (Y^2) \, \mathbb E (Y) & \mathbb E (Y^4) - \mathbb E (Y^2) \, \mathbb E (Y^2)\end{bmatrix} \begin{bmatrix} 20\\ 4\end{bmatrix}\\ &= 400 \, \mbox{Var} (Y) + 160 \left( \mathbb E (Y^3) - \mathbb E (Y) \, \mathbb E (Y^2) \right) + 16 \left( \mathbb E (Y^4) - \mathbb E (Y^2) \, \mathbb E (Y^2) \right)\end{array}$$
One can now use Siong's formula for $\mathbb E (Y^n)$ to compute the variance.


text:
Q: Label on top of select moves to background when label and select are disabled in Chrome I have an input and select element with a label on top of it wrapped in a div "container1".
When I disable all the elements of container1, the label on top of the select-element moves to the back. Like the disabled label on the input-element, I want the label to stay on top. Since this happens only in Chrome, I tried different webkits, but nothing seemed to work.
Does anybody know a solution for this isue?
Below the code, you see a printscreen from Chrome with the problem.
You can find the code also on https://jsfiddle.net/JanRo/q4szervh/16/
HTML:
<form>

                Input

                <input type="text" id="name" name="name">

                Select

                <select id="classnow" name="classnow">
                    <option value="" selected></option>
                </select>

            <button onclick="disable()" type="button">Next</button>

</form>

CSS:
* {
  box-sizing: border-box;
  margin-bottom: 0;
  padding: 0;
}

html {
  height: 100%;
  width: 100%;
}

body {
  height: 100%;
  width: 100%;
  padding: 5px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  font-size: small;
}

#container1 > div {
  margin-top: 15px;
}

.question {
  top: 5px;
  position: relative;
  background-color: red;
  margin-left: 10px;
  padding: 6px 6px 6px 6px;
  font-size: small;
  font-weight: bold;
}

input[type=text], select {
  width: 100%;
  height: 35px;
  border: solid 1px black;
  border-radius: 10px;
  padding: 3px 3px 3px 10px;
  font-size: small;
  background-color: white;
}

input[type=text]:disabled, select:disabled {
  outline: none !important;
  width: 100%;
  height: 35px;
  border: solid 1px black;
  border-radius: 10px;
  padding: 3px 3px 3px 10px;
  font-size: small;
}

JS
function disable() {

    var nodes = document.getElementById("container1").getElementsByTagName('*');
    for (var i = 0; i < nodes.length; i++) {
      nodes[i].disabled = true;
    }
}

A: You can add a z-index css property to the div surrounding your labels. you should add a class name to your divs for better control. example below:
div.yourClassName {
 z-index: 5; /* you can set whatever number higher than 0 */
 position: relative;
}

A:  Select

and

            <select id="classnow" name="classnow">
                <option value="" selected></option>
            </select>

Try this it Worked for Me and If it Works Dont Forgot to UpVote


text:
Q: Ребята помогите решить проблему TorSharp Ребята помогите решить проблему у меня очень плохо с C# не судите строго.
Использую библиотеку https://github.com/joelverhagen/TorSharp
public class Program
{
    private static void Main()
    {
        var t = new TestToor();
        Console.WriteLine("Start");
        try
        {
            t.Start();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        Console.WriteLine("End");

        Console.Read();
    }

}

class TestToor
{

    public bool Start()
    {
        VirtualDesktopToolRunner().Wait();
        return true;
    }

    public async Task VirtualDesktopToolRunner()
    {
        var settings = new TorSharpSettings
        {
            TorSocksPort = 9150,
            PrivoxyPort = 8118,
            ExtractedToolsDirectory = @"\bin\ExtractedTools",
            ZippedToolsDirectory = @"\bin\ZippedTools",
            ToolRunnerType = ToolRunnerType.VirtualDesktop
        };

        using (var proxy = new TorSharpProxy(settings))
        {
            await new TorSharpToolFetcher(settings, new HttpClient()).FetchAsync();
            await proxy.ConfigureAndStartAsync();

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://api.ipify.org/?format=json");
            request.Proxy = new WebProxy("127.0.0.1", 8118);

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {

                // Get the stream associated with the response.
                System.IO.Stream receiveStream = response.GetResponseStream();
                // Pipes the stream to a higher level stream reader with the required encoding format.
                StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                var html = readStream.ReadToEnd();
                Console.WriteLine(html);
            }

        }
    }
}

Я так понимаю ошибка и за того что тор не успевает подключится но я так и не нашел пример с ожиданием инициализации всех инструментов.
Помогите примером пожалуйста.


text:
Q: Shift key not working on Windows 7 64-bit HP Compaq Pro 6300 SFF Overnight, on a Windows 7 64-bit HP Compaq Pro 6300 SFF desktop PC, in Word and Excel,

*

*if I press Shift + ' - nothing happens.

*if I do it twice I get 2 quotation marks like this ""

If I'm not looking and just type away I get öther" (and no space even thought I type it) instead of "other" – this is only with some "words"" (see – had to double hit the quotes as first one didn't show and instead I get 2).
Sticky Keys is not on.
Turning Sticky Keys on and off does not resolve this.
Keyboard layout is English (Australian) / US.

A: There was a keyboard icon in the system tray.
Clicking this showed there were two options to choose from:

*

*US

*US (international)

It was set to US (international).
Changing it to US resolved the issue.

A: Several keyboard settings support easy accesws to special keys and accents on letters such as ó à etc.
This is by typing a marker-key, and the the letter. This is especially usefull when typing non-english languages which make a lot more use of accents on letters.
Example: ' followed by a results in á
To solve this you have 2 options:
- switch to a keyboard setting that does not support this option (such as US)
- after pressing a marker key press space. (' [space] a will result in 'a)


text:
Q: How to check for sequential ordering in having clause in HIVE? I want to be able to write a query that will tell me which groups of my data do not have every number in a sequence.
For example, my table loks like this:
Columns:   sequence  group1
           0         ADM
           1         ADM
           0         GDM
           2         GDM
           3         GDM
           0         WJK

And, I want to know which unique values in group1 contain all of the numbers starting at 0 and counting.  So, in this instance, ADM and WJK would get returned, but GDM would not.  GDM would not, because it goes from 0, 2, 3 and skips 1.
How would I write a query in HIVE to tell me which unique values in column group1 contain all integers sequentially?

A: You can use count and max, due the fact that sequence start  form zero
 select group1
 from my_table
 group by group1
 having count(*) = max(sequence) +1

for your last comment then you can use
 select group1
 from my_table
 group by group1
 having count(distinct sequence) = max(sequence) +1

A: SELECT group1
FROM
    TableName
GROUP BY
    group1
HAVING
    COUNT(*) = MAX(sequence) - MIN(sequence) + 1

this works if 0 based or positive integer

A: If sequence can have duplicates, then you need to be careful.  One method is to take a real sequence, subtract it, and be sure the difference is contant:
select group1
from (select t.*,
             (sequence - row_number() over (partition by group1 order by sequence)) as diff
      from t
     ) t
group by group1
having min(diff) = max(diff);


text:
Q: how to grab an element in a string in hive? I have a table called datatable like this:
columnA   columnB
1         1^1^4~3^4^2~4^9^a
2         4^2^2~8^9^a~1^1^1

I want to be able to search the elements of an array and operate on it.  In this case, I need to find the first number before the a in each set between the ~.  So, the output should look like this:
columnA   columnB
1         4
2         8

How do I express this in HIVEQL?  Right now, I know how to split on the ~:
select columnA, split(columnB, '~') from datatable  but...I don't know how to program it to grab the element from group containing "a".  How do I do this?
I'm trying to avoid regular expressions, but I realize they might be needed here....

A: The regular expressions seem to be pretty handy in your case. The one extracting first numbers in an a-featured group is:
(\d+)\^(?:\d+\^)*a

Demo: https://regex101.com/r/rL8gV3/1
And the query would be:
select columnA, regexp_extract(columnB, '(\\d+)\\^(?:\\d+\\^)*a', 1) from datatable


text:
Q: Query latest state based on audit events in Postgres I have the following table with "auditing" events (add,remove, or update):
CREATE TABLE test (
  id INTEGER,
  timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
  action TEXT NOT NULL,
  key TEXT NOT NULL,
  value TEXT
);

INSERT INTO test(id, action, key, value) VALUES (1, 'add',    'name', 'Stack Overflow');
INSERT INTO test(id, action, key, value) VALUES (1, 'add',    'website', 'google.com');
INSERT INTO test(id, action, key, value) VALUES (1, 'update', 'name', 'google');
INSERT INTO test(id, action, key, value) VALUES (1, 'update', 'name', 'Google');
INSERT INTO test(id, action, key, value) VALUES (3, 'add', 'name', 'Facebook');
INSERT INTO test(id, action, key, value) VALUES (2, 'add',    'name', 'Amazon'); // row 5
INSERT INTO test(id, action, key) VALUES (2, 'remove', 'name');
INSERT INTO test(id, action, key, value) VALUES (2, 'add',    'name', 'Oracle');
INSERT INTO test(id, action, key, value) VALUES (1, 'update', 'name', 'Microsoft');
INSERT INTO test(id, action, key, value) VALUES (1, 'update', 'website', 'microsoft.com');
INSERT INTO test(id, action, key) VALUES (3, 'remove', 'name');

Given a timestamp, I need to query the "state" of a config at any point in time.
i.e.,
If I queried the table using the timestamp of row 5, I should get:
id, key       , value
1 , 'name'    , 'Google'
1 , 'website' , 'google.com'
2 , 'name'    , 'Amazon'
3 , 'name'    , 'Facebook'

If I queried with the the current timestamp, I should get:
id, key       , value
1 , 'name'    , 'Microsoft'
1 , 'website' , 'microsoft.com'
2 , 'name'    , 'Oracle'

How can this be achieved in Postgres (using straight SQL preferably)?

A: Without any changes to your table, you can do like this:
select t.id,t.key,t.value from test t,
(select id,key,max(timestamp) ts from test
group by id,key) mx
where t.id = mx.id and t.key=mx.key and t.timestamp = mx.ts
and t.value != 'remove'

But I strongly suggest you to add an autoincremental primary key, so the comparison between tables will be much faster.

A: I would recommend distinct on:
select id, key, value
from (select distinct on (id, key) t.*
      from test t
      where timestamp < current_timestamp
      order by id, key, timestamp desc
     ) t
where action <> 'remove';

I don't know what "row 5" means in your context.  SQL tables represent unordered sets.  There is no "row 5" unless a column specifies the ordering or row number.


text:
Q: Magnific Popup - Scroll using the Ajax popup I know the lightbox gallery you can scroll left and right and view picture after picture but is this possible with the ajax popup? I don't believe you can assign a delegate to allow this functionality.
Examples here.

A: Yep, it's possible with ajax too, you can even mix ajax with another content type.
<button class="link">Click me</button>
<script>
$('.link').magnificPopup({
  items: [
    {
      src: 'ajax-file.html'
    },
    {
      src: 'ajax-file-2.html'
    },
    {
      src: 'http://farm9.staticflickr.com/8379/8588290361_ecf8c27021_b.jpg',
      type: 'image'
    }
  ],
  type: 'ajax',
  gallery: {
    enabled: true
  }
});
</script>


text:
Q: GA - GT Event value not coming through with decimal places For some reason when I gt event values through to analytics it comes through without a decimal place.
They way I track the event is on the site after conversion I use the datalayer to send the amount data via tag manager to the corresponding places.
The amount is a custom variable setup in tag manager and feeds to a few different locations like Bing conversion tracking and Adwords Conversion tracking as well as my goal and event tracking within analytics. What I have noticed though is for some reason in analytics my event values are coming through minus the decimal space.
so for instance if my conv value was 5.68 it comes through as 5 in analytics event value.
Anyone had any similar issues in the past?

A: The workaround here is to set the value in a more granular unit (e.g. cents instead of dollars). In your example you would set the value to 568 instead of 5.68
Warning: value should be exactly Integer, not 568.0 - same events will skipped GA.


text:
Q: update statement in sql returns error must declare scalar variable The following is my code:
        Using myCommand As DbCommand = _Cn.CreateCommand()
            Try
                Dim sql As String = String.Empty
                If Not LUNA.LunaContext.TransactionBox Is Nothing Then myCommand.Transaction = LUNA.LunaContext.TransactionBox.Transaction
                    If cls.UserID = 0 Then
                        sql = "INSERT INTO Tabusers ("
                        sql &= " BenchID,"
                        sql &= " UserType,"
                        sql &= " UserName,"
                        sql &= " Password,"
                        sql &= " Status,"
                        sql &= " LastInTime,"
                        sql &= " LastOutTime"
                        sql &= ") VALUES ("
                        sql &= " @BenchID,"
                        sql &= " @UserType,"
                        sql &= " @UserName,"
                        sql &= " @Password,"
                        sql &= " @Status,"
                        sql &= " @LastInTime,"
                        sql &= " @LastOutTime"
                        sql &= ")"
                    Else
                        sql = "UPDATE Tabusers SET "
                        sql &= "BenchID = @BenchID,"
                        sql &= "UserType = @UserType,"
                        sql &= "UserName = @UserName,"
                        sql &= "Password = @Password,"
                        sql &= "Status = @Status,"
                        sql &= "LastInTime = @LastInTime,"
                        sql &= "LastOutTime = @LastOutTime"
                        sql &= " WHERE UserID= " & cls.UserID
                    End If

                    Dim p As DbParameter = Nothing
                    p = myCommand.CreateParameter
                    p.ParameterName = "@BenchID"
                    p.Value = cls.BenchID
                    myCommand.Parameters.Add(p)

                    p = myCommand.CreateParameter
                    p.ParameterName = "@UserType"
                    p.Value = cls.UserType
                    myCommand.Parameters.Add(p)

                    p = myCommand.CreateParameter
                    p.ParameterName = "@UserName"
                    p.Value = cls.UserName
                    myCommand.Parameters.Add(p)

                    p = myCommand.CreateParameter
                    p.ParameterName = "@Password"
                    p.Value = cls.Password
                    myCommand.Parameters.Add(p)

                    p = myCommand.CreateParameter
                    p.ParameterName = "@Status"
                    p.Value = cls.Status
                    myCommand.Parameters.Add(p)

                    p = myCommand.CreateParameter
                    p.ParameterName = "@LastInTime"
                    p.DbType = DbType.DateTime
                    If cls.LastInTime <> Date.MinValue Then
                        p.Value = cls.LastInTime
                    Else
                        p.Value = DBNull.Value
                    End If
                    myCommand.Parameters.Add(p)

                    p = myCommand.CreateParameter
                    p.ParameterName = "@LastOutTime"
                    p.DbType = DbType.DateTime
                    If cls.LastOutTime <> Date.MinValue Then
                        p.Value = cls.LastOutTime
                    Else
                        p.Value = DBNull.Value
                    End If
                    myCommand.Parameters.Add(p)

                    myCommand.CommandText = sql
                    myCommand.CommandType = CommandType.Text
                    myCommand.ExecuteNonQuery()

                    If cls.UserID = 0 Then
                        Dim IdInserito As Integer = 0
                        sql = "select @@identity"
                        myCommand.CommandText = sql
                        IdInserito = myCommand.ExecuteScalar()
                        cls.UserID = IdInserito
                        Ris = IdInserito
                    Else
                        Ris = cls.UserID
                    End If

                Catch ex As Exception
                    ManageError(ex)
                End Try
            End Using

I am getting the following error:

Must declare the scalar variable "@BenchID".

A: I've done a lot of trail and error and found answer to my trouble.  The answer is SQL server 2008 R2, which I am using, is not supporting named parameters.  That's why the error.
I had to change my code as under:
If cls.UserID = 0 Then
                        sql = "INSERT INTO Tabusers ("
                        sql &= " BenchID,"
                        sql &= " UserType,"
                        sql &= " UserName,"
                        sql &= " Password,"
                        sql &= " Status,"
                        sql &= " LastInTime,"
                        sql &= " LastOutTime"
                        sql &= ") VALUES ("
                        sql &= " ?,"
                        sql &= " ?,"
                        sql &= " ?,"
                        sql &= " ?,"
                        sql &= " ?,"
                        sql &= " ?,"
                        sql &= " ?"
                        sql &= " )"

Then it worked.  Thank you all for your suggestions.


text:
Q: How to move files from one S3 bucket directory to another directory in same bucket? Scala/Java I want to move all files under a directory in my s3 bucket to another directory within the same bucket, using scala.
Here is what I have:
def copyFromInputFilesToArchive(spark: SparkSession) : Unit = {
    val sourcePath = new Path("s3a://path-to-source-directory/")
    val destPath = new Path("s3a:/path-to-destination-directory/")
    val fs = sourcePath.getFileSystem(spark.sparkContext.hadoopConfiguration)
    fs.moveFromLocalFile(sourcePath,destPath)
  }

I get this error:
fs.copyFromLocalFile returns  Wrong FS: s3a:// expected file:///

A: Error explained
The error you are seeing is because the copyFromLocalFile method is really for moving files from a local filesystem to S3. You are trying to "move" files that are already both in S3.
It is important to note that directories don't really exist in Amazon S3 buckets - The folder/file hierarchy you see is really just key-value metadata attached to the file. All file objects are really sitting in the same big, single level container and that filename key is there to give the illusion of files/folders.
To "move" files in a bucket, what you really need to do is update the filename key with the new path which is really just editing object metadata.
How to do a "move" within a bucket with Scala
To accomplish this, you'd need to copy the original object, assign the new metadata to the copy, and then write it back to S3. In practice, you can copy it and save it to the same object which will overwrite the old version, which acts a lot like an update.
Try something like this (from datahackr):
/**
   * Copy object from a key to another in multiparts
   *
   * @param sourceS3Path S3 object key
   * @param targetS3Path S3 object key
   * @param fromBucketName bucket name
   * @param toBucketName bucket name
   */
  @throws(classOf[Exception])
  @throws(classOf[AmazonServiceException])
  def copyMultipart(sourceS3Path: String, targetS3Path: String, fromS3BucketName: String, toS3BucketName: String) {

    // Create a list of ETag objects. You retrieve ETags for each object part uploaded,
    // then, after each individual part has been uploaded, pass the list of ETags to
    // the request to complete the upload.
    var partETags = new ArrayList[PartETag]();

    // Initiate the multipart upload.
    val initRequest = new InitiateMultipartUploadRequest(toS3BucketName, targetS3Path);
    val initResponse = s3client.initiateMultipartUpload(initRequest);

    // Get the object size to track the end of the copy operation.
    var metadataResult = getS3ObjectMetadata(sourceS3Path, fromS3BucketName);
    var objectSize = metadataResult.getContentLength();

    // Copy the object using 50 MB parts.
    val partSize = (50 * 1024 * 1024) * 1L;
    var bytePosition = 0L;
    var partNum = 1;
    var copyResponses = new ArrayList[CopyPartResult]();
    while (bytePosition < objectSize) {
      // The last part might be smaller than partSize, so check to make sure
      // that lastByte isn't beyond the end of the object.
      val lastByte = Math.min(bytePosition + partSize - 1, objectSize - 1);

      // Copy this part.
      val copyRequest = new CopyPartRequest()
        .withSourceBucketName(fromS3BucketName)
        .withSourceKey(sourceS3Path)
        .withDestinationBucketName(toS3BucketName)
        .withDestinationKey(targetS3Path)
        .withUploadId(initResponse.getUploadId())
        .withFirstByte(bytePosition)
        .withLastByte(lastByte)
        .withPartNumber(partNum + 1);
      partNum += 1;
      copyResponses.add(s3client.copyPart(copyRequest));
      bytePosition += partSize;
    }

    // Complete the upload request to concatenate all uploaded parts and make the copied object available.
    val completeRequest = new CompleteMultipartUploadRequest(
      toS3BucketName,
      targetS3Path,
      initResponse.getUploadId(),
      getETags(copyResponses));
    s3client.completeMultipartUpload(completeRequest);
    logger.info("Multipart upload complete.");

  }

  // This is a helper function to construct a list of ETags.
  def getETags(responses: java.util.List[CopyPartResult]): ArrayList[PartETag] = {
    var etags = new ArrayList[PartETag]();
    val it = responses.iterator();
    while (it.hasNext()) {
      val response = it.next();
      etags.add(new PartETag(response.getPartNumber(), response.getETag()));
    }
    return etags;
  }

 def moveObject(sourceS3Path: String, targetS3Path: String, fromBucketName: String, toBucketName: String) {

    logger.info(s"Moving S3 frile from $sourceS3Path ==> $targetS3Path")
    // Get the object size to track the end of the copy operation.
    var metadataResult = getS3ObjectMetadata(sourceS3Path, fromBucketName);
    var objectSize = metadataResult.getContentLength();

    if (objectSize > ALLOWED_OBJECT_SIZE) {
      logger.info("Object size is greater than 1GB. Initiating multipart upload.");
      copyMultipart(sourceS3Path, targetS3Path, fromBucketName, toBucketName);
    } else {
      s3client.copyObject(fromBucketName, sourceS3Path, toBucketName, targetS3Path);
    }
    // Delete source object after successful copy
    s3client.deleteObject(fromS3BucketName, sourceS3Path);
  }

A: You will need the AWS Sdk for this.
If you are using AWS Sdk Version 1,
projectDependencies ++= Seq(
  "com.amazonaws" % "aws-java-sdk-s3" % "1.12.248"
)

import com.amazonaws.services.s3.transfer.{ Copy, TransferManager, TransferManagerBuilder }

val transferManager: TransferManager =
  TransferManagerBuilder.standard().build()

def copyFile(): Unit = {
  val copy: Copy =
    transferManager.copy(
      "source-bucket-name", "source-file-key",
      "destination-bucket-name", "destination-file-key"
    )

  copy.waitForCompletion()
}

If you are using AWS Sdk Version 2
projectDependencies ++= Seq(
  "software.amazon.awssdk" % "s3" % "2.17.219",
  "software.amazon.awssdk" % "s3-transfer-manager" % "2.17.219-PREVIEW"
)

import software.amazon.awssdk.regions.Region
import software.amazon.awssdk.services.s3.model.CopyObjectRequest
import software.amazon.awssdk.transfer.s3.{Copy, CopyRequest, S3ClientConfiguration, S3TransferManager}

// change Region.US_WEST_2 to your required region
// or it might even work without the whole `.region(Region.US_WEST_2)` thing
val s3ClientConfig: S3ClientConfiguration =
    S3ClientConfiguration
      .builder()
      .region(Region.US_WEST_2)
      .build()

val s3TransferManager: S3TransferManager =
   S3TransferManager.builder().s3ClientConfiguration(s3ClientConfig).build()

def copyFile(): Unit = {
  val copyObjectRequest: CopyObjectRequest =
    CopyObjectRequest
      .builder()
      .sourceBucket("source-bucket-name")
      .sourceKey("source-file-key")
      .destinationBucket("destination-bucket-name")
      .destinationKey("destination-file-key")
      .build()

  val copyRequest: CopyRequest =
    CopyRequest
      .builder()
      .copyObjectRequest(copyObjectRequest)
      .build()

  val copy: Copy =
    s3TransferManager.copy(copyRequest)

  copy.completionFuture().get()
}

Keep in mind that you will need the AWS credentials with appropriate permissions for both the source and destination object. For this, You just need to get the credentials and make them available as following environment variables.
export AWS_ACCESS_KEY_ID=your_access_key_id
export AWS_SECRET_ACCESS_KEY=your_secret_access_key
export AWS_SESSION_TOKEN=your_session_token

Also, "source-file-key" and "destination-file-key" should be the full path of the file in the bucket.


text:
Q: Empty constructor of Fragment called instead of newInstance I experience some weird behaviour in an android app I am developing:
I have a class HintsMenu (snippet):
public class HintsMenu extends Fragment implements AbsListView.OnItemClickListener {

...

/**
 * Returns a new instance of this fragment for the given section
 * number.
 */
public static HintsMenu newInstance() {
    System.out.println("HintsMenu.newInstance()");
    HintsMenu fragment = new HintsMenu();
    Bundle args=new Bundle();
    args.putString(ARG_TITLE,"Hints");
    fragment.setArguments(args);
    return fragment;
}

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public HintsMenu() {
    System.out.println("Hintsmenu constructor");
}

This Fragment is dynamically used in an activity:
public class MainActivity extends ActionBarActivity implements MainMenu.NavigationDrawerCallbacks {

....

@Override
public void onNavigationDrawerItemSelected(MenuEntry item) {
    // update the main content by replacing fragments
    if (item.hasActivity()){
        ...
    } else if (item.hasFragment()){
        try {
            FragmentManager fragmentManager = getSupportFragmentManager();
            Class<? extends Fragment> cl=item.getFragmentClass();
            System.out.println("Calling " + cl.getSimpleName() + ".newInstance()...");
            Fragment newFragment=cl.newInstance();
            fragmentManager.beginTransaction().replace(R.id.container, newFragment).commit();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

The idea is, that item.activityClass (code not shown) is set by the expression
item.fragmentClass=HintsMenu.class;

at another position in the code, and item.getFragmentClass() returns this value inside onNavigationDrawerItemSelected().
In "onNavigationDrawerItemSelected", a new HintsMenu is created using the cl.newInstance() call.
However, HintsMenu's newInstance method is NOT called, but the empty Constructor is.
So insted of the expected output
Calling HintsMenu.newInstance()...
HintsMenu.newInstance()
Hintsmenu constructor

I only get
Calling HintsMenu.newInstance()...
Hintsmenu constructor

If i do
HintsMenu.newInstance()

I get the expected output.
Can anyone tell me, what I am doing wrong?

A: The static newInstance() on HintsMenu is not the newInstance() method on Class. You are calling the latter. For example, if you were to rename newInstance() on HintsMenu to be newMenu(), and you changed your onNavigationDrawerItemSelected() implementation to try calling newMenu(), you will get a compile error, as the compiler will complain that it cannot find a newMenu() method on Class.


text:
Q: named starts but doesn't answer until reboot I have a current arch linux arm running on raspberry-pi and bind 9.9.4.P2-1 from the community repository.
I'm using this bind as a slave-nameserver for our internal network.
I have enabled named using systemctl enable named.
When I reboot the raspberry pi the named doesn't answer for dig stackexchange.com @xx.xx.xx.xx and runs into a timeout. systemctl status named says named is active and all zones have been successfully loaded.
 If I simply login and issue systemctl restart named it provides the correct answer for dig stackexchange.com @xx.xx.xx.xx.

A: I solved the problem by editing : /etc/systemd/system/multi-user.target.wants/named.service
Change :
ExecStart=/usr/bin/named -f -u named
To:
ExecStart=/usr/bin/named -f -u root
Of course it's not a very good solution ... but it works for me.


text:
Q: Tesseract training files folder for iOS application Where I should put Tesseract's training data (~34MB) for my iOS application to comply Apple's storage Guideline?
I do not know why but many examples from the Internet copy these files under /Document folder.
Does it comply with the iOS Data Storage Guidelines?
Apple rejected my application twice :
             1) In particular, we found that on launch and/or content download, your
                app  stores 34.4MB. To check how much data your app is storing:

                    - Install and launch your app
                    - Go to Settings > iCloud > Storage & Backup > Manage Storage

            2) Moved training files from /Document to /Library folder :

                  We have found upon downloading the application and launching it,
                  that the storage is 34.4MB.
                  The application should not store over 2MB of data unless user
                  generated. It would be appropriate to revise the content.

Where I should place Tessaract's training files to comply Apple's policy?


text:
Q: Access 2007 VBA Copying Records to Same Table So I have been scratching my head for awhile on this issue and although it seems simple in theory I am having a tough time implementing it in VBA.
Some background on the project will be needed to understand what i am trying to do
So our database/application is meant to keep track of how we test a version of software, what the results are, and if the tests were done properly. we have a specific set of scripts that we use from version to version.
In the database we have a table that list these scripts without assigning them to a specific version of software.
then we have a form where you select the version of software you are running against.
here is the problem i am encountering
when you have selected a software version I want to have a button that you click and it takes all the associated test scripts copies them and assigns the selected software version IF THIS HASNT BEEN DONE YET. this will allow you to make notes for the specific script that can differ from version to version.
I am currently trying to do this with a union query and have experimented with using the append query but haven had any luck, with the code snippet that i am putting below the results i get when i click the button to execute the assigning of the software version it alerts the proper "Test Script", PROC_CHECK_ID and "Software Version" but then i get a strange prompt that sais "Enter Paramater Value" and it sais the "Test Script Name" with a text field, this goes into an infite loop where i can just keep entering values in the text field.
Here is my code
Dim rs1 As DAO.Recordset
Dim unionquery As String

 Dim CURRENT_SOFTWARE_VERSION As String

 CURRENT_SOFTWARE_VERSION = Me.Parent.[Software Version].Value

 unionquery = "select [Test Script] , [PROC_CHECK_ID], [Software Version] from (FORMAL_CERT_PROCEDURE_TEST_SCRIPTS inner join FORMAL_CERT_PROCEDURE_CHECK on FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID = FORMAL_CERT_PROCEDURE_CHECK.TEST_CASE_ID) inner join FORMAL_CERT_SOFTWARE_VERSION on FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID = FORMAL_CERT_SOFTWARE_VERSION.TEST_CASE_ID where PROC_CHECK_ID=" & Me.PROC_CHECK_ID & " AND [Software Version]=""" & CURRENT_SOFTWARE_VERSION & """ "

 ' Debug.Print unionquery

 Set rs1 = CurrentDb.OpenRecordset(unionquery, dbOpenForwardOnly)

 If Not (rs1.EOF And rs1.BOF) Then

    Do Until rs1.EOF = True
        ' MsgBox " " & rs1![Test Script] & ", " & rs1![PROC_CHECK_ID] & ", " & rs1![Software Version] & " "

        INSERT_INTO_TEST_SCRIPTS = "insert into FORMAL_CERT_PROCEDURE_TEST_SCRIPTS([Test Script], [PROC_CHECK_ID_FK], [Software_Version], [TEST_CASE_ID]) values(" & rs1![Test Script] & ", " & rs1!PROC_CHECK_ID & ", " & rs1![Software Version].Value & ", " & Me.TEST_CASE_ID & ")"

        ' APPEND QUERY THAT THROWS INTO AN INFINITE LOOP *NEEDS WORK* INSERT_INTO_TEST_SCRIPTS = "INSERT INTO FORMAL_CERT_PROCEDURE_TEST_SCRIPTS([Test Script], [PROC_CHECK_ID_FK], [Software_Version], [TEST_CASE_ID]) SELECT FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.[Test Script], " & rs1!PROC_CHECK_ID & ",  " & rs1![Software Version].Value & ", FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID FROM FORMAL_CERT_PROCEDURE_TEST_SCRIPTS WHERE FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID = " & Me.TEST_CASE_ID & " "

        DoCmd.SetWarnings False
          DoCmd.RunSQL INSERT_INTO_TEST_SCRIPTS
        DoCmd.SetWarnings True

        rs1.MoveNext
    Loop

 End If

I appreciate any help and am willing to completely rework this mechanic, i am probably over complicating this : /
thanks!

A: Your first SELECT query (unionquery) has quotes around the value for [Software Version], indicating that it is a text field. However, your subsequent INSERT query (INSERT_INTO_TEST_SCRIPTS) omits the quotes. Therefore, the INSERT query is treating the value you are trying to insert as the name of some other field, and since no other field exists with that name you are getting the parameter prompt.
Your code might be a bit cleaner (and more reliable) if you did a Recordset insert instead of "gluing together" an INSERT statement. That approach would look something like this:
Dim rs2 As DAO.Recordset
Set rs2 = CurrentDb.OpenRecordset( _
        "SELECT * FROM FORMAL_CERT_PROCEDURE_TEST_SCRIPTS", _
        dbOpenDynaset)
rs2.AddNew
rs2![Test Script] = rs1![Test Script]
rs2![PROC_CHECK_ID_FK] = rs1!PROC_CHECK_ID
rs2![Software_Version] = rs1![Software Version]
rs2![TEST_CASE_ID] = Me.TEST_CASE_ID
rs2.Update
rs2.Close
Set rs2 = Nothing


text:
Q: how to initialise all the value of an array to zero In cpp imagine if I am writing like
int n;cin>>n;
int a[n]={0};

what I am expecting is that this code will convert all the n elements value to zero but instead, this is giving me the error:

variable sized object may not be initialised

A: For variable array length use

*

*vector<int> a(n, 0); to both allocate and initialize (I explicitly indicate 0 as the initial value but this is the default), that both allows you to resize and also to ask for the size, check the index is valid when you access it etc. This is the more secure and practical way.

*new int[n]; then initialize it with 0, but the array size is constant and you have to know the size is n by yourself when you use it

*or as in C (int *) calloc(n, sizeof(int)) allowing to resize it through realloc, but you still have to know the size when you use it

A: #include <iostream>
#include <algorithm>

int main()
{
    int n = 5;
    int val = 0;

    int arr[n];
    std::fill_n (arr, n, val);
}

Do you need something like this?