text:
Q: get hourly chart of sales of particular date in single query i am having an invoice table
i want to get the chart report of sales by hour on particular date

there is large amount of data of single days by 10 branch
i have used query of between using time slot loop but isn't working because of too much load on database due to multiple time slot & branch loop
SELECT SUM(total_payble) as totalPayble, sum(invoice_pax_no) AS TotalPax,count(invoice_id) as TotalInvoice from bkt_invoice where (invoice_created_date between '2016-09-20 17:00:00' AND '2016-09-20 18:00:00') AND invoice_is_void = 0 AND invoice_branch_id = '1'

as above query i have to fire this query 10 times for 10 branches also plus multiple time slots like from morning 7 to night 12
so is there any possibilities where i can create a query which can return the result as below in single query
Branch A

A: Given
MariaDB [sandbox]> select * from customer;
+------+------+
| id   | name |
+------+------+
|    1 | abc  |
|    2 | def  |
|    3 | ghi  |
|    4 | jkl  |
|    5 | jkl  |
+------+------+
5 rows in set (0.00 sec)

MariaDB [sandbox]> select * from bkt_invoice;
+----+------+---------------------+-------+
| id | cid  | dt                  | value |
+----+------+---------------------+-------+
|  1 |    1 | 2018-01-29 07:00:00 |    10 |
|  2 |    1 | 2018-01-29 23:00:00 |    20 |
|  3 |    1 | 2018-01-29 07:30:00 |    10 |
|  4 |    1 | 2018-01-29 11:30:00 |    10 |
|  5 |    1 | 2018-01-29 11:45:00 |    10 |
|  6 |    2 | 2018-01-29 07:30:00 |    10 |
+----+------+---------------------+-------+
6 rows in set (0.00 sec)

The inner sub query below will generate all the hours for which a bkt_invoice might exists, the outer query simply groups and sums.
select s.id,s.name,
    case s.hr
        when 7 then '07-08'
        when 11 then '11-12'
    else 'undefined'
    end as hr,
    ifnull(hour(dt),'') bhr,ifnull(sum(value),0) TotalValue,ifnull(count(b.id),0) as NofInvoices
from
(
select id, name ,hr.hr
from customer as branch
cross join
(
select 7 as hr union select 8 union select 9 union select 10 union select 11 union select 12 union
select 13 as hr union select 14 union select 15 union select 16 union select 17 union select 18 union
select 19 as hr union select 20 union select 22 union select 23 union select 24
) hr
) s
left join bkt_invoice b on b.cid = s.id and hour(dt) = s.hr
group by s.id,s.name,s.hr,hour(dt)

+------+------+-----------+-----+------------+-------------+
| id   | name | hr        | bhr | TotalValue | NofInvoices |
+------+------+-----------+-----+------------+-------------+
|    1 | abc  | 07-08     | 7   |         20 |           2 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | 11-12     | 11  |         20 |           2 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined |     |          0 |           0 |
|    1 | abc  | undefined | 23  |         20 |           1 |
|    1 | abc  | undefined |     |          0 |           0 |
|    2 | def  | 07-08     | 7   |         10 |           1 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | 11-12     |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    2 | def  | undefined |     |          0 |           0 |
|    3 | ghi  | 07-08     |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | 11-12     |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    3 | ghi  | undefined |     |          0 |           0 |
|    4 | jkl  | 07-08     |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | 11-12     |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    4 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | 07-08     |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | 11-12     |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
|    5 | jkl  | undefined |     |          0 |           0 |
+------+------+-----------+-----+------------+-------------+
85 rows in set (0.00 sec)


text:
Q: apache stop responding then crashes Apache (2.4.25 FPM/FastCGI) stop responding and crashes after a while on my wordpress multisite website.
For some reason it used to run fine several days until I changed the wordpress(mu) domain using this script github.com/interconnectit/Search-Replace-DB (probably not the reason).
When restarted it works for about an hour then choked again.
I have added a mysql slow query log but its empty.
Apache error_log has multiple errors like this one:
[Wed Sep 06 08:50:27.941819 2017] [proxy_fcgi:error] [pid 25444:tid 140610719610624] (70007)The timeout specified has expired: [client x.x.x.x:53398] AH01075: Error dispatching request to : (polling)

and occasionally this error appears too:
[Wed Sep 06 09:13:33.296777 2017] [core:notice] [pid 10710:tid 140611211331392] AH00051: child pid 25582 exit signal Segmentation fault (11), possible coredump in /opt/bitnami/apache2

another occasional error (expected due to the multiple AH01075 timeout errors):
[Mon Sep 04 20:18:58.758718 2017] [mpm_event:error] [pid 19928:tid 140675798046528] AH00484: server reached MaxRequestWorkers setting, consider raising the MaxRequestWorkers setting

