text:
Q: Is there a method to simply transpose a table in SQL. This table contains Numeric and Varchar values I would like to know how to transpose very simply a table in SQL. There is no sum or calculations to do.
This table contains Numeric and Varchar values.
Meaning, I have a table of 2 rows x 195 columns. I would like to have the same table with 195 rows x 2 columns (maybe 3 columns)

time_index
legal_entity_code
cohort
...
...

0
AAA
50
...
...

1
BBB
55
...
...

TO

Element
time_index_0
time_index_1

legal_entity_code
AAA
BBB

cohort
50
55

...
...
...

...
...
...

I have created this piece of code for testing
SELECT  time_index, ValueT, FieldName
FROM   (select legal_entity_code, cohort, time_index from ifrs17.output_bba where id in (1349392,1349034)) as T
UNPIVOT
(
    ValueT
    FOR FieldName in ([legal_entity_code],[cohort])
) as P

but I receive this error message :

The type of column "cohort" conflicts with the type of other columns specified in the UNPIVOT list.

A: I would recommend using apply for this.  I don't fully follow the specified results because the query and the sample data are inconsistent in their naming.
I'm pretty sure you want:
select o.time_index, v.*
from ifrs17.output_bba o cross apply
     (values ('Name1', o.name1),
             ('Value1', convert(varchar(max), o.value1)),
             ('Name2', o.name2)
     ) v(name, value)
where o.id in (1349392,1349034);

A: Gordon's approach is correct and certainly more performant.  +1
However, if you want to dynamically unpivot 195 columns without having to list them all, consider the following:
Note: if not 2016+ ... there is a similar XML approach.
Example or dbFiddle
Select Element = [Key]
      ,Time_Index_0 = max(case when time_index=0 then value end)
      ,Time_Index_1 = max(case when time_index=1 then value end)
 From  (
        Select [time_index]
              ,B.*
         From  YourTable A
         Cross Apply (
                      Select [Key]
                            ,Value
                       From OpenJson( (Select A.* For JSON Path,Without_Array_Wrapper ) )
                       Where [Key] not in ('time_index')
                     ) B
        ) A
 Group By [Key]

Returns
Element             Time_Index_0    Time_Index_1
cohort              50              55
legal_entity_code   AAA             BBB


text:
Q: Какая вероятность что из 5 карт 4 будут одной масти? Есть колода с бесконечным числом карт, вытягиваем оттуда 5 карт. Какая вероятность что из 5-и 4 будут одной масти?
Посчитал на пальцах - выходит 0,015625% (может быть и неправильно), но интересно узнать какой формулой нужно считать в таком задании, ведь задание может быть и очень трудным и тут уже без формулы никак

A: Ну, давайте соображать. Пусть мы выбираем конкретную масть, и какова вероятность, что таких карт - 4? Вероятность вынуть одну карту "не такую" - 3/4, и "такую" - 1/4. При этом пять вариантов размещения "не такой" карты - первой, второй ... пятой. Итого, вероятность вынуть пять карт, из которых 4 - нужной масти - 5*(3/4)*(1/4)^4.
Мастей - 4, события взаимоисключающие, так что просто можно сложить вероятности, т.е. умножить на 4.
Итак -
5*3*(1/4)^4 ~ 5.86%

Вычислительный эксперимент подтверждает :)
Готовых формул на все случаи жизни не существует... Данная ситуация называется мультиномиальным распределением, но оно же будет у вас не всегда :)

A: Задача легко решается "в лоб", простым подсчетом количества всевозможных равновероятных исходов эксперимента.
Количество вариантов размещения 4 мастей по 5 позициям равно 45 = 1024.

*

*Если под "4 карты одной масти" имеется в виду "ровно 4, любой, но одинаковой масти", то количество интересующих нас вариантов равно количеству размещений двух разных мастей (4 * 3 = 12), умноженному на количество размещений вида "4 одинаковых, 1 отличная" (5). Итого: 12 * 5 = 60 интересующих нас вариантов. Вероятность равна 60 / 1024 = 0.05859375

*Если под "4 карты одной масти" имеется в виду "ровно 4, одной конкретной, заранее заданной масти", то количество интересующих нас вариантов равно количеству вариантов пятой карты (3), умноженному на количество размещений вида "4 одинаковых, 1 отличная" (5). Итого: 3 * 5 = 15 интересующих нас вариантов. Вероятность равна 15 / 1024 = 0.0146484375
Если же под "4 карты" подразумевается "найдется хотя бы 4 карты одной масти", то количество интересующих нас вариантов в первом случае увеличивается на 4, а во втором - на 1. Вероятности меняются соответствующим образом.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why IPython Console in Spyder4 updates constantly when connecting to remote kernel on server? I followed the instructions on the official Spyder page and successfully connected to remote kernel via SSH. However I have a problem in my Ipython Console as it refreshes every 2-3 seconds adding In [1]: lines infinitely. I suppose it is refreshing of a state on server, but could someone explain what is this, why this happens and can I turn it off, so that the Console behaves the same as when I work on my local kernel(without infinite adding of empty lines)?

A: The solution could be found here in post of scott-8: https://github.com/spyder-ide/spyder/issues/10240#issuecomment-543913159
The copy of the answer:
Don't know about the issue above, but here is what solved my issue for anyone reading: instead of running python -m spyder_kernels.console and connecting to the kernel, quit the kernel after running it. Then restart the kernel with python -m spyder_kernels.console -f kernel-xxxxx.json, specifying the file that was just created in the runtime directory, and connect to it. This fixed my problem for some reason.


text:
Q: ¿Puedo cargar un interceptor desde una librería? Tengo un interceptor
public class ActivityTrackerInterceptor extends EmptyInterceptor {...
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {...
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
        String[] propertyNames, Type[] types) {...

Para cargar el interceptor en el archivo persistence.xml
<properties>
    ...
    <property name="hibernate.ejb.interceptor"
            value="com.demo.ActivityTrackerInterceptor" />
</properties>

Quiero generar una librería java con el interceptor, pero cuando genero el jar no detecta, probé incluyendo la clase en el proyecto y trabaja correctamente. ¿Se puede cargar un interceptor desde un archivo jar?

A: Sí se puede.
Yo tengo mis clases Java y mapeos de Hibernate en unas librerías y adicional a ello tengo un proyecto (jar) donde está la configuración de interceptors para configurarlo por proyecto solo si es necesario.
Realizo esta configuración mediante Spring en el artefacto final.
 Comentario de Luiggi Mendoza convertido en respuesta en modo wiki de comunidad, para que entre todos lo podamos mejorar.


text:
Q: Why the performance is degraded in a basic client/server http requests after a certain number of requests? I am learning how http test servers are implemented in Go. One of the tests I have done is a client sequentially launching http requests against the server. I notice that at a certain point the performance degrades and I am trying to understand why this is happening.
Server:
package main

import (
        "fmt"
        "log"
        "net/http"
        "time"
)

var i int64

func testEndpoint(w http.ResponseWriter, r *http.Request){
        fmt.Fprintf(w, "Test API Endpoint")
        i++
        if i%500==0 {
                fmt.Printf("%8d ",i)
                fmt.Println(time.Now())
        }
}

func handleRequests() {
        http.HandleFunc("/testendpoint/", testEndpoint)
        log.Fatal(http.ListenAndServe("192.168.1.10:10000", nil))
}

func main() {
        handleRequests()
}

Client:
package main

import (
        "fmt"
        "net/http"
        "os"
        "strconv"
        "time"
)

func main() {

        var i int64 = 0

        for true {
                _, err := http.Get("http://192.168.1.10:10000/testendpoint/")
                if err != nil {
                        fmt.Fprintf(os.Stderr, "ERROR IN REQUEST " + strconv.FormatInt(i, 10))
                }

                i++
                if i%500==0 {
                        fmt.Printf("%8d ",i)
                        fmt.Println(time.Now())
                }
        }

}

If I run the server in one computer and the client in another, I get the following results both for client and server.
Note how after around 14000 requests, the performance degrades drastically. Before that point, 500 requests were being processed in less than 300ms, but after that it takes more than 2 seconds.
I am wondering why this could be happening. Any tip on why this might be happening or further ideas to test/debug are welcomed.
$ ./client
     500 2020-12-15 16:44:35.501204136 +0000 UTC m=+0.286423636
    1000 2020-12-15 16:44:35.795277425 +0000 UTC m=+0.580496937
    1500 2020-12-15 16:44:36.097232522 +0000 UTC m=+0.882452022
    2000 2020-12-15 16:44:36.386123508 +0000 UTC m=+1.171342996
    2500 2020-12-15 16:44:36.694897004 +0000 UTC m=+1.480116492
    3000 2020-12-15 16:44:36.965486139 +0000 UTC m=+1.750705639
    3500 2020-12-15 16:44:37.274670444 +0000 UTC m=+2.059889944
    4000 2020-12-15 16:44:37.54871805 +0000 UTC m=+2.333937706
    4500 2020-12-15 16:44:37.883014229 +0000 UTC m=+2.668233705
    5000 2020-12-15 16:44:38.154143461 +0000 UTC m=+2.939362937
    5500 2020-12-15 16:44:38.425432208 +0000 UTC m=+3.210651684
    6000 2020-12-15 16:44:38.698070384 +0000 UTC m=+3.483289872
    6500 2020-12-15 16:44:39.043044644 +0000 UTC m=+3.828264144
    7000 2020-12-15 16:44:39.316508615 +0000 UTC m=+4.101728103
    7500 2020-12-15 16:44:39.706906271 +0000 UTC m=+4.492125771
    8000 2020-12-15 16:44:39.977016014 +0000 UTC m=+4.762235550
    8500 2020-12-15 16:44:40.249749997 +0000 UTC m=+5.034969497
    9000 2020-12-15 16:44:40.519252681 +0000 UTC m=+5.304472181
    9500 2020-12-15 16:44:40.790891768 +0000 UTC m=+5.576111280
   10000 2020-12-15 16:44:41.061129286 +0000 UTC m=+5.846348774
   10500 2020-12-15 16:44:41.331537024 +0000 UTC m=+6.116756524
   11000 2020-12-15 16:44:41.6014923 +0000 UTC m=+6.386711776
   11500 2020-12-15 16:44:42.015862138 +0000 UTC m=+6.801081638
   12000 2020-12-15 16:44:42.27974172 +0000 UTC m=+7.064961220
   12500 2020-12-15 16:44:42.550598739 +0000 UTC m=+7.335818239
   13000 2020-12-15 16:44:43.042057538 +0000 UTC m=+7.827277026
   13500 2020-12-15 16:44:43.308593233 +0000 UTC m=+8.093812721
   14000 2020-12-15 16:44:43.579001342 +0000 UTC m=+8.364220842
   14500 2020-12-15 16:44:46.101204626 +0000 UTC m=+10.886424114
   15000 2020-12-15 16:44:49.326795176 +0000 UTC m=+14.112014676
   15500 2020-12-15 16:44:52.595643491 +0000 UTC m=+17.380862991
   16000 2020-12-15 16:44:55.913072093 +0000 UTC m=+20.698291593
   16500 2020-12-15 16:44:59.235625136 +0000 UTC m=+24.020844612
   17000 2020-12-15 16:45:02.587721179 +0000 UTC m=+27.372940679
   17500 2020-12-15 16:45:05.971204497 +0000 UTC m=+30.756423997
   18000 2020-12-15 16:45:09.670093598 +0000 UTC m=+34.455313158
   18500 2020-12-15 16:45:13.163007448 +0000 UTC m=+37.948226924

$ ./server
     500 2020-12-15 16:44:35.50228497 +0000 UTC m=+15.289897949
    1000 2020-12-15 16:44:35.796584274 +0000 UTC m=+15.584197229
    1500 2020-12-15 16:44:36.098598652 +0000 UTC m=+15.886211619
    2000 2020-12-15 16:44:36.387435748 +0000 UTC m=+16.175048739
    2500 2020-12-15 16:44:36.696201259 +0000 UTC m=+16.483814274
    3000 2020-12-15 16:44:36.966804096 +0000 UTC m=+16.754417099
    3500 2020-12-15 16:44:37.276015936 +0000 UTC m=+17.063628891
    4000 2020-12-15 16:44:37.549883639 +0000 UTC m=+17.337496654
    4500 2020-12-15 16:44:37.88435121 +0000 UTC m=+17.671964249
    5000 2020-12-15 16:44:38.155498249 +0000 UTC m=+17.943111216
    5500 2020-12-15 16:44:38.426771588 +0000 UTC m=+18.214384591
    6000 2020-12-15 16:44:38.699408325 +0000 UTC m=+18.487021304
    6500 2020-12-15 16:44:39.044393354 +0000 UTC m=+18.832006333
    7000 2020-12-15 16:44:39.317814954 +0000 UTC m=+19.105428077
    7500 2020-12-15 16:44:39.708233633 +0000 UTC m=+19.495846648
    8000 2020-12-15 16:44:39.978336727 +0000 UTC m=+19.765949682
    8500 2020-12-15 16:44:40.251108332 +0000 UTC m=+20.038721287
    9000 2020-12-15 16:44:40.520548483 +0000 UTC m=+20.308161450
    9500 2020-12-15 16:44:40.79225032 +0000 UTC m=+20.579863335
   10000 2020-12-15 16:44:41.062455042 +0000 UTC m=+20.850068045
   10500 2020-12-15 16:44:41.332890285 +0000 UTC m=+21.120503252
   11000 2020-12-15 16:44:41.602861006 +0000 UTC m=+21.390473985
   11500 2020-12-15 16:44:42.0171982 +0000 UTC m=+21.804811155
   12000 2020-12-15 16:44:42.281081042 +0000 UTC m=+22.068693997
   12500 2020-12-15 16:44:42.551927035 +0000 UTC m=+22.339540014
   13000 2020-12-15 16:44:43.043399317 +0000 UTC m=+22.831012404
   13500 2020-12-15 16:44:43.309902419 +0000 UTC m=+23.097515386
   14000 2020-12-15 16:44:43.580302453 +0000 UTC m=+23.367915456
   14500 2020-12-15 16:44:46.102551408 +0000 UTC m=+25.890164399
   15000 2020-12-15 16:44:49.328143306 +0000 UTC m=+29.115756321
   15500 2020-12-15 16:44:52.596990705 +0000 UTC m=+32.384603720
   16000 2020-12-15 16:44:55.914415702 +0000 UTC m=+35.702028717
   16500 2020-12-15 16:44:59.236974914 +0000 UTC m=+39.024587869
   17000 2020-12-15 16:45:02.589078535 +0000 UTC m=+42.376691562
   17500 2020-12-15 16:45:05.972513206 +0000 UTC m=+45.760126281
   18000 2020-12-15 16:45:09.671430175 +0000 UTC m=+49.459043154
   18500 2020-12-15 16:45:13.164329259 +0000 UTC m=+52.951942274

A: You're probably not closing the response body, which is exhausting memory and causing your machine to swap. Try this in the client:
res, err := http.Get("http://192.168.1.10:10000/testendpoint/")
if err != nil {
    fmt.Fprintf(os.Stderr, "ERROR IN REQUEST " + strconv.FormatInt(i, 10))
}
res.Body.Close()


text:
Q: How to notify OSX app when something on Parse changes From time to time my iOS app pushes some PFObject (or change some of its fields) to one table.
Since there are NO push notifications for OSX (in Parse SDK), can I somehow inform my OSX app that there were some changes on Parse?
Currently app is polling Parse database every second for changes and that makes heavy requests per sec. (I need very fast response, so 1 second is something like max delay).

A: It sounds like you need another way to implement OSX push. There are two main options here:
1. Roll your own.
Set up a push notification server and build out your own service. You can find documentation on that here:
https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW9
http://mobiforge.com/design-development/programming-apple-push-notification-services
2. Use a Service besides Parse.com
There are a great number of services that offer OSX push services, and it sounds like you have an OSX app, so local integration should be easy.  Here are a few well-known ones to get you started:
http://www.urbanairship.com
http://responsys.com/marketing-cloud/products/push-IO
https://www.pushwoosh.com/
https://zeropush.com/documentation/apns


text:
Q: Update ACF select field data programmatically I have a ACF select field with a field name of "sales_rep". It is populated with:
John Doe
Bart Simpson
Eric Cartman
The field is set to show on the "User Form" and only show when the "Current User Role" is an admin.
The field shows on each user page and I can manually change it to the sales rep I want and save it.
The issue is that I want to be able to programmatically update it whenever the user profile is saved. I will eventually add more code to determine the sales rep but I simplified the issue for this post.
Below is my code in functions.php:
Attempt 1: No error and no change to value
// Update sales rep
add_action( 'edit_user_profile_update', 'update_rep' );
add_action( 'personal_options_update', 'update_rep' );

function update_rep( $user_id )
{
    update_user_meta( $user_id, 'sales_rep', 'Eric Cartman' );
}

Attempt 2: No error and no change to value
// Update sales rep
add_action( 'edit_user_profile_update', 'update_rep' );
add_action( 'personal_options_update', 'update_rep' );

function update_rep( $user_id )
{
    $field_key = "sales_rep";
    $value = array("Eric Cartman");
    update_field( $field_key, $value, $user_id );
}

A: Seems like user_ prefix could fix the issue.
Try to get/update fields with user_ prefix.
F.e:
update_field( $field_key, $value, "user_$user_id" );

And for update_user_meta,
Calling delete_user_meta before could solve the problem.
User meta could have duplicate keys.
Try this one
delete_user_meta( $user_id, $field_key );
add_user_meta( $user_id, $field_key, $value );

A: I think @Andrii Kovalenko is right, user_ prefix could be your issue.
Also noticed you are saving acf field data as an array("Eric Cartman").
I am assuming your ACF select field predefined select options look like this...
John Doe
Bart Simpson
Eric Cartman

This should work for your acf option...
// is run when you edit YOUR profile, and save it
add_action('personal_options_update', 'handle_user_profile_update' );

// is run when you edit ANY OTHER profile and save it
add_action('edit_user_profile_update', 'handle_user_profile_update' );

// on user profile update function handler
function handle_user_profile_update($user_id) {

    // update sales rep
    update_sales_rep_field($user_id);

    // add anymore on user update profile functions here...

}

// update sales rep field
function update_sales_rep_field($user_id) {

    // our values
    $value = 'Eric Cartman';

    // update acf user field by user id
    update_field('sales_rep', $value, 'user_' . $user_id);

}

Out of curiosity, are these sales reps actually users in your wordpress site?
If so you can dynamically populate the select sales_rep user field with sales rep users on your site like this...
function render_sales_rep_select_field($field) {

    // reset sales_rep select field choices
    $field['choices'] = [];

    // get users with user role sales
    $args = array(
        'role'    => 'sales', // your sales reps user role
        'orderby' => 'user_nicename',
        'order'   => 'ASC'
    );

    // get user with args from above
    $users = get_users( $args );

    // for each sales rep user
    foreach ( $users as $user ) {

        // build our sales rep select field choices by user_id > full name
        $field['choices'][$user->id] = $user->first_name . ' ' . $user->last_name

    }

    // return the select field
    return $field;

}

// load user field with our custom select drop of sales rep users
add_filter('acf/load_field/name=sales_rep', 'render_sales_rep_select_field');

With this method you won't need to update the field when the user saves changes to their profile.
For example if you get_field like this...
// get user field sales rep array
get_field('sales_rep', 'user_' . $user_id ); // random user id

it will return an array of user_id and full name...
Array
    (
        [5] => Eric Cartman
    )

In your acf user select field settings you will need select return both value and label.


text:
Q: SQL - How many numbers from 1 list are in another list This is a SQL query question.
I am write a smal lotto program in .net with a SQL backend.
the simple description of my problem is this:
i have a set of numbers (5 or 6) of the game which was drawn and a table full with suggested games (can be between a few thousand to a million).
i basically want to end up with that suggestion table updated with what the potential win would have been for each suggested game.
suggested game 1: 3 numbers correct
suggested game 2: 0 numbers correct
suggested game 3: 6 numbers correct
...

because of the potential size of the suggestion table speed is of essence.
the below is the direction i was going, but i am stuck and also don't think its going the right direction.
declare @WinningGame table(n1 int)
insert into @WinningGame (n1) values (5)
insert into @WinningGame (n1) values (12)
insert into @WinningGame (n1) values (15)
insert into @WinningGame (n1) values (16)
insert into @WinningGame (n1) values (22)
insert into @WinningGame (n1) values (35)

declare @SuggestedGames table(
N1 int,
N2 int,
N3 int,
N4 int,
N5 int,
N6 int,
Hit1 int,
Hit2 int,
Hit3 int,
Hit4 int,
Hit5 int,
Hit6 int)

insert into @SuggestedGames
(N1, N2, N3, N4, N5, N6, Hit1, Hit2, Hit3, Hit4, Hit5, Hit6)
Values (5, 12, 15, 16, 22, 35, 0, 0, 0, 0, 0, 0),
(5, 12, 16, 18, 27, 42, 0, 0, 0, 0, 0, 0),
(5, 12, 15, 16, 22, 35, 0, 0, 0, 0, 0, 0)

select (case when N1 in (select * from @WinningGame) then 1 else 0 end) as myCount
from @SuggestedGames

thoughts, help?
Thanks

A: You need a left join of @SuggestedGames to @WinningGame and aggregation:
select s.N1, s.N2, s.N3, s.N4, s.N5, s.N6,
       count(w.n1) as myCount
from @SuggestedGames s left join @WinningGame w
on w.n1 in (s.N1, s.N2, s.N3, s.N4, s.N5, s.N6)
group by s.N1, s.N2, s.N3, s.N4, s.N5, s.N6


text:
Q: Continuum Limit for this Sum Consider a sum of the form
$$
S=\sum_{\substack{k \\ k \neq k_0}} \frac{f(k)}{k-k_0},
$$
where $k$ is running over some countably infinite set of numbers and $f$ is a well behaved function, such that $S$ exists. In the problem I'm working on the $k$ are related to wavenumbers of electrons and I'm interested in a specific continuum limit of the sum.
I know that i need to transform the sum to an integral and multiply the integrand by a function $g(k)$ (that is known to me), that contains amongst other things the density of states for my problem.
Now i get confused about how to translate the condition $k \neq k_0$ into
"integral language", because simply ignoring the condition leads to a divergent integral.
Any help would be much appreciated.


text:
Q: How does the functions differ from objects in Javascript? I have this habit of using function id(_id) { return document.getElementById(_id); } as to lessen the work of typing this over and over.
sidenote:

jquery becomes too heavy for small tasks and projects

As I  learnt Javascript more I came to know that we can pass around functions just like objects so we can do
var id = document.getElementById;

It seems like both do the exact same thing. However, I am not an expert in Javascript, so could there be any difference internally? and which is the preferred way of using?

A: Yes, the context is:
const log = console.log;

log("test");

The upper wont work because the context changed, and log must be called on a console object, not on window ( aka without context). However, there are easy workarounds:
const log = console.log.bind(console);

Or you use functions, for example the arrow ones:
const log = (...args) => console.log(...args);


text:
Q: Two different set of discounts that should be applied with respect to 2 different categories in woocommerce This is WordPress website integrated with woocommerce. In this store, they are two main categories Category1 and Category2.
I want to make two different set of discounts that should be applied with respect to 2 different categories.
For instance:
Scenario For Category 1:

*

*Buy $500-$999 and get 5% Discount

*Buy $1000-$2000 and get 15% Discount

*Buy $2001-$5000 and get 25% Discount

Scenario For Category 2:

*

*Buy $500-$999 and get 20% Discount

*Buy $1000-$2000 and get 40% Discount

*Buy $2001-$5000 and get 60% Discount

Consider if I buy the product1 & product2 from Category1 worth $1000 and product5 & product6 from Category2 worth $4000.
So the summary cart should show like below:
    Cart subtotal:                       $5000
    Category 1 Discount (15%) of $1000: -$150
    Category 2 Discount (60%) of $4000  -$2400
    Amount to Pay:                       $2450

The discount should be applied based on the subtotal of each category. I have tried many plugins and customized the code and I could not achieve the functionality in woocoomerce.
Could you please suggest any plugins or custom code to acheive this functionality?
UPDATE:
I have tried the below code based on the thread Auto apply a percentage or fixed cart discount based on the total in WooCommerce.
Tried to apply progressive discount based on 2 conditions.

*

*Based on the cart value

*With respect to specific category.

But the code tried is not working. What I need to change in this code? I need to set the progressive discount for 2 different categories.
add_action( 'woocommerce_cart_calculate_fees', 'cart_items_quantity_wise_discount', 10, 1 );

    function cart_items_quantity_wise_discount($cart_object) {

        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;

        // Set HERE your category (can be an ID, a slug or the name)
        $category = '224'; // our category id

        $category_count = 0;
        $category_total = 0;
        $discount = 0;

        // Iterating through each cart item
        foreach($cart_object->get_cart() as $cart_item):
        //print_r($cart_item);exit;
            if( has_term( $category, 'product_cat', $cart_item['product_id']) ):
                $category_count += $cart_item['quantity'];
                $category_total += $cart_item["line_total"]; // calculated total items amount (quantity x price)
            endif;

        endforeach;

        $discount_text = __( 'Quantity discount of ', 'woocommerce' );

        if ( $category_total >=2000 && $category_total <=2999 ) {
            $discount -= $category_total * 0.3; // Discount of 10%
            $discount_text_output = $discount_text . '10%';
        }
        elseif ( $category_total >=3000 && $category_total <=4999 ) {
            $discount -= $category_total * 0.15; // Discount of 15%
            $discount_text_output = $discount_text . '15%';
        }
    // Adding the discount
        if ( $discount != 0 && $category_count >= 12 )
            $cart_object->add_fee( $discount_text_output, $discount, false );

        // Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
    }

SECOND UPDATE (version 2) - I have tried the below code. But category wise discount not affected on my checkout page. Could you please look into this and what i am doing wrong in this code?
add_action( 'woocommerce_cart_calculate_fees', 'cart_items_quantity_multiple_discounts', 10, 1 );
function cart_items_quantity_multiple_discounts( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE set your 2 product category term names
    $category1 = 'Appliances';
    $category2 = 'Electronics';

    $total1 = $total2 = $percentage1 = $percentage2 = 0;

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ) {
        if( has_term( $category1, 'product_cat', $cart_item['product_id']) ) {
            $total1 += $cart_item["line_total"]; // Excluding taxes
        } elseif( has_term( $category2, 'product_cat', $cart_item['product_id']) ) {
            $total2 += $cart_item["line_total"]; // Excluding taxes
        }
    }

    // All Amounts need to be set without taxes

    // First category "Appliances" progressive percentage discount
    if ( $total1 >= 1000 && $total1 < 1500 ) { // <== set excluding taxes
        $percentage1 = 5;
    }elseif ( $total1 >= 1500 && $total1 < 2500 ) { // <== set excluding taxes
        $percentage1 = 10;
    }elseif ( $total1 >= 2500 ) { // <== set excluding taxes amounts
        $percentage1 = 15;
    }

    // Second category "Electronics" progressive percentage discount
    if ( $total2 >= 1000 && $total2 < 1500 ) { // <== set excluding taxes amounts
        $percentage2 = 10;
    }elseif ( $total2 >= 1500 && $total2 < 2500 ) { // <== set excluding taxes amounts
        $percentage2 = 15;
    }elseif ( $total2 >= 2500 ) { // <== set excluding taxes amounts
        $percentage2 = 20;
    }

    // Set the first discount for "Appliances"
    if( $percentage1 > 0 ){
        $discount1   = $total1 * $percentage1 / 100;
        $label_text1 = sprintf( __( '%s Discount (%s) of %s', 'woocommerce' ),
            $category1, $percentage1 . '%', strip_tags(wc_price($total1)));
        $cart->add_fee( $label_text1, -$discount1 );
    }

    // Set the Second discount for "Electronics"
    if( $percentage2 > 0 ){
        $discount2   = $total2 * $percentage2 / 100;
        $label_text2 = sprintf( __( '%s Discount (%s) of %s', 'woocommerce' ),
            $category2, $percentage2 . '%', strip_tags(wc_price($total2)));
        $cart->add_fee( $label_text2, -$discount2 );
    }

    // Note: Last argument "taxable" in add_fee() method is always true for negative fees (discounts)
}

A: @Vinayagam - Please use the below code in your child theme functions.php. I have tested and working fine.
    add_action( 'woocommerce_cart_calculate_fees', 'cart_items_quantity_multiple_discounts', 10, 1 );

    function cart_items_quantity_multiple_discounts( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;

        // HERE set your 2 product category term names
        $category1 = 250;//Appliances
        $category2 = 224;//Electronics

        $pdt_id_1 = $pdt_id_2 = $total1 = $total2 = $percentage1 = $percentage2 = 0;
        //$pdt_id_1 - Category One;
        //$pdt_id_2 - Category Two;
enter code here
        // Loop through cart items
        foreach( $cart->get_cart() as $cart_item ) {
            $_product = $cart_item['data'];
            $terms = get_the_terms( $_product->id, 'product_cat' );
            foreach ($terms as $term) {
                $_categoryid = $term->parent;
                if ( $_categoryid === $category1 and $pdt_id_1!=$_product->id) {
                    $total1 += $cart_item["line_total"];
                    $pdt_id _1= $_product->id;
                }
                else if ( $_categoryid === $category2 and $pdt_id_2!=$_product->id) {
                    $total2 += $cart_item["line_total"];
                    $pdt_id_2 = $_product->id;
                }
            }
        }

        // All Amounts need to be set without taxes

        // First category "Appliances" progressive percentage discount
        if ( $total1 >= 2000 && $total1 <= 2999 ) {
            $percentage1 = 3;
        }elseif ( $total1 >= 3000 && $total1 <= 4999 ) {
            $percentage1 = 5;
        }elseif ( $total1 >= 5000 && $total1 <= 9999) {
            $percentage1 = 8;
        }elseif ( $total1 >= 10000 && $total1 <= 14999) {
            $percentage1 = 10;
        }elseif ( $total1 >= 15000 && $total1 <= 24999) {
            $percentage1 = 13;
        }elseif ( $total1 >= 25000 && $total1 <= 29999) {
            $percentage1 = 15;
        }elseif ( $total1 >= 30000 && $total1 <= 49999) {
            $percentage1 = 18;
        }elseif ( $total1 >= 50000 && $total1 <= 59999) {
            $percentage1 = 19;
        }elseif ( $total1 >= 60000 && $total1 <= 499999) {
            $percentage1 = 20;
        }

        // Second category "Electronics" progressive percentage discount
        if ( $total2 >= 2000 && $total2 <= 2999 ) {
            $percentage2 = 5;
        }elseif ( $total2 >= 3000 && $total2 <= 4999 ) {
            $percentage2 = 10;
        }elseif ( $total2 >= 5000 && $total2 <= 9999 ) {
            $percentage2 = 15;
        }elseif ( $total2 >= 10000 && $total2 <= 14999 ) {
            $percentage2 = 20;
        }elseif ( $total2 >= 15000 && $total2 <= 24999 ) {
            $percentage2 = 25;
        }elseif ( $total2 >= 25000 && $total2 <= 29999 ) {
            $percentage2 = 30;
        }elseif ( $total2 >= 30000 && $total2 <= 49999 ) {
            $percentage2 = 40;
        }elseif ( $total2 >= 50000 && $total2 <= 59999 ) {
            $percentage2 = 45;
        }elseif ( $total2 >= 60000 && $total2 <= 499999 ) {
            $percentage2 = 50;
        }

        // Set the first discount for "Appliances"
        if( $percentage1 > 0 ){
            $discount1   = $total1 * $percentage1 / 100;
            $label_text1 = sprintf( __( '%s Discount (%s) of %s', 'woocommerce' ),
                'Appliances', $percentage1 . '%', strip_tags(wc_price($total1)));
            $cart->add_fee( $label_text1, -$discount1, true, '');
        }

        // Set the Second discount for "Electronics"
        if( $percentage2 > 0 ){
            $discount2   = $total2 * $percentage2 / 100;
            $label_text2 = sprintf( __( '%s Discount (%s) of %s', 'woocommerce' ),
                'Electronics', $percentage2 . '%', strip_tags(wc_price($total2)));
            $cart->add_fee( $label_text2, -$discount2 );
        }
        // Note: Last argument "taxable" in add_fee() method is always true for negative fees (discounts)
    }


text:
Q: What is a better way to inference on chained machine learning models? I'm trying to figure out a better way to make inference for my audio gender classification models.
I have created 2 models: (1) model1 predicts adult/child, (2) model2 predicts male/female.
My current approach is:

*

*predict using model1, if "child", done, else continue

*predict using model2, get "male" or "female"

If my model1 has an accuracy (on validation) of 85% and my model2 has an accuracy of 93%, then this is the expected accuracyfor my approach:

*

*child:
$$P(model1\_correct) = 0.85 = 85\%$$

*male/female
$$P(model2\_correct | model1\_correct) = \frac{0.93\times0.85}{0.85} = 0.93$$
since two models are independent though chained
$$P(model2\_correct) = P(model2\_correct | model1\_correct)P(model1\_correct)=0.93 * 0.85 = 0.79$$
Is the calculation above reasonable? However, in this way, my male/female confidence is much lower after adding child. Is there a better way I can use those 2 models for the 3-class classification?


text:
Q: How to set Django channels self.scope["user"] with Javascript (React) I am using the following technologies:
Django Channels 2.1.2, ReactJS + reconnecting-websocket package
For consumers.py
class ChatConsumer(AsyncConsumer):
    async def websocket_connect(self, event):
        me = self.scope['user']
        print(str(self.scope['user']))

For routinig.py
application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                [
                    url(r"^chat/(?P<user_id>[0-9]+)/$", ChatConsumer),
                ]
            )
        )
    )
})

For ReactJS, I'm connecting with the socket with
import ReconnectingWebSocket from 'reconnecting-websocket'

...

const rws = new ReconnectingWebSocket('ws://127.0.0.1:8000/chat/30/')

But Django is not picking up any user in scope?
For React, I'm storing user and token in cookies.
I believe it's a ReactJS fault but can somebody please help me out? Thanks!


text:
Q: How to use ef core in a static class with ConcurrentQueues? there will be multi request to one action .So I created a static class which has ConcurrentQueue to process the data.
but I can not use ef core in it.because it is static class.
and I have to save data and re-read data per request.
otherwise the data will be wrong.

A: Static class is 100% out. You can't get it done. However, there's probably no need for an actual static class here. You should instead use a normal class, register it as a singleton, and then inject it where you need it. The context is a scoped service, so you still cannot directly inject it into the class, but you can inject IServiceProvider and use the service-locator pattern:
using var scope = _serviceProvider.CreateScope();
using var context = scope.ServiceProvider.GetRequiredService<MyContext>();
// do something with context

It's important to note that you can only use the context in within the scope of which it's defined. You cannot do something like a set a field or property on the class with it. You'll have to use the above code within each method that needs to use the context within the class.


text:
Q: What package replaces dkim-filter in 12.04? Previously, I was using the dkim-filter package in Ubuntu 10.04 LTS for DKIM.
That package is no longer in Ubuntu 12.04 LTS.  What's the replacement or alternative?
opendkim, maybe?

A: According to the SourceForge website:

dkim-milter has been replaced by OpenDKIM

Indeed - the project has now states:

As of 2011-12-13, this project is no longer under active development.

You are quite correct - OpenDKIM is its replacement - its a fork of dkim
More information about the OpenDKIM filter is in the README file.
The version in Precise is slightly older then than the Project site - v2.5.0 vs 2.5.1  respectively.


text:
Q: Same button outputting different sounds This is the code I have at the moment.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_earthbound);

    int charNo = (Integer)getIntent().getExtras().get(EXTRA_CHARNO);
    Earthbound character = Earthbound.chars[charNo];

    ImageView photo = (ImageView) findViewById(R.id.photo);
    photo.setImageResource(character.getImageResourceId());
    photo.setContentDescription(character.getName());

    TextView name = (TextView) findViewById(R.id.name);
    name.setText(character.getName());

    TextView desc = (TextView) findViewById(R.id.desc);
    desc.setText(character.getDesc());

    Button voice_btn = (Button)this.findViewById(R.id.voice_btn);
    voice_btn.setContentDescription(character.getName());
    final MediaPlayer mp = MediaPlayer.create(this, R.raw.snd_se_narration_characall_Ness);
    final MediaPlayer mmp = MediaPlayer.create(this, R.raw.snd_se_narration_characall_Lucas);
    voice_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            mp.start();
            mmp.start();
        }
    });

I essentially have two activities, the first one being that the user can choose the list view option "Earthbound", a Java class which lists the characters, and an activity displaying the characters bio. The second activity has one button, but this button will change sounds depending on which character the user picked. This is where I am stuck.
This is the Java class if it helps:
private String name;
private String desc;
private int imageResourceId;
private int voiceId;

public Earthbound(String name, String desc, int imageResourceId, int voice){
    this.name = name;
    this.desc = desc;
    this.imageResourceId = imageResourceId;
    this.voiceId = voiceId;
}
public static final Earthbound[] chars = {
        new Earthbound("Ness", "Ness is the silent main protagonist of EarthBound (Mother 2 in Japan), " +
                "and is analogous to Ninten and Lucas in their respective games. He greatly enjoys baseball; " +
                "not only are most of his weapons various types of baseball bats, " +
                "but he can also equip several baseball caps. ", R.drawable.ness, R.raw.snd_se_narration_characall_Ness),
        new Earthbound("Lucas", "Lucas is the central character of Mother 3, out of seven main characters total. " +
                "(Lucas, Kumatora, Duster, Boney, Claus, Flint, and Salsa). He is from Tazmily Village. " +
                "He is the gentle twin of Claus. ", R.drawable.lucas, R.raw.snd_se_narration_characall_Lucas),
};

public String getName() {
    return name;
}

public String getDesc() {
    return desc;
}

public int getImageResourceId() {
    return imageResourceId;
}

@Override
public String toString() {
    return this.name;
}

public int getVoiceId() {
    return voiceId;
}

A: Can't you just use an if or switch statement to determine which sound plays?
if ((character.getName().compareTo("Ness")) == 0)
            mp.start();
else
            mmp.start();

something like this ought to work.

A: If you just need choose a sound to play, you can set your sound resource to you Earthbound, Others use your code and need not know which resource to selected.
private String name;
private String desc;
private int imageResourceId;
private int voiceId;

public Earthbound(String name, String desc, int imageResourceId, int voice){
    this.name = name;
    this.desc = desc;
    this.imageResourceId = imageResourceId;
    this.voiceId = voiceId;
}
public static final Earthbound[] chars = {
        new Earthbound("Ness", "Ness is the silent main protagonist of EarthBound (Mother 2 in Japan), " +
                "and is analogous to Ninten and Lucas in their respective games. He greatly enjoys baseball; " +
                "not only are most of his weapons various types of baseball bats, " +
                "but he can also equip several baseball caps. ", R.drawable.ness, R.raw.snd_se_narration_characall_Ness),
        new Earthbound("Lucas", "Lucas is the central character of Mother 3, out of seven main characters total. " +
                "(Lucas, Kumatora, Duster, Boney, Claus, Flint, and Salsa). He is from Tazmily Village. " +
                "He is the gentle twin of Claus. ", R.drawable.lucas, R.raw.snd_se_narration_characall_Lucas),
};

public String getName() {
    return name;
}

public String getDesc() {
    return desc;
}

public int getImageResourceId() {
    return imageResourceId;
}

@Override
public String toString() {
    return this.name;
}

public int getVoiceId() {
    return voiceId;
}

public int getMediaResourceId() {
    return TextUtils.equals(name, "Ness") ? R.raw.snd_se_narration_characall_Ness : R.raw.snd_se_narration_characall_Lucas;
}

Then
final MediaPlayer mp = MediaPlayer.create(this, character.getMediaResourceId());
voice_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            mp.start();
        }
    });


text:
Q: What does "? :" mean? I have a generic JS question that I'm not even sure how to put it.
In what cases do you use the following code structure? What does it mean (or use does this have)? And what is this practice called?
x1 = x2 ? x3 : x4;

Can you give references, examples and possibilities please?

A: the following thing
  if(x>10)
  {
      y=10;
  }
  else
  {
      y=9;
  }

can be written as
  (x>10) ? y=10 : y=9;

I think now you understood

A: if x2 is false, x1 = x4
if x2 is true, x1 = x3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

A: In expanded code this says:
if(x2){
    x1 = x3;
}
else{
    x1 = x4
}

If you're familiar with the ternary operator (if not, look it up) then this might make a lot more sense.
x1 = (x2 ? x3 : x4);

A: It's called the ternary operator. It is a shorthand of if-else. It is used in many high-level programming languages.
x1 = x2 ? x3 : x4;

the above code can be expanded to:
x1 = undefined;

if (x2) {
    x1 = x3;
} else {
    x1 = x4;
}

A: This is a ternary operator.
if X1 = X2 ,   X1 takes the value X3 else X1 takes the value X4.

A: ? : is a 'ternary operator'; it takes three arguments. The first argument is a test, the second argument is return value if test was true, and the third is a return value if the test was false.
so 1 === 1 ? 'foo' : 'bar' would return 'foo' and 1 === 0 ? 'foo' : 'bar' would return 'bar'. This can always be replaced with an if..else structure, but given its short form it can keep your code uncluttered.
If the test and return values are very complex in form, I would use the more "traditional" if..else structure.


text:
Q: How does evaluate pointers and reinterpret_cast? I have the following code that I run in Visual Studio. The address of c is the same as the address to which points pa but not the same as pb. Yet both ternary operator will evaluate as true, which is what would have expected by only viewing the code and not see the pointed addresses for pa and pb in debugger.
The third ternary operator will evaluate as false.
#include <iostream>

class A
{
public:
    A() : m_i(0) {}

protected:
    int m_i;
};

class B
{
public:
    B() : m_d(0.0) {}

protected:
    double m_d;
};

class C
    : public A
    , public B
{
public:
    C() : m_c('a') {}

private:
    char m_c;
};

int main()
{
    C c;
    A *pa = &c;
    B *pb = &c;

    const int x = (pa == &c) ? 1 : 2;
    const int y = (pb == &c) ? 3 : 4;
    const int z = (reinterpret_cast<char*>(pa) == reinterpret_cast<char*>(pb)) ? 5 : 6;

    std::cout << x << y << z << std::endl;

    return 0;
}

How does this work?

A: pa and pb are actually different. One way to test that is:
reinterpret_cast<char*>(pa) == reinterpret_cast<char*>(pb)

pa == &c and pb == &c both return true, but that does not mean the above must be true. &c will be converted to appropriate pointer type (A* or B*) via implicit pointer conversion. This conversion changes the pointer's value to the address of respective base class subobject of the object pointed-to by &c.
From cppreference:

A prvalue pointer to a (optionally cv-qualified) derived class type can be converted to a prvalue pointer to its accessible, unambiguous (identically cv-qualified) base class. The result of the conversion is a pointer to the base class subobject within the pointed-to object. The null pointer value is converted to the null pointer value of the destination type.

(emphasis mine)

A is the first non-virtual base class of C, so it is placed directly at the beginning of C's memory space, i.e.:
reinterpret_cast<char*>(pa) == reinterpret_cast<char*>(&c)

is true. But, B subobject is laid out after A, so it can not possibly satisfy the above condition. Both implicit conversion and static_cast then gives you the right address of the base subobject.

A: A C instance has an A subobject and a B subobject.
Something like this:
    |---------|
    |---------|
    |    A    |
    |---------|
 C: |---------|
    |    B    |
    |---------|
    |---------|

Now,
A *pa = &c;

makes pa point to the location of the A subobject, and
B *pb = &c;

makes pb point to the location of the B subobject.
    |---------|
    |---------| <------ pa
    |    A    |
    |---------|
 C: |---------| <------ pb
    |    B    |
    |---------|
    |---------|

When you compare pa and pb to &c, the same thing happens - in the first case, &c is the location of the A subobject and in the second it's the location of the B subobject.
So the reason that they both compare equal to &c is that the expression &c actually has different values (and different types) in the comparisons.
When you reinterpret_cast, no adjustment takes place - it means "take the representation of this value and interpret it as representing a value of a different type".
Since the subobjects are in different locations, the results of reinterpreting them as locations of a char are also different.

A: If you add some extra output, you can see what is going on;  I added the following line:
std::cout << "pa: " << pa << "; pb: " << pb << "; c: " << &c <<  std::endl;

The output of this will vary of course, since I am printing the values of the pointers, but it will look like:
pa: 0x1000 pb: 0x1008 c: 0x1000

The pb pointer is in fact pointing at pa + sizeof(int) (which on my 64 bit machine is 8 bytes).  This is because when you do:
B *pb = &c;

The compiler is casting the C object to a B, and will return you the value of the B variable.  The confusion is that your second ternary operator shows true.  This is (I am assuming) because the address of B is within the bounds of the address of C.

A: You're comparing the address pa and pb pointing to directly, they're different because A and B are both base class of C, and pa is pointing to the base class subobject A of c, pb is pointing to the base class subobject B of c, the actual memory address will be different. They can't/shouldn't point to the same memory address.


text:
Q: Camera options definitions not recognized in ionic app I am using the Cordova camera plugin into a Ionic app,
if I define the options parameters using the definitions as for example:
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,

the ionic -serve -l doesn't work, it displays 2 empty devices (iOS, Android) in the browser,
if I use the corresponding numbers instead of symbols (0 for destinationType, 1 for sourceType) it works (and even the ionicview app works fine with the camera).
What can be the problem?

A: The solution, as indicated by a classmate of the Multiplatform Mobile App Development with Web Technologies course on Coursera, is to put under condition the section where the definitions are referred as follows:
if (typeof Camera !== "undefined") {
  // Provided code here :
  var cameraOptions = { ...Camera.DestinationType.DATA_URL };
  $scope.takePicture = function() { ... }
} else {
  // Alternate version if the camera is unavailable
  $scope.takePicture = function() {
    console.log("Camera unavailable");
  }
}


text:
Q: Want to show all elements at once in plot, but this doesn't Currently I try to show result of my Random Number Generator on plot, but it come out with different plots, not at once. Please see my code:
import matplotlib.pyplot as plt
import random

global rand
rand = 1

def lcg():
    a = 65539
    c = 0
    m = (2**31)
    global rand
    rand = (a*rand + c) % m
    return rand

for i in range(10000):
    plt.plot(rand, lcg(), 'o')
    plt.show()
    continue

I'm not that good in programming, so I couldn't understand the reason. It will be really helpful if you teach me the reason.

A: plot.show after the for loop to have one graph with all the required points
import matplotlib.pyplot as plt
import random

global rand
rand = 1

def lcg():
    a = 65539
    c = 0
    m = (2**31)
    global rand
    rand = (a * rand + c) % m
    return rand

for i in range(100):
    print (rand, lcg())
    plt.plot(rand, lcg(), 'o')
    continue
plt.show() # show outside for loop for one graph with all plots

since every time you call plot.show() it will display a graph, so if you ran your code you would have to close each window 10000 times to view each point.


text:
Q: Using Firebase user UID with vuefire manual binding In a simple SPA with Vue and Firebase, there are two routes: Login and Chat.
Upon login, the user is redirected to the Chat route where Firebase database bindings are done manually using vuefire's $bindAsArray(), inside the created() life-cycle hook. This is because the bindings require the uid assigned by the Firebase authentication to be available.
This works fine, until the user refreshes the page. If auth().currentUser is used to get the uid, it returns null. If the auth().onAuthStateChanged() watcher is used, Vue attempts to render the component before the Firebase database bindings are done. What am I missing?

A: I come across this scenario, as workaround I use component wrapper that has UID as property, if UID is null show a waiting message/animation else show your original component.
My real scenario is a little more complex to post it here (firebase, routing, vuex) but basically that wrapper component should look similar to this
<template>
<component :is="CurrentComponent" />
</template>

<script>
import App from './App';
import WaitingAnimation from './WaitingAnimation';

export default {
  data() {
    return {
      Uid: null,
    }
  },
  computed: {
    CurrentComponent() {
      return this.Uid == null ? WaitingAnimation : App;
    }
  }
  beforeMount() {
    //While Firebase is initializing `Firebase.auth().currentUser` will be null
    let currentUser = Firebase.auth().currentUser;

    //Check currentUser in case you previously initialize Firebase somewhere else
    if (currentUser) {
      //if currentUser is ready we just finish here
      this.Uid = currentUser.uid;
    } else {
      // if currentUser isn't ready we need to listen for changes
      // onAuthStateChanged takes a functions as callback and also return a function
      // to stop listening for changes
      let authListenerUnsuscribe = Firebase.auth().onAuthStateChanged(user => {
        //onAuthStateChanged can pass null when logout
        if (user) {
          this.Uid = user.uid;
          authListenerUnsuscribe(); //Stop listening for changes
        }
      });
    }
  }
}
</script>


text:
Q: Unable to save my admin.py changes in my model I am pretty new to django. I am trying to save my admin.py list_editable changes in my model for the following field foodQuality. I am using 'def clean(self):' in my model for validationError and if there is no validation error. I need to save my changes. But it is not saving the right decimal value i recently entered.I tried using self.cleaned_data I m geting the following error 'object has no attribute 'cleaned_data'
class DashBoard(models.Model):
    """Dashboard to be used to upload all my items"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    title = models.CharField(max_length = 255, null = True)
    tranScription = models.CharField(max_length = 255, null = True)
    videoUrl = models.CharField(max_length = 255, null = True)
    audioUrl = models.CharField(max_length = 255, null = True)
    imageUrl = models.CharField(max_length = 255, null = True)
    foodQuality = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00))
    ambience = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00))
    cleanliness = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00))
    mediaType = models.CharField(max_length = 255, default ='mp4')
    date = models.CharField(max_length = 255, default= datetime.today().strftime("%Y-%m-%d"))
    isUploaded = models.BooleanField(max_length = 255, default = False)

    def clean(self):
        if foodQuality < 0 or foodQuality > 1:
           raise ValidationError(u'%s is not between 0 and 1' % value)

    def __str__(self):
        return self.title

class DashBoardModel(admin.ModelAdmin):
     model = models.DashBoard
     actions = ['delete_model']
     ordering = ['id']
     list_display = ['title',
                     'tranScription',
                     'foodQuality',
                     'ambience',
                     'cleanliness',
                     'videoUrl',
                     'audioUrl',
                     'imageUrl',
                     'mediaType',
                     'date',
                     'isUploaded']

     """ Following fields are made editable """
     list_editable = ('foodQuality', 'ambience', 'cleanliness')

     """ Below provides Link field in admin panel. Made Clickable"""
     list_display_links = ('videoUrl', 'imageUrl', 'audioUrl')

     """ Below provides searchFields against which search is made"""
     search_fields = ('title',
                      'mediaType',
                      'tranScription',
                      'foodQuality',
                      'ambience',
                      'cleanliness')

     fieldsets = (
         (
             ('Permissions'),
             {'fields': ('is_active', 'is_staff', 'is_superuser')}
         ),
         (
             ('Important dates'), {'fields': ('last_login',)}
         )
     )

     def delete_queryset(self, request, queryset):
         queryset.delete()

     def VIDEOURL(self, obj):
        return format_html("{url}", url=obj.firm_url)

admin.site.register(models.User, UserAdmin)
admin.site.register(models.DashBoard, DashBoardModel)


text:
Q: How can I add data in nunjucks? I want to show the answer for adding two data values that a user has entered in the front end, in nunjucks.
I've tried:
{{data['firstanswer'] + data['secondanswer']}}
And
{% set total = (data['firstanswer'] + data['secondanswer'] %} {{total}}
I keep getting 22 for a sum like 2+2, but * and / works fine.
I've followed https://mozilla.github.io/nunjucks/templating.html#math


text:
Q: Draw WFS with latlong coordinates to canvas in Java I am very new to Java programming, I would appreciate any kind of help.
So I want to display a set of lat-long coordinates (more than 50 coordinates) in Java-based canvas (e.g JFrame, Processing) from a WFS server. I have managed to parse lat-long value and print it to the console. Now I'm stuck in how to bring the lat-long coordinates to the screen coordinates (I'd like to draw it on 1000x500 size). I've tried to search for the reference but couldn't find the simplest one for a beginner like me. Here is the current part of my code :
String[] splitc = coord.split(",");
                    String lon = splitc[0];
                    String lat = splitc[1];
                    //parse string to float
                    float loncoord=Float.parseFloat(lon);
                    float latcoord=Float.parseFloat(lat);

*

*Can I transfer the coordinates from the WFS to screen coordinates using world2screen.translate of Geotools library as in https://docs.geotools.org/latest/userguide/library/referencing/axis.html ?

*In processing, there is a map() function (https://processing.org/reference/map_.html) to transfer from a range to another. I've tried it but it didn't work on my IDE.

*One super noob question, I'm trying to store the WFS connection in a function so I can call it in another class, should I store it in static void or use "return"?

If someone can provide an example of a similar task, that would be very helpful. Thanks (Sara)

A: *

*You can use this formula instead:
float x = ((WIDTH/360.0) * (180 + loncoord));
float y = ((HEIGHT/180.0) * (90 - latcoord));

*It should work... Note that it returns a float and takes 5 arguments of the form:
map(input, inputMin, inputMax, outputMin, outputMax)

*You only want to create the connection once, so you're left with two viable options: defining the connection as a static variable of a static class, or defining the connection as an instance variable of a class following the singleton pattern.
Assuming you chose the former approach, the method that returns the connection variable should therefore be static but not void:
public static connectionType getConnection() {
    return connectionObject;
}

... where connectionType is the datatype of the connection.

A: The easiest way is to create a GeoTools WFSDataStore, this code builds up the getCapabilities string if the user has given just a URL to the service endpoint and handles authentication if needed. The datastore is stored in a field of the class:
  public FetchWFS(String url, String user, String passwd) throws IOException, URISyntaxException {
    if (!user.isEmpty()) {
      auth = true;
    }
    baseURL = new URL(url);
    List<NameValuePair> nvp = URLEncodedUtils.parse(baseURL.toURI(), "UTF-8");
    NameValuePair service = new BasicNameValuePair("service", "wfs");
    NameValuePair request = new BasicNameValuePair("request", "getCapabilities");
    NameValuePair version = new BasicNameValuePair("version", "2.0.0");
    HashMap<String, NameValuePair> parts = new HashMap<>();
    parts.put(service.getName(), service);
    parts.put(request.getName(), request);
    parts.put(version.getName(), version);
    for (NameValuePair part : nvp) {

      if (part.getName().equalsIgnoreCase("SERVICE")) {
        // We don't care what they think this should be
      } else if (part.getName().equalsIgnoreCase("REQUEST")) {
        // This must be getCapabuilities so we ignore them
      } else if (part.getName().equalsIgnoreCase("VERSION")) {
        System.out.println("Changing version to " + part.getValue());
        parts.put(version.getName(), part);
      } else {
        parts.put(part.getName(), part);
      }
    }

    URIBuilder builder = new URIBuilder();
    builder.setScheme(baseURL.getProtocol());
    builder.setHost(baseURL.getHost());
    builder.setPort(baseURL.getPort());
    builder.setPath(baseURL.getPath());
    List<NameValuePair> p = new ArrayList<>();
    p.addAll(parts.values());
    builder.setParameters(p);
    // builder.addParameter("viewparams", "q:\"mySolrQuery\"");
    URI uri = builder.build();
    System.out.println(uri);
    baseURL = uri.toURL();
    // fetch the DataStore
    Map<String, Object> params = new HashMap<>();
    params.put(WFSDataStoreFactory.URL.key, baseURL);
    // params.put(WFSDataStoreFactory.WFS_STRATEGY.key, "mapserver");
    if (auth) {
      params.put(WFSDataStoreFactory.USERNAME.key, user);
      params.put(WFSDataStoreFactory.PASSWORD.key, passwd);
    }
    // params.put(WFSDataStoreFactory.WFS_STRATEGY.key, "mapserver");
    datastore = DataStoreFinder.getDataStore(params);
  }

Once you have a DataStore (of any type) you can get a list of available
featureTypes and then add one (or more) of them to a map:
        JMapFrame frame = new JMapFrame();
        MapContent map = new MapContent();
        String[] names = datastore.getNames();
        featureSource = store.getFeatureSource(names[0]); //fetch first featureType
        schema = featureSource.getSchema();

        Style style = SLD.createSimpleStyle(schema);
        this.layer = new FeatureLayer(featureSource, style);

        map.addLayer(layer);
        frame.enableToolBar(true);
        frame.setMinimumSize(new Dimension(800, 400));
        frame.setVisible(true);

The GeoTools Quickstart Tutorial will help you get started with simple mapping, and the Map Styling tutorial will allow you to generate a prettier map when you want more than a simple black and white default map.


text:
Q: object UTF8String is not a member of package How to solve this issue when executing a Maven program from IntellijIdea (with SBT Incremental compiler):

Error:(27, 38) object UTF8String is not a member of package
  org.apache.spark.unsafe.types import
  org.apache.spark.unsafe.types.UTF8String.{fromString => toUTF8}
                                       ^
Error:(37, 14) not found: value toUTF8
        assert(toUTF8(s).toString() === s)
               ^

The project has been built successfully.


text:
Q: Ion-items inside ion-tabs disappears I have implemented ion-tabs to show my recently viewed products and search results. I am storing the recent items in localstorage and I am binding it in my html. Initially this was working fine, but the list was disappearing frequently. The list was not binding in html.
I have come across some solutions like - using $rootScope.apply(), $timeout(), etc.. I have tried everything. Now the number of disappearances has reduced. But still sometimes the list disappears.Unless I reinstall the app, the list is not getting displayed.
In my controller I am doing this :-
$scope.$on( "$ionicView.loaded", function( scopes, states ) {
    $scope.init();
});
$timeout(function() {
   $rootScope.$apply(function()
   {
       $rootScope.viewedList = JSON.parse(window.localStorage.getItem("viewedList") || "[]");
    });
}, 10);

The following code is in my html:-
  <ion-tabs class="tabs-striped tabs-top tabs-background-grey tabs-positive">
    <ion-tab title="Viewed items">
       <ion-content class="has-header has-subheader has-tabs-top padding"   style="padding:40px 0" overflow-scroll="true" has-bouncing="false">

              <ion-list>
          <ion-item  class="item item-divider" ng-click="productSearch(item.productId)">
              {{item.Description}}

                               {{item.productId}}
          </ion-item>
               </ion-list>

                <ion-item>No Viewed Items
                </ion-item>

        </ion-content>
    </ion-tab>

    <ion-tab title="Search Results">

    </ion-tab>
</ion-tabs>

Can someone please help me with this issue???

A: I fixed this issue by using 'track by'
in html I added this :-

The problem was in our app the list keeps changing and the hash value will also change. And somehow the list loses its reference. Using 'track by' solved this problem.


text:
Q: How can I configure Zenoss to send an SMS or Voice alert Has anyone successfully configured Zenoss to send an SMS or Voice alert? Googling only comes up with a service called TeamTILT for Zenoss. Is this the only alternative available? Has anyone solved this without using this service? Thanks.

A: The easiest means is to simply send an e-mail to the provider's email-to-text gateway. Which, of course, requires a working internet connection :-).

A: Note: If you want the pager field to goto someone's SMS "email" like 1235551234@vtext.com you can do the followin.
Create folder $ZENHOME/scripts/
Create the script below.
Page Command : $ZENHOME/scripts/mail.pl
File: mail.pl
#!/usr/bin/perl

my $title="Alert";
my $to=$ARGV[0];

$from= 'Zenoss';
$subject=$title;

open(MAIL, "|/usr/sbin/sendmail -t");

## Mail Header
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
## Mail Body
foreach $line ( <STDIN> ) {
    chomp( $line );
    print MAIL "$line\n";
}
close(MAIL);

As long as you have sendmail configured then you should be seeing pages.

A: I was actually able to setup the dialer zenpack at one point to dial a 56K modem and deliver SMS that way, but only T-Mobile's numbers were still working for this method. We ended up running DSL over a dedicated POTS line for this purpose.
http://community.zenoss.org/docs/DOC-5819


text:
Q: View Controllers accumulate memory even when dismissed, in Objective C I can't seem to find any resolutions to this. I've made all my objects 'weak' in both view controllers in question. I have included dismiss functions and even the 'RemoveFromSuperView' function. I tried them all without luck. I also tried making the button action 'modal', 'push', ect. None made any difference.
Essentially as I move from controllers, memory seems to just accumulate more and more. On both controllers I'm simply using WebView's. I rack up over 100MB of memory usage after some time navigating between views. Eventually the app runs out of memory and crashes.
How do I either clear all memory accumulated by the app or properly dismiss/kill all inactive View Controllers and clear all memory associated?

A: This is how you override dealloc method
- (void)dealloc {
    [_object release];
    [super dealloc];
}

where _object is whatever property you initialized.


text:
Q: Phonon videowidget on qgraphicsview I would like to place a phonon videowidget onto a qgraphicsscene so I can overlay graphics etc.  When I run the following I get the sound, but no video playing on the qgraphicsview.  Help would be appreciated as I thought I was doing as the examples show.  However, I suspect its something in how I have understood videoplayer and videowidget.
For testing I am just playing a video straight from a file.
from PySide import QtGui, QtCore
from PySide.phonon import Phonon
from window import Ui_MainWindow # main GUI window
import os, sys

class DiagramScene(QtGui.QGraphicsScene):
    InsertItem, InsertLine, InsertText, MoveItem  = range(4)

    def __init__(self):
        super(DiagramScene, self).__init__()
        self.myLineColor = QtCore.Qt.black
        self.myMode = "Start"
        self.line = None

    def mousePressEvent(self, mouseEvent):
        if (mouseEvent.button() == QtCore.Qt.LeftButton):
            if self.myMode == "Start":
                self.line = QtGui.QGraphicsLineItem(QtCore.QLineF(mouseEvent.scenePos(), mouseEvent.scenePos()))
                self.addItem(self.line)
        elif (mouseEvent.button() == QtCore.Qt.RightButton):
            self.addText("Hello")
        super(DiagramScene, self).mousePressEvent(mouseEvent)

    def mouseMoveEvent(self, mouseEvent):
        if self.line:
            newLine = QtCore.QLineF(self.line.line().p1(), mouseEvent.scenePos())
            self.line.setLine(newLine)

    def mouseReleaseEvent(self, mouseEvent):
        self.line = None
        super(DiagramScene, self).mouseReleaseEvent(mouseEvent)

class QPlayer(QtGui.QWidget):

    def __init__(self):
        super(QPlayer, self).__init__()
        media_src = Phonon.MediaSource("C:\Users\Public\Videos\Sample Videos\Wildlife.wmv")
        self.audioOuptut=Phonon.AudioOutput(Phonon.MusicCategory, self)
        self.player=Phonon.MediaObject(self)
        self.player.setCurrentSource(media_src)
        Phonon.createPath(self.player, self.audioOuptut)
        self.videoWidget=Phonon.VideoWidget(self)
        self.videoWidget.FitInView
        Phonon.createPath(self.player, self.videoWidget)
        self.player.play()

class Main(QtGui.QMainWindow):
    def __init__(self):
        super(Main, self).__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.scene = DiagramScene()
        self.scene.addWidget(QPlayer())
        self.gview = self.ui.gView
        self.gview.setScene(self.scene)

def main():
    app = QtGui.QApplication(sys.argv)
    window=Main()
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

A: Ok - think I've sorted it (to an extent).  Simple case of:
self.videoWidget.setMinimumSize(640,480)

The video doesn't really run very well - breaks up a lot but at least I can draw on it :)


text:
Q: Unable to produce graphviz in RStudio presentation I am trying to create a slide deck that is a condensed version of a more thorough RMarkdown analysis.  My graphviz plots do not render in the RStudio presentation.
The graphviz plots properly render in my RMarkdown analysis.
The following code works in RMarkdown, but not RPresentation.
DiagrammeR::grViz("
digraph rmarkdown {
A -> B
}
", height = 200)

I would have expected this diagram to render in my slide deck.  Instead I get an error:
Error in file(con, "rb") : cannot open the connection


text:
Q: How to find out user defined function in SQL server 2005? I am creating sql data dictionary.I am using sql server 2005.I wanted to know user defined function.I Expanded database.Under Programability :- Function:- table value function and scalar value function.

A: Assuming that you are asking how to list all functions programatically
SELECT SCHEMA_NAME(schema_id) AS schema_name,
       name,
       OBJECT_DEFINITION(object_id) AS definition
FROM sys.objects
WHERE type_desc IN ('SQL_SCALAR_FUNCTION','SQL_TABLE_VALUED_FUNCTION',
                  'SQL_INLINE_TABLE_VALUED_FUNCTION','CLR_TABLE_VALUED_FUNCTION')


text:
Q: Apples On Demand resources storage I have got the code for downloading on Demand resources working correctly and I can get the path where the file is currently being stored and can access. My question is if I move the file to another location would the file later get deleted as usual or does it only deletes the files if its in the default folder? I couldn't really find an answer to this question from looking in the documentation. Any help would be greatly appreciated. Thanks in advance

A: Actually you don't really know where the on demand resources are and you have no direct access to them. The whole thing is kind of a delusion. It will appear to you that they are somewhere inside your bundle, but that is not the case. You can read them but you cannot move them because you cannot access the place where they really are.
And to answer your question, no, if you were able to move them — for example if you copied them to a different location — the copies would not be the on-demand resources and would not be managed by Apple.


text:
Q: How to access local data in new apps from previously deleted app User's profile in application include some data (like history in browser or tweets in twitter).
I want to use it in new application, but user can delete old application.
What can help me to save this data without losing it when old application will be deleted and get this data when new application will be installed?
Maybe there is some ways to save data in IPhone files, but I don't want user to see it.
Thanks

A: You can save data in iCloud. Your applications can share iCloud data as long as they have the same bundle identifier prefix.
Alternatively, you can sync this data with your own (web) server.
It's up to you to write this functionality in your apps.
There is currently no shared document space on iOS. Each application is contained within a sandbox and cannot access documents stored in another application. Documents can be shared through URL schemes, but this has to be launched from the originating app to the destination app (both apps must be installed at the same time).

A: You can use iCloud data saving . iCloud uses
What happens quite easily after a restore (for example after an update) is that iTunes restores the save data for all applications, but not the applications themselves. Therefore as soon as you install them , the old save data will be available (this applies to all apps, not just games). Just by itself nothing will be saved without backup.


text:
Q: Refactor this recursive method? I'm pretty new to the idea of recursion and this is actually my first attempt at writing a recursive method.
I tried to implement a recursive function Max that passes an array, along with a variable that holds the array's size in order to print the largest element.
It works, but it just doesn't feel right!
I have also noticed that I seem to use the static modifier much more than my classmates in general...
Can anybody please provide any general tips as well as feedback as to how I can improve my code?
public class RecursiveTry{

static int[] n = new int[] {1,2,4,3,3,32,100};
static int current = 0;
static int maxValue = 0;
static int SIZE = n.length;

public static void main(String[] args){
    System.out.println(Max(n, SIZE));
}

public static int Max(int[] n, int SIZE) {
    if(current <= SIZE - 1){
        if (maxValue <= n[current]) {
            maxValue = n[current];
            current++;
            Max(n, SIZE);
        }
        else {
            current++;
            Max(n, SIZE);
        }
    }
    return maxValue;
}

}

A: Your use of static variables for holding state outside the function will be a source of difficulty.
An example of a recursive implementation of a max() function in pseudocode might be:
function Max(data, size) {
    assert(size > 0)
    if (size == 1) {
        return data[0]
    }
    maxtail = Max(data[1..size], size-1)
    if (data[0] > maxtail) {
        return data[0]
    } else {
        return maxtail
    }
}

The key here is the recursive call to Max(), where you pass everything except the first element, and one less than the size. The general idea is this function says "the maximum value in this data is either the first element, or the maximum of the values in the rest of the array, whichever is larger".
This implementation requires no static data outside the function definition.
One of the hallmarks of recursive implementations is a so-called "termination condition" which prevents the recursion from going on forever (or, until you get a stack overflow). In the above case, the test for size == 1 is the termination condition.

A: Making your function dependent on static variables is not a good idea. Here is possible implementation of recursive Max function:
int Max(int[] array, int currentPos, int maxValue) {
    // Ouch!
    if (currentPos < 0) {
        raise some error
    }
    // We reached the end of the array, return latest maxValue
    if (currentPos >= array.length) {
        return maxValue;
    }
    // Is current value greater then latest maxValue ?
    int currentValue = array[currentPos];
    if (currentValue > maxValue) {
        // currentValue is a new maxValue
        return Max(array, currentPos + 1, currentValue);
    } else {
        // maxValue is still a max value
        return Max(array, currentPos + 1, maxValue);
    }
}
...

int[] array = new int[] {...};
int currentPos = 0;
int maxValue = array[currentPos] or minimum int value;
    maxValue = Max(array, currentPos, maxValue);

A: A "max" function is the wrong type of thing to write a recursive function for -- and the fact you're using static values for "current" and "maxValue" makes your function not really a recursive function.
Why not do something a little more amenable to a recursive algorithm, like factorial?

A: "not-homework"?
Anyway. First things first. The
static int[] n = new int[] {1,2,4,3,3,32,100};
static int SIZE = n.length;

have nothing to do with the parameters of Max() with which they share their names. Move these over to main and lose the "static" specifiers. They are used only once, when calling the first instance of Max() from inside main(). Their scope shouldn't extend beyond main().
There is no reason for all invocations of Max() to share a single "current" index. "current" should be local to Max(). But then how would successive recurrences of Max() know what value of "current" to use? (Hint: Max() is already passing other Max()'s lower down the line some data. Add "current" to this data.)
The same thing goes for maxValue, though the situation here is a bit more complex. Not only do you need to pass a current "maxValue" down the line, but when the recursion finishes, you have to pass it back up all the way to the first Max() function, which will return it to main(). You may need to look at some other examples of recursion and spend some time with this one.
Finally, Max() itself is static. Once you've eliminated the need to refer to external data (the static variables) however; it doesn't really matter. It just means that you can call Max() without having to instantiate an object.

A: As others have observed, there is no need for recursion to implement a Max function, but it can be instructive to use a familiar algorithm to experiment with a new concept. So, here is the simplified code, with an explanation below:
public class RecursiveTry
{
    public static void main(String[] args)
    {
        System.out.println(Max(new int[] {1,2,4,3,3,32,100}, 0, 0));
    }

    public static int Max(int[] n, int current, int maxValue)
    {
        if(current < n.Length)
        {
            if (maxValue <= n[current] || current == 0))
            {
                return Max(n, current+1, n[current]);
            }
            return Max(n, current+1, maxValue);
        }
        return maxValue;
   }
}

all of the static state is gone as unnecessary; instead everything is passed on the stack. the internal logic of the Max function is streamlined, and we recurse in two different ways just for fun

A: Here's a Java version for you.
public class Recursion {

    public static void main(String[] args) {
        int[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        System.out.println("Max: " + max(0, data));
    }

    public static int max(int i, int[] arr) {
        if(i == arr.length-1) {
            return arr[i];
        }

        int memo = max(i+1, arr);
        if(arr[i] > memo) {
            return arr[i];
        }
        return memo;
    }
}

The recurrence relation is that the maximum element of an array is either the first element, or the maximum of the rest of the array.  The stop condition is reached when you reach the end of the array.  Note the use of memoization to reduce the recursive calls  (roughly) in half.

A: You are essentially writing an iterative version but using tail recursion for the looping.  Also, by making so many variables static, you are essentially using global variables instead of objects.  Here is an attempt at something closer to a typical recursive implementation.  Of course, in real life if you were using a language like Java that doesn't optimize tail calls, you would implement a "Max" function using a loop.
public class RecursiveTry{
  static int[] n;

  public static void main(String[] args){
        RecursiveTry t = new RecursiveTry(new int[] {1,2,4,3,3,32,100});
        System.out.println(t.Max());
  }

  RecursiveTry(int[] arg) {
    n = arg;
  }

  public int Max() {
    return MaxHelper(0);
  }

  private int MaxHelper(int index) {
    if(index == n.length-1) {
      return n[index];
    } else {
      int maxrest = MaxHelper(index+1);
      int current = n[index];
      if(current > maxrest)
        return current;
      else
        return maxrest;
    }
  }
}

A: In Scheme this can be written very concisely:
(define (max l)
    (if (= (length l) 1)
        (first l)
        (local ([define maxRest (max (rest l))])
          (if (> (first l) maxRest)
              (first l)
              maxRest))))

Granted, this uses linked lists and not arrays, which is why I didn't pass it a size element, but I feel this distills the problem to its essence. This is the pseudocode definition:
define max of a list as:
    if the list has one element, return that element
    otherwise, the max of the list will be the max between the first element and the max of the rest of the list

A: A nicer way of getting the max value of an array recursively would be to implement quicksort (which is a nice, recursive sorting algorithm), and then just return the first value.
Here is some Java code for quicksort.

A: Smallest codesize I could get:
public class RecursiveTry {
    public static void main(String[] args) {
        int[] x = new int[] {1,2,4,3,3,32,100};
        System.out.println(Max(x, 0));
    }

    public static int Max(int[] arr, int currPos) {
        if (arr.length == 0) return -1;
        if (currPos == arr.length) return arr[0];
        int len = Max (arr, currPos + 1);
        if (len < arr[currPos]) return arr[currPos];
        return len;
    }
}

A few things:
1/ If the array is zero-size, it returns a max of -1 (you could have another marker value, say, -MAX_INT, or throw an exception). I've made the assumption for code clarity here to assume all values are zero or more. Otherwise I would have peppered the code with all sorts of unnecessary stuff (in regards to answering the question).
2/ Most recursions are 'cleaner' in my opinion if the terminating case is no-data rather than last-data, hence I return a value guaranteed to be less than or equal to the max when we've finished the array.  Others may differ in their opinion but it wouldn't be the first or last time that they've been wrong :-).
3/ The recursive call just gets the max of the rest of the list and compares it to the current element, returning the maximum of the two.
4/ The 'ideal' solution would have been to pass a modified array on each recursive call so that you're only comparing the first element with the rest of the list, removing the need for currPos.  But that would have been inefficient and would have bought down the wrath of SO.
5/ This may not necessarily be the best solution. It may be that by gray matter has been compromised from too much use of LISP with its CAR, CDR and those interminable parentheses.

A: First, let's take care of the static scope issue ... Your class is defining an object, but never actually instantiating one.  Since main is statically scoped, the first thing to do is get an object, then execute it's methods like this:
public class RecursiveTry{

    private int[] n = {1,2,4,3,3,32,100};

    public static void main(String[] args){
        RecursiveTry maxObject = new RecursiveTry();
        System.out.println(maxObject.Max(maxObject.n, 0));
    }

    public int Max(int[] n, int start) {
        if(start == n.length - 1) {
            return n[start];
        } else {
            int maxRest = Max(n, start + 1);
            if(n[start] > maxRest) {
                return n[start];
            }
            return maxRest;
        }
    }

}

So now we have a RecursiveTry object named maxObject that does not require the static scope.  I'm not sure that finding a maximum is effective using recursion as the number of iterations in the traditional looping method is roughly equivalent, but the amount of stack used is larger using recursion.  But for this example, I'd pare it down a lot.
One of the advantages of recursion is that your state doesn't generally need to be persisted during the repeated tests like it does in iteration.  Here, I've conceded to the use of a variable to hold the starting point, because it's less CPU intensive that passing a new int[] that contains all the items except for the first one.


text:
Q: Limit the Length of TextView
Possible Duplicate:
Limit text length of EditText in Android

I am a textView on Activity, which is being displayed as per the parameter it is receiving from the JSON response, I need to restrict it to 12 characters only.
<TextView
    android:id="@+id/textViewName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/includeheadersetting"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="20dp"
    android:gravity="center"
    android:text="Name"
    android:textColor="#000000"
    android:textStyle="bold" />

A: Use android:maxLength="12" to limit the text length
 <TextView
            android:id="@+id/textViewName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/includeheadersetting"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="20dp"
            android:gravity="center"
            android:text="Name"
            android:maxLength="12"
            android:textColor="#000000"
            android:textStyle="bold" />

You can also use another property as follows:
android:ellipsize="end"
android:maxLines="1"

Using this property "..." will be added end of the text as follows:
"Hello How are ..." instead of "Hello How are you?"

A: Generally speaking only including android:maxLength is not considered good idea.
Use maxLength attribute, then use the android:ellipsize="marquee" to add a "..." automatically to the end of any line that has been cut-off.
<TextView
    android:id="@+id/txtView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:maxLength="10"
    android:ellipsize="marquee"/>

A: add code like
android:maxLength="12"

A: Add the following max length parameter to your text view-
android:maxLength="12"

whatever the limit you want you can replace that like instead of 12 can give 14 or whatever length you want.

A: Add android:maxLength="12" to your text view..
<TextView
            android:id="@+id/textViewName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/includeheadersetting"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="20dp"
            android:gravity="center"
            android:text="Name"
            android:textColor="#000000"
            android:textStyle="bold"
            android:maxLength="12" />


text:
Q: Is there a good way to define a Data Access Layer for getting related objects in Android? It took me about 4 hours to follow an example in a book about android, where they showed the code for just a table. I had 6 tables, so I extended the class for every table I had. Dirty but effective. The problem appeared when I was deciding how to access to related objects. For instance, I have a Piece object, which has a list of pieces (using a table which connects a piece to another piece). Well, suppose each Piece can have up to 15 (on average) of those pieces, and I need to access them as an object (not as an index).
This sort of connection was not commented in the book, and I came up with a good (yet really slow) way of getting these, by querying for the related pieces indexes, and then getting them just as a regular Piece (with a getPiece(long id) method). The big problem is that it takes about 5 seconds to load 10 Pieces with their related pieces.
I was wondering if there is an already defined Data Acces Layer styling for complex objects in Android. (I got used to the way Yii framework for PHP does)
Do you know any good implementation for getting related objects fairly fast? Thanks in advance

A: Well, it's been a long time, but I'll write what I'm using right now. It's ORMLite: It's not what I expected to be, relations are still a little pain, but hey, at least it encapsulates all the procedures.


text:
Q: "SyntaxError: Non-ASCII character '\xfe' in file" error when running python program Although I included
# -*- coding: utf-8 -*-

in the first line of the python file, I keep getting
SyntaxError: Non-ASCII character '\xfe' in file C:\Users\user\PycharmProjects\my_project\my_script.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

I use PyCharm Community Edition on Windows 7. Please help.

A: Your file is not saved as UTF-8. Most probably you have saved in some legacy 8-bit encoding (ISO-8859-1 or the like).

A: I am not sure if I totally understood your question.
But sometimes this can solve the issue:
import sys
reload(sys)
setdefaultencoding('utf-8')

Or try to open the file by applied an encoding format. for instance:
import codecs
 with codecs.open(filename, 'r3', encoding='utf-8') as fd:
     do something.

A: It file is with encoding wrong.
Change it to UTF-8 and try again.
Example in notepad ++:


text:
Q: How to change message position in magento 2 I want to show a message like error or success in below Login Button instead of page top in login page.
How to change message position in below Login Button in Magento 2?

A: Create customer_account_login.xml in your theme and move message block to customer.login.container
<move element="messages" destination="customer.login.container"/>

Full answer here: Magento 2: Change message location


text:
Q: Removing axis labels matplotlib I have this image and I don't know how to remove the axis labels from the top and right hand side.

I have tried:
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

and
ax.yaxis.set_label_position("left")
ax.xaxis.set_label_position("bottom")

and
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')

This is my code for plotting:
 ax = plt.axes(projection=ccrs.PlateCarree())

 plt.pcolormesh(reflon, reflat, par_interp, vmin=0, vmax=2, cmap=plt.cm.jet,
 transform=ccrs.PlateCarree())

 plt.colorbar()

 rowskip = 50
 colskip = 50
 plt.quiver(reflon[0::rowskip,0::colskip],reflat[0::rowskip,0::colskip],
           u[0::rowskip,0::colskip],v[0::rowskip,0::colskip],
           color='black',pivot='middle', alpha=0.7, width=0.015, units='inches',
            transform=ccrs.PlateCarree())

 ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                     linewidth=0.5, color='gray', alpha=0.5, linestyle='--')

 ax.coastlines()
 figtitle = siteid+': HS (m MSL) and Wnd: '+dstr
 ax.set_title(figtitle)

 dtlabel = datetime.date.strftime(dt,'%Y%m%d%H%M%S')
 dtlabel = dtlabel[0:8]+'_'+dtlabel[8:14]
 filenm = dtlabel+'.png'
 plt.show()
 plt.savefig(filenm,dpi=150,bbox_inches='tight',pad_inches=0.5)

Also, if you know how to make it so the east coast of the US is not red, let me know. Trying to figure that out too. Might be an issue with the data I am plotting though.

A: According to this, you could simply color the labels white by
plt.xticks(color='w') and plt.yticks(color='w')
with plt = matplotlib.pyplot

A: Found answer here  https://scitools.org.uk/cartopy/docs/v0.13/matplotlib/gridliner.html
   gl.xlabels_top = False
   gl.ylabels_right = False


text:
Q: Why are my PostgreSQL "real" data being rounded? I have a table with a column named total having the real data type.
But I'm finding that this column is being rounded when I query its value, as illustrated in the following:
SELECT total FROM data WHERE id='xe54g';
 total
---------
  105861

UPDATE data SET total=105860.5 WHERE id='xe54g';
UPDATE 1

SELECT total FROM data WHERE id='xe54g';
 total
---------
  105860

UPDATE data SET total=105860.7 WHERE id='xe54g';
UPDATE 1

SELECT total FROM data WHERE id='xe54g';
 total
---------
  105861

\d+ data
   Column  |  Type | Collation | Nullable |  Default  | Storage  | Stats target | Description
-----------+-------+-----------+----------+-----------+----------+--------------+-------------
 total     | real  |           |          | 0         | plain    |              |

How do I get it to return the full precision?  I'm using PG 11.1.

A: You can get the full precision by setting
extra_float_digits = 3

Then PostgreSQL will also display decimal digits that may contain rounding errors.
Note that real has a low number of significant digits. You'd be happier if you used double precision.


text:
Q: Error cloning Conda env arcgispro-py3 on an ArcGIS Server Whenever I try to clone the base package that comes with ArcGIS Server I get an error saying:
ERROR conda.core.link:_execute_actions(337): An error occurred while installing package 'defaults::notebook-5.7.8-py36_0'.
CondaError: Cannot link a source that does not exist. <USER>\AppData\Local\ESRI\conda\pkgs\notebook-5.7.8-py36_0\Lib\site-packages\notebook\i18n\zh_CN\LC_MESSAGES\nbjs.json

Can I install Anaconda onto the server and will this help fix the problem?