text:
Q: array group by part of string and sort by another in postgresql I am trying to sort the following array
'{  job.8.10.2.54, job.8.11*, job.44.89.16.188, job.29292.9, job.8.1, job.8.3, job.8.2}'

as
'{job.29292.9, job.44.89.16.188, job.8.9.2.54, job.8.11*, job.8.3, job.8.2, job.8.1}'

So, the idea would be to group those by their body, aka "the part up to the last dot."
Then order by the last_nb, meaning the part after the last dot ( and ignoring the * )
create or replace function order_array(tasks varchar[])
returns varchar[]

language plpgsql
as $$
declare
new_array varchar[];
task varchar:='';
body varchar='';
last_nb integer;
begin

--store body
task:=tasks[1];

body:= substring(task,'.*(?=\.)\.') ;
last_nb:= substring(task, '([\d]+)\*?$');

raise notice 'body %', body;
raise notice 'last_nb %', last_nb;

new_array:=array_agg(x ORDER  BY substring(x, '([\d]+)\*?$')::INTEGER desc) FROM unnest(tasks) x;

return new_array;

end
$$;

select * from order_array('{job.8.10.2.54, job.8.11*, job.44.89.16.188, job.29292.9, job.8.1, job.8.3, job.8.2}');

Here, I am getting
{job.44.89.16.188,job.8.10.2.54,job.8.11*,job.29292.9,job.8.3,job.8.2,job.8.1}

The sorting seems to be working fine, I also found a way to group with
select array(select unnest(tasks) order by 1) as sorted_arr, count(*) from unnest(tasks) group by sorted_arr into new_array;

How could I combine those too in a single statement?
Thanks!

A: Finally, the solution was not to group, but order by body, then by last_nb
CREATE OR REPLACE FUNCTION sortage(
    tasks VARCHAR[]
)
RETURNS VARCHAR[]
    LANGUAGE plpgsql
AS $$
DECLARE
    regex_body VARCHAR :='.*(?=\.)\.'; -- takes everything up to the last dot
    regex_last_nb VARCHAR :='([\d]+)\*?$'; -- takes everything after the last dot, excluding the *

BEGIN

return  array(SELECT id FROM unnest( tasks ) as id order BY substring(id,regex_body), substring(id, regex_last_nb)::INTEGER desc );

END
$$;


text:
Q: One to Many Mapping to JPA Object with Composite Key I am trying to figure out how to map an entity with a composite key and has an attribute that is part of a composite key on the joining table.
I have SalesOrderNumber on the parent table and 3 attributes on the child table, one of which is SalesOrderNumber.
For the main table (SalesHeader) I am trying to get the SalesOrder entity using the SalesOrderNumber as the joining column so that when I retrieve the SalesHeader, I have a SalesOrder object as well.
Thanks in advance.
Database
SalesHeader Table
ClientKey - PK, int
InvoiceNumber - PK, String
InvoiceBillingDateKey - PK, int
SalesOrderNumber - String, not null

SalesOrder Table
ClientKey - PK, int
SalesOrderNumber - PK, String
SalesOrderCreatedOnDateKey - PK, int

Mappings
SalesHeader JPA Object
@EmbeddedId
    private FactSalesHeaderKey  factSalesHeaderKey;

@OneToOne(fetch=FetchType.EAGER)

@JoinColumn(name = "SalesOrderNumber", referencedColumnName="SalesOrderNumber", nullable=false)

private FactSalesOrder factSalesOrder;  <==== TRYING TO SET THIS

public FactSalesOrder getFactSalesOrder() {
    return factSalesOrder;
}

public void setFactSalesOrder(FactSalesOrder factSalesOrder) {
    this.factSalesOrder = factSalesOrder;
}

SalesOrderKey - Composite PK Object
@Embeddable

    public class FactSalesOrderKey implements Serializable{

        private static final long serialVersionUID = 1L;
        @Column(name="ClientKey")
        private Long  clientKey;
        @Column(name="SalesOrderNumber")
        private String salesOrderNumber;
        @Column(name="SalesOrderCreatedOnDateKey")
        private Long salesOrderCreatedOnDateKey;
    }

SalesOrder - JPA Object
@Entity

    public class FactSalesOrder {

    @EmbeddedId
    private FactSalesOrderKey factSalesOrderKey;
    @Column(name="OverallBillingStatus", nullable = true)
    private Long overallBillingStatus;
    @Column(name="OverallDeliveryStatus", nullable = true)
    private Long overallDeliveryStatus;
    @Column(name="OverallOrderStatus", nullable = true)
    private Long overallOrderStatus;

}

A: *

*Are you asking for One to One or One to Many ? You question title says One to Many but code fragment has One to One annotation. Moreover if you have one to one why would you store them in separate table ? If you have one to many relation then you need a join table.

*Assuming you have one-to-many relation, then you need a set of referenced objects and a mapped by attribute in the table where you put one to many annotation. On other side, you need to put many-to-one annotation and join-columns annotation containing one join-column annotation for each attribute which is part of composite key in referencing table.
public class SalesHeader {
  @EmbeddedId
  private SHKey shKey;
  @OneToMany(mappedBy="salesHeader")
  private Set<SalesOrder> salesOrders;

}

public class SalesOrder {
@EmbeddedId
private SOKey soKey;
@ManyToOne
@JoinColumns({@JoinColumn(name="clientKey",referencedColumnName="clientKey"),@JoinColumn(name="invoiceNumber",referencedColumnName="invoiceNumber"),@JoinColumn(name="invoiceBillingDateKey",referencedColumnName="invoiceBillingDateKey")})
private SalesHeader salesHeader;

}

public class SHKey{
 @Column(name="clientKey")
 private Long clientKey;
 @Column(name="invoiceNumber")
 private String InvoiceNumber;
 @Column(name="invoiceBillingDateKey")
 private Long InvoiceBillingDateKey;
}

Hope it helps.
UPDATE
I think you can not achieve what you are asking this way. It is required to have all the columns of composite key from referenced table into referring table for one-to-one relationship, then only you can define join column(s). In addition to ClientKey and SalesOrderNumber ou need to have SalesOrderCreatedOnDate attribute in SalesHeader table for salesHeader.getSalesOrder() kind of call to work. As you are telling that you don't have liberty of database schema change, for achieving this you can write queries for given salesOrderNumber
Sample code for one-to-one mapping -
  @Entity
  public class SalesHeader implements Serializable {

private static final long serialVersionUID = 1L;

@EmbeddedId
private SHKey shkey;

@OneToOne
@JoinColumns({@JoinColumn(name="clientKey",referencedColumnName="clientKey",updatable = false,insertable = false),@JoinColumn(name="SalesOrderNumber",referencedColumnName="SalesOrderNumber"),@JoinColumn(name="SalesOrderCreatedOnDateKey",referencedColumnName="SalesOrderCreatedOnDateKey",updatable = false,insertable = false)})
private SalesOrder salesOrder;

}

@Entity
public class SalesOrder implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private SOKey sokey;

 }

@Embeddable
public class SHKey implements Serializable {

@Column(name = "clientKey")
private Long clientKey;
@Column(name = "invoiceNumber")
private String InvoiceNumber;
@Column(name = "invoiceBillingDateKey")
private Long InvoiceBillingDateKey;
}

@Embeddable
public class SOKey implements Serializable{

@Column(name = "ClientKey")
private Long clientKey;
@Column(name = "SalesOrderNumber")
private String salesOrderNumber;
@Column(name = "SalesOrderCreatedOnDateKey")
private Long salesOrderCreatedOnDateKey;
}

You can achieve what you are asking for using named queries or criteria API.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is the vuex component isn't updated, despite the state updating? When I load my page, I fetch a list of optboxes items.
Sources
Project's sources are online:

*

*optboxes page ;

*store (store, actions, mutations, getters).

optboxes pages
The HTTP request is well send and return adequate data:
created(){
    this.getOptboxes();
},
components: {
    'optbox': OptboxComponent,
},
methods: {
    getOptboxes() {
        optboxes.all().then((response) => {
            this.setOptboxes(response.data.output);
    }).catch(() = > {
            this.no_optbox_message = 'there is no optbox';
        logging.error(this.$t('optboxes.get.failed'))
    });
    }
},
vuex: {
    actions: { setOptboxes: actions.setOptboxes},
    getters: { optboxesList: getters.retrieveOptboxes}
}

I'm iterating over the results as follow:
<div v-for="optbox in optboxesList" class="panel panel-default">
     <optbox :optbox="optbox"></optbox>
</div>

Store
const state = {
    optboxes: {
        /*
        'akema': {
            hostname: "192.168.2.23",
            id: "akema",
            printers: [
                {
                    description: "bureau",
                    destination_port: 9100,
                    forward: "normal",
                    hostname: "1.2.3.4",
                    id: 0,
                    listening_port: 9102
                }
            ]
        }
        */
    }
};

Question
If I switch to another pages and come back then the list appear. I also notice that with the Vuex extension I can commit the state and see the changes.
Why are my changes not applied automatically?

A: I had to change my data structure due to Change Detection Caveats.

Due to limitations of JavaScript, Vue.js cannot detect the following
  changes to an Array:

*

*When you directly set an item with the index, e.g. vm.items[0] = {};

*When you modify the length of the Array, e.g. vm.items.length = 0.

Store
optboxes is now an array.
const state = {
    optboxes:[]
}

Then update my mutations accordingly to edit the array.

A: Maybe it's an issue of reactivity?! I assume your setOptboxes mutation is not being picked up by vue:
setOptboxes(state, optboxes) {
    for (var optbox of optboxes) {
        state.optboxes[optbox.id] = optbox;
    }
}

You can read about it here:
https://vuejs.org/guide/list.html#Caveats
https://vuejs.org/guide/reactivity.html
The docs solution is to use:
state.optboxes.$set(optbox.id, optbox);

which will trigger a view update.

A: Using Vue.set dit it for me. Take a look here


text:
Q: curl from Write_http plugin of collectd is not working I am trying to enable to Write_http plugin in collectd for Splunk, the problem is when I try to curl externally
curl http://10.xx.xxx.x:8088/services/collector/raw  -H "Authorization: Splunk 2c396ad4-f518-416f-83cd-e37596228792" -d {"test":"value"}

It works. But when I do the same in
 collectd plugin
<Plugin write_http>
<Node "node-http-1">
URL "http://10.xx.xxx.x:8088/services/collector/raw?channel=2c396ad4-f518-416f-83cd-e37596228792"
Header "Authorization: Splunk 2c396ad4-f518-416f-83cd-e37596228792"
Format "JSON"
Metrics true
StoreRates true

I get
[error] write_http plugin: curl_easy_perform failed with status 56: Recv failure: Connection reset by peer

is it because of the curl version of collectd?

A: Just check the port in global settings in http data inputs in splunk.
It must be 8080 by default. Change the port in collect.conf accordingly in write_http plugin.
Hope it works for you!


text:
Q: Complicated alignment within multiline equation I'm having trouble getting the desired alignment behavior in a set of "sets" that I'm typesetting.  I have a bunch of set definitions of the form
$$U = \{\text{$x$ $|$ $x$ satisfies some condition}\}$$

Of course, I want the equals signs to line up, which is easy enough to do with an align* environment.
The problem is that for some of the sets, the "some condition" takes a couple of lines to state.  I'd like like those lines to align after the | symbol.
Of course, if I only had one set to define, then I could do the previous thing with the align* environment.
However, I want to achieve both of the above behaviors in the same set of equations.  How do I do this?
EDIT: After seeing frabjous's answer below, I realized that I didn't emphasize (or even mention) one of the key difficulties.  The U's and x's in my set definition are actually expressions with different lengths, so the second align point in each set definition is different.  This prevents me from using an array environment.  For instance, I could have something like the following:

X = {(p,q) | p=q+7 and something else very long that doesn't fiton one line}
Y(1) = {x | x is prime}
Z' = {(a,b,c) | the variables a, b, and c satisfy a condition thatis too long for one line}.

Sorry for not using tex in the above, but I think it makes it clear what is happening.
Thanks for any help.
EDIT 2: Thanks to Antal S-Z's nice answer, I was able to create a macro that does exactly what I wanted. In case anyone desires the same behavior, here it is.
\newcommand\Set[3]{\ensuremath{\{\text{#1 $|$ \parbox[t]{\widthof{#3}}{#2\}}}}}

You call it with 3 arguments.  To get a set {x|P}, the first argument should be x, the second P (with newlines in it) and the third the longest line in your condition P.  This is compatible with align*, so you can then do things like
\begin{align*}
A &= \Set{x}{P}{Q}\\
B &= \Set{y}{R}{S}
\end{align*}

and it typesets things correctly.

A: I'd do this with an alignat* environment, but just put the text inside a parbox.  That way, you can just align every equals sign and vertical bar; the line breaking will leave the text after the bar in ever case.  This works, but is unfortunately slightly complicated.  The best way to typeset a set comprehension (using etex) is with something like \left\{ x \;\middle|\; \phi \right\}1,2, but apparently you can't put an & between a \left and a \right.  Manual scaling works, though, which gives this solution:
\newcommand{\pctext}[2]{\text{\parbox{#1}{\centering #2}}}
\begin{alignat*}{2}
  X    &= \biggl\{(p,q)   &&\;\bigg|\; \pctext{1.5in}{$p=q+7$ and something else
                                                      very long}\biggr\} \\
  Y(1) &= \{x             &&\;|\;      \pctext{1.5in}{$x$ is prime}\} \\
  Z'   &= \Biggl\{(a,b,c) &&\;\Bigg|\; \pctext{1.5in}{the variables $a$, $b$,
                                                      and $c$ satisfy a
                                                      condition that is too long
                                                      for one line}\Biggr\} \\
\end{alignat*}

This gives the following output:

As you can see, this does work, though I think it's not ideal.  There are some spacing issues (which I'm not sure how to fix, or even what best to do) stemming from the differing sizes of the braces.  And the code's a bit cluttered; one could probably write a macro to abstract some of the boilerplate, but enclosing & in macros with align and friends tends to be problematic.

1: Actually, I typically use the braket package to write \Set{x | \phi}, but it uses \left and \right (and \middle if it can) under the hood.
2: Since it's assumed that | is a delimiter here, it's not spaced out, and so we use \;s to get the spacing right.  If we use a relation such as \mid, we get the same (I think) spacing, but we can't \middle it.

A: You could use an array environment (or perhaps alignat). Something like:
 \documentclass{article}
 \usepackage{amsmath}
 \begin{document}
 \[
 \begin{array}{r@{\,}l@{\,}l}
 U &= x \mid &x \text{ satisfies some condition that}\\
   &         &\text{takes a long long time to state}\\
 V &= y \mid &y \text{ satisfies something else}
 \end{array}
 \]
 \end{document}

It's also possible you really should use a cases environment for conditional definitions.
Note: you should not use $$ ... $$ for displayed math. It is considered obsolete. For further explanation, see l2tabu.


text:
Q: iptables doesn't redirect http traffic to my Squid proxy! I arranged a transparent Squid proxy which listens to port 3128 on localhost, to block some web sites.
I've tested the proxy using Firefox, and it works.
Then I ran this, hoping to redirect all the http requests to the proxy:
sudo iptables -t nat -A PREROUTING -p tcp -j REDIRECT --to-ports 3128

Sadly, nothing happens. The other browsers in my system don't seem to be using the proxy. I don't want to configure each browser, to use the proxy either.
sudo iptables -L shows no rules assigned.
I'm on Ubuntu 13.04, and using a 3G USB modem (ppp0) to connect to the Internet. Any advice is appreciated!

A: I think you are missing the destination port, try following
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 3128

Without dport, you are forwarding traffic with destination port 3128 to local port 3128. What you want is traffic with destination port 80 forward to local port 3128.
Additionally, to show nat rules, use
iptables -t nat -L

However, the above rules will not work for a transparent proxy setup on the same machine of the browser, because PREROUTING chain alters packges before routing from a remote client and it will not do anything for locally generated packets. Thus we should use OUTPUT chain for packets locally generated which are going out from the system.
Try following instead
iptables -t nat -A OUTPUT -p tcp -m owner ! --uid-owner proxy --dport 80 -j REDIRECT --to-port 3128

It will only redirect traffic for processes other than the ones owned by proxy user.
Without -m owner ! --uid-owner proxy, it will not work because the rules will also caught the proxy server outgoing traffic and end up in a loop.


text:
Q: Setting textbox text value on button click I have a from in PowerApps with labels and textboxes. By default textboxes are empty. There is a Button named "Copy last row" when use will click on this button some sample values should be displayed in textboxes.
I checked on internet and the following solution was suggested by PowerApp support.
You need to set the text box' text property to this:
 If(HasBeenPressed, "Hello", "GoodBye")

You also need to set the button's onselect property to this:
UpdateContext({HasBeenPressed: true})

or for more fun,
UpdateContext({HasBeenPressed: !HasBeenPressed})

But when I go to the properties of my textbox there is no such property like 'TEXT'.

A: What do you mean by textbox? a label or a text-input?
Anyways, Label has a text property:

Text-input has a default property

I'm afraid u can't change the text directly. What u can do is create a context variable in the property "OnVisible" of your screen and give the default text you want your labels to have in the first place, or leave the variable in blank since you want them to have no text:
On visible context variable

Then, set the text property of your label to be the value inside the variable

Or the default property of your text-input

Last but not least, set the OnSelect property of your button to change the value of your variable:

This is the result:

Hope this helps!

A: Adding clarifications on top of Bruno's demonstrating answer.
In Canvas PowerApps, both Label & Text input controls have the Text property.
But Text is Output only property for Text input control whereas for Label its of both type ie. input and output property. People (bloggers/trainers) often mix these controls & properties.

Text is an Output property on that control, to be consumed by other controls. You can't set it manually as it is not an Input property. The Default property determines its initial content.

by PowerApps staff on PowerApps forum


text:
Q: Is visualising centripetal acceleration, as pulling the rotating body towards the centre, correct? Centripetal force would literally mean 'the centre-seeking force'. So in order to bring a body towards the centre it turns it and the body is always trying to reach the centre however is unable to reach it and ends up rotating. Is this way of describing circular motion-rotation about a fixed axis correct? Also is it that a rotating body would feel an inward pull towards the centre? Why or why not?
[Here: rotation could be like any of Earth's two circular motions of rotation about its axis and revolution about Sun]

A: For a mass moving along a curve, there must be an applied force which is causing it to accelerate toward the center of curvature.

A: Yes, it was correct to visualise a centripetal force as one that pulls a moving body towards the centre of curvature of the body's path of motion.
In your second question you talk about a rotating body. Are you clear about the different between rotation and circular motion? A body in circular motion must experience a force directed towards the centre of the circle- if there is no component of force towards the centre, then the body will continue in a straight line tangentially.


text:
Q: custom theme for wordpress new page I created a custom theme for word-press. When i say 'add new' page and i put content into this page it only displays the footer and header but dosnt hook my content which is in the CMS on that page.
This is what i have : page.php
<?php get_header(); ?>

        <?php
            if ( have_posts() ) : while ( have_posts() ) : the_post();

                get_template_part( 'content', get_post_format() );

            endwhile; endif;
        ?>

<?php get_footer(); ?>

Its been a long day what am i doing wrong here. Any tips please?
Would also like to make like a parent page from this new page, but its only option with page attributes are 'default template'.

A: If you didn't have a template part please use the_content() instead of
get_template_part( 'content', get_post_format() );

A: My actual problem, resolved. So i used 'advanced custom field' plugin for my WordPress. The problem using this is that it still requires you to do some coding.
I added a new page.
For that page I had an header image and content. So for ACF(advanced custom field) that is equal to two field types "Image --> field type and Text-Area --> field type"
Field name is what i used to call the fields to my .php page template.
Field Name : Image = header-image
Field Name : (2)Text Area = header-image-text-top (and) header-image-text-author
(I needed to display my text on the image thats why my div is just based on header image.)
So I hooked my page template and then added the the hooks for the fields i want to display on this page template.
page-stay.php :
  <?php
    /*Template Name: Stay - Parent Page */
   get_header(); ?>

    <?php
    // Start the loop.
    while ( have_posts() ) : the_post(); ?>

    <article id="post=<?php the_ID(); ?>" <?php post_class(); ?>>

        <?php
        $image = get_field('header-image');

            if( !empty($image) ): ?>

            <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

<?php the_field('header-image-text-top'); ?>

<?php the_field('header-image-text-bottom'); ?>

        <?php endif; ?>

    <?php endwhile; ?>

<?php get_footer(); ?>


text:
Q: Non-linear regressions with caret package in R I'm new using R and my doubt is really basic.
I have several dependent variables (x) and one independent variable (y), and I'd like to generate different regression models with 10-folds-cross-validation in order to select the better one. All my values are numerical.
They recommended me to use Caret package and I made some tests. I had no troubles using linear regressions (lm or glm) but when I use other regressions like logreg I have an error.
What I introduce is:
 Datos_AGB <- read.table("plotstatistics.txt",header=TRUE)
 ctrl <- trainControl(method = "repeatedcv", number = 10, repeats = 10)
 modelFit <- train(AGB~HOMEmean+WDmean, data=Datos_AGB, method = 'logreg', trControl=ctrl)

And I receive this error:
Something is wrong; all the RMSE metric values are missing:
>       RMSE        Rsquared    Min.   : NA   Min.   : NA    1st Qu.: NA   1st Qu.: NA    Median : NA   Median : NA    Mean   :NaN   Mean   :NaN
> 3rd Qu.: NA   3rd Qu.: NA    Max.   : NA   Max.   : NA    NA's   :9
> NA's   :9     Error in train.default(x, y, weights = w, ...) :
> Stopping 50: In eval(expr, envir, enclos) :   model fit failed for
> Fold06.Rep01: ntrees=3, treesize= 8 Error in logreg(resp = y, bin = x,
> ntrees = param$ntrees, tree.control = logreg.tree.control(treesize =
> param$treesize),  :    some non binary data among binary predictors

I don't know if I have to introduce other parameters or to do some steps before.
I'd like that someone explained me how to solve this and how to get non-linear regressions.

A:
All my values are numerical

That's the issue. Note the error message

some non binary data among binary predictors

logreg requires binary predictors.
Max


text:
Q: kubernetes certmanager letsencrypt giving error "Your connection is not private" I set up a cluster issuer, certificate, and ingress under my Kubernetes environment and everything is working fine as per status, but when I am connecting to the host as per my ingress, it's giving me  "Your connection is not private".
CluserterIssuer output lastlines;-
...
Conditions:
    Last Transition Time:  2020-02-16T10:21:24Z
    Message:               The ACME account was registered with the ACME server
    Reason:                ACMEAccountRegistered
    Status:                True
    Type:                  Ready
Events:                    <none>

Certificate output last lines :-
Status:
  Conditions:
    Last Transition Time:  2020-02-16T10:24:06Z
    Message:               Certificate is up to date and has not expired
    Reason:                Ready
    Status:                True
    Type:                  Ready
  Not After:               2020-05-14T09:24:05Z
Events:                    <none>

Ingress file:-
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
   name: b1-ingress  # change me
   namespace: b1
   annotations:
    kubernetes.io/ingress.class: "nginx"
    kubernetes.io/tls-acme: "true"
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:
  tls:
  - hosts:
     - '*.testing.example.com'
    secretName: acme-crt
  rules:
  - host: flower.testing.example.com
    http:
      paths:
      - backend:
          serviceName: flower-service
          servicePort: 5555

  - host: hasura.testing.example.com
    http:
      paths:
      - backend:
          serviceName: hasura-service
          servicePort: 80

A: Based on cert menager documentation

certmanager.k8s.io/issuer - The Issuer must be in the same namespace as the Ingress resource.

As @me25 confirmed in comments

yes everything worked when I copied secret in to namespace: b1 – me25

The answer here was missing secret certificate in proper namespace.
The solution was to copy secret certificate to namespace: b1,same as the ingress.

Do you know any better way other than a copy secrets

This stackoverflow post provide few tricks about copying secret from one namespace to other.

Additional links:

*

*https://itnext.io/automated-tls-with-cert-manager-and-letsencrypt-for-kubernetes-7daaa5e0cae4

*https://cert-manager.io/docs/tutorials/acme/ingress/

A: nginx server is using self-signed certificates and chrome does not trust that. usually when u click on "Advanced" tab, you should have an option that says "trust this website" or something like that and nginx server config does not show that. the solution is just type this on the keyword :
"thisisunsafe"

and error message will gone


text:
Q: Need to create a NSDecimalNumber with 2 decimal places to store in Core Data but last decimal (0) is being cut I am trying to create a NSDecimalNumber to store a currency value in Core Data based in a string that contains the value 11.90. I want to keep the 2 decimals but the 0 is being ignored and it always turns 11.9 as NSDecimalNumber. I tried to use the Behavior protocol rounding and add the scale but it didn't work for me.
Is it working as designed and should I just use a formatter to add the 0 when retrieving the 11.9 from Core Data or is there any step I'm missing ?
Thanks.
    NSDecimalNumberHandler *behavior = [[NSDecimalNumberHandler alloc] initWithRoundingMode:NSRoundPlain
                                                                                scale:2
                                                                                raiseOnExactness:NO
                                                                                raiseOnOverflow:NO
                                                                                raiseOnUnderflow:NO
                                                                                raiseOnDivideByZero:NO];

    [NSDecimalNumber setDefaultBehavior:behavior];

    NSDecimalNumber *priceDecimal;

    NSDictionary *locale = [NSDictionary dictionaryWithObject:currentLocaleSeparator forKey:NSLocaleDecimalSeparator];
    priceDecimal = [NSDecimalNumber decimalNumberWithString:price locale:locale];
    priceDecimal = [priceDecimal decimalNumberByRoundingAccordingToBehavior:behavior];

A: Right, the formatter is the right approach. You have to distinguish between the precision of the decimal number being stored, which seems to be working fine, and its representation or formatting.
I have made lots of apps with currencies - I have always found that it is easier and more convenient to simply count the cents (or hundreds unit) using 64 bit Integers.
Check out NSNumberFormatter's minimumFractionDigits.


text:
Q: Post controller require post In an article, a Post controller is created.
But in post_params, params.require requires :post. How this possible or What does it mean that Post controller requires :post
def create
  Post.create(post_params)
  redirect_to root_path
end
private
def post_params
  params.require(:post).permit(:description, :image, :user_id)
end

A: it's a way Rails Controlling mass-assigment attributes with strong_parameters. this approach forbids mass-assignment of a model attribute from a controller unless that attribute was white-listed
whitelisting is configured using two methos

*

*require, calling require will validate that the parameter is actually present, if not present it will throw an error

*permit, calling permit with list of attributes will enable those attributes to "pass through" to model during mass-assignment (this restriction disable code injection by passing unpermitted objects, hashes etc)

from your sample above
params.require(:post).permit(:description, :image)

meaning an instance of post must exist in params and keys/column that allowed to pass through only description and image, if your form passing other field for example :other_description and it's not listed in permit, it will not be saved

A: The class name :post is required because the controller expects that the parameters are arranged hierarchically under their class names, as one single POST request can yield parameters pertaining to many classes. For example your post description will be available as
params[:post][:description]

In development, it's sometimes useful to inspect the parameters in the browser window. You could use this simple code:
<% if !Rails.env.production? %>
  <%= debug(params) %>
<% end %>


text:
Q: How to delete rows in Table1 where COUNT of WHERE in Table2 is greater than 0? I have [Table1] with user ID and [Table2] with the same user ID (left join) and column "open" with number of readed messages. I want to delete all users from [Table1] which has all rows in [Table2] with "open" column value < 1. I trying to select them first, but it gives SQL errors:
Trying 1:
SELECT pg_acymailing_subscriber.*,
       COUNT(DISTINCT case when pg_acymailing_userstats.open > 0 end) as readc
LEFT JOIN `pg_acymailing_userstats`
    ON pg_acymailing_subscriber.subid=pg_acymailing_userstats.subid
WHERE pg_acymailing_subscriber.subid=24 AND readc > 0;

Trying 2:
SELECT *
FROM `pg_acymailing_subscriber`
LEFT JOIN `pg_acymailing_userstats`
    ON pg_acymailing_subscriber.subid=pg_acymailing_userstats.subid
WHERE COUNT(DISTINCT case when pg_acymailing_userstats.open > 0 /*If user doesn't have rows with "open" column value > 0, we select it if whole rows numer is 0*/
                     end) < 1
  and pg_acymailing_subscriber.subid=24;

A: If performance is not an issue, it's probably easiest to build this with a subquery.
My understanding of your logic is that you want to delete all users from [Table1] that do not have any rows in [Table2] where open > 0, is that a correct paraphrasing of your requirement?

select * from pg_acymailing_subscriber where subid not in
( select subid from pg_acymailing_userstats where open > 0 )

If that shows the correct records, delete as follows:

delete from pg_acymailing_subscriber where subid not in
( select subid from pg_acymailing_userstats where open > 0 )

A: If you want to filter on results of aggregate functions you need GROUP BY and HAVING clauses, like e.g.
SELECT pg_acymailing_subscriber.userid,
       COUNT(DISTINCT case when pg_acymailing_userstats.open > 0 end) as readc
FROM `pg_acymailing_subscriber`
LEFT JOIN `pg_acymailing_userstats`
    ON pg_acymailing_subscriber.subid=pg_acymailing_userstats.subid
WHERE pg_acymailing_subscriber.subid=24
GROUP BY pg_acymailing_subscriber.userid
HAVING readc > 0;

I guessed that the user ID column is called userid. I might not have the quoting correct, but that's easy to repair.
And the HAVING readc > 0 might or might not be correct syntax in mysql.
If it's not, you write HAVING COUNT(DISTINCT case when pg_acymailing_userstats.open > 0 end) > 0

A: If i understand correctly you questio you want delete the rows in table1 related to id in table2 whit  the sum of all open message is < 1
this should be the select
  select table1.userID
  from table1
  inner  join table2 on table1.userID = table2.userID
  group by table1.userID
  havine sum(open)<1

and then you could use a delete like
  detele
  from table1
  inner  join table2 on table1.userID = table2.userID
  group by table1.userID
  havine sum(open)<1


text:
Q: p-point ultrafilters on a countable linear order Suppose that $(P,\leq)$ is a countably infinite linear ordering, and $U$ is a p-point ultrafilter on $P$. Show that there is an $X\in U$ such that $X$ has order type $\omega$ or $\omega^*$. (This is Exercise 7.8 in Jech)
I know that if $U=\{P\}$, or if $U$ is Ramsey, then this is true; enumerate $P=\{a_n\}_{n\in\omega}$ and color pairs $\{m,n\}$ according to whether or not their order in $\omega$ agrees with the order of $\{a_m,a_n\}$. But if $U$ is a p-point, I don't see how to adapt this argument.
(Edit) A definition: $U$ is a p-point ultrafilter on a countably infinite set $P$ if it is non-principle and for every partition $\{A_n:n\in\omega\}$ of $P$ into $\aleph_0$ many pieces such that $A_n\notin U$ for all $n$, there is an $X\in U$ such that $X\cap A_n$ is finite for all $n$.

A: We shall make use of the following facts:

*

*If $U$ is an ultrafilter and $X\cup Y\in U$, then $X\in U$ or $Y\in U$.

*(Exercise $7.7$ of Jech's Set Theory)If $D$ is a $p$-point on $\omega$, then for any decreasing sequence $A_0\supset A_1\supset \cdots \supset A_n\supset \cdots$ of elements of $D$, there exists $X\in D$ such that for each $n\in \mathbb N$, $X-A_n$ is finite.

With no loss of generality we may assume that $P\subseteq \mathbb Q$ and $<=<^{\mathbb Q}\cap P\times P$, and furthermore we may assume $P$ is bounded in $(\mathbb Q,<)$; $P\subseteq [a,b]$ for some $a,b\in \mathbb Q$.
Let $D$ be a $p$-point on $P$.
By fact $(1)$ we have that $[a,\frac{a+b}{2}]\cap P\in D$ or $[\frac{a+b}{2},b]\cap P\in D$, let $[a_1,b_1]$ be one of these half-intervals such that $[a_1,b_1]\cap P\in D$.
Continuing this process we get a shrinking sequence of nested intervals $\{ [a_k,b_k]\}_{k\in \mathbb N}$; with $[a_o,b_0]=[a,b]$, such that $b_k-a_k=\frac{b-a}{2^k}$ and $[a_k,b_k]\cap P\in D$ for all $k\in \mathbb N$
By fact $(2)$ there exists $X\in D$ such that $X-([a_k,b_k]\cap P)$ is finite for all $k\in \mathbb N$. Let $r\in \mathbb R$ be such that $r\in \bigcap_{k\in \mathbb N}[a_k,b_k]$, then either $[a,r]\cap P\in D$ or $[r,b]\cap P\in D$.
If $[a,r]\cap P\in D$, then $[a,r]\cap P\cap X\in D$, and hence since $D$ is nonprincipal, $[a,r]\cap P\cap X$ is infinite, but $a_k\rightarrow r$ as $k\rightarrow \infty$ then $X\cap  P\cap [a,r]$ is a discrete infinite linear ordering, since $X-[a_k,b_k]$ is finite for all $k$, since $X\cap P\cap [a_k,b_k]\neq \emptyset $ for all sufficiently large $k$; otherwise $[a,r]\cap P\cap X$ would be finite, and since the intersection of the nested intervals is $\{ r\}$, the order-type of $[a,r)\cap P\cap X$ must be $\omega$, but since $D$ is non-principal $[a,r)\cap P\cap X\in D$.
Similarly if $[r,b]\cap P \in D$, the order-type of $(r,b]\cap X$ must be $\omega^*$, and $(r,b]\cap X\in D$. Since one of this cases must hold by fact $(1)$, we are done.

A: I'm going to call the ultrafilter $\mathscr{U}$. Let $P_0=P\in\mathscr{U}$. Given $P_\xi\in\mathscr{U}$ for some $n\in\omega$, choose a non-endpoint $p_\xi\in P_\xi$. Exactly one of the sets $\{p\in P_\xi:p<p_\xi\}$ and $\{p\in P_\xi:p_\xi\le p\}$ belongs to $\mathscr{U}$; let it be $P_{\xi+1}$. If $\eta$ is a limit ordinal, $P_\xi$ has been constructed for each $\xi<\eta$, let $P_\eta=\bigcap_{\xi<\eta}P_\xi$. If $P_\eta\in\mathscr{U}$, continue the construction; otherwise, stop.
Since $P$ is countable, there must be a countable limit ordinal $\eta$ such that $P_\eta\notin\mathscr{U}$. For $\xi<\eta$ let $D_\xi=P_\xi\setminus P_{\xi+1}\notin\mathscr{U}$, and note that $\bigcup_{\xi<\eta}D_\xi=P\setminus P_\eta\in\mathscr{U}$, while each $D_\xi\notin\mathscr{U}$. Moreover, the sets $D_\xi$ are order-convex and pairwise disjoint, so the linear order on $P$ induces a natural linear order on $\mathscr{D}=\{D_\xi:\xi<\eta\}$. Each $D_\xi$ is either the left or the right end of the corresponding $P_\xi$; let $L=\{\xi<\eta:D_\xi\text{ is the left end of }P_\xi\}$, and let $R=\eta\setminus L$. Then exactly one of $\bigcup_{\xi\in L}D_\xi$ and $\bigcup_{\xi\in R}D_\xi$ belongs to $\mathscr{U}$; without loss of generality assume that $\bigcup_{\xi\in L}D_\xi\in\mathscr{U}$.
Let $L=\{\lambda_\xi:\xi<\alpha\}$ be an increasing enumeration of $L$, and let $\beta$ be minimal such that $\bigcup_{\xi<\beta}D_{\lambda_\xi}\in\mathscr{U}$; clearly $\beta$ is a limit ordinal, so there is a strictly increasing sequence $\langle\beta_n:n\in\omega\rangle$ of ordinals such that $\beta_0=\lambda_0$ and $\beta=\sup_n\beta_n$. For $n\in\omega$ let $E_n=\bigcup\{D_{\lambda_\xi}:\beta_n\le\lambda_\xi<\beta_{n+1}\}$; then $\bigcup_nE_n\in\mathscr{U}$, but $E_n\notin\mathscr{U}$ for $n\in\omega$, so there is a $U\in\mathscr{U}$ such that $U\subseteq\bigcup_nE_n$ and $U\cap E_n$ is finite for each $n\in\omega$. The construction then ensures that the order-type of $U$ as a subset of $P$ is $\omega$. (Had $\bigcup_{\xi\in R}D_\xi$ been a member of $\mathscr{U}$, we would instead have got a member of $\mathscr{U}$ of type $\omega^*$.)


text:
Q: AWS Glue ETL Job getting final dataFrame with Join.apply Vs SQL JOIN Query I am fairly new to AWS and I am currently exploring it. I was hoping to get an insight or suggestion on the best way to implement the job.
I wanted to get data from multiple mysql tables.

*

*user_transaction

*user_loans

*promo_offers

To get the final table I found the following 2 ways.
Method 1:

*

*Create Catalog for each table then,

user_transaction = glueContext.create_dynamic_frame.from_catalog(
           database="Org_Data_Lake",
           table_name="user_transaction"
       transformation_ctx = "user_transaction",
       additional_options = {"jobBookmarkKeys":["transaction_id"],"jobBookmarksKeysSortOrder":"asc"})

user_loans = glueContext.create_dynamic_frame.from_catalog(
           database="Org_Data_Lake",
           table_name="user_loans")
promo_offers = glueContext.create_dynamic_frame.from_catalog(
           database="Org_Data_Lake",
           table_name="promo_offers")

*Then apply Join.apply to get final

final_history = Join.apply(user_transaction,
                       Join.apply(user_loans, promo_offers, 'offer_id', 'offer_id'),
                       'user_loan_id', 'user_loan_id').drop_fields([.......])

*Finally, put all data into S3

glueContext.write_dynamic_frame.from_options(frame = final_history,
          connection_type = "s3",
          connection_options = {"path": "s3://glue-sample-target/output-dir/final_history"},
          format = "parquet")

Method 2:

*

*Get the final_history data ready at once,

query = "t1.transaction_id, t1.status, t2.loan_status, t3.offer_amount
     FROM user_transaction AS t1
     JOIN user_loans AS t2 ON (t2.user_loan_id = t1.user_loan_id)
     JOIN promo_offers AS t3 ON (t3.offer_id = t2.offer_id)
     WHERE t1.created_at > '2020-01-01 00:00:00' LIMIT 10) as tmp"

final_history_data = glueContext.read.format("jdbc")
             .option("driver", jdbc_driver_name)
             .option("url", db_url)
             .option("dbtable", query)
             .option("user", db_username)
             .option("password", db_password).load()

final_history = DynamicFrame.fromDF(final_history_data, glueContext, "final_history")

*Finally put all data into S3

glueContext.write_dynamic_frame.from_options(frame = final_history,
          connection_type = "s3",
          connection_options = {"path": "s3://glue-sample-target/output-dir/final_history"},
          format = "parquet")

Which method is the best way and how to apply jobBookmarkKeys to method 2??

A: Your job might fail if you are using Method 1 which you need to handle:

*

*Consider there is no new data returned for dynamic_frame user_transaction because you enabled jobbookmark which will fail step 2 as it is empty.

*So you need to conditional check that if it is empty then skip the processing and exit.
In Method 2 you cannot leverage jobbookmark as transformation_ctx is missing and cannot be included as you are reading directly from database by pushing down the query down to engine.The transformation_ctx parameter is used to identify state information within a job bookmark for the given operator. Specifically, AWS Glue uses transformation_ctx to index the key to the bookmark state. Refer to this to know more.
Comparing these two methods:

*

*Method 1 will help your jobs to run faster if there is no data to process between job runs as job bookmark is enabled.

*Method 2 will give you better performance if your DB has some good hardware which can return the result of the query with less turn around time. But if there is no new data between multiple job runs your job will still send the query to DB engine where as in the later case it will not.

*Also considering the number of new records between job runs you can decide to choose either job bookmark or pushing down the query to DB engine.


text:
Q: Why an orthonormal polynomial set over a continuous domain is not over a discrete one? I would like to read the proof showing that a orthonormal polynomial set over a continuous domain is neither orthonormal nor complete over a discrete values on that domain.
For example, Zernike polynomials are a complete and orthonormal set of polynomials over the continuous unit disk. However, they are not over a set of discrete samples in the unit disk. Where can I read why?
Thanks for your time.

A: There is a theory concerning discrete measures. See for example the book
"Discrete orthogonal polynomials : asymptotics and applications" by J. Baik, T. Kriecherbauer, K. T.-R. McLaughlin & P. D. Miller. P. 8-9 may be what you are looking for.
Also, there is a theory of orthogonal polynomials for measures with a support equal to a Cantor set, hence a totally disconnected set. See for example, "Orthogonal polynomials associated with invariant measures on Julia sets" and "Infinite-dimensional jacobi matrices associated with Julia sets" by  M. F. Barnsley, J. S. Gerónimo and A. N. Harrington.


text:
Q: What real life applications does diffusion limited aggregation have? While studying DLA - diffusion limited aggregation - in the field of fluid dynamics I started wondering what real life application does this phenomena have? We observe fractals in experiments such as following experiment : https://www.youtube.com/watch?v=zf1gR-tNzUs and pondering that we will be able to explain why the fractals appear in such way, what can we learn from this and how is that applicable in for instance life science or anything related to sustainability or global goals?
The exact problem is :
"The effect of fractal fingering can be observed if a droplet of an ink-alcohol mixture is deposited onto diluted acrylic paint. How are the geometry and dynamics of the fingers influenced by relevant parameters?"


text:
Q: How to turn continuous signal into a short pulse using logic gates? Basically, I want to turn a continuous "1" into a short "1" pulse then "0". I'm new to logic gates, apologies if it's too obvious.

A: An XOR gate and a pair of inverters will do this if you don't need precise control over the pulse width.

simulate this circuit – Schematic created using CircuitLab
How it works:
An XOR gate output is high only when its inputs are at different states (i.e. 10 or 01). The two inverters add a small amount of delay to the signal seen on the bottom leg which gives you a brief moment when the inputs are different, leading to a pulse on the output whenever the line changes high or low. This is a very simple edge detector circuit.
If you need more delay you can add a resistor between the two inverters along with a capacitor between the resistor and input to the second inverter:

simulate this circuit
This adjusts the pulse delay by slowing down the signal even more. The values of the resistor and capacitor determine the delay. If you're going to be sticking analog elements into your digital design you may want to use Schmitt trigger inverters as they can better handle input signals which "wander" through the boundary between a logic 0 and logic 1.

A: In the simplest form a single non-inverting gate can be used with an RC differentiator input to give a single pulse output from a high going signal transition.  The resistor/capacitor values shown are just for reference when a very short output pulse is needed.  (See Figure 1.)
When the positive transition is received at C1 only a very short spike of current reaches the gate input.  The gate outputs a high.  The spike at the gate input quickly dissipates to ground by way of R1. As the spike dissipates it will have a typical RC droop curve but the digital gate turns this into a squared off low output. By varying the values of R1 C1 the width of the output pulse can be varied. Larger RC values would generate wider output pulses and vise-versa.
To be sure that extra pulses are not generated a schmitt trigger type gate can be used or a high value resistor can be added to give some positive feedback.  (See Figure 2.)
Note that the gate input will also receive a negative voltage spike when the input switches back low.  Most common gates will include protective diodes on the input pins that safely reroute low power over/under voltage spikes to ground or Vcc. Some gates (such as those rated as higher voltage tolerant) may not have such diodes, so adding external diodes can help in this case.  (See Figure 3.)

simulate this circuit – Schematic created using CircuitLab

A: I was looking for a circuit that produced a pulse only when the input went from low to high. Inspired by @akohlsmith answer, I came up with this:

A: I've created pretty simple short pulse generator. If state changes from high to low on generator, there will appear high state on first inverter output, and first AND gate input. But on second AND gate input there will be still low state (beacuse RC is not charged) - and if on second inverter input we have low state, on output will be high - both outputs have high - so on circuit output there will be high state (until RC has less voltage than Vinlowmax (inverter parameter). To use this kind of circuit - use Schmitt inverters (for low-growing signals).
Image

If you want signal on rising edge - delete one inverter.

A: Input: oscilating pulses (Function Generator) + button;
Output: single pulse from oscilator;
Simulation on Falstad's

A: one easy way to do this is with two d-flops and some logic gates.  this will produce a pulse exactly one half a clock long, which is to say the output pulse is equal to one high pulse of the clock. it will never output a partial pulse. very similar but a bit simpler than Raivis's answer.
see a simulation here.


text:
Q: IPsec transport mode and MTU [Similar to Right way to set the MTU of an IPsec Client (Linux/Racoon), but different in that there is no router on the responder side]
I have a setup where machines in a local network need to talk to a Linux server in a datacenter. The router for the local network has a static external IP address, so I've configured a policy on both the router and the server to use IPsec in transport mode to speak to each other.
This works fine for small packets, however the server cannot accurately determine the MTU for outgoing packets, leading to connection hangs.
What is the best way to avoid these issues?
Ideas so far:

*

*limit the MTU in the routing table. This requires a static route on the server and basically works, but breaks for mobile ("roadwarrior") clients when I introduce them in two weeks.

*use iptables to modify the TCPMSS setting on incoming packets. This appears to have no real effect, and would not work for UDP.

A: This is a bug in the Linux kernel IPsec.  It fails to account for the size of the transport-mode ESP encapsulation when deciding whether to fragment the outgoing packet; it's then dropped on output as it exceeds the interface MTU.  I don't know whether this has been fixed in newer kernels.

A: 1) There's no MTU for packets. MTU is for an interface. Packets size is compared to the interface MTU.
2) Router always knows MTU of its interface. This knowledge can be erroneous, but stil it does exist.
3) TCP MSS can be modified on incoming packets. And this HAS real effect on the transmission.
As about your setup - the maximum size that your IPSec channel can incapsulate without fragmentation is determined bu the IPSec headers size, thus this is dependant on the transform set and encryption ciphers. Without knowing one, it's impossible to calculate.
Still, if the sum of the payload + headers is more that the MTU of the outgoing interface, it doesn't mean that the packet will be dropped - the fragmentation may occur. Even if the encapsulating packet has the DF bit set - it may or it may not be copied to the outer header (if we speak about tunnels), and this depends on the configuration of your security endpoint.
I don't quite understand what your setup is. I guess you are using IPsec transport mode with some intermediate encapsulation, like gre or ipip.


text:
Q: look for an object in an array of object return undefined Hy,
I have the following array of objects, I wish that the id returns to me its object. How could I do?
    prodotto=[
{
    categoria:"primi",
    prodotti:[
    {
        id:1,
        nome:"pasta",
        prezzo:12,
        qta:0
    },{
        id:2,
        nome:"gnocchi",
        prezzo:12,
        qta:0
    }
    ]
},
{
    categoria:"secondi",
    prodotti:[  {
        id:3,
        nome:"salsiccia",
        prezzo:12,
        qta:0
    },{
        id:4,
        nome:"frittura",
        prezzo:12,
        qta:0
    }]

}

];

for example, after id 2 returns
{
            id:2,
            nome:"gnocchi",
            prezzo:12,
            qta:0
        }

A: You can use .map() and .find() methods to find the desired object.

let data = [{
  categoria:"primi",
  prodotti:[
    { id:1, nome:"pasta", prezzo:12, qta:0 },
    {id:2, nome:"gnocchi", prezzo:12, qta:0 }
]}, {
  categoria:"secondi",
  prodotti:[
    { id:3, nome:"salsiccia", prezzo:12, qta:0 },
    {id:4, nome:"frittura", prezzo:12, qta:0 }
]}];

let locator = (objId) => [].concat(...data.map(({ prodotti }) => prodotti))
                           .find(( {id} ) => id === objId);

console.log(locator(2));

You may also store the intermediate results in another array to easily iterate over them and find the resultant object.

let data = [{
  categoria:"primi",
  prodotti:[
    { id:1, nome:"pasta", prezzo:12, qta:0 },
    {id:2, nome:"gnocchi", prezzo:12, qta:0 }
]}, {
  categoria:"secondi",
  prodotti:[
    { id:3, nome:"salsiccia", prezzo:12, qta:0 },
    {id:4, nome:"frittura", prezzo:12, qta:0 }
]}];

let _data = [].concat(...data.map(({ prodotti }) => prodotti));

let locator =  (objId) => _data.find(( {id} ) => id === objId);

console.log(locator(2));

A: You can use flatMap and find like this:

const prodotto = [{categoria:"primi",prodotti:[{id:1,nome:"pasta",prezzo:12,qta:0},{id:2,nome:"gnocchi",prezzo:12,qta:0}]},{categoria:"secondi",prodotti:[{id:3,nome:"salsiccia",prezzo:12,qta:0},{id:4,nome:"frittura",prezzo:12,qta:0}]}]

const output = prodotto.flatMap(a => a.prodotti).find(p => p.id === 2)
console.log(output)

If flatMap isn't supported in your browser, use concat and Spread syntax

const prodotto = [{categoria:"primi",prodotti:[{id:1,nome:"pasta",prezzo:12,qta:0},{id:2,nome:"gnocchi",prezzo:12,qta:0}]},{categoria:"secondi",prodotti:[{id:3,nome:"salsiccia",prezzo:12,qta:0},{id:4,nome:"frittura",prezzo:12,qta:0}]}]

const output = [].concat(...prodotto.map(a => a.prodotti))
                  .find(p => p.id === 2)

console.log(output)

A: function getObjById(id) {
  for (var i = 0; i < prodotto.length; i++) {
    var obj = prodotto[i];
    for (var j = 0; j < obj.prodotti.length; j++) {
      var inn = obj.prodotti[j];
      if (inn.id === id) return inn;
    }
  }
}

console.log(getObjById(4));

It's an old version of javascript, it's supported for ECMA5.

A: One approach could be to use the Array#reduce method combined with Array#find. This allows you to iterate through each prodotto array item and "reduce" this array down to the result that you're looking for (ie an item in the prodotti sub-array with id matching 2).
During each reduce iteration, the following logic allows you to either "pass through" a previously found result, or invoke a search for the sub-array item (via the Array#find method):
// If currentResult defined, return that, otherwise look for a matching item
// in prodotti sub-array which will become the currentResult for subsequent
// iterations:
return currentResult || item.prodotti.find(subitem => {
  return subitem.id === 2;
});

These two ideas combined into a working solution are shown as the following:

var prodotto = [{
    categoria: "primi",
    prodotti: [{
      id: 1,
      nome: "pasta",
      prezzo: 12,
      qta: 0
    }, {
      id: 2,
      nome: "gnocchi",
      prezzo: 12,
      qta: 0
    }]
  },
  {
    categoria: "secondi",
    prodotti: [{
      id: 3,
      nome: "salsiccia",
      prezzo: 12,
      qta: 0
    }, {
      id: 4,
      nome: "frittura",
      prezzo: 12,
      qta: 0
    }]

  }

];

// Use reduce to search all sub arrays of the prodotto array
var result = prodotto.reduce((currentResult, item) => {

  // return the current result found, or if none yet return
  // the result (if any) that is found in the prodotti sub array
  return currentResult || item.prodotti.find(subitem => {
    return subitem.id === 2;
  });

}, undefined)

console.log(result)


text:
Q: Color statelist not working on recyclerview textview I set up a color statelist like so:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="@color/white_25percent_opacity" android:state_selected="true"/>
    <item android:color="@color/white_25percent_opacity" android:state_pressed="true"/>
    <item android:color="@color/white_25percent_opacity" android:state_focused="true"/>
    <item android:color="@android:color/white"/>

</selector>

Then I tried to set it in the xml for a recyclerview item like so:
<TextView
        android:id="@+id/myTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_centerHorizontal="true"
        android:textSize="18sp"
        android:paddingLeft="10dp"
        android:paddingStart="10dp"
        android:paddingRight="10dp"
        android:paddingEnd="10dp"
        android:textColor="@color/mySelector"
        />

but it doesnt work - the color doesnt change when pressed. So I tried to set it programmatically in onBindViewHolder like this:
viewHolder.myTextView.setTextColor(ContextCompat.getColorStateList(context, R.color.mySelector));

and I also tried like this:
viewHolder.myTextView.setTextColor(ContextCompat.getColor(context, R.color.mySelector));

which also don't work. Where is the mistake here and why doesn't this work for recyclerviews? To clarify - the text is shown in the initial color (white) but doesn't change to the pressed color.
Edit: also tried to solve it by making the selector a drawable - but it didn't work:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/white_25percent_opacity" android:state_selected="true"/>
    <item android:drawable="@color/white_25percent_opacity" android:state_pressed="true"/>
    <item android:drawable="@color/white_25percent_opacity" android:state_focused="true"/>
    <item android:drawable="@android:color/white"/>

</selector>

If I set an ontouchlistener and switch the colors manually then it works properly - but I want to do this with a statelist.

A: Hi Implement your XML like the below code , Hope it would be helpful may be the issue is you have given both state_pressed and state_selected = true.
    <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Color when the row is selected -->
    <item android:drawable="@android:color/darker_gray" android:state_pressed="false" android:state_selected="true" />
    <!-- Standard background color -->
    <item android:drawable="@android:color/white" android:state_selected="false" />
</selector>

A: Turns out I needed to set this on the textview to make it work:
android:clickable="true"


text:
Q: Center Only Specific Text I am trying to make it so that only one draw text item will be centered instead of all of them but i cant get it to work.  draw_set_halign(fa_center) changes all text but I am only looking to change one thing.  I know this is a simple question with pretty much no detail but I think it is still clear.

A: Use draw_set_halign() before each text.
draw_set_halign(fa_center);
draw_text(...);

draw_set_halign(fa_left);
draw_text(...);
draw_text(...);

If you want change one line (or just a part) of one text, then you need split text to independent parts and draw each one using correct halign.


text:
Q: Youtube API > Videos Search > lr parameter not work Since today :
"http://gdata.youtube.com/feeds/api/videos?q=nexus&orderby=relevance&start-index=1&max-results=5&v=2&alt=jsonc&lr=fr"
Give me no results, where as "http://gdata.youtube.com/feeds/api/videos?q=nexus&orderby=relevance&start-index=1&max-results=5&v=2&alt=jsonc" does return results.
I notice it's working on my home laptop, but not on my production server. Is it possible youtube blacklist my server IP ? But I got result w/o LR parameter ......
Thanks

A: Ok got it,
gdata.youtube.com => has lot of IPs and 1 of range is buggy ;-(
So the solution was to edit /etc/hosts and manually enter my home youtube IP on the server.


text:
Q: An easy way to deep copy objects in Java I am getting an entity over the wire (using oData4j). This entity has properties that map to the properties of an object. If I were to copy the contents of this entity to my object in .net, I would just serialize it into json and deserialize it back to my object. This would have automatically copied properties by name.
In java I found a library org.apache.commons.lang.SerializationUtils
However if I serailize using this library, it puts the @type attribute which is the original type of the object serialized. So this is not possible
PersonEntity p =new PersonEntity();
 p.Name="tada";
String json = JsonWriter.objectToJson(p);
LocalPerson lp=  new LocalPerson();
 lp = (LocalPerson)JsonReader.jsonToJava(json);//Fails on this line

However I could do this in .net using newtonsoft.json. Is there an easy way to copy the entity properties into my class just by property name?


text:
Q: How to use route parameter as argument for a service method? I'm trying to get product details to the route of single product.
for now
I have route for single product with id parameter and it's working fine
{ path: 'single-product/:id', component: SingleProductComponent }

and in component typescript :
 id: string;
 private mainSub: any;
 public ngOnInit(): void {
  this.mainSub = this.route.params.subscribe(params => {
     this.id = params['id'];
  }
   this.productsService
    .all()
    .map(res => res.filter(item => item.id === this.id))
    .subscribe(resp => console.log(resp));
 });
 }

in the console I got the right product but How can I get data to the view ?

A: First things first:
Lets encapsulate that filter logic in the service class:
export interface Product {
 // define the properties for your product
}

@Inject()
export class ProductService {
 ....
 // constructor injetction and other methods
 ....

 all(): Observable<Product[]>{
   // implementation
 }

 getById(id:string): Observable<Product> {
   // or maybe could your backend offer an endpoint that does this for you?
   // something like `root/api/products/:id`;
   return this.all().map(products => products.find(product => product.id === id));
 }
}

Now we can go back to the component:
import 'rxjs/add/operator/switchMap'; // Maybe replace with lettable operators

@Component({...})
export class FooComponent {
 product$: Observable<Product>;
 constructor(private _route: ActivatedRoute, private _productService: ProductService){
    this.product$ = _route.paramMap
       .map(params => params.get('id')) // maps the route params. map to the id key
       .switchMap(id => _productService.getById(id));// change the main stream to the stream returned by the service
 }
}

Now in your template you could use a little trick to access to the latest value in the product$ stream:
<ng-container *ngIf="product$ | async as product">
   {{ product | json }}
   // your template goes here
</ng-container>

A: Use following code to implement in your component:
 id: string;
 product: any;
 private mainSub: any;
 public ngOnInit(): void {
  this.mainSub = this.route.params.subscribe(params => {
     // I used + sign if id is number otherwise remove it
     this.id = +params['id'];
     this.productsService
      .all()
      .map(res => res.find(item => item.id === this.id))
      .subscribe(resp => this.product = resp);
    });
  }
 }

Now use your data in your html template like this (dummy html):

    Product Name
    {{product.productName}}


text:
Q: swift 3 equivalent for indexAtPosition, urlRequest.url!.isEqual Hi i am getting following errors while upgrading from swift 2.2 to swift 3

Argument labels '(atPosition:)' do not match any available overloads"

Below are the following code in swift 2.2.could you guys help me out.
private func getIndexInTheLastSection(indexPath: NSIndexPath) -> Int? {
        let index = indexPath.indexAtPosition(indexPath.length - 1)
        if index == NSNotFound {
            return nil
        }
        return index
    }

////////////////

A: For isEqual error with URL use == instead of isEqual to compare.
if urlRequest.URL! == strongSelf.request?.urlRequest?.URL {

For error Argument labels '(atPosition:)'
indexPath.index(atPosition: (indexPath as NSIndexPath).length - 1)


text:
Q: SocketException: Weblogic 'm getting the following exception when try to query a page, from weblogic server 10.3. Kindly help me out to fix this issue.
java.net.SocketException: socket write error: Connection reset by peer.
at jrockit.net.SocketNativeIO.writeBytesPinned(Native Method)
at jrockit.net.SocketNativeIO.socketWrite(SocketNativeIO.java:46)
at java.net.SocketOutputStream.socketWrite0(SocketOutputStream.java)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at weblogic.utils.io.ChunkedOutputStream.writeTo(ChunkedOutputStream.java:284)
at weblogic.servlet.internal.ServletOutputStreamImpl.writeHeader(ServletOutputStreamImpl.java:167)
at weblogic.servlet.internal.ResponseHeaders.writeHeaders(ResponseHeaders.java:444)
at weblogic.servlet.internal.ServletResponseImpl.writeHeaders(ServletResponseImpl.java:1288)
at weblogic.servlet.internal.ServletOutputStreamImpl.sendHeaders(ServletOutputStreamImpl.java:281)
at weblogic.servlet.internal.ChunkOutput.flush(ChunkOutput.java:424)
at weblogic.servlet.internal.CharsetChunkOutput.flush(CharsetChunkOutput.java:298)
at weblogic.servlet.internal.ChunkOutput$2.checkForFlush(ChunkOutput.java:648)
at weblogic.servlet.internal.CharsetChunkOutput.write(CharsetChunkOutput.java:200)
at weblogic.servlet.internal.ChunkOutputWrapper.write(ChunkOutputWrapper.java:148)
at weblogic.servlet.jsp.JspWriterImpl.write(JspWriterImpl.java:275)

Thanks.

A: It is related timeout issue. you can increment timeout by following way
Complete Message Timeout: Maximum value: 480
Maximum Message Size:
Minimum value: 4096
Maximum value: 2000000000
Secure value: 10000000
These are available at: server >>>>> AdminServer >>>> Protocols>>> General.
Also that would be better if your application compiled with the same java version that is used by the weblogic.
It could happen if you are not flushing the buffer.
Get read/write steams and control them with buffers.
you can even try increasing the jsp buffer size..
you could check if you have the same issue by switching the server to Sun JDK

A: As before stated this error happens for many reasons. I will just give you some hints on troubleshoting.  First there are several types of logs with Weblogic architecture. This certainly can be a timeout issue, but can be many other reasons.  To debug it is important to understand the Weblogic architecture, configuration, and environment. First it important to determine which tier is throwing the root cause error.
This particular log appears to be Weblogic server log(Thrown before reaching the application). My next step would go to  your application.log to see if it generated any errors. That will rule out your application tier.  If no log exists create application log via application configuration or web console. Next if there is no corresponding error, then its time to troublshoot your webtier.
Webtier being Apache, Http server, or proxy.  Sometimes these can throw errors when certificates trusts etc not in alignment. Wallets and keystores.
If you are using nodemanager, that can also be a point of failure.
In my experience, this happens when the application tier croaks, database connection,network disconnect(user client tier) bad deployment, long running queries, or misconfigured certs or ports. Lastly, if this happens irregularly then in my experience it is normal too, but performance/load should be looked at.

A: The client is closing the connection to the server, so Weblogic cannot write back the reply completely.
If this error is happening randomly, it can be due to an exception while processing the response in the client side.
If you have many clients, chances are some users get suddenly disconnected (e.g. client machine unplugged, program crash, etc.) while receiving the response from the server.
This error is very generic and can have multiple root causes.
BR


text:
Q: Get value of textarea with this element and not identifier I want to check empty textarea in tinymce
$(".tooltip-empty-editor").each(function() {

    if( $.trim( tinymce.get(this).getContent() ) == '' ) {
        // .....
    }

});

html
<textarea class="editor tooltip-empty-editor " name="modif" >....</textarea>

But this i got error tinymce.get(this).getContent() with this he expect a ID.
How can I use this with tinymce to get value of textarea ?

A: Why can't you define the id and access it as follows?
$(".tooltip-empty-editor").each(function() {

    if( $.trim( tinymce.get($(this).attr("id")).getContent() ) == '' ) {
        // .....
    }

});

A: Depending on how your textarea's are related to eachother, you could try to find the index. You need a sibling, or if they're all children of the same node (parent) no need to bother => $(this).index()
If you only have one on the page => textarea = tinymce.get(0)
HTML expectation:

        <textarea class="editor tooltip-empty-editor " name="modif" >....</textarea>

        <textarea class="editor tooltip-empty-editor " name="modif" >....</textarea>

JS
$(".tooltip-empty-editor").each(function() {
    var index = $(this).closest('.sibling').index(),
        //index = $(this).index(),
        textarea = tinymce.get(index); // get() requires an id or a number

    if( $.trim( textarea.getContent() ) == '' ) {
        // .....
    }
});

If your html is polluted with other elements on the parent, you'll need to use .filter() to get the index from.

A: Per the product documentation, the get() API for TinyMCE "Returns an editor instance by id".  The id parameter is expected to be a String.  In your example you seems to be trying to pass it the "this" object which is not a String.
I would give each textarea on the page a unique ID attribute and you can then reference each textarea using that ID.
As one other poster noted you can also use an integer to access each TinyMCE instance on the page (e.g. tinymce.get(0) and tinymce.get(1))


text:
Q: websocket parser error in Node JS Socket I have got following warning in my Node JS application :
warn - websocket parser error: continuation frame cannot follow current opcode
It has occurred only once but I have no clue what it was about.
Does anybody have idea on this?
Thanks in advance.

A: What version of node / ws are you using? I had this same warning (intermittently) when using an old version of ws (0.8.2) with a modern node (6.9.1). I upgraded to ws 1.1.1 (same node version) and never saw this again. Hope this helps.


text:
Q: Get gull Request URL from dotnet core behind a nginx proxy I need to get the URL from the dotnet-core webapi from where the api is called.
The api itself is hosted behind a nginx-proxy in a specific location:
nginx config:
server {
    server_name my.domain.com;
    root /var/www/html/someotherapp;
    index index.php;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log info;

    location /myapi/ {
            proxy_pass http://localhost:8181/;
            proxy_buffering off;
            proxy_read_timeout 7200;

            proxy_set_header Upgrade           $http_upgrade;
            proxy_set_header Connection        "upgrade";
            proxy_set_header Host              $host;
            proxy_set_header X-Real-IP         $remote_addr;
            proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Host  $host;
            proxy_set_header X-Forwarded-Port  $server_port;

    }
    location / {
            index index.html;
    }

listen 443 ssl; # managed by Certbot
}

dotnet api:
in startup.configureservices:
services.Configure<ForwardedHeadersOptions>(options =>
{
  options.ForwardedHeaders =
    ForwardedHeaders.All;
});

and startup.configure
app.UseForwardedHeaders();

I can call this app now via

https://my.domain.com/myapi/api/testapi?myquery=test

And while trying to get the URL I'm called with in the controller with something like
$"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}{HttpContext.Request.Path}{HttpContext.Request.QueryString}";

I won't the the location, where the proxy is forwarding, so the result is always
https://my.domain.com/api/testapi?myquery=test

missing the "myapi" location.
Any Idea how to get the location as well?


text:
Q: Error with iOS 5.1 when i use ASIHTTPRequest and SBJSON i am getting this error:
Undefined symbols for architecture i386:
  "_OBJC_CLASS_$_ASIHTTPRequest", referenced from:
      objc-class-ref in FirstViewController.o
  "_OBJC_CLASS_$_SBJsonParser", referenced from:
      objc-class-ref in FirstViewController.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Note i have added the frameworks core graphics,system configuration,mobile core services,libz.dylib,libz.1.2.5.dylib,CF Network,UI Kit and Foundation.
I have searched all the forums and spend almost 4 days but just don't find the cause.
When i comment my ASIHTTPRequest and SBJSON  code lines,it works fine.
I have added all the classes for ASIHTTPRequest and SBJSON and checked thrice.
Could anyone suggest what am i doing wrong?

A: For ASIHTTP Request add the following frameworks:

*

*libz.1.2.5.dylib

*SystemConfiguration

*UIKit

*Foundation

*CoreGraphics

*MobileCoreServices

*CFNetworks

If you are using ASIHttp classes in iOS 5 or later, you need to turn ARC off for the ASIHttpRequest classes in Project-> Build Phases -> Compile Sources by using -fno-objc-arc for the ASI API classes.
Hope it solves the problem.

A: i had this same problem , but when i included the following frame-work
its working fine now..Don't forget to include -fno-objc-arc in the compile source
Best Wishes.......

A: I would take a look at the Build Phases section in your Target. Under "Compile Sources", make sure you see the .m files for ASIHTTPRequest and for SBJson. Sometimes when you drag external classes into a project, even if you check the box to copy the files into your project, they don't make it into these compile sources. When you drag a file into Xcode, there is a check box to add the file to the target. If this isn't checked, the file won't make it into the Compile Sources. Delete the files and re-add them, ensuring this file is checked (or you can add the .m files manually if you'd like).

A: For the ASIHTTPRequest error, it sounds like you've not added ASIHTTPRequest.m to your project.
(Or you have added ASIHTTPRequest.m, but have forgotten to mention the 4 billion errors xcode is emitting about ARC - see Why are my ASIHTTPRequest files showing ARC errors? )


text:
Q: Searching Date Fields I have a query that looks for a search term in certain fields of Data Model.
eventsQuery.where = 'Name contains :SearchTerm OR ' +
                    'Description contains :SearchTerm OR ' +
                    'ID contains :SearchTerm OR ' +
                    'Owner contains :SearchTerm';

I want to add the Date field into the search.
'Date contains :SearchTerm OR ' +

What would be the proper way to do so? FYI "Date" is already defined as a date field in the Data Model.

A: I'm not sure that it is possible to do with Query Builder, but it looks like it works with Calculated SQL Model:
Your SQL query would look similar to this:
SELECT
  Id,
  Name,
  Date
FROM
  Test
WHERE
  Name LIKE :SearchTerm OR
  Date LIKE :SearchTerm OR
  MONTHNAME(Date) LIKE :SearchTerm OR
  DAYNAME(DATE) LIKE :SearchTerm

Notes
To make it work for dates your search terms should look like this

*

*2018-12-31% - to search for exact date

*%2018% - to search for all 2018 year's records

*Full month name (e.g. January, February, March, ect...)

*jan% (for all months that start with 'jan')

*%uary (for all months that end with 'uary')

*%r% (for all months that contain 'r')

*same logic to search dates with specific days

Feel free to learn more about pattern matching in MySQL here: https://dev.mysql.com/doc/refman/5.7/en/pattern-matching.html
Inside your you can either educate your users to this query syntax or smartly analyze and format search term before passing it to the search query. You can find complex Calculated SQL search query sample in Project Tracker template. I would also consider using REGEXP instead of LIKE depending on your search requirements.


text:
Q: converting data sent into audio signal using microcontroller that suits the application i want to convert text or some numeric data got into speech to make it audible for the listener how do i make it?
Like example :
Say the temp detected at some far place for some process is some "x" data this data got wirelessly near the operator room must be converted into audible voice how do i do this?
Which microcontroller can i use. I have arduino due.

A: You will need to implement the following at a minimum of you want to achieve this with a micro
●Sound files, of the recorded words you need the system to say during announcements.
●External storage to hold them.
●A software algorithm to select the correct files and the correct order
●software interfacing between data input, storage, and audio output.
●Some kind of dac
●some kind of amplifier
●Some kind of speaker
There are things you may want to add, for example file compression to reduce the size of the storage required. Ambient noise sensors to adjust the volume to a sensible level.
If your micro has a built in DAC, you could boost it with an opamp and feed it into an external PA. Alternatively, you may want to use audio specific ics to get better sound quality and an on board power amp.
What is the scope of this project? What other requirements do you have?


text:
Q: Citrix XenApp alternative? I have one Windows application that I need to use when I travel. I have a Chromebook and wouldn't mind getting a tablet. It seems like a waste and a hassle to get a full laptop just for that one application. While looking for solutions, I came across Citrix Receiver and XenApp. It seems to do the trick, however I don't have a server and don't know how complicated it would be.
The reason I'm not using Remote Desktop or the like is because it's very important that it works and if something happens that requires me to have physical access to my home PC to fix, I could be without the app for days/weeks.
Are there any hosted solutions for this, so that I don't need my own server? Or does anybody have any other ideas?

A: You can use to Applidis, Systancia.
This solution permits to publish your application through a client or webacess onto your tablet.

A: Citrix XenApp is absolute overkill and very likely much too expensive. Use RDP or some other desktop access/sharing product.

A: I am a certified XenApp 6.5 Admin.
Basically, you are going to need an entire Windows Domain in order to get XenApp running.
This means paying for Window Server licensing fees, buying a huge server with an i7 and loads of memory, paying for Citrix XenApp licenses, etc.
This is the reason that it will be overkill for a single user with a single application.
XenApp is not for you.
Now, your next bet would be to see if your Chromebook uses an x86 processor (not an ARM) processor.
-If your Chromebook uses an ARM processor... sell it and or get a laptop/tablet with Windows that will run your application.
If your Chromebook happens to use an x86 processor AND your program works at Platinum level under WINE (https://www.winehq.org/) (You can find out how well it works searching in the WINE AppDB, https://appdb.winehq.org/), then you might be able to make it work by installing Ubuntu on your Chromebook, then installing WINE, and then installing your program.
If you are unable/uncomfortable installing Ubuntu on your Chromebook and or your program does not run at Platinum level using WINE: Sell your Chromebook and or get a Windows laptop to run your program.
TL;DR:
If your Chromebook is x86 AND you can install Ubuntu AND your program runs at Platinum level using WINE, then install Ubuntu, install WINE, install your program.
If not, then get a Windows laptop/tablet.


text:
Q: How to define height to an element in react native in android? I'm currently developing an app to be used in an Android tablet, unfortunately I got comfortable and added too many features in web view before testing again on android and now they look quite different.
I have a few elements in a flex-box view with flex-direction 'row', this is how they look on the browser and how they should look:

Then the same app on android looks like this:

You can see the two lines with inputs without proper height to fit the text, and a third line on the bottom already from another input.
This is the component code (I removed one input line to make it simpler):
<View>
  <Text style={styles.header}>
    {LanguageService(language).form.personalData}:
  </Text>
  <View style={styles.twoColumns}>
    <View style={styles.inputWrapper}>
      <Text>
        {LanguageService(language).form.firstName}:
      </Text>
      <TextInput
        style={styles.input}
        onChangeText={formikProps.handleChange('firstName')}
        value={formikProps.values.firstName}
        maxLength={20}
      />
    </View>
    <View style={styles.inputWrapper}>
      <Text>
        {LanguageService(language).form.phone}:
      </Text>
      <TextInput
        style={styles.input}
        onChangeText={formikProps.handleChange('phoneNumber')}
        value={formikProps.values.phoneNumber}
        keyboardType='phone-pad'
        maxLength={15}
      />
    </View>
  </View>
</View>

And here is the style:
const styles = StyleSheet.create({
  twoColumns: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  inputWrapper: {
    width: '48%',
    flexDirection: 'row',
    justifyContent: 'space-around',
    borderBottomWidth: 1,
    borderBottomColor: 'black',
    margin: 10,
  },
  input: {
    flexGrow: 1,
    paddingLeft: 5,
  },
  header: {
    color: 'red',
    fontWeight: 'bold',
    fontSize: 22,
  },
}

A: I think you can achieve the shape in the first image with this structure:

<View style={styles.container}>
  <View style={styles.headerContainer}>
    <Text style={styles.header}>
      {LanguageService(language).form.personalData}:
    </Text>
  </View>
  <View style={styles.inputsContainer}>
    <View stlye={styles.leftContainer>
      <View style={styles.inputWrapper}>
        <Text>
          {LanguageService(language).form.firstName}:
        </Text>
        <TextInput
          style={styles.input}
          onChangeText={formikProps.handleChange('firstName')}
          value={formikProps.values.firstName}
          maxLength={20}
         />
      </View>
    </View>
    <View stlye={styles.rightContainer>
      <View style={styles.inputWrapper}>
        <Text>
          {LanguageService(language).form.phone}:
        </Text>
        <TextInput
          style={styles.input}
          onChangeText={formikProps.handleChange('phoneNumber')}
          value={formikProps.values.phoneNumber}
          keyboardType='phone-pad'
          maxLength={15}
        />
      </View>
    </View>
  </View>
</View>

Style:
const styles = StyleSheet.create({
  container: {
    display: 'flex',
    flexDirection: 'column'
  },
  headerContainer: {
    flex: 0.5
  },
  inputsContainer: {
    flex: 1,
    display: 'flex',
    flexDirection: 'row'
  },
  leftContainer: {
    flex: 1
  },
  rightContainer: {
    flex: 1
  }
  inputWrapper: {
    width: '48%',
    flexDirection: 'row',
    justifyContent: 'space-around',
    borderBottomWidth: 1,
    borderBottomColor: 'black',
    margin: 10,
  },
  input: {
    flexGrow: 1,
    paddingLeft: 5,
  },
  header: {
    color: 'red',
    fontWeight: 'bold',
    fontSize: 22,
  },
}

A: I manage to solve this by removing the following line:
const styles = StyleSheet.create({
  twoColumns: {
    flex: 1,
  }
}


text:
Q: HikariCp metrics collection using micrometer in Java springboot application by configuring it in community,
I have a requirement where I want to do HikariCp metrics collection using micrometre in Java spring boot application by configuring it. I was looking around but I could not find much help in the official documentation

https://github.com/brettwooldridge/HikariCP/tree/dev/src/main/java/com/zaxxer/hikari

Can anyone please help me with how to do that?
Note: In the official documentation of Hikari they have provided a way to set metric registry for dropwizard but I wanted to do it with Micrometre.

A: only data source autoconfigured is exposed for metrics in my case I have a custom Hikari data source configuration.
public myDataSource(){
   DataSource datasource = this.createDataSource();// you can write your own implementation to create datasource. you can pass URL, username etc to create it.
 this.setUpHikariWithMetrics();
}

public void setUpHikariWithMetrics() {
    if (dataSource instanceof HikariDataSource) {
        ((HikariDataSource) dataSource).setMetricRegistry(metricRegistry);
    }
}


text:
Q: Why didn't Riker do something else in The Vengeance Factor? In the final scene of Star Trek: The Next Generation, "The Vengeance Factor" (episode 9 of season 3), why did Riker

 have to kill Yuta?

It is clearly said in previous scenes (by Dr. Beverly Crusher) that a microvirus, embodied in Yuta, was only harmful to members of the clan with which Yuta's clan was fighting. If so, couldn't he simply use force? Like catch her, and block her from reaching Brull or doing anything less harmful? If he wouldn't have enough force, I think that Worf was somewhere close to help him.
In my opinion, "The Vengeance Factor" is one of the best episodes of Star Trek: The Next Generation. But its final scene is simply terrible. Was it really necessary to end it in such a poor / lame / American-western-like way (where every "evil" must eventually die at the movie's end)?

A: The script simply indicates that he had "no choice". He'd tried lower settings (which she'd proven resistant to) and she was intent on reaching her victim:

Riker lowers the phaser, extends his other hand toward Yuta --
Riker : come on... (Yuta pauses) - I'm... sorry.
As Yuta whirls, reaches to touch Chorgan -- and Riker FIRES.
The stun charge shakes Yuta up -- but she remains conscious, recovers
  her footing. Riker changes the phaser setting, FIRES again. It
  knocks Yuta back. But she keeps coming.
Riker has no choice. He adjusts the phaser --
RIKER : Don't --
Yuta reaches for Chorgan again -- And Riker FIRES. Setting eight.
  Vaporize. And Yuta's gone.

A: The script (in Valorum's answer) explains that Riker had no choice, and perhaps if the scene was set up better that would come across better. (Very weird that everyone else stays seated during an attempted murder.)
But having "no choice" does not explain why Yuta cannot be stopped by the phaser on stun. One explanation could be that her species is naturally more immune to being stunned. The script says:

Riker MATERIALIZES, phaser in hand. Everyone's astounded. The Gatherer guard goes for his phaser rifle. Riker FIRES, stunning the guard. ... Riker aims the phaser at Chorgan, who freezes, glares at Riker. The guard is already starting to shake off the effects of the stun.

The script also provides the villain a moment to reveal her unnatural physical state:

"I was the one chosen... transformed... my cells were altered... my aging slowed... enough to finish my task."

So, although it is not definitively explained,  it's possible that her natural biology combined with altered cells made her immune to being stunned, forcing Riker to go up to setting eight.


text:
Q: How do I mmap a _particular_ region in memory? I have a program. I want it to be able to mmap a particular region of memory over different runs.

*

*I have the source code of the program. C/C++

*I control how the program is compiled. gcc

*I control how the program is linked. gcc

*I control how the program is run (Linux).

I just want to have this particular region of memory, say 0xabcdabcd to 0xdeadbeef that I mmap to a particular file. Is there anyway to guarantee this? (I have to somehow make sure that other things aren't loaded into this particular region).
EDIT:
How do I make sure that nothing else takes this particular region in memory?

A: You need to do two things:

*

*Specify the starting address as the first argument to mmap.

*Include the MAP_FIXED flag.

For the starting address, you need to make sure it's a multiple of the pagesize.  To get the pagesize, use the call sysconf(_SC_PAGESIZE) (that's the appropriate call on Linux, other platforms may be different).

A: Pass the address to map in addr. Try to get it on a 8KB boundary. You could try mlock() instead though.

A: You cannot make sure that nothing else takes that area of memory - first come, first served. However, as you need a particular part of the memory, I'm guessing that you have a pretty specialized environment, so you simply need to make sure that you are first (using start scripts)


text:
Q: Building Filtering sidebar and searching box I want to build filtering sidebar and search box . My problem is, I can't make it run searching box and filtering items together at the same time. I hope any of u can help me?
I think,the main problem is in my script "var s" php parameter where I'm getting cities from
Let's see what I've done so for,
Here's my script;

Search Box

 <form class="search" name="search" method="POST"
 action="product.php?product=<?php echo
 ''.htmlentities($_GET['product']).''; ?>" >

    <input  id="small_search"
   name="searchTerm" class="item_filter s" <?php { echo "checked"; } ?>
   list="local"  />

        <?php
            while($row = mysqli_fetch_assoc($result)){
                $local = ($row['local']); ?>
        <input type="submit"
         id="small_search_btn"  value="Search">
            <datalist id="local">
            <option value="<?php echo ''.htmlentities($row['local']).'';  ?
          >"></option>

        <?php } ?>
    </form >

   **Filtering **

   <?php

    some sql statement..
     ?>

    <input type="checkbox" class="item_filter b" value="<?php echo
    htmlentities($row['brand']); ?>" <?php if(in_array($row['brand'],$b
   {echo "checked"; } ?> >   <?php echo ucfirst($row['brand']);
   ?>

   <?php } ?>


text:
Q: Creating several boxplots with the same scale in Matlab I'd like to plot several distinct boxplot in Matlab, but give them the same scale so that readers do not get misled by comparing them side by side.
I've tried using the datalim option, but it only imposes an upper limit to the boxplot, but does not stretch it if the data doesn't reach it.
Any ideas?

A: Try linkaxes(). That will give them the same scale, and keep them synchronized if the user zooms or something else changes the scale.


text:
Q: Java GUI stopwatch not displaying time I've been working on this stopwatch application for a decent amount of time now but I've encountered some problems.
Problems

*

*The stopwatch isn't starting properly probably due to the clock logic

*The stopwatch isn't displaying the numbers onto my Java program properly

It would be nice if anyone were to help explain the flaws in my program and tell me why it isn't working the way I would like it to be. Much help needed and appreciated so here is my code.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Clock {

    private static void createWindow() {

        // Important
        final int windowWidth = 800; // Window width
        final int windowHeight = 300; // Window height
        // Clock variables
        boolean clockRunning = true; // When clock is running, this will be true
        int milliseconds = 0;
        int seconds = 0;
        int minutes = 0;
        int hours = 0;

        // Create JFrame
        JFrame frame = new JFrame(); // JFrame object

        // Create timer text
        JLabel timer = new JLabel("00:00:00");
        timer.setText("00:00:00");
        timer.setBounds(355, 100, 100, 40); // Button position

        // JButtons
        JButton startTimer = new JButton("Start the timer"); // Start timer button
        JButton stopTimer = new JButton("Stop the timer"); // Stop timer button

        // Event listeners

        startTimer.addActionListener(new ActionListener() // Start timer
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                System.out.println("Timer has started");
            }
        });

        stopTimer.addActionListener(new ActionListener() // Stop timer
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                System.out.println("Timer has stoped");
            }
        });

        // Clock logic
        if (clockRunning = true) {
            milliseconds = 0;
            seconds++;
        }

        if(milliseconds > 1000) {
            milliseconds=0;
            seconds++;
        }

        if(seconds > 60) {
            milliseconds=0;
            seconds=0;
            minutes++;
        }

        if(minutes > 60) {
            milliseconds=0;
            minutes=0;
            hours++;
        }

        timer.setText(" : " + seconds); // Milliseconds
        timer.setText(" : " + milliseconds); // Seconds
        timer.setText(" : " + minutes); // Minutes
        timer.setText("" + hours); // Hours

        // JButton Settings
        startTimer.setBounds(10, 100, 200, 30); // Button position
        stopTimer.setBounds(570, 100, 200, 30); // Button position

        // Frame Settings
        frame.setSize(windowWidth, windowHeight); // Window size
        frame.setLayout(null); // Frame position

        // Add
        frame.add(startTimer);
        frame.add(stopTimer);
        frame.add(timer);

        // Frame settings
        frame.setVisible(true); // Make frame visible
        frame.setResizable(false); // Disables maximize
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Allows the window to be closed
    }

    public static void main(String[] args) {
        createWindow();
    }
}

A:
The stopwatch isn't displaying the numbers onto my Java program properly

timer.setText(" : " + seconds); // Milliseconds
timer.setText(" : " + milliseconds); // Seconds
timer.setText(" : " + minutes); // Minutes
timer.setText("" + hours); // Hours

The setText(…) method replaces the existing text.
So the above code is the same as:
timer.setText("" + hours); // Hours

The stopwatch isn't starting properly probably due to the clock logic

For a stop watch you will need to use a Swing Timer so you can update the text at a specified interval.
See: Program freezes during Thread.sleep() and with Timer for the basics of using a Timer.


text:
Q: How to find the *position* of a single record in a limited, arbitrarily ordered record set? MySQL
Suppose you want to retrieve just a single record by some id, but you want to know what its position would have been if you'd encountered it in a large ordered set.
Case in point is a photo gallery. You land on a single photo, but the system must know what its offset is in the entire gallery.
I suppose I could use custom indexing fields to keep track of positions, but there must be a more graceful way in SQL alone.

A: So, first you create a virtual table with the position # ordered by whatever your ORDER BY is, then you select the highest one from that set. That's the position in the greater result set. You can run into problems if you don't order by a unique value/set of values...
If you create an index on (photo_gallery_id, date_created_on) it may do an index scan (depending on the distribution of photos), which ought to be faster than a table scan (provided your gallery_id isn't 90% of the photos or whatnot).
SELECT @row := 0;
SELECT MAX( position )
  FROM ( SELECT @row := @row + 1 AS position
           FROM photos
          WHERE photo_gallery_id = 43
            AND date_created_on <= 'the-date-time-your-photo-was'
          ORDER BY date_created_on ) positions;

A: Not really.  I think Oracle gives you a "ROWID" or something like that, but most don't give you one.  A custom ordering, like a column in your database that tells you want position the entry in the gallery is good because you can never be sure that SQL will put things in the table in the order you think they should be in.

A: As you are not specific about what database you're using, in SQL Server 2005 you could use
SELECT
  ROW_NUMBER() OVER (ORDER BY PhotoID)
  , PhotoID
FROM dbo.Photos

A: You don't say what DBMS you are using, and the "solution" will vary accordingly.  In Oracle you could do this (but I would urge you not to!):
select photo, offset
from
( select photo
  ,      row_number() over (partition by gallery_id, order by photo_seq) as offset
  from   photos
)
where  id = 123

That query will select all photos (full table scan) and then pick out the one you asked for - not a performant query!
I would suggest if you really need this information it should be stored.

A: Assuming the position is determined solely by the id, would it not be as simple as counting all records with a smaller id value?:
select
    po.[id]
    ...
    ((select count(pi.[id]) from photos pi where pi.[id] < po.[id]) + 1) as index
    ...
from photos po
...

I'm not sure what the performance implications of such a query would be, but I would think returning a lot of records could be a problem.

A: You must understand the difference between a "application key" and a "technical key".
The technical key exists for the sole purpose to make an item unique. It's usually in INTEGER or BIGINT, generated (identity, whatever). This key is used to locate objects in the database, quickly figure out of an object has already been persisted (IDs must be > 0, so an object with the default ID == 0 is not in the DB, yet), etc.
The application key is something which you need to make sense of an object within the context of your application. In this case, it's the ordering of the photos in the gallery. This has no meaning whatsoever for the database.
Think ordered list: This is the default in most languages. You have a set of items, accessed by an index. For a database, this index is an application key since sets in the database are unordered (or rather the database doesn't guarantee any ordering unless you specify ORDER BY). For the very same reason, paging through results from a query is such a pain: Databases really don't like the idea of "position".
So what you must do is add an index row (i.e. an INTEGER which says at which position in the gallery your image is; not a database index for quicker access, even though you should create an index on this column ...) and maintain that. For every insertion, you must  UPDATE index = index + 1 where index >= insertion_point, etc.
Yes, it sucks. The only solution I know of: Use an ORM framework which solves this for you.

A: There's no need for an extra table, why not just count the records instead?
You know the order in which they are displayed (which can vary), but you know it.
You also know the ID of the current record; let's say it's ordered on date:
The offset of the record, is the total number of records counted with a date < that date.
SELECT COUNT(1) FROM ... WHERE date < "the-date"

This gives you the number you can use as the offset for the other queries...