Stopping mysql server kills my site but seems to keep apache working fine, at least for an hour or two that i`ve been testing.
Is 457452 value is normal for mysqld.bin in the following process list? (ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS)
2128 /sbin/init
2400 php-fpm: master process (/opt/bitnami/php/etc/php-fpm.conf)
3840 -bash
4244 sshd: ubuntu [priv]
6928 /usr/bin/gonit
11036 /opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf -DDISABLE_BANNER
11320 /opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf -DDISABLE_BANNER
11364 /opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf -DDISABLE_BANNER
11592 /opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf -DDISABLE_BANNER
20592 /opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf -DDISABLE_BANNER
57668 php-fpm: pool wordpress
57716 php-fpm: pool wordpress
65252 php-fpm: pool wordpress
67608 php-fpm: pool wordpress
68776 php-fpm: pool wordpress
457452 /opt/bitnami/mysql/bin/mysqld.bin --defaults-file=/opt/bitnami/mysql/my.cnf --basedir=/opt/bi

PHP Version 5.6.30
mysql.bin Ver 14.14 Distrib 5.6.36
Ubuntu 14.04.5 (bitnami image on AWS)
Memory usage while apache not responding: used:883mb of 992mb
php.ini script memory_limit = 128M

A: Was a bit long to put it in a comment, so replying as an answer.
Are you logging any php errors? From what you presented so far, my theory would be that:

*

*You used that script to do a search & replace of db but it executed poorly causing malformed or corrupted data.

*That caused your php scripts that rely on mysql to go haywire due to malformed or corrupted data.

*Because your php on fcgi isn't responding, your apache waits for it and holds onto the resources.

*All the requests are hanging and now you run out of resources and start seg-faulting.

*And then stupid apache, seeing that you're out of child count asks you to raise it not realizing you're already exhausted on physical resource beyond reason. Typical apache...

*Because apache is now out of free children, it can't take anymore requests and it appears as if all of apache is broken even though it's merely clogged up by bad fcgi processes.

If my theory is correct, you should.

*

*Check that none of the mysql data is corrupted

*Check that the data that was replaced in mysql was as what you expected

*Check for PHP error logs as they should be logging something if they can.

*You should isolate the PHP processes that are actually the cause of clogging up and remove it if cleaning up data alone wasn't enough. Ideally, no matter how bad the data, the php program should've died cleanly.
Good luck hunting.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using atom and future is creating race condition in my Clojure program I have a web service written in Clojure. It has a simple GET method implemented, which returns back a JSON object representing the router's current position and different time counters.
My code has a bunch of atoms to keep track of time. Each atom represents different activities a machine might be doing at a given time. For example: calibrating, idle, stuck, or working:
(def idle-time (atom 0))
(def working-time (atom 0))
(def stuck-time (atom 0))
(def calibration-time (atom 0))

Towards the end I have a loop that updates the position and time counters every 15 seconds:
(defn update-machine-info []
  (let [machine-info (parse-data-files)]
    (update-time-counters machine-info)
    (reset! new-state (merge machine-info
                             {:idleCounter        @idle-time
                              :workingCounter     @working-time
                              :stuckCounter       @stuck-time
                              :calibrationCounter @calibration-time}))))

(loop []
  (future
    (Thread/sleep 15000)
    (update-machine-info)
    (recur)))

Currently this code runs into race condition, meaning the  position and time counters are not updating. However, the Web Service still responses back a proper JSON response, albeit with old values.
Web Service is using Cheshire to generate map into JSON, here my GET implementation:
(defroutes app-routes
  (GET "/" [] (resource :available-media-types ["application/json"]
                        :handle-ok (generate-string (get-machine-information))))
  (route/not-found "Not Found"))

Should I be using refs instead of atoms? Am I using future correctly? Is (Thread/sleep 15000) causing the issue, because atoms are async?
Please let me know if you see an obvious bug in my code.

A: I don't think you can reliably recur inside a future to a loop that's outside the future (not completely sure), but why not try something like this instead?
(future
  (loop []
    (Thread/sleep 15000)
    (update-machine-info)
    (recur)))

That way loop/recur stays within the same thread.
Other than that, it's possible that if update-machine-counters throws an exception the loop will stop, and you'll never see the exception because the future is never dereferenced. An agent ( http://clojure.org/agents ) might be better suited for this, since you can register an error handler.

A: I think what is happening is that the process where you call your futures is terminating before your futures actually execute. For what your doing, futures are probably the wrong type of construct. I also don't think your loop future recor sequence is doing what you think.
There is a lot of guesswork here as it isn't clear exactly where you are actually defining and calling your code. I think you probably want to use something like agents, which you need to setup in the root process and then send a message to them in your handler before you return your response.


text:
Q: Как перебрать все inputs и записать в бд в Laravel? Здравствуйте. Подскажите: Есть интпуты такого типа
<input type="text" name="name[]">
<input type="text" name="fabricator[]">
<input type="text" name="value[]">

Эта группа инпутов, будет задаваться в неопределенном количестве пользователем, то есть динамика. Так вот, вопрос, как перебрать эти массивы всех инпутов и записать в бд или как ещё сделать лучше?
Пока сделал ток перебор по одному массиву, а можно ли сразу как-то все перебрать и в бд отправить?
foreach($request->name as $key => $val ) {
    $param = Flavors::create(['name' => $val);
}

A: Сначала собираете данные в один массив, а затем с помощью insert Eloquent вставляете в БД.
$data = [];
$fabricator = $request->fabricator;
$valueInput = $request->value;

foreach($request->name as $key => $val ) {
    if(array_key_exists($key, $fabricator) && array_key_exists($key, $valueInput)){
        $data[$key] = [
            'name' => $val,
            'fabricator' => $request->fabricator[$key],
            'value' => $request->value[$key]
        ];
    }
}
if($data){
    $param = Flavors::insert($data);
}


text:
Q: Need clarity on Webgl Shaders configuration and parameters to achieve the desired results I want to apply wave effect on water spritesheet from top to bottom direction in way that it looks animated. I got some piece of code from internet but it's creating some effects but in random manner. I want to control it as per my requirement. Below is the code:
function CustomFilter(customSprite, ambientColor, resolution) {
        PIXI.Filter.call(
            this,
            null,
            (
                `
               varying vec2 vTextureCoord;
            uniform sampler2D uSampler;
            uniform float u_ctime;
            const int iterations = 1;
            const float view = 3.;
            void main()
            {
                    vec2 fragCoord = vTextureCoord;
                    vec2 iResolution = vec2(1.0,1.0);
                    float iGlobalTime = u_ctime;
                vec2 uv = fragCoord.xy;
                uv *= view;
                for (int i = 0; i < iterations; i++) {
                float ang = atan(uv.y+cos(uv.y*2.+iGlobalTime)*.5,
                uv.y+sin(uv.y*2.+iGlobalTime)*.5)-length(uv)*.1;
                float sn = sin(ang);

                 mat2 m = mat2(sn,sn,sn,sn);
                 uv = uv*.15-abs(uv*.5*m);
                }

                float d = length(mod(uv,1.)-.5)-.4;

                d *= 20.;
                vec4 FragColor = vec4( sin(uv.x*d), sin(d+.5346), -sin(d+uv.x*1.63), 1. )*.5;
                vec2 u_Scale = vec2(0.0,0.07)*sin(u_ctime);
                vec3 displace = FragColor.rba;
                displace.xy *= displace.z * u_Scale*(0.5-fragCoord.x);
                gl_FragColor = texture2D( uSampler, vTextureCoord + displace.xy );
            }

            `
            )

        );

A: The base base functions for wave effect are sin or cos, and if you look closely, you will see that your super complex shader is full of that. Paradoxically, this is way more complex to acheive randomness than a regular wave.
For example, to draw a wave along X (horizontal) axis, with variation on Y (vertical) axis, you would use this function:
let frequency = 2.0;
let amplitude = 1.0;
let y_base = 0.0;
for(x = 0.0; x < 1.0; x += 0.01) {
  point.x = x;
  point.y = y_base + (sin(x * frequency) * amplitude);
}

Pretty simple, no ? You simply have to apply this concept to your shader, for example, with texture sampling. So, if you want, for example, create a wave effect along X axis, you can use something like that:
 float f = 5.0;
 float a = 0.05;
 vec4 waved = texture2D(sampler, vec2(coord.x, coord.y+(sin(coord.x*f)*a)));

If you want add some animation, you simply have to add a kind of time variable (in your shader, this is currently u_ctime), and the pseudo-code will look like this:
let time = clock();
let pitch = 0.5;
let frequency = 2.0;
let amplitude = 1.0;
let y_base = 0.0;

for(x = 0.0; x < 1.0; x += 0.01) {
  point.x = x;
  point.y = y_base + (sin((time * pitch) + x * frequency) * amplitude);
}

See also: https://en.wikipedia.org/wiki/Sine#Unit_circle_definition


text:
Q: Add 'document_id' column to pandas dataframe of word-id's and wordcounts I have following dataset:
import pandas as pd
jsonDF = pd.DataFrame({'DOCUMENT_ID':[263403828328665088,264142543883739136], 'MESSAGE':['@Zuora wants to help @Network4Good with Hurric...','@ztrip please help spread the good word on hel...']})

DOCUMENT_ID             MESSAGE
0   263403828328665088  @Zuora wants to help @Network4Good with Hurric...
1   264142543883739136  @ztrip please help spread the good word on hel...

I am trying to reshape my data in the form of
docID   wordID  count
0   1   118     1
1   1   285     1
2   1   1229    1
3   1   1688    1
4   1   2068    1

I used following
r=[]
for i in jsonDF['MESSAGE']:
    for j in sortedValues(wordsplit(i)):
        r.append(j)
IDCount_Re=pd.DataFrame(r)
IDCount_Re[:5]

gives me following result
0               17
1   help         2
2   wants        1
3   hurricane   1
4   relief      1
5   text        1
6   sandy       1
7   donate      1
8              6
9   please    1

I can get word counts
I have no idea to to append Document_ID to the in the above dataframe.
Following functions were used to split words
from nltk.corpus import stopwords
import re

def wordsplit(wordlist):
    j=wordlist
    j=re.sub(r'\d+', '', j)
    j=re.sub('RT', '',j)
    j=re.sub('http', '', j)
    j = re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", j)
    j=j.lower()
    j=j.strip()
    if not j in stopwords.words('english'):
        yield j

def wordSplitCount(wordlist):
    '''merges a list into string, splits it, removes stop words and
    then counts the occurrences returning an ordered dictitonary'''
    #stopwords=set(stopwords.words('english'))
    string1=''.join(list(itertools.chain(filter(None, wordlist))))
    cnt=Counter()
    j = []
    for i in string1.split(" "):
        i=re.sub(r'&', ' ', i.lower())
        if i not in stopwords.words('english'):
            cnt[i]+=1
    return OrderedDict(cnt)

def sortedValues(wordlist):
    '''creates a dictionary list of occurenced w/ values descending'''
    d=wordSplitCount(wordlist)
    return sorted(d.items(), key=lambda t: t[1], reverse=True)

UPDATE: SOLUTION HERE:
string split and and assign unique ids to Pandas DataFrame

A: 'DOCUMENT_ID' is one of the two fields in each row of jsonDF. Your current code doesn't access it because it directly works on jsonDF['MESSAGE'].
Here is some non-working pseudocode - something like:
for _, row in jsonDF.iterrows():
    doc_id, msg = row
    words = [word for word in wordsplit(msg)][0].split() # hack
    wordcounts = Counter(words).most_common() # sort by decr frequency

Then do a pd.concat(pd.DataFrame({'DOCUMENT_ID': doc_id, ...
and get the 'wordId' and 'count' fields from wordcounts.


text:
Q: Problem With Conditional Check When Two Elements of Array are Same String Value I am running into a problem where, if two elements of an array are the same string value, then it produces problems in what gets printed to the console based on my current conditional logic, that looks like this:
const homeTeamScorers = ['John Smith', 'John Smith', 'Sam Jones'];
const homeTeamGoalTimes = [3, 10, 22];

 for (let t of homeTeamGoalTimes) {
  const timeIdx = homeTeamGoalTimes.indexOf(t);
  for (let homeScorer of homeTeamScorers) {
    const scorerIdx = homeTeamScorers.indexOf(homeScorer);
    if (scorerIdx === timeIdx) {
      console.log('home scorerIdx:', scorerIdx);
      console.log('home goalTime: ', t);
      console.log('home timeIdx:', timeIdx);
      console.log('home scorer: ', homeScorer);
      console.log('-----------');
    }
  }
 }

This is what I see in the console (notice the second element group is repeating the first):
home scorerIdx: 0
home goalTime:  3
home timeIdx: 0
home scorer:  John Smith
-----------
home scorerIdx: 0
home goalTime:  3
home timeIdx: 0
home scorer:  John Smith
-----------
home scorerIdx: 2
home goalTime:  22
home timeIdx: 2
home scorer:  Sam Jones
-----------

When what I want to see is this:
home scorerIdx: 0
home goalTime:  3
home timeIdx: 0
home scorer:  John Smith
-----------
home scorerIdx: 1
home goalTime:  10
home timeIdx: 1
home scorer:  John Smith
-----------
home scorerIdx: 2
home goalTime:  22
home timeIdx: 2
home scorer:  Sam Jones
-----------

What am I missing here?

A: const timeIdx = homeTeamGoalTimes.indexOf('John Smith');

Will always return the first instance of John Smith.
I would suggest using foreach where you can access the actual index of the element in the loop.
homeTeamGoalTimes.foreach((el, index) => {
   const timeIdx = index;
})

A: Your issue has nothing to do with your code, and everything to do with your data.  That data has two 'John Smith' in it, which means this line:
const scorerIdx = homeTeamScorers.indexOf(homeScorer);

will be 0 for both the first AND second 'John Smith'.
One way to fix this would be by using objects with ID properties to represent your players.  You could change your home team scorers variable to:
const homeTeamScorers = [
    { id: 1, name: 'John Smith'},
    { id: 2, name: 'John Smith'},
    { id: 3, name: 'Sam Jones'}
];

and then use the ID for all your indexing.  However, really I don't think you need two indexes at all (ie. one for the score and one for the team member), and I think that's you real issue.
If you change:
for (let t of homeTeamGoalTimes) {
  const timeIdx = homeTeamGoalTimes.indexOf(t);
  for (let homeScorer of homeTeamScorers) {
    const scorerIdx = homeTeamScorers.indexOf(homeScorer);
    if (scorerIdx === timeIdx) {
      // do log

to:
for (let index of homeTeamGoalTimes) {
  // do log, and use index for both timeIdx and scorerIdx

That should simplify your code and fix your problem.  This should work because both your arrays:
const homeTeamScorers = ['John Smith', 'John Smith', 'Sam Jones'];
const homeTeamGoalTimes = [3, 10, 22];

Have the same (conceptual) index: in both cases the index represents the index of the score in the game (in the first array it's "who scored that index of goal" and in the second it's "when was the score of that index of goal").  Thus, there's really no need to indexOf at all.
P.S. How I'd really recommend doing it though would be ...
const homeTeamScores = [
  { scorer: 'John Smith', time: 3 },
  // ...

because that way your two bits of data for each score are inherently linked in an object, instead of you the coder having to "link" them via index.


text:
Q: what's the point of auto_ptr & unique_ptr? I just can't understand the meaning of unique_ptr or auto_ptr, as we all know, once the parameter gets out of its scope, we won't get memory leaks. However, is it a better idea if I create the parameter on the stack rather on the heap. I don't see its advantage over normal parameters. If we really need to create parameters on the heap, then we must use new operator, right?
Here is a little code snippet:
class Base
{
public:
    Base()
    {
        cout << "Base::()" << endl;
    }
    virtual ~Base()
    {
        cout << "~Base()" << endl;
    }

    virtual void iPhone()
    {
        cout << "I'm iPhone5s" << endl;
    }
};

class Derive : public Base
{
public:

    Derive()
    {
        cout << "Derive()" << endl;
    }

    virtual void iPhone()
    {
        cout << "I'm iPhone 6" << endl;
    }

    virtual ~Derive()
    {
        cout << "~Derive()" << endl;
    }
};

void main()
{
  {

      auto_ptr<Base> ptr(new Derive());//a foolish idea to do so?
      ptr->iPhone();

      Derive d;//isn't it better?
      Base* base = &d;
      base->iPhone();
 }
}

A: It can help to look at std::unique_ptr and std::shared_ptr in the form of ownership instead of as pointers: std::unique_ptr when something can only have one owner at a time, and std::shared_pointer when something can be shared.
Note that since C++11 (which introduced the other smart pointers) std::auto_ptr has been deprecated.

A: I'm getting a lot of down votes for answering your question that is in the comment and not in the title. In the comment, you ask However, is it a better idea if I create the parameter on the stack rather on the heap. This is the answer for that question:
Automatic variables should always be preferred, but it has it is limitation. A reason why you might want to allocate memory dynamically that only lasts for the scope is when you want to create a large memory, the stack has a limited size and so you might want to create it on the heap if it might breach that size.

A: Forget auto_ptr. It is obsolete now, because of its unusual copy semantics. If you would like to have real smart pointers, use unique_ptr or shared_ptr.
Now, your question is: why use unique_ptr ? When you create an object A inside an object B, you could declare it  as an attribute of B class, for example. It is on the stack, and you don't need unique_ptr. This is true, but sometimes, your object B must be initialized without the instance of A, because, for example, A is too big, or you don't use it. Thus, you must do dynamic allocation, and it helps to use  unique_ptr to not avoid to delete your pointer.

A: Consider you have:

class A { };
class B : public A { };

A* factory(bool willBeA)
{
  return willBeA ? new A() : new B();
}

int main()
{
  //I want to get an instance of A or maybe B depending on a value
  bool val = false;
  unique_ptr<A> ptr { factory(val) }; //you need having a pointer to the returned value of A

  //do something

  //no need for delete

  return 0;
}

In this case, you cannot create an automatic variable to store A, because you actually do not know if an instance of A or B will be used.


text:
Q: Audience counts in your deployments How many audiences does your implementation of SharePoint have? I'm trying to communicate to my management that audiences are powerful tools for content filtering, but collectively we're getting hung up on the idea that we might have dozens or hundreds of them, and that this might be onerous to manage. My contention is that for a large SharePoint farm, having many multiple audiences based on AD Groups or User Profile properties would be normal.
I work at a university, and I think it would be a natural fit for audiences to describe academic programs (ex. "Bachelor's Degree in English"). The perceived complexity of our audiences would be describing our real-world environment, nothing more.

A: We use audiences alot, both for targeting web part content on pages, and for targeting list items like publishing pages to specific targets.
You can also use them to target navigation links on my sites.
Both me and my colleagues use audiences quite alot. They do have some teeth that can bite you, if you want to move your content as they contain guids that are specific for the farm where they are used. This can be fixed as well if you know what you are doing.
They are truely powerfull when used correctly. I love the fact that i can target both on what people are (user profile properties) and what people can access (SharePoint groups, distribution lists and security groups).
What people often misunderstand about audiences are that they do not determine what you can and cannot see (Security) but only what is pushed to you based on the rules of the audience.
You should read the Technet planning documents here to make sure you fully understand the potential of audience targeting.


text:
Q: Including pug file causes error but jade works fine Running into a weird issue here. I have a pretty basic jade/pug include going on here:
extends base.pug

block vars
    - var title = 'Home'

block body
    header
        include ./includes/header.pug

A quick note, just using extends base (without the extension) just doesn't work. But this include gives the following error:
TypeError: Cannot read property 'replace' of undefined
   at before (/var/node/website/node_modules/pug-linker/index.js:104:48)
   at walkAST (/var/node/website/node_modules/pug-walk/index.js:13:26)
   at /var/node/website/node_modules/pug-walk/index.js:21:16
   at Array.map (native)
   at walkAST (/var/node/website/node_modules/pug-walk/index.js:20:29)
   at walkAST (/var/node/website/node_modules/pug-walk/index.js:33:21)
   at /var/node/website/node_modules/pug-walk/index.js:21:16
   at Array.map (native)
   at walkAST (/var/node/website/node_modules/pug-walk/index.js:20:29)
   at /var/node/website/node_modules/pug-walk/index.js:21:16
   at Array.map (native)
   at walkAST (/var/node/website/node_modules/pug-walk/index.js:20:29)
   at applyIncludes (/var/node/website/node_modules/pug-linker/index.js:102:10)
   at link (/var/node/website/node_modules/pug-linker/index.js:21:9)
   at compileBody (/var/node/website/node_modules/pug/lib/index.js:84:11)
   at Object.exports.compile (/var/node/website/node_modules/pug/lib/index.js:164:16)

But changing that to :
extends base.pug

block vars
    - var title = 'Home'

block body
    header
        include ./includes/header.jade

Works perfectly fine. The contents of header.jade and header.pug are the exact same so I am a bit perplexed here. Some help would be appreciated.
Thanks,
PS: Searching did reveal: https://github.com/pugjs/pug-linker/issues/13 - seems to be a bug but not sure how this could be.

A: So it looks like pug isn't really ready for primetime YET! Look forward to when it is but using jade instead of pug solves the issue, just rename everything to .jade.

A: One of the breaking changes in the move from Jade to Pug is that you can't interpolate variables anymore. You used to be able (and encouraged) to use #{something} inside another string, but now you're encouraged to use regular JavaScript variables.
for example, this
a(href="#{link}")
a(href='before#{link}after')

should now become
a(href=link)
a(href=`before${link}after`) //(on Node.js/io.js ≥ 1.0.0)
a(href='before' + link + 'after') //(everywhere)

Source: tracking issue with breaking changes.


text:
Q: Passing data from listview Good night, to pass data from one listview generated a database I do so by Intent and capturing the value:
intent.putExtra("name", listView.getItemAtPosition(position).toString());
To pick do with Bundle:
Bundle bundle = getIntent().getExtras();
String myData = bundle.getString("name");
nombre.setText(miData);
The problem is that I receive is in the form of array:
{value = first name}
I tried various shape and not get capture only the string "first course" because it is what is shown in the listview, any suggestions? Thank you!
PD -> Sorry if my English is not good.

A: Thanks for the reply but I do not get what I want, when I pick up the data from the database and pick them up
arrayList.add (createList ("value" name));
With the index or value
But I have solved:
int start = myData.indexOf("=");
int end = myData.indexOf("}", start + 1);
nombre.setText(myData.substring(start + 1, end));
is not an elegant solution, but eventually get him in the EditText name.


text:
Q: How to make repeated ajax calls and abort all the previous calls which is not finished yet when it enters some particular function? This is my ajax function
function repeatedCall() {
    $.ajax({
        url: '/getUrl',
        complete: function(data) {
            if (data.statusText != "error") {
                //my actions
            }
        }
    })
}

setInterval(repeatedCall, 5000); //To make repeated ajax calls

function updateData_function{
     //I want to abort all previous ajax calls and make a new ajax call since it will update the data
}

I can use clearInterval but the pending calls are not getting aborted and hence it is not updating properly.
How can i make repeated calls and at the same time abort all the requests if it enters my updateData_function.
This updateData_function will have new values so i need to make fresh ajax request.
How can i do this? Please help!! Thanks a lot in advance!!

A: Using setInterval to make repetead calls is not a good practice. Assume that your previous request is not completed, then there is no point in making the same ajax call. Also, as you may know, there are possibility that the response from the previous ajax call can come after the recent ajax response. So it is always better to abort any previous ajax calls.
I think the below solutions may solve your issue:
Solution 1: Just Extentending what you have done:
var xhr

function repeatedCall() {
  if(xhr){
    // abort any previous calls, to avoid any inconsistency
    xhr.abort()
  }
  xhr = $.ajax({
    url: '/getUrl',
    complete: function(data) {
      if (data.statusText != "error") {
        //my actions
      }
    }
  })
}
setInterval(repeatedCall, 5000)
function updateData_function {
  //I want to abort all previous ajax calls and make a new ajax call since it will update the data
  if(xhr){
    xhr.abort()
  }
}

Solution 2: What I feel is a better approach
var xhr;

function repeatedCall() {
  xhr = $.ajax({
    url: '/getUrl',
    complete: function(data) {
      if (data.statusText != "error") {
        //my actions
        // Call the ajax call again:
        setTimeout(repeatedCall, 5000)
      }
    }
  })
}

function updateData_function {
  //I want to abort all previous ajax calls and make a new ajax call since it will update the data
  if(xhr){
    xhr.abort()
  }
  // do something
}
// somewhere - to initiate the repeatedCall for the first time
repeatedCall()

A: I faced the same problem before as well and I was sending to many ajax calls on keyup which was leading my website to collapse. I found out the solution to setTimeout(); in to the ajax all firing and keeping firing the function clears timeout and settimeout again. This let you to fire ajax only 1 time on pressing to many time.
Edit: Ok for example I had a searchbox which was getting predefined suggestions with ajax call with onkeyup function. as I was start typing it was firing ajax call again and again and stucking. I started to cancel the one before as I firing another so fixed the situation. Here is the DEMO Doesnt matter how many time you hit the button it fires only one.

A: I've modified my code and this works
    abortValue = false;
    var xhr;
    xhrPool = [];
    var trying;

    function abortAjax() {
        $.each(xhrPool, function(idx, jqXHR) {
            jqXHR.abort();

        });

    }
    $(document).ready(function() {
        fn = function() {
            xhr = $.ajax({
                url: '/getUrl',
                beforeSend: function(jqXHR) {
                    xhrPool.push(jqXHR);
                },
                complete: function(jqXHR, data) {
                    if (abortValue == true) {
                        abortAjax()
                    } else {
                        if (jqXHR.statusText != "error" && "undefined") {
                            //myactions

                        }

                    }
                }
            });

        };

        var interval = setInterval(fn, 5000);
    });

    function updateData_function {
        //I want to abort all previous ajax calls and make a new ajax call since it will update the data

        abortValue = true;
        abortAjax();
        abortValue = false;
        fn();
}


text:
Q: What is the max connection limit of ajax long poll? For how many second can I keep a connection open? I mean, how long will the browser wait for an answer before a timeout and connect again to the longpoll.php?

A: That depends very much on what browser you are using (Ranging from a couple of seconds to an hour and beyond). Theoretically it is only limited by the 8 hour TCP Timeout.


text:
Q: How do we store cascading taxes in a database? or database structure for storing taxes Hi i have to create a database structure for storing tax details.
I have an itemDetails table which has the details of the item like name and price.
The problem is for each item there are two taxes service charge (10%) and VAT (4%)
but the taxes are cascaded i.e after I apply servicecharge, then on the new total I have to apply I apply vat.
I want to store this in a database; I can acheive this with hard coding it but I want it in a database so that in the future if the customer wants he can store more taxes by specifying which order the taxes apply and weather they cascade or not. And each item may have a different tax structure.. (Ex. one item may have the above mentioned tax structure, another item has only vat, another item has a completely diffenet structure etc)
I have a tax category table where the user can store a tax structure and each item will belong to a tax category i.e the itemDetailsTable has TaxCategory_id in it. I need your help figuring it out from there.

A: You could add another table that has a many-to-one relationship with TaxCategory that uses a ranking column to define what order the taxes are applied in.
TaxCategoryRates

taxCategoryId    taxRate    taxRank   taxDescription
-------------    -------    -------   --------------
1                10         1         Service Charge
1                4          2         VAT
2                3          NULL      Local Sales Tax
2                4.5        NULL      State Sales Tax

Your logic then applies the taxes in order of taxRank.  If you have other tax categories where order doesn't matter (as in taxCategoryId 2), you can just leave the rank NULL and have your logic sum the tax rates and apply them.


text:
Q: Surface Integral Question I have this question:
Evaluate $\int r . dS$ over the surface of a sphere, radius a, centred at the origin.
I'm not really sure what '$r$' is supposed to be? I would guess a position vector? If so, I would have $r . dS$ as $(asin\theta cos\phi, a sin\theta sin\phi, acos\theta) . (a^2sin\theta d\theta d\phi)$ which doesn't seem right. Any pointers appreciated, thanks!

A: There's two ways to look at this.  For both ways, though, the notation $r \cdot dS$ is a shorthand for $r \cdot n dS$, where $n$ is the normal vector to $S$, pointed outward.  In this case, the normal vector is just the position vector $r$, normalized to unit length.  Thus the surface integral is simply
$$a \int_S dS = 4 \pi a^3$$
This may also be analyzed using the divergence theorem.  Because $\nabla \cdot r = 3$, we have the surface integral equal to
$$3 \int_{\text{sphere}} dV = 4 \pi a^3$$

A: It's very easy, you don't even need to change coordinates or anything of this kind. Just note that at each point of the sphere the normal unit vector $n$ points outwards, so he is radially pointing away from the sphere. However, the position vector of this point also points radially outwards. This means that both $r$ and $n$ have the same direction. Also, you know that the magnitude of $r$ is $a$. Why you know that? Well, $r$ is the position of each point on the sphere, and by definition each point is at a distance $a$ from the origin.
Now, you have $r\cdot n = |r||n|\cos\theta$, however $\theta =0$ since they're paralel, $|n|=1$ because $n$ is unitary and $|r| = a$ by the preceding discussion. So $r\cdot n = a$. Now you'll get:
$$\int_S r \cdot n \ = a \int_S 1$$
And recall that the integral of the constant function $1$ over any surface gives you the area of the surface which you know is $4\pi a^2$. So you get:
$$\int_S r \cdot n = 4\pi a^3$$


text:
Q: Set SVG as mouse pointer image I am having a svg image .I neet to set that svg image as mouse pointer using javascript.
I can able to set the image as mouse pointer using following code:
  $("div").mouseover(function(){
            $(this).attr("style","cursor: url(red_bucket.png), pointer;");
        });

Is there any possiblities to set the svg as mouse pointer...?

A: This should work
    $("div").mouseover(function(){
        $(this).attr("style","cursor: url('red_bucket.svg'), pointer;");
    });


text:
Q: How can I fix memory leak in Spring Scheduled function? I have a strange memory leak in the java application that uses Spring 3.0
the java class has this structure
@EnableAsync
@Component
public class ScheduleFixedRate {

SellerRepository sellerRepository;
SellerProfileRepository sellerProfileRepository;
StatsRepository statsRepository;

public ScheduleFixedRate(SellerRepository sellerRepository, SellerProfileRepository sellerProfileRepository, StatsRepository statsRepository) {
        this.sellerRepository = sellerRepository;
        this.sellerProfileRepository = sellerProfileRepository;
        this.statsRepository = statsRepository;
    }

    public Builder webClientBuilder(String baseUrl) {
        boolean secure = baseUrl.contains("https");

        HttpClient httpClient = HttpClient.create().followRedirect(true);
        if (secure) {
            httpClient = httpClient.secure(sslContextSpec -> sslContextSpec.sslContext(createInsecureSslContext()));
        }
        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .baseUrl(baseUrl);
    }

    private SslContext createInsecureSslContext() {
        try {
            return SslContextBuilder
                    .forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    }

@Scheduled(fixedRate = 60000)
public void updateOrdersList() {
       WebClient client = webClientBuilder("https://web.com:443").build();
                HttpMethod method = HttpMethod.valueOf("GET");
                RequestBodySpec requestBodySpec = client.method(method).uri("/api***");
                requestBodySpec.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.125 Safari/537.36");
                StringBuilder response = new StringBuilder();

                try {
                    response.append(requestBodySpec.exchangeToMono(clientResponse -> {
                        if (clientResponse.statusCode().is4xxClientError()) {
                            return Mono.error(new Throwable());//Mono.empty();
                        }
                        return clientResponse.bodyToMono(String.class);
                    }).block(Duration.ofSeconds(5)));
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
       // doing some manipulation with response
sellerRepository.save(data);
 }
}

Within one day, I saw that my app will start using an additional 1.5GB of memory.
I saw that the spring is creating many scheduler threads in the memory. Please see the images below (the first image is after 10 minutes of starting the application, and the second image is after one day)

Could you help me with what's wrong?

A: Hard to know what is going on without seeing more code, but I would look into EntityManager.clear() if you have long living threads that handle many entities.

A: You can try something below.
WebClientConfig
@Configuration
class WebClientConfig {

    @Value("{$base.url}")
    private String baseUrl;

    @Bean
    WebClient webClientBuilder(String baseUrl) {
        boolean secure = baseUrl.contains("https");

        HttpClient httpClient = HttpClient.create().followRedirect(true);
        if (secure) {
            httpClient = httpClient.secure(sslContextSpec -> sslContextSpec.sslContext(createInsecureSslContext()));
        }
        return WebClient.builder()
                        .clientConnector(new ReactorClientHttpConnector(httpClient))
                        .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                        .baseUrl(baseUrl)
                        .build();
    }

    private SslContext createInsecureSslContext() {
        try {
            return SslContextBuilder
                    .forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .build();
        }
        catch (SSLException e) {
            throw new RuntimeException(e);
        }
    }
}

Scheduler Code:
@EnableAsync
@Component
public class ScheduleFixedRate {

    private final SellerRepository sellerRepository;
    private final SellerProfileRepository sellerProfileRepository;
    private final StatsRepository statsRepository;
    private WebClient webClient;

    public ScheduleFixedRate(SellerRepository sellerRepository,
            SellerProfileRepository sellerProfileRepository,
            StatsRepository statsRepository,
            WebClient webClient) {
        this.sellerRepository = sellerRepository;
        this.sellerProfileRepository = sellerProfileRepository;
        this.statsRepository = statsRepository;
        this.webClient = webClient;
    }

    @Scheduled(fixedRate = 60000)
    public void updateOrdersList() {
        String response = webClient
                .get()
                .uri("/api***")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.125 Safari/537.36")
                .retrieve()
                .onStatus(HttpStatus::is4xxClientError, res -> Mono.error(new Throwable()))
                .bodyToMono(String.class)
                .block();

        // doing some manipulation with response
        sellerRepository.save(response);
    }
}

A: I replaced the
import reactor.netty.http.client.HttpClient;

with
import java.net.http.HttpRequest;
public String sendGetRequest(String url) throws IOException, InterruptedException {
        java.net.http.HttpClient client = java.net.http.HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(Duration.ofSeconds(5))
                .build();

        HttpResponse<String> response = client.send(request,
                HttpResponse.BodyHandlers.ofString());

        return (response.body());
    }

And the issue has been fixed.
It looks like the issue is on the netty library.


text:
Q: Python TypeError: reduce_noise() got an unexpected keyword hi guys I'm trying to do audio classification using python and  I installed a package and when I tried to use the functions, it said "TypeError: TypeError: reduce_noise() got an unexpected keyword argument 'audio_clip' hear the code of function.
import librosa
import numpy as np
import noisereduce as nr
def save_STFT(file, name, activity, subject):
#read audio data
audio_data, sample_rate = librosa.load(file)
print(file)
 #noise reduction
  noisy_part = audio_data[0:25000]
  reduced_noise = nr.reduce_noise(audio_clip=audio_data, noise_clip=noisy_part, verbose=False)

 #trimming
  trimmed, index = librosa.effects.trim(reduced_noise, top_db=20, frame_length=512, hop_length=64)

 #extract features
  stft = np.abs(librosa.stft(trimmed, n_fft=512, hop_length=256, win_length=512))
 # save features
  np.save("STFT_features/stft_257_1/" + subject + "_" + name[:-4] + "_" + activity + ".npy", stft)

this code running in jupyternote book with Conda environment but It's not running in pycharm.
I installed conda environment in PYcharm but it does not work. Could you please help me know how to fix this error?

A: Answer to your question is in the error message.
"TypeError: TypeError: reduce_noise() got an unexpected keyword argument 'audio_clip'

I am guessing you are using noisereduce Python library. If you check the docs, it does not have audio_clip on parameters' list.
Example of correct code:
reduced_noise = nr.reduce_noise(y=audio_data, y_noise=noisy_part, sr=SAMPLING_FREQUENCY) # check the SAMPLING_FREQUENCY

A: Probably you are referring old APIs for newer version of library
The work around to use old APIs in newer version of library is
from noisereduce.noisereducev1 import reduce_noise

Now you can reuse your code as
reduced_noise = reduce_noise(audio_clip=audio_data, noise_clip=noisy_part, verbose=False)


text:
Q: Apex Query on ContentVersion object and get all record Apex Query on ContentVersion object and get all records, but the record are coming on current login user owned, not all records are coming. for example i am login with administrator account and want to see all records on my page, but they just return the records owned by me . is it any work around to get all records.

A: The ContentVersion Sobject document mentions

Users (including users with the "View All Data" permission) can only
  query files they have access to, including:

*

*All Salesforce CRM Content files in libraries they're a member of and    in their personal library, regardless of library permissions
  (API    version 17.0 and later).

*All Chatter files they own, posted on their profile, posted on groups they can see, and shared directly with them (API version
  21.0 and later).


text:
Q: High Chart Async drilldown I am following http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/drilldown/async/ Link for making Drilldown chart.
I am not able to understand how can I set value for drilldowns = {} (dynamically from ajax call)
and  series = drilldowns[e.point.name];
drilldowns = {
                            'Animals': {
                                name: 'Animals',
                                data: [
                                    ['Cows', 2],
                                    ['Sheep', 3]
                                ]
                            },
                            'Fruits': {
                                name: 'Fruits',
                                data: [
                                    ['Apples', 5],
                                    ['Oranges', 7],
                                    ['Bananas', 2]
                                ]
                            },
                            'Cars': {
                                name: 'Cars',
                                data: [
                                    ['Toyota', 1],
                                    ['Volkswagen', 2],
                                    ['Opel', 5]
                                ]
                            }
                        }

I have tried to search .addSeriesAsDrilldown(e.point, series);
please help me on how to can I achieve drilldown via $.ajax call.
$(function () {

// Create the chart
$('#container').highcharts({
    chart: {
        type: 'column',
        events: {
            drilldown: function (e) {
                if (!e.seriesOptions) {

                    var chart = this,
                        drilldowns = {
                            'Animals': {
                                name: 'Animals',
                                data: [
                                    ['Cows', 2],
                                    ['Sheep', 3]
                                ]
                            },
                            'Fruits': {
                                name: 'Fruits',
                                data: [
                                    ['Apples', 5],
                                    ['Oranges', 7],
                                    ['Bananas', 2]
                                ]
                            },
                            'Cars': {
                                name: 'Cars',
                                data: [
                                    ['Toyota', 1],
                                    ['Volkswagen', 2],
                                    ['Opel', 5]
                                ]
                            }
                        },
                        series = drilldowns[e.point.name];

                    // Show the loading label
                    chart.showLoading('Simulating Ajax ...');

                    setTimeout(function () {
                        chart.hideLoading();
                        chart.addSeriesAsDrilldown(e.point, series);
                    }, 1000);
                }

            }
        }
    },
    title: {
        text: 'Async drilldown'
    },
    xAxis: {
        type: 'category'
    },

    legend: {
        enabled: false
    },

    plotOptions: {
        series: {
            borderWidth: 0,
            dataLabels: {
                enabled: true,
            }
        }
    },

    series: [{
        name: 'Things',
        colorByPoint: true,
        data: [{
            name: 'Animals',
            y: 5,
            drilldown: true
        }, {
            name: 'Fruits',
            y: 2,
            drilldown: true
        }, {
            name: 'Cars',
            y: 4,
            drilldown: true
        }]
    }],

    drilldown: {
        series: []
    }
})

});

A: Example for you: http://jsfiddle.net/S3j35/
Use e.point.name to determine which point is clicked and which data you need from server. When AJAX comes, just add series with new data:
            drilldown: function (e) {
                if (!e.seriesOptions) {
                    // e.point.name is info which bar was clicked
                    chart.showLoading('Simulating Ajax ...');
                    $.get("path/to/place.html?name=" + e.point.name, function(data) {
                        /***
                        where data is this format:
                        data = {
                            name: 'Cars',
                            data: [
                                ['Toyota', 1],
                                ['Volkswagen', 2],
                                ['Opel', 5]
                            ]
                        }
                        ***/
                        chart.hideLoading();
                        chart.addSeriesAsDrilldown(e.point, data);
                    });
                }
            }

A: Below is the working code with ajax for drilldown levels:

Create ajax_response.php with below codes:

<?php
if($_REQUEST['name'] == "Cars") {
$response = array('name' => 'Cars', 'data'=>array(array('Toyota', 1), array('Volkswagen', 2), array('Opel', 5)));
}else if($_REQUEST['name'] == "Fruits"){
    $response = array('name' => 'Fruits', 'data'=>array(array('Apples', 5), array('Oranges', 7), array('Bananas', 2)));
}else if($_REQUEST['name'] == "Animals"){
    $response = array('name' => 'Animals', 'data'=>array(array('Cows', 2), array('Sheep', 3)));
}

echo json_encode($response);
?>


text:
Q: Algorithm / MySQL - Get all points within a radius I have MySQL table of coordinates (longitude and latitude).
I would like to find the most efficient way to get all points around a certain point within a specific radius.
In other words,
input: longitude, latitude, radius (in kilometers)
output: all points (longitude and latitude) in this circle
How to do it in the most efficient way?

A: One efficient way to do it, following @jean's idea, is to perform a range query then filter the points within the circle, since range query can be optimized by range index. Let (x, y, r) be the input. Namely,
SELETE * FROM coordinates WHERE longitude <= x + r and longitude >= x - r and latitude <= y + r and latitude >= y - r

Then you can load the tuples to memory and filter the result yourseft, or you do another sql query over the result of this subquery to filter the points.
Following the same idea, we can do it in a more fancy way: we can decompose the circle into multiple rectangles and perform range queries for all these rectangles, but I doubt how much this can improve the performance.


text:
Q: Issues with "&" symbol in javascript I have a aspx page from which some strings are passed into the Javascript function. I am facing a strange issue if the string contains a & symbol.
Here is the simplified version of the code
if(stringWhichComesFromUI == "AD&D")
{
    //populate a hidden field
    $('#hdnSomeHiddenField').value = "AD&D";
}

and in the UI, the hidden field value is populated in a cell inside a grid.
Now the problem is, even if user is sending "AD&D" from the UI, the variable stringWhichComesFromUI is becoming "AD&Amp;D" thats why the if block never executes.
I have also tried with
if(stringWhichComesFromUI == "AD&D" || stringWhichComesFromUI == "AD&Amp;D")
{
    //populate a hidden field
    $('#hdnSomeHiddenField').value = "AD&D";
}

This executes the if block, but the value which is going into the hidden field does not show properly in the UI. Value which is displayed in UI is "AD", the "&D" part is gone! I am not able to figure out why, please help?

A: There is error in syntax of assigning value in jquery. Use this
<asp:TextBox ID="myinput" runat="server" />
<asp:Button ID="SubmitButton" runat="server" OnClientClick="Showme()" Text="Submit" />
<asp:HiddenField ID="hiddenFieldText" runat="server" />

And your script will be like this:
function Showme(){
 var stringWhichComesFromUI= $("#myinput").text();

if(stringWhichComesFromUI == "AD&D")
{
//populate a hidden field
$("#hiddenFieldText").val("AD&D");
}

}


text:
Q: Cannot find jena.db package with maven I have a little problem with jena. I want to use https://github.com/ldodds/slug in one of my project. This application comes without dependencies so I use Maven to gather what this app needs. Maven resolved everything except one package
import com.hp.hpl.jena.db.*;

I cannot resolve it with any of jena maven respositories. Do you know where I can find it? Maybe jena.db was available in older package but I cannot find any migration guide about this package.
If you are familiar with problem or know Jena structure well, please help.
Thanks in advance.

A: The RDB storage layer (the package com.hp.hpl.jena.db) was removed from Jena a long time.  Presumably slug works with the version of in it's lib directory.
It would be better to use TDB or generalise and use SPARQL (query and update) so it will work with an external, standard triple store (like Jena Fuseki -- there are many to choose from).  It will need changes to slug.


text:
Q: How to remove pre-installed ubuntu and and install another OS? I bought a new PC with ubuntu11.10 pre-installed but now I want to use Windows 7.

A: Wipe the HD first using Diskpart from Windows 7 DVD: SSD / HDD : Optimize for Windows Reinstallation
Follow these tips to get a purrfect clean reinstall - use the ones which apply: re-install windows 7
SOURCE : http://www.sevenforums.com/installation-setup/150731-install-windows-7-over-ubuntu.html

A: I suppose Windows 7 installation will give you the option to format the hard drive.


text:
Q: Xamarin.Forms with Web Service doesn't work I try to consume a Web Service API from a Xamarin.Forms Prism application, but it doesn't work. When I tried the same code in a Console Application it works.
when I debug the code, it exits at line:
var json = await httpClient.GetStringAsync(WebServiceUrl);

Here is the code of the classe I use:
public class RestClient<T>
    {
        private const string WebServiceUrl = "http://localhost:64049/api/Evenements";

        public async Task<List<T>> GetAsync()
        {
            var httpClient = new HttpClient();
            var json = await httpClient.GetStringAsync(WebServiceUrl);
            var evenements = JsonConvert.DeserializeObject<List<T>>(json);
            return evenements;
        }
    }


text: Q: Count number of Partial order relations of $5$ elements $\{1,2,3,4,5\}$ How to count number of Partial order relations of $5$ elements $\{1,2,3,4,5\}$? I know that i must use Hasse diagram and count how many distinguishable ways each can enter, but i can't draw them for $5$ elements case. Could you please help to me to do that?


text:
Q: How does Celery work? I have recently started working on distributed computing for increasing the computation speed. I opted for Celery. However, I am not very familiar with some terms. So, I have several related questions.
From the Celery docs:

What's a Task Queue?
...
Celery communicates via messages, usually using a broker to mediate between clients and workers. To initiate a task the client adds a message to the queue, the broker then delivers that message to a worker.

What are clients (here)? What is a broker? Why are messages delivered through a broker? Why would Celery use a backend and queues for interprocess communication?
When I execute the Celery console by issuing the command
celery worker -A tasks --loglevel=info --concurrency 5

Does this mean that the Celery console is a worker process which is in charge of 5 different processes and keeps track of the task queue? When a new task is pushed into the task queue, does this worker assign the task/job to any of the 5 processes?

A: Last question first:
celery worker -A tasks --loglevel=info --concurrency 5

You are correct - the worker controls 5 processes. The worker distributes tasks among the 5 processes.
A "client" is any code that runs celery tasks asynchronously.
There are 2 different types of communication - when you run apply_async you send a task request to a broker (most commonly rabbitmq) - this is basically a set of message queues.
When the workers finish they put their results into the result backend.
The broker and results backend are quite separate and require different kinds of software to function optimally.
You can use RabbitMQ for both, but once you reach a certain rate of messages it will not work properly. The most common combination is RabbitMQ for broker and Redis for results.

A: We can take analogy of assembly line packaging in a factory to understand the working of celery.

*

*Each product is placed on a conveyor belt.

*The products are processed by machines.

*At the end all the processed product is stored in one place one by one.

Celery working:
Note: Instead of taking each product for processing as they are placed on convey belt, In celery the queue is maintained whose output will be fed to a worker for execution one per task (sometimes more than one queue is maintained).

*

*Each request (which is a task) is send to a queue (Redis/Rabbit MQ) and an acknowledgment is send back.

*Each task is assigned to a specific worker which executes the task.

*Once the worker has finished the task its output is stored in the result backend (Redis).


text:
Q: Trouble getting jQuery to select an option from dropdown menu via an image map I'm stuck trying to implement an HTML image map in my Rails 4 application.  The image map is of the human muscular system. The goal is for a user to click hotspots to choose target muscle groups.  The target muscle groups are in a drop-down menu, which works okay.  My objective is to improve user experience by associating drop-down menu options with hotspots on the image map.
The HTML for the muscle group collection (drop-down menu) is:

<%= f.label :muscle_group %>

<%= f.collection_select :muscle_group_id, MuscleGroup.order(:name), :id, :name, prompt: "Choose your target muscles", include_blank: false %>

Source code for the dropdown menu is:
<select id="strength_exercise_muscle_group_id"
 name="strength_exercise[muscle_group_id]"><option value="">Choose your target muscles</option>
<option value="11">Abs - rectus abdominis</option>
//more options
</select>

HTML code for the image map is:

<%=image_tag("muscles_anterior_front view_pubic domain - Copy.png", :usemap => "#musclesfrontview") %>
<map name="musclesfrontview" style="height: 1100px; display: inline-block; position: absolute; left: 0px; top: 0px; width: 919px;">
  <area shape="rect" coords="335,404,422,580" alt="Abs" href="#" id="map_abs"/>
  <area shape="default" href="" />
  //more areas
</map>

To test the image map, I created the following jQuery code:
$(document).ready(function() {
$("#map_abs").click(function(event){
    $('#strength_exercise_muscle_group_id option:selected').val();
})
});

When I click the "abs" hotspot area in Firefox, nothing appears to happen.  Using Firebug, I am able to highlight the "abs" hot spot on the image, so the area coordinates on the image map appear to be correct.  I suspect there's a problem with my jQuery code.  For some reason the click event is not firing.  What am I doing wrong?  How do I fix my code to get my image map working?  I'd appreciate any help.

A: You were very close! You just need to set the value of the select with the abs value of 11 like so:
$("#map_abs").click(function (event) {
   $('#strength_exercise_muscle_group_id').val(11);
});

If you are listening for change events on the selects, you can even trigger one when you change the value by doing $('#strength_exercise_muscle_group_id').trigger('change'). Hope this helps.

A: This worked for me:
$("#map_abs").click(function(){
    var absID = 11;
    var muscle_group = $("#strength_exercise_muscle_group_id option[value='" + absID + "']").attr("selected","selected");


text:
Q: Save only if multiple JTextFields are not empty I have multiple JTextFields and JComboBox in my JFrame. So whenever I click the _Add_ button it will check if the four (4) text fields in Current Medication Panel is Empty. If it is not then Execute, but it also depends if the Personal info Panel text fields are filled.
But I have a problem when I use the if and else statement, if I use the if and else:
    if(condition if the first textfield is empty) {
        // execute something like the textfield turn to red
    } else if(condition if the second textfield is empty) {
        // execute something like the textfield turn to red
    } else if(condition if the third textfield is empty) {
        // execute something like the textfield turn to red
    } else{
        // execute save information of the patient
    }

In this situation if the 1st text field is empty then it will turn to red but if both 1st and 2nd text field is empty only the 1st text field turn to red.
I also tried the if, and if and if but were should put the else whenever there is no empty or invalid input where it will execute and save the patient info like this:
   if(condition if the first textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the second textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the third textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the fourth textfield is empty) {
     // execute something like the textfield turn to red
   } else

If I use this only the last if statement only works for the else statement.
So if the last statement is true then execute, but not then else statement execute which is patient save info.
Is there any thing I can do about this? or is there any tutorial for me to learn more about Java and about if and else?

A:
but were should put the else

It is not mandatory to follow if with else. The purpose of specifying else is to allow your code execution flow to go through all other case when if was not satisfied (true).

if i use this only the last if statement only works for the else
  statement

Because, if might have satisfied, so it executes else case. I would suggest to include return in each if case. So that, if any of the if case was satisfied. Then, it won't execute further code.

A: In the Add button action listener's actionPerformed method, you can try this:
public void actionPerformed(ActionEvent e) {

    if (! textFieldsValid()) {
        // one or more of the text fields are empty
        // may be display a message in a JOptionPane
        System.out.println("The text fields are not filled with data, etc...");
        return;
    }

    // else, text fields have valid data, so do whatever processing it further...
}

/*
 * This method checks if the text fields are empty and sets their borders as red. Returns
 * a boolean false in case any of the text fields are empty, else true.
 */
private boolean textFieldsValid() {

    boolean validTextFields = true;

    if (textField1.getText().isEmpty()) {
        validTextFields = false;
        textField1.setBorder(new LineBorder(Color.RED));
    }

    if (textField2.getText().isEmpty()) {
        validTextFields = false;
        // textField2.setBorder(...)
    }

    // ... same with textField3 and textField4

    return validTextFields;
}

A: This should not be news to you: you are doing it wrong.
There are several ways to implement your desired solution,
here is one of them:
boolean performSave = true;

if (field1 is empty)
{
    do some stuff.
    performSave = false;
}

if (field2 is empty)
{
    do some stuff.
    performSave = false;
}

... repeat for any number of fields.

if (performSave) // no fields are empty.
{
    save stuff.
}


text:
Q: How to delete unwanted commit files I am new to git functions and I wrote a set of code, I intend to push it to Github but my commit report is showing over 5000 files, I do not know where such heavy set of commits emanated from. Please help!
The image for the commit box is shown below:

A: Had the exact same problem.
In Vscode open the drop down "SOURCE CONTROL REPOSITORIES" at the top of the source control panel.
Then right click on the repo which is incorrectly set and select Close Repository.
Here is a visual of the answer

A: You have a lot of files in folders you do not want to be pushing. The .cache folder for example. You can fix this  by creating a .gitignore file containing the paths that you don't want to push.
For example, to add the .cache folder to .gitignore, you can use.
.cache

Figure out which files you want to push to github, and which you should not be pushing. Also, if you have already pushed any files to the repo that are included in the .gitignore, you will need to remove them.


text:
Q: Dissolving polygons to single part features with Python (shapely and fiona)? I used the code from Dissolving polygons based on multiple attributes with Python (shapely and fiona)? to dissolve a shapefile using shapely and fiona. However the output creates multi-part geometries.
Is it possible to convert the output to single part or generate single part features instead?
I'm attempting to create a single chain using open source tools in Linux. I would also like to avoid calling QGIS tools if that's at all possible.
Here's the code sample:
from shapely.geometry import shape, mapping
from shapely.ops import unary_union
import fiona
import itertools
with fiona.open('cb_2013_us_county_20m.shp') as input:
    # preserve the schema of the original shapefile, including the crs
    meta = input.meta
    with fiona.open('dissolve.shp', 'w', **meta) as output:
        # groupby clusters consecutive elements of an iterable which have the same key so you must first sort the features by the 'STATEFP' field
        e = sorted(input, key=lambda k: k['properties']['STATEFP'])
        # group by the 'STATEFP' field
        for key, group in itertools.groupby(e, key=lambda x:x['properties']['STATEFP']):
            properties, geom = zip(*[(feature['properties'],shape(feature['geometry'])) for feature in group])
            # write the feature, computing the unary_union of the elements in the group with the properties of the first element in the group
            output.write({'geometry': mapping(unary_union(geom)), 'properties': properties[0]})

A: I had an error due to the input shapefiles being a mixture of polygon and multipolygon types. I've included some code to skip the for loop for polygon types.
import fiona
from shapely import geometry
from shapely.geometry import shape, mapping

# open the original MultiPolygon file
with fiona.open('/home/matt/share/zoning/dissolve2.shp') as source:
    # create the new file: the driver and crs are the same
    # for the schema the geometry type is "Polygon" instead
    output_schema = dict(source.schema)  # make an independant copy
    output_schema['geometry'] = "Polygon"

    with fiona.open('/home/matt/share/zoning/output.shp', 'w',
                    driver=source.driver,
                    crs=source.crs,
                    schema=output_schema) as output:

        # read the input file
        for multi in source:

            polygon_shape = shape(multi['geometry'])

            if isinstance(polygon_shape, geometry.Polygon):

                # write the Polygon feature
                output.write({
                    'properties': multi['properties'],
                    'geometry': mapping(polygon_shape)
                })
            elif isinstance(polygon_shape, geometry.MultiPolygon):
                # extract each Polygon feature
                for poly in polygon_shape:

                    # write the Polygon feature
                    output.write({
                        'properties': multi['properties'],
                        'geometry': mapping(poly)
                    })
            else:
                raise ValueError('Unhandled geometry type: {}'.format(polygon_shape))


text:
Q: How to select only one checkbox in foreach in SwiftUI? I am trying to show checkbox in foreach loop but when i click on any one of them all are selected.
How can we separate them.
struct Screen: View {

    @State private var checked = true
    var data = ["1","2", "3"]

 var body: some View {
     ForEach( data.indices, id:\.self ) { item in
                HStack {
                CheckBoxView(checked: $checked)
                Text(data[item])
                }
            }
}

struct CheckBoxView: View {
    @Binding var checked: Bool

    var body: some View {
        Image(systemName: checked ? "checkmark.square.fill" : "square")
            .foregroundColor(checked ? Color(UIColor.systemBlue) : Color.secondary)
            .onTapGesture {
                self.checked.toggle()
            }
    }
}

Thank You for help.

A: The easiest way is to use an array of state variables:
struct Screen: View {

    @State private var checked: [Bool] = [true, true, true]
    var data = ["1","2", "3"]

    var body: some View {
        VStack {
            ForEach( data.indices, id:\.self ) { index in
                HStack {
                    CheckBoxView(checked: $checked[index])
                    Text(data[index])
                }
            }
        }
    }

    struct CheckBoxView: View {
        @Binding var checked: Bool

        var body: some View {
            Image(systemName: checked ? "checkmark.square.fill" : "square")
                .foregroundColor(checked ? Color(UIColor.systemBlue) : Color.secondary)
                .onTapGesture {
                    self.checked.toggle()
                }
        }
    }
}

However, I personally do not like this solution, because the state array is not dynamic in size to your data. With this initialization your state array is always the same size as your data.
struct Screen: View {

    var data = ["1","2", "3"]
    @State private var checked: [Bool]

    init() {
        _checked = State(initialValue: [Bool](repeating: false, count: data.count))
    }

    var body: some View {
        VStack {
            ForEach( data.indices, id:\.self ) { index in
                HStack {
                    CheckBoxView(checked: $checked[index])
                    Text(data[index])
                }
            }
        }
    }

    struct CheckBoxView: View {
        @Binding var checked: Bool

        var body: some View {
            Image(systemName: checked ? "checkmark.square.fill" : "square")
                .foregroundColor(checked ? Color(UIColor.systemBlue) : Color.secondary)
                .onTapGesture {
                    self.checked.toggle()
                }
        }
    }
}

A: Here is an answer that will allow you to check one or more boxes, and keep track of which values were selected. It uses an .onChanged to keep track of the actual value that has been selected as the check box itself is just UI:
struct Screen: View {

    var data = ["1","2","3"]
    @State var selectedItems: Set<String> = [] // Use a Set to keep track of multiple check boxes
    @State var selectedItems = "" // Use a String to keep track of only one.

    var body: some View {
        List {
            ForEach( data, id:\.self ) { item in
                CheckBoxRow(title:item, selectedItems: $selectedItems, isSelected: selectedItems.contains(item))
            }
        }
    }
}

struct CheckBoxRow: View {
    var title: String
    @Binding var selectedItems: Set<String>
    @State var isSelected: Bool

    var body: some View {
        GeometryReader { geometry in
            HStack {
                CheckBoxView(checked: $isSelected, title: title)
                    .onChange(of: isSelected) { _ in
                        if isSelected {
                            selectedItems.insert(title)// or
                            selectedItems = title
                        } else {
                            selectedItems.remove(title)// or
                            selectedItems = ""
                        }
                    }
            }
        }
    }
}

struct CheckBoxView: View {

    @Binding var checked: Bool
    @State var title: String

    var body: some View {
        HStack {
            Image(systemName: (checked ? "checkmark.square" : "square"))
            Text(title)
                .padding(.leading)
        }
        .onTapGesture {
            self.checked.toggle()
        }
    }
}


text:
Q: Javascript es6 - How to remove duplicates in an array of objects, except the last duplicate one? I have an array:
var arr = [
  {price: 5, amount: 100},
  {price: 3, amount: 50},
  {price: 10, amount: 20},
  {price: 3, amount: 75},
  {price: 7, amount: 15},
  {price: 3, amount: 65},
  {price: 2, amount: 34}
]

I want to remove the duplicates which has the same price, and only keep the last duplicate one then sort the array based on price from highest to lowest. Here is the result I want:
var result = [
  {price: 10, amount: 20},
  {price : 7, amount: 15},
  {price: 5, amount: 100},
  {price: 3, amount: 65},
  {price: 2, amount: 34}
]

A: Use reduce to convert it an object first to remove the duplicates and last duplicate should override the previous one
var obj = arr.reduce( ( acc, c ) =>  Object.assign(acc, {[c.price]:c.amount}) , {});

Convert it back to array and sort the same
var output = Object.keys( obj )
              .map( s => ({ price : s, amount : obj[ s ] }) )
              .sort( ( a, b )  => b.price - a.price );

Demo

var arr = [
  {price: 5, amount: 100},
  {price: 3, amount: 50},
  {price: 10, amount: 20},
  {price: 3, amount: 75},
  {price: 7, amount: 15},
  {price: 3, amount: 65},
  {price: 2, amount: 34}
];
var obj = arr.reduce( ( acc, c ) =>  Object.assign(acc, {[c.price]:c.amount}) , {});
var output = Object.keys( obj )
              .map( s => ({ price : s, amount : obj[ s ] }) )
              .sort( ( a, b )  => b.price - a.price );
console.log( output );

A: I'd use reduceRight and splice to remove duplicates. It doesn't create any useless intermediate objects, just a list of unique prices found along the way:

var arr = [
  {price: 5, amount: 100},
  {price: 3, amount: 50},
  {price: 10, amount: 20},
  {price: 3, amount: 75},
  {price: 7, amount: 15},
  {price: 3, amount: 65},
  {price: 2, amount: 34}
]

arr.reduceRight((acc, obj, i) => {
  acc[obj.price]? arr.splice(i, 1) : acc[obj.price] = true;
  return acc;
}, Object.create(null));

arr.sort((a, b) => b.price - a.price);

console.log(arr)

A: You can use Array.reduce to aggregate results in an array:
var arr = [
  {price: 5, amount: 100},
  {price: 3, amount: 50},
  {price: 10, amount: 20},
  {price: 3, amount: 75},
  {price: 7, amount: 15},
  {price: 3, amount: 65},
  {price: 2, amount: 34}
]

var results = arr.reduce<{ [price: string] : typeof arr[0] }>((p, e)=> {
    p[e.price] = e
    return p;
}, {});

var resultsAsArray = Object.keys(results)
     .map(k=>results[k])
     .sort((a, b) => b.price - a.price);

You can replace typeof arr[0] with the type of the array items if one is defined.
The idea of the solution is to acumulate the result in an object where the price is the key, if the same key is encountered multiple times, the old value is overwritten to in the end you will have only the last value for a given price.


text:
Q: AS3 combining strings I am trying to make a program combine two strings to make a name...
My code is
function addStudent(evt: MouseEvent)
{
var tempFirst = newStudent.firstName.text;
var tempLast = newStudent.lastName.text;
var tempStartDate = String(newStudent.startDate.text);
var tempBirthDate = String(newStudent.birthDate.text);
numStudents++;

var tempName = newStudent.firstName.text + newStudent.lastName.text;
trace(tempName);

studentList.dataProvider.addItem({label: tempName, data: tempName});

var tempStudent:student = new student(tempFirst, tempLast, tempStartDate, tempBirthDate);

studentHolder.addChild(tempStudent);

listStudents();
}

what the trace returns (if I input Jack Rob) is:
Jack
Rob

instead of JackRob
newStudent.firstName.text points to a movie clip called newStudent, with an input box called firstName
I have tried:
var tempFirst = String(newStudent.firstName.text);
var tempLast = String(newStudent.lastName.text);

var tempName = newStudent.firstName.text + newStudent.lastName.text;
var tempName = (newStudent.firstName.text).concat(newStudent.lastName.text);
var tempName = String(newStudent.firstName.text) + String(newStudent.lastName.text);

most of those were just me grasping at straws and hoping maybe something would work
essentially the goal is for the user to input a first and last name, and that first and last name is inputted into the dataProvider as one single string (JackRob)
I appreciate any help anyone can give, thank you in advance

A: I believe you have an invisible carriage return at the end of your string in the TextField. Try this :
var tempFirst.replace(String.fromCharCode(13), "");

If that works, then that is indeed the case.
I believe this happens when you are using a multiline textfield. Set it to a single line TextField in the Flash  IDE on the properties panel for the TextField(s) or use this code :
newStudent.firstName.multiline = false;


text:
Q: Cypress: global variables in callbacks I am trying to set up a new Cypress framework and I hit a point where I need help.
The scenario I am trying to work out: a page that is calling the same endpoint after every change and I use an interceptor to wait for the call. As we all know you can't use the same intercept name for the same request multiple times so I did a trick here. I used a dynamically named alias, which works.
var counters = {}
function registerIntercept(method, url, name) {
   counters[name] = 1;
   cy.intercept(method, url, (req) => {
      var currentCounter = counters[name]++;
      cy.wrap(counters).as(counters)
      req.alias = name + (currentCounter);

   })
}

function waitForCall(call) {
   waitForCall_(call + (counters[call.substr(1)]));
// HERE counters[any_previously_added_key] is always 1, even though the counters entry in registerIntercept is bigger
// I suspect counters here is not using the same counters value as registerIntercept

}

function waitForCall_(call) {
   cy.wait(call)
   cy.wait(100)
}

It is supposed to be used by using waitForCall("@callalias") and it will be converted to @callalias1, callalias2 and so on.
The problem is that the global counters is working in registerIntercept but I can't get its values from waitForCall. It will always retrieve value 1 for a specific key, while the counters key in registerIntercept is already at a bigger number.
This code works if you use it as waitForCall_("@callalias4") to wait for the 4th request for example.  Each intercept will get an alias ending with an incremented number. But I want to not keep track of how many calls were made and let the code retrieve that from counters and build the wait.
Any idea why counters in waitForCall is not having the same values for its keys as it has in registerIntercept?


text:
Q: C# Filter duplicates from list according to two criteria I want to filter duplicates from a list of objects of type A based on a function IsDuplicate.
class A
{
    public int p1;
    public List<int> p2;
    public bool IsDuplicate(A other) => p2.Sum() == other.p2.Sum();

    public List<A> GetDistinctA(List<A> objects)
    {
        List<A> results = new();
        for (int i = 0; i < objects.Count; i++)
        {
            bool duplicated = false;
            for (int j = i + 1; j < objects.Count; j++)
            {
                if (objects[i].IsDuplicate(objects[j]))
                {
                    duplicated = true;
                    break;
                }
            }

            if (duplicated)
            {
                continue;
            }

            results.Add(objects[i]);
        }
        return results;
    }
}

I can accomplish this with a nested for-loop.
New requirement is to deduplicate the list based on the same function isDuplicate but the winning element if there is a duplicate is the one with the higher value of property p1. Sorting objects by p1 will work but I guess that is not the most performant solution.
I am aware of Linqs GroupBy and Distinct but I don't know how to use the function as comparison criterion rather than a property.

A: You can group the items by the sum of p2, order the groups by p1 in descending order, then take the first one from each group in order to remove the duplicates.
You can also make the method static, since it doesn't need instance data:
public static List<A> GetDistinctA(List<A> objects)
{
    return objects?
        .GroupBy(a => a.p2.Sum())
        .Select(a => a.OrderByDescending(x => x.p1).First())
        .ToList();
}

Example usage:
var items = new List<A>
{
    new A { p1 = 0, p2 = new List<int> { 1, 2, 3, 4, 5 } }, // 15
    new A { p1 = 1, p2 = new List<int> { 1, 2, 3 } },       // 6
    new A { p1 = 2, p2 = new List<int> { 1, 2, 5 } },       // 8
    new A { p1 = 3, p2 = new List<int> { 14 } },
    new A { p1 = 4, p2 = new List<int> { 3 } },
    new A { p1 = 5, p2 = new List<int> { 1, 2 } },          // 3
    new A { p1 = 6, p2 = new List<int> { 2, 3, 4, 5 } },    // 14
    new A { p1 = 7, p2 = new List<int> { 6 } },
    new A { p1 = 8, p2 = new List<int> { 15 } },
    new A { p1 = 9, p2 = new List<int> { 1, 3, 4} },        // 8
    new A { p1 = 10, p2 = new List<int> { 15 } },
};

var results = A.GetDistinct(items);

Console.WriteLine(string.Join(", ", results.Select(a => a.p1)));
// Output: 10, 7, 9, 6, 5

A: You only need to store all duplicates in a separate list "duplicates" and then
p2.RemoveAll(duplicates);

The new method for getting a distinct list AND removing all duplicates:
public List<A> GetDistinctAndRemoveDuplicatesFromA(List<A> objects)
{
    List<A> results = new();
    List<A> duplicates = new();

    for (int i = 0; i < objects.Count; i++)
    {
        bool duplicated = false;
        for (int j = i + 1; j < objects.Count; j++)
        {
            if (objects[i].IsDuplicate(objects[j]))
            {
                duplicated = true;
                if(objects[i].p1 < objects[j].p1) duplicates.Add(objects[i]); // Higher p1 survives
                break;
            }
        }

        if (duplicated)
        {
            continue;
        }

        results.Add(objects[i]);
    }
    objects.RemoveAll(duplicates)
    return results;
}

A: Using a helper class to generate an IEqualityComparer based on passed in lambda functions, you can use any IsDuplicate method to compare objects, though this is less efficient since I used the same hashcode of 1 for every object to avoid a dependency on the contents of IsDuplicate. This allows you to use GroupBy to combine "equal" objects and then select the appropriate one using the new .Net Core MaxBy extension method. (If you don't have MaxBy, it is easy to implement yourself.)
(The method should be static since it doesn't depend on a particular instance.)
public static List<A> GetDistinctA(List<A> someAs)
    => someAs.GroupBy(a => a,
                      Make.LambdaEq<A>(a => 1,
                                       (a1,a2) => a1.IsDuplicate(a2)))
             .Select(ag => ag.MaxBy(a => a.p1))
             .ToList();

Here is the Make helper class:
public static class Make {
    public static IEqualityComparer<T> LambdaEq<T>(Func<T, int> hashCodeFn, Func<T, T, bool> equalsFn) => new LambdaEqualityComparer<T>(hashCodeFn, equalsFn);
    public static IEqualityComparer<T> LambdaEq<T>(T _, Func<T, int> hashCodeFn, Func<T, T, bool> equalsFn) => new LambdaEqualityComparer<T>(hashCodeFn, equalsFn);

    class LambdaEqualityComparer<T> : IEqualityComparer<T> {
        private Func<T, int> hashCodeFn;
        private Func<T, T, bool> equalsFn;

        public LambdaEqualityComparer(Func<T, int> _hashCodeFn, Func<T, T, bool> _equalsFn) {
            //        if(_hashCodeFn == null) throw new ArgumentNullException(nameof(_hashCodeFn));
            //        if(_equalsFn == null) throw new ArgumentNullException(nameof(_equalsFn));
            hashCodeFn = _hashCodeFn;
            equalsFn = _equalsFn;
        }

        public int GetHashCode(T x) => hashCodeFn(x); // must be method to fulfill interface
        public bool Equals(T x, T y) => equalsFn(x, y); // must be method to fulfill interface
    }
}


text:
Q: What program is used to create this? What program was used to create this type of mapbook?
So if I want to get my roads to look similar to the above PDF - how would I go about doing that.

A: The best way to be certain how it was created is by contacting the author/organisation that published it.
However, I suspect that it was created using ArcGIS for Desktop's Data Driven Pages and ArcPy; and the ReportLab open-source PDF Toolkit using techniques similar to those described in:

*

*an Esri blog entitled Creating Place Name Indexes for Map Books; and

*the Help page entitled Creating a map book with facing pages.

It is also possible that it is using the Fire Run Book tool but I have not downloaded that, and I suspect that it will use the above techniques anyway.


text:
Q: Why does this SSL certificate validate fine in browsers, but not in .NET/Silverlight? If I access https://www.mynetfone.com.au in a browser, the cerificate validates fine.
To do anything with this site in .NET, I have to override ServicePointManager and turn certificate validation off.
This becomes more of a problem with Windows Phone 7, where there is no way to change certificate validation, and no way to remove certificates once you add them.
Is there anything obviously wrong with the certificate? What would the company have to do to fix it?

A: There are only a limited number of root certificate authorities with root certificates installed by default. For more details see "Windows Phone 7 Root Certificates_FINAL_121610.pdf" available from http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=8842
The other docs on that page also provide more information about SSL & certificates on the phone.


text:
Q: How do I display a DataGridView within a cell of another datagridview in C# forms app? How do I display a DataGridView within a cell of another datagridview in C# forms app?
How would I have to handle Sorting & value changed if this possible?
That is the only way I can display data to make some sense.. Think of it like I have a task column and dates column. Under the dates column I have a list of things to be done. These date columns are dynamic & there might be multiple date columns

A: That sounds like a difficult interface to use, have you considered some kind of tree control?
If you're determined to use data grid views, look at customizing data grid view columns and cells. You need to declare custom subclasses for the column and cell behaviour that you want. I don't know if it's possible to do what you want, but that's where I would start.

A: This is a suggestion since what your asking I do not think is possible with the built in DGV of .NET.
Using custom controls made by professional companies that provides a DataGrid with the capability of hierarchical data.  For example a row can be expanded to show multiple entries (the multiple entries can be an entirely different table containing completely different columns even).  Here are a few options that you can check out.
Infragistics WinGrid
Component One
There are a few other places/companies that make great .NET component packages that provide added features to the existing .NET components.

A: http://blogs.msdn.com/markrideout/archive/2006/01/08/510700.aspx
Found a link where hierarchichal datagrid is implemented.
Now, I have to either modify the control, or settle for hierarchichal gridview!
Hope this helps someone. Will update later


text:
Q: Starting with Java, syntax error on tokens For some reason its highlighting boolean and string as errors, I copied this code straight out of the textbook why wont it work?
package practice;
public class practice{

public boolean isUniqueChars(string str){
if (str.length() > 256)
            return false;

        boolean[] char_set = new boolean[256];
        for (int i = 0; i< str.length(); i++){
            int val = str.charAt(i);
            if (char_set[val]) {
                return false;

            char_set[val] = true;
        }
        return true;
    }
}
Errors: Multiple markers at this line
- string cannot be resolved to a type
- Syntax error on token "boolean", @
 expected
- Syntax error on token ")", -> expected
- Syntax error on token(s), misplaced
 construct(s)

A: Well Try this:
package practice;

/**
 *
 * @author manoj.sharma
 */

public class Test{
public static void main(String [] a){
System.out.println(new Test().isUniqueChars("Hello world"));
}
public boolean isUniqueChars(String str){
    if (str.length() > 256)
        return false;

    boolean[] char_set = new boolean[256];
    for (int i = 0; i< str.length(); i++){
        int val = str.charAt(i);
        if (char_set[val]) {
            return false;
        }
        char_set[val] = true;
    }
    return true;
}
}

A: public boolean isUniqueChars(string str){

seems a typo, string should be String

A: Use "S" for String declaration in Java.
isUniqueChars(String str)


text:
Q: Warning about  tag for gist when run jekyll server I embeded a gist using {% gist octocat/0831f3fbd83ac4d46451 git-author-rewrite.sh %}, then I ran jekyll server, came this warning:

Regenerating: 1 file(s) changed at 2015-08-28 19:43:12
  Warning: The  tag for your gist octocat/0831f3fbd83ac4d46451
  could not be generated. This will affect users who do not have JavaScript available or enabled in their browsers.
  Warning: The  tag for your gist octocat/0831f3fbd83ac4d46451 could not be generated. This will affect users who do not have JavaScript available or enabled in their browsers. ...done in 7.157032 seconds.

And the page generated looked strange: extra word displayed. Reason unknown.
Gem jekyll-gist has been installed already. What can I do with this? I googled for several hours, but with no luck.
Edit: Hmm, add pictures to show why this question came out:

*

*noscript tag warning:

*

*extra word 'true' displayed:

A: To close this issue, let me add something.
Yes, this is related with proxy, and the jekyll (my version is 2.5.3). In my case, I ran jekyll server just behind the http proxy, and jekyll threw out a warning, generated this html code (I thought there may be something wrong):

true

So you can see the extra word 'true'.
To avoid this, I just insert the script instead of embedded gist (retrieved from the generated code):

I recommend the audiences to use script instead of gist. There's another reason: if you want to run jekyll and overview site offline, the embedded gist will cause a connection error.


text:
Q: Change Primary Image in Array of Images I have several images on my page that I use a jQuery scroller to scroll through the thumbnail images.  The scrolling portion of my site works just fine.  The problem comes in when I try to click on a thumbnail to set it as the "primary" large image.  The code I am using works in Firefox but not in IE.  Here is the code for the primary and thumb images:

I am using a javascript function to change the primary image:
function viewVehicle(name,src) {
    if (document.images) {
            document.images[name].src = src;
    }
    document.getElementById(name).href = src;
    return false;
}

I need to change the primary image src to the src of the thumbnail, and I am controlling which image is showing by using a "primary" class vs. "hidden" class.  I hope I explained this enough to understand.
You can view an example here:
http://www.upcars.com/find-vehicle/vehicle-details.asp?v_id=31